context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // namespace Revit.SDK.Samples.SlabShapeEditing.CS { partial class SlabShapeEditingForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SlabShapeEditingForm)); this.SlabShapePictureBox = new System.Windows.Forms.PictureBox(); this.PointButton = new System.Windows.Forms.Button(); this.LineButton = new System.Windows.Forms.Button(); this.DistanceLabel = new System.Windows.Forms.Label(); this.DistanceTextBox = new System.Windows.Forms.TextBox(); this.MoveButton = new System.Windows.Forms.Button(); this.ResetButton = new System.Windows.Forms.Button(); this.OKButton = new System.Windows.Forms.Button(); this.UpdateButton = new System.Windows.Forms.Button(); this.NoteLabel = new System.Windows.Forms.Label(); this.toolTip = new System.Windows.Forms.ToolTip(this.components); ((System.ComponentModel.ISupportInitialize)(this.SlabShapePictureBox)).BeginInit(); this.SuspendLayout(); // // SlabShapePictureBox // this.SlabShapePictureBox.BackColor = System.Drawing.Color.White; this.SlabShapePictureBox.Location = new System.Drawing.Point(12, 13); this.SlabShapePictureBox.Name = "SlabShapePictureBox"; this.SlabShapePictureBox.Size = new System.Drawing.Size(354, 301); this.SlabShapePictureBox.TabIndex = 0; this.SlabShapePictureBox.TabStop = false; this.SlabShapePictureBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.SlabShapePictureBox_MouseDown); this.SlabShapePictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.SlabShapePictureBox_MouseMove); this.SlabShapePictureBox.Paint += new System.Windows.Forms.PaintEventHandler(this.SlabShapePictureBox_Paint); this.SlabShapePictureBox.MouseClick += new System.Windows.Forms.MouseEventHandler(this.SlabShapePictureBox_MouseClick); this.SlabShapePictureBox.MouseHover += new System.EventHandler(this.SlabShapePictureBox_MouseHover); // // PointButton // this.PointButton.Image = ((System.Drawing.Image)(resources.GetObject("PointButton.Image"))); this.PointButton.Location = new System.Drawing.Point(46, 342); this.PointButton.Name = "PointButton"; this.PointButton.Size = new System.Drawing.Size(28, 28); this.PointButton.TabIndex = 1; this.PointButton.UseVisualStyleBackColor = true; this.PointButton.Click += new System.EventHandler(this.PointButton_Click); this.PointButton.MouseHover += new System.EventHandler(this.PointButton_MouseHover); // // LineButton // this.LineButton.Image = ((System.Drawing.Image)(resources.GetObject("LineButton.Image"))); this.LineButton.Location = new System.Drawing.Point(80, 342); this.LineButton.Name = "LineButton"; this.LineButton.Size = new System.Drawing.Size(28, 28); this.LineButton.TabIndex = 2; this.LineButton.UseVisualStyleBackColor = true; this.LineButton.Click += new System.EventHandler(this.LineButton_Click); this.LineButton.MouseHover += new System.EventHandler(this.LineButton_MouseHover); // // DistanceLabel // this.DistanceLabel.AutoSize = true; this.DistanceLabel.Location = new System.Drawing.Point(113, 351); this.DistanceLabel.Name = "DistanceLabel"; this.DistanceLabel.Size = new System.Drawing.Size(93, 14); this.DistanceLabel.TabIndex = 4; this.DistanceLabel.Text = "Distance (Feet):"; // // DistanceTextBox // this.DistanceTextBox.Location = new System.Drawing.Point(210, 348); this.DistanceTextBox.Name = "DistanceTextBox"; this.DistanceTextBox.Size = new System.Drawing.Size(75, 22); this.DistanceTextBox.TabIndex = 5; // // MoveButton // this.MoveButton.Image = ((System.Drawing.Image)(resources.GetObject("MoveButton.Image"))); this.MoveButton.Location = new System.Drawing.Point(12, 342); this.MoveButton.Name = "MoveButton"; this.MoveButton.Size = new System.Drawing.Size(28, 28); this.MoveButton.TabIndex = 6; this.MoveButton.UseVisualStyleBackColor = true; this.MoveButton.Click += new System.EventHandler(this.MoveButton_Click); this.MoveButton.MouseHover += new System.EventHandler(this.MoveButton_MouseHover); // // ResetButton // this.ResetButton.Location = new System.Drawing.Point(210, 387); this.ResetButton.Name = "ResetButton"; this.ResetButton.Size = new System.Drawing.Size(75, 25); this.ResetButton.TabIndex = 7; this.ResetButton.Text = "&Reset"; this.ResetButton.UseVisualStyleBackColor = true; this.ResetButton.Click += new System.EventHandler(this.ResetButton_Click); // // OKButton // this.OKButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.OKButton.Location = new System.Drawing.Point(291, 387); this.OKButton.Name = "OKButton"; this.OKButton.Size = new System.Drawing.Size(75, 25); this.OKButton.TabIndex = 9; this.OKButton.Text = "&OK"; this.OKButton.UseVisualStyleBackColor = true; // // UpdateButton // this.UpdateButton.Location = new System.Drawing.Point(291, 348); this.UpdateButton.Name = "UpdateButton"; this.UpdateButton.Size = new System.Drawing.Size(75, 25); this.UpdateButton.TabIndex = 10; this.UpdateButton.Text = "&Update"; this.UpdateButton.UseVisualStyleBackColor = true; this.UpdateButton.Click += new System.EventHandler(this.UpdateButton_Click); // // NoteLabel // this.NoteLabel.AutoSize = true; this.NoteLabel.Font = new System.Drawing.Font("Calibri", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.NoteLabel.Location = new System.Drawing.Point(12, 317); this.NoteLabel.Name = "NoteLabel"; this.NoteLabel.Size = new System.Drawing.Size(316, 15); this.NoteLabel.TabIndex = 11; this.NoteLabel.Text = "Click right mouse button and move mouse to rotate Slab."; // // SlabShapeEditingForm // this.AcceptButton = this.OKButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 14F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.OKButton; this.ClientSize = new System.Drawing.Size(377, 425); this.Controls.Add(this.NoteLabel); this.Controls.Add(this.UpdateButton); this.Controls.Add(this.OKButton); this.Controls.Add(this.ResetButton); this.Controls.Add(this.MoveButton); this.Controls.Add(this.DistanceTextBox); this.Controls.Add(this.DistanceLabel); this.Controls.Add(this.LineButton); this.Controls.Add(this.PointButton); this.Controls.Add(this.SlabShapePictureBox); this.Font = new System.Drawing.Font("Calibri", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SlabShapeEditingForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "Slab Shape Editing"; ((System.ComponentModel.ISupportInitialize)(this.SlabShapePictureBox)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox SlabShapePictureBox; private System.Windows.Forms.Button PointButton; private System.Windows.Forms.Button LineButton; private System.Windows.Forms.Label DistanceLabel; private System.Windows.Forms.TextBox DistanceTextBox; private System.Windows.Forms.Button MoveButton; private System.Windows.Forms.Button ResetButton; private System.Windows.Forms.Button OKButton; private System.Windows.Forms.Button UpdateButton; private System.Windows.Forms.Label NoteLabel; private System.Windows.Forms.ToolTip toolTip; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Xml.Schema; using System.Xml.XPath; using System.Xml.Xsl; using System.Xml.Xsl.Runtime; namespace System.Xml.Xsl.Qil { /// <summary> /// This class performs two functions: /// 1. Infer XmlQueryType of Qil nodes (constant, from arguments, etc) /// 2. Validate the arguments of Qil nodes if DEBUG is defined /// </summary> internal class QilTypeChecker { public QilTypeChecker() { } public XmlQueryType Check(QilNode n) { #region AUTOGENERATED switch (n.NodeType) { case QilNodeType.QilExpression: return CheckQilExpression((QilExpression)n); case QilNodeType.FunctionList: return CheckFunctionList((QilList)n); case QilNodeType.GlobalVariableList: return CheckGlobalVariableList((QilList)n); case QilNodeType.GlobalParameterList: return CheckGlobalParameterList((QilList)n); case QilNodeType.ActualParameterList: return CheckActualParameterList((QilList)n); case QilNodeType.FormalParameterList: return CheckFormalParameterList((QilList)n); case QilNodeType.SortKeyList: return CheckSortKeyList((QilList)n); case QilNodeType.BranchList: return CheckBranchList((QilList)n); case QilNodeType.OptimizeBarrier: return CheckOptimizeBarrier((QilUnary)n); case QilNodeType.Unknown: return CheckUnknown(n); case QilNodeType.DataSource: return CheckDataSource((QilDataSource)n); case QilNodeType.Nop: return CheckNop((QilUnary)n); case QilNodeType.Error: return CheckError((QilUnary)n); case QilNodeType.Warning: return CheckWarning((QilUnary)n); case QilNodeType.For: return CheckFor((QilIterator)n); case QilNodeType.Let: return CheckLet((QilIterator)n); case QilNodeType.Parameter: return CheckParameter((QilParameter)n); case QilNodeType.PositionOf: return CheckPositionOf((QilUnary)n); case QilNodeType.True: return CheckTrue(n); case QilNodeType.False: return CheckFalse(n); case QilNodeType.LiteralString: return CheckLiteralString((QilLiteral)n); case QilNodeType.LiteralInt32: return CheckLiteralInt32((QilLiteral)n); case QilNodeType.LiteralInt64: return CheckLiteralInt64((QilLiteral)n); case QilNodeType.LiteralDouble: return CheckLiteralDouble((QilLiteral)n); case QilNodeType.LiteralDecimal: return CheckLiteralDecimal((QilLiteral)n); case QilNodeType.LiteralQName: return CheckLiteralQName((QilName)n); case QilNodeType.LiteralType: return CheckLiteralType((QilLiteral)n); case QilNodeType.LiteralObject: return CheckLiteralObject((QilLiteral)n); case QilNodeType.And: return CheckAnd((QilBinary)n); case QilNodeType.Or: return CheckOr((QilBinary)n); case QilNodeType.Not: return CheckNot((QilUnary)n); case QilNodeType.Conditional: return CheckConditional((QilTernary)n); case QilNodeType.Choice: return CheckChoice((QilChoice)n); case QilNodeType.Length: return CheckLength((QilUnary)n); case QilNodeType.Sequence: return CheckSequence((QilList)n); case QilNodeType.Union: return CheckUnion((QilBinary)n); case QilNodeType.Intersection: return CheckIntersection((QilBinary)n); case QilNodeType.Difference: return CheckDifference((QilBinary)n); case QilNodeType.Average: return CheckAverage((QilUnary)n); case QilNodeType.Sum: return CheckSum((QilUnary)n); case QilNodeType.Minimum: return CheckMinimum((QilUnary)n); case QilNodeType.Maximum: return CheckMaximum((QilUnary)n); case QilNodeType.Negate: return CheckNegate((QilUnary)n); case QilNodeType.Add: return CheckAdd((QilBinary)n); case QilNodeType.Subtract: return CheckSubtract((QilBinary)n); case QilNodeType.Multiply: return CheckMultiply((QilBinary)n); case QilNodeType.Divide: return CheckDivide((QilBinary)n); case QilNodeType.Modulo: return CheckModulo((QilBinary)n); case QilNodeType.StrLength: return CheckStrLength((QilUnary)n); case QilNodeType.StrConcat: return CheckStrConcat((QilStrConcat)n); case QilNodeType.StrParseQName: return CheckStrParseQName((QilBinary)n); case QilNodeType.Ne: return CheckNe((QilBinary)n); case QilNodeType.Eq: return CheckEq((QilBinary)n); case QilNodeType.Gt: return CheckGt((QilBinary)n); case QilNodeType.Ge: return CheckGe((QilBinary)n); case QilNodeType.Lt: return CheckLt((QilBinary)n); case QilNodeType.Le: return CheckLe((QilBinary)n); case QilNodeType.Is: return CheckIs((QilBinary)n); case QilNodeType.After: return CheckAfter((QilBinary)n); case QilNodeType.Before: return CheckBefore((QilBinary)n); case QilNodeType.Loop: return CheckLoop((QilLoop)n); case QilNodeType.Filter: return CheckFilter((QilLoop)n); case QilNodeType.Sort: return CheckSort((QilLoop)n); case QilNodeType.SortKey: return CheckSortKey((QilSortKey)n); case QilNodeType.DocOrderDistinct: return CheckDocOrderDistinct((QilUnary)n); case QilNodeType.Function: return CheckFunction((QilFunction)n); case QilNodeType.Invoke: return CheckInvoke((QilInvoke)n); case QilNodeType.Content: return CheckContent((QilUnary)n); case QilNodeType.Attribute: return CheckAttribute((QilBinary)n); case QilNodeType.Parent: return CheckParent((QilUnary)n); case QilNodeType.Root: return CheckRoot((QilUnary)n); case QilNodeType.XmlContext: return CheckXmlContext(n); case QilNodeType.Descendant: return CheckDescendant((QilUnary)n); case QilNodeType.DescendantOrSelf: return CheckDescendantOrSelf((QilUnary)n); case QilNodeType.Ancestor: return CheckAncestor((QilUnary)n); case QilNodeType.AncestorOrSelf: return CheckAncestorOrSelf((QilUnary)n); case QilNodeType.Preceding: return CheckPreceding((QilUnary)n); case QilNodeType.FollowingSibling: return CheckFollowingSibling((QilUnary)n); case QilNodeType.PrecedingSibling: return CheckPrecedingSibling((QilUnary)n); case QilNodeType.NodeRange: return CheckNodeRange((QilBinary)n); case QilNodeType.Deref: return CheckDeref((QilBinary)n); case QilNodeType.ElementCtor: return CheckElementCtor((QilBinary)n); case QilNodeType.AttributeCtor: return CheckAttributeCtor((QilBinary)n); case QilNodeType.CommentCtor: return CheckCommentCtor((QilUnary)n); case QilNodeType.PICtor: return CheckPICtor((QilBinary)n); case QilNodeType.TextCtor: return CheckTextCtor((QilUnary)n); case QilNodeType.RawTextCtor: return CheckRawTextCtor((QilUnary)n); case QilNodeType.DocumentCtor: return CheckDocumentCtor((QilUnary)n); case QilNodeType.NamespaceDecl: return CheckNamespaceDecl((QilBinary)n); case QilNodeType.RtfCtor: return CheckRtfCtor((QilBinary)n); case QilNodeType.NameOf: return CheckNameOf((QilUnary)n); case QilNodeType.LocalNameOf: return CheckLocalNameOf((QilUnary)n); case QilNodeType.NamespaceUriOf: return CheckNamespaceUriOf((QilUnary)n); case QilNodeType.PrefixOf: return CheckPrefixOf((QilUnary)n); case QilNodeType.TypeAssert: return CheckTypeAssert((QilTargetType)n); case QilNodeType.IsType: return CheckIsType((QilTargetType)n); case QilNodeType.IsEmpty: return CheckIsEmpty((QilUnary)n); case QilNodeType.XPathNodeValue: return CheckXPathNodeValue((QilUnary)n); case QilNodeType.XPathFollowing: return CheckXPathFollowing((QilUnary)n); case QilNodeType.XPathPreceding: return CheckXPathPreceding((QilUnary)n); case QilNodeType.XPathNamespace: return CheckXPathNamespace((QilUnary)n); case QilNodeType.XsltGenerateId: return CheckXsltGenerateId((QilUnary)n); case QilNodeType.XsltInvokeLateBound: return CheckXsltInvokeLateBound((QilInvokeLateBound)n); case QilNodeType.XsltInvokeEarlyBound: return CheckXsltInvokeEarlyBound((QilInvokeEarlyBound)n); case QilNodeType.XsltCopy: return CheckXsltCopy((QilBinary)n); case QilNodeType.XsltCopyOf: return CheckXsltCopyOf((QilUnary)n); case QilNodeType.XsltConvert: return CheckXsltConvert((QilTargetType)n); default: return CheckUnknown(n); } #endregion } #region meta //----------------------------------------------- // meta //----------------------------------------------- public XmlQueryType CheckQilExpression(QilExpression node) { Check(node[0].NodeType == QilNodeType.False || node[0].NodeType == QilNodeType.True, node, "IsDebug must either be True or False"); CheckLiteralValue(node[1], typeof(XmlWriterSettings)); CheckLiteralValue(node[2], typeof(IList<WhitespaceRule>)); CheckClassAndNodeType(node[3], typeof(QilList), QilNodeType.GlobalParameterList); CheckClassAndNodeType(node[4], typeof(QilList), QilNodeType.GlobalVariableList); CheckLiteralValue(node[5], typeof(IList<EarlyBoundInfo>)); CheckClassAndNodeType(node[6], typeof(QilList), QilNodeType.FunctionList); return XmlQueryTypeFactory.ItemS; } public XmlQueryType CheckFunctionList(QilList node) { foreach (QilNode child in node) CheckClassAndNodeType(child, typeof(QilFunction), QilNodeType.Function); return node.XmlType; } public XmlQueryType CheckGlobalVariableList(QilList node) { foreach (QilNode child in node) CheckClassAndNodeType(child, typeof(QilIterator), QilNodeType.Let); return node.XmlType; } public XmlQueryType CheckGlobalParameterList(QilList node) { foreach (QilNode child in node) { CheckClassAndNodeType(child, typeof(QilParameter), QilNodeType.Parameter); Check(((QilParameter)child).Name != null, child, "Global parameter's name is null"); } return node.XmlType; } public XmlQueryType CheckActualParameterList(QilList node) { return node.XmlType; } public XmlQueryType CheckFormalParameterList(QilList node) { foreach (QilNode child in node) CheckClassAndNodeType(child, typeof(QilParameter), QilNodeType.Parameter); return node.XmlType; } public XmlQueryType CheckSortKeyList(QilList node) { foreach (QilNode child in node) CheckClassAndNodeType(child, typeof(QilSortKey), QilNodeType.SortKey); return node.XmlType; } public XmlQueryType CheckBranchList(QilList node) { return node.XmlType; } public XmlQueryType CheckOptimizeBarrier(QilUnary node) { return node.Child.XmlType; } public XmlQueryType CheckUnknown(QilNode node) { return node.XmlType; } #endregion // meta #region specials //----------------------------------------------- // specials //----------------------------------------------- public XmlQueryType CheckDataSource(QilDataSource node) { CheckXmlType(node.Name, XmlQueryTypeFactory.StringX); CheckXmlType(node.BaseUri, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.NodeNotRtfQ; } public XmlQueryType CheckNop(QilUnary node) { return node.Child.XmlType; } public XmlQueryType CheckError(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.None; } public XmlQueryType CheckWarning(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.Empty; } #endregion // specials #region variables //----------------------------------------------- // variables //----------------------------------------------- public XmlQueryType CheckFor(QilIterator node) { return node.Binding.XmlType.Prime; } public XmlQueryType CheckLet(QilIterator node) { return node.Binding.XmlType; } public XmlQueryType CheckParameter(QilParameter node) { Check(node.Binding == null || node.Binding.XmlType.IsSubtypeOf(node.XmlType), node, "Parameter binding's xml type must be a subtype of the parameter's type"); return node.XmlType; } public XmlQueryType CheckPositionOf(QilUnary node) { return XmlQueryTypeFactory.IntX; } #endregion // variables #region literals //----------------------------------------------- // literals //----------------------------------------------- public XmlQueryType CheckTrue(QilNode node) { return XmlQueryTypeFactory.BooleanX; } public XmlQueryType CheckFalse(QilNode node) { return XmlQueryTypeFactory.BooleanX; } public XmlQueryType CheckLiteralString(QilLiteral node) { CheckLiteralValue(node, typeof(string)); return XmlQueryTypeFactory.StringX; } public XmlQueryType CheckLiteralInt32(QilLiteral node) { CheckLiteralValue(node, typeof(int)); return XmlQueryTypeFactory.IntX; } public XmlQueryType CheckLiteralInt64(QilLiteral node) { CheckLiteralValue(node, typeof(long)); return XmlQueryTypeFactory.IntegerX; } public XmlQueryType CheckLiteralDouble(QilLiteral node) { CheckLiteralValue(node, typeof(double)); return XmlQueryTypeFactory.DoubleX; } public XmlQueryType CheckLiteralDecimal(QilLiteral node) { CheckLiteralValue(node, typeof(decimal)); return XmlQueryTypeFactory.DecimalX; } public XmlQueryType CheckLiteralQName(QilName node) { CheckLiteralValue(node, typeof(QilName)); // BUGBUG: Xslt constructs invalid QNames, so don't check this //Check(ValidateNames.ValidateName(node.Prefix, node.LocalName, node.NamespaceUri, XPathNodeType.Element, ValidateNames.Flags.All), node, "QName is not valid"); return XmlQueryTypeFactory.QNameX; } public XmlQueryType CheckLiteralType(QilLiteral node) { CheckLiteralValue(node, typeof(XmlQueryType)); return (XmlQueryType)node; } public XmlQueryType CheckLiteralObject(QilLiteral node) { Check(node.Value != null, node, "Literal value is null"); return XmlQueryTypeFactory.ItemS; } #endregion // literals #region boolean operators //----------------------------------------------- // boolean operators //----------------------------------------------- public XmlQueryType CheckAnd(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.BooleanX); CheckXmlType(node.Right, XmlQueryTypeFactory.BooleanX); return XmlQueryTypeFactory.BooleanX; } public XmlQueryType CheckOr(QilBinary node) { return CheckAnd(node); } public XmlQueryType CheckNot(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.BooleanX); return XmlQueryTypeFactory.BooleanX; } #endregion // boolean operators #region choice //----------------------------------------------- // choice //----------------------------------------------- public XmlQueryType CheckConditional(QilTernary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.BooleanX); return XmlQueryTypeFactory.Choice(node.Center.XmlType, node.Right.XmlType); } public XmlQueryType CheckChoice(QilChoice node) { CheckXmlType(node.Expression, XmlQueryTypeFactory.IntX); CheckClassAndNodeType(node.Branches, typeof(QilList), QilNodeType.BranchList); Check(node.Branches.Count > 0, node, "Choice must have at least one branch"); return node.Branches.XmlType; } #endregion // choice #region collection operators //----------------------------------------------- // collection operators //----------------------------------------------- public XmlQueryType CheckLength(QilUnary node) { return XmlQueryTypeFactory.IntX; } public XmlQueryType CheckSequence(QilList node) { return node.XmlType; } public XmlQueryType CheckUnion(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return DistinctType(XmlQueryTypeFactory.Sequence(node.Left.XmlType, node.Right.XmlType)); } public XmlQueryType CheckIntersection(QilBinary node) { return CheckUnion(node); } public XmlQueryType CheckDifference(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.AtMost(node.Left.XmlType, node.Left.XmlType.Cardinality); } public XmlQueryType CheckAverage(QilUnary node) { XmlQueryType xmlType = node.Child.XmlType; CheckNumericXS(node.Child); return XmlQueryTypeFactory.PrimeProduct(xmlType, xmlType.MaybeEmpty ? XmlQueryCardinality.ZeroOrOne : XmlQueryCardinality.One); } public XmlQueryType CheckSum(QilUnary node) { return CheckAverage(node); } public XmlQueryType CheckMinimum(QilUnary node) { return CheckAverage(node); } public XmlQueryType CheckMaximum(QilUnary node) { return CheckAverage(node); } #endregion // collection operators #region arithmetic operators //----------------------------------------------- // arithmetic operators //----------------------------------------------- public XmlQueryType CheckNegate(QilUnary node) { CheckNumericX(node.Child); return node.Child.XmlType; } public XmlQueryType CheckAdd(QilBinary node) { CheckNumericX(node.Left); CheckNumericX(node.Right); CheckNotDisjoint(node); return node.Left.XmlType.TypeCode == XmlTypeCode.None ? node.Right.XmlType : node.Left.XmlType; } public XmlQueryType CheckSubtract(QilBinary node) { return CheckAdd(node); } public XmlQueryType CheckMultiply(QilBinary node) { return CheckAdd(node); } public XmlQueryType CheckDivide(QilBinary node) { return CheckAdd(node); } public XmlQueryType CheckModulo(QilBinary node) { return CheckAdd(node); } #endregion // arithmetic operators #region string operators //----------------------------------------------- // string operators //----------------------------------------------- public XmlQueryType CheckStrLength(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.IntX; } public XmlQueryType CheckStrConcat(QilStrConcat node) { CheckXmlType(node.Delimiter, XmlQueryTypeFactory.StringX); CheckXmlType(node.Values, XmlQueryTypeFactory.StringXS); return XmlQueryTypeFactory.StringX; } public XmlQueryType CheckStrParseQName(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.StringX); Check(node.Right.XmlType.IsSubtypeOf(XmlQueryTypeFactory.StringX) || node.Right.XmlType.IsSubtypeOf(XmlQueryTypeFactory.NamespaceS), node, "StrParseQName must take either a string or a list of namespace as its second argument"); return XmlQueryTypeFactory.QNameX; } #endregion // string operators #region value comparison operators //----------------------------------------------- // value comparison operators //----------------------------------------------- public XmlQueryType CheckNe(QilBinary node) { CheckAtomicX(node.Left); CheckAtomicX(node.Right); CheckNotDisjoint(node); return XmlQueryTypeFactory.BooleanX; } public XmlQueryType CheckEq(QilBinary node) { return CheckNe(node); } public XmlQueryType CheckGt(QilBinary node) { return CheckNe(node); } public XmlQueryType CheckGe(QilBinary node) { return CheckNe(node); } public XmlQueryType CheckLt(QilBinary node) { return CheckNe(node); } public XmlQueryType CheckLe(QilBinary node) { return CheckNe(node); } #endregion // value comparison operators #region node comparison operators //----------------------------------------------- // node comparison operators //----------------------------------------------- public XmlQueryType CheckIs(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.BooleanX; } public XmlQueryType CheckAfter(QilBinary node) { return CheckIs(node); } public XmlQueryType CheckBefore(QilBinary node) { return CheckIs(node); } #endregion // node comparison operators #region loops //----------------------------------------------- // loops //----------------------------------------------- public XmlQueryType CheckLoop(QilLoop node) { CheckClass(node[0], typeof(QilIterator)); Check(node.Variable.NodeType == QilNodeType.For || node.Variable.NodeType == QilNodeType.Let, node, "Loop variable must be a For or Let iterator"); XmlQueryType bodyType = node.Body.XmlType; XmlQueryCardinality variableCard = node.Variable.NodeType == QilNodeType.Let ? XmlQueryCardinality.One : node.Variable.Binding.XmlType.Cardinality; // Loops do not preserve DocOrderDistinct return XmlQueryTypeFactory.PrimeProduct(bodyType, variableCard * bodyType.Cardinality); } public XmlQueryType CheckFilter(QilLoop node) { CheckClass(node[0], typeof(QilIterator)); Check(node.Variable.NodeType == QilNodeType.For || node.Variable.NodeType == QilNodeType.Let, node, "Filter variable must be a For or Let iterator"); CheckXmlType(node.Body, XmlQueryTypeFactory.BooleanX); // Attempt to restrict filter's type by checking condition XmlQueryType filterType = FindFilterType(node.Variable, node.Body); if (filterType != null) return filterType; return XmlQueryTypeFactory.AtMost(node.Variable.Binding.XmlType, node.Variable.Binding.XmlType.Cardinality); } #endregion // loops #region sorting //----------------------------------------------- // sorting //----------------------------------------------- public XmlQueryType CheckSort(QilLoop node) { XmlQueryType varType = node.Variable.Binding.XmlType; CheckClassAndNodeType(node[0], typeof(QilIterator), QilNodeType.For); CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.SortKeyList); // Sort does not preserve DocOrderDistinct return XmlQueryTypeFactory.PrimeProduct(varType, varType.Cardinality); } public XmlQueryType CheckSortKey(QilSortKey node) { CheckAtomicX(node.Key); CheckXmlType(node.Collation, XmlQueryTypeFactory.StringX); return node.Key.XmlType; } public XmlQueryType CheckDocOrderDistinct(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS); return DistinctType(node.Child.XmlType); } #endregion // sorting #region function definition and invocation //----------------------------------------------- // function definition and invocation //----------------------------------------------- public XmlQueryType CheckFunction(QilFunction node) { CheckClassAndNodeType(node[0], typeof(QilList), QilNodeType.FormalParameterList); Check(node[2].NodeType == QilNodeType.False || node[2].NodeType == QilNodeType.True, node, "SideEffects must either be True or False"); Check(node.Definition.XmlType.IsSubtypeOf(node.XmlType), node, "Function definition's xml type must be a subtype of the function's return type"); return node.XmlType; } public XmlQueryType CheckInvoke(QilInvoke node) { #if DEBUG CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.ActualParameterList); QilList actualArgs = node.Arguments; QilList formalArgs = node.Function.Arguments; Check(actualArgs.Count == formalArgs.Count, actualArgs, "Invoke argument count must match function's argument count"); for (int i = 0; i < actualArgs.Count; i++) Check(actualArgs[i].XmlType.IsSubtypeOf(formalArgs[i].XmlType), actualArgs[i], "Invoke argument must be a subtype of the invoked function's argument"); #endif return node.Function.XmlType; } #endregion // function definition and invocation #region XML navigation //----------------------------------------------- // XML navigation //----------------------------------------------- public XmlQueryType CheckContent(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.AttributeOrContentS; } public XmlQueryType CheckAttribute(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.QNameX); return XmlQueryTypeFactory.AttributeQ; } public XmlQueryType CheckParent(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.DocumentOrElementQ; } public XmlQueryType CheckRoot(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.NodeNotRtf; } public XmlQueryType CheckXmlContext(QilNode node) { return XmlQueryTypeFactory.NodeNotRtf; } public XmlQueryType CheckDescendant(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } public XmlQueryType CheckDescendantOrSelf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.Choice(node.Child.XmlType, XmlQueryTypeFactory.ContentS); } public XmlQueryType CheckAncestor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.DocumentOrElementS; } public XmlQueryType CheckAncestorOrSelf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.Choice(node.Child.XmlType, XmlQueryTypeFactory.DocumentOrElementS); } public XmlQueryType CheckPreceding(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.DocumentOrContentS; } public XmlQueryType CheckFollowingSibling(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } public XmlQueryType CheckPrecedingSibling(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } public XmlQueryType CheckNodeRange(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.Choice(node.Left.XmlType, XmlQueryTypeFactory.ContentS, node.Right.XmlType); } public XmlQueryType CheckDeref(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.ElementS; } #endregion // XML navigation #region XML construction //----------------------------------------------- // XML construction //----------------------------------------------- public XmlQueryType CheckElementCtor(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.QNameX); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.UntypedElement; } public XmlQueryType CheckAttributeCtor(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.QNameX); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.UntypedAttribute; } public XmlQueryType CheckCommentCtor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.Comment; } public XmlQueryType CheckPICtor(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.StringX); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.PI; } public XmlQueryType CheckTextCtor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.Text; } public XmlQueryType CheckRawTextCtor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.Text; } public XmlQueryType CheckDocumentCtor(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.UntypedDocument; } public XmlQueryType CheckNamespaceDecl(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.StringX); CheckXmlType(node.Right, XmlQueryTypeFactory.StringX); return XmlQueryTypeFactory.Namespace; } public XmlQueryType CheckRtfCtor(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtfS); CheckClassAndNodeType(node.Right, typeof(QilLiteral), QilNodeType.LiteralString); return XmlQueryTypeFactory.Node; } #endregion // XML construction #region Node properties //----------------------------------------------- // Node properties //----------------------------------------------- public XmlQueryType CheckNameOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); return XmlQueryTypeFactory.QNameX; } public XmlQueryType CheckLocalNameOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); return XmlQueryTypeFactory.StringX; } public XmlQueryType CheckNamespaceUriOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); return XmlQueryTypeFactory.StringX; } public XmlQueryType CheckPrefixOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); return XmlQueryTypeFactory.StringX; } #endregion // Node properties #region Copy operators #endregion // Copy operators #region Type operators //----------------------------------------------- // Type operators //----------------------------------------------- public XmlQueryType CheckTypeAssert(QilTargetType node) { CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType); return node.TargetType; } public XmlQueryType CheckIsType(QilTargetType node) { CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType); return XmlQueryTypeFactory.BooleanX; } public XmlQueryType CheckIsEmpty(QilUnary node) { return XmlQueryTypeFactory.BooleanX; } #endregion // Type operators #region XPath operators //----------------------------------------------- // XPath operators //----------------------------------------------- public XmlQueryType CheckXPathNodeValue(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeS); return XmlQueryTypeFactory.StringX; } public XmlQueryType CheckXPathFollowing(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } public XmlQueryType CheckXPathPreceding(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.ContentS; } public XmlQueryType CheckXPathNamespace(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtf); return XmlQueryTypeFactory.NamespaceS; } #endregion // XPath operators #region XSLT //----------------------------------------------- // XSLT //----------------------------------------------- public XmlQueryType CheckXsltGenerateId(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.NodeNotRtfS); return XmlQueryTypeFactory.StringX; } public XmlQueryType CheckXsltInvokeLateBound(QilInvokeLateBound node) { CheckLiteralValue(node[0], typeof(QilName)); CheckClassAndNodeType(node[1], typeof(QilList), QilNodeType.ActualParameterList); return XmlQueryTypeFactory.ItemS; } public XmlQueryType CheckXsltInvokeEarlyBound(QilInvokeEarlyBound node) { #if DEBUG CheckLiteralValue(node[0], typeof(QilName)); CheckLiteralValue(node[1], typeof(MethodInfo)); CheckClassAndNodeType(node[2], typeof(QilList), QilNodeType.ActualParameterList); XmlExtensionFunction extFunc = new XmlExtensionFunction(node.Name.LocalName, node.Name.NamespaceUri, node.ClrMethod); QilList actualArgs = node.Arguments; Check(actualArgs.Count == extFunc.Method.GetParameters().Length, actualArgs, "InvokeEarlyBound argument count must match function's argument count"); for (int i = 0; i < actualArgs.Count; i++) { Check(actualArgs[i].XmlType.IsSubtypeOf(extFunc.GetXmlArgumentType(i)), actualArgs[i], "InvokeEarlyBound argument must be a subtype of the invoked function's argument type"); } #endif return node.XmlType; } public XmlQueryType CheckXsltCopy(QilBinary node) { CheckXmlType(node.Left, XmlQueryTypeFactory.NodeNotRtf); CheckXmlType(node.Right, XmlQueryTypeFactory.NodeS); return XmlQueryTypeFactory.Choice(node.Left.XmlType, node.Right.XmlType); } public XmlQueryType CheckXsltCopyOf(QilUnary node) { CheckXmlType(node.Child, XmlQueryTypeFactory.Node); if ((node.Child.XmlType.NodeKinds & XmlNodeKindFlags.Document) != 0) return XmlQueryTypeFactory.NodeNotRtfS; return node.Child.XmlType; } public XmlQueryType CheckXsltConvert(QilTargetType node) { CheckClassAndNodeType(node[1], typeof(QilLiteral), QilNodeType.LiteralType); return node.TargetType; } #endregion // Xslt operators //----------------------------------------------- // Helper functions //----------------------------------------------- [Conditional("DEBUG")] private void Check(bool value, QilNode node, string message) { if (!value) QilValidationVisitor.SetError(node, message); } [Conditional("DEBUG")] private void CheckLiteralValue(QilNode node, Type clrTypeValue) { Check(node is QilLiteral, node, "Node must be instance of QilLiteral"); Type clrType = ((QilLiteral)node).Value.GetType(); Check(clrTypeValue.IsAssignableFrom(clrType), node, "Literal value must be of type " + clrTypeValue.Name); } [Conditional("DEBUG")] private void CheckClass(QilNode node, Type clrTypeClass) { Check(clrTypeClass.IsAssignableFrom(node.GetType()), node, "Node must be instance of " + clrTypeClass.Name); } [Conditional("DEBUG")] private void CheckClassAndNodeType(QilNode node, Type clrTypeClass, QilNodeType nodeType) { CheckClass(node, clrTypeClass); Check(node.NodeType == nodeType, node, "Node must have QilNodeType." + nodeType); } [Conditional("DEBUG")] private void CheckXmlType(QilNode node, XmlQueryType xmlType) { Check(node.XmlType.IsSubtypeOf(xmlType), node, "Node's type " + node.XmlType + " is not a subtype of " + xmlType); } [Conditional("DEBUG")] private void CheckNumericX(QilNode node) { Check(node.XmlType.IsNumeric && node.XmlType.IsSingleton && node.XmlType.IsStrict, node, "Node's type " + node.XmlType + " must be a strict singleton numeric type"); } [Conditional("DEBUG")] private void CheckNumericXS(QilNode node) { Check(node.XmlType.IsNumeric && node.XmlType.IsStrict, node, "Node's type " + node.XmlType + " must be a strict numeric type"); } [Conditional("DEBUG")] private void CheckAtomicX(QilNode node) { Check(node.XmlType.IsAtomicValue && node.XmlType.IsStrict, node, "Node's type " + node.XmlType + " must be a strict atomic value type"); } [Conditional("DEBUG")] private void CheckNotDisjoint(QilBinary node) { Check(node.Left.XmlType.IsSubtypeOf(node.Right.XmlType) || node.Right.XmlType.IsSubtypeOf(node.Left.XmlType), node, "Node must not have arguments with disjoint types " + node.Left.XmlType + " and " + node.Right.XmlType); } private XmlQueryType DistinctType(XmlQueryType type) { if (type.Cardinality == XmlQueryCardinality.More) return XmlQueryTypeFactory.PrimeProduct(type, XmlQueryCardinality.OneOrMore); if (type.Cardinality == XmlQueryCardinality.NotOne) return XmlQueryTypeFactory.PrimeProduct(type, XmlQueryCardinality.ZeroOrMore); return type; } private XmlQueryType FindFilterType(QilIterator variable, QilNode body) { XmlQueryType leftType; QilBinary binary; if (body.XmlType.TypeCode == XmlTypeCode.None) return XmlQueryTypeFactory.None; switch (body.NodeType) { case QilNodeType.False: return XmlQueryTypeFactory.Empty; case QilNodeType.IsType: // If testing the type of "variable", then filter type can be restricted if ((object)((QilTargetType)body).Source == (object)variable) return XmlQueryTypeFactory.AtMost(((QilTargetType)body).TargetType, variable.Binding.XmlType.Cardinality); break; case QilNodeType.And: // Both And conditions can be used to restrict filter's type leftType = FindFilterType(variable, ((QilBinary)body).Left); if (leftType != null) return leftType; return FindFilterType(variable, ((QilBinary)body).Right); case QilNodeType.Eq: // Restrict cardinality if position($iterator) = $pos is found binary = (QilBinary)body; if (binary.Left.NodeType == QilNodeType.PositionOf) { if ((object)((QilUnary)binary.Left).Child == (object)variable) return XmlQueryTypeFactory.AtMost(variable.Binding.XmlType, XmlQueryCardinality.ZeroOrOne); } break; } return null; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.Debugger.Interop; using System.Diagnostics; namespace Microsoft.MIDebugEngine { // An implementation of IDebugProperty2 // This interface represents a stack frame property, a program document property, or some other property. // The property is usually the result of an expression evaluation. // // The sample engine only supports locals and parameters for functions that have symbols loaded. internal class AD7Property : IDebugProperty3 { private static uint s_maxChars = 1000000; private byte[] _bytes; private AD7Engine _engine; private IVariableInformation _variableInformation; public AD7Property(AD7Engine engine, IVariableInformation vi) { _engine = engine; _variableInformation = vi; } // Construct a DEBUG_PROPERTY_INFO representing this local or parameter. public DEBUG_PROPERTY_INFO ConstructDebugPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields) { IVariableInformation variable = _variableInformation; if ((dwFields & (enum_DEBUGPROP_INFO_FLAGS)enum_DEBUGPROP_INFO_FLAGS100.DEBUGPROP100_INFO_NOSIDEEFFECTS) != 0) { if ((variable = _engine.DebuggedProcess.Natvis.Cache.VisualizeOnRefresh(_variableInformation)) == null) { return AD7ErrorProperty.ConstructErrorPropertyInfo(dwFields, _variableInformation.Name, ResourceStrings.NoSideEffectsVisualizerMessage, this); } } DEBUG_PROPERTY_INFO propertyInfo = new DEBUG_PROPERTY_INFO(); if ((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME) != 0) { propertyInfo.bstrFullName = variable.FullName(); if (propertyInfo.bstrFullName != null) { propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_FULLNAME; } } if ((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME) != 0) { propertyInfo.bstrName = variable.Name; propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME; } if ((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_TYPE) != 0 && !string.IsNullOrEmpty(variable.TypeName)) { propertyInfo.bstrType = variable.TypeName; propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_TYPE; } if ((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE) != 0) { propertyInfo.bstrValue = _engine.DebuggedProcess.Natvis.FormatDisplayString(variable); propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE; } if ((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_ATTRIB) != 0) { // don't check readonly attribute, it doubles the eval time for a variable //if (this.m_variableInformation.IsReadOnly()) //{ // propertyInfo.dwAttrib |= enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_VALUE_READONLY; //} if (variable.CountChildren != 0) { propertyInfo.dwAttrib |= enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_OBJ_IS_EXPANDABLE; } if (variable.Error) { propertyInfo.dwAttrib |= enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_VALUE_ERROR; } if (variable.IsStringType) { propertyInfo.dwAttrib |= enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_VALUE_RAW_STRING; } propertyInfo.dwAttrib |= variable.Access; } // If the debugger has asked for the property, or the property has children (meaning it is a pointer in the sample) // then set the pProperty field so the debugger can call back when the children are enumerated. if (((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP) != 0) || (variable.CountChildren != 0)) { propertyInfo.pProperty = (IDebugProperty2)this; propertyInfo.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP; } return propertyInfo; } #region IDebugProperty2 Members // Enumerates the children of a property. This provides support for dereferencing pointers, displaying members of an array, or fields of a class or struct. public int EnumChildren(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, ref Guid guidFilter, enum_DBG_ATTRIB_FLAGS dwAttribFilter, string pszNameFilter, uint dwTimeout, out IEnumDebugPropertyInfo2 ppEnum) { ppEnum = null; _variableInformation.EnsureChildren(); if (_variableInformation.CountChildren != 0) { try { _engine.DebuggedProcess.Natvis.WaitDialog.ShowWaitDialog(_variableInformation.Name); var children = _engine.DebuggedProcess.Natvis.Expand(_variableInformation); DEBUG_PROPERTY_INFO[] properties = new DEBUG_PROPERTY_INFO[children.Length]; for (int i = 0; i < children.Length; i++) { properties[i] = (new AD7Property(_engine, children[i])).ConstructDebugPropertyInfo(dwFields); } ppEnum = new AD7PropertyEnum(properties); return Constants.S_OK; } finally { _engine.DebuggedProcess.Natvis.WaitDialog.EndWaitDialog(); } } return Constants.S_FALSE; } // Returns the property that describes the most-derived property of a property // This is called to support object oriented languages. It allows the debug engine to return an IDebugProperty2 for the most-derived // object in a hierarchy. This engine does not support this. public int GetDerivedMostProperty(out IDebugProperty2 ppDerivedMost) { throw new NotImplementedException(); } // This method exists for the purpose of retrieving information that does not lend itself to being retrieved by calling the IDebugProperty2::GetPropertyInfo // method. This includes information about custom viewers, managed type slots and other information. // The sample engine does not support this. public int GetExtendedInfo(ref System.Guid guidExtendedInfo, out object pExtendedInfo) { throw new NotImplementedException(); } // Returns the memory bytes for a property value. public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) { throw new NotImplementedException(); } // Returns the memory context for a property value. public int GetMemoryContext(out IDebugMemoryContext2 ppMemory) { ppMemory = null; if (_variableInformation.Error) return AD7_HRESULT.S_GETMEMORYCONTEXT_NO_MEMORY_CONTEXT; // try to interpret the result as an address string v = _variableInformation.Value; v = v.Trim(); if (v.Length == 0) { return AD7_HRESULT.S_GETMEMORYCONTEXT_NO_MEMORY_CONTEXT; } if (v[0] == '{') { // strip type name and trailing spaces v = v.Substring(v.IndexOf('}') + 1); v = v.Trim(); } int i = v.IndexOf(' '); if (i > 0) { v = v.Substring(0, i); } uint addr; if (!UInt32.TryParse(v, System.Globalization.NumberStyles.Any, null, out addr)) { if (v.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { v = v.Substring(2); if (!UInt32.TryParse(v, System.Globalization.NumberStyles.AllowHexSpecifier, null, out addr)) { return AD7_HRESULT.S_GETMEMORYCONTEXT_NO_MEMORY_CONTEXT; } } else { return AD7_HRESULT.S_GETMEMORYCONTEXT_NO_MEMORY_CONTEXT; } } ppMemory = new AD7MemoryAddress(_engine, addr, null); return Constants.S_OK; } // Returns the parent of a property. // The sample engine does not support obtaining the parent of properties. public int GetParent(out IDebugProperty2 ppParent) { throw new NotImplementedException(); } // Fills in a DEBUG_PROPERTY_INFO structure that describes a property. public int GetPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, uint dwTimeout, IDebugReference2[] rgpArgs, uint dwArgCount, DEBUG_PROPERTY_INFO[] pPropertyInfo) { pPropertyInfo[0] = new DEBUG_PROPERTY_INFO(); rgpArgs = null; pPropertyInfo[0] = ConstructDebugPropertyInfo(dwFields); return Constants.S_OK; } // Return an IDebugReference2 for this property. An IDebugReference2 can be thought of as a type and an address. public int GetReference(out IDebugReference2 ppReference) { throw new NotImplementedException(); } // Returns the size, in bytes, of the property value. public int GetSize(out uint pdwSize) { throw new NotImplementedException(); } // The debugger will call this when the user tries to edit the property's values // the sample has set the read-only flag on its properties, so this should not be called. public int SetValueAsReference(IDebugReference2[] rgpArgs, uint dwArgCount, IDebugReference2 pValue, uint dwTimeout) { throw new NotImplementedException(); } // The debugger will call this when the user tries to edit the property's values in one of the debugger windows. // the sample has set the read-only flag on its properties, so this should not be called. public int SetValueAsString(string pszValue, uint dwRadix, uint dwTimeout) { string error; return SetValueAsStringWithError(pszValue, dwRadix, dwTimeout, out error); } #endregion public int CreateObjectID() { throw new NotImplementedException(); } public int DestroyObjectID() { throw new NotImplementedException(); } public int GetCustomViewerCount(out uint pcelt) { pcelt = 0; return Constants.S_OK; } public int GetCustomViewerList(uint celtSkip, uint celtRequested, DEBUG_CUSTOM_VIEWER[] rgViewers, out uint pceltFetched) { throw new NotImplementedException(); } private void InitializeBytes() { if (_bytes != null) return; uint fetched = 0; _bytes = new byte[0]; IDebugMemoryContext2 memAddr; if (GetMemoryContext(out memAddr) != Constants.S_OK) { // no address in the expression value, try casting to a char* VariableInformation v = new VariableInformation("(char*)(" + _variableInformation.FullName() + ")", (VariableInformation)_variableInformation); v.SyncEval(); if (v.Error) { return; } AD7Property p = new AD7Property(_engine, v); uint pLen; if (p.GetStringCharLength(out pLen) == Constants.S_OK) { _bytes = new byte[pLen]; p.GetStringRawBytes(pLen, _bytes, out fetched); } return; } IDebugMemoryBytes2 memContent; if (((AD7MemoryAddress)memAddr).Engine.GetMemoryBytes(out memContent) != Constants.S_OK) { return; } fetched = 0; bool eos = false; byte[] bytes = new byte[s_maxChars + 1]; byte[] chunk = new byte[2048]; while (!eos) { // fetched is count of bytes in string so far // eos == false => fetch < s_maxChars // eos == true => string is terminated, that is bytes[fetched-1] == 0 uint bytesRead; uint bytesUnreadable = 0; // get next chunk if (memContent.ReadAt(memAddr, (uint)chunk.Length, chunk, out bytesRead, ref bytesUnreadable) != Constants.S_OK) { break; } // copy chunk to bytes for (uint i = 0; i < bytesRead; ++i) { bytes[fetched++] = chunk[i]; if (bytes[fetched - 1] == 0) { eos = true; // end of string break; } if (fetched == s_maxChars) // buffer is full { bytes[fetched++] = 0; // end the string eos = true; break; } } if (bytesRead != chunk.Length) { // read to end of available memory break; } // advance to next chunk memAddr.Add(bytesRead, out memAddr); } if (!eos) { Debug.Assert(fetched < bytes.Length); bytes[fetched++] = 0; } if (fetched < bytes.Length) { _bytes = new byte[fetched]; Array.Copy(bytes, _bytes, (int)fetched); } else { _bytes = bytes; } } public int GetStringCharLength(out uint pLen) { InitializeBytes(); pLen = (uint)_bytes.Length; return Constants.S_OK; } private int GetStringRawBytes(uint buflen, byte[] rgString, out uint pceltFetched) { InitializeBytes(); for (pceltFetched = 0; pceltFetched < Math.Min(_bytes.Length, buflen); ++pceltFetched) { rgString[pceltFetched] = _bytes[pceltFetched]; } return Constants.S_OK; } public int GetStringChars(uint buflen, ushort[] rgString, out uint pceltFetched) { pceltFetched = 0; if (_bytes == null) { return Constants.E_FAIL; } for (pceltFetched = 0; pceltFetched < Math.Min(_bytes.Length, buflen); ++pceltFetched) { rgString[pceltFetched] = _bytes[pceltFetched]; } return Constants.S_OK; } public int SetValueAsStringWithError(string pszValue, uint dwRadix, uint dwTimeout, out string errorString) { errorString = null; try { if (_variableInformation is VariableInformation) { ((VariableInformation)_variableInformation).Assign(pszValue); return Constants.S_OK; } else { errorString = ResourceStrings.InvalidAssignment; } } catch (MICore.UnexpectedMIResultException e) { if (!string.IsNullOrEmpty(e.MIError)) { errorString = e.MIError; } else { errorString = e.Message; } } return Constants.E_FAIL; } } internal class AD7ErrorProperty : IDebugProperty3 { private readonly string _name; private readonly string _message; public AD7ErrorProperty(string name, string message) { _name = name; _message = message; } public int CreateObjectID() { throw new NotImplementedException(); } public int DestroyObjectID() { throw new NotImplementedException(); } public int EnumChildren(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, ref Guid guidFilter, enum_DBG_ATTRIB_FLAGS dwAttribFilter, string pszNameFilter, uint dwTimeout, out IEnumDebugPropertyInfo2 ppEnum) { ppEnum = null; return Constants.S_FALSE; } public int GetCustomViewerCount(out uint pcelt) { pcelt = 0; return Constants.S_OK; } public int GetCustomViewerList(uint celtSkip, uint celtRequested, DEBUG_CUSTOM_VIEWER[] rgViewers, out uint pceltFetched) { throw new NotImplementedException(); } public int GetDerivedMostProperty(out IDebugProperty2 ppDerivedMost) { throw new NotImplementedException(); } public int GetExtendedInfo(ref Guid guidExtendedInfo, out object pExtendedInfo) { throw new NotImplementedException(); } public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) { throw new NotImplementedException(); } public int GetMemoryContext(out IDebugMemoryContext2 ppMemory) { ppMemory = null; return AD7_HRESULT.S_GETMEMORYCONTEXT_NO_MEMORY_CONTEXT; } public int GetParent(out IDebugProperty2 ppParent) { throw new NotImplementedException(); } public static DEBUG_PROPERTY_INFO ConstructErrorPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields, string name, string error, IDebugProperty2 prop) { DEBUG_PROPERTY_INFO property = new DEBUG_PROPERTY_INFO(); ; if ((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME) != 0) { property.bstrName = name; property.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_NAME; } if ((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE) != 0) { property.bstrValue = error; property.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_VALUE; } if ((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_ATTRIB) != 0) { property.dwAttrib |= enum_DBG_ATTRIB_FLAGS.DBG_ATTRIB_VALUE_ERROR; } if ((dwFields & enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP) != 0) { property.pProperty = prop; property.dwFields |= enum_DEBUGPROP_INFO_FLAGS.DEBUGPROP_INFO_PROP; } return property; } public int GetPropertyInfo(enum_DEBUGPROP_INFO_FLAGS dwFields, uint dwRadix, uint dwTimeout, IDebugReference2[] rgpArgs, uint dwArgCount, DEBUG_PROPERTY_INFO[] pPropertyInfo) { pPropertyInfo[0] = ConstructErrorPropertyInfo(dwFields, _name, _message, this); rgpArgs = null; return Constants.S_OK; } public int GetReference(out IDebugReference2 ppReference) { throw new NotImplementedException(); } public int GetSize(out uint pdwSize) { throw new NotImplementedException(); } public int GetStringCharLength(out uint pLen) { pLen = 0; return Constants.S_OK; } public int GetStringChars(uint buflen, ushort[] rgString, out uint pceltFetched) { pceltFetched = 0; return Constants.E_FAIL; } public int SetValueAsReference(IDebugReference2[] rgpArgs, uint dwArgCount, IDebugReference2 pValue, uint dwTimeout) { throw new NotImplementedException(); } public int SetValueAsString(string pszValue, uint dwRadix, uint dwTimeout) { return Constants.E_FAIL; } public int SetValueAsStringWithError(string pszValue, uint dwRadix, uint dwTimeout, out string errorString) { errorString = null; return Constants.E_FAIL; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System { public static partial class PlatformDetection { // // Do not use the " { get; } = <expression> " pattern here. Having all the initialization happen in the type initializer // means that one exception anywhere means all tests using PlatformDetection fail. If you feel a value is worth latching, // do it in a way that failures don't cascade. // public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase); public static bool IsNetNative => RuntimeInformation.FrameworkDescription.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase); public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows); public static bool IsWindows7 => IsWindows && GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1; public static bool IsWindows8x => IsWindows && GetWindowsVersion() == 6 && (GetWindowsMinorVersion() == 2 || GetWindowsMinorVersion() == 3); public static bool IsOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX); public static bool IsNetBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")); public static bool IsOpenSUSE => IsDistroAndVersion("opensuse"); public static bool IsUbuntu => IsDistroAndVersion("ubuntu"); public static bool IsWindowsNanoServer => (IsWindows && !File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "regedit.exe"))); public static bool IsNotWindowsNanoServer => !IsWindowsNanoServer; public static bool IsWindows10Version1607OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393; public static bool IsWindows10Version1703OrGreater => IsWindows && GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063; // Windows OneCoreUAP SKU doesn't have httpapi.dll public static bool IsNotOneCoreUAP => (!IsWindows || File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "System32", "httpapi.dll"))); public static int WindowsVersion => GetWindowsVersion(); public static bool IsNetfx462OrNewer() { if (!IsFullFramework) { return false; } Version net462 = new Version(4, 6, 2); Version runningVersion = GetFrameworkVersion(); return runningVersion != null && runningVersion >= net462; } public static bool IsNetfx470OrNewer() { if (!IsFullFramework) { return false; } Version net470 = new Version(4, 7, 0); Version runningVersion = GetFrameworkVersion(); return runningVersion != null && runningVersion >= net470; } public static Version GetFrameworkVersion() { string[] descriptionArray = RuntimeInformation.FrameworkDescription.Split(' '); if (descriptionArray.Length < 3) { return null; } string runningVersion = descriptionArray[2]; // we could get a version with build number > 1 e.g 4.6.1375 but we only want to have 4.6.1 // so that we get the actual Framework Version if (runningVersion.Length > 5) { runningVersion = runningVersion.Substring(0, 5); } Version result; return Version.TryParse(runningVersion, out result) ? result : null; } private static int s_isWinRT = -1; public static bool IsWinRT { get { if (s_isWinRT != -1) return s_isWinRT == 1; if (!IsWindows || IsWindows7) { s_isWinRT = 0; return false; } byte[] buffer = new byte[0]; uint bufferSize = 0; try { int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer); switch (result) { case 15703: // APPMODEL_ERROR_NO_APPLICATION s_isWinRT = 0; break; case 0: // ERROR_SUCCESS case 122: // ERROR_INSUFFICIENT_BUFFER // Success is actually insufficent buffer as we're really only looking for // not NO_APPLICATION and we're not actually giving a buffer here. The // API will always return NO_APPLICATION if we're not running under a // WinRT process, no matter what size the buffer is. s_isWinRT = 1; break; default: throw new InvalidOperationException($"Failed to get AppId, result was {result}."); } } catch (Exception e) { // We could catch this here, being friendly with older portable surface area should we // desire to use this method elsewhere. if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal)) { // API doesn't exist, likely pre Win8 s_isWinRT = 0; } else { throw; } } return s_isWinRT == 1; } } private static Lazy<bool> m_isWindowsSubsystemForLinux = new Lazy<bool>(GetIsWindowsSubsystemForLinux); public static bool IsWindowsSubsystemForLinux => m_isWindowsSubsystemForLinux.Value; public static bool IsNotWindowsSubsystemForLinux => !IsWindowsSubsystemForLinux; public static bool IsNotFedoraOrRedHatOrCentos => !IsDistroAndVersion("fedora") && !IsDistroAndVersion("rhel") && !IsDistroAndVersion("centos"); public static bool IsFedora => IsDistroAndVersion("fedora"); private static bool GetIsWindowsSubsystemForLinux() { // https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364 if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { const string versionFile = "/proc/version"; if (File.Exists(versionFile)) { string s = File.ReadAllText(versionFile); if (s.Contains("Microsoft") || s.Contains("WSL")) { return true; } } } return false; } public static bool IsDebian8 => IsDistroAndVersion("debian", "8"); public static bool IsUbuntu1404 => IsDistroAndVersion("ubuntu", "14.04"); public static bool IsCentos7 => IsDistroAndVersion("centos", "7"); /// <summary> /// Get whether the OS platform matches the given Linux distro and optional version. /// </summary> /// <param name="distroId">The distribution id.</param> /// <param name="versionId">The distro version. If omitted, compares the distro only.</param> /// <returns>Whether the OS platform matches the given Linux distro and optional version.</returns> private static bool IsDistroAndVersion(string distroId, string versionId = null) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { IdVersionPair v = ParseOsReleaseFile(); if (v.Id == distroId && (versionId == null || v.VersionId == versionId)) { return true; } } return false; } private static IdVersionPair ParseOsReleaseFile() { Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)); IdVersionPair ret = new IdVersionPair(); ret.Id = ""; ret.VersionId = ""; if (File.Exists("/etc/os-release")) { foreach (string line in File.ReadLines("/etc/os-release")) { if (line.StartsWith("ID=", System.StringComparison.Ordinal)) { ret.Id = line.Substring("ID=".Length); } else if (line.StartsWith("VERSION_ID=", System.StringComparison.Ordinal)) { ret.VersionId = line.Substring("VERSION_ID=".Length); } } } string versionId = ret.VersionId; if (versionId.Length >= 2 && versionId[0] == '"' && versionId[versionId.Length - 1] == '"') { // Remove quotes. ret.VersionId = versionId.Substring(1, versionId.Length - 2); } if (ret.Id.Length >= 2 && ret.Id[0] == '"' && ret.Id[ret.Id.Length - 1] == '"') { // Remove quotes. ret.Id = ret.Id.Substring(1, ret.Id.Length - 2); } return ret; } private struct IdVersionPair { public string Id { get; set; } public string VersionId { get; set; } } private static int GetWindowsVersion() { if (IsWindows) { RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); Assert.Equal(0, RtlGetVersion(out osvi)); return (int)osvi.dwMajorVersion; } return -1; } private static int GetWindowsMinorVersion() { if (IsWindows) { RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); Assert.Equal(0, RtlGetVersion(out osvi)); return (int)osvi.dwMinorVersion; } return -1; } private static int GetWindowsBuildNumber() { if (IsWindows) { RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX(); osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi); Assert.Equal(0, RtlGetVersion(out osvi)); return (int)osvi.dwBuildNumber; } return -1; } [DllImport("ntdll.dll")] private static extern int RtlGetVersion(out RTL_OSVERSIONINFOEX lpVersionInformation); [StructLayout(LayoutKind.Sequential)] private struct RTL_OSVERSIONINFOEX { internal uint dwOSVersionInfoSize; internal uint dwMajorVersion; internal uint dwMinorVersion; internal uint dwBuildNumber; internal uint dwPlatformId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] internal string szCSDVersion; } private static int s_isWindowsElevated = -1; public static bool IsWindowsAndElevated { get { if (s_isWindowsElevated != -1) return s_isWindowsElevated == 1; if (!IsWindows || IsWinRT) { s_isWindowsElevated = 0; return false; } IntPtr processToken; Assert.True(OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out processToken)); try { uint tokenInfo; uint returnLength; Assert.True(GetTokenInformation( processToken, TokenElevation, out tokenInfo, sizeof(uint), out returnLength)); s_isWindowsElevated = tokenInfo == 0 ? 0 : 1; } finally { CloseHandle(processToken); } return s_isWindowsElevated == 1; } } private const uint TokenElevation = 20; private const uint STANDARD_RIGHTS_READ = 0x00020000; private const uint TOKEN_QUERY = 0x0008; private const uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY; [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] public static extern bool GetTokenInformation( IntPtr TokenHandle, uint TokenInformationClass, out uint TokenInformation, uint TokenInformationLength, out uint ReturnLength); [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)] public static extern bool CloseHandle( IntPtr handle); [DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)] public static extern bool OpenProcessToken( IntPtr ProcessHandle, uint DesiredAccesss, out IntPtr TokenHandle); // The process handle does NOT need closing [DllImport("kernel32.dll", ExactSpelling = true)] public static extern IntPtr GetCurrentProcess(); [DllImport("kernel32.dll", ExactSpelling = true)] public static extern int GetCurrentApplicationUserModelId( ref uint applicationUserModelIdLength, byte[] applicationUserModelId); public static bool IsNonZeroLowerBoundArraySupported { get { if (s_lazyNonZeroLowerBoundArraySupported == null) { bool nonZeroLowerBoundArraysSupported = false; try { Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 5 }); nonZeroLowerBoundArraysSupported = true; } catch (PlatformNotSupportedException) { } s_lazyNonZeroLowerBoundArraySupported = Tuple.Create<bool>(nonZeroLowerBoundArraysSupported); } return s_lazyNonZeroLowerBoundArraySupported.Item1; } } private static volatile Tuple<bool> s_lazyNonZeroLowerBoundArraySupported; public static bool IsReflectionEmitSupported = !PlatformDetection.IsNetNative; // Tracked in: https://github.com/dotnet/corert/issues/3643 in case we change our mind about this. public static bool IsInvokingStaticConstructorsSupported => !PlatformDetection.IsNetNative; // System.Security.Cryptography.Xml.XmlDsigXsltTransform.GetOutput() relies on XslCompiledTransform which relies // heavily on Reflection.Emit public static bool IsXmlDsigXsltTransformSupported => PlatformDetection.IsReflectionEmitSupported; } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * 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.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Profiling; using Grpc.Core.Utils; using NUnit.Framework; namespace Grpc.Core.Tests { public class ClientServerTest { const string Host = "127.0.0.1"; MockServiceHelper helper; Server server; Channel channel; [SetUp] public void Init() { helper = new MockServiceHelper(Host); server = helper.GetServer(); server.Start(); channel = helper.GetChannel(); } [TearDown] public void Cleanup() { channel.ShutdownAsync().Wait(); server.ShutdownAsync().Wait(); } [Test] public async Task UnaryCall() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return request; }); Assert.AreEqual("ABC", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "ABC")); Assert.AreEqual("ABC", await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "ABC")); } [Test] public void UnaryCall_ServerHandlerThrows() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new Exception("This was thrown on purpose by a test"); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unknown, ex2.Status.StatusCode); } [Test] public void UnaryCall_ServerHandlerThrowsRpcException() { helper.UnaryHandler = new UnaryServerMethod<string, string>((request, context) => { throw new RpcException(new Status(StatusCode.Unauthenticated, "")); }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); } [Test] public void UnaryCall_ServerHandlerSetsStatus() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { context.Status = new Status(StatusCode.Unauthenticated, ""); return ""; }); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex.Status.StatusCode); var ex2 = Assert.ThrowsAsync<RpcException>(async () => await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc")); Assert.AreEqual(StatusCode.Unauthenticated, ex2.Status.StatusCode); } [Test] public async Task ClientStreamingCall() { helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { string result = ""; await requestStream.ForEachAsync(async (request) => { result += request; }); await Task.Delay(100); return result; }); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); Assert.AreEqual("ABC", await call.ResponseAsync); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull(call.GetTrailers()); } [Test] public async Task ServerStreamingCall() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { await responseStream.WriteAllAsync(request.Split(new []{' '})); context.ResponseTrailers.Add("xyz", ""); }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), "A B C"); CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync()); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull("xyz", call.GetTrailers()[0].Key); } [Test] public async Task ServerStreamingCall_EndOfStreamIsIdempotent() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); Assert.IsFalse(await call.ResponseStream.MoveNext()); Assert.IsFalse(await call.ResponseStream.MoveNext()); } [Test] public async Task ServerStreamingCall_ErrorCanBeAwaitedTwice() { helper.ServerStreamingHandler = new ServerStreamingServerMethod<string, string>(async (request, responseStream, context) => { context.Status = new Status(StatusCode.InvalidArgument, ""); }); var call = Calls.AsyncServerStreamingCall(helper.CreateServerStreamingCall(), ""); var ex = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.InvalidArgument, ex.Status.StatusCode); // attempting MoveNext again should result in throwing the same exception. var ex2 = Assert.ThrowsAsync<RpcException>(async () => await call.ResponseStream.MoveNext()); Assert.AreEqual(StatusCode.InvalidArgument, ex2.Status.StatusCode); } [Test] public async Task DuplexStreamingCall() { helper.DuplexStreamingHandler = new DuplexStreamingServerMethod<string, string>(async (requestStream, responseStream, context) => { while (await requestStream.MoveNext()) { await responseStream.WriteAsync(requestStream.Current); } context.ResponseTrailers.Add("xyz", "xyz-value"); }); var call = Calls.AsyncDuplexStreamingCall(helper.CreateDuplexStreamingCall()); await call.RequestStream.WriteAllAsync(new string[] { "A", "B", "C" }); CollectionAssert.AreEqual(new string[] { "A", "B", "C" }, await call.ResponseStream.ToListAsync()); Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); Assert.IsNotNull("xyz-value", call.GetTrailers()[0].Value); } [Test] public async Task ClientStreamingCall_CancelAfterBegin() { var barrier = new TaskCompletionSource<object>(); helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { barrier.SetResult(null); await requestStream.ToListAsync(); return ""; }); var cts = new CancellationTokenSource(); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); await barrier.Task; // make sure the handler has started. cts.Cancel(); try { // cannot use Assert.ThrowsAsync because it uses Task.Wait and would deadlock. await call.ResponseAsync; Assert.Fail(); } catch (RpcException ex) { Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } } [Test] public async Task ClientStreamingCall_ServerSideReadAfterCancelNotificationReturnsNull() { var handlerStartedBarrier = new TaskCompletionSource<object>(); var cancelNotificationReceivedBarrier = new TaskCompletionSource<object>(); var successTcs = new TaskCompletionSource<string>(); helper.ClientStreamingHandler = new ClientStreamingServerMethod<string, string>(async (requestStream, context) => { handlerStartedBarrier.SetResult(null); // wait for cancellation to be delivered. context.CancellationToken.Register(() => cancelNotificationReceivedBarrier.SetResult(null)); await cancelNotificationReceivedBarrier.Task; var moveNextResult = await requestStream.MoveNext(); successTcs.SetResult(!moveNextResult ? "SUCCESS" : "FAIL"); return ""; }); var cts = new CancellationTokenSource(); var call = Calls.AsyncClientStreamingCall(helper.CreateClientStreamingCall(new CallOptions(cancellationToken: cts.Token))); await handlerStartedBarrier.Task; cts.Cancel(); try { await call.ResponseAsync; Assert.Fail(); } catch (RpcException ex) { Assert.AreEqual(StatusCode.Cancelled, ex.Status.StatusCode); } Assert.AreEqual("SUCCESS", await successTcs.Task); } [Test] public async Task AsyncUnaryCall_EchoMetadata() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { foreach (Metadata.Entry metadataEntry in context.RequestHeaders) { if (metadataEntry.Key != "user-agent") { context.ResponseTrailers.Add(metadataEntry); } } return ""; }); var headers = new Metadata { { "ascii-header", "abcdefg" }, { "binary-header-bin", new byte[] { 1, 2, 3, 0, 0xff } } }; var call = Calls.AsyncUnaryCall(helper.CreateUnaryCall(new CallOptions(headers: headers)), "ABC"); await call; Assert.AreEqual(StatusCode.OK, call.GetStatus().StatusCode); var trailers = call.GetTrailers(); Assert.AreEqual(2, trailers.Count); Assert.AreEqual(headers[0].Key, trailers[0].Key); Assert.AreEqual(headers[0].Value, trailers[0].Value); Assert.AreEqual(headers[1].Key, trailers[1].Key); CollectionAssert.AreEqual(headers[1].ValueBytes, trailers[1].ValueBytes); } [Test] public void UnknownMethodHandler() { var nonexistentMethod = new Method<string, string>( MethodType.Unary, MockServiceHelper.ServiceName, "NonExistentMethod", Marshallers.StringMarshaller, Marshallers.StringMarshaller); var callDetails = new CallInvocationDetails<string, string>(channel, nonexistentMethod, new CallOptions()); var ex = Assert.Throws<RpcException>(() => Calls.BlockingUnaryCall(callDetails, "abc")); Assert.AreEqual(StatusCode.Unimplemented, ex.Status.StatusCode); } [Test] public void ServerCallContext_PeerInfoPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return context.Peer; }); string peer = Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc"); Assert.IsTrue(peer.Contains(Host)); } [Test] public void ServerCallContext_HostAndMethodPresent() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { Assert.IsTrue(context.Host.Contains(Host)); Assert.AreEqual("/tests.Test/Unary", context.Method); return "PASS"; }); Assert.AreEqual("PASS", Calls.BlockingUnaryCall(helper.CreateUnaryCall(), "abc")); } [Test] public async Task Channel_WaitForStateChangedAsync() { helper.UnaryHandler = new UnaryServerMethod<string, string>(async (request, context) => { return request; }); Assert.ThrowsAsync(typeof(TaskCanceledException), async () => await channel.WaitForStateChangedAsync(channel.State, DateTime.UtcNow.AddMilliseconds(10))); var stateChangedTask = channel.WaitForStateChangedAsync(channel.State); await Calls.AsyncUnaryCall(helper.CreateUnaryCall(), "abc"); await stateChangedTask; Assert.AreEqual(ChannelState.Ready, channel.State); } [Test] public async Task Channel_ConnectAsync() { await channel.ConnectAsync(); Assert.AreEqual(ChannelState.Ready, channel.State); await channel.ConnectAsync(DateTime.UtcNow.AddMilliseconds(1000)); Assert.AreEqual(ChannelState.Ready, channel.State); } } }
// The MIT License (MIT) // // Copyright (c) 2014-2016, Institute for Software & Systems Engineering // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace SafetySharp.Runtime.Serialization { using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Modeling; using Utilities; /// <summary> /// Dynamically generates a method that checks range violations or clamps ranges. /// </summary> public sealed class RangeRestrictionsGenerator { /// <summary> /// The reflection information of the <see cref="ObjectTable.GetObject" /> method. /// </summary> private readonly MethodInfo _getObjectMethod = typeof(ObjectTable).GetMethod(nameof(ObjectTable.GetObject)); /// <summary> /// The IL generator of the serialization method. /// </summary> private readonly ILGenerator _il; /// <summary> /// The method that is being generated. /// </summary> private readonly DynamicMethod _method; /// <summary> /// The object that is currently stored in the local variable. /// </summary> private int _loadedObject; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="methodName">The name of the generated method.</param> internal RangeRestrictionsGenerator(string methodName) { Requires.NotNullOrWhitespace(methodName, nameof(methodName)); _method = new DynamicMethod( name: methodName, returnType: typeof(void), parameterTypes: new[] { typeof(ObjectTable) }, m: typeof(object).Assembly.ManifestModule, skipVisibility: true); _il = _method.GetILGenerator(); _il.DeclareLocal(typeof(object)); } /// <summary> /// Compiles the dynamic method, returning a delegate that can be used to invoke it. /// </summary> /// <param name="objects">The known objects that can be serialized and deserialized.</param> internal Action Compile(ObjectTable objects = null) { _il.Emit(OpCodes.Ret); return (Action)_method.CreateDelegate(typeof(Action), objects); } /// <summary> /// Generates the code for the range restriction method. /// </summary> /// <param name="stateGroups">The state groups the code should be generated for.</param> internal void GenerateCode(CompactedStateGroup[] stateGroups) { Requires.NotNull(stateGroups, nameof(stateGroups)); foreach (var group in stateGroups.SelectMany(g => g.Slots).GroupBy(slot => slot.Object, ReferenceEqualityComparer<object>.Default)) { var rangedSlots = group.Where(slot => slot.Range != null && slot.DataType.IsPrimitiveType() && !slot.DataType.IsEnum).ToArray(); if (rangedSlots.Length == 0) continue; LoadObject(rangedSlots[0].ObjectIdentifier); foreach (var slot in rangedSlots) { if (slot.ObjectType.IsArray) RestrictFields(slot); else RestrictField(slot); } } } /// <summary> /// Generates the code to restrict the values contained in ranged array fields. /// </summary> private void RestrictFields(StateSlotMetadata metadata) { for (var i = 0; i < metadata.ElementCount; ++i) RestrictField(metadata, i); } /// <summary> /// Generates the code to restrict the values contained in ranged object fields. /// </summary> private void RestrictField(StateSlotMetadata metadata, int elementIndex = 0) { var exceedsFourBytes = metadata.ElementSizeInBits > 32; var continueLabel = _il.DefineLabel(); switch (metadata.Range.OverflowBehavior) { case OverflowBehavior.Error: // if (v < lower | v > upper) throw PrepareAccess(metadata, elementIndex); AccessField(metadata, OpCodes.Ldfld); LoadConstant(metadata.Range.LowerBound, exceedsFourBytes); _il.Emit(metadata.DataType.IsUnsignedNumericType() ? OpCodes.Clt_Un : OpCodes.Clt); PrepareAccess(metadata, elementIndex); AccessField(metadata, OpCodes.Ldfld); LoadConstant(metadata.Range.UpperBound, exceedsFourBytes); _il.Emit(metadata.DataType.IsUnsignedNumericType() ? OpCodes.Cgt_Un : OpCodes.Cgt); _il.Emit(OpCodes.Or); _il.Emit(OpCodes.Brfalse, continueLabel); // throw new RangeViolationException(obj, field) _il.Emit(OpCodes.Ldloc_0); var field = metadata.ContainedInStruct ? metadata.FieldChain.Last() : metadata.Field; _il.Emit(OpCodes.Ldtoken, field); _il.Emit(OpCodes.Ldtoken, field.DeclaringType); var parameters = new[] { typeof(RuntimeFieldHandle), typeof(RuntimeTypeHandle) }; _il.Emit(OpCodes.Call, typeof(FieldInfo).GetMethod("GetFieldFromHandle", parameters)); LoadConstant(metadata.Range.LowerBound, exceedsFourBytes); _il.Emit(OpCodes.Box, metadata.EffectiveType); LoadConstant(metadata.Range.UpperBound, exceedsFourBytes); _il.Emit(OpCodes.Box, metadata.EffectiveType); _il.Emit(OpCodes.Ldc_I4, (int)OverflowBehavior.Error); _il.Emit(OpCodes.Newobj, typeof(RangeAttribute).GetConstructors().Single()); _il.Emit(OpCodes.Newobj, typeof(RangeViolationException).GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic).Single()); _il.Emit(OpCodes.Throw); break; case OverflowBehavior.Clamp: var clampLabel = _il.DefineLabel(); PrepareAccess(metadata, elementIndex); AccessField(metadata, OpCodes.Ldfld); _il.Emit(OpCodes.Dup); // if (v < lower) v = lower LoadConstant(metadata.Range.LowerBound, exceedsFourBytes); _il.Emit(metadata.DataType.IsUnsignedNumericType() ? OpCodes.Bge_Un_S : OpCodes.Bge_S, clampLabel); _il.Emit(OpCodes.Pop); PrepareAccess(metadata, elementIndex); LoadConstant(metadata.Range.LowerBound, exceedsFourBytes); AccessField(metadata, OpCodes.Stfld); _il.Emit(OpCodes.Br, continueLabel); // else if (v > upper) v = upper _il.MarkLabel(clampLabel); LoadConstant(metadata.Range.UpperBound, exceedsFourBytes); _il.Emit(metadata.DataType.IsUnsignedNumericType() ? OpCodes.Ble_Un_S : OpCodes.Ble_S, continueLabel); PrepareAccess(metadata, elementIndex); LoadConstant(metadata.Range.UpperBound, exceedsFourBytes); AccessField(metadata, OpCodes.Stfld); break; case OverflowBehavior.WrapClamp: var wrapLabel = _il.DefineLabel(); PrepareAccess(metadata, elementIndex); AccessField(metadata, OpCodes.Ldfld); _il.Emit(OpCodes.Dup); // if (v < lower) v = upper LoadConstant(metadata.Range.LowerBound, exceedsFourBytes); _il.Emit(metadata.DataType.IsUnsignedNumericType() ? OpCodes.Bge_Un_S : OpCodes.Bge_S, wrapLabel); _il.Emit(OpCodes.Pop); PrepareAccess(metadata, elementIndex); LoadConstant(metadata.Range.UpperBound, exceedsFourBytes); AccessField(metadata, OpCodes.Stfld); _il.Emit(OpCodes.Br, continueLabel); // else if (v > upper) v = lower _il.MarkLabel(wrapLabel); LoadConstant(metadata.Range.UpperBound, exceedsFourBytes); _il.Emit(metadata.DataType.IsUnsignedNumericType() ? OpCodes.Ble_Un_S : OpCodes.Ble_S, continueLabel); PrepareAccess(metadata, elementIndex); LoadConstant(metadata.Range.LowerBound, exceedsFourBytes); AccessField(metadata, OpCodes.Stfld); break; default: Assert.NotReached("Unknown overflow behavior."); break; } _il.MarkLabel(continueLabel); } /// <summary> /// Loads the <paramref name="constant" /> onto the stack. /// </summary> private void LoadConstant(object constant, bool exceedsFourBytes) { if (exceedsFourBytes) { if (constant is double) _il.Emit(OpCodes.Ldc_I8, (double)constant); else _il.Emit(OpCodes.Ldc_I8, NormalizeToInt64(constant)); } else { if (constant is float) _il.Emit(OpCodes.Ldc_I4, (float)constant); else _il.Emit(OpCodes.Ldc_I4, NormalizeToInt32(constant)); } } /// <summary> /// Normalizes the type of the <paramref name="constant" /> value. /// </summary> private static int NormalizeToInt32(object constant) { switch (Type.GetTypeCode(constant.GetType())) { case TypeCode.Char: return (char)constant; case TypeCode.SByte: return (sbyte)constant; case TypeCode.Byte: return (byte)constant; case TypeCode.Int16: return (short)constant; case TypeCode.UInt16: return (ushort)constant; case TypeCode.Int32: return (int)constant; case TypeCode.UInt32: return (int)(uint)constant; case TypeCode.Int64: return checked((int)(long)constant); case TypeCode.UInt64: return checked((int)(ulong)constant); default: return Assert.NotReached<int>($"Cannot normalize value of type {constant.GetType().FullName}."); } } /// <summary> /// Normalizes the type of the <paramref name="constant" /> value. /// </summary> private static long NormalizeToInt64(object constant) { switch (Type.GetTypeCode(constant.GetType())) { case TypeCode.Char: return (char)constant; case TypeCode.SByte: return (sbyte)constant; case TypeCode.Byte: return (byte)constant; case TypeCode.Int16: return (short)constant; case TypeCode.UInt16: return (ushort)constant; case TypeCode.Int32: return (int)constant; case TypeCode.UInt32: return (int)(uint)constant; case TypeCode.Int64: return (long)constant; case TypeCode.UInt64: return (long)(ulong)constant; default: return Assert.NotReached<long>($"Cannot normalize value of type {constant.GetType().FullName}."); } } /// <summary> /// Loads the object with the <paramref name="objectIdentifier" /> into the local variable. /// </summary> private void LoadObject(int objectIdentifier) { if (_loadedObject == objectIdentifier) return; // o = objs.GetObject(objectIdentifier) _il.Emit(OpCodes.Ldarg_0); _il.Emit(OpCodes.Ldc_I4, objectIdentifier); _il.Emit(OpCodes.Call, _getObjectMethod); _il.Emit(OpCodes.Stloc_0); _loadedObject = objectIdentifier; } /// <summary> /// Prepares the access to the field referenced by the <paramref name="metadata" />. /// </summary> private void PrepareAccess(StateSlotMetadata metadata, int elementIndex) { _il.Emit(OpCodes.Ldloc_0); if (!metadata.ContainedInStruct) return; if (metadata.ObjectType.IsArray) { _il.Emit(OpCodes.Ldc_I4, elementIndex); _il.Emit(OpCodes.Ldelema, metadata.ObjectType.GetElementType()); } else _il.Emit(OpCodes.Ldflda, metadata.Field); for (var i = 0; i < metadata.FieldChain.Length - 1; ++i) _il.Emit(OpCodes.Ldflda, metadata.FieldChain[i]); } /// <summary> /// Accesses the field on the object currently on the stack. /// </summary> private void AccessField(StateSlotMetadata metadata, OpCode accessCode) { var field = metadata.ContainedInStruct ? metadata.FieldChain.Last() : metadata.Field; _il.Emit(accessCode, field); } } }
#region Copyright // Copyright 2014 Myrcon Pty. Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Linq; using NUnit.Framework; namespace Potato.Net.Shared.Test { [TestFixture] public class PacketStreamTest { /// <summary> /// Tests that data can be pushed onto the end of the packet stream, if the packet stream is uninitialized. /// </summary> [Test] public void TestEmptyPacketStreamPush() { PacketStream stream = new PacketStream(); stream.Push(new byte[] { 0x01 }, 1); Assert.AreEqual(1, stream.Data.Length); Assert.AreEqual(0x01, stream.Data[0]); } /// <summary> /// Tests that a size is returned of 0, even on an uninitialized stream. /// </summary> [Test] public void TestEmptyPacketStreamSizeZero() { PacketStream stream = new PacketStream(); Assert.AreEqual(0, stream.Size()); } /// <summary> /// Tests that a size can be obtained from an initialized stream. /// </summary> [Test] public void TestEmptyPacketStreamSizeOne() { PacketStream stream = new PacketStream(); stream.Push(new byte[] { 0x01 }, 1); Assert.AreEqual(1, stream.Size()); } /// <summary> /// Test that pushing an empty array of data onto an empty set results in no exception, but remains an empty stream. /// </summary> [Test] public void TestEmptyPacketStreamPushEmptyData() { PacketStream stream = new PacketStream(); stream.Push(new byte[0], 0); Assert.AreEqual(0, stream.Data.Length); } /// <summary> /// Tests that pushing a null data array onto the packet stream results in no changes and no exceptions. /// </summary> [Test] public void TestEmptyPacketStreamPushNullData() { PacketStream stream = new PacketStream(); stream.Push(null, 0); Assert.AreEqual(0, stream.Data.Length); } /// <summary> /// Tests that single data can be appended to the end of an existing stream. /// </summary> [Test] public void TestSingleAppendPacketStreamPush() { PacketStream stream = new PacketStream() { Data = new byte[] {0x01} }; stream.Push(new byte[] { 0x02 }, 1); Assert.AreEqual(2, stream.Data.Length); Assert.AreEqual(0x01, stream.Data[0]); Assert.AreEqual(0x02, stream.Data[1]); } /// <summary> /// Tests that an empty data array can be appended to the end of an existing stream, resulting in no change to the stream /// with no exceptions posted. /// </summary> [Test] public void TestSingleAppendPacketStreamPushEmptyData() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01 } }; stream.Push(new byte[0], 0); Assert.AreEqual(1, stream.Data.Length); Assert.AreEqual(0x01, stream.Data[0]); } /// <summary> /// Tests that pushing a null data array onto an established stream results in no changes and no exceptions. /// </summary> [Test] public void TestSingleAppendPacketStreamPushNullData() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01 } }; stream.Push(null, 0); Assert.AreEqual(1, stream.Data.Length); Assert.AreEqual(0x01, stream.Data[0]); } /// <summary> /// Tests that multiple pushes can be done in a row, with multiple bytes. /// </summary> [Test] public void TestMultipleAppendPacketStreamPush() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01 } }; stream.Push(new byte[] { 0x02 }, 1); stream.Push(new byte[] { 0x03, 0x04 }, 2); Assert.AreEqual(4, stream.Data.Length); Assert.AreEqual(0x01, stream.Data[0]); Assert.AreEqual(0x02, stream.Data[1]); Assert.AreEqual(0x03, stream.Data[2]); Assert.AreEqual(0x04, stream.Data[3]); } /// <summary> /// Tests a single byte can be pulled from the packet stream, without altering the stream. /// </summary> [Test] public void TestSinglePacketStreamPeekShift() { PacketStream stream = new PacketStream() { Data = new byte[] {0x01, 0x02, 0x03, 0x04} }; Assert.AreEqual(0x01, stream.PeekShift(1).First()); Assert.AreEqual(4, stream.Data.Length); Assert.AreEqual(0x01, stream.Data[0]); Assert.AreEqual(0x02, stream.Data[1]); Assert.AreEqual(0x03, stream.Data[2]); Assert.AreEqual(0x04, stream.Data[3]); } /// <summary> /// Tests pulling multiple bytes off the stream for a peek will not alter the stream. /// </summary> [Test] public void TestMultiplePacketStreamPeekShift() { PacketStream stream = new PacketStream() { Data = new byte[] {0x01, 0x02, 0x03, 0x04} }; Assert.AreEqual(0x01, stream.PeekShift(2).First()); Assert.AreEqual(0x02, stream.PeekShift(2).Last()); Assert.AreEqual(4, stream.Data.Length); Assert.AreEqual(0x01, stream.Data[0]); Assert.AreEqual(0x02, stream.Data[1]); Assert.AreEqual(0x03, stream.Data[2]); Assert.AreEqual(0x04, stream.Data[3]); } /// <summary> /// Tests that peeking at no bytes returns an empty array with no changes to the packet stream. /// </summary> [Test] public void TestMultiplePacketStreamPeekShiftZeroBytes() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01, 0x02, 0x03, 0x04 } }; Assert.AreEqual(0, stream.PeekShift(0).Length); Assert.AreEqual(4, stream.Data.Length); Assert.AreEqual(0x01, stream.Data[0]); Assert.AreEqual(0x02, stream.Data[1]); Assert.AreEqual(0x03, stream.Data[2]); Assert.AreEqual(0x04, stream.Data[3]); } /// <summary> /// Tests that a new packet stream with no data initialized will return null when asked for any data. /// </summary> [Test] public void TestUninitializedPacketStreamPeekShift() { PacketStream stream = new PacketStream(); Assert.IsNull(stream.PeekShift(1)); } /// <summary> /// Tests that requesting a peek at more data than is available will return null /// </summary> [Test] public void TestIndexBoundsPacketStreamPeekShift() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01, 0x02, 0x03, 0x04 } }; Assert.IsNull(stream.PeekShift(5)); } /// <summary> /// Tests a single byte can be pulled from the packet stream, removing it from the start of the stream /// </summary> [Test] public void TestSinglePacketStreamShift() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01, 0x02, 0x03, 0x04 } }; byte[] data = stream.Shift(1); Assert.AreEqual(0x01, data.First()); Assert.AreEqual(3, stream.Data.Length); Assert.AreEqual(0x02, stream.Data[0]); Assert.AreEqual(0x03, stream.Data[1]); Assert.AreEqual(0x04, stream.Data[2]); } /// <summary> /// Tests pulling multiple bytes off the stream will remove them from the stream /// </summary> [Test] public void TestMultiplePacketStreamShift() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01, 0x02, 0x03, 0x04 } }; byte[] data = stream.Shift(2); Assert.AreEqual(0x01, data.First()); Assert.AreEqual(0x02, data.Last()); Assert.AreEqual(2, stream.Data.Length); Assert.AreEqual(0x03, stream.Data[0]); Assert.AreEqual(0x04, stream.Data[1]); } /// <summary> /// Tests that all data can be moved off the start of the array, resulting in an empty Data array. /// </summary> [Test] public void TestAllDataPacketStreamShift() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01, 0x02, 0x03, 0x04 } }; byte[] data = stream.Shift(4); Assert.AreEqual(0x01, data[0]); Assert.AreEqual(0x02, data[1]); Assert.AreEqual(0x03, data[2]); Assert.AreEqual(0x04, data[3]); Assert.AreEqual(0, stream.Data.Length); } /// <summary> /// Tests that a new packet stream with no data initialized will return null when asked for any data. /// </summary> [Test] public void TestUninitializedPacketStreamShift() { PacketStream stream = new PacketStream(); Assert.IsNull(stream.Shift(1)); } /// <summary> /// Tests that shifting no bytes returns an empty array with no changes to the packet stream. /// </summary> [Test] public void TestMultiplePacketStreamShiftZeroBytes() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01, 0x02, 0x03, 0x04 } }; Assert.AreEqual(0, stream.Shift(0).Length); Assert.AreEqual(4, stream.Data.Length); Assert.AreEqual(0x01, stream.Data[0]); Assert.AreEqual(0x02, stream.Data[1]); Assert.AreEqual(0x03, stream.Data[2]); Assert.AreEqual(0x04, stream.Data[3]); } /// <summary> /// Tests that requesting a peek at more data than is available will return null /// </summary> [Test] public void TestIndexBoundsPacketStreamShift() { PacketStream stream = new PacketStream() { Data = new byte[] { 0x01, 0x02, 0x03, 0x04 } }; Assert.IsNull(stream.Shift(5)); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using Glass.Mapper.Caching; using Glass.Mapper.Pipelines.ConfigurationResolver; using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.MultiInterfaceResolver; using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver; using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.StandardResolver; using Glass.Mapper.Pipelines.DataMapperResolver; using Glass.Mapper.Pipelines.DataMapperResolver.Tasks; using Glass.Mapper.Pipelines.ObjectConstruction; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CacheAdd; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CacheCheck; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateConcrete; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateInterface; using Glass.Mapper.Pipelines.ObjectConstruction.Tasks.CreateMultiInterface; using Glass.Mapper.Pipelines.ObjectSaving; using Glass.Mapper.Pipelines.ObjectSaving.Tasks; using Glass.Mapper.Sc.CastleWindsor.Pipelines.ObjectConstruction; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.DataMappers; using Glass.Mapper.Sc.DataMappers.SitecoreQueryParameters; using Glass.Mapper.Sc.Pipelines.ConfigurationResolver; using Glass.Mapper.Sc.Pipelines.ObjectConstruction; namespace Glass.Mapper.Sc.CastleWindsor { /// <summary> /// The windsor specific Sitecore installer /// </summary> public class WindsorSitecoreInstaller : IWindsorInstaller { private readonly Config _config; public WindsorSitecoreInstaller(Config config) { _config = config; } public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component.For<Config>().Instance(_config).Named("ScConfig"), Component.For<Mapper.Config>().Instance(_config).Named("Config"), Component.For<Mapper.Caching.ICacheManager>() .ImplementedBy<HttpCache>() .LifestyleCustom<NoTrackLifestyleManager>() ); #region DataMappers container.Register( Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreIgnoreMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreChildrenCastMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreChildrenMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldBooleanMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldDateTimeMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldDecimalMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldDoubleMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldEnumMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldFileMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldFloatMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldGuidMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldHtmlEncodingMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldIEnumerableMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldImageMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldIntegerMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldLinkMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldLongMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNameValueCollectionMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldDictionaryMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableDateTimeMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableDoubleMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableDecimalMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableFloatMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableGuidMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableIntMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldNullableEnumMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldRulesMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldStreamMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldStringMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreFieldTypeMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreIdMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreItemMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreInfoMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreNodeMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreLinkedMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreParentMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>() .ImplementedBy<SitecoreDelegateMapper>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<AbstractDataMapper>().ImplementedBy<SitecoreQueryMapper>() .DynamicParameters((k, d) => { d["parameters"] = k.ResolveAll<ISitecoreQueryParameter>(); }) .LifestyleCustom<NoTrackLifestyleManager>() ); #endregion #region QueryParameters container.Register( Component.For<ISitecoreQueryParameter>() .ImplementedBy<ItemDateNowParameter>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<ISitecoreQueryParameter>() .ImplementedBy<ItemEscapedPathParameter>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<ISitecoreQueryParameter>() .ImplementedBy<ItemIdNoBracketsParameter>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<ISitecoreQueryParameter>() .ImplementedBy<ItemIdParameter>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<ISitecoreQueryParameter>() .ImplementedBy<ItemPathParameter>() .LifestyleCustom<NoTrackLifestyleManager>() ); #endregion #region DataMapperTasks container.Register( Component.For<IDataMapperResolverTask>() .ImplementedBy<DataMapperStandardResolverTask>() .LifestyleCustom<NoTrackLifestyleManager>() ); #endregion #region ConfigurationResolver container.Register( Component.For<IConfigurationResolverTask>() .ImplementedBy<SitecoreItemResolverTask>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<IConfigurationResolverTask>() .ImplementedBy<MultiInterfaceResolverTask>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<IConfigurationResolverTask>() .ImplementedBy<TemplateInferredTypeTask>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<IConfigurationResolverTask>() .ImplementedBy<ConfigurationStandardResolverTask>() .LifestyleCustom<NoTrackLifestyleManager>(), Component.For<IConfigurationResolverTask>() .ImplementedBy<ConfigurationOnDemandResolverTask<SitecoreTypeConfiguration>>() .LifestyleCustom<NoTrackLifestyleManager>() ); #endregion #region ObjectConstruction container.Register( Component.For<IObjectConstructionTask>().ImplementedBy<CacheCheckTask>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<IObjectConstructionTask>().ImplementedBy<CreateDynamicTask>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<IObjectConstructionTask>().ImplementedBy<SitecoreItemTask>().LifestyleCustom<NoTrackLifestyleManager>(), Component.For<IObjectConstructionTask>().ImplementedBy<EnforcedTemplateCheck>().LifestyleCustom<NoTrackLifestyleManager>() ); if (_config.UseIoCConstructor) { container.Register( Component.For<IObjectConstructionTask>().ImplementedBy<WindsorConstruction>().LifestyleCustom<NoTrackLifestyleManager>() ); } container.Register( // Tasks are called in the order they are specified below. Component.For<IObjectConstructionTask>().ImplementedBy<CreateMultiInferaceTask>().LifestyleTransient(), Component.For<IObjectConstructionTask>().ImplementedBy<CreateConcreteTask>().LifestyleTransient(), Component.For<IObjectConstructionTask>().ImplementedBy<CreateInterfaceTask>().LifestyleTransient(), Component.For<IObjectConstructionTask>().ImplementedBy<CacheAddTask>().LifestyleCustom<NoTrackLifestyleManager>() ); #endregion #region ObjectSaving container.Register( Component.For<IObjectSavingTask>().ImplementedBy<StandardSavingTask>().LifestyleCustom<NoTrackLifestyleManager>() ); #endregion } } }
using System; using System.Collections.Generic; using NGUI.Internal; using UnityEngine; namespace NGUI { [Serializable] public class InvGameItem { public int itemLevel; private InvBaseItem mBaseItem; [SerializeField] private int mBaseItemID; public Quality quality; public InvGameItem(int id) { this.quality = Quality.Sturdy; this.itemLevel = 1; this.mBaseItemID = id; } public InvGameItem(int id, InvBaseItem bi) { this.quality = Quality.Sturdy; this.itemLevel = 1; this.mBaseItemID = id; this.mBaseItem = bi; } public List<InvStat> CalculateStats() { List<InvStat> list = new List<InvStat>(); if (this.baseItem != null) { float statMultiplier = this.statMultiplier; List<InvStat> stats = this.baseItem.stats; int num2 = 0; int count = stats.Count; while (num2 < count) { InvStat stat = stats[num2]; int num4 = Mathf.RoundToInt(statMultiplier * stat.amount); if (num4 != 0) { bool flag = false; int num5 = 0; int num6 = list.Count; while (num5 < num6) { InvStat stat2 = list[num5]; if (stat2.id == stat.id && stat2.modifier == stat.modifier) { stat2.amount += num4; flag = true; break; } num5++; } if (!flag) { InvStat item = new InvStat { id = stat.id, amount = num4, modifier = stat.modifier }; list.Add(item); } } num2++; } list.Sort(new Comparison<InvStat>(InvStat.CompareArmor)); } return list; } public InvBaseItem baseItem { get { if (this.mBaseItem == null) { this.mBaseItem = InvDatabase.FindByID(this.baseItemID); } return this.mBaseItem; } } public int baseItemID { get { return this.mBaseItemID; } } public Color color { get { Color white = Color.white; switch (this.quality) { case Quality.Broken: return new Color(0.4f, 0.2f, 0.2f); case Quality.Cursed: return Color.red; case Quality.Damaged: return new Color(0.4f, 0.4f, 0.4f); case Quality.Worn: return new Color(0.7f, 0.7f, 0.7f); case Quality.Sturdy: return new Color(1f, 1f, 1f); case Quality.Polished: return NGUIMath.HexToColor(3774856959); case Quality.Improved: return NGUIMath.HexToColor(2480359935); case Quality.Crafted: return NGUIMath.HexToColor(1325334783); case Quality.Superior: return NGUIMath.HexToColor(12255231); case Quality.Enchanted: return NGUIMath.HexToColor(1937178111); case Quality.Epic: return NGUIMath.HexToColor(2516647935); case Quality.Legendary: return NGUIMath.HexToColor(4287627519); } return white; } } public string name { get { if (this.baseItem == null) { return null; } return this.quality + " " + this.baseItem.name; } } public float statMultiplier { get { float num = 0f; switch (this.quality) { case Quality.Broken: num = 0f; break; case Quality.Cursed: num = -1f; break; case Quality.Damaged: num = 0.25f; break; case Quality.Worn: num = 0.9f; break; case Quality.Sturdy: num = 1f; break; case Quality.Polished: num = 1.1f; break; case Quality.Improved: num = 1.25f; break; case Quality.Crafted: num = 1.5f; break; case Quality.Superior: num = 1.75f; break; case Quality.Enchanted: num = 2f; break; case Quality.Epic: num = 2.5f; break; case Quality.Legendary: num = 3f; break; } float from = this.itemLevel / 50f; return num * Mathf.Lerp(@from, @from * @from, 0.5f); } } public enum Quality { Broken, Cursed, Damaged, Worn, Sturdy, Polished, Improved, Crafted, Superior, Enchanted, Epic, Legendary, _LastDoNotUse } } }
// // SignedXml.cs - SignedXml implementation for XML Signature // // Author: // Sebastien Pouliot <sebastien@ximian.com> // Atsushi Enomoto <atsushi@ximian.com> // Tim Coleman <tim@timcoleman.com> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) Tim Coleman, 2004 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Policy; using System.Net; using System.Text; using System.Xml; using System.Security.Cryptography.X509Certificates; namespace System.Security.Cryptography.Xml { public class SignedXml { public const string XmlDsigCanonicalizationUrl = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; public const string XmlDsigCanonicalizationWithCommentsUrl = XmlDsigCanonicalizationUrl + "#WithComments"; public const string XmlDsigDSAUrl = XmlDsigNamespaceUrl + "dsa-sha1"; public const string XmlDsigHMACSHA1Url = XmlDsigNamespaceUrl + "hmac-sha1"; public const string XmlDsigMinimalCanonicalizationUrl = XmlDsigNamespaceUrl + "minimal"; public const string XmlDsigNamespaceUrl = "http://www.w3.org/2000/09/xmldsig#"; public const string XmlDsigRSASHA1Url = XmlDsigNamespaceUrl + "rsa-sha1"; public const string XmlDsigSHA1Url = XmlDsigNamespaceUrl + "sha1"; public const string XmlDecryptionTransformUrl = "http://www.w3.org/2002/07/decrypt#XML"; public const string XmlDsigBase64TransformUrl = XmlDsigNamespaceUrl + "base64"; public const string XmlDsigC14NTransformUrl = XmlDsigCanonicalizationUrl; public const string XmlDsigC14NWithCommentsTransformUrl = XmlDsigCanonicalizationWithCommentsUrl; public const string XmlDsigEnvelopedSignatureTransformUrl = XmlDsigNamespaceUrl + "enveloped-signature"; public const string XmlDsigExcC14NTransformUrl = "http://www.w3.org/2001/10/xml-exc-c14n#"; public const string XmlDsigExcC14NWithCommentsTransformUrl = XmlDsigExcC14NTransformUrl + "WithComments"; public const string XmlDsigXPathTransformUrl = "http://www.w3.org/TR/1999/REC-xpath-19991116"; public const string XmlDsigXsltTransformUrl = "http://www.w3.org/TR/1999/REC-xslt-19991116"; public const string XmlLicenseTransformUrl = "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform"; private EncryptedXml encryptedXml; protected Signature m_signature; private AsymmetricAlgorithm key; protected string m_strSigningKeyName; private XmlDocument envdoc; private IEnumerator pkEnumerator; private XmlElement signatureElement; private Hashtable hashes; // FIXME: enable it after CAS implementation private XmlResolver xmlResolver = new XmlUrlResolver (); private ArrayList manifests; private IEnumerator _x509Enumerator; private static readonly char [] whitespaceChars = new char [] {' ', '\r', '\n', '\t'}; public SignedXml () { m_signature = new Signature (); m_signature.SignedInfo = new SignedInfo (); hashes = new Hashtable (2); // 98% SHA1 for now } public SignedXml (XmlDocument document) : this () { if (document == null) throw new ArgumentNullException ("document"); envdoc = document; } public SignedXml (XmlElement elem) : this () { if (elem == null) throw new ArgumentNullException ("elem"); envdoc = new XmlDocument (); envdoc.LoadXml (elem.OuterXml); } [ComVisible (false)] public EncryptedXml EncryptedXml { get { return encryptedXml; } set { encryptedXml = value; } } public KeyInfo KeyInfo { get { if (m_signature.KeyInfo == null) m_signature.KeyInfo = new KeyInfo (); return m_signature.KeyInfo; } set { m_signature.KeyInfo = value; } } public Signature Signature { get { return m_signature; } } public string SignatureLength { get { return m_signature.SignedInfo.SignatureLength; } } public string SignatureMethod { get { return m_signature.SignedInfo.SignatureMethod; } } public byte[] SignatureValue { get { return m_signature.SignatureValue; } } public SignedInfo SignedInfo { get { return m_signature.SignedInfo; } } public AsymmetricAlgorithm SigningKey { get { return key; } set { key = value; } } // NOTE: CryptoAPI related ? documented as fx internal public string SigningKeyName { get { return m_strSigningKeyName; } set { m_strSigningKeyName = value; } } public void AddObject (DataObject dataObject) { m_signature.AddObject (dataObject); } public void AddReference (Reference reference) { if (reference == null) throw new ArgumentNullException ("reference"); m_signature.SignedInfo.AddReference (reference); } private Stream ApplyTransform (Transform t, XmlDocument input) { // These transformer modify input document, which should // not affect to the input itself. if (t is XmlDsigXPathTransform || t is XmlDsigEnvelopedSignatureTransform || t is XmlDecryptionTransform ) input = (XmlDocument) input.Clone (); t.LoadInput (input); if (t is XmlDsigEnvelopedSignatureTransform) // It returns XmlDocument for XmlDocument input. return CanonicalizeOutput (t.GetOutput ()); object obj = t.GetOutput (); if (obj is Stream) return (Stream) obj; else if (obj is XmlDocument) { MemoryStream ms = new MemoryStream (); XmlTextWriter xtw = new XmlTextWriter (ms, Encoding.UTF8); ((XmlDocument) obj).WriteTo (xtw); xtw.Flush (); // Rewind to the start of the stream ms.Position = 0; return ms; } else if (obj == null) { throw new NotImplementedException ("This should not occur. Transform is " + t + "."); } else { // e.g. XmlDsigXPathTransform returns XmlNodeList return CanonicalizeOutput (obj); } } private Stream CanonicalizeOutput (object obj) { Transform c14n = GetC14NMethod (); c14n.LoadInput (obj); return (Stream) c14n.GetOutput (); } private XmlDocument GetManifest (Reference r) { XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; if (r.Uri [0] == '#') { // local manifest if (signatureElement != null) { XmlElement xel = GetIdElement (signatureElement.OwnerDocument, r.Uri.Substring (1)); if (xel == null) throw new CryptographicException ("Manifest targeted by Reference was not found: " + r.Uri.Substring (1)); doc.AppendChild (doc.ImportNode (xel, true)); FixupNamespaceNodes (xel, doc.DocumentElement, false); } } else if (xmlResolver != null) { // TODO: need testing Stream s = (Stream) xmlResolver.GetEntity (new Uri (r.Uri), null, typeof (Stream)); doc.Load (s); } if (doc.FirstChild != null) { // keep a copy of the manifests to check their references later if (manifests == null) manifests = new ArrayList (); manifests.Add (doc); return doc; } return null; } private void FixupNamespaceNodes (XmlElement src, XmlElement dst, bool ignoreDefault) { // add namespace nodes foreach (XmlAttribute attr in src.SelectNodes ("namespace::*")) { if (attr.LocalName == "xml") continue; if (ignoreDefault && attr.LocalName == "xmlns") continue; dst.SetAttributeNode (dst.OwnerDocument.ImportNode (attr, true) as XmlAttribute); } } private byte[] GetReferenceHash (Reference r, bool check_hmac) { Stream s = null; XmlDocument doc = null; if (r.Uri == String.Empty) { doc = envdoc; } else if (r.Type == XmlSignature.Uri.Manifest) { doc = GetManifest (r); } else { doc = new XmlDocument (); doc.PreserveWhitespace = true; string objectName = null; if (r.Uri.StartsWith ("#xpointer")) { string uri = string.Join ("", r.Uri.Substring (9).Split (whitespaceChars)); if (uri.Length < 2 || uri [0] != '(' || uri [uri.Length - 1] != ')') // FIXME: how to handle invalid xpointer? uri = String.Empty; else uri = uri.Substring (1, uri.Length - 2); if (uri == "/") doc = envdoc; else if (uri.Length > 6 && uri.StartsWith ("id(") && uri [uri.Length - 1] == ')') // id('foo'), id("foo") objectName = uri.Substring (4, uri.Length - 6); } else if (r.Uri [0] == '#') { objectName = r.Uri.Substring (1); } else if (xmlResolver != null) { // TODO: test but doc says that Resolver = null -> no access try { // no way to know if valid without throwing an exception Uri uri = new Uri (r.Uri); s = (Stream) xmlResolver.GetEntity (uri, null, typeof (Stream)); } catch { // may still be a local file (and maybe not xml) s = File.OpenRead (r.Uri); } } if (objectName != null) { XmlElement found = null; foreach (DataObject obj in m_signature.ObjectList) { if (obj.Id == objectName) { found = obj.GetXml (); found.SetAttribute ("xmlns", SignedXml.XmlDsigNamespaceUrl); doc.AppendChild (doc.ImportNode (found, true)); // FIXME: there should be theoretical justification of copying namespace declaration nodes this way. foreach (XmlNode n in found.ChildNodes) // Do not copy default namespace as it must be xmldsig namespace for "Object" element. if (n.NodeType == XmlNodeType.Element) FixupNamespaceNodes (n as XmlElement, doc.DocumentElement, true); break; } } if (found == null && envdoc != null) { found = GetIdElement (envdoc, objectName); if (found != null) { doc.AppendChild (doc.ImportNode (found, true)); FixupNamespaceNodes (found, doc.DocumentElement, false); } } if (found == null) throw new CryptographicException (String.Format ("Malformed reference object: {0}", objectName)); } } if (r.TransformChain.Count > 0) { foreach (Transform t in r.TransformChain) { if (s == null) { s = ApplyTransform (t, doc); } else { t.LoadInput (s); object o = t.GetOutput (); if (o is Stream) s = (Stream) o; else s = CanonicalizeOutput (o); } } } else if (s == null) { // we must not C14N references from outside the document // e.g. non-xml documents if (r.Uri [0] != '#') { s = new MemoryStream (); doc.Save (s); } else { // apply default C14N transformation s = ApplyTransform (new XmlDsigC14NTransform (), doc); } } HashAlgorithm digest = GetHash (r.DigestMethod, check_hmac); return (digest == null) ? null : digest.ComputeHash (s); } private void DigestReferences () { // we must tell each reference which hash algorithm to use // before asking for the SignedInfo XML ! foreach (Reference r in m_signature.SignedInfo.References) { // assume SHA-1 if nothing is specified if (r.DigestMethod == null) r.DigestMethod = XmlDsigSHA1Url; r.DigestValue = GetReferenceHash (r, false); } } private Transform GetC14NMethod () { Transform t = null; if (m_signature.SignedInfo.CanonicalizationMethod.Contains ("http://www.w3.org/2001/10/xml-exc-c14n#")) { t = new XmlDsigExcC14NTransform (); } if (t == null) t = (Transform) CryptoConfig.CreateFromName (m_signature.SignedInfo.CanonicalizationMethod); if (t == null) throw new CryptographicException ("Unknown Canonicalization Method {0}", m_signature.SignedInfo.CanonicalizationMethod); return t; } private Stream SignedInfoTransformed () { Transform t = GetC14NMethod (); if (signatureElement == null) { // when creating signatures XmlDocument doc = new XmlDocument (); doc.PreserveWhitespace = true; doc.LoadXml (m_signature.SignedInfo.GetXml ().OuterXml); if (envdoc != null) foreach (XmlAttribute attr in envdoc.DocumentElement.SelectNodes ("namespace::*")) { if (attr.LocalName == "xml") continue; if (attr.Prefix == doc.DocumentElement.Prefix) continue; doc.DocumentElement.SetAttributeNode (doc.ImportNode (attr, true) as XmlAttribute); } t.LoadInput (doc); } else { // when verifying signatures // TODO - check m_signature.SignedInfo.Id XmlElement el = signatureElement.GetElementsByTagName (XmlSignature.ElementNames.SignedInfo, XmlSignature.NamespaceURI) [0] as XmlElement; StringWriter sw = new StringWriter (); XmlTextWriter xtw = new XmlTextWriter (sw); xtw.WriteStartElement (el.Prefix, el.LocalName, el.NamespaceURI); // context namespace nodes (except for "xmlns:xml") XmlNodeList nl = el.SelectNodes ("namespace::*"); foreach (XmlAttribute attr in nl) { if (attr.ParentNode == el) continue; if (attr.LocalName == "xml") continue; if (attr.Prefix == el.Prefix) continue; attr.WriteTo (xtw); } foreach (XmlNode attr in el.Attributes) attr.WriteTo (xtw); foreach (XmlNode n in el.ChildNodes) n.WriteTo (xtw); xtw.WriteEndElement (); byte [] si = Encoding.UTF8.GetBytes (sw.ToString ()); MemoryStream ms = new MemoryStream (); ms.Write (si, 0, si.Length); ms.Position = 0; t.LoadInput (ms); } // C14N and C14NWithComments always return a Stream in GetOutput return (Stream) t.GetOutput (); } // reuse hash - most document will always use the same hash private HashAlgorithm GetHash (string algorithm, bool check_hmac) { HashAlgorithm hash = (HashAlgorithm) hashes [algorithm]; if (hash == null) { hash = HashAlgorithm.Create (algorithm); if (hash == null) throw new CryptographicException ("Unknown hash algorithm: {0}", algorithm); hashes.Add (algorithm, hash); // now ready to be used } else { // important before reusing an hash object hash.Initialize (); } // we can sign using any hash algorith, including HMAC, but we can only verify hash (MS compatibility) if (check_hmac && (hash is KeyedHashAlgorithm)) return null; return hash; } public bool CheckSignature () { return (CheckSignatureInternal (null) != null); } private bool CheckReferenceIntegrity (ArrayList referenceList) { if (referenceList == null) return false; // check digest (hash) for every reference foreach (Reference r in referenceList) { // stop at first broken reference byte[] hash = GetReferenceHash (r, true); if (! Compare (r.DigestValue, hash)) return false; } return true; } public bool CheckSignature (AsymmetricAlgorithm key) { if (key == null) throw new ArgumentNullException ("key"); return (CheckSignatureInternal (key) != null); } private AsymmetricAlgorithm CheckSignatureInternal (AsymmetricAlgorithm key) { pkEnumerator = null; if (key != null) { // check with supplied key if (!CheckSignatureWithKey (key)) return null; } else { if (Signature.KeyInfo == null) return null; // no supplied key, iterates all KeyInfo while ((key = GetPublicKey ()) != null) { if (CheckSignatureWithKey (key)) { break; } } pkEnumerator = null; if (key == null) return null; } // some parts may need to be downloaded // so where doing it last // if (!CheckReferenceIntegrity (m_signature.SignedInfo.References)) // return null; if (manifests != null) { // do not use foreach as a manifest could contain manifests... for (int i=0; i < manifests.Count; i++) { Manifest manifest = new Manifest ((manifests [i] as XmlDocument).DocumentElement); if (! CheckReferenceIntegrity (manifest.References)) return null; } } return key; } // Is the signature (over SignedInfo) valid ? private bool CheckSignatureWithKey (AsymmetricAlgorithm key) { if (key == null) return false; SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod); if (sd == null) return false; AsymmetricSignatureDeformatter verifier = (AsymmetricSignatureDeformatter) CryptoConfig.CreateFromName (sd.DeformatterAlgorithm); if (verifier == null) return false; try { verifier.SetKey (key); verifier.SetHashAlgorithm (sd.DigestAlgorithm); HashAlgorithm hash = GetHash (sd.DigestAlgorithm, true); // get the hash of the C14N SignedInfo element MemoryStream ms = (MemoryStream) SignedInfoTransformed (); byte[] digest = hash.ComputeHash (ms); return verifier.VerifySignature (digest, m_signature.SignatureValue); } catch { // e.g. SignatureMethod != AsymmetricAlgorithm type return false; } } private bool Compare (byte[] expected, byte[] actual) { bool result = ((expected != null) && (actual != null)); if (result) { int l = expected.Length; result = (l == actual.Length); if (result) { for (int i=0; i < l; i++) { if (expected[i] != actual[i]) return false; } } } return result; } public bool CheckSignature (KeyedHashAlgorithm macAlg) { if (macAlg == null) throw new ArgumentNullException ("macAlg"); pkEnumerator = null; // Is the signature (over SignedInfo) valid ? Stream s = SignedInfoTransformed (); if (s == null) return false; byte[] actual = macAlg.ComputeHash (s); // HMAC signature may be partial and specified by <HMACOutputLength> if (m_signature.SignedInfo.SignatureLength != null) { int length = Int32.Parse (m_signature.SignedInfo.SignatureLength); // we only support signatures with a multiple of 8 bits // and the value must match the signature length if ((length & 7) != 0) throw new CryptographicException ("Signature length must be a multiple of 8 bits."); // SignatureLength is in bits (and we works on bytes, only in multiple of 8 bits) // and both values must match for a signature to be valid length >>= 3; if (length != m_signature.SignatureValue.Length) throw new CryptographicException ("Invalid signature length."); // is the length "big" enough to make the signature meaningful ? // we use a minimum of 80 bits (10 bytes) or half the HMAC normal output length // e.g. HMACMD5 output 128 bits but our minimum is 80 bits (not 64 bits) int minimum = Math.Max (10, actual.Length / 2); if (length < minimum) throw new CryptographicException ("HMAC signature is too small"); if (length < actual.Length) { byte[] trunked = new byte [length]; Buffer.BlockCopy (actual, 0, trunked, 0, length); actual = trunked; } } if (Compare (m_signature.SignatureValue, actual)) { // some parts may need to be downloaded // so where doing it last return CheckReferenceIntegrity (m_signature.SignedInfo.References); } return false; } [MonoTODO] [ComVisible (false)] public bool CheckSignature (X509Certificate2 certificate, bool verifySignatureOnly) { throw new NotImplementedException (); } public bool CheckSignatureReturningKey (out AsymmetricAlgorithm signingKey) { signingKey = CheckSignatureInternal (null); return (signingKey != null); } public void ComputeSignature () { if (key != null) { if (m_signature.SignedInfo.SignatureMethod == null) // required before hashing m_signature.SignedInfo.SignatureMethod = key.SignatureAlgorithm; else if (m_signature.SignedInfo.SignatureMethod != key.SignatureAlgorithm) throw new CryptographicException ("Specified SignatureAlgorithm is not supported by the signing key."); DigestReferences (); AsymmetricSignatureFormatter signer = null; // in need for a CryptoConfig factory if (key is DSA) signer = new DSASignatureFormatter (key); else if (key is RSA) signer = new RSAPKCS1SignatureFormatter (key); if (signer != null) { SignatureDescription sd = (SignatureDescription) CryptoConfig.CreateFromName (m_signature.SignedInfo.SignatureMethod); HashAlgorithm hash = GetHash (sd.DigestAlgorithm, false); // get the hash of the C14N SignedInfo element byte[] digest = hash.ComputeHash (SignedInfoTransformed ()); signer.SetHashAlgorithm ("SHA1"); m_signature.SignatureValue = signer.CreateSignature (digest); } } else throw new CryptographicException ("signing key is not specified"); } public void ComputeSignature (KeyedHashAlgorithm macAlg) { if (macAlg == null) throw new ArgumentNullException ("macAlg"); string method = null; if (macAlg is HMACSHA1) { method = XmlDsigHMACSHA1Url; } else if (macAlg is HMACSHA256) { method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256"; } else if (macAlg is HMACSHA384) { method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha384"; } else if (macAlg is HMACSHA512) { method = "http://www.w3.org/2001/04/xmldsig-more#hmac-sha512"; } else if (macAlg is HMACRIPEMD160) { method = "http://www.w3.org/2001/04/xmldsig-more#hmac-ripemd160"; } if (method == null) throw new CryptographicException ("unsupported algorithm"); DigestReferences (); m_signature.SignedInfo.SignatureMethod = method; m_signature.SignatureValue = macAlg.ComputeHash (SignedInfoTransformed ()); } public virtual XmlElement GetIdElement (XmlDocument document, string idValue) { if ((document == null) || (idValue == null)) return null; // this works only if there's a DTD or XSD available to define the ID XmlElement xel = document.GetElementById (idValue); if (xel == null) { // search an "undefined" ID xel = (XmlElement) document.SelectSingleNode ("//*[@Id='" + idValue + "']"); } return xel; } // According to book ".NET Framework Security" this method // iterates all possible keys then return null protected virtual AsymmetricAlgorithm GetPublicKey () { if (m_signature.KeyInfo == null) return null; if (pkEnumerator == null) { pkEnumerator = m_signature.KeyInfo.GetEnumerator (); } #if SECURITY_DEP if (_x509Enumerator != null) { if (_x509Enumerator.MoveNext ()) { X509Certificate cert = (X509Certificate) _x509Enumerator.Current; return new X509Certificate2 (cert.GetRawCertData ()).PublicKey.Key; } else { _x509Enumerator = null; } } #endif while (pkEnumerator.MoveNext ()) { AsymmetricAlgorithm key = null; KeyInfoClause kic = (KeyInfoClause) pkEnumerator.Current; if (kic is DSAKeyValue) key = DSA.Create (); else if (kic is RSAKeyValue) key = RSA.Create (); if (key != null) { key.FromXmlString (kic.GetXml ().InnerXml); return key; } #if SECURITY_DEP if (kic is KeyInfoX509Data) { _x509Enumerator = ((KeyInfoX509Data) kic).Certificates.GetEnumerator (); if (_x509Enumerator.MoveNext ()) { X509Certificate cert = (X509Certificate) _x509Enumerator.Current; return new X509Certificate2 (cert.GetRawCertData ()).PublicKey.Key; } } #endif } return null; } public XmlElement GetXml () { return m_signature.GetXml (envdoc); } public void LoadXml (XmlElement value) { if (value == null) throw new ArgumentNullException ("value"); signatureElement = value; m_signature.LoadXml (value); // Need to give the EncryptedXml object to the // XmlDecryptionTransform to give it a fighting // chance at decrypting the document. foreach (Reference r in m_signature.SignedInfo.References) { foreach (Transform t in r.TransformChain) { if (t is XmlDecryptionTransform) ((XmlDecryptionTransform) t).EncryptedXml = EncryptedXml; } } } [ComVisible (false)] public XmlResolver Resolver { set { xmlResolver = value; } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests { using System; using System.Collections.ObjectModel; using System.IO; using System.Management.Automation; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Management.ServiceManagement.Model; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.ConfigDataInfo; using Microsoft.WindowsAzure.Management.ServiceManagement.Test.Properties; using Microsoft.WindowsAzure.ServiceManagement; [TestClass] public class FunctionalTest : ServiceManagementTest { bool createOwnService = false; private static string defaultService; private static string defaultVm; private const string vhdBlob = "vhdstore/os.vhd"; private string vhdName = "os.vhd"; private string serviceName; private string vmName; protected static string vhdBlobLocation; [ClassInitialize] public static void ClassInit(TestContext context) { SetTestSettings(); if (defaultAzureSubscription.Equals(null)) { Assert.Inconclusive("No Subscription is selected!"); } do { defaultService = Utilities.GetUniqueShortName(serviceNamePrefix); } while (vmPowershellCmdlets.TestAzureServiceName(defaultService)); defaultVm = Utilities.GetUniqueShortName(vmNamePrefix); Assert.IsNull(vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService)); vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, defaultVm, defaultService, imageName, username, password, locationName); Console.WriteLine("Service Name: {0} is created.", defaultService); vhdBlobLocation = blobUrlRoot + vhdBlob; try { vmPowershellCmdlets.AddAzureVhd(new FileInfo(localFile), vhdBlobLocation); } catch (Exception e) { if (e.ToString().Contains("already exists")) { // Use the already uploaded vhd. Console.WriteLine("Using already uploaded blob.."); } else { throw; } } } [TestInitialize] public void Initialize() { pass = false; testStartTime = DateTime.Now; } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureStorageAccount)")] [Ignore] public void ScriptTestSample() { var result = vmPowershellCmdlets.RunPSScript("Get-Help Save-AzureVhd -full"); } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove)-AzureAffinityGroup)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\affinityGroupData.csv", "affinityGroupData#csv", DataAccessMethod.Sequential)] [Ignore] public void AzureAffinityGroupTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string affinityName1 = Convert.ToString(TestContext.DataRow["affinityName1"]); string affinityLabel1 = Convert.ToString(TestContext.DataRow["affinityLabel1"]); string location1 = Convert.ToString(TestContext.DataRow["location1"]); string description1 = Convert.ToString(TestContext.DataRow["description1"]); string affinityName2 = Convert.ToString(TestContext.DataRow["affinityName2"]); string affinityLabel2 = Convert.ToString(TestContext.DataRow["affinityLabel2"]); string location2 = Convert.ToString(TestContext.DataRow["location2"]); string description2 = Convert.ToString(TestContext.DataRow["description2"]); try { ServiceManagementCmdletTestHelper vmPowershellCmdlets = new ServiceManagementCmdletTestHelper(); // Remove previously created affinity groups foreach (var aff in vmPowershellCmdlets.GetAzureAffinityGroup(null)) { if (aff.Name == affinityName1 || aff.Name == affinityName2) { vmPowershellCmdlets.RemoveAzureAffinityGroup(aff.Name); } } // New-AzureAffinityGroup vmPowershellCmdlets.NewAzureAffinityGroup(affinityName1, location1, affinityLabel1, description1); vmPowershellCmdlets.NewAzureAffinityGroup(affinityName2, location2, affinityLabel2, description2); Console.WriteLine("Affinity groups created: {0}, {1}", affinityName1, affinityName2); // Get-AzureAffinityGroup pass = AffinityGroupVerify(vmPowershellCmdlets.GetAzureAffinityGroup(affinityName1)[0], affinityName1, affinityLabel1, location1, description1); pass &= AffinityGroupVerify(vmPowershellCmdlets.GetAzureAffinityGroup(affinityName2)[0], affinityName2, affinityLabel2, location2, description2); // Set-AzureAffinityGroup vmPowershellCmdlets.SetAzureAffinityGroup(affinityName2, affinityLabel1, description1); Console.WriteLine("update affinity group: {0}", affinityName2); pass &= AffinityGroupVerify(vmPowershellCmdlets.GetAzureAffinityGroup(affinityName2)[0], affinityName2, affinityLabel1, location2, description1); // Remove-AzureAffinityGroup vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityName2); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityName2); vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityName1); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityName1); } catch (Exception e) { pass = false; Assert.Fail(e.ToString()); } } private bool AffinityGroupVerify(AffinityGroupContext affContext, string name, string label, string location, string description) { bool result = true; Console.WriteLine("AffinityGroup: Name - {0}, Location - {1}, Label - {2}, Description - {3}", affContext.Name, affContext.Location, affContext.Label, affContext.Description); try { Assert.AreEqual(affContext.Name, name, "Error: Affinity Name is not equal!"); Assert.AreEqual(affContext.Label, label, "Error: Affinity Label is not equal!"); Assert.AreEqual(affContext.Location, location, "Error: Affinity Location is not equal!"); Assert.AreEqual(affContext.Description, description, "Error: Affinity Description is not equal!"); } catch (Exception e) { Console.WriteLine(e.ToString()); result = false; } return result; } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Remove)-AzureCertificate)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\certificateData.csv", "certificateData#csv", DataAccessMethod.Sequential)] [Ignore] public void AzureCertificateTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Certificate files to test string cerFileName = Convert.ToString(TestContext.DataRow["cerFileName"]); string pfxFileName = Convert.ToString(TestContext.DataRow["pfxFileName"]); string password = Convert.ToString(TestContext.DataRow["password"]); string thumbprintAlgorithm = Convert.ToString(TestContext.DataRow["algorithm"]); // Install the .cer file to local machine. StoreLocation certStoreLocation = StoreLocation.CurrentUser; StoreName certStoreName = StoreName.My; X509Certificate2 installedCert = InstallCert(cerFileName, certStoreLocation, certStoreName); // Certificate1: get it from the installed certificate. PSObject cert1 = vmPowershellCmdlets.RunPSScript( String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0]; string cert1data = Convert.ToBase64String(((X509Certificate2)cert1.BaseObject).RawData); // Certificate2: get it from .pfx file. X509Certificate2Collection cert2 = new X509Certificate2Collection(); cert2.Import(pfxFileName, password, X509KeyStorageFlags.PersistKeySet); string cert2data = Convert.ToBase64String(cert2[0].RawData); // Certificate3: get it from .cer file. X509Certificate2Collection cert3 = new X509Certificate2Collection(); cert3.Import(cerFileName); string cert3data = Convert.ToBase64String(cert3[0].RawData); try { RemoveAllExistingCerts(defaultService); // Add a cert item vmPowershellCmdlets.AddAzureCertificate(defaultService, cert1); CertificateContext getCert1 = vmPowershellCmdlets.GetAzureCertificate(defaultService)[0]; Console.WriteLine("Cert is added: {0}", getCert1.Thumbprint); Assert.AreEqual(getCert1.Data, cert1data, "Cert is different!!"); vmPowershellCmdlets.RemoveAzureCertificate(defaultService, getCert1.Thumbprint, thumbprintAlgorithm); pass = Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, getCert1.Thumbprint, thumbprintAlgorithm); // Add .pfx file vmPowershellCmdlets.AddAzureCertificate(defaultService, pfxFileName, password); CertificateContext getCert2 = vmPowershellCmdlets.GetAzureCertificate(defaultService, cert2[0].Thumbprint, thumbprintAlgorithm)[0]; Console.WriteLine("Cert is added: {0}", cert2[0].Thumbprint); Assert.AreEqual(getCert2.Data, cert2data, "Cert is different!!"); vmPowershellCmdlets.RemoveAzureCertificate(defaultService, cert2[0].Thumbprint, thumbprintAlgorithm); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, cert2[0].Thumbprint, thumbprintAlgorithm); // Add .cer file vmPowershellCmdlets.AddAzureCertificate(defaultService, cerFileName); CertificateContext getCert3 = vmPowershellCmdlets.GetAzureCertificate(defaultService, cert3[0].Thumbprint, thumbprintAlgorithm)[0]; Console.WriteLine("Cert is added: {0}", cert3[0].Thumbprint); Assert.AreEqual(getCert3.Data, cert3data, "Cert is different!!"); vmPowershellCmdlets.RemoveAzureCertificate(defaultService, cert3[0].Thumbprint, thumbprintAlgorithm); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureCertificate, defaultService, cert3[0].Thumbprint, thumbprintAlgorithm); } catch (Exception e) { pass = false; Assert.Fail(e.ToString()); } finally { UninstallCert(installedCert, certStoreLocation, certStoreName); RemoveAllExistingCerts(defaultService); } } private void RemoveAllExistingCerts(string serviceName) { vmPowershellCmdlets.RunPSScript(String.Format("{0} -ServiceName {1} | {2}", Utilities.GetAzureCertificateCmdletName, serviceName, Utilities.RemoveAzureCertificateCmdletName)); } private X509Certificate2 InstallCert(string certFile, StoreLocation location, StoreName name) { X509Certificate2 cert = new X509Certificate2(certFile); X509Store certStore = new X509Store(name, location); certStore.Open(OpenFlags.ReadWrite); certStore.Add(cert); certStore.Close(); Console.WriteLine("Cert, {0}, is installed.", cert.Thumbprint); return cert; } private void UninstallCert(X509Certificate2 cert, StoreLocation location, StoreName name) { try { X509Store certStore = new X509Store(name, location); certStore.Open(OpenFlags.ReadWrite); certStore.Remove(cert); certStore.Close(); Console.WriteLine("Cert, {0}, is uninstalled.", cert.Thumbprint); } catch (Exception e) { Console.WriteLine("Error during uninstalling the cert: {0}", e.ToString()); throw; } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (New-AzureCertificateSetting)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\certificateData.csv", "certificateData#csv", DataAccessMethod.Sequential)] [Ignore] public void AzureCertificateSettingTest() { createOwnService = true; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Install the .cer file to local machine. string cerFileName = Convert.ToString(TestContext.DataRow["cerFileName"]); StoreLocation certStoreLocation = StoreLocation.CurrentUser; StoreName certStoreName = StoreName.My; X509Certificate2 installedCert = InstallCert(cerFileName, certStoreLocation, certStoreName); PSObject certToUpload = vmPowershellCmdlets.RunPSScript( String.Format("Get-Item cert:\\{0}\\{1}\\{2}", certStoreLocation.ToString(), certStoreName.ToString(), installedCert.Thumbprint))[0]; try { vmName = Utilities.GetUniqueShortName(vmNamePrefix); serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, locationName); vmPowershellCmdlets.AddAzureCertificate(serviceName, certToUpload); CertificateSettingList certList = new CertificateSettingList(); certList.Add(vmPowershellCmdlets.NewAzureCertificateSetting(certStoreName.ToString(), installedCert.Thumbprint)); AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, InstanceSize.Small, imageName); AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, certList, username, password); PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm }); PersistentVMRoleContext result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Console.WriteLine("{0} is created", result.Name); pass = true; } catch (Exception e) { pass = false; Assert.Fail(e.ToString()); } finally { UninstallCert(installedCert, certStoreLocation, certStoreName); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureDataDisk)")] [Ignore] public void AzureDataDiskTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string diskLabel1 = "disk1"; int diskSize1 = 30; int lunSlot1 = 0; string diskLabel2 = "disk2"; int diskSize2 = 50; int lunSlot2 = 2; try { AddAzureDataDiskConfig dataDiskInfo1 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize1, diskLabel1, lunSlot1); AddAzureDataDiskConfig dataDiskInfo2 = new AddAzureDataDiskConfig(DiskCreateOption.CreateNew, diskSize2, diskLabel2, lunSlot2); vmPowershellCmdlets.AddDataDisk(defaultVm, defaultService, new [] {dataDiskInfo1, dataDiskInfo2}); // Add-AzureEndpoint with Get-AzureVM and Update-AzureVm Assert.IsTrue(CheckDataDisk(defaultVm, defaultService, dataDiskInfo1, HostCaching.None), "Data disk is not properly added"); Console.WriteLine("Data disk added correctly."); Assert.IsTrue(CheckDataDisk(defaultVm, defaultService, dataDiskInfo2, HostCaching.None), "Data disk is not properly added"); Console.WriteLine("Data disk added correctly."); vmPowershellCmdlets.SetDataDisk(defaultVm, defaultService, HostCaching.ReadOnly, lunSlot1); Assert.IsTrue(CheckDataDisk(defaultVm, defaultService, dataDiskInfo1, HostCaching.ReadOnly), "Data disk is not properly changed"); Console.WriteLine("Data disk is changed correctly."); pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } finally { // Remove DataDisks created foreach (DataVirtualHardDisk disk in vmPowershellCmdlets.GetAzureDataDisk(defaultVm, defaultService)) { vmPowershellCmdlets.RemoveDataDisk(defaultVm, defaultService, new[] { disk.Lun }); // Remove-AzureDataDisk RemoveDisk(disk.DiskName, 10); } Assert.AreEqual(0, vmPowershellCmdlets.GetAzureDataDisk(defaultVm, defaultService).Count, "DataDisk is not removed."); } } private void RemoveDisk(string diskName, int maxTry) { for (int i = 0; i < maxTry ; i++) { try { vmPowershellCmdlets.RemoveAzureDisk(diskName, true); break; } catch (Exception e) { if (i == maxTry) { Console.WriteLine("Max try reached. Couldn't delete the Virtual disk"); } if (e.ToString().Contains("currently in use")) { Thread.Sleep(5000); continue; } } } } private bool CheckDataDisk(string vmName, string serviceName, AddAzureDataDiskConfig dataDiskInfo, HostCaching hc) { bool found = false; foreach (DataVirtualHardDisk disk in vmPowershellCmdlets.GetAzureDataDisk(vmName, serviceName)) { Console.WriteLine("DataDisk - Name:{0}, Label:{1}, Size:{2}, LUN:{3}, HostCaching: {4}", disk.DiskName, disk.DiskLabel, disk.LogicalDiskSizeInGB, disk.Lun, disk.HostCaching); if (disk.DiskLabel == dataDiskInfo.DiskLabel && disk.LogicalDiskSizeInGB == dataDiskInfo.DiskSizeGB && disk.Lun == dataDiskInfo.LunSlot) { if (disk.HostCaching == hc.ToString()) { found = true; Console.WriteLine("DataDisk found: {0}", disk.DiskLabel); } } } return found; } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Update,Remove)-AzureDisk)")] [Ignore] public void AzureDiskTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string mediaLocation = String.Format("{0}vhdstore/{1}", blobUrlRoot, vhdName); try { vmPowershellCmdlets.AddAzureDisk(vhdName, mediaLocation, vhdName, null); bool found = false; foreach (DiskContext disk in vmPowershellCmdlets.GetAzureDisk(vhdName)) { Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk.DiskName, disk.Label, disk.DiskSizeInGB); if (disk.DiskName == vhdName && disk.Label == vhdName) { found = true; Console.WriteLine("{0} is found", disk.DiskName); } } Assert.IsTrue(found, "Error: Disk is not added"); string newLabel = "NewLabel"; vmPowershellCmdlets.UpdateAzureDisk(vhdName, newLabel); DiskContext disk2 = vmPowershellCmdlets.GetAzureDisk(vhdName)[0]; Console.WriteLine("Disk: Name - {0}, Label - {1}, Size - {2},", disk2.DiskName, disk2.Label, disk2.DiskSizeInGB); Assert.AreEqual(newLabel, disk2.Label); Console.WriteLine("Disk Label is successfully updated"); vmPowershellCmdlets.RemoveAzureDisk(vhdName, false); Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDisk, vhdName), "The disk was not removed"); } catch (Exception e) { pass = false; if (e.ToString().Contains("ResourceNotFound")) { Console.WriteLine("Please upload {0} file to \\vhdtest\\ blob directory before running this test", vhdName); } Assert.Fail("Exception occurs: {0}", e.ToString()); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove,Move)-AzureDeployment)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)] [Ignore] public void AzureDeploymentTest() { createOwnService = true; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["packageName"]); string configName = Convert.ToString(TestContext.DataRow["configName"]); string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); string upgradeConfigName2 = Convert.ToString(TestContext.DataRow["upgradeConfig2"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); var packagePath2 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + upgradePackageName); var configPath2 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + upgradeConfigName); var configPath3 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + upgradeConfigName2); Assert.IsTrue(File.Exists(packagePath1.FullName), "file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(packagePath2.FullName), "file not exist={0}", packagePath2); Assert.IsTrue(File.Exists(configPath1.FullName), "file not exist={0}", configPath1); Assert.IsTrue(File.Exists(configPath2.FullName), "file not exist={0}", configPath2); Assert.IsTrue(File.Exists(configPath3.FullName), "file not exist={0}", configPath3); string deploymentName = "deployment1"; string deploymentLabel = "label1"; DeploymentInfoContext result; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); Console.WriteLine("service, {0}, is created.", serviceName); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, DeploymentSlotType.Staging, deploymentLabel, deploymentName, false, false); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Staging); pass = Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Staging, null, 1); Console.WriteLine("successfully deployed the package"); // Move the deployment from 'Staging' to 'Production' vmPowershellCmdlets.MoveAzureDeployment(serviceName); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 1); Console.WriteLine("successfully moved"); // Set the deployment status to 'Suspended' vmPowershellCmdlets.SetAzureDeploymentStatus(serviceName, DeploymentSlotType.Production, DeploymentStatus.Suspended); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, DeploymentStatus.Suspended, 1); Console.WriteLine("successfully changed the status"); // Update the deployment vmPowershellCmdlets.SetAzureDeploymentConfig(serviceName, DeploymentSlotType.Production, configPath2.FullName); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, deploymentLabel, DeploymentSlotType.Production, null, 2); Console.WriteLine("successfully updated the deployment"); // Upgrade the deployment DateTime start = DateTime.Now; vmPowershellCmdlets.SetAzureDeploymentUpgrade(serviceName, DeploymentSlotType.Production, UpgradeType.Simultaneous, packagePath2.FullName, configPath3.FullName); TimeSpan duration = DateTime.Now - start; Console.WriteLine("Auto upgrade took {0}.", duration); result = vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production); pass &= Utilities.PrintAndCompareDeployment(result, serviceName, deploymentName, serviceName, DeploymentSlotType.Production, null, 4); Console.WriteLine("successfully updated the deployment"); vmPowershellCmdlets.RemoveAzureDeployment(serviceName, DeploymentSlotType.Production, true); pass &= Utilities.CheckRemove(vmPowershellCmdlets.GetAzureDeployment, serviceName, DeploymentSlotType.Production); } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } finally { } } /// <summary> /// /// </summary> [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get)-AzureDns)")] [Ignore] public void AzureDnsTest() { createOwnService = true; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string dnsName = "OpenDns1"; string ipAddress = "208.67.222.222"; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, locationName); DnsServer dns = vmPowershellCmdlets.NewAzureDns(dnsName, ipAddress); AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, InstanceSize.ExtraSmall, imageName); AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); vmPowershellCmdlets.NewAzureVM(serviceName, new []{vm}, null, new[]{dns}, null, null, null, null, null, null); DnsServerList dnsList = vmPowershellCmdlets.GetAzureDns(vmPowershellCmdlets.GetAzureDeployment(serviceName, DeploymentSlotType.Production).DnsSettings); foreach (DnsServer dnsServer in dnsList) { Console.WriteLine("DNS Server Name: {0}, DNS Server Address: {1}", dnsServer.Name, dnsServer.Address); Assert.AreEqual(dnsServer.Name, dns.Name); Assert.AreEqual(dnsServer.Address, dns.Address); } pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureEndpoint)")] [Ignore] public void AzureEndpointTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string ep1Name = "tcp1"; int ep1LocalPort = 60010; int ep1PublicPort = 60011; string ep1LBSetName = "lbset1"; int ep1ProbePort = 60012; string ep1ProbePath = string.Empty; int? ep1ProbeInterval = 7; int? ep1ProbeTimeout = null; string ep2Name = "tcp2"; int ep2LocalPort = 60020; int ep2PublicPort = 60021; int ep2LocalPortChanged = 60030; int ep2PublicPortChanged = 60031; string ep2LBSetName = "lbset2"; int ep2ProbePort = 60022; string ep2ProbePath = string.Empty; int? ep2ProbeInterval = null; int? ep2ProbeTimeout = 32; AzureEndPointConfigInfo ep1Info = new AzureEndPointConfigInfo( ProtocolInfo.tcp, ep1LocalPort, ep1PublicPort, ep1Name, ep1LBSetName, ep1ProbePort, ProtocolInfo.tcp, ep1ProbePath, ep1ProbeInterval, ep1ProbeTimeout); AzureEndPointConfigInfo ep2Info = new AzureEndPointConfigInfo( ProtocolInfo.tcp, ep2LocalPort, ep2PublicPort, ep2Name, ep2LBSetName, ep2ProbePort, ProtocolInfo.tcp, ep2ProbePath, ep2ProbeInterval, ep2ProbeTimeout); try { foreach (AzureEndPointConfigInfo.ParameterSet p in Enum.GetValues(typeof(AzureEndPointConfigInfo.ParameterSet))) { string pSetName = Enum.GetName(typeof(AzureEndPointConfigInfo.ParameterSet), p); Console.WriteLine("--Begin Endpoint Test with '{0}' parameter set.", pSetName); ep1Info.ParamSet = p; ep2Info.ParamSet = p; ep2Info.EndpointLocalPort = ep2LocalPort; ep2Info.EndpointPublicPort = ep2PublicPort; // Add two new endpoints Console.WriteLine("-----Add 2 new endpoints."); vmPowershellCmdlets.AddEndPoint(defaultVm, defaultService, new[] { ep1Info, ep2Info }); // Add-AzureEndpoint with Get-AzureVM and Update-AzureVm CheckEndpoint(defaultVm, defaultService, new[] { ep1Info, ep2Info }); // Change the endpoint Console.WriteLine("-----Change the second endpoint."); ep2Info.EndpointLocalPort = ep2LocalPortChanged; ep2Info.EndpointPublicPort = ep2PublicPortChanged; vmPowershellCmdlets.SetEndPoint(defaultVm, defaultService, ep2Info); // Set-AzureEndpoint with Get-AzureVM and Update-AzureVm CheckEndpoint(defaultVm, defaultService, new[] { ep2Info }); // Remove Endpoint Console.WriteLine("-----Remove endpoints."); vmPowershellCmdlets.RemoveEndPoint(defaultVm, defaultService, new[] { ep1Name, ep2Name }); // Remove-AzureEndpoint CheckEndpointRemoved(defaultVm, defaultService, new[] { ep1Info, ep2Info }); Console.WriteLine("Endpoint Test passed with '{0}' parameter set.", pSetName); } pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } private bool CheckEndpoint(string vmName, string serviceName, AzureEndPointConfigInfo [] epInfos) { var serverEndpoints = vmPowershellCmdlets.GetAzureEndPoint(vmPowershellCmdlets.GetAzureVM(vmName, serviceName)); // List the endpoints found for debugging. Console.WriteLine("***** Checking for Endpoints **************************************************"); Console.WriteLine("***** Listing Returned Endpoints"); foreach (InputEndpointContext ep in serverEndpoints) { Console.WriteLine("Endpoint - Name:{0} Protocol:{1} Port:{2} LocalPort:{3} Vip:{4}", ep.Name, ep.Protocol, ep.Port, ep.LocalPort, ep.Vip); if (!string.IsNullOrEmpty(ep.LBSetName)) { Console.WriteLine("\t- LBSetName:{0}", ep.LBSetName); Console.WriteLine("\t- Probe - Port:{0} Protocol:{1} Interval:{2} Timeout:{3}", ep.ProbePort, ep.ProbeProtocol, ep.ProbeIntervalInSeconds, ep.ProbeTimeoutInSeconds); } } Console.WriteLine("*******************************************************************************"); // Check if the specified endpoints were found. foreach (AzureEndPointConfigInfo epInfo in epInfos) { bool found = false; foreach (InputEndpointContext ep in serverEndpoints) { if (epInfo.CheckInputEndpointContext(ep)) { found = true; Console.WriteLine("Endpoint found: {0}", epInfo.EndpointName); } } Assert.IsTrue(found, string.Format("Error: Endpoint '{0}' was not found!", epInfo.EndpointName)); } return true; } private bool CheckEndpointRemoved(string vmName, string serviceName, AzureEndPointConfigInfo[] epInfos) { var serverEndpoints = vmPowershellCmdlets.GetAzureEndPoint(vmPowershellCmdlets.GetAzureVM(vmName, serviceName)); // List the endpoints found for debugging. Console.WriteLine("***** Checking for Removed Endpoints ******************************************"); Console.WriteLine("***** Listing Returned Endpoints"); foreach (InputEndpointContext ep in serverEndpoints) { Console.WriteLine("Endpoint - Name:{0} Protocol:{1} Port:{2} LocalPort:{3} Vip:{4}", ep.Name, ep.Protocol, ep.Port, ep.LocalPort, ep.Vip); if (!string.IsNullOrEmpty(ep.LBSetName)) { Console.WriteLine("\t- LBSetName:{0}", ep.LBSetName); Console.WriteLine("\t- Probe - Port:{0} Protocol:{1} Interval:{2} Timeout:{3}", ep.ProbePort, ep.ProbeProtocol, ep.ProbeIntervalInSeconds, ep.ProbeTimeoutInSeconds); } } Console.WriteLine("*******************************************************************************"); // Check if the specified endpoints were found. foreach (AzureEndPointConfigInfo epInfo in epInfos) { bool found = false; foreach (InputEndpointContext ep in serverEndpoints) { if (epInfo.CheckInputEndpointContext(ep)) { found = true; Console.WriteLine("Endpoint found: {0}", epInfo.EndpointName); } } Assert.IsFalse(found, string.Format("Error: Endpoint '{0}' was found!", epInfo.EndpointName)); } return true; } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet Set-AzureAvailabilitySet)")] [Ignore] public void AzureAvailabilitySetTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string testAVSetName = "testAVSet1"; try { var vm = vmPowershellCmdlets.SetAzureAvailabilitySet(defaultVm, defaultService, testAVSetName); vmPowershellCmdlets.UpdateAzureVM(defaultVm, defaultService, vm); CheckAvailabilitySet(defaultVm, defaultService, testAVSetName); pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } private void CheckAvailabilitySet(string vmName, string serviceName, string availabilitySetName) { var vm = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Assert.IsTrue(vm.AvailabilitySetName.Equals(availabilitySetName, StringComparison.InvariantCultureIgnoreCase)); } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureLocation)")] [Ignore] public void AzureLocationTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); try { foreach (LocationsContext loc in vmPowershellCmdlets.GetAzureLocation()) { Console.WriteLine("Location: Name - {0}, DisplayName - {1}", loc.Name, loc.DisplayName); } pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureOSDisk)")] [Ignore] public void AzureOSDiskTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); try { PersistentVM vm = vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService).VM; OSVirtualHardDisk osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm); Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS); Assert.IsTrue(osdisk.Equals(vm.OSVirtualHardDisk), "OS disk returned is not the same!"); PersistentVM vm2 = vmPowershellCmdlets.SetAzureOSDisk(HostCaching.ReadOnly, vm); osdisk = vmPowershellCmdlets.GetAzureOSDisk(vm2); Console.WriteLine("OS Disk: Name - {0}, Label - {1}, HostCaching - {2}, OS - {3}", osdisk.DiskName, osdisk.DiskLabel, osdisk.HostCaching, osdisk.OS); Assert.IsTrue(osdisk.Equals(vm2.OSVirtualHardDisk), "OS disk returned is not the same!"); pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet (Get-AzureOSVersion)")] [Ignore] public void AzureOSVersionTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); try { foreach (OSVersionsContext osVersions in vmPowershellCmdlets.GetAzureOSVersion()) { Console.WriteLine("OS Version: Family - {0}, FamilyLabel - {1}, Version - {2}", osVersions.Family, osVersions.FamilyLabel, osVersions.Version); } pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "PAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureRole)")] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\package.csv", "package#csv", DataAccessMethod.Sequential)] [Ignore] public void AzureRoleTest() { createOwnService = true; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); // Choose the package and config files from local machine string packageName = Convert.ToString(TestContext.DataRow["packageName"]); string configName = Convert.ToString(TestContext.DataRow["configName"]); string upgradePackageName = Convert.ToString(TestContext.DataRow["upgradePackage"]); string upgradeConfigName = Convert.ToString(TestContext.DataRow["upgradeConfig"]); var packagePath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + packageName); var configPath1 = new FileInfo(Directory.GetCurrentDirectory() + "\\" + configName); Assert.IsTrue(File.Exists(packagePath1.FullName), "VHD file not exist={0}", packagePath1); Assert.IsTrue(File.Exists(configPath1.FullName), "VHD file not exist={0}", configPath1); string deploymentName = "deployment1"; string deploymentLabel = "label1"; string slot = DeploymentSlotType.Production; //DeploymentInfoContext result; string roleName = ""; try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); vmPowershellCmdlets.NewAzureDeployment(serviceName, packagePath1.FullName, configPath1.FullName, slot, deploymentLabel, deploymentName, false, false); foreach (RoleContext role in vmPowershellCmdlets.GetAzureRole(serviceName, slot, null, false)) { Console.WriteLine("Role: Name - {0}, ServiceName - {1}, DeploymenntID - {2}, InstanceCount - {3}", role.RoleName, role.ServiceName, role.DeploymentID, role.InstanceCount); Assert.AreEqual(serviceName, role.ServiceName); roleName = role.RoleName; } vmPowershellCmdlets.SetAzureRole(serviceName, slot, roleName, 2); foreach (RoleContext role in vmPowershellCmdlets.GetAzureRole(serviceName, slot, null, false)) { Console.WriteLine("Role: Name - {0}, ServiceName - {1}, DeploymenntID - {2}, InstanceCount - {3}", role.RoleName, role.ServiceName, role.DeploymentID, role.InstanceCount); Assert.AreEqual(serviceName, role.ServiceName); Assert.AreEqual(2, role.InstanceCount); } pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set)-AzureSubnet)")] [Ignore] public void AzureSubnetTest() { createOwnService = true; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); try { serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmPowershellCmdlets.NewAzureService(serviceName, serviceName, locationName); PersistentVM vm = vmPowershellCmdlets.NewAzureVMConfig(new AzureVMConfigInfo(vmName, InstanceSize.Small, imageName)); AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); azureProvisioningConfig.Vm = vm; string [] subs = new [] {"subnet1", "subnet2", "subnet3"}; vm = vmPowershellCmdlets.SetAzureSubnet(vmPowershellCmdlets.AddAzureProvisioningConfig(azureProvisioningConfig), subs); SubnetNamesCollection subnets = vmPowershellCmdlets.GetAzureSubnet(vm); foreach (string subnet in subnets) { Console.WriteLine("Subnet: {0}", subnet); } CollectionAssert.AreEqual(subnets, subs); pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get)-AzureStorageKey)")] [Ignore] public void AzureStorageKeyTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); try { StorageServiceKeyOperationContext key1 = vmPowershellCmdlets.GetAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccount); // Get-AzureStorageAccountKey Console.WriteLine("Primary - {0}", key1.Primary); Console.WriteLine("Secondary - {0}", key1.Secondary); StorageServiceKeyOperationContext key2 = vmPowershellCmdlets.NewAzureStorageAccountKey(defaultAzureSubscription.CurrentStorageAccount, KeyType.Secondary); Console.WriteLine("Primary - {0}", key2.Primary); Console.WriteLine("Secondary - {0}", key2.Secondary); Assert.AreEqual(key1.Primary, key2.Primary); Assert.AreNotEqual(key1.Secondary, key2.Secondary); pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((New,Get,Set,Remove)-AzureStorageAccount)")] [Ignore] [DataSource("Microsoft.VisualStudio.TestTools.DataSource.CSV", "|DataDirectory|\\Resources\\storageAccountTestData.csv", "storageAccountTestData#csv", DataAccessMethod.Sequential)] public void AzureStorageAccountTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string storageAccountPrefix = Convert.ToString(TestContext.DataRow["NamePrefix"]); string locationName1 = Convert.ToString(TestContext.DataRow["Location1"]); string locationName2 = Convert.ToString(TestContext.DataRow["Location2"]); string affinityGroupName = Convert.ToString(TestContext.DataRow["AffinityGroupName"]); string[] label = new string[3] { Convert.ToString(TestContext.DataRow["Label1"]), Convert.ToString(TestContext.DataRow["Label2"]), Convert.ToString(TestContext.DataRow["Label3"])}; string[] description = new string[3] { Convert.ToString(TestContext.DataRow["Description1"]), Convert.ToString(TestContext.DataRow["Description2"]), Convert.ToString(TestContext.DataRow["Description3"])}; bool?[] geoReplicationSettings = new bool?[3] { true, false, null }; bool geoReplicationEnabled = true; string[] storageName = new string[2] { Utilities.GetUniqueShortName(storageAccountPrefix), Utilities.GetUniqueShortName(storageAccountPrefix)}; string[][] storageStaticProperties = new string[2][] { new string[3] {storageName[0], locationName1, null}, new string [3] {storageName[1], null, affinityGroupName}}; try { // New-AzureStorageAccount test vmPowershellCmdlets.NewAzureStorageAccount(storageName[0], locationName1, null, null, null); Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[0])[0], storageStaticProperties[0], storageName[0], null, true)); Console.WriteLine("{0} is created", storageName[0]); if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityGroupName)) { vmPowershellCmdlets.NewAzureAffinityGroup(affinityGroupName, locationName2, label[0], description[0]); } vmPowershellCmdlets.NewAzureStorageAccount(storageName[1], null, affinityGroupName, null, null); Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[1])[0], storageStaticProperties[1], storageName[1], null, true)); Console.WriteLine("{0} is created", storageName[1]); // Set-AzureStorageAccount & Remove-AzureStorageAccount test for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { vmPowershellCmdlets.SetAzureStorageAccount(storageName[i], label[j], null, geoReplicationSettings[j]); if (geoReplicationSettings[j] != null) { geoReplicationEnabled = geoReplicationSettings[j].Value; } Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[i])[0], storageStaticProperties[i], label[j], null, geoReplicationEnabled)); } for (int j = 0; j < 3; j++) { vmPowershellCmdlets.SetAzureStorageAccount(storageName[i], null, description[j], geoReplicationSettings[j]); if (geoReplicationSettings[j] != null) { geoReplicationEnabled = geoReplicationSettings[j].Value; } Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[i])[0], storageStaticProperties[i], label[2], description[j], geoReplicationEnabled)); } for (int j = 0; j < 3; j++) { vmPowershellCmdlets.SetAzureStorageAccount(storageName[i], null, null, geoReplicationSettings[j]); if (geoReplicationSettings[j] != null) { geoReplicationEnabled = geoReplicationSettings[j].Value; } Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[i])[0], storageStaticProperties[i], label[2], description[2], geoReplicationEnabled)); } for (int j = 0; j < 3; j++) { vmPowershellCmdlets.SetAzureStorageAccount(storageName[i], label[j], description[j], geoReplicationSettings[j]); if (geoReplicationSettings[j] != null) { geoReplicationEnabled = geoReplicationSettings[j].Value; } Assert.IsTrue(StorageAccountVerify(vmPowershellCmdlets.GetAzureStorageAccount(storageName[i])[0], storageStaticProperties[i], label[j], description[j], geoReplicationEnabled)); } vmPowershellCmdlets.RemoveAzureStorageAccount(storageName[i]); Assert.IsTrue(Utilities.CheckRemove(vmPowershellCmdlets.GetAzureStorageAccount, storageName[i]), "The storage account was not removed"); } vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityGroupName); pass = true; } catch (Exception e) { pass = false; // Clean-up storage if it is not removed. foreach (string storage in storageName) { if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureStorageAccount, storage)) { vmPowershellCmdlets.RemoveAzureStorageAccount(storage); } } // Clean-up affinity group created. if (!Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityGroupName)) { vmPowershellCmdlets.RemoveAzureAffinityGroup(affinityGroupName); } Assert.Fail("Exception occurred: {0}", e.ToString()); } } private bool StorageAccountVerify(StorageServicePropertiesOperationContext storageContext, string [] staticParameters, string label, string description, bool geo) { string name = staticParameters[0]; string location = staticParameters[1]; string affinity = staticParameters[2]; Console.WriteLine("Name: {0}, Label: {1}, Description: {2}, AffinityGroup: {3}, Location: {4}, GeoReplicationEnabled: {5}", storageContext.StorageAccountName, storageContext.Label, storageContext.StorageAccountDescription, storageContext.AffinityGroup, storageContext.Location, storageContext.GeoReplicationEnabled); try { Assert.AreEqual(storageContext.StorageAccountName, name, "Error: Storage Account Name is not equal!"); Assert.AreEqual(storageContext.Label, label, "Error: Storage Account Label is not equal!"); Assert.AreEqual(storageContext.StorageAccountDescription, description, "Error: Storage Account Description is not equal!"); Assert.AreEqual(storageContext.AffinityGroup, affinity, "Error: Affinity Group is not equal!"); Assert.AreEqual(storageContext.Location, location, "Error: Location is not equal!"); Assert.AreEqual(storageContext.GeoReplicationEnabled, geo, "Error: GeoReplicationEnabled is not equal!"); Console.WriteLine("All contexts are matched!!\n"); } catch (Exception e) { Console.WriteLine(e.ToString()); return false; } return true; } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Save,Update,Remove)-AzureVMImage)")] [Ignore] public void AzureVMImageTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string newImageName = Utilities.GetUniqueShortName("vmimage"); string mediaLocation = string.Format("{0}vhdstore/{1}", blobUrlRoot, vhdName); string oldLabel = "old label"; string newLabel = "new label"; try { OSImageContext result = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, oldLabel); OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); result = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, newLabel); resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(CompareContext<OSImageContext>(result, resultReturned)); vmPowershellCmdlets.RemoveAzureVMImage(newImageName); pass = true; } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Get,Set,Remove)-AzureVNetConfig)")] [Ignore] public void AzureVNetConfigTest() { createOwnService = false; StartTest(MethodBase.GetCurrentMethod().Name, testStartTime); string affinityGroup = "WestUsAffinityGroup"; try { if (Utilities.CheckRemove(vmPowershellCmdlets.GetAzureAffinityGroup, affinityGroup)) { vmPowershellCmdlets.NewAzureAffinityGroup(affinityGroup, Resource.Location, null, null); } vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath); var result = vmPowershellCmdlets.GetAzureVNetConfig(vnetConfigFilePath); vmPowershellCmdlets.SetAzureVNetConfig(vnetConfigFilePath); Collection<VirtualNetworkSiteContext> vnetSites = vmPowershellCmdlets.GetAzureVNetSite(null); foreach (var re in vnetSites) { Console.WriteLine("VNet: {0}", re.Name); } vmPowershellCmdlets.RemoveAzureVNetConfig(); Collection<VirtualNetworkSiteContext> vnetSitesAfter = vmPowershellCmdlets.GetAzureVNetSite(null); Assert.AreNotEqual(vnetSites.Count, vnetSitesAfter.Count, "No Vnet is removed"); foreach (var re in vnetSitesAfter) { Console.WriteLine("VNet: {0}", re.Name); } pass = true; } catch (Exception e) { if (e.ToString().Contains("while in use")) { Console.WriteLine(e.InnerException.ToString()); } else { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } } [TestMethod(), TestCategory("Functional"), TestProperty("Feature", "IAAS"), Priority(1), Owner("hylee"), Description("Test the cmdlet ((Add,Get,Set,Remove)-AzureEndpoint)")] [Ignore] public void VMSizeTest() { string newImageName = Utilities.GetUniqueShortName("vmimage"); string mediaLocation = string.Format("{0}vhdstore/{1}", blobUrlRoot, vhdName); try { Array instanceSizes = Enum.GetValues(typeof(InstanceSize)); int arrayLength = instanceSizes.GetLength(0); for (int i = 1; i < arrayLength; i++) { // Add-AzureVMImage test for VM size OSImageContext result2 = vmPowershellCmdlets.AddAzureVMImage(newImageName, mediaLocation, OS.Windows, (InstanceSize) instanceSizes.GetValue(i)); OSImageContext resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(CompareContext<OSImageContext>(result2, resultReturned)); Console.WriteLine(i); // Update-AzureVMImage test for VM size result2 = vmPowershellCmdlets.UpdateAzureVMImage(newImageName, (InstanceSize) instanceSizes.GetValue(Math.Max((i + 1) % arrayLength, 1))); resultReturned = vmPowershellCmdlets.GetAzureVMImage(newImageName)[0]; Assert.IsTrue(CompareContext<OSImageContext>(result2, resultReturned)); vmPowershellCmdlets.RemoveAzureVMImage(newImageName); } foreach (InstanceSize size in instanceSizes) { if (size.Equals(InstanceSize.A6) || size.Equals(InstanceSize.A7)) { // We skip tests for regular VM sizes. Also, a VM created with regular size cannot be updated to Hi-MEM. serviceName = Utilities.GetUniqueShortName(serviceNamePrefix); vmName = Utilities.GetUniqueShortName(vmNamePrefix); // New-AzureQuickVM test for VM size PersistentVMRoleContext result = vmPowershellCmdlets.NewAzureQuickVM(OS.Windows, vmName, serviceName, imageName, username, password, locationName, size); Assert.AreEqual(size.ToString(), result.InstanceSize); Console.WriteLine("VM size, {0}, is verified for New-AzureQuickVM", size.ToString()); vmPowershellCmdlets.RemoveAzureVM(vmName, serviceName); // New-AzureVMConfig test for VM size AzureVMConfigInfo azureVMConfigInfo = new AzureVMConfigInfo(vmName, size, imageName); AzureProvisioningConfigInfo azureProvisioningConfig = new AzureProvisioningConfigInfo(OS.Windows, username, password); PersistentVMConfigInfo persistentVMConfigInfo = new PersistentVMConfigInfo(azureVMConfigInfo, azureProvisioningConfig, null, null); PersistentVM vm = vmPowershellCmdlets.GetPersistentVM(persistentVMConfigInfo); vmPowershellCmdlets.NewAzureVM(serviceName, new[] { vm }); result = vmPowershellCmdlets.GetAzureVM(vmName, serviceName); Assert.AreEqual(size.ToString(), result.InstanceSize); Console.WriteLine("VM size, {0}, is verified for New-AzureVMConfig", size.ToString()); vmPowershellCmdlets.RemoveAzureVM(vmName, serviceName); vmPowershellCmdlets.RemoveAzureService(serviceName); // Set-AzureVMSize test for VM size. SetAzureVMSizeConfig vmSizeConfig = new SetAzureVMSizeConfig(size); vmPowershellCmdlets.SetVMSize(defaultVm, defaultService, vmSizeConfig); result = vmPowershellCmdlets.GetAzureVM(defaultVm, defaultService); Assert.AreEqual(size.ToString(), result.InstanceSize); Console.WriteLine("VM size, {0}, is verified for Set-AzureVMSize", size.ToString()); } } } catch (Exception e) { pass = false; Assert.Fail("Exception occurred: {0}", e.ToString()); } } private bool CompareContext<T>(T obj1, T obj2) { bool result = true; Type type = typeof(T); foreach(PropertyInfo property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { string typeName = property.PropertyType.FullName; if (typeName.Equals("System.String") || typeName.Equals("System.Int32") || typeName.Equals("System.Uri") || typeName.Contains("Nullable")) { var obj1Value = property.GetValue(obj1, null); var obj2Value = property.GetValue(obj2, null); if (obj1Value == null) { result &= (obj2Value == null); } else { result &= (obj1Value.Equals(obj2Value)); } } else { Console.WriteLine("This type is not compared: {0}", typeName); } } return result; } [TestCleanup] public virtual void CleanUp() { Console.WriteLine("Test {0}", pass ? "passed" : "failed"); // Cleanup if ((createOwnService && cleanupIfPassed && pass) || (createOwnService && cleanupIfFailed && !pass)) { Console.WriteLine("Starting to clean up created VM and service."); try { vmPowershellCmdlets.RemoveAzureVM(vmName, serviceName); Console.WriteLine("VM, {0}, is deleted", vmName); } catch (Exception e) { Console.WriteLine("Error during removing VM: {0}", e.ToString()); } try { vmPowershellCmdlets.RemoveAzureService(serviceName); Console.WriteLine("Service, {0}, is deleted", serviceName); } catch (Exception e) { Console.WriteLine("Error during removing VM: {0}", e.ToString()); } } } [ClassCleanup] public static void ClassCleanUp() { try { vmPowershellCmdlets.RemoveAzureVM(defaultVm, defaultService); Console.WriteLine("VM, {0}, is deleted", defaultVm); } catch (Exception e) { Console.WriteLine("Error during removing VM: {0}", e.ToString()); } try { vmPowershellCmdlets.RemoveAzureService(defaultService); Console.WriteLine("Service, {0}, is deleted", defaultService); } catch (Exception e) { Console.WriteLine("Error during removing VM: {0}", e.ToString()); } } } }
// *********************************************************************** // Copyright (c) 2009 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; namespace NUnit.Framework.Constraints { /// <summary> /// ConstraintExpression represents a compound constraint in the /// process of being constructed from a series of syntactic elements. /// /// Individual elements are appended to the expression as they are /// reorganized. When a constraint is appended, it is returned as the /// value of the operation so that modifiers may be applied. However, /// any partially built expression is attached to the constraint for /// later resolution. When an operator is appended, the partial /// expression is returned. If it's a self-resolving operator, then /// a ResolvableConstraintExpression is returned. /// </summary> public class ConstraintExpression { #region Instance Fields /// <summary> /// The ConstraintBuilder holding the elements recognized so far /// </summary> protected ConstraintBuilder builder; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ConstraintExpression"/> class. /// </summary> public ConstraintExpression() { this.builder = new ConstraintBuilder(); } /// <summary> /// Initializes a new instance of the <see cref="ConstraintExpression"/> /// class passing in a ConstraintBuilder, which may be pre-populated. /// </summary> /// <param name="builder">The builder.</param> public ConstraintExpression(ConstraintBuilder builder) { this.builder = builder; } #endregion #region ToString() /// <summary> /// Returns a string representation of the expression as it /// currently stands. This should only be used for testing, /// since it has the side-effect of resolving the expression. /// </summary> /// <returns></returns> public override string ToString() { return builder.Resolve().ToString(); } #endregion #region Append Methods /// <summary> /// Appends an operator to the expression and returns the /// resulting expression itself. /// </summary> public ConstraintExpression Append(ConstraintOperator op) { builder.Append(op); return this; } /// <summary> /// Appends a self-resolving operator to the expression and /// returns a new ResolvableConstraintExpression. /// </summary> public ResolvableConstraintExpression Append(SelfResolvingOperator op) { builder.Append(op); return new ResolvableConstraintExpression(builder); } /// <summary> /// Appends a constraint to the expression and returns that /// constraint, which is associated with the current state /// of the expression being built. Note that the constraint /// is not reduced at this time. For example, if there /// is a NotOperator on the stack we don't reduce and /// return a NotConstraint. The original constraint must /// be returned because it may support modifiers that /// are yet to be applied. /// </summary> public Constraint Append(Constraint constraint) { builder.Append(constraint); return constraint; } #endregion #region Not /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression Not { get { return this.Append(new NotOperator()); } } /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public ConstraintExpression No { get { return this.Append(new NotOperator()); } } #endregion #region All /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them succeed. /// </summary> public ConstraintExpression All { get { return this.Append(new AllOperator()); } } #endregion #region Some /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if at least one of them succeeds. /// </summary> public ConstraintExpression Some { get { return this.Append(new SomeOperator()); } } #endregion #region None /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them fail. /// </summary> public ConstraintExpression None { get { return this.Append(new NoneOperator()); } } #endregion #region Exactly(n) /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding only if a specified number of them succeed. /// </summary> public ItemsConstraintExpression Exactly(int expectedCount) { builder.Append(new ExactCountOperator(expectedCount)); return new ItemsConstraintExpression(builder); } #endregion #region One /// <summary> /// Returns a <see cref="ItemsConstraintExpression"/>, which will /// apply the following constraint to a collection of length one, succeeding /// only if exactly one of them succeeds. /// </summary> public ItemsConstraintExpression One { get { builder.Append(new ExactCountOperator(1)); return new ItemsConstraintExpression(builder); } } #endregion #region Property /// <summary> /// Returns a new PropertyConstraintExpression, which will either /// test for the existence of the named property on the object /// being tested or apply any following constraint to that property. /// </summary> public ResolvableConstraintExpression Property(string name) { return this.Append(new PropOperator(name)); } #endregion #region Length /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Length property of the object being tested. /// </summary> public ResolvableConstraintExpression Length { get { return Property("Length"); } } #endregion #region Count /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Count property of the object being tested. /// </summary> public ResolvableConstraintExpression Count { get { return Property("Count"); } } #endregion #region Message /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the Message property of the object being tested. /// </summary> public ResolvableConstraintExpression Message { get { return Property("Message"); } } #endregion #region InnerException /// <summary> /// Returns a new ConstraintExpression, which will apply the following /// constraint to the InnerException property of the object being tested. /// </summary> public ResolvableConstraintExpression InnerException { get { return Property("InnerException"); } } #endregion #region Attribute /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute(Type expectedType) { return this.Append(new AttributeOperator(expectedType)); } /// <summary> /// Returns a new AttributeConstraint checking for the /// presence of a particular attribute on an object. /// </summary> public ResolvableConstraintExpression Attribute<TExpected>() { return Attribute(typeof(TExpected)); } #endregion #region With /// <summary> /// With is currently a NOP - reserved for future use. /// </summary> public ConstraintExpression With { get { return this.Append(new WithOperator()); } } #endregion #region Matches /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches(IResolveConstraint constraint) { return this.Append((Constraint)constraint.Resolve()); } /// <summary> /// Returns the constraint provided as an argument - used to allow custom /// custom constraints to easily participate in the syntax. /// </summary> public Constraint Matches<TActual>(Predicate<TActual> predicate) { return this.Append(new PredicateConstraint<TActual>(predicate)); } #endregion #region Null /// <summary> /// Returns a constraint that tests for null /// </summary> public NullConstraint Null { get { return (NullConstraint)this.Append(new NullConstraint()); } } #endregion #region True /// <summary> /// Returns a constraint that tests for True /// </summary> public TrueConstraint True { get { return (TrueConstraint)this.Append(new TrueConstraint()); } } #endregion #region False /// <summary> /// Returns a constraint that tests for False /// </summary> public FalseConstraint False { get { return (FalseConstraint)this.Append(new FalseConstraint()); } } #endregion #region Positive /// <summary> /// Returns a constraint that tests for a positive value /// </summary> public GreaterThanConstraint Positive { get { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(0)); } } #endregion #region Negative /// <summary> /// Returns a constraint that tests for a negative value /// </summary> public LessThanConstraint Negative { get { return (LessThanConstraint)this.Append(new LessThanConstraint(0)); } } #endregion #region Zero /// <summary> /// Returns a constraint that tests if item is equal to zero /// </summary> public EqualConstraint Zero { get { return (EqualConstraint)this.Append(new EqualConstraint(0)); } } #endregion #region NaN /// <summary> /// Returns a constraint that tests for NaN /// </summary> public NaNConstraint NaN { get { return (NaNConstraint)this.Append(new NaNConstraint()); } } #endregion #region Empty /// <summary> /// Returns a constraint that tests for empty /// </summary> public EmptyConstraint Empty { get { return (EmptyConstraint)this.Append(new EmptyConstraint()); } } #endregion #region Unique /// <summary> /// Returns a constraint that tests whether a collection /// contains all unique items. /// </summary> public UniqueItemsConstraint Unique { get { return (UniqueItemsConstraint)this.Append(new UniqueItemsConstraint()); } } #endregion #region BinarySerializable #if !NETSTANDARD1_6 /// <summary> /// Returns a constraint that tests whether an object graph is serializable in binary format. /// </summary> public BinarySerializableConstraint BinarySerializable { get { return (BinarySerializableConstraint)this.Append(new BinarySerializableConstraint()); } } #endif #endregion #region XmlSerializable #if !NETSTANDARD1_6 /// <summary> /// Returns a constraint that tests whether an object graph is serializable in xml format. /// </summary> public XmlSerializableConstraint XmlSerializable { get { return (XmlSerializableConstraint)this.Append(new XmlSerializableConstraint()); } } #endif #endregion #region EqualTo /// <summary> /// Returns a constraint that tests two items for equality /// </summary> public EqualConstraint EqualTo(object expected) { return (EqualConstraint)this.Append(new EqualConstraint(expected)); } #endregion #region SameAs /// <summary> /// Returns a constraint that tests that two references are the same object /// </summary> public SameAsConstraint SameAs(object expected) { return (SameAsConstraint)this.Append(new SameAsConstraint(expected)); } #endregion #region GreaterThan /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than the supplied argument /// </summary> public GreaterThanConstraint GreaterThan(object expected) { return (GreaterThanConstraint)this.Append(new GreaterThanConstraint(expected)); } #endregion #region GreaterThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the supplied argument /// </summary> public GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the supplied argument /// </summary> public GreaterThanOrEqualConstraint AtLeast(object expected) { return (GreaterThanOrEqualConstraint)this.Append(new GreaterThanOrEqualConstraint(expected)); } #endregion #region LessThan /// <summary> /// Returns a constraint that tests whether the /// actual value is less than the supplied argument /// </summary> public LessThanConstraint LessThan(object expected) { return (LessThanConstraint)this.Append(new LessThanConstraint(expected)); } #endregion #region LessThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the supplied argument /// </summary> public LessThanOrEqualConstraint LessThanOrEqualTo(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the supplied argument /// </summary> public LessThanOrEqualConstraint AtMost(object expected) { return (LessThanOrEqualConstraint)this.Append(new LessThanOrEqualConstraint(expected)); } #endregion #region TypeOf /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf(Type expectedType) { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public ExactTypeConstraint TypeOf<TExpected>() { return (ExactTypeConstraint)this.Append(new ExactTypeConstraint(typeof(TExpected))); } #endregion #region InstanceOf /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf(Type expectedType) { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public InstanceOfTypeConstraint InstanceOf<TExpected>() { return (InstanceOfTypeConstraint)this.Append(new InstanceOfTypeConstraint(typeof(TExpected))); } #endregion #region AssignableFrom /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom(Type expectedType) { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableFromConstraint AssignableFrom<TExpected>() { return (AssignableFromConstraint)this.Append(new AssignableFromConstraint(typeof(TExpected))); } #endregion #region AssignableTo /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo(Type expectedType) { return (AssignableToConstraint)this.Append(new AssignableToConstraint(expectedType)); } /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public AssignableToConstraint AssignableTo<TExpected>() { return (AssignableToConstraint)this.Append(new AssignableToConstraint(typeof(TExpected))); } #endregion #region EquivalentTo /// <summary> /// Returns a constraint that tests whether the actual value /// is a collection containing the same elements as the /// collection supplied as an argument. /// </summary> public CollectionEquivalentConstraint EquivalentTo(IEnumerable expected) { return (CollectionEquivalentConstraint)this.Append(new CollectionEquivalentConstraint(expected)); } #endregion #region SubsetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a subset of the collection supplied as an argument. /// </summary> public CollectionSubsetConstraint SubsetOf(IEnumerable expected) { return (CollectionSubsetConstraint)this.Append(new CollectionSubsetConstraint(expected)); } #endregion #region SupersetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a superset of the collection supplied as an argument. /// </summary> public CollectionSupersetConstraint SupersetOf(IEnumerable expected) { return (CollectionSupersetConstraint)this.Append(new CollectionSupersetConstraint(expected)); } #endregion #region Ordered /// <summary> /// Returns a constraint that tests whether a collection is ordered /// </summary> public CollectionOrderedConstraint Ordered { get { return (CollectionOrderedConstraint)this.Append(new CollectionOrderedConstraint()); } } #endregion #region Member /// <summary> /// Returns a new <see cref="SomeItemsConstraint"/> checking for the /// presence of a particular object in the collection. /// </summary> public SomeItemsConstraint Member(object expected) { return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected))); } #endregion #region Contains /// <summary> /// Returns a new <see cref="SomeItemsConstraint"/> checking for the /// presence of a particular object in the collection. /// </summary> public SomeItemsConstraint Contains(object expected) { return (SomeItemsConstraint)this.Append(new SomeItemsConstraint(new EqualConstraint(expected))); } /// <summary> /// Returns a new ContainsConstraint. This constraint /// will, in turn, make use of the appropriate second-level /// constraint, depending on the type of the actual argument. /// This overload is only used if the item sought is a string, /// since any other type implies that we are looking for a /// collection member. /// </summary> public ContainsConstraint Contains(string expected) { return (ContainsConstraint)this.Append(new ContainsConstraint(expected)); } /// <summary> /// Returns a new <see cref="SomeItemsConstraint"/> checking for the /// presence of a particular object in the collection. /// </summary> public SomeItemsConstraint Contain(object expected) { return Contains(expected); } /// <summary> /// Returns a new ContainsConstraint. This constraint /// will, in turn, make use of the appropriate second-level /// constraint, depending on the type of the actual argument. /// This overload is only used if the item sought is a string, /// since any other type implies that we are looking for a /// collection member. /// </summary> public ContainsConstraint Contain(string expected) { return Contains(expected); } #endregion #region DictionaryContains /// <summary> /// Returns a new DictionaryContainsKeyConstraint checking for the /// presence of a particular key in the Dictionary key collection. /// </summary> /// <param name="expected">The key to be matched in the Dictionary key collection</param> public DictionaryContainsKeyConstraint ContainKey(object expected) { return (DictionaryContainsKeyConstraint)this.Append(new DictionaryContainsKeyConstraint(expected)); } /// <summary> /// Returns a new DictionaryContainsValueConstraint checking for the /// presence of a particular value in the Dictionary value collection. /// </summary> /// <param name="expected">The value to be matched in the Dictionary value collection</param> public DictionaryContainsValueConstraint ContainValue(object expected) { return (DictionaryContainsValueConstraint)this.Append(new DictionaryContainsValueConstraint(expected)); } #endregion #region StringContaining /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> [Obsolete("Deprecated, use Contains")] public SubstringConstraint StringContaining(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> [Obsolete("Deprecated, use Contains")] public SubstringConstraint ContainsSubstring(string expected) { return (SubstringConstraint)this.Append(new SubstringConstraint(expected)); } #endregion #region StartsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StartWith(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public StartsWithConstraint StartsWith(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> [Obsolete("Deprecated, use Does.StartWith or StartsWith")] public StartsWithConstraint StringStarting(string expected) { return (StartsWithConstraint)this.Append(new StartsWithConstraint(expected)); } #endregion #region EndsWith /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint EndWith(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public EndsWithConstraint EndsWith(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> [Obsolete("Deprecated, use Does.EndWith or EndsWith")] public EndsWithConstraint StringEnding(string expected) { return (EndsWithConstraint)this.Append(new EndsWithConstraint(expected)); } #endregion #region Matches /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Match(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> public RegexConstraint Matches(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } /// <summary> /// Returns a constraint that succeeds if the actual /// value matches the regular expression supplied as an argument. /// </summary> [Obsolete("Deprecated, use Does.Match or Matches")] public RegexConstraint StringMatching(string pattern) { return (RegexConstraint)this.Append(new RegexConstraint(pattern)); } #endregion #region SamePath /// <summary> /// Returns a constraint that tests whether the path provided /// is the same as an expected path after canonicalization. /// </summary> public SamePathConstraint SamePath(string expected) { return (SamePathConstraint)this.Append(new SamePathConstraint(expected)); } #endregion #region SubPath /// <summary> /// Returns a constraint that tests whether the path provided /// is the a subpath of the expected path after canonicalization. /// </summary> public SubPathConstraint SubPathOf(string expected) { return (SubPathConstraint)this.Append(new SubPathConstraint(expected)); } #endregion #region SamePathOrUnder /// <summary> /// Returns a constraint that tests whether the path provided /// is the same path or under an expected path after canonicalization. /// </summary> public SamePathOrUnderConstraint SamePathOrUnder(string expected) { return (SamePathOrUnderConstraint)this.Append(new SamePathOrUnderConstraint(expected)); } #endregion #region InRange /// <summary> /// Returns a constraint that tests whether the actual value falls /// inclusively within a specified range. /// </summary> /// <param name="from">Inclusive beginning of the range.</param> /// <param name="to">Inclusive end of the range.</param> public RangeConstraint InRange(object from, object to) { return (RangeConstraint)this.Append(new RangeConstraint(from, to)); } #endregion #region Exist /// <summary> /// Returns a constraint that succeeds if the value /// is a file or directory and it exists. /// </summary> public Constraint Exist { get { return Append(new FileOrDirectoryExistsConstraint()); } } #endregion } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Engines { /** * A class that provides a basic International Data Encryption Algorithm (IDEA) engine. * <p> * This implementation is based on the "HOWTO: INTERNATIONAL DATA ENCRYPTION ALGORITHM" * implementation summary by Fauzan Mirza (F.U.Mirza@sheffield.ac.uk). (baring 1 typo at the * end of the mulinv function!). * </p> * <p> * It can be found at ftp://ftp.funet.fi/pub/crypt/cryptography/symmetric/idea/ * </p> * <p> * Note 1: This algorithm is patented in the USA, Japan, and Europe including * at least Austria, France, Germany, Italy, Netherlands, Spain, Sweden, Switzerland * and the United Kingdom. Non-commercial use is free, however any commercial * products are liable for royalties. Please see * <a href="http://www.mediacrypt.com">www.mediacrypt.com</a> for * further details. This announcement has been included at the request of * the patent holders. * </p> * <p> * Note 2: Due to the requests concerning the above, this algorithm is now only * included in the extended assembly. It is not included in the default distributions. * </p> */ public class IdeaEngine : IBlockCipher { private const int BLOCK_SIZE = 8; private int[] workingKey; /** * standard constructor. */ public IdeaEngine() { } /** * initialise an IDEA cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public virtual void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to IDEA init - " + parameters.GetType().ToString()); workingKey = GenerateWorkingKey(forEncryption, ((KeyParameter)parameters).GetKey()); } public virtual string AlgorithmName { get { return "IDEA"; } } public virtual bool IsPartialBlockOkay { get { return false; } } public virtual int GetBlockSize() { return BLOCK_SIZE; } public virtual int ProcessBlock( byte[] input, int inOff, byte[] output, int outOff) { if (workingKey == null) throw new InvalidOperationException("IDEA engine not initialised"); Check.DataLength(input, inOff, BLOCK_SIZE, "input buffer too short"); Check.OutputLength(output, outOff, BLOCK_SIZE, "output buffer too short"); IdeaFunc(workingKey, input, inOff, output, outOff); return BLOCK_SIZE; } public virtual void Reset() { } private static readonly int MASK = 0xffff; private static readonly int BASE = 0x10001; private int BytesToWord( byte[] input, int inOff) { return ((input[inOff] << 8) & 0xff00) + (input[inOff + 1] & 0xff); } private void WordToBytes( int word, byte[] outBytes, int outOff) { outBytes[outOff] = (byte)((uint) word >> 8); outBytes[outOff + 1] = (byte)word; } /** * return x = x * y where the multiplication is done modulo * 65537 (0x10001) (as defined in the IDEA specification) and * a zero input is taken to be 65536 (0x10000). * * @param x the x value * @param y the y value * @return x = x * y */ private int Mul( int x, int y) { if (x == 0) { x = (BASE - y); } else if (y == 0) { x = (BASE - x); } else { int p = x * y; y = p & MASK; x = (int) ((uint) p >> 16); x = y - x + ((y < x) ? 1 : 0); } return x & MASK; } private void IdeaFunc( int[] workingKey, byte[] input, int inOff, byte[] outBytes, int outOff) { int x0, x1, x2, x3, t0, t1; int keyOff = 0; x0 = BytesToWord(input, inOff); x1 = BytesToWord(input, inOff + 2); x2 = BytesToWord(input, inOff + 4); x3 = BytesToWord(input, inOff + 6); for (int round = 0; round < 8; round++) { x0 = Mul(x0, workingKey[keyOff++]); x1 += workingKey[keyOff++]; x1 &= MASK; x2 += workingKey[keyOff++]; x2 &= MASK; x3 = Mul(x3, workingKey[keyOff++]); t0 = x1; t1 = x2; x2 ^= x0; x1 ^= x3; x2 = Mul(x2, workingKey[keyOff++]); x1 += x2; x1 &= MASK; x1 = Mul(x1, workingKey[keyOff++]); x2 += x1; x2 &= MASK; x0 ^= x1; x3 ^= x2; x1 ^= t1; x2 ^= t0; } WordToBytes(Mul(x0, workingKey[keyOff++]), outBytes, outOff); WordToBytes(x2 + workingKey[keyOff++], outBytes, outOff + 2); /* NB: Order */ WordToBytes(x1 + workingKey[keyOff++], outBytes, outOff + 4); WordToBytes(Mul(x3, workingKey[keyOff]), outBytes, outOff + 6); } /** * The following function is used to expand the user key to the encryption * subkey. The first 16 bytes are the user key, and the rest of the subkey * is calculated by rotating the previous 16 bytes by 25 bits to the left, * and so on until the subkey is completed. */ private int[] ExpandKey( byte[] uKey) { int[] key = new int[52]; if (uKey.Length < 16) { byte[] tmp = new byte[16]; Array.Copy(uKey, 0, tmp, tmp.Length - uKey.Length, uKey.Length); uKey = tmp; } for (int i = 0; i < 8; i++) { key[i] = BytesToWord(uKey, i * 2); } for (int i = 8; i < 52; i++) { if ((i & 7) < 6) { key[i] = ((key[i - 7] & 127) << 9 | key[i - 6] >> 7) & MASK; } else if ((i & 7) == 6) { key[i] = ((key[i - 7] & 127) << 9 | key[i - 14] >> 7) & MASK; } else { key[i] = ((key[i - 15] & 127) << 9 | key[i - 14] >> 7) & MASK; } } return key; } /** * This function computes multiplicative inverse using Euclid's Greatest * Common Divisor algorithm. Zero and one are self inverse. * <p> * i.e. x * MulInv(x) == 1 (modulo BASE) * </p> */ private int MulInv( int x) { int t0, t1, q, y; if (x < 2) { return x; } t0 = 1; t1 = BASE / x; y = BASE % x; while (y != 1) { q = x / y; x = x % y; t0 = (t0 + (t1 * q)) & MASK; if (x == 1) { return t0; } q = y / x; y = y % x; t1 = (t1 + (t0 * q)) & MASK; } return (1 - t1) & MASK; } /** * Return the additive inverse of x. * <p> * i.e. x + AddInv(x) == 0 * </p> */ int AddInv( int x) { return (0 - x) & MASK; } /** * The function to invert the encryption subkey to the decryption subkey. * It also involves the multiplicative inverse and the additive inverse functions. */ private int[] InvertKey( int[] inKey) { int t1, t2, t3, t4; int p = 52; /* We work backwards */ int[] key = new int[52]; int inOff = 0; t1 = MulInv(inKey[inOff++]); t2 = AddInv(inKey[inOff++]); t3 = AddInv(inKey[inOff++]); t4 = MulInv(inKey[inOff++]); key[--p] = t4; key[--p] = t3; key[--p] = t2; key[--p] = t1; for (int round = 1; round < 8; round++) { t1 = inKey[inOff++]; t2 = inKey[inOff++]; key[--p] = t2; key[--p] = t1; t1 = MulInv(inKey[inOff++]); t2 = AddInv(inKey[inOff++]); t3 = AddInv(inKey[inOff++]); t4 = MulInv(inKey[inOff++]); key[--p] = t4; key[--p] = t2; /* NB: Order */ key[--p] = t3; key[--p] = t1; } t1 = inKey[inOff++]; t2 = inKey[inOff++]; key[--p] = t2; key[--p] = t1; t1 = MulInv(inKey[inOff++]); t2 = AddInv(inKey[inOff++]); t3 = AddInv(inKey[inOff++]); t4 = MulInv(inKey[inOff]); key[--p] = t4; key[--p] = t3; key[--p] = t2; key[--p] = t1; return key; } private int[] GenerateWorkingKey( bool forEncryption, byte[] userKey) { if (forEncryption) { return ExpandKey(userKey); } else { return InvertKey(ExpandKey(userKey)); } } } } #endif
#region Using directives using System; using System.Management.Automation; using System.Management.Automation.SecurityAccountsManager; using System.Management.Automation.SecurityAccountsManager.Extensions; using Microsoft.PowerShell.LocalAccounts; #endregion namespace Microsoft.PowerShell.Commands { /// <summary> /// The Rename-LocalGroup cmdlet renames a local security group in the Security /// Accounts Manager. /// </summary> [Cmdlet(VerbsCommon.Rename, "LocalGroup", SupportsShouldProcess = true, HelpUri = "http://go.microsoft.com/fwlink/?LinkId=717978")] [Alias("rnlg")] public class RenameLocalGroupCommand : Cmdlet { #region Instance Data private Sam sam = null; #endregion Instance Data #region Parameter Properties /// <summary> /// The following is the definition of the input parameter "InputObject". /// Specifies the of the local group account to rename in the local Security /// Accounts Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "InputObject")] [ValidateNotNullOrEmpty] public Microsoft.PowerShell.Commands.LocalGroup InputObject { get { return this.inputobject;} set { this.inputobject = value; } } private Microsoft.PowerShell.Commands.LocalGroup inputobject; /// <summary> /// The following is the definition of the input parameter "Name". /// Specifies the local group to be renamed in the local Security Accounts /// Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "Default")] [ValidateNotNullOrEmpty] public string Name { get { return this.name;} set { this.name = value; } } private string name; /// <summary> /// The following is the definition of the input parameter "NewName". /// Specifies the new name for the local security group in the Security Accounts /// Manager. /// </summary> [Parameter(Mandatory = true, Position = 1)] [ValidateNotNullOrEmpty] public string NewName { get { return this.newname;} set { this.newname = value; } } private string newname; /// <summary> /// The following is the definition of the input parameter "SID". /// Specifies a security group from the local Security Accounts Manager. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "SecurityIdentifier")] [ValidateNotNullOrEmpty] public System.Security.Principal.SecurityIdentifier SID { get { return this.sid;} set { this.sid = value; } } private System.Security.Principal.SecurityIdentifier sid; #endregion Parameter Properties #region Cmdlet Overrides /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { sam = new Sam(); } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { ProcessGroup(); ProcessName(); ProcessSid(); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { if (sam != null) { sam.Dispose(); sam = null; } } #endregion Cmdlet Overrides #region Private Methods /// <summary> /// Process group requested by -Name /// </summary> /// <remarks> /// Arguments to -Name will be treated as names, /// even if a name looks like a SID. /// </remarks> private void ProcessName() { if (Name != null) { try { if (CheckShouldProcess(Name, NewName)) sam.RenameLocalGroup(sam.GetLocalGroup(Name), NewName); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } } /// <summary> /// Process group requested by -SID /// </summary> private void ProcessSid() { if (SID != null) { try { if (CheckShouldProcess(SID.ToString(), NewName)) sam.RenameLocalGroup(SID, NewName); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } } /// <summary> /// Process group given through -InputObject /// </summary> private void ProcessGroup() { if (InputObject != null) { try { if (CheckShouldProcess(InputObject.Name, NewName)) sam.RenameLocalGroup(InputObject, NewName); } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } } /// <summary> /// Determine if a group should be processed. /// Just a wrapper around Cmdlet.ShouldProcess, with localized string /// formatting. /// </summary> /// <param name="groupName"> /// Name of the group to rename. /// </param> /// <param name="newName"> /// New name for the group. /// </param> /// <returns> /// True if the group should be processed, false otherwise. /// </returns> private bool CheckShouldProcess(string groupName, string newName) { string msg = StringUtil.Format(Strings.ActionRenameGroup, newName); return ShouldProcess(groupName, msg); } #endregion Private Methods }//End Class }//End namespace
using System.Diagnostics; using System; // //Module : AAECLIPSES.CPP //Purpose: Implementation for the algorithms which obtain the principal characteristics of an eclipse of the Sun or the Moon //Created: PJN / 21-01-2004 //History: PJN / 25-02-2004 1. Calculation of semi durations is now calculated only when required // PJN / 31-01-2005 1. Fixed a GCC compiler error related to missing include for memset. Thanks to Mika Heiskanen for // reporting this problem. // //Copyright (c) 2004 - 2007 by PJ Naughter (Web: www.naughter.com, Email: pjna@naughter.com) // //All rights reserved. // //Copyright / Usage Details: // //You are allowed to include the source code in any product (commercial, shareware, freeware or otherwise) //when your product is released in binary form. You are allowed to modify the source code in any way you want //except you cannot modify the copyright details at the top of each module. If you want to distribute source //code with your application, then you are only allowed to distribute versions released by the author. This is //to maintain a single distribution point for the source code. // // //////////////////////////// Includes ///////////////////////////////////////// /////////////////////// Classes /////////////////////////////////////////////// public class CAASolarEclipseDetails { //Constructors / Destructors public CAASolarEclipseDetails() { bEclipse = false; TimeOfMaximumEclipse = 0; F = 0; u = 0; gamma = 0; GreatestMagnitude = 0; } //Member variables public bool bEclipse; public double TimeOfMaximumEclipse; public double F; public double u; public double gamma; public double GreatestMagnitude; } public class CAALunarEclipseDetails { //Constructors / Destructors public CAALunarEclipseDetails() { bEclipse = false; TimeOfMaximumEclipse = 0; F = 0; u = 0; gamma = 0; PenumbralRadii = 0; UmbralRadii = 0; PenumbralMagnitude = 0; UmbralMagnitude = 0; PartialPhaseSemiDuration = 0; TotalPhaseSemiDuration = 0; PartialPhasePenumbraSemiDuration = 0; } //Member variables public bool bEclipse; public double TimeOfMaximumEclipse; public double F; public double u; public double gamma; public double PenumbralRadii; public double UmbralRadii; public double PenumbralMagnitude; public double UmbralMagnitude; public double PartialPhaseSemiDuration; public double TotalPhaseSemiDuration; public double PartialPhasePenumbraSemiDuration; } public class CAAEclipses { //Static methods public static CAASolarEclipseDetails CalculateSolar(double k) { #if _DEBUG double intp = 0; bool bSolarEclipse = (GlobalMembersStdafx.modf(k, ref intp) == 0); Debug.Assert(bSolarEclipse); #endif double Mdash = 0; return Calculate(k, ref Mdash); } public static CAALunarEclipseDetails CalculateLunar(double k) { #if _DEBUG double intp = 0; bool bSolarEclipse = (GlobalMembersStdafx.modf(k, ref intp) == 0); Debug.Assert(!bSolarEclipse); #endif double Mdash = 0; CAASolarEclipseDetails solarDetails = Calculate(k, ref Mdash); //What will be the return value CAALunarEclipseDetails details = new CAALunarEclipseDetails(); details.bEclipse = solarDetails.bEclipse; details.F = solarDetails.F; details.gamma = solarDetails.gamma; details.TimeOfMaximumEclipse = solarDetails.TimeOfMaximumEclipse; details.u = solarDetails.u; if (details.bEclipse) { details.PenumbralRadii = 1.2848 + details.u; details.UmbralRadii = 0.7403 - details.u; double fgamma = Math.Abs(details.gamma); details.PenumbralMagnitude = (1.5573 + details.u - fgamma) / 0.5450; details.UmbralMagnitude = (1.0128 - details.u - fgamma) / 0.5450; double p = 1.0128 - details.u; double t = 0.4678 - details.u; double n = 0.5458 + 0.0400 * Math.Cos(Mdash); double gamma2 = details.gamma * details.gamma; double p2 = p * p; if (p2 >= gamma2) details.PartialPhaseSemiDuration = 60 / n * Math.Sqrt(p2 - gamma2); double t2 = t * t; if (t2 >= gamma2) details.TotalPhaseSemiDuration = 60 / n * Math.Sqrt(t2 - gamma2); double h = 1.5573 + details.u; double h2 = h * h; if (h2 >= gamma2) details.PartialPhasePenumbraSemiDuration = 60 / n * Math.Sqrt(h2 - gamma2); } return details; } //Tangible Process Only End //////////////////////////// Implementation /////////////////////////////////// protected static CAASolarEclipseDetails Calculate(double k, ref double Mdash) { //Are we looking for a solar or lunar eclipse double intp = Math.Floor(k); bool bSolarEclipse = ((k - intp) == 0); //What will be the return value CAASolarEclipseDetails details = new CAASolarEclipseDetails(); //convert from K to T double T = k / 1236.85; double T2 = T * T; double T3 = T2 * T; double T4 = T3 * T; double E = 1 - 0.002516 * T - 0.0000074 * T2; double M = CAACoordinateTransformation.MapTo0To360Range(2.5534 + 29.10535670 * k - 0.0000014 * T2 - 0.00000011 * T3); M = CAACoordinateTransformation.DegreesToRadians(M); Mdash = CAACoordinateTransformation.MapTo0To360Range(201.5643 + 385.81693528 * k + 0.0107582 * T2 + 0.00001238 * T3 - 0.000000058 * T4); Mdash = CAACoordinateTransformation.DegreesToRadians(Mdash); double omega = CAACoordinateTransformation.MapTo0To360Range(124.7746 - 1.56375588 * k + 0.0020672 * T2 + 0.00000215 * T3); omega = CAACoordinateTransformation.DegreesToRadians(omega); double F = CAACoordinateTransformation.MapTo0To360Range(160.7108 + 390.67050284 * k - 0.0016118 * T2 - 0.00000227 * T3 + 0.00000001 * T4); details.F = F; double Fdash = F - 0.02665 * Math.Sin(omega); F = CAACoordinateTransformation.DegreesToRadians(F); Fdash = CAACoordinateTransformation.DegreesToRadians(Fdash); //Do the first check to see if we have an eclipse if (Math.Abs(Math.Sin(F)) > 0.36) return details; double A1 = CAACoordinateTransformation.MapTo0To360Range(299.77 + 0.107408 * k - 0.009173 * T2); A1 = CAACoordinateTransformation.DegreesToRadians(A1); details.TimeOfMaximumEclipse = CAAMoonPhases.MeanPhase(k); double DeltaJD = 0; if (bSolarEclipse) DeltaJD += -0.4075 * Math.Sin(Mdash) + 0.1721 * E * Math.Sin(M); else DeltaJD += -0.4065 * Math.Sin(Mdash) + 0.1727 * E * Math.Sin(M); DeltaJD += 0.0161 * Math.Sin(2 * Mdash) + -0.0097 * Math.Sin(2 * Fdash) + 0.0073 * E * Math.Sin(Mdash - M) + -0.0050 * E * Math.Sin(Mdash + M) + -0.0023 * Math.Sin(Mdash - 2 * Fdash) + 0.0021 * E * Math.Sin(2 * M) + 0.0012 * Math.Sin(Mdash + 2 * Fdash) + 0.0006 * E * Math.Sin(2 * Mdash + M) + -0.0004 * Math.Sin(3 * Mdash) + -0.0003 * E * Math.Sin(M + 2 * Fdash) + 0.0003 * Math.Sin(A1) + -0.0002 * E * Math.Sin(M - 2 * Fdash) + -0.0002 * E * Math.Sin(2 * Mdash - M) + -0.0002 * Math.Sin(omega); details.TimeOfMaximumEclipse += DeltaJD; double P = 0.2070 * E * Math.Sin(M) + 0.0024 * E * Math.Sin(2 * M) + -0.0392 * Math.Sin(Mdash) + 0.0116 * Math.Sin(2 * Mdash) + -0.0073 * E * Math.Sin(Mdash + M) + 0.0067 * E * Math.Sin(Mdash - M) + 0.0118 * Math.Sin(2 * Fdash); double Q = 5.2207 + -0.0048 * E * Math.Cos(M) + 0.0020 * E * Math.Cos(2 * M) + -0.3299 * Math.Cos(Mdash) + -0.0060 * E * Math.Cos(Mdash + M) + 0.0041 * E * Math.Cos(Mdash - M); double W = Math.Abs(Math.Cos(Fdash)); details.gamma = (P * Math.Cos(Fdash) + Q * Math.Sin(Fdash)) * (1 - 0.0048 * W); details.u = 0.0059 + 0.0046 * E * Math.Cos(M) + -0.0182 * Math.Cos(Mdash) + 0.0004 * Math.Cos(2 * Mdash) + -0.0005 * Math.Cos(M + Mdash); //Check to see if the eclipse is visible from the Earth's surface if (Math.Abs(details.gamma) > (1.5433 + details.u)) return details; //We have an eclipse at this time details.bEclipse = true; //In the case of a partial eclipse, calculate its magnitude double fgamma = Math.Abs(details.gamma); if (((fgamma > 0.9972) && (fgamma < 1.5433 + details.u))) details.GreatestMagnitude = (1.5433 + details.u - fgamma) / (0.5461 + 2 * details.u); return details; } }
#region Namespaces using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using Epi.Fields; using Epi.Windows; using Epi.Windows.Controls; using Epi.Windows.Enter.PresentationLogic; #endregion //Namespaces namespace Epi.Windows.Enter { #region Public Delegates /// <summary> /// The event handler which fires when the panel is left /// </summary> /// <param name="panel">The panel that loses focus</param> public delegate void LeavePanelEventHandler(Panel panel); #endregion //Public Delegates /// <summary> /// Enter's canvas /// </summary> public partial class Canvas : Epi.Windows.Docking.DockWindow { public event GuiMediator.GotoRecordEventHandler GotoRecordEvent; public event GuiMediator.OpenFieldEventHandler GotoFieldEvent; public event GuiMediator.CloseFieldEventHandler CloseFieldEvent; public event GuiMediator.FieldChangeEventHandler FieldChangeEvent; public event GuiMediator.ClickFieldEventHandler ClickFieldEvent; public event GuiMediator.DirtyFieldEventHandler DirtyFieldEvent; public event DataGridViewRowEventHandler DataGridRowAddedEvent; #region Private Members private Panel currentPanel; private View currentView; private List<Panel> panelsList = new List<Panel>(); private Graphics bufferGraphics; private Bitmap bufferBitmap; private Configuration config; private EnterMainForm mainFrm; static public Color HighlightColor = Color.Yellow; static public Color UnHighlightColor = Color.White; #endregion //Private Members #region Public Properties /// <summary> /// List of panels loaded for the view /// </summary> public List<Panel> Panels { get { if (this.canvasPanel.Controls.Count > 0) { return new List<Panel>(){this.canvasPanel.Controls[0] as Panel}; } else { return new List<Panel>(); } } } public void DisposePanels() { try { foreach (Panel panel in panelsList) { panel.MouseDown -= new MouseEventHandler(panel_MouseDown); panel.Paint -= new PaintEventHandler(DrawBorderRect); panel.Dispose(); } } catch (Exception ex) { // } finally { panelsList.Clear(); GC.Collect(); } } public View CurrentView { get { return this.currentView; } set { this.currentView = value; } } #endregion //Public Properties #region Public Events /// <summary> /// Event to be raised when a panel loses focus /// </summary> public event LeavePanelEventHandler PanelLeft; #endregion //Public Events #region Constructors /// <summary> /// Constructor for Canvas /// </summary> public Canvas(MainForm frm) { config = Configuration.GetNewInstance(); mainFrm = frm as EnterMainForm; InitializeComponent(); canvasPanel.Dock = DockStyle.None; canvasPanel.BorderStyle = BorderStyle.FixedSingle; canvasPanel.Visible = false; RedrawCanvasBackground(); } #endregion //Constructors #region Public Methods /// <summary> /// Resets the canvas to its original state /// </summary> public void Reset() { foreach (Control control in canvasPanel.Controls) { if (control is Panel) { Panel jPanel = control as Panel; foreach (Control jControl in jPanel.Controls) { if (jControl is DataGridView) { DataGridView dgv = jControl as DataGridView; dgv.DataSource = null; } } } canvasPanel.Controls.Remove(control); control.Dispose(); } RedrawCanvasBackground(); canvasPanel.Visible = false; } /// <summary> /// Sets the dirty flag /// </summary> public void SetDirtyFlag() { DirtyFieldEvent(this, new EventArgs()); } /// <summary> /// Enable/Disable the current record /// </summary> /// <param name="view">The current view</param> /// <param name="enable">Boolean to indicate whether to enable or disable record</param> public void EnableDisableCurrentRecord(View view, bool enable) { #region Input Validation if (view == null) { throw new ArgumentNullException("view"); } #endregion //Input Validation //When loading a new page or adding a new record, unselect //first entry for comboboxes and enable controls foreach (Panel panel in this.Panels) { Epi.Windows.Enter.PresentationLogic.ControlFactory factory = Epi.Windows.Enter.PresentationLogic.ControlFactory.Instance; foreach (Control control in panel.Controls) //foreach (Page page in view.Pages) //{ // foreach (Control control in currentPanel.Controls) { Field field = factory.GetAssociatedField(control); // Test for perf improvements on record nav if (field is InputFieldWithSeparatePrompt && control.Enabled == enable) { continue; } if (control is ComboBox) { if (view.CurrentRecordId == 0) { ((ComboBox)control).SelectedIndex = -1; ((ComboBox)control).Text = string.Empty; } else { if (string.IsNullOrEmpty(((IDataField)field).CurrentRecordValueString)) { ((ComboBox)control).SelectedIndex = -1; ((ComboBox)control).Text = string.Empty; } } } control.Visible = true; //reset control to visible in case the Hide command was executed control.Enabled = enable; // If we're enabling the record (typically what's done unless 'mark record for deletion' button is pressed) if (enable) { if (field is InputFieldWithSeparatePrompt) { control.Enabled = !((InputFieldWithSeparatePrompt)field).IsReadOnly ? true : false; } else if (field is InputFieldWithoutSeparatePrompt) { control.Enabled = !((InputFieldWithoutSeparatePrompt)field).IsReadOnly ? true : false; } if (field is MirrorField) { control.Enabled = false; } } } } currentView = view; return; } /// <summary> /// Show a panel /// </summary> /// <param name="panel">The panel to show</param> public void ShowPanel(Panel panel) { panel.Visible = true; panel.BringToFront(); currentPanel = panel; } /// <summary> /// Add a panel to the canvas /// </summary> /// <param name="panel">The panel to add</param> public void SetPanelProperties(Panel panel) { panel.Dock = DockStyle.Fill; panel.MouseDown += new MouseEventHandler(panel_MouseDown); panel.BackColor = Color.Transparent; panel.AutoScroll = false; panel.Paint += new PaintEventHandler(DrawBorderRect); //panelsList.Clear(); //panelsList.Add(panel); } /// <summary> /// Hides controls for check code execution /// </summary> /// <param name="controlsList">The list of controls to be hidden</param> public void HideCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { throw new ArgumentNullException("controlsList"); } #endregion //Input Validation Control[] tmpControlList = new Control[controlsList.Count]; controlsList.CopyTo(tmpControlList); foreach (Control control in tmpControlList) { controlsList[controlsList.IndexOf(control)].Visible = false; } } /// <summary> /// Hides all controls except those specified for check code execution /// </summary> /// <param name="controlsList">The list of controls to not be hidden</param> public void HideExceptCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { throw new ArgumentNullException("controlsList"); } #endregion //Input Validation foreach (Panel panel in Panels) { foreach (Control control in panel.Controls) { if (!controlsList.Contains(control)) { control.Visible = false; } else { control.Visible = true; } } } } /// <summary> /// Unhides controls for check code execution /// </summary> /// <param name="controlsList">The list of controls to be unhidden </param> public void UnhideCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { throw new ArgumentNullException("controlsList"); } #endregion //Input Validation foreach (Panel panel in Panels) { foreach (Control control in controlsList) { if (panel.Controls.Contains(control)) { control.Visible = true; } } } } /// <summary> /// Unhides all controls except those specified for check code execution /// </summary> /// <param name="controlsList">The list of controls to be hidden </param> public void UnhideExceptCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { throw new ArgumentNullException("controlsList"); } #endregion //Input Validation foreach (Panel panel in Panels) { foreach (Control control in controlsList) { if (panel.Controls.Contains(control)) { control.Visible = false; } } } } /// <summary> /// Highlights controls for check code execution /// </summary> /// <param name="controlsList">The list of controls to be hidden</param> public void HighlightCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { throw new ArgumentNullException("controlsList"); } #endregion //Input Validation Control[] tmpControlList = new Control[controlsList.Count]; controlsList.CopyTo(tmpControlList); foreach (Control control in tmpControlList) { controlsList[controlsList.IndexOf(control)].BackColor = HighlightColor; } } /// <summary> /// Highlights all controls except those specified for check code execution /// </summary> /// <param name="controlsList">The list of controls to not be hidden</param> public void HighlightExceptCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { throw new ArgumentNullException("controlsList"); } #endregion //Input Validation foreach (Panel panel in Panels) { foreach (Control control in panel.Controls) { if (!controlsList.Contains(control)) { control.BackColor = HighlightColor; } else { control.BackColor = HighlightColor; } } } } /// <summary> /// UnHighlights controls for check code execution /// </summary> /// <param name="controlsList">The list of controls to be hidden</param> public void UnHighlightCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { throw new ArgumentNullException("controlsList"); } #endregion //Input Validation Control[] tmpControlList = new Control[controlsList.Count]; controlsList.CopyTo(tmpControlList); foreach (Control control in tmpControlList) { controlsList[controlsList.IndexOf(control)].BackColor = UnHighlightColor; } } /// <summary> /// UnHighlights all controls except those specified for check code execution /// </summary> /// <param name="controlsList">The list of controls to not be hidden</param> public void UnHighlightExceptCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { throw new ArgumentNullException("controlsList"); } #endregion //Input Validation foreach (Panel panel in Panels) { foreach (Control control in panel.Controls) { if (!controlsList.Contains(control)) { control.BackColor = UnHighlightColor; } else { control.BackColor = UnHighlightColor; } } } } /// <summary> /// Highlights controls for check code execution /// </summary> /// <param name="controlsList">The list of controls to be hidden</param> public void EnableCheckCodeItems(List<Control> pList) { #region Input Validation if (pList == null) { //throw new ArgumentNullException("controlsList"); return; } #endregion //Input Validation for (int i = 0; i < pList.Count; i++) { pList[i].Enabled = true; } /* Control[] tmpControlList = new Control[controlsList.Count]; controlsList.CopyTo(tmpControlList); foreach (Control control in tmpControlList) { controlsList[controlsList.IndexOf(control)].Enabled = true; }*/ } /// <summary> /// Highlights all controls except those specified for check code execution /// </summary> /// <param name="controlsList">The list of controls to not be hidden</param> public void EnableExceptCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { //throw new ArgumentNullException("controlsList"); return; } #endregion //Input Validation foreach (Panel panel in Panels) { foreach (Control control in panel.Controls) { if (!controlsList.Contains(control)) { control.Enabled = true; } else { control.Enabled = true; } } } } /// <summary> /// Highlights controls for check code execution /// </summary> /// <param name="controlsList">The list of controls to be hidden</param> public void DisableCheckCodeItems(List<Control> pList) { #region Input Validation if (pList == null) { //throw new ArgumentNullException("controlsList"); return; } #endregion //Input Validation for (int i = 0; i < pList.Count; i++) { pList[i].Enabled = false; } } /// <summary> /// Highlights all controls except those specified for check code execution /// </summary> /// <param name="controlsList">The list of controls to not be hidden</param> public void DisableExceptCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { //throw new ArgumentNullException("controlsList"); return; } #endregion //Input Validation foreach (Panel panel in Panels) { foreach (Control control in panel.Controls) { if (!controlsList.Contains(control)) { control.Enabled = false; } else { control.Enabled = false; } } } } /// <summary> /// Assigns controls to desired text /// </summary> /// <param name="controlsList">The list of controls to be assigned</param> public void AssignCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { //throw new ArgumentNullException("controlsList"); return; } #endregion //Input Validation foreach (Panel panel in Panels) { foreach (Control control in controlsList) { if (!(control is Label)) { if (panel.Controls.Contains(control)) { control.Text = control.Text.Substring(1, control.Text.Length - 2); } } } } } /// <summary> /// Clears content of controls for check code execution /// </summary> /// <param name="controlsList">List of controls to be cleared</param> public void ClearCheckCodeItems(List<Control> controlsList) { #region Input Validation if (controlsList == null) { //throw new ArgumentNullException("controlsList"); return; } #endregion //Input Validation //foreach (Panel panel in Panels) //{ foreach (Control control in controlsList) { //if (panel.Controls.Contains(control)) //{ if (control is TextBoxBase) { control.Text = string.Empty; } else if (control is CheckBox) { ((CheckBox)control).Checked = false; } else if (control is ComboBox) { ((ComboBox)control).SelectedIndex = -1; ((ComboBox)control).Text = string.Empty; }/* else { // do nothing for now }*/ //} } //} } /// <summary> /// Hide all the panels /// </summary> public void HideAll() { foreach (Control control in canvasPanel.Controls) { control.Visible = false; } } public void DesignerFocus() { canvasPanel.Focus(); } /// <summary> /// Sets the focus to a specific field /// </summary> /// <param name="controlsList">A list of controls to set the focus to</param> public void GoToField(List<Control> controlsList, Epi.Fields.Field field) { #region Input Validation if (controlsList == null) { throw new ArgumentNullException("ControlsList"); } #endregion //Input Validation for (int i = 0; i <= controlsList.Count - 1; i++) { if (!(controlsList[i] is Label)) { if (!currentPanel.Controls.Contains(controlsList[i])) { foreach (Panel panel in canvasPanel.Controls) { if (panel.Controls.Contains(controlsList[i])) { Control control = controlsList[i]; this.Invoke(new MethodInvoker(delegate() { SetFocusToControl(control, field); })); } } } else { Control control = controlsList[i]; this.Invoke(new MethodInvoker(delegate() { SetFocusToControl(control, field); })); } } } } /// <summary> /// Adds the autosearch results grid to the current panel /// </summary> /// <param name="dataGrid1">Auto search results grid</param> public void AddGridToPanel(DataGrid dataGrid1) { currentPanel.Controls.Add(dataGrid1); dataGrid1.BringToFront(); } /// <summary> /// Sets the focus to a given control. /// </summary> /// <param name="control">The control to focus on.</param> /// <param name="field">The field associated with the control.</param> public void SetFocusToControl(Control control, Field field) { #region Input Validation if (control == null) { throw new ArgumentNullException("Epi.Windows.Enter.SetFocusToControl control is null"); } if (field == null) { throw new ArgumentNullException("Epi.Windows.Enter.SetFocusToControl field is null"); } #endregion // Input Validation if (control.Focused && this.IsEventEnabled) { control_Enter(control, new EventArgs()); } else { control.Focus(); } if (control is MaskedTextBox) { ((MaskedTextBox)control).SelectAll(); } else if (control is TextBoxBase) { if (control is RichTextBox) { ((TextBoxBase)control).DeselectAll(); ((TextBoxBase)control).Select(control.Text.Length, 0); } else { if (control.Text.Length > 0) { ((TextBoxBase)control).SelectAll(); } else { ((TextBoxBase)control).SelectionStart = 0; } } } else if (control is ComboBox) { if (string.IsNullOrEmpty(((InputFieldWithSeparatePrompt)field).CurrentRecordValueString)) { ((ComboBox)control).SelectedIndex = -1; } else if (field is YesNoField) { if (((IDataField)field).CurrentRecordValueObject.ToString() == "1") { ((ComboBox)control).SelectedItem = config.Settings.RepresentationOfYes; ((ComboBox)control).Text = config.Settings.RepresentationOfYes; } else if (((IDataField)field).CurrentRecordValueObject.ToString() == "0") { ((ComboBox)control).SelectedItem = config.Settings.RepresentationOfNo; ((ComboBox)control).Text = config.Settings.RepresentationOfNo; } } else { string val = ((IDataField)field).CurrentRecordValueString; foreach (object item in ((ComboBox)control).Items) { if (item is String) { string[] parts = ((string)item).Split('-'); if (val == parts[0]) { ((ComboBox)control).Text = ((string)item); ((ComboBox)control).SelectedIndex = ((ComboBox)control).FindString(((string)item)); break; } } } } } } /// <summary> /// Sets the focus to the first input control on the current panel /// </summary> /// <param name="currentPage">The current page</param> /// <param name="currentPanel">The current panel</param> public void SetFocusToFirstControl(Page currentPage, Panel currentPanel) { #region Input Validation if (currentPage == null) { throw new ArgumentNullException("Epi.Windows.Enter.SetFocusToFirstControl currentPage is null"); } if (currentPanel == null) { throw new ArgumentNullException("Epi.Windows.Enter.SetFocusToFirstControl currentPanel is null"); } #endregion //Input Validation double minTabIndex = currentPage.GetMetadata().GetMinTabIndex(currentPage.Id, currentPage.GetView().Id); if (minTabIndex != -1) { foreach (Control control in currentPanel.Controls) { if (control is TextBox || control is RichTextBox || control is CheckBox || control is ComboBox || control is MaskedTextBox || control is Button) { Epi.Windows.Enter.PresentationLogic.ControlFactory factory = Epi.Windows.Enter.PresentationLogic.ControlFactory.Instance; Field field = factory.GetAssociatedField(control); ((RenderableField)field).Tag = ""; } } foreach (Control control in currentPanel.Controls) { if (control is TextBox || control is RichTextBox || control is CheckBox || control is ComboBox || control is MaskedTextBox || control is Button) { Epi.Windows.Enter.PresentationLogic.ControlFactory factory = Epi.Windows.Enter.PresentationLogic.ControlFactory.Instance; Field field = factory.GetAssociatedField(control); if (((RenderableField)field).TabIndex == minTabIndex) { if (control.Enabled) { // The problem with calling SetFocusToControl directly is that // later on, other controls steal the focus in ways that we // cannot control. This theft has unintended side-effects, e.g // running check code in ways that aren't desired, and/or the focus // doesn't actually get placed in the first field of the page in // some cases. By invoking the method, we pass it to the message queue // and it is run after the other focus-stealing events are called. // EK 12/7/2010 this.BeginInvoke(new MethodInvoker(delegate() { SetFocusToControl(control, field); })); ((RenderableField)field).Tag = "tabbed"; return; } else { GoToNextControl(currentPage, currentView, control); } } } } } } /// <summary> /// Sets the focus of the next control depending upon the tab index /// </summary> /// <param name="currentPage">The current page</param> /// <param name="currentView">The current panel</param> /// <param name="currentControl">The current control that is losing focus</param> public void GoToNextControl(Page currentPage, View currentView, Control currentControl) { #region Input Validation if (currentPage == null) { throw new ArgumentNullException("Current Page"); } if (currentPanel == null) { throw new ArgumentNullException("Current Panel"); } if (currentControl == null) { throw new ArgumentException("Control"); } #endregion //Input Validation Epi.Windows.Enter.PresentationLogic.ControlFactory factory = Epi.Windows.Enter.PresentationLogic.ControlFactory.Instance; Field currentField = factory.GetAssociatedField(currentControl); if (currentField == null) { return; } double currentTabIndex = ((RenderableField)currentField).TabIndex; double nextTabIndex = currentPage.GetMetadata().GetNextTabIndex(currentPage, currentView, currentTabIndex); double maxTabIndex = currentPage.GetMetadata().GetMaxTabIndex(currentPage.Id, currentView.Id, false); foreach (Control control in currentPanel.Controls) { if (control is TextBox || control is RichTextBox || control is CheckBox || control is ComboBox || control is Button || control is MaskedTextBox || control is GroupBox || control is DateTimePicker) { Field field = factory.GetAssociatedField(control); if (((RenderableField)field).TabIndex == nextTabIndex || ((RenderableField)field).TabIndex == currentTabIndex & control != currentControl & ((RenderableField)field).Tag == "") { if (!control.Visible || !control.Enabled) //if hidden by check code command or disabled due to read only property being set { if (control.TabIndex != maxTabIndex && currentView.CurrentRecordStatus != 0) { GoToNextControl(currentPage, currentView, control); } } ((RenderableField)field).Tag ="tabbed"; this.EnableTabToNextControl = false; if (control.Focused && this.IsEventEnabled) { control_Enter(control, new EventArgs()); } else if((control is GroupBox) == false) { control.Focus(); } if (control is TextBoxBase) { ((TextBoxBase)control).SelectAll(); } if ((control is TextBox || control is RichTextBox || control is ComboBox || control is MaskedTextBox || control is DateTimePicker) && (field is InputFieldWithSeparatePrompt)) { if (((InputFieldWithSeparatePrompt)field).IsRequired) { control.CausesValidation = true; } else { control.CausesValidation = false; } if (field is DateField) { if (((DateField)field).Upper.Length + ((DateField)field).Lower.Length > 0) { control.CausesValidation = true; } } } else if(control is GroupBox ) { control.Controls[0].Focus(); } this.EnableTabToNextControl = false; return; } } } } /// <summary> /// Updates current view's controls with config settings /// </summary> public void UpdateSettings() { //TODO Add other option settings as they pertain to the Enter module foreach (Panel panel in this.Panels) { foreach (Control control in panel.Controls) { if (control is ComboBox) { Epi.Windows.Enter.PresentationLogic.ControlFactory factory = Epi.Windows.Enter.PresentationLogic.ControlFactory.Instance; Field field = factory.GetAssociatedField(control); if (field is YesNoField) { DataTable dt = new DataTable(); dt.Columns.Add("name", typeof(string)); dt.Columns.Add("value", typeof(int)); DataRow dr; dr = dt.NewRow(); dr["name"] = config.Settings.RepresentationOfYes; dr["value"] = Constants.YES; dt.Rows.Add(dr); dr = dt.NewRow(); dr["name"] = config.Settings.RepresentationOfNo; dr["value"] = Constants.NO; dt.Rows.Add(dr); ((ComboBox)control).ValueMember = "value"; ((ComboBox)control).DisplayMember = "name"; ((ComboBox)control).DataSource = dt; } } } } } #endregion //Public Methods #region Private Methods #region Background management private void pnlDesigner_Resize(object sender, EventArgs e) { RedrawCanvasBackground(); } /// <summary> /// Handles the Mouse Down event of the panel /// </summary> /// <param name="sender">Object that fired the event</param> /// <param name="e">.NET supplied event parameters</param> void panel_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { for (int ix = ((Control)sender).Controls.Count - 1; ix >= 0; ix--) if (((Control)sender).Controls[ix] is MonthCalendar) { ((Control)sender).Controls[ix].Dispose(); ControlFactory factory = ControlFactory.Instance; factory.IsPopup = false; } this.Focus(); // needed to grab back focus for scroll-wheel effects } } private void mainForm_PageChanged(object sender, EventArgs e) { RedrawCanvasBackground(); } public void RedrawCanvasBackground() { SaveSnapshot(); DrawPicture(bufferGraphics); } private void SaveSnapshot() { if ((mainFrm.CurrentBackgroundImage==null) && (mainFrm.CurrentBackgroundColor.Equals(Color.Empty))) { canvasPanel.BackColor = Color.White; } else { canvasPanel.BackgroundImageLayout = ImageLayout.None; if (canvasPanel.Size.Width > 0 && canvasPanel.Size.Height > 0) { Bitmap b = new Bitmap(canvasPanel.Size.Width, canvasPanel.Size.Height); this.bufferGraphics = Graphics.FromImage(b); if(!(mainFrm.CurrentBackgroundColor.Equals(Color.Empty))) { canvasPanel.BackColor = mainFrm.CurrentBackgroundColor; } this.bufferGraphics.Clear(canvasPanel.BackColor); if (mainFrm.CurrentBackgroundImage != null ) { Image img = mainFrm.CurrentBackgroundImage; switch (mainFrm.CurrentBackgroundImageLayout.ToUpperInvariant()) { case "TILE": TextureBrush tileBrush = new TextureBrush(img, System.Drawing.Drawing2D.WrapMode.Tile); bufferGraphics.FillRectangle(tileBrush, 0, 0, canvasPanel.Size.Width, canvasPanel.Size.Height); tileBrush.Dispose(); break; case "STRETCH": bufferGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; bufferGraphics.DrawImage(img, 0, 0, canvasPanel.Size.Width, canvasPanel.Size.Height); bufferGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default; break; case "CENTER": int centerX = (canvasPanel.Size.Width / 2) - (img.Size.Width / 2); int centerY = (canvasPanel.Size.Height / 2) - (img.Size.Height / 2); bufferGraphics.DrawImage(img, centerX, centerY); break; default: bufferGraphics.DrawImage(img, 0, 0); break; } } bufferGraphics.DrawImage(b, 0, 0); bufferBitmap = b; canvasPanel.BackgroundImage = b; } } } private void DrawGrid(Bitmap b) { for (int y = 0; y < b.Height; y += config.Settings.GridSize * 10) { for (int x = 0; x < b.Width; x += config.Settings.GridSize * 10) { b.SetPixel(x, y, Color.Black); } } } private void DrawPicture(Graphics g) { if (bufferBitmap != null) { g.DrawImage(bufferBitmap, 0, 0); } } #endregion private Dictionary<int, object> repeatableFields; private Epi.Collections.NamedObjectCollection<IDataField> dataFields; public bool hasRepeatableFields = false; /// <summary> /// Clears all values in controls /// </summary> public void SetNewRecordValues() { foreach (IDataField dataField in this.currentView.Fields.DataFields) { if (dataField is GlobalRecordIdField) { ((GlobalRecordIdField)dataField).NewValue(); } else if (dataField is ForeignKeyField == false) { dataField.SetNewRecordValue(); } } foreach (GridField grid in currentView.Fields.GridFields) { grid.SetNewRecordValue(); } SetControlDefaults(); } /// <summary> /// Sets the default values for the controls on the panel /// </summary> private void SetControlDefaults() { foreach (Panel panel in this.Panels) { foreach (Control control in panel.Controls) { if (control is PictureBox) { (control as PictureBox).ImageLocation = string.Empty; } if (control is TextBox || control is RichTextBox || control is ComboBox || control is CheckBox || control is MaskedTextBox || control is DataGridView || control is GroupBox) { ControlFactory factory = ControlFactory.Instance; Field field = factory.GetAssociatedField(control); if (field is GUIDField) { control.Text = ((GUIDField)field).NewGuid().ToString(); SetTextData(field, control); } else if (field is IDataField || field is MirrorField || field is OptionField) { if (control is CheckBox) { ((CheckBox)control).Checked = false; } else if (control is ComboBox) { ((ComboBox)control).Text = string.Empty; ((ComboBox)control).SelectedIndex = -1; ((ComboBox)control).SelectedIndex = -1; // necessary to prevent an odd occurrence of values being pre-populated into new records with Yes/No fields. See defect #221. TODO: Re-investigate later why this is the case and why two of these commands must be issued. } else if (control is GroupBox) { foreach (Control ofGroupBox in control.Controls) { if (ofGroupBox is RadioButton) { ((RadioButton)ofGroupBox).Checked = false; } } } else { control.Text = string.Empty; } } else if (field is GridField) { ((GridField)field).DataSource = null; GetDataGridViewData(field, control); ((GridField)field).DataSource.Clear(); } } } } } #endregion public void DrawRequiredBorder(Control pValue) { /**/ // The parents that'll draw the borders for their children HashSet<Control> parents = new HashSet<Control>(); // The controls' types that you want to apply the new border on them List<Type> controlsThatHaveBorder = new List<Type> { typeof(TextBox), typeof(ComboBox), typeof(Epi.Windows.Enter.Controls.LegalValuesComboBox) }; parents.Add(pValue.Parent); foreach (var parent in parents) { parent.Paint += (sender, e) => { if (pValue.Parent != sender || pValue is Epi.Windows.Controls.TransparentLabel) return; // Create the border's bounds var bounds = pValue.Bounds; var activeCountrolBounds = new Rectangle(bounds.X - 1, bounds.Y - 1, bounds.Width + 1, bounds.Height + 1); // Draw the border... ((Control)sender).CreateGraphics().DrawRectangle(Pens.IndianRed, activeCountrolBounds); }; } } public void UnDrawRequiredBorder(Control pValue) { if (pValue is Epi.Windows.Controls.TransparentLabel) { return; } // Create the border's bounds var bounds = pValue.Bounds; var activeCountrolBounds = new Rectangle(bounds.X - 1, bounds.Y - 1, bounds.Width + 1, bounds.Height + 1); // Draw the border... this.CreateGraphics().DrawRectangle(Pens.White, activeCountrolBounds); /* // The parents that'll draw the borders for their children HashSet<Control> parents = new HashSet<Control>(); // The controls' types that you want to apply the new border on them List<Type> controlsThatHaveBorder = new List<Type> { typeof(TextBox), typeof(ComboBox), typeof(Epi.Windows.Enter.Controls.LegalValuesComboBox) }; parents.Add(pValue.Parent); foreach (var parent in parents) { parent.Paint += (sender, e) => { if (pValue.Parent != sender || pValue is Epi.Windows.Controls.TransparentLabel) return; // Create the border's bounds Rectangle bounds = pValue.Bounds; Rectangle activeCountrolBounds = new Rectangle(bounds.X - 1, bounds.Y - 1, bounds.Width + 1, bounds.Height + 1); // Draw the border... ((Control)sender).CreateGraphics().DrawRectangle(Pens.White, activeCountrolBounds); }; }*/ } void DrawBorderRect(object sender, System.Windows.Forms.PaintEventArgs e) { Panel panel = ((Panel)sender); Control.ControlCollection cc = panel.Controls; foreach (Control control in cc) { if (control is Epi.Windows.Controls.TransparentLabel || control is Epi.Windows.Controls.FieldGroupBox) { continue; } Field f = ControlFactory.Instance.GetAssociatedField(control); if (f is InputFieldWithSeparatePrompt) { InputFieldWithSeparatePrompt field = (InputFieldWithSeparatePrompt)f; Graphics g = e.Graphics; var bounds = control.Bounds; var activeCountrolBounds = new Rectangle(bounds.X - 1, bounds.Y - 1, bounds.Width + 1, bounds.Height + 1); // Draw the border... if (field.IsRequired == true) { g.DrawRectangle(Pens.Goldenrod, activeCountrolBounds); } else { g.DrawRectangle(Pens.White, activeCountrolBounds); } } }; } public void DrawBorderRect(Control control) { if (control is Epi.Windows.Controls.TransparentLabel || control is Epi.Windows.Controls.FieldGroupBox) { return; } Field associatedField = ControlFactory.Instance.GetAssociatedField(control); if (associatedField is InputFieldWithSeparatePrompt) { InputFieldWithSeparatePrompt field = (InputFieldWithSeparatePrompt)associatedField; var bounds = control.Bounds; var activeCountrolBounds = new Rectangle(bounds.X - 1, bounds.Y - 1, bounds.Width + 1, bounds.Height + 1); Graphics graphics = ((Control)Panels[0]).CreateGraphics(); if (field.IsRequired == true) { graphics.DrawRectangle(Pens.Goldenrod, activeCountrolBounds); } else { graphics.DrawRectangle(Pens.White, activeCountrolBounds); } } } } }
namespace Nancy.Testing { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Nancy.Bootstrapper; using Nancy.Helpers; using IO; /// <summary> /// Provides the capability of executing a request with Nancy, using a specific configuration provided by an <see cref="INancyBootstrapper"/> instance. /// </summary> public class Browser : IHideObjectMembers { private readonly Action<BrowserContext> defaultBrowserContext; private readonly INancyBootstrapper bootstrapper; private readonly INancyEngine engine; private readonly IDictionary<string, string> cookies = new Dictionary<string, string>(); /// <summary> /// Initializes a new instance of the <see cref="Browser"/> class, with the /// provided <see cref="ConfigurableBootstrapper"/> configuration. /// </summary> /// <param name="action">The <see cref="ConfigurableBootstrapper"/> configuration that should be used by the bootstrapper.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> public Browser(Action<ConfigurableBootstrapper.ConfigurableBootstrapperConfigurator> action, Action<BrowserContext> defaults = null) : this(new ConfigurableBootstrapper(action), defaults) { } /// <summary> /// Initializes a new instance of the <see cref="Browser"/> class. /// </summary> /// <param name="bootstrapper">A <see cref="INancyBootstrapper"/> instance that determines the Nancy configuration that should be used by the browser.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> public Browser(INancyBootstrapper bootstrapper, Action<BrowserContext> defaults = null) { this.bootstrapper = bootstrapper; this.bootstrapper.Initialise(); this.engine = this.bootstrapper.GetEngine(); this.defaultBrowserContext = defaults ?? this.DefaultBrowserContext; } /// <summary> /// Performs a DELETE request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Delete(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("DELETE", path, browserContext); } /// <summary> /// Performs a DELETE request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Delete(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("DELETE", url, browserContext); } /// <summary> /// Performs a GET request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Get(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("GET", path, browserContext); } /// <summary> /// Performs a GET request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Get(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("GET", url, browserContext); } /// <summary> /// Performs a HEAD request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Head(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("HEAD", path, browserContext); } /// <summary> /// Performs a HEAD request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Head(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("HEAD", url, browserContext); } /// <summary> /// Performs a OPTIONS request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Options(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("OPTIONS", path, browserContext); } /// <summary> /// Performs a OPTIONS request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Options(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("OPTIONS", url, browserContext); } /// <summary> /// Performs a PATCH request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Patch(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PATCH", path, browserContext); } /// <summary> /// Performs a PATCH request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Patch(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PATCH", url, browserContext); } /// <summary> /// Performs a POST request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Post(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("POST", path, browserContext); } /// <summary> /// Performs a POST request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Post(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("POST", url, browserContext); } /// <summary> /// Performs a PUT request against Nancy. /// </summary> /// <param name="path">The path that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Put(string path, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PUT", path, browserContext); } /// <summary> /// Performs a PUT request against Nancy. /// </summary> /// <param name="url">The url that is being requested.</param> /// <param name="browserContext">An closure for providing browser context for the request.</param> /// <returns>An <see cref="BrowserResponse"/> instance of the executed request.</returns> public BrowserResponse Put(Url url, Action<BrowserContext> browserContext = null) { return this.HandleRequest("PUT", url, browserContext); } private BrowserResponse HandleRequest(string method, Url url, Action<BrowserContext> browserContext) { var request = CreateRequest(method, url, browserContext ?? (with => {})); var response = new BrowserResponse(this.engine.HandleRequest(request), this); this.CaptureCookies(response); return response; } private BrowserResponse HandleRequest(string method, string path, Action<BrowserContext> browserContext) { var url = Uri.IsWellFormedUriString(path, UriKind.Relative) ? new Url {Path = path} : (Url)new Uri(path); return HandleRequest(method, url, browserContext); } private void DefaultBrowserContext(BrowserContext context) { context.HttpRequest(); } private void SetCookies(BrowserContext context) { if (!this.cookies.Any()) { return; } var cookieString = this.cookies.Aggregate(string.Empty, (current, cookie) => current + string.Format("{0}={1};", HttpUtility.UrlEncode(cookie.Key), HttpUtility.UrlEncode(cookie.Value))); context.Header("Cookie", cookieString); } private void CaptureCookies(BrowserResponse response) { if (response.Cookies == null || !response.Cookies.Any()) { return; } foreach (var cookie in response.Cookies) { if (string.IsNullOrEmpty(cookie.Value)) { this.cookies.Remove(cookie.Name); } else { this.cookies[cookie.Name] = cookie.Value; } } } private static void BuildRequestBody(IBrowserContextValues contextValues) { if (contextValues.Body != null) { return; } var useFormValues = !String.IsNullOrEmpty(contextValues.FormValues); var bodyContents = useFormValues ? contextValues.FormValues : contextValues.BodyString; var bodyBytes = bodyContents != null ? Encoding.UTF8.GetBytes(bodyContents) : new byte[] { }; if (useFormValues && !contextValues.Headers.ContainsKey("Content-Type")) { contextValues.Headers["Content-Type"] = new[] { "application/x-www-form-urlencoded" }; } contextValues.Body = new MemoryStream(bodyBytes); } private Request CreateRequest(string method, Url url, Action<BrowserContext> browserContext) { var context = new BrowserContext(); this.SetCookies(context); defaultBrowserContext.Invoke(context); browserContext.Invoke(context); var contextValues = (IBrowserContextValues)context; BuildRequestBody(contextValues); var requestStream = RequestStream.FromStream(contextValues.Body, 0, true); var certBytes = (contextValues.ClientCertificate == null) ? new byte[] { } : contextValues.ClientCertificate.GetRawCertData(); var requestUrl = url; requestUrl.Scheme = string.IsNullOrWhiteSpace(contextValues.Protocol) ? requestUrl.Scheme : contextValues.Protocol; requestUrl.HostName = string.IsNullOrWhiteSpace(contextValues.HostName) ? requestUrl.HostName : contextValues.HostName; requestUrl.Query = string.IsNullOrWhiteSpace(url.Query) ? (contextValues.QueryString ?? string.Empty) : url.Query; return new Request(method, requestUrl, requestStream, contextValues.Headers, contextValues.UserHostAddress, certBytes); } } }
using System; using System.Linq; using System.Reflection; using System.Text; using AnyOfTypes; using JetBrains.Annotations; using Newtonsoft.Json.Linq; using WireMock.Exceptions; using WireMock.Extensions; using WireMock.Models; using Stef.Validation; namespace WireMock.Matchers { /// <summary> /// CSharpCode / CS-Script Matcher /// </summary> /// <inheritdoc cref="ICSharpCodeMatcher"/> internal class CSharpCodeMatcher : ICSharpCodeMatcher { private const string TemplateForIsMatchWithString = "public class CodeHelper {{ public bool IsMatch(string it) {{ {0} }} }}"; private const string TemplateForIsMatchWithDynamic = "public class CodeHelper {{ public bool IsMatch(dynamic it) {{ {0} }} }}"; private readonly string[] _usings = { "System", "System.Linq", "System.Collections.Generic", "Microsoft.CSharp", "Newtonsoft.Json.Linq" }; public MatchBehaviour MatchBehaviour { get; } /// <inheritdoc cref="IMatcher.ThrowException"/> public bool ThrowException { get; } private readonly AnyOf<string, StringPattern>[] _patterns; /// <summary> /// Initializes a new instance of the <see cref="CSharpCodeMatcher"/> class. /// </summary> /// <param name="patterns">The patterns.</param> public CSharpCodeMatcher([NotNull] params AnyOf<string, StringPattern>[] patterns) : this(MatchBehaviour.AcceptOnMatch, patterns) { } /// <summary> /// Initializes a new instance of the <see cref="CSharpCodeMatcher"/> class. /// </summary> /// <param name="matchBehaviour">The match behaviour.</param> /// <param name="patterns">The patterns.</param> public CSharpCodeMatcher(MatchBehaviour matchBehaviour, [NotNull] params AnyOf<string, StringPattern>[] patterns) { Guard.NotNull(patterns, nameof(patterns)); MatchBehaviour = matchBehaviour; ThrowException = false; _patterns = patterns; } public double IsMatch(string input) { return IsMatchInternal(input); } public double IsMatch(object input) { return IsMatchInternal(input); } public double IsMatchInternal(object input) { double match = MatchScores.Mismatch; if (input != null) { match = MatchScores.ToScore(_patterns.Select(pattern => IsMatch(input, pattern.GetPattern()))); } return MatchBehaviourHelper.Convert(MatchBehaviour, match); } private bool IsMatch(dynamic input, string pattern) { bool isMatchWithString = input is string; var inputValue = isMatchWithString ? input : JObject.FromObject(input); string source = GetSourceForIsMatchWithString(pattern, isMatchWithString); object result = null; #if (NET451 || NET452) var compilerParams = new System.CodeDom.Compiler.CompilerParameters { GenerateInMemory = true, GenerateExecutable = false, ReferencedAssemblies = { "System.dll", "System.Core.dll", "Microsoft.CSharp.dll", "Newtonsoft.Json.dll" } }; using (var codeProvider = new Microsoft.CSharp.CSharpCodeProvider()) { var compilerResults = codeProvider.CompileAssemblyFromSource(compilerParams, source); if (compilerResults.Errors.Count != 0) { var errors = from System.CodeDom.Compiler.CompilerError er in compilerResults.Errors select er.ToString(); throw new WireMockException(string.Join(", ", errors)); } object helper = compilerResults.CompiledAssembly.CreateInstance("CodeHelper"); if (helper == null) { throw new WireMockException("CSharpCodeMatcher: Unable to create instance from WireMock.CodeHelper"); } var methodInfo = helper.GetType().GetMethod("IsMatch"); if (methodInfo == null) { throw new WireMockException("CSharpCodeMatcher: Unable to find method 'IsMatch' in WireMock.CodeHelper"); } try { result = methodInfo.Invoke(helper, new[] { inputValue }); } catch (Exception ex) { throw new WireMockException("CSharpCodeMatcher: Unable to call method 'IsMatch' in WireMock.CodeHelper", ex); } } #elif (NET46 || NET461) dynamic script; try { script = CSScriptLibrary.CSScript.Evaluator.CompileCode(source).CreateObject("*"); } catch (Exception ex) { throw new WireMockException("CSharpCodeMatcher: Unable to create compiler for WireMock.CodeHelper", ex); } try { result = script.IsMatch(inputValue); } catch (Exception ex) { throw new WireMockException("CSharpCodeMatcher: Problem calling method 'IsMatch' in WireMock.CodeHelper", ex); } #elif (NETSTANDARD2_0 || NETSTANDARD2_1 || NETCOREAPP3_1 || NET5_0 || NET6_0) Assembly assembly; try { assembly = CSScriptLib.CSScript.Evaluator.CompileCode(source); } catch (Exception ex) { throw new WireMockException($"CSharpCodeMatcher: Unable to compile code `{source}` for WireMock.CodeHelper", ex); } dynamic script; try { //#if NETSTANDARD2_0 // script = csscript.GenericExtensions.CreateObject(assembly, "*"); //#else script = CSScripting.ReflectionExtensions.CreateObject(assembly, "*"); //#endif } catch (Exception ex) { throw new WireMockException("CSharpCodeMatcher: Unable to create object from assembly", ex); } try { result = script.IsMatch(inputValue); } catch (Exception ex) { throw new WireMockException("CSharpCodeMatcher: Problem calling method 'IsMatch' in WireMock.CodeHelper", ex); } #else throw new NotSupportedException("The 'CSharpCodeMatcher' cannot be used in netstandard 1.3"); #endif try { return (bool)result; } catch { throw new WireMockException($"Unable to cast result '{result}' to bool"); } } private string GetSourceForIsMatchWithString(string pattern, bool isMatchWithString) { string template = isMatchWithString ? TemplateForIsMatchWithString : TemplateForIsMatchWithDynamic; var stringBuilder = new StringBuilder(); foreach (string @using in _usings) { stringBuilder.AppendLine($"using {@using};"); } stringBuilder.AppendLine(); stringBuilder.AppendFormat(template, pattern); return stringBuilder.ToString(); } /// <inheritdoc cref="IStringMatcher.GetPatterns"/> public AnyOf<string, StringPattern>[] GetPatterns() { return _patterns; } /// <inheritdoc cref="IMatcher.Name"/> public string Name => "CSharpCodeMatcher"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Internal.TypeSystem; namespace Internal.TypeSystem.Ecma { public partial class EcmaModule : ModuleDesc { private PEReader _peReader; protected MetadataReader _metadataReader; internal interface IEntityHandleObject { EntityHandle Handle { get; } } private sealed class EcmaObjectLookupWrapper : IEntityHandleObject { private EntityHandle _handle; private object _obj; public EcmaObjectLookupWrapper(EntityHandle handle, object obj) { _obj = obj; _handle = handle; } public EntityHandle Handle { get { return _handle; } } public object Object { get { return _obj; } } } internal class EcmaObjectLookupHashtable : LockFreeReaderHashtable<EntityHandle, IEntityHandleObject> { private EcmaModule _module; public EcmaObjectLookupHashtable(EcmaModule module) { _module = module; } protected override int GetKeyHashCode(EntityHandle key) { return key.GetHashCode(); } protected override int GetValueHashCode(IEntityHandleObject value) { return value.Handle.GetHashCode(); } protected override bool CompareKeyToValue(EntityHandle key, IEntityHandleObject value) { return key.Equals(value.Handle); } protected override bool CompareValueToValue(IEntityHandleObject value1, IEntityHandleObject value2) { if (Object.ReferenceEquals(value1, value2)) return true; else return value1.Handle.Equals(value2.Handle); } protected override IEntityHandleObject CreateValueFromKey(EntityHandle handle) { object item; switch (handle.Kind) { case HandleKind.TypeDefinition: item = new EcmaType(_module, (TypeDefinitionHandle)handle); break; case HandleKind.MethodDefinition: { MethodDefinitionHandle methodDefinitionHandle = (MethodDefinitionHandle)handle; TypeDefinitionHandle typeDefinitionHandle = _module._metadataReader.GetMethodDefinition(methodDefinitionHandle).GetDeclaringType(); EcmaType type = (EcmaType)_module.GetObject(typeDefinitionHandle); item = new EcmaMethod(type, methodDefinitionHandle); } break; case HandleKind.FieldDefinition: { FieldDefinitionHandle fieldDefinitionHandle = (FieldDefinitionHandle)handle; TypeDefinitionHandle typeDefinitionHandle = _module._metadataReader.GetFieldDefinition(fieldDefinitionHandle).GetDeclaringType(); EcmaType type = (EcmaType)_module.GetObject(typeDefinitionHandle); item = new EcmaField(type, fieldDefinitionHandle); } break; case HandleKind.TypeReference: item = _module.ResolveTypeReference((TypeReferenceHandle)handle); break; case HandleKind.MemberReference: item = _module.ResolveMemberReference((MemberReferenceHandle)handle); break; case HandleKind.AssemblyReference: item = _module.ResolveAssemblyReference((AssemblyReferenceHandle)handle); break; case HandleKind.TypeSpecification: item = _module.ResolveTypeSpecification((TypeSpecificationHandle)handle); break; case HandleKind.MethodSpecification: item = _module.ResolveMethodSpecification((MethodSpecificationHandle)handle); break; case HandleKind.ExportedType: item = _module.ResolveExportedType((ExportedTypeHandle)handle); break; case HandleKind.StandaloneSignature: item = _module.ResolveStandaloneSignature((StandaloneSignatureHandle)handle); break; case HandleKind.ModuleDefinition: // ECMA-335 Partition 2 II.22.38 1d: This should not occur in a CLI ("compressed metadata") module, // but resolves to "current module". item = _module; break; default: throw new BadImageFormatException("Unknown metadata token type: " + handle.Kind); } switch (handle.Kind) { case HandleKind.TypeDefinition: case HandleKind.MethodDefinition: case HandleKind.FieldDefinition: // type/method/field definitions directly correspond to their target item. return (IEntityHandleObject)item; default: // Everything else is some form of reference which cannot be self-describing return new EcmaObjectLookupWrapper(handle, item); } } } private LockFreeReaderHashtable<EntityHandle, IEntityHandleObject> _resolvedTokens; internal EcmaModule(TypeSystemContext context, PEReader peReader, MetadataReader metadataReader) : base(context) { _peReader = peReader; _metadataReader = metadataReader; _resolvedTokens = new EcmaObjectLookupHashtable(this); } public static EcmaModule Create(TypeSystemContext context, PEReader peReader) { MetadataReader metadataReader = CreateMetadataReader(context, peReader); if (metadataReader.IsAssembly) return new EcmaAssembly(context, peReader, metadataReader); else return new EcmaModule(context, peReader, metadataReader); } private static MetadataReader CreateMetadataReader(TypeSystemContext context, PEReader peReader) { if (!peReader.HasMetadata) { ThrowHelper.ThrowBadImageFormatException(); } var stringDecoderProvider = context as IMetadataStringDecoderProvider; MetadataReader metadataReader = peReader.GetMetadataReader(MetadataReaderOptions.None /* MetadataReaderOptions.ApplyWindowsRuntimeProjections */, (stringDecoderProvider != null) ? stringDecoderProvider.GetMetadataStringDecoder() : null); return metadataReader; } public PEReader PEReader { get { return _peReader; } } public MetadataReader MetadataReader { get { return _metadataReader; } } /// <summary> /// Gets the managed entrypoint method of this module or null if the module has no managed entrypoint. /// </summary> public MethodDesc EntryPoint { get { CorHeader corHeader = _peReader.PEHeaders.CorHeader; if ((corHeader.Flags & CorFlags.NativeEntryPoint) != 0) { // Entrypoint is an RVA to an unmanaged method return null; } int entryPointToken = corHeader.EntryPointTokenOrRelativeVirtualAddress; if (entryPointToken == 0) { // No entrypoint return null; } EntityHandle handle = MetadataTokens.EntityHandle(entryPointToken); if (handle.Kind == HandleKind.MethodDefinition) { return GetMethod(handle); } else if (handle.Kind == HandleKind.AssemblyFile) { // Entrypoint not in the manifest assembly throw new NotImplementedException(); } // Bad metadata throw new BadImageFormatException(); } } public sealed override MetadataType GetType(string nameSpace, string name, bool throwIfNotFound = true) { var stringComparer = _metadataReader.StringComparer; // TODO: More efficient implementation? foreach (var typeDefinitionHandle in _metadataReader.TypeDefinitions) { var typeDefinition = _metadataReader.GetTypeDefinition(typeDefinitionHandle); if (stringComparer.Equals(typeDefinition.Name, name) && stringComparer.Equals(typeDefinition.Namespace, nameSpace)) { return (MetadataType)GetType((EntityHandle)typeDefinitionHandle); } } foreach (var exportedTypeHandle in _metadataReader.ExportedTypes) { var exportedType = _metadataReader.GetExportedType(exportedTypeHandle); if (stringComparer.Equals(exportedType.Name, name) && stringComparer.Equals(exportedType.Namespace, nameSpace)) { if (exportedType.IsForwarder) { Object implementation = GetObject(exportedType.Implementation); if (implementation is ModuleDesc) { return ((ModuleDesc)(implementation)).GetType(nameSpace, name); } // TODO throw new NotImplementedException(); } // TODO: throw new NotImplementedException(); } } if (throwIfNotFound) ThrowHelper.ThrowTypeLoadException(nameSpace, name, this); return null; } public TypeDesc GetType(EntityHandle handle) { TypeDesc type = GetObject(handle) as TypeDesc; if (type == null) throw new BadImageFormatException("Type expected"); return type; } public MethodDesc GetMethod(EntityHandle handle) { MethodDesc method = GetObject(handle) as MethodDesc; if (method == null) throw new BadImageFormatException("Method expected"); return method; } public FieldDesc GetField(EntityHandle handle) { FieldDesc field = GetObject(handle) as FieldDesc; if (field == null) throw new BadImageFormatException("Field expected"); return field; } public Object GetObject(EntityHandle handle) { IEntityHandleObject obj = _resolvedTokens.GetOrCreateValue(handle); if (obj is EcmaObjectLookupWrapper) { return ((EcmaObjectLookupWrapper)obj).Object; } else { return obj; } } private Object ResolveMethodSpecification(MethodSpecificationHandle handle) { MethodSpecification methodSpecification = _metadataReader.GetMethodSpecification(handle); MethodDesc methodDef = GetMethod(methodSpecification.Method); BlobReader signatureReader = _metadataReader.GetBlobReader(methodSpecification.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader); TypeDesc[] instantiation = parser.ParseMethodSpecSignature(); return Context.GetInstantiatedMethod(methodDef, new Instantiation(instantiation)); } private Object ResolveStandaloneSignature(StandaloneSignatureHandle handle) { StandaloneSignature signature = _metadataReader.GetStandaloneSignature(handle); BlobReader signatureReader = _metadataReader.GetBlobReader(signature.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader); MethodSignature methodSig = parser.ParseMethodSignature(); return methodSig; } private Object ResolveTypeSpecification(TypeSpecificationHandle handle) { TypeSpecification typeSpecification = _metadataReader.GetTypeSpecification(handle); BlobReader signatureReader = _metadataReader.GetBlobReader(typeSpecification.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader); return parser.ParseType(); } private Object ResolveMemberReference(MemberReferenceHandle handle) { MemberReference memberReference = _metadataReader.GetMemberReference(handle); Object parent = GetObject(memberReference.Parent); TypeDesc parentTypeDesc = parent as TypeDesc; if (parentTypeDesc != null) { BlobReader signatureReader = _metadataReader.GetBlobReader(memberReference.Signature); EcmaSignatureParser parser = new EcmaSignatureParser(this, signatureReader); string name = _metadataReader.GetString(memberReference.Name); if (parser.IsFieldSignature) { FieldDesc field = parentTypeDesc.GetField(name); if (field != null) return field; ThrowHelper.ThrowMissingFieldException(parentTypeDesc, name); } else { MethodSignature sig = parser.ParseMethodSignature(); TypeDesc typeDescToInspect = parentTypeDesc; // Try to resolve the name and signature in the current type, or any of the base types. do { // TODO: handle substitutions MethodDesc method = typeDescToInspect.GetMethod(name, sig); if (method != null) { // If this resolved to one of the base types, make sure it's not a constructor. // Instance constructors are not inherited. if (typeDescToInspect != parentTypeDesc && method.IsConstructor) break; return method; } typeDescToInspect = typeDescToInspect.BaseType; } while (typeDescToInspect != null); ThrowHelper.ThrowMissingMethodException(parentTypeDesc, name, sig); } } else if (parent is MethodDesc) { ThrowHelper.ThrowInvalidProgramException(ExceptionStringID.InvalidProgramVararg, (MethodDesc)parent); } else if (parent is ModuleDesc) { throw new NotImplementedException("MemberRef to a global function or variable."); } throw new BadImageFormatException(); } private Object ResolveTypeReference(TypeReferenceHandle handle) { TypeReference typeReference = _metadataReader.GetTypeReference(handle); Object resolutionScope = GetObject(typeReference.ResolutionScope); if (resolutionScope is ModuleDesc) { return ((ModuleDesc)(resolutionScope)).GetType(_metadataReader.GetString(typeReference.Namespace), _metadataReader.GetString(typeReference.Name)); } else if (resolutionScope is MetadataType) { string typeName = _metadataReader.GetString(typeReference.Name); if (!typeReference.Namespace.IsNil) typeName = _metadataReader.GetString(typeReference.Namespace) + "." + typeName; MetadataType result = ((MetadataType)(resolutionScope)).GetNestedType(typeName); if (result != null) return result; ThrowHelper.ThrowTypeLoadException(typeName, ((MetadataType)resolutionScope).Module); } // TODO throw new NotImplementedException(); } private Object ResolveAssemblyReference(AssemblyReferenceHandle handle) { AssemblyReference assemblyReference = _metadataReader.GetAssemblyReference(handle); AssemblyName an = new AssemblyName(); an.Name = _metadataReader.GetString(assemblyReference.Name); an.Version = assemblyReference.Version; var publicKeyOrToken = _metadataReader.GetBlobBytes(assemblyReference.PublicKeyOrToken); if ((assemblyReference.Flags & AssemblyFlags.PublicKey) != 0) { an.SetPublicKey(publicKeyOrToken); } else { an.SetPublicKeyToken(publicKeyOrToken); } an.CultureName = _metadataReader.GetString(assemblyReference.Culture); an.ContentType = GetContentTypeFromAssemblyFlags(assemblyReference.Flags); return Context.ResolveAssembly(an); } private Object ResolveExportedType(ExportedTypeHandle handle) { ExportedType exportedType = _metadataReader.GetExportedType(handle); var implementation = GetObject(exportedType.Implementation); if (implementation is ModuleDesc) { var module = (ModuleDesc)implementation; string nameSpace = _metadataReader.GetString(exportedType.Namespace); string name = _metadataReader.GetString(exportedType.Name); return module.GetType(nameSpace, name); } else if (implementation is MetadataType) { var type = (MetadataType)implementation; string name = _metadataReader.GetString(exportedType.Name); var nestedType = type.GetNestedType(name); if (nestedType == null) ThrowHelper.ThrowTypeLoadException(name, this); return nestedType; } else { throw new BadImageFormatException("Unknown metadata token type for exported type"); } } public sealed override IEnumerable<MetadataType> GetAllTypes() { foreach (var typeDefinitionHandle in _metadataReader.TypeDefinitions) { yield return (MetadataType)GetType(typeDefinitionHandle); } } public sealed override MetadataType GetGlobalModuleType() { int typeDefinitionsCount = _metadataReader.TypeDefinitions.Count; if (typeDefinitionsCount == 0) return null; return (MetadataType)GetType(MetadataTokens.EntityHandle(0x02000001 /* COR_GLOBAL_PARENT_TOKEN */)); } protected static AssemblyContentType GetContentTypeFromAssemblyFlags(AssemblyFlags flags) { return (AssemblyContentType)(((int)flags & 0x0E00) >> 9); } public string GetUserString(UserStringHandle userStringHandle) { // String literals are not cached return _metadataReader.GetUserString(userStringHandle); } public override string ToString() { ModuleDefinition moduleDefinition = _metadataReader.GetModuleDefinition(); return _metadataReader.GetString(moduleDefinition.Name); } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.Drawing.Drawing2D; using System.ComponentModel; namespace UWOLMaps { public class LevelViewer : Panel { public LevelViewer() { this.DoubleBuffered = true; } private int zoomFactor = 2; public int ZoomFactor { get { return zoomFactor; } set { zoomFactor = value; } } private Image tileMap; public Image TileMap { get { return tileMap; } set { tileMap = value; } } private Level level; [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)] public Level Level { get { return level; } set { level = value; } } private Dictionary<string, Image> imageList; public Dictionary<string, Image> ImageList { get { return imageList; } set { imageList = value; } } private Version version; public Version Version { get { return version; } set { version = value; } } private Color gridColor; public Color GridColor { get { return gridColor; } set { gridColor = value; this.Invalidate(); } } private bool showGrid; public bool ShowGrid { get { return showGrid; } set { showGrid = value; } } private bool showArrows; public bool ShowArrows { get { return showArrows; } set { showArrows = value; } } protected override void OnPaintBackground(PaintEventArgs e) { // base.OnPaintBackground(e); e.Graphics.FillRectangle(Brushes.Black, this.ClientRectangle); } protected override void OnPaint(PaintEventArgs e) { drawLevel(e.Graphics, true); } private void drawLevel(Graphics graphics, bool grid) { graphics.InterpolationMode = InterpolationMode.NearestNeighbor; if (level != null && imageList != null) { TilesFondo tilFondo = level.TileFondo; int tilWidth = 32; int tilHeight = 32; Rectangle srcRect = new Rectangle(0, 0, 16, 16); Rectangle destRect = new Rectangle(0, 0, 33, 33); for (int iFila = 0; iFila < 10; iFila++) { for (int iCol = 0; iCol < 12; iCol++) { graphics.DrawImage(this.imageList[version.CPU.ToString() + tilFondo.ToString()], destRect, srcRect, GraphicsUnit.Pixel); destRect.X += tilWidth; } destRect.X = 0; destRect.Y += tilHeight; } drawPlatforms(graphics, tilWidth, tilHeight, ref srcRect, ref destRect); drawCoins(graphics, tilWidth, tilHeight, ref srcRect, ref destRect); drawEnemies(graphics, tilWidth, tilHeight, ref srcRect, ref destRect); if (grid && this.showGrid) { drawGrid(graphics, tilWidth, tilHeight); } } } private void drawGrid(Graphics graphics, int tilWidth, int tilHeight) { int x, y; SolidBrush br = new SolidBrush(this.gridColor); Pen currentPen = new Pen(br, 1); currentPen.DashStyle = DashStyle.Dash; y = 0; for (int iFila = 0; iFila < 11; iFila++) { graphics.DrawLine(currentPen, 0, y, this.Width, y); y += tilHeight; } x = 0; for (int iCol = 0; iCol < 12; iCol++) { graphics.DrawLine(currentPen, x, 0, x, this.Height); x += tilWidth; } } private void drawPlatforms(Graphics graphics, int tilWidth, int tilHeight, ref Rectangle srcRect, ref Rectangle destRect) { Rectangle shadowRect = new Rectangle(0, 0, 33, 33); foreach (Plataforma obj in this.level.Plataformas) { if (obj != null) { destRect = new Rectangle(obj.X * tilWidth, obj.Y * tilHeight, 33, 33); if (obj.X == 0) { shadowRect.X = 0; shadowRect.Y = destRect.Y + 16; graphics.DrawImage(this.imageList[version.CPU.ToString() + "s" + this.level.TileFondo.ToString()], shadowRect, srcRect, GraphicsUnit.Pixel); } for (int iPos = 0; iPos < obj.Longitud; iPos++) { shadowRect.X = destRect.X + 16; shadowRect.Y = destRect.Y + 16; graphics.DrawImage(this.imageList[version.CPU.ToString() + "s" + this.level.TileFondo.ToString()], shadowRect, srcRect, GraphicsUnit.Pixel); graphics.DrawImage(this.imageList[version.CPU.ToString() + obj.TipoPlataforma.ToString()], destRect, srcRect, GraphicsUnit.Pixel); if (obj.Direccion == Direccion.Horizontal) { destRect.X += tilWidth; } else { destRect.Y += tilHeight; } } } } } private void drawCoins(Graphics graphics, int tilWidth, int tilHeight, ref Rectangle srcRect, ref Rectangle destRect) { foreach (Moneda moneda in this.level.Monedas) { if (moneda != null) { destRect = new Rectangle(moneda.X * tilWidth, moneda.Y * tilHeight, 33, 33); if (version.CPU == CPUVersion.ZX) { graphics.DrawImage(this.ImageList[version.CPU.ToString() + "Moneda" + level.TileFondo.ToString()], destRect, srcRect, GraphicsUnit.Pixel); } else { graphics.DrawImage(this.ImageList[version.CPU.ToString() + "Moneda"], destRect, srcRect, GraphicsUnit.Pixel); } } } } private void drawEnemies(Graphics graphics, int tilWidth, int tilHeight, ref Rectangle srcRect, ref Rectangle destRect) { Pen arrowPen = new Pen(Color.FromArgb(192, 255, 32, 32), 5.0f); arrowPen.EndCap = LineCap.ArrowAnchor; arrowPen.StartCap = LineCap.ArrowAnchor; foreach (Enemigo enemigo in this.level.Enemigos) { if (enemigo != null) { if (this.showArrows) { int arrowY = enemigo.TileVert * tilHeight + (tilHeight / 2); int arrowX1 = enemigo.TileIzq * tilWidth + (tilWidth / 2); int arrowX2 = enemigo.TileDer * tilWidth + (tilWidth / 2); graphics.DrawLine(arrowPen, arrowX1, arrowY, arrowX2, arrowY); } destRect = new Rectangle((enemigo.TileIzq + ((enemigo.TileDer - enemigo.TileIzq) / 2)) * tilWidth, enemigo.TileVert * tilHeight, 33, 33); graphics.DrawImage(this.ImageList[version.CPU.ToString() + enemigo.TipoEnemigo.ToString()], destRect, srcRect, GraphicsUnit.Pixel); } } arrowPen.Dispose(); } internal Image GetPreview() { Bitmap previewBmp = new Bitmap(this.Width, this.Height); Graphics graphics = Graphics.FromImage(previewBmp); this.drawLevel(graphics, false); return previewBmp; } internal void SavePreview(string fileName) { Bitmap previewBmp = new Bitmap(this.Width, this.Height); Graphics graphics = Graphics.FromImage(previewBmp); this.drawLevel(graphics, false); previewBmp.Save(fileName); } } }
using System; using BizHawk.Common; // Motorola Corp 6800 namespace BizHawk.Emulation.Common.Components.MC6800 { public sealed partial class MC6800 { // operations that can take place in an instruction public const ushort IDLE = 0; public const ushort OP = 1; public const ushort RD = 2; public const ushort WR = 3; public const ushort TR = 4; public const ushort SET_ADDR = 5; public const ushort ADD8 = 6; public const ushort SUB8 = 7; public const ushort ADC8 = 8; public const ushort SBC8 = 9; public const ushort INC16 = 10; public const ushort INC8 = 11; public const ushort DEC16 = 12; public const ushort DEC8 = 13; public const ushort ROL = 14; public const ushort ROR = 15; public const ushort COM = 16; public const ushort DA = 17; public const ushort AND8 = 18; public const ushort XOR8 = 19; public const ushort OR8 = 20; public const ushort ASL = 21; public const ushort ASR = 22; public const ushort LSR = 23; public const ushort BIT = 24; public const ushort WAI = 25; public const ushort RD_INC = 26; public const ushort RD_INC_OP = 27; public const ushort WR_DEC_LO = 28; public const ushort WR_DEC_HI = 29; public const ushort WR_HI = 30; public const ushort LD_8 = 31; public const ushort LD_16 = 32; public const ushort NEG = 33; public const ushort TST = 34; public const ushort CLR = 35; public const ushort ADD8BR = 36; public const ushort IDX_DCDE = 37; public const ushort IDX_OP_BLD = 38; public const ushort WR_HI_INC = 39; public const ushort SET_I = 40; public const ushort CMP8 = 41; public const ushort CMP16 = 42; public const ushort TAP = 43; public const ushort TPA = 44; public const ushort INX = 45; public const ushort DEX = 46; public const ushort CLV = 47; public const ushort SEV = 48; public const ushort CLC = 49; public const ushort SEC = 50; public const ushort CLI = 51; public const ushort SEI = 52; public const ushort SBA = 53; public const ushort CBA = 54; public const ushort TAB = 55; public const ushort TBA = 56; public const ushort ABA = 57; public const ushort TSX = 58; public const ushort INS = 59; public const ushort DES = 60; public const ushort TXS = 61; public MC6800() { Reset(); } public void Reset() { ResetRegisters(); ResetInterrupts(); TotalExecutedCycles = 0; Regs[PC] = 0xFFFE; PopulateCURINSTR(IDLE, IDLE, IDLE, RD_INC, ALU, PC, RD_INC, ALU2, PC, SET_ADDR, PC, ALU, ALU2); IRQS = 6; instr_pntr = irq_pntr = 0; } // Memory Access public Func<ushort, byte> ReadMemory; public Action<ushort, byte> WriteMemory; public Func<ushort, byte> PeekMemory; public Func<ushort, byte> DummyReadMemory; // Special Function for Speed switching executed on a STOP public Func<int, int> SpeedFunc; //this only calls when the first byte of an instruction is fetched. public Action<ushort> OnExecFetch; public void UnregisterMemoryMapper() { ReadMemory = null; ReadMemory = null; PeekMemory = null; DummyReadMemory = null; } public void SetCallbacks ( Func<ushort, byte> ReadMemory, Func<ushort, byte> DummyReadMemory, Func<ushort, byte> PeekMemory, Action<ushort, byte> WriteMemory ) { this.ReadMemory = ReadMemory; this.DummyReadMemory = DummyReadMemory; this.PeekMemory = PeekMemory; this.WriteMemory = WriteMemory; } //a little CDL related stuff public delegate void DoCDLCallbackType(ushort addr, MC6800.eCDLogMemFlags flags); public DoCDLCallbackType CDLCallback; public enum eCDLogMemFlags { FetchFirst = 1, FetchOperand = 2, Data = 4, Write = 8 }; // Execute instructions public void ExecuteOne() { //Console.Write(opcode_see + " "); //Console.WriteLine(Regs[PC] + " "); switch (cur_instr[instr_pntr++]) { case IDLE: // do nothing break; case OP: // Read the opcode of the next instruction if (OnExecFetch != null) OnExecFetch(PC); if (TraceCallback != null) TraceCallback(State()); if (CDLCallback != null) CDLCallback(PC, eCDLogMemFlags.FetchFirst); FetchInstruction(ReadMemory(Regs[PC]++)); instr_pntr = 0; irq_pntr = -1; break; case RD: Read_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case RD_INC: Read_Inc_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case RD_INC_OP: Read_Inc_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); switch (cur_instr[instr_pntr++]) { case AND8: AND8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case ADD8: ADD8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case ADC8: ADC8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case OR8: OR8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case XOR8: XOR8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case BIT: BIT_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case SUB8: SUB8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case SBC8: SBC8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case CMP8: CMP8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case DEC16: DEC16_Func(cur_instr[instr_pntr++]); break; case ADD8BR: ADD8BR_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case TR: TR_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case SET_ADDR: reg_d_ad = cur_instr[instr_pntr++]; reg_h_ad = cur_instr[instr_pntr++]; reg_l_ad = cur_instr[instr_pntr++]; Regs[reg_d_ad] = (ushort)((Regs[reg_h_ad] << 8) | Regs[reg_l_ad]); break; case IDX_DCDE: Index_decode(); break; case IDX_OP_BLD: Index_Op_Builder(); break; case LD_8: LD_8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case LD_16: LD_16_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; } break; case WR: Write_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case WR_DEC_LO: Write_Dec_Lo_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case WR_DEC_HI: Write_Dec_HI_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case WR_HI: Write_Hi_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case WR_HI_INC: Write_Hi_Inc_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case TR: TR_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case LD_8: LD_8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case LD_16: LD_16_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case IDX_OP_BLD: Index_Op_Builder(); break; case SET_ADDR: reg_d_ad = cur_instr[instr_pntr++]; reg_h_ad = cur_instr[instr_pntr++]; reg_l_ad = cur_instr[instr_pntr++]; // Console.WriteLine(reg_d_ad + " " + reg_h_ad + " " + reg_l_ad); // Console.WriteLine(Regs[reg_d_ad] + " " + Regs[reg_h_ad] + " " + Regs[reg_l_ad]); Regs[reg_d_ad] = (ushort)((Regs[reg_h_ad] << 8) | Regs[reg_l_ad]); break; case NEG: NEG_8_Func(cur_instr[instr_pntr++]); break; case TST: TST_Func(cur_instr[instr_pntr++]); break; case CLR: CLR_Func(cur_instr[instr_pntr++]); break; case SET_I: FlagI = true; break; case ADD8BR: ADD8BR_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case ADD8: ADD8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case SUB8: SUB8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case ADC8: ADC8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case SBC8: SBC8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case CMP8: CMP8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case INC16: INC16_Func(cur_instr[instr_pntr++]); break; case INC8: INC8_Func(cur_instr[instr_pntr++]); break; case DEC16: DEC16_Func(cur_instr[instr_pntr++]); break; case CMP16: CMP16_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case DEC8: DEC8_Func(cur_instr[instr_pntr++]); break; case ROL: ROL_Func(cur_instr[instr_pntr++]); break; case ROR: ROR_Func(cur_instr[instr_pntr++]); break; case COM: COM_Func(cur_instr[instr_pntr++]); break; case DA: DA_Func(cur_instr[instr_pntr++]); break; case AND8: AND8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case XOR8: XOR8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case OR8: OR8_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case ASL: ASL_Func(cur_instr[instr_pntr++]); break; case ASR: ASR_Func(cur_instr[instr_pntr++]); break; case LSR: LSR_Func(cur_instr[instr_pntr++]); break; case TAP: instr_pntr++; Regs[CC] = (ushort)((Regs[A] & 0x3F) | 0xC0); // last 2 bits always 1 break; case TPA: instr_pntr++; Regs[A] = Regs[CC]; break; case INX: instr_pntr++; Regs[X] = (ushort)(Regs[X] + 1); FlagZ = Regs[X] == 0; break; case DEX: instr_pntr++; Regs[X] = (ushort)(Regs[X] - 1); FlagZ = Regs[X] == 0; break; case CLV: instr_pntr++; FlagV = false; break; case SEV: instr_pntr++; FlagV = true; break; case CLC: instr_pntr++; FlagC = false; break; case SEC: instr_pntr++; FlagC = true; break; case CLI: instr_pntr++; FlagI = false; break; case SEI: instr_pntr++; FlagI = true; break; case SBA: instr_pntr++; SBC8_Func(A, B); break; case CBA: instr_pntr++; CMP8_Func(A, B); break; case TAB: instr_pntr++; Regs[B] = Regs[A]; break; case TBA: instr_pntr++; Regs[A] = Regs[B]; break; case ABA: instr_pntr++; ADD8_Func(A, B); break; case TSX: instr_pntr++; Regs[X] = (ushort)(Regs[SP] + 1); break; case INS: instr_pntr++; Regs[SP] = (ushort)(Regs[SP] + 1); break; case DES: instr_pntr++; Regs[SP] = (ushort)(Regs[SP] - 1); break; case TXS: instr_pntr++; Regs[SP] = (ushort)(Regs[X] - 1); break; case BIT: BIT_Func(cur_instr[instr_pntr++], cur_instr[instr_pntr++]); break; case WAI: if (NMIPending) { NMIPending = false; Regs[ADDR] = 0xFFFC; PopulateCURINSTR(RD_INC, ALU, ADDR, RD_INC, ALU2, ADDR, SET_ADDR, PC, ALU, ALU2); irq_pntr = -1; IRQS = 3; if (TraceCallback != null) { TraceCallback(new TraceInfo { Disassembly = "====CWAI NMI====", RegisterInfo = "" }); } } else if (IRQPending && !FlagI) { IRQPending = false; Regs[ADDR] = 0xFFF8; PopulateCURINSTR(RD_INC, ALU, ADDR, RD_INC, ALU2, ADDR, SET_ADDR, PC, ALU, ALU2); irq_pntr = -1; IRQS = 3; if (TraceCallback != null) { TraceCallback(new TraceInfo { Disassembly = "====CWAI IRQ====", RegisterInfo = "" }); } } else { PopulateCURINSTR(WAI); irq_pntr = 0; IRQS = -1; } instr_pntr = 0; break; } if (++irq_pntr == IRQS) { // NMI has priority if (NMIPending) { NMIPending = false; if (TraceCallback != null) { TraceCallback(new TraceInfo { Disassembly = "====NMI====", RegisterInfo = "" }); } NMI_(); NMICallback(); instr_pntr = irq_pntr = 0; } // then regular IRQ else if (IRQPending && !FlagI) { if (!FlagI) { IRQPending = false; if (TraceCallback != null) { TraceCallback(new TraceInfo { Disassembly = "====IRQ====", RegisterInfo = "" }); } IRQ_(); IRQCallback(); instr_pntr = irq_pntr = 0; } } // otherwise start the next instruction else { PopulateCURINSTR(OP); instr_pntr = irq_pntr = 0; IRQS = -1; } } TotalExecutedCycles++; } // tracer stuff public Action<TraceInfo> TraceCallback; public string TraceHeader { get { return "MC6809: PC, machine code, mnemonic, operands, registers (A, B, X, SP, CC), Cy, flags (EHINZVC)"; } } public TraceInfo State(bool disassemble = true) { ushort notused; return new TraceInfo { Disassembly = $"{(disassemble ? Disassemble(Regs[PC], ReadMemory, out notused) : "---")} ".PadRight(50), RegisterInfo = string.Format( "A:{0:X2} B:{1:X2} X:{2:X4} SP:{3:X4} CC:{4:X2} Cy:{5} {6}{7}{8}{9}{10}{11}", Regs[A], Regs[B], Regs[X], Regs[SP], Regs[CC], TotalExecutedCycles, FlagH ? "H" : "h", FlagI ? "I" : "i", FlagN ? "N" : "n", FlagZ ? "Z" : "z", FlagV ? "V" : "v", FlagC ? "C" : "c" ) }; } /// <summary> /// Optimization method to set cur_instr /// </summary> private void PopulateCURINSTR(ushort d0 = 0, ushort d1 = 0, ushort d2 = 0, ushort d3 = 0, ushort d4 = 0, ushort d5 = 0, ushort d6 = 0, ushort d7 = 0, ushort d8 = 0, ushort d9 = 0, ushort d10 = 0, ushort d11 = 0, ushort d12 = 0, ushort d13 = 0, ushort d14 = 0, ushort d15 = 0, ushort d16 = 0, ushort d17 = 0, ushort d18 = 0, ushort d19 = 0, ushort d20 = 0, ushort d21 = 0, ushort d22 = 0, ushort d23 = 0, ushort d24 = 0, ushort d25 = 0, ushort d26 = 0, ushort d27 = 0, ushort d28 = 0, ushort d29 = 0, ushort d30 = 0, ushort d31 = 0, ushort d32 = 0, ushort d33 = 0, ushort d34 = 0, ushort d35 = 0, ushort d36 = 0, ushort d37 = 0, ushort d38 = 0, ushort d39 = 0, ushort d40 = 0, ushort d41 = 0, ushort d42 = 0, ushort d43 = 0, ushort d44 = 0, ushort d45 = 0, ushort d46 = 0, ushort d47 = 0, ushort d48 = 0, ushort d49 = 0, ushort d50 = 0, ushort d51 = 0, ushort d52 = 0, ushort d53 = 0, ushort d54 = 0, ushort d55 = 0, ushort d56 = 0, ushort d57 = 0, ushort d58 = 0) { cur_instr[0] = d0; cur_instr[1] = d1; cur_instr[2] = d2; cur_instr[3] = d3; cur_instr[4] = d4; cur_instr[5] = d5; cur_instr[6] = d6; cur_instr[7] = d7; cur_instr[8] = d8; cur_instr[9] = d9; cur_instr[10] = d10; cur_instr[11] = d11; cur_instr[12] = d12; cur_instr[13] = d13; cur_instr[14] = d14; cur_instr[15] = d15; cur_instr[16] = d16; cur_instr[17] = d17; cur_instr[18] = d18; cur_instr[19] = d19; cur_instr[20] = d20; cur_instr[21] = d21; cur_instr[22] = d22; cur_instr[23] = d23; cur_instr[24] = d24; cur_instr[25] = d25; cur_instr[26] = d26; cur_instr[27] = d27; cur_instr[28] = d28; cur_instr[29] = d29; cur_instr[30] = d30; cur_instr[31] = d31; cur_instr[32] = d32; cur_instr[33] = d33; cur_instr[34] = d34; cur_instr[35] = d35; cur_instr[36] = d36; cur_instr[37] = d37; cur_instr[38] = d38; cur_instr[39] = d39; cur_instr[40] = d40; cur_instr[41] = d41; cur_instr[42] = d42; cur_instr[43] = d43; cur_instr[44] = d44; cur_instr[45] = d45; cur_instr[46] = d46; cur_instr[47] = d47; cur_instr[48] = d48; cur_instr[49] = d49; cur_instr[50] = d50; cur_instr[51] = d51; cur_instr[52] = d52; cur_instr[53] = d53; cur_instr[54] = d54; cur_instr[55] = d55; cur_instr[56] = d56; cur_instr[57] = d57; cur_instr[58] = d58; } // State Save/Load public void SyncState(Serializer ser) { ser.BeginSection("MC6809"); ser.Sync(nameof(NMIPending), ref NMIPending); ser.Sync(nameof(IRQPending), ref IRQPending); ser.Sync(nameof(indexed_op), ref indexed_op); ser.Sync(nameof(indexed_reg), ref indexed_reg); ser.Sync(nameof(indexed_op_reg), ref indexed_op_reg); ser.Sync(nameof(instr_pntr), ref instr_pntr); ser.Sync(nameof(cur_instr), ref cur_instr, false); ser.Sync(nameof(opcode_see), ref opcode_see); ser.Sync(nameof(IRQS), ref IRQS); ser.Sync(nameof(irq_pntr), ref irq_pntr); ser.Sync(nameof(Regs), ref Regs, false); ser.Sync(nameof(TotalExecutedCycles), ref TotalExecutedCycles); ser.EndSection(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public static class LiftedSubtractCheckedNullableTests { #region Test methods [Fact] public static void CheckLiftedSubtractCheckedNullableByteTest() { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableByte(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableCharTest() { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableChar(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableDecimalTest() { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableDecimal(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableDoubleTest() { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableDouble(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableFloatTest() { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableFloat(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableIntTest() { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableInt(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableLongTest() { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableLong(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableSByteTest() { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableSByte(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableShortTest() { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableShort(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableUIntTest() { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableUInt(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableULongTest() { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableULong(values[i], values[j]); } } } [Fact] public static void CheckLiftedSubtractCheckedNullableUShortTest() { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifySubtractCheckedNullableUShort(values[i], values[j]); } } } #endregion #region Helpers public static byte SubtractCheckedNullableByte(byte a, byte b) { return (byte)checked(a - b); } public static char SubtractCheckedNullableChar(char a, char b) { return (char)checked(a - b); } public static decimal SubtractCheckedNullableDecimal(decimal a, decimal b) { return (decimal)checked(a - b); } public static double SubtractCheckedNullableDouble(double a, double b) { return (double)checked(a - b); } public static float SubtractCheckedNullableFloat(float a, float b) { return (float)checked(a - b); } public static int SubtractCheckedNullableInt(int a, int b) { return (int)checked(a - b); } public static long SubtractCheckedNullableLong(long a, long b) { return (long)checked(a - b); } public static sbyte SubtractCheckedNullableSByte(sbyte a, sbyte b) { return (sbyte)checked(a - b); } public static short SubtractCheckedNullableShort(short a, short b) { return (short)checked(a - b); } public static uint SubtractCheckedNullableUInt(uint a, uint b) { return (uint)checked(a - b); } public static ulong SubtractCheckedNullableULong(ulong a, ulong b) { return (ulong)checked(a - b); } public static ushort SubtractCheckedNullableUShort(ushort a, ushort b) { return (ushort)checked(a - b); } #endregion #region Test verifiers private static void VerifySubtractCheckedNullableByte(byte? a, byte? b) { Expression<Func<byte?>> e = Expression.Lambda<Func<byte?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableByte"))); Func<byte?> f = e.Compile(); byte? result = default(byte); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } byte? expected = default(byte); Exception csEx = null; try { expected = (byte?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableChar(char? a, char? b) { Expression<Func<char?>> e = Expression.Lambda<Func<char?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableChar"))); Func<char?> f = e.Compile(); char? result = default(char); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } char? expected = default(char); Exception csEx = null; try { expected = (char?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableDecimal(decimal? a, decimal? b) { Expression<Func<decimal?>> e = Expression.Lambda<Func<decimal?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableDecimal"))); Func<decimal?> f = e.Compile(); decimal? result = default(decimal); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } decimal? expected = default(decimal); Exception csEx = null; try { expected = (decimal?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableDouble(double? a, double? b) { Expression<Func<double?>> e = Expression.Lambda<Func<double?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableDouble"))); Func<double?> f = e.Compile(); double? result = default(double); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } double? expected = default(double); Exception csEx = null; try { expected = (double?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableFloat(float? a, float? b) { Expression<Func<float?>> e = Expression.Lambda<Func<float?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableFloat"))); Func<float?> f = e.Compile(); float? result = default(float); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } float? expected = default(float); Exception csEx = null; try { expected = (float?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableInt(int? a, int? b) { Expression<Func<int?>> e = Expression.Lambda<Func<int?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableInt"))); Func<int?> f = e.Compile(); int? result = default(int); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } int? expected = default(int); Exception csEx = null; try { expected = (int?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableLong(long? a, long? b) { Expression<Func<long?>> e = Expression.Lambda<Func<long?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableLong"))); Func<long?> f = e.Compile(); long? result = default(long); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } long? expected = default(long); Exception csEx = null; try { expected = (long?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableSByte(sbyte? a, sbyte? b) { Expression<Func<sbyte?>> e = Expression.Lambda<Func<sbyte?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableSByte"))); Func<sbyte?> f = e.Compile(); sbyte? result = default(sbyte); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } sbyte? expected = default(sbyte); Exception csEx = null; try { expected = (sbyte?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableShort(short? a, short? b) { Expression<Func<short?>> e = Expression.Lambda<Func<short?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableShort"))); Func<short?> f = e.Compile(); short? result = default(short); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } short? expected = default(short); Exception csEx = null; try { expected = (short?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableUInt(uint? a, uint? b) { Expression<Func<uint?>> e = Expression.Lambda<Func<uint?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableUInt"))); Func<uint?> f = e.Compile(); uint? result = default(uint); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } uint? expected = default(uint); Exception csEx = null; try { expected = (uint?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableULong(ulong? a, ulong? b) { Expression<Func<ulong?>> e = Expression.Lambda<Func<ulong?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableULong"))); Func<ulong?> f = e.Compile(); ulong? result = default(ulong); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } ulong? expected = default(ulong); Exception csEx = null; try { expected = (ulong?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } private static void VerifySubtractCheckedNullableUShort(ushort? a, ushort? b) { Expression<Func<ushort?>> e = Expression.Lambda<Func<ushort?>>( Expression.SubtractChecked( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), typeof(LiftedSubtractCheckedNullableTests).GetTypeInfo().GetDeclaredMethod("SubtractCheckedNullableUShort"))); Func<ushort?> f = e.Compile(); ushort? result = default(ushort); Exception fEx = null; try { result = f(); } catch (Exception ex) { fEx = ex; } ushort? expected = default(ushort); Exception csEx = null; try { expected = (ushort?)checked(a - b); } catch (Exception ex) { csEx = ex; } if (fEx != null || csEx != null) { Assert.NotNull(fEx); Assert.NotNull(csEx); Assert.Equal(csEx.GetType(), fEx.GetType()); } else { Assert.Equal(expected, result); } } #endregion } }
namespace android.graphics { [global::MonoJavaBridge.JavaClass()] public partial class Canvas : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Canvas(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public sealed partial class EdgeType : java.lang.Enum { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal EdgeType(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public static global::android.graphics.Canvas.EdgeType[] values() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Canvas.EdgeType._m0.native == global::System.IntPtr.Zero) global::android.graphics.Canvas.EdgeType._m0 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Canvas.EdgeType.staticClass, "values", "()[Landroid/graphics/Canvas/EdgeType;"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.graphics.Canvas.EdgeType>(@__env.CallStaticObjectMethod(android.graphics.Canvas.EdgeType.staticClass, global::android.graphics.Canvas.EdgeType._m0)) as android.graphics.Canvas.EdgeType[]; } private static global::MonoJavaBridge.MethodId _m1; public static global::android.graphics.Canvas.EdgeType valueOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Canvas.EdgeType._m1.native == global::System.IntPtr.Zero) global::android.graphics.Canvas.EdgeType._m1 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Canvas.EdgeType.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/graphics/Canvas$EdgeType;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Canvas.EdgeType>(@__env.CallStaticObjectMethod(android.graphics.Canvas.EdgeType.staticClass, global::android.graphics.Canvas.EdgeType._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Canvas.EdgeType; } internal static global::MonoJavaBridge.FieldId _AA2264; public static global::android.graphics.Canvas.EdgeType AA { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Canvas.EdgeType>(@__env.GetStaticObjectField(global::android.graphics.Canvas.EdgeType.staticClass, _AA2264)) as android.graphics.Canvas.EdgeType; } } internal static global::MonoJavaBridge.FieldId _BW2265; public static global::android.graphics.Canvas.EdgeType BW { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Canvas.EdgeType>(@__env.GetStaticObjectField(global::android.graphics.Canvas.EdgeType.staticClass, _BW2265)) as android.graphics.Canvas.EdgeType; } } static EdgeType() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.Canvas.EdgeType.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Canvas$EdgeType")); global::android.graphics.Canvas.EdgeType._AA2264 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.Canvas.EdgeType.staticClass, "AA", "Landroid/graphics/Canvas$EdgeType;"); global::android.graphics.Canvas.EdgeType._BW2265 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.Canvas.EdgeType.staticClass, "BW", "Landroid/graphics/Canvas$EdgeType;"); } } [global::MonoJavaBridge.JavaClass()] public sealed partial class VertexMode : java.lang.Enum { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal VertexMode(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public static global::android.graphics.Canvas.VertexMode[] values() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Canvas.VertexMode._m0.native == global::System.IntPtr.Zero) global::android.graphics.Canvas.VertexMode._m0 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Canvas.VertexMode.staticClass, "values", "()[Landroid/graphics/Canvas/VertexMode;"); return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.graphics.Canvas.VertexMode>(@__env.CallStaticObjectMethod(android.graphics.Canvas.VertexMode.staticClass, global::android.graphics.Canvas.VertexMode._m0)) as android.graphics.Canvas.VertexMode[]; } private static global::MonoJavaBridge.MethodId _m1; public static global::android.graphics.Canvas.VertexMode valueOf(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Canvas.VertexMode._m1.native == global::System.IntPtr.Zero) global::android.graphics.Canvas.VertexMode._m1 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Canvas.VertexMode.staticClass, "valueOf", "(Ljava/lang/String;)Landroid/graphics/Canvas$VertexMode;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Canvas.VertexMode>(@__env.CallStaticObjectMethod(android.graphics.Canvas.VertexMode.staticClass, global::android.graphics.Canvas.VertexMode._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Canvas.VertexMode; } internal static global::MonoJavaBridge.FieldId _TRIANGLES2266; public static global::android.graphics.Canvas.VertexMode TRIANGLES { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Canvas.VertexMode>(@__env.GetStaticObjectField(global::android.graphics.Canvas.VertexMode.staticClass, _TRIANGLES2266)) as android.graphics.Canvas.VertexMode; } } internal static global::MonoJavaBridge.FieldId _TRIANGLE_FAN2267; public static global::android.graphics.Canvas.VertexMode TRIANGLE_FAN { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Canvas.VertexMode>(@__env.GetStaticObjectField(global::android.graphics.Canvas.VertexMode.staticClass, _TRIANGLE_FAN2267)) as android.graphics.Canvas.VertexMode; } } internal static global::MonoJavaBridge.FieldId _TRIANGLE_STRIP2268; public static global::android.graphics.Canvas.VertexMode TRIANGLE_STRIP { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Canvas.VertexMode>(@__env.GetStaticObjectField(global::android.graphics.Canvas.VertexMode.staticClass, _TRIANGLE_STRIP2268)) as android.graphics.Canvas.VertexMode; } } static VertexMode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.Canvas.VertexMode.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Canvas$VertexMode")); global::android.graphics.Canvas.VertexMode._TRIANGLES2266 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.Canvas.VertexMode.staticClass, "TRIANGLES", "Landroid/graphics/Canvas$VertexMode;"); global::android.graphics.Canvas.VertexMode._TRIANGLE_FAN2267 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.Canvas.VertexMode.staticClass, "TRIANGLE_FAN", "Landroid/graphics/Canvas$VertexMode;"); global::android.graphics.Canvas.VertexMode._TRIANGLE_STRIP2268 = @__env.GetStaticFieldIDNoThrow(global::android.graphics.Canvas.VertexMode.staticClass, "TRIANGLE_STRIP", "Landroid/graphics/Canvas$VertexMode;"); } } private static global::MonoJavaBridge.MethodId _m0; protected override void finalize() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "finalize", "()V", ref global::android.graphics.Canvas._m0); } private static global::MonoJavaBridge.MethodId _m1; public virtual void concat(android.graphics.Matrix arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "concat", "(Landroid/graphics/Matrix;)V", ref global::android.graphics.Canvas._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public virtual int save() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "save", "()I", ref global::android.graphics.Canvas._m2); } private static global::MonoJavaBridge.MethodId _m3; public virtual int save(int arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "save", "(I)I", ref global::android.graphics.Canvas._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; public virtual void rotate(float arg0, float arg1, float arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "rotate", "(FFF)V", ref global::android.graphics.Canvas._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m5; public virtual void rotate(float arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "rotate", "(F)V", ref global::android.graphics.Canvas._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; public virtual bool isOpaque() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "isOpaque", "()Z", ref global::android.graphics.Canvas._m6); } private static global::MonoJavaBridge.MethodId _m7; public virtual void scale(float arg0, float arg1, float arg2, float arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "scale", "(FFFF)V", ref global::android.graphics.Canvas._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m8; public virtual void scale(float arg0, float arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "scale", "(FF)V", ref global::android.graphics.Canvas._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new int Density { get { return getDensity(); } set { setDensity(value); } } private static global::MonoJavaBridge.MethodId _m9; public virtual int getDensity() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "getDensity", "()I", ref global::android.graphics.Canvas._m9); } private static global::MonoJavaBridge.MethodId _m10; public virtual void setDensity(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "setDensity", "(I)V", ref global::android.graphics.Canvas._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int Width { get { return getWidth(); } } private static global::MonoJavaBridge.MethodId _m11; public virtual int getWidth() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "getWidth", "()I", ref global::android.graphics.Canvas._m11); } public new int Height { get { return getHeight(); } } private static global::MonoJavaBridge.MethodId _m12; public virtual int getHeight() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "getHeight", "()I", ref global::android.graphics.Canvas._m12); } public new global::javax.microedition.khronos.opengles.GL GL { get { return getGL(); } } private static global::MonoJavaBridge.MethodId _m13; public virtual global::javax.microedition.khronos.opengles.GL getGL() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<javax.microedition.khronos.opengles.GL>(this, global::android.graphics.Canvas.staticClass, "getGL", "()Ljavax/microedition/khronos/opengles/GL;", ref global::android.graphics.Canvas._m13) as javax.microedition.khronos.opengles.GL; } private static global::MonoJavaBridge.MethodId _m14; public static void freeGlCaches() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Canvas._m14.native == global::System.IntPtr.Zero) global::android.graphics.Canvas._m14 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.Canvas.staticClass, "freeGlCaches", "()V"); @__env.CallStaticVoidMethod(android.graphics.Canvas.staticClass, global::android.graphics.Canvas._m14); } public new global::android.graphics.Bitmap Bitmap { set { setBitmap(value); } } private static global::MonoJavaBridge.MethodId _m15; public virtual void setBitmap(android.graphics.Bitmap arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "setBitmap", "(Landroid/graphics/Bitmap;)V", ref global::android.graphics.Canvas._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m16; public virtual void setViewport(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "setViewport", "(II)V", ref global::android.graphics.Canvas._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m17; public virtual int saveLayer(android.graphics.RectF arg0, android.graphics.Paint arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "saveLayer", "(Landroid/graphics/RectF;Landroid/graphics/Paint;I)I", ref global::android.graphics.Canvas._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m18; public virtual int saveLayer(float arg0, float arg1, float arg2, float arg3, android.graphics.Paint arg4, int arg5) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "saveLayer", "(FFFFLandroid/graphics/Paint;I)I", ref global::android.graphics.Canvas._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } private static global::MonoJavaBridge.MethodId _m19; public virtual int saveLayerAlpha(float arg0, float arg1, float arg2, float arg3, int arg4, int arg5) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "saveLayerAlpha", "(FFFFII)I", ref global::android.graphics.Canvas._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } private static global::MonoJavaBridge.MethodId _m20; public virtual int saveLayerAlpha(android.graphics.RectF arg0, int arg1, int arg2) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "saveLayerAlpha", "(Landroid/graphics/RectF;II)I", ref global::android.graphics.Canvas._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m21; public virtual void restore() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "restore", "()V", ref global::android.graphics.Canvas._m21); } public new int SaveCount { get { return getSaveCount(); } } private static global::MonoJavaBridge.MethodId _m22; public virtual int getSaveCount() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.graphics.Canvas.staticClass, "getSaveCount", "()I", ref global::android.graphics.Canvas._m22); } private static global::MonoJavaBridge.MethodId _m23; public virtual void restoreToCount(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "restoreToCount", "(I)V", ref global::android.graphics.Canvas._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m24; public virtual void translate(float arg0, float arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "translate", "(FF)V", ref global::android.graphics.Canvas._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m25; public virtual void skew(float arg0, float arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "skew", "(FF)V", ref global::android.graphics.Canvas._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m26; public virtual void setMatrix(android.graphics.Matrix arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "setMatrix", "(Landroid/graphics/Matrix;)V", ref global::android.graphics.Canvas._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.graphics.Matrix Matrix { get { return getMatrix(); } set { setMatrix(value); } } private static global::MonoJavaBridge.MethodId _m27; public virtual global::android.graphics.Matrix getMatrix() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.graphics.Canvas.staticClass, "getMatrix", "()Landroid/graphics/Matrix;", ref global::android.graphics.Canvas._m27) as android.graphics.Matrix; } private static global::MonoJavaBridge.MethodId _m28; public virtual void getMatrix(android.graphics.Matrix arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "getMatrix", "(Landroid/graphics/Matrix;)V", ref global::android.graphics.Canvas._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m29; public virtual bool clipRect(android.graphics.Rect arg0, android.graphics.Region.Op arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipRect", "(Landroid/graphics/Rect;Landroid/graphics/Region$Op;)Z", ref global::android.graphics.Canvas._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m30; public virtual bool clipRect(android.graphics.RectF arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipRect", "(Landroid/graphics/RectF;)Z", ref global::android.graphics.Canvas._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public virtual bool clipRect(android.graphics.Rect arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipRect", "(Landroid/graphics/Rect;)Z", ref global::android.graphics.Canvas._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m32; public virtual bool clipRect(float arg0, float arg1, float arg2, float arg3, android.graphics.Region.Op arg4) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipRect", "(FFFFLandroid/graphics/Region$Op;)Z", ref global::android.graphics.Canvas._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m33; public virtual bool clipRect(float arg0, float arg1, float arg2, float arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipRect", "(FFFF)Z", ref global::android.graphics.Canvas._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m34; public virtual bool clipRect(int arg0, int arg1, int arg2, int arg3) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipRect", "(IIII)Z", ref global::android.graphics.Canvas._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m35; public virtual bool clipRect(android.graphics.RectF arg0, android.graphics.Region.Op arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipRect", "(Landroid/graphics/RectF;Landroid/graphics/Region$Op;)Z", ref global::android.graphics.Canvas._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m36; public virtual bool clipPath(android.graphics.Path arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipPath", "(Landroid/graphics/Path;)Z", ref global::android.graphics.Canvas._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m37; public virtual bool clipPath(android.graphics.Path arg0, android.graphics.Region.Op arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipPath", "(Landroid/graphics/Path;Landroid/graphics/Region$Op;)Z", ref global::android.graphics.Canvas._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m38; public virtual bool clipRegion(android.graphics.Region arg0, android.graphics.Region.Op arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipRegion", "(Landroid/graphics/Region;Landroid/graphics/Region$Op;)Z", ref global::android.graphics.Canvas._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m39; public virtual bool clipRegion(android.graphics.Region arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "clipRegion", "(Landroid/graphics/Region;)Z", ref global::android.graphics.Canvas._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new global::android.graphics.DrawFilter DrawFilter { get { return getDrawFilter(); } set { setDrawFilter(value); } } private static global::MonoJavaBridge.MethodId _m40; public virtual global::android.graphics.DrawFilter getDrawFilter() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.graphics.Canvas.staticClass, "getDrawFilter", "()Landroid/graphics/DrawFilter;", ref global::android.graphics.Canvas._m40) as android.graphics.DrawFilter; } private static global::MonoJavaBridge.MethodId _m41; public virtual void setDrawFilter(android.graphics.DrawFilter arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "setDrawFilter", "(Landroid/graphics/DrawFilter;)V", ref global::android.graphics.Canvas._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m42; public virtual bool quickReject(android.graphics.RectF arg0, android.graphics.Canvas.EdgeType arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "quickReject", "(Landroid/graphics/RectF;Landroid/graphics/Canvas$EdgeType;)Z", ref global::android.graphics.Canvas._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m43; public virtual bool quickReject(android.graphics.Path arg0, android.graphics.Canvas.EdgeType arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "quickReject", "(Landroid/graphics/Path;Landroid/graphics/Canvas$EdgeType;)Z", ref global::android.graphics.Canvas._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m44; public virtual bool quickReject(float arg0, float arg1, float arg2, float arg3, android.graphics.Canvas.EdgeType arg4) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "quickReject", "(FFFFLandroid/graphics/Canvas$EdgeType;)Z", ref global::android.graphics.Canvas._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } public new global::android.graphics.Rect ClipBounds { get { return getClipBounds(); } } private static global::MonoJavaBridge.MethodId _m45; public virtual global::android.graphics.Rect getClipBounds() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.graphics.Rect>(this, global::android.graphics.Canvas.staticClass, "getClipBounds", "()Landroid/graphics/Rect;", ref global::android.graphics.Canvas._m45) as android.graphics.Rect; } private static global::MonoJavaBridge.MethodId _m46; public virtual bool getClipBounds(android.graphics.Rect arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.graphics.Canvas.staticClass, "getClipBounds", "(Landroid/graphics/Rect;)Z", ref global::android.graphics.Canvas._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m47; public virtual void drawRGB(int arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawRGB", "(III)V", ref global::android.graphics.Canvas._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m48; public virtual void drawARGB(int arg0, int arg1, int arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawARGB", "(IIII)V", ref global::android.graphics.Canvas._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m49; public virtual void drawColor(int arg0, android.graphics.PorterDuff.Mode arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawColor", "(ILandroid/graphics/PorterDuff$Mode;)V", ref global::android.graphics.Canvas._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m50; public virtual void drawColor(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawColor", "(I)V", ref global::android.graphics.Canvas._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m51; public virtual void drawPaint(android.graphics.Paint arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPaint", "(Landroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m52; public virtual void drawPoints(float[] arg0, android.graphics.Paint arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPoints", "([FLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m53; public virtual void drawPoints(float[] arg0, int arg1, int arg2, android.graphics.Paint arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPoints", "([FIILandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m54; public virtual void drawPoint(float arg0, float arg1, android.graphics.Paint arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPoint", "(FFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m55; public virtual void drawLine(float arg0, float arg1, float arg2, float arg3, android.graphics.Paint arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawLine", "(FFFFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m55, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m56; public virtual void drawLines(float[] arg0, android.graphics.Paint arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawLines", "([FLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m56, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m57; public virtual void drawLines(float[] arg0, int arg1, int arg2, android.graphics.Paint arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawLines", "([FIILandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m57, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m58; public virtual void drawRect(android.graphics.Rect arg0, android.graphics.Paint arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawRect", "(Landroid/graphics/Rect;Landroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m58, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m59; public virtual void drawRect(float arg0, float arg1, float arg2, float arg3, android.graphics.Paint arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawRect", "(FFFFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m59, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m60; public virtual void drawRect(android.graphics.RectF arg0, android.graphics.Paint arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawRect", "(Landroid/graphics/RectF;Landroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m60, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m61; public virtual void drawOval(android.graphics.RectF arg0, android.graphics.Paint arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawOval", "(Landroid/graphics/RectF;Landroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m61, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m62; public virtual void drawCircle(float arg0, float arg1, float arg2, android.graphics.Paint arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawCircle", "(FFFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m62, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m63; public virtual void drawArc(android.graphics.RectF arg0, float arg1, float arg2, bool arg3, android.graphics.Paint arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawArc", "(Landroid/graphics/RectF;FFZLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m63, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m64; public virtual void drawRoundRect(android.graphics.RectF arg0, float arg1, float arg2, android.graphics.Paint arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawRoundRect", "(Landroid/graphics/RectF;FFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m64, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m65; public virtual void drawPath(android.graphics.Path arg0, android.graphics.Paint arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPath", "(Landroid/graphics/Path;Landroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m65, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m66; public virtual void drawBitmap(android.graphics.Bitmap arg0, android.graphics.Rect arg1, android.graphics.RectF arg2, android.graphics.Paint arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawBitmap", "(Landroid/graphics/Bitmap;Landroid/graphics/Rect;Landroid/graphics/RectF;Landroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m66, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m67; public virtual void drawBitmap(android.graphics.Bitmap arg0, android.graphics.Rect arg1, android.graphics.Rect arg2, android.graphics.Paint arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawBitmap", "(Landroid/graphics/Bitmap;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m67, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m68; public virtual void drawBitmap(int[] arg0, int arg1, int arg2, float arg3, float arg4, int arg5, int arg6, bool arg7, android.graphics.Paint arg8) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawBitmap", "([IIIFFIIZLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m68, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8)); } private static global::MonoJavaBridge.MethodId _m69; public virtual void drawBitmap(int[] arg0, int arg1, int arg2, int arg3, int arg4, int arg5, int arg6, bool arg7, android.graphics.Paint arg8) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawBitmap", "([IIIIIIIZLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m69, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8)); } private static global::MonoJavaBridge.MethodId _m70; public virtual void drawBitmap(android.graphics.Bitmap arg0, android.graphics.Matrix arg1, android.graphics.Paint arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawBitmap", "(Landroid/graphics/Bitmap;Landroid/graphics/Matrix;Landroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m70, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m71; public virtual void drawBitmap(android.graphics.Bitmap arg0, float arg1, float arg2, android.graphics.Paint arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawBitmap", "(Landroid/graphics/Bitmap;FFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m71, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m72; public virtual void drawBitmapMesh(android.graphics.Bitmap arg0, int arg1, int arg2, float[] arg3, int arg4, int[] arg5, int arg6, android.graphics.Paint arg7) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawBitmapMesh", "(Landroid/graphics/Bitmap;II[FI[IILandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m72, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7)); } private static global::MonoJavaBridge.MethodId _m73; public virtual void drawVertices(android.graphics.Canvas.VertexMode arg0, int arg1, float[] arg2, int arg3, float[] arg4, int arg5, int[] arg6, int arg7, short[] arg8, int arg9, int arg10, android.graphics.Paint arg11) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawVertices", "(Landroid/graphics/Canvas$VertexMode;I[FI[FI[II[SIILandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m73, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg7), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg8), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg9), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg10), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg11)); } private static global::MonoJavaBridge.MethodId _m74; public virtual void drawText(java.lang.CharSequence arg0, int arg1, int arg2, float arg3, float arg4, android.graphics.Paint arg5) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawText", "(Ljava/lang/CharSequence;IIFFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m74, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } public void drawText(string arg0, int arg1, int arg2, float arg3, float arg4, android.graphics.Paint arg5) { drawText((global::java.lang.CharSequence)(global::java.lang.String)arg0, arg1, arg2, arg3, arg4, arg5); } private static global::MonoJavaBridge.MethodId _m75; public virtual void drawText(java.lang.String arg0, float arg1, float arg2, android.graphics.Paint arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawText", "(Ljava/lang/String;FFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m75, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m76; public virtual void drawText(char[] arg0, int arg1, int arg2, float arg3, float arg4, android.graphics.Paint arg5) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawText", "([CIIFFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m76, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } private static global::MonoJavaBridge.MethodId _m77; public virtual void drawText(java.lang.String arg0, int arg1, int arg2, float arg3, float arg4, android.graphics.Paint arg5) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawText", "(Ljava/lang/String;IIFFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m77, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } private static global::MonoJavaBridge.MethodId _m78; public virtual void drawPosText(java.lang.String arg0, float[] arg1, android.graphics.Paint arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPosText", "(Ljava/lang/String;[FLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m78, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m79; public virtual void drawPosText(char[] arg0, int arg1, int arg2, float[] arg3, android.graphics.Paint arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPosText", "([CII[FLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m79, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m80; public virtual void drawTextOnPath(java.lang.String arg0, android.graphics.Path arg1, float arg2, float arg3, android.graphics.Paint arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawTextOnPath", "(Ljava/lang/String;Landroid/graphics/Path;FFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m80, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m81; public virtual void drawTextOnPath(char[] arg0, int arg1, int arg2, android.graphics.Path arg3, float arg4, float arg5, android.graphics.Paint arg6) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawTextOnPath", "([CIILandroid/graphics/Path;FFLandroid/graphics/Paint;)V", ref global::android.graphics.Canvas._m81, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6)); } private static global::MonoJavaBridge.MethodId _m82; public virtual void drawPicture(android.graphics.Picture arg0, android.graphics.Rect arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPicture", "(Landroid/graphics/Picture;Landroid/graphics/Rect;)V", ref global::android.graphics.Canvas._m82, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m83; public virtual void drawPicture(android.graphics.Picture arg0, android.graphics.RectF arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPicture", "(Landroid/graphics/Picture;Landroid/graphics/RectF;)V", ref global::android.graphics.Canvas._m83, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m84; public virtual void drawPicture(android.graphics.Picture arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.Canvas.staticClass, "drawPicture", "(Landroid/graphics/Picture;)V", ref global::android.graphics.Canvas._m84, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m85; public Canvas(android.graphics.Bitmap arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Canvas._m85.native == global::System.IntPtr.Zero) global::android.graphics.Canvas._m85 = @__env.GetMethodIDNoThrow(global::android.graphics.Canvas.staticClass, "<init>", "(Landroid/graphics/Bitmap;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Canvas.staticClass, global::android.graphics.Canvas._m85, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m86; public Canvas(javax.microedition.khronos.opengles.GL arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Canvas._m86.native == global::System.IntPtr.Zero) global::android.graphics.Canvas._m86 = @__env.GetMethodIDNoThrow(global::android.graphics.Canvas.staticClass, "<init>", "(Ljavax/microedition/khronos/opengles/GL;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Canvas.staticClass, global::android.graphics.Canvas._m86, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m87; public Canvas() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.Canvas._m87.native == global::System.IntPtr.Zero) global::android.graphics.Canvas._m87 = @__env.GetMethodIDNoThrow(global::android.graphics.Canvas.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.Canvas.staticClass, global::android.graphics.Canvas._m87); Init(@__env, handle); } public static int MATRIX_SAVE_FLAG { get { return 1; } } public static int CLIP_SAVE_FLAG { get { return 2; } } public static int HAS_ALPHA_LAYER_SAVE_FLAG { get { return 4; } } public static int FULL_COLOR_LAYER_SAVE_FLAG { get { return 8; } } public static int CLIP_TO_LAYER_SAVE_FLAG { get { return 16; } } public static int ALL_SAVE_FLAG { get { return 31; } } static Canvas() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.Canvas.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/Canvas")); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ParameterNamesShouldMatchBaseDeclarationAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ParameterNamesShouldMatchBaseDeclarationFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ParameterNamesShouldMatchBaseDeclarationAnalyzer, Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.ParameterNamesShouldMatchBaseDeclarationFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class ParameterNamesShouldMatchBaseDeclarationTests { [Fact] public async Task VerifyNoFalsePositivesAreReportedAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public void TestMethod() { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public void TestMethod(string arg1, string arg2) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public void TestMethod(string arg1, string arg2, __arglist) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public void TestMethod(string arg1, string arg2, params string[] arg3) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class TestClass Public Sub TestMethod() End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class TestClass Public Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class TestClass Public Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3() As String) End Sub End Class"); } [Fact] public async Task VerifyOverrideWithWrongParameterNamesAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(8, 71, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(8, 84, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2)")); await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, __arglist); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, __arglist) { } }", GetCSharpResultAt(8, 71, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2, __arglist)"), GetCSharpResultAt(8, 84, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2, __arglist)")); await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, params string[] arg3) { } }", GetCSharpResultAt(8, 71, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 84, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 106, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg3", "baseArg3", "void BaseClass.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)")); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String) End Class Public Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class", GetBasicResultAt(8, 63, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(8, 79, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)")); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Class Public Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) End Sub End Class", GetBasicResultAt(8, 63, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg1", "baseArg1", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 79, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg2", "baseArg2", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 106, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg3", "baseArg3", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task VerifyInternalOverrideWithWrongParameterNames_NoDiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { internal abstract void TestMethod(string baseArg1, string baseArg2); } public class TestClass : BaseClass { internal override void TestMethod(string arg1, string arg2) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"internal abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, __arglist); } internal class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, __arglist) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"internal class OuterClass { public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : BaseClass { public override void TestMethod(string arg1, string arg2, params string[] arg3) { } } }"); await VerifyVB.VerifyAnalyzerAsync(@"Friend MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String) End Class Friend Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Friend MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Class Public Class TestClass Inherits BaseClass Friend Overrides Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Friend Class OuterClass Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Class Public Class TestClass Inherits BaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) End Sub End Class End Class"); } [Fact] public async Task VerifyInterfaceImplementationWithWrongParameterNamesAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2); } public class TestClass : IBase { public void TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(8, 62, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(8, 75, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2)")); await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, __arglist); } public class TestClass : IBase { public void TestMethod(string arg1, string arg2, __arglist) { } }", GetCSharpResultAt(8, 62, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2, __arglist)"), GetCSharpResultAt(8, 75, "void TestClass.TestMethod(string arg1, string arg2, __arglist)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2, __arglist)")); await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : IBase { public void TestMethod(string arg1, string arg2, params string[] arg3) { } }", GetCSharpResultAt(8, 62, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg1", "baseArg1", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 75, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg2", "baseArg2", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)"), GetCSharpResultAt(8, 97, "void TestClass.TestMethod(string arg1, string arg2, params string[] arg3)", "arg3", "baseArg3", "void IBase.TestMethod(string baseArg1, string baseArg2, params string[] baseArg3)")); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String) End Interface Public Class TestClass Implements IBase Public Sub TestMethod(arg1 As String, arg2 As String) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 53, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(8, 69, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)")); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3() As String) End Interface Public Class TestClass Implements IBase Public Sub TestMethod(arg1 As String, arg2 As String, ParamArray arg3() As String) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 53, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 69, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 96, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg3", "baseArg3", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task VerifyExplicitInterfaceImplementationWithWrongParameterNames_NoDiagnosticAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2); } public class TestClass : IBase { void IBase.TestMethod(string arg1, string arg2) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, __arglist); } public class TestClass : IBase { void IBase.TestMethod(string arg1, string arg2, __arglist) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public interface IBase { void TestMethod(string baseArg1, string baseArg2, params string[] baseArg3); } public class TestClass : IBase { void IBase.TestMethod(string arg1, string arg2, params string[] arg3) { } }"); } [Fact] public async Task VerifyInterfaceImplementationWithDifferentMethodNameAsync() { await VerifyVB.VerifyAnalyzerAsync(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String) End Interface Public Class TestClass Implements IBase Public Sub AnotherTestMethod(arg1 As String, arg2 As String) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 60, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(8, 76, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String)")); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface IBase Sub TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String()) End Interface Public Class TestClass Implements IBase Public Sub AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String()) Implements IBase.TestMethod End Sub End Class", GetBasicResultAt(8, 60, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg1", "baseArg1", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 76, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg2", "baseArg2", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())"), GetBasicResultAt(8, 103, "Sub TestClass.AnotherTestMethod(arg1 As String, arg2 As String, ParamArray arg3 As String())", "arg3", "baseArg3", "Sub IBase.TestMethod(baseArg1 As String, baseArg2 As String, ParamArray baseArg3 As String())")); } [Fact] public async Task VerifyThatInvalidOverrideIsNotReportedAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public class TestClass { public override void {|CS0115:TestMethod|}(string arg1, string arg2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class TestClass Public Overrides Sub {|BC30284:TestMethod|}(arg1 As String, arg2 As String) End Sub End Class"); } [Fact] public async Task VerifyOverrideWithInheritanceChainAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string baseArg1, string baseArg2); } public abstract class IntermediateBaseClass : BaseClass { } public class TestClass : IntermediateBaseClass { public override void TestMethod(string arg1, string arg2) { } }", GetCSharpResultAt(12, 71, "void TestClass.TestMethod(string arg1, string arg2)", "arg1", "baseArg1", "void BaseClass.TestMethod(string baseArg1, string baseArg2)"), GetCSharpResultAt(12, 84, "void TestClass.TestMethod(string arg1, string arg2)", "arg2", "baseArg2", "void BaseClass.TestMethod(string baseArg1, string baseArg2)")); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(baseArg1 As String, baseArg2 As String) End Class Public MustInherit Class IntermediateBaseClass Inherits BaseClass End Class Public Class TestClass Inherits IntermediateBaseClass Public Overrides Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class", GetBasicResultAt(12, 63, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg1", "baseArg1", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)"), GetBasicResultAt(12, 79, "Sub TestClass.TestMethod(arg1 As String, arg2 As String)", "arg2", "baseArg2", "Sub BaseClass.TestMethod(baseArg1 As String, baseArg2 As String)")); } [Fact] public async Task VerifyNewOverrideWithInheritanceAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public class BaseClass { public void TestMethod(string baseArg1, string baseArg2) { } } public class TestClass : BaseClass { public new void TestMethod(string arg1, string arg2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Class BaseClass Public Sub TestMethod(baseArg1 As String, baseArg2 As String) End Sub End Class Public Class TestClass Inherits BaseClass Public Shadows Sub TestMethod(arg1 As String, arg2 As String) End Sub End Class"); } [Fact] public async Task VerifyBaseClassNameHasPriorityAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string arg1, string arg2); } public interface ITest { void TestMethod(string interfaceArg1, string interfaceArg2); } public class TestClass : BaseClass, ITest { public override void TestMethod(string arg1, string arg2) { } }"); await VerifyCS.VerifyAnalyzerAsync(@"public abstract class BaseClass { public abstract void TestMethod(string arg1, string arg2); } public interface ITest { void TestMethod(string interfaceArg1, string interfaceArg2); } public class TestClass : BaseClass, ITest { public override void TestMethod(string interfaceArg1, string interfaceArg2) { } }", GetCSharpResultAt(13, 71, "void TestClass.TestMethod(string interfaceArg1, string interfaceArg2)", "interfaceArg1", "arg1", "void BaseClass.TestMethod(string arg1, string arg2)"), GetCSharpResultAt(13, 93, "void TestClass.TestMethod(string interfaceArg1, string interfaceArg2)", "interfaceArg2", "arg2", "void BaseClass.TestMethod(string arg1, string arg2)")); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(arg1 As String, arg2 As String) End Class Public Interface ITest Sub TestMethod(interfaceArg1 As String, interfaceArg2 As String) End Interface Public Class TestClass Inherits BaseClass Implements ITest Public Overrides Sub TestMethod(arg1 As String, arg2 As String) Implements ITest.TestMethod End Sub End Class"); await VerifyVB.VerifyAnalyzerAsync(@"Public MustInherit Class BaseClass Public MustOverride Sub TestMethod(arg1 As String, arg2 As String) End Class Public Interface ITest Sub TestMethod(interfaceArg1 As String, interfaceArg2 As String) End Interface Public Class TestClass Inherits BaseClass Implements ITest Public Overrides Sub TestMethod(interfaceArg1 As String, interfaceArg2 As String) Implements ITest.TestMethod End Sub End Class", GetBasicResultAt(13, 63, "Sub TestClass.TestMethod(interfaceArg1 As String, interfaceArg2 As String)", "interfaceArg1", "arg1", "Sub BaseClass.TestMethod(arg1 As String, arg2 As String)"), GetBasicResultAt(13, 88, "Sub TestClass.TestMethod(interfaceArg1 As String, interfaceArg2 As String)", "interfaceArg2", "arg2", "Sub BaseClass.TestMethod(arg1 As String, arg2 As String)")); } [Fact] public async Task VerifyMultipleClashingInterfacesWithFullMatchAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public interface ITest1 { void TestMethod(string arg1, string arg2); } public interface ITest2 { void TestMethod(string otherArg1, string otherArg2); } public class TestClass : ITest1, ITest2 { public void TestMethod(string arg1, string arg2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface ITest1 Sub TestMethod(arg1 As String, arg2 As String) End Interface Public Interface ITest2 Sub TestMethod(otherArg1 As String, otherArg2 As String) End Interface Public Class TestClass Implements ITest1, ITest2 Public Sub TestMethod(arg1 As String, arg2 As String) Implements ITest1.TestMethod, ITest2.TestMethod End Sub End Class"); } [Fact] public async Task VerifyMultipleClashingInterfacesWithPartialMatchAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public interface ITest1 { void TestMethod(string arg1, string arg2, string arg3); } public interface ITest2 { void TestMethod(string otherArg1, string otherArg2, string otherArg3); } public class TestClass : ITest1, ITest2 { public void TestMethod(string arg1, string arg2, string otherArg3) { } }", GetCSharpResultAt(13, 88, "void TestClass.TestMethod(string arg1, string arg2, string otherArg3)", "otherArg3", "arg3", "void ITest1.TestMethod(string arg1, string arg2, string arg3)")); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface ITest1 Sub TestMethod(arg1 As String, arg2 As String, arg3 As String) End Interface Public Interface ITest2 Sub TestMethod(otherArg1 As String, otherArg2 As String, otherArg3 As String) End Interface Public Class TestClass Implements ITest1, ITest2 Public Sub TestMethod(arg1 As String, arg2 As String, otherArg3 As String) Implements ITest1.TestMethod, ITest2.TestMethod End Sub End Class", GetBasicResultAt(12, 85, "Sub TestClass.TestMethod(arg1 As String, arg2 As String, otherArg3 As String)", "otherArg3", "arg3", "Sub ITest1.TestMethod(arg1 As String, arg2 As String, arg3 As String)")); } [Fact] public async Task VerifyIgnoresPropertiesWithTheSameNameAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public interface ITest1 { void TestMethod(string arg1, string arg2); } public interface ITest2 { int TestMethod { get; set; } } public class TestClass : ITest1, ITest2 { public void TestMethod(string arg1, string arg2) { } int ITest2.TestMethod { get; set; } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface ITest1 Sub TestMethod(arg1 As String, arg2 As String) End Interface Public Interface ITest2 Property TestMethod As Integer End Interface Public Class TestClass Implements ITest1, ITest2 Public Sub TestMethod(arg1 As String, arg2 As String) Implements ITest1.TestMethod End Sub Private Property TestMethodFromITest2 As Integer Implements ITest2.TestMethod End Class"); } [Fact] public async Task VerifyHandlesMultipleBaseMethodsWithTheSameNameAsync() { await VerifyCS.VerifyAnalyzerAsync(@"public interface ITest { void TestMethod(string arg1); void TestMethod(string arg1, string arg2); } public class TestClass : ITest { public void TestMethod(string arg1) { } public void TestMethod(string arg1, string arg2) { } }"); await VerifyVB.VerifyAnalyzerAsync(@"Public Interface ITest Sub TestMethod(arg1 As String) Sub TestMethod(arg1 As String, arg2 As String) End Interface Public Class TestClass Implements ITest Public Sub TestMethod(arg1 As String) Implements ITest.TestMethod End Sub Public Sub TestMethod(arg1 As String, arg2 As String) Implements ITest.TestMethod End Sub End Class"); } private static DiagnosticResult GetCSharpResultAt(int line, int column, string violatingMember, string violatingParameter, string baseParameter, string baseMember) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(violatingMember, violatingParameter, baseParameter, baseMember); private static DiagnosticResult GetBasicResultAt(int line, int column, string violatingMember, string violatingParameter, string baseParameter, string baseMember) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic() .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(violatingMember, violatingParameter, baseParameter, baseMember); } }
using System; using System.IO; using IronPython.Hosting; using Microsoft.Scripting; using Microsoft.Scripting.Hosting; using System.Collections.Generic; namespace IronPythonConsole { class IPConsole { private ScriptEngine engine; private ScriptScope scope; private string script; private string old_code; private List<string> old_entries; private int old_entry_num; private int line; private string cmd_prefix; private string new_cmd_line_prefix; private string identation_indicator; private PythonAutoComplete autocompleter; public IPConsole() { script = ""; old_code = ""; old_entries = new List<string>(); old_entry_num = 0; line = 1; cmd_prefix = ">>> "; new_cmd_line_prefix = "...."; identation_indicator = "...."; engine = Python.CreateEngine (); scope = engine.CreateScope (); var coll = engine.GetSearchPaths (); coll.Add ("."); coll.Add("./ipython-lib"); coll.Add("./ipython-dlls"); engine.SetSearchPaths(coll); this.autocompleter = new PythonAutoComplete (this.engine, this.scope); } private void handle_backspace() { if (script.Length == 0) return; script = script.Remove(script.Length - 1); Console.Write("\b \b"); } private void handle_up_or_downarrow() { foreach (char c in script) { Console.Write("\b"); } if (old_entries.Count + old_entry_num >= old_entries.Count || old_entries.Count + old_entry_num < 0) { old_entry_num = 0; script = ""; } else { script = old_entries[old_entries.Count + old_entry_num]; Console.Write(script); } } private void handle_uparrow() { old_entry_num--; handle_up_or_downarrow (); } private void handle_downarrow() { old_entry_num++; handle_up_or_downarrow (); } private void handle_enter() { old_entry_num = 0; Console.Write("\n"); old_code += script + "\n"; line++; old_entries.Add(script); ScriptSource source = engine.CreateScriptSourceFromString (script); try { CompiledCode code = source.Compile (); code.Execute (scope); } catch (System.Exception e) { Console.WriteLine(e.GetType().Name + ": " + e.Message); } script = ""; Console.Write(this.cmd_prefix); } private void handle_tab() { try { AutocompleteInfo[] ret = this.autocompleter.GenerateCompletionData(script); if (ret.Length == 0) return; if (ret.Length == 1) { Console.Write(ret[0].complete); script += ret[0].complete; } else { Console.Write("\n"); foreach (AutocompleteInfo aci in ret) { Console.WriteLine(aci.stub); } Console.Write(this.cmd_prefix + script + ret[0].common_starter_complete); script += ret[0].common_starter_complete; } } catch (System.Exception e) { Console.WriteLine(e.GetType().Name + ": " + e.Message); } } public void main_loop() { Console.WriteLine ("Please type your python code:"); ConsoleKeyInfo keyinfo; Console.Write (this.cmd_prefix); do { keyinfo = Console.ReadKey(true); if (keyinfo.Key == ConsoleKey.Backspace) { this.handle_backspace(); } else if (keyinfo.Key == ConsoleKey.UpArrow) { this.handle_uparrow(); } else if (keyinfo.Key == ConsoleKey.DownArrow) { this.handle_downarrow(); } else if (keyinfo.Key == ConsoleKey.Enter && (keyinfo.Modifiers & ConsoleModifiers.Shift) == 0) { this.handle_enter(); } else if (keyinfo.Key == ConsoleKey.Tab && (keyinfo.Modifiers & ConsoleModifiers.Shift) == 0) { this.handle_tab(); } else if (keyinfo.Key == ConsoleKey.Enter) { Console.Write(Environment.NewLine + this.new_cmd_line_prefix); script += "\n"; } else if (keyinfo.Key == ConsoleKey.Tab) { string script_trim_res = script.Substring(script.LastIndexOf('\n') + 1).Trim(); if (script_trim_res == string.Empty) Console.Write(this.identation_indicator); else Console.Write(" "); script += " "; } else if (keyinfo.KeyChar == '\0') { continue; } else { Console.Write(keyinfo.KeyChar); script += keyinfo.KeyChar; } } while (keyinfo.Key != ConsoleKey.Escape); } } class MainClass { public static void Main (string[] args) { IPConsole cs = new IPConsole (); cs.main_loop (); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.ServiceDiscovery.Rewrite; using Gigya.Microdot.SharedLogic.Rewrite; using Gigya.Microdot.Testing.Shared; using Ninject; using NSubstitute; using NUnit.Framework; using Shouldly; namespace Gigya.Microdot.UnitTests.Discovery.Rewrite { [TestFixture,Parallelizable(ParallelScope.Fixtures)] public class MultiEnvironmentConsulDiscoveryMasterFallBackTest { private const string ServiceVersion = "1.2.30.1234"; private string _serviceName; private const string MASTER_ENVIRONMENT = "prod"; private const string ORIGINATING_ENVIRONMENT = "fake_env"; private Dictionary<string, string> _configDic; private TestingKernel<ConsoleLog> _unitTestingKernel; private Dictionary<DeploymentIdentifier, ILoadBalancer> _loadBalancers; private Dictionary<DeploymentIdentifier, Func<Node>> _nodeResults; private HashSet<DeploymentIdentifier> _consulServiceList; private IEnvironment _environment; private IDateTime _dateTimeMock; private int id; private const int Repeat = 1; [SetUp] public void SetUp() { _unitTestingKernel?.Dispose(); _serviceName = $"ServiceName{++id}"; _environment = Substitute.For<IEnvironment>(); _environment.Zone.Returns("il3"); _environment.DeploymentEnvironment.Returns(ORIGINATING_ENVIRONMENT); _environment.ConsulAddress.Returns((string)null); _configDic = new Dictionary<string, string> { { "Discovery.EnvironmentFallbackEnabled", "true" } }; _unitTestingKernel = new TestingKernel<ConsoleLog>(k => { k.Rebind<IEnvironment>().ToConstant(_environment); k.Rebind<IDiscovery>().To<ServiceDiscovery.Rewrite.Discovery>().InSingletonScope(); SetupConsulMocks(k); _dateTimeMock = Substitute.For<IDateTime>(); _dateTimeMock.Delay(Arg.Any<TimeSpan>()).Returns(c => Task.Delay(TimeSpan.FromMilliseconds(100))); k.Rebind<IDateTime>().ToConstant(_dateTimeMock); }, _configDic); var environment = _unitTestingKernel.Get<IEnvironment>(); Assert.AreEqual(_environment, environment); } private void SetupConsulMocks(IKernel kernel) { _loadBalancers = new Dictionary<DeploymentIdentifier, ILoadBalancer>(); _nodeResults = new Dictionary<DeploymentIdentifier, Func<Node>>(); _consulServiceList = new HashSet<DeploymentIdentifier>(); var discovery = Substitute.For<IDiscovery>(); discovery.CreateLoadBalancer(Arg.Any<DeploymentIdentifier>(), Arg.Any<ReachabilityCheck>(), TrafficRoutingStrategy.RandomByRequestID).Returns(c => GetLoadBalancerMock(c.Arg<DeploymentIdentifier>())); kernel.Rebind<IDiscovery>().ToMethod(_ => discovery); CreateConsulMock(MasterService); CreateConsulMock(OriginatingService); } private ILoadBalancer CreateLoadBalancerMock(DeploymentIdentifier di) { var mock = Substitute.For<ILoadBalancer>(); mock.TryGetNode().Returns(_ => _consulServiceList.Contains(di) ? _nodeResults[di]() : null); return mock; } private ILoadBalancer GetLoadBalancerMock(DeploymentIdentifier di) { if (_loadBalancers.ContainsKey(di)) return _loadBalancers[di]; return CreateLoadBalancerMock(di); } private void CreateConsulMock(DeploymentIdentifier di) { var mock = CreateLoadBalancerMock(di); _nodeResults[di] = () => new ConsulNode(hostName: "dummy", version: ServiceVersion) ; _loadBalancers[di] = mock; _consulServiceList.Add(di); } [TearDown] public void TearDown() { _unitTestingKernel.Dispose(); } [Test] [Repeat(Repeat)] public async Task ServiceNotExistsShouldFallBackToMaster() { SetMockToReturnHost(MasterService); SetMockToReturnServiceNotDefined(OriginatingService); var nextHost = await GetServiceDiscovery().GetNode(); nextHost.Node.Hostname.ShouldBe(HostnameFor(MasterService)); } [Test] [Repeat(Repeat)] public async Task FallbackDisabledByConsul_ShouldNotFallBackToMaster() { _configDic[$"Discovery.EnvironmentFallbackEnabled"] = "false"; SetMockToReturnHost(MasterService); SetMockToReturnServiceNotDefined(OriginatingService); Should.ThrowAsync<EnvironmentException>(()=>GetServiceDiscovery().GetNode()); } [Test] [Repeat(Repeat)] public async Task WhenServiceDeletedShouldFallBackToMaster() { var reloadInterval = TimeSpan.FromMilliseconds(5); _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); SetMockToReturnHost(MasterService); SetMockToReturnHost(OriginatingService); var discovey = GetServiceDiscovery(); var node = await discovey.GetNode(); node.Node.Hostname.ShouldBe(HostnameFor(OriginatingService)); SetMockToReturnServiceNotDefined(OriginatingService); node = await discovey.GetNode(); node.Node.Hostname.ShouldBe(HostnameFor(MasterService)); } [Test] [Repeat(Repeat)] public async Task WhenServiceAddedShouldNotFallBackToMaster() { var reloadInterval = TimeSpan.FromMilliseconds(5); _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); SetMockToReturnHost(MasterService); SetMockToReturnServiceNotDefined(OriginatingService); var discovey = GetServiceDiscovery(); var node = await discovey.GetNode(); node.Node.Hostname.ShouldBe(HostnameFor(MasterService)); SetMockToReturnHost(OriginatingService); node = await discovey.GetNode(); node.Node.Hostname.ShouldBe(HostnameFor(OriginatingService)); } [Test] [Repeat(Repeat)] public async Task ShouldNotFallBackToMasterOnConsulError() { SetMockToReturnHost(MasterService); SetMockToReturnError(OriginatingService); Should.Throw<EnvironmentException>(async () => await GetServiceDiscovery().GetNode()); } [Test] [Repeat(Repeat)] public async Task ServiceExistsShouldNotFallBackToMaster() { SetMockToReturnHost(MasterService); SetMockToReturnHost(OriginatingService); var nextHost = await GetServiceDiscovery().GetNode(); nextHost.Node.Hostname.ShouldBe(HostnameFor(OriginatingService)); } [Test] [Repeat(Repeat)] public void MasterShouldNotFallBack() { _environment = Substitute.For<IEnvironment>(); _environment.Zone.Returns("il3"); _environment.DeploymentEnvironment.Returns(MASTER_ENVIRONMENT); _unitTestingKernel.Rebind<IEnvironment>().ToConstant(_environment); SetMockToReturnServiceNotDefined(MasterService); Should.ThrowAsync<EnvironmentException>(() => GetServiceDiscovery().GetNode()); } private void SetMockToReturnHost(DeploymentIdentifier di) { if (!_loadBalancers.ContainsKey(di)) CreateConsulMock(di); var newNode = new Node(HostnameFor(di)); _nodeResults[di] = () => newNode; _consulServiceList.Add(di); } private void SetMockToReturnServiceNotDefined(DeploymentIdentifier di) { _consulServiceList.Remove(di); } private void SetMockToReturnError(DeploymentIdentifier di) { _nodeResults[di] = () => throw new EnvironmentException("Mock: some error"); } [Test] public void ServiceDiscoveySameNameShouldBeTheSame() { Assert.AreEqual(GetServiceDiscovery(), GetServiceDiscovery()); } private IMultiEnvironmentServiceDiscovery GetServiceDiscovery() { var discovery = _unitTestingKernel.Get<Func<string, ReachabilityCheck, IMultiEnvironmentServiceDiscovery>>()(_serviceName, (n, c) => Task.FromResult(true)); return discovery; } private DeploymentIdentifier MasterService => new DeploymentIdentifier(_serviceName, MASTER_ENVIRONMENT, _environment); private DeploymentIdentifier OriginatingService => new DeploymentIdentifier(_serviceName, ORIGINATING_ENVIRONMENT, _environment); private string HostnameFor(DeploymentIdentifier di) => $"{di.DeploymentEnvironment}-host"; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Test { public class ImmutableListBuilderTest : ImmutableListTestBase { [Fact] public void CreateBuilder() { ImmutableList<string>.Builder builder = ImmutableList.CreateBuilder<string>(); Assert.NotNull(builder); } [Fact] public void ToBuilder() { var builder = ImmutableList<int>.Empty.ToBuilder(); builder.Add(3); builder.Add(5); builder.Add(5); Assert.Equal(3, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var list = builder.ToImmutable(); Assert.Equal(builder.Count, list.Count); builder.Add(8); Assert.Equal(4, builder.Count); Assert.Equal(3, list.Count); Assert.True(builder.Contains(8)); Assert.False(list.Contains(8)); } [Fact] public void BuilderFromList() { var list = ImmutableList<int>.Empty.Add(1); var builder = list.ToBuilder(); Assert.True(builder.Contains(1)); builder.Add(3); builder.Add(5); builder.Add(5); Assert.Equal(4, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var list2 = builder.ToImmutable(); Assert.Equal(builder.Count, list2.Count); Assert.True(list2.Contains(1)); builder.Add(8); Assert.Equal(5, builder.Count); Assert.Equal(4, list2.Count); Assert.True(builder.Contains(8)); Assert.False(list.Contains(8)); Assert.False(list2.Contains(8)); } [Fact] public void SeveralChanges() { var mutable = ImmutableList<int>.Empty.ToBuilder(); var immutable1 = mutable.ToImmutable(); Assert.Same(immutable1, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences."); mutable.Add(1); var immutable2 = mutable.ToImmutable(); Assert.NotSame(immutable1, immutable2); //, "Mutating the collection did not reset the Immutable property."); Assert.Same(immutable2, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences."); Assert.Equal(1, immutable2.Count); } [Fact] public void EnumerateBuilderWhileMutating() { var builder = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 10)).ToBuilder(); Assert.Equal(Enumerable.Range(1, 10), builder); var enumerator = builder.GetEnumerator(); Assert.True(enumerator.MoveNext()); builder.Add(11); // Verify that a new enumerator will succeed. Assert.Equal(Enumerable.Range(1, 11), builder); // Try enumerating further with the previous enumerable now that we've changed the collection. Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.Reset(); enumerator.MoveNext(); // resetting should fix the problem. // Verify that by obtaining a new enumerator, we can enumerate all the contents. Assert.Equal(Enumerable.Range(1, 11), builder); } [Fact] public void BuilderReusesUnchangedImmutableInstances() { var collection = ImmutableList<int>.Empty.Add(1); var builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // no changes at all. builder.Add(2); var newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. } [Fact] public void Insert() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.Insert(0, 1); mutable.Insert(0, 0); mutable.Insert(2, 3); Assert.Equal(new[] { 0, 1, 3 }, mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.Insert(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.Insert(4, 0)); } [Fact] public void InsertRange() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.InsertRange(0, new[] { 1, 4, 5 }); Assert.Equal(new[] { 1, 4, 5 }, mutable); mutable.InsertRange(1, new[] { 2, 3 }); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, mutable); mutable.InsertRange(5, new[] { 6 }); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable); mutable.InsertRange(5, new int[0]); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(-1, new int[0])); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(mutable.Count + 1, new int[0])); } [Fact] public void AddRange() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.AddRange(new[] { 1, 4, 5 }); Assert.Equal(new[] { 1, 4, 5 }, mutable); mutable.AddRange(new[] { 2, 3 }); Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable); mutable.AddRange(new int[0]); Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable); Assert.Throws<ArgumentNullException>(() => mutable.AddRange(null)); } [Fact] public void Remove() { var mutable = ImmutableList<int>.Empty.ToBuilder(); Assert.False(mutable.Remove(5)); mutable.Add(1); mutable.Add(2); mutable.Add(3); Assert.True(mutable.Remove(2)); Assert.Equal(new[] { 1, 3 }, mutable); Assert.True(mutable.Remove(1)); Assert.Equal(new[] { 3 }, mutable); Assert.True(mutable.Remove(3)); Assert.Equal(new int[0], mutable); Assert.False(mutable.Remove(5)); } [Fact] public void RemoveAt() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.Add(1); mutable.Add(2); mutable.Add(3); mutable.RemoveAt(2); Assert.Equal(new[] { 1, 2 }, mutable); mutable.RemoveAt(0); Assert.Equal(new[] { 2 }, mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(1)); mutable.RemoveAt(0); Assert.Equal(new int[0], mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(0)); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.RemoveAt(1)); } [Fact] public void Reverse() { var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); mutable.Reverse(); Assert.Equal(Enumerable.Range(1, 3).Reverse(), mutable); } [Fact] public void Clear() { var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); mutable.Clear(); Assert.Equal(0, mutable.Count); // Do it again for good measure. :) mutable.Clear(); Assert.Equal(0, mutable.Count); } [Fact] public void IsReadOnly() { ICollection<int> builder = ImmutableList.Create<int>().ToBuilder(); Assert.False(builder.IsReadOnly); } [Fact] public void Indexer() { var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Equal(2, mutable[1]); mutable[1] = 5; Assert.Equal(5, mutable[1]); mutable[0] = -2; mutable[2] = -3; Assert.Equal(new[] { -2, 5, -3 }, mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable[3] = 4); Assert.Throws<ArgumentOutOfRangeException>(() => mutable[-1] = 4); Assert.Throws<ArgumentOutOfRangeException>(() => mutable[3]); Assert.Throws<ArgumentOutOfRangeException>(() => mutable[-1]); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => ImmutableList.CreateRange(seq).ToBuilder(), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => ImmutableList.CreateRange(seq).ToBuilder(), (b, v) => b.LastIndexOf(v), (b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void GetEnumeratorExplicit() { ICollection<int> builder = ImmutableList.Create<int>().ToBuilder(); var enumerator = builder.GetEnumerator(); Assert.NotNull(enumerator); } [Fact] public void IsSynchronized() { ICollection collection = ImmutableList.Create<int>().ToBuilder(); Assert.False(collection.IsSynchronized); } [Fact] public void IListMembers() { IList list = ImmutableList.Create<int>().ToBuilder(); Assert.False(list.IsReadOnly); Assert.False(list.IsFixedSize); Assert.Equal(0, list.Add(5)); Assert.Equal(1, list.Add(8)); Assert.True(list.Contains(5)); Assert.False(list.Contains(7)); list.Insert(1, 6); Assert.Equal(6, list[1]); list.Remove(5); list[0] = 9; Assert.Equal(new[] { 9, 8 }, list.Cast<int>().ToArray()); list.Clear(); Assert.Equal(0, list.Count); } [Fact] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableList.CreateBuilder<int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableList.CreateBuilder<string>()); } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { return ImmutableList<T>.Empty.AddRange(contents).ToBuilder(); } protected override void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test) { var builder = list.ToBuilder(); var bcl = list.ToList(); int expected = bcl.RemoveAll(test); var actual = builder.RemoveAll(test); Assert.Equal(expected, actual); Assert.Equal<T>(bcl, builder.ToList()); } protected override void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count) { var expected = list.ToList(); expected.Reverse(index, count); var builder = list.ToBuilder(); builder.Reverse(index, count); Assert.Equal<T>(expected, builder.ToList()); } #if NET45PLUS internal override ImmutableList<T> GetListQuery<T>(ImmutableList<T> list) { return list; } #else internal override IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list) { return list.ToBuilder(); } #endif protected override List<T> SortTestHelper<T>(ImmutableList<T> list) { var builder = list.ToBuilder(); builder.Sort(); return builder.ToImmutable().ToList(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison) { var builder = list.ToBuilder(); builder.Sort(comparison); return builder.ToImmutable().ToList(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer) { var builder = list.ToBuilder(); builder.Sort(comparer); return builder.ToImmutable().ToList(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer) { var builder = list.ToBuilder(); builder.Sort(index, count, comparer); return builder.ToImmutable().ToList(); } } }
//------------------------------------------------------------------------------ // <copyright file="DataControlFieldCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.ComponentModel; /// <devdoc> /// <para>Represents the collection of fields to be displayed in /// a data bound control that uses fields.</para> /// </devdoc> public sealed class DataControlFieldCollection : StateManagedCollection { private static readonly Type[] knownTypes = new Type[] { typeof(BoundField), typeof(ButtonField), typeof(CheckBoxField), typeof(CommandField), typeof(HyperLinkField), typeof(ImageField), typeof(TemplateField) }; public event EventHandler FieldsChanged; /// <devdoc> /// <para>Gets a <see cref='System.Web.UI.WebControls.DataControlField'/> at the specified index in the /// collection.</para> /// </devdoc> [ Browsable(false) ] public DataControlField this[int index] { get { return ((IList)this)[index] as DataControlField; } } /// <devdoc> /// <para>Appends a <see cref='System.Web.UI.WebControls.DataControlField'/> to the collection.</para> /// </devdoc> public void Add(DataControlField field) { ((IList)this).Add(field); } /// <devdoc> /// <para>Provides a deep copy of the collection. Used mainly by design time dialogs to implement "cancel" rollback behavior.</para> /// </devdoc> public DataControlFieldCollection CloneFields() { DataControlFieldCollection fields = new DataControlFieldCollection(); foreach (DataControlField field in this) { fields.Add(field.CloneField()); } return fields; } /// <devdoc> /// <para>Returns whether a DataControlField is a member of the collection.</para> /// </devdoc> public bool Contains(DataControlField field) { return ((IList)this).Contains(field); } /// <devdoc> /// <para>Copies the contents of the entire collection into an <see cref='System.Array' qualify='true'/> appending at /// the specified index of the <see cref='System.Array' qualify='true'/>.</para> /// </devdoc> public void CopyTo(DataControlField[] array, int index) { ((IList)this).CopyTo(array, index); return; } /// <devdoc> /// <para>Creates a known type of DataControlField.</para> /// </devdoc> protected override object CreateKnownType(int index) { switch (index) { case 0: return new BoundField(); case 1: return new ButtonField(); case 2: return new CheckBoxField(); case 3: return new CommandField(); case 4: return new HyperLinkField(); case 5: return new ImageField(); case 6: return new TemplateField(); default: throw new ArgumentOutOfRangeException(SR.GetString(SR.DataControlFieldCollection_InvalidTypeIndex)); } } /// <devdoc> /// <para>Returns an ArrayList of known DataControlField types.</para> /// </devdoc> protected override Type[] GetKnownTypes() { return knownTypes; } /// <devdoc> /// <para>Returns the index of the first occurrence of a value in a <see cref='System.Web.UI.WebControls.DataControlField'/>.</para> /// </devdoc> public int IndexOf(DataControlField field) { return ((IList)this).IndexOf(field); } /// <devdoc> /// <para>Inserts a <see cref='System.Web.UI.WebControls.DataControlField'/> to the collection /// at the specified index.</para> /// </devdoc> public void Insert(int index, DataControlField field) { ((IList)this).Insert(index, field); } /// <devdoc> /// Called when the Clear() method is complete. /// </devdoc> protected override void OnClearComplete() { OnFieldsChanged(); } /// <devdoc> /// </devdoc> void OnFieldChanged(object sender, EventArgs e) { OnFieldsChanged(); } /// <devdoc> /// </devdoc> void OnFieldsChanged() { if (FieldsChanged != null) { FieldsChanged(this, EventArgs.Empty); } } /// <devdoc> /// Called when the Insert() method is complete. /// </devdoc> protected override void OnInsertComplete(int index, object value) { DataControlField field = value as DataControlField; if (field != null) { field.FieldChanged += new EventHandler(OnFieldChanged); } OnFieldsChanged(); } /// <devdoc> /// Called when the Remove() method is complete. /// </devdoc> protected override void OnRemoveComplete(int index, object value) { DataControlField field = value as DataControlField; if (field != null) { field.FieldChanged -= new EventHandler(OnFieldChanged); } OnFieldsChanged(); } /// <devdoc> /// <para>Validates that an object is a HotSpot.</para> /// </devdoc> protected override void OnValidate(object o) { base.OnValidate(o); if (!(o is DataControlField)) throw new ArgumentException(SR.GetString(SR.DataControlFieldCollection_InvalidType)); } /// <devdoc> /// <para>Removes a <see cref='System.Web.UI.WebControls.DataControlField'/> from the collection at the specified /// index.</para> /// </devdoc> public void RemoveAt(int index) { ((IList)this).RemoveAt(index); } /// <devdoc> /// <para>Removes the specified <see cref='System.Web.UI.WebControls.DataControlField'/> from the collection.</para> /// </devdoc> public void Remove(DataControlField field) { ((IList)this).Remove(field); } /// <devdoc> /// <para>Marks a DataControlField as dirty so that it will record its entire state into view state.</para> /// </devdoc> protected override void SetDirtyObject(object o) { ((DataControlField)o).SetDirty(); } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace Core.Settings.LocaleAndLanguageWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using Csla; using ParentLoad.DataAccess; using ParentLoad.DataAccess.ERCLevel; namespace ParentLoad.Business.ERCLevel { /// <summary> /// B09_Region_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="B09_Region_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="B08_Region"/> collection. /// </remarks> [Serializable] public partial class B09_Region_ReChild : BusinessBase<B09_Region_ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int region_ID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_Child_NameProperty = RegisterProperty<string>(p => p.Region_Child_Name, "Region Child Name"); /// <summary> /// Gets or sets the Region Child Name. /// </summary> /// <value>The Region Child Name.</value> public string Region_Child_Name { get { return GetProperty(Region_Child_NameProperty); } set { SetProperty(Region_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="B09_Region_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="B09_Region_ReChild"/> object.</returns> internal static B09_Region_ReChild NewB09_Region_ReChild() { return DataPortal.CreateChild<B09_Region_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="B09_Region_ReChild"/> object from the given B09_Region_ReChildDto. /// </summary> /// <param name="data">The <see cref="B09_Region_ReChildDto"/>.</param> /// <returns>A reference to the fetched <see cref="B09_Region_ReChild"/> object.</returns> internal static B09_Region_ReChild GetB09_Region_ReChild(B09_Region_ReChildDto data) { B09_Region_ReChild obj = new B09_Region_ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(data); obj.MarkOld(); // check all object rules and property rules obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="B09_Region_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public B09_Region_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="B09_Region_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="B09_Region_ReChild"/> object from the given <see cref="B09_Region_ReChildDto"/>. /// </summary> /// <param name="data">The B09_Region_ReChildDto to use.</param> private void Fetch(B09_Region_ReChildDto data) { // Value properties LoadProperty(Region_Child_NameProperty, data.Region_Child_Name); // parent properties region_ID2 = data.Parent_Region_ID; var args = new DataPortalHookArgs(data); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="B09_Region_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(B08_Region parent) { var dto = new B09_Region_ReChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnInsertPre(args); var dal = dalManager.GetProvider<IB09_Region_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Insert(dto); args = new DataPortalHookArgs(resultDto); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="B09_Region_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(B08_Region parent) { if (!IsDirty) return; var dto = new B09_Region_ReChildDto(); dto.Parent_Region_ID = parent.Region_ID; dto.Region_Child_Name = Region_Child_Name; using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(dto); OnUpdatePre(args); var dal = dalManager.GetProvider<IB09_Region_ReChildDal>(); using (BypassPropertyChecks) { var resultDto = dal.Update(dto); args = new DataPortalHookArgs(resultDto); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="B09_Region_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(B08_Region parent) { using (var dalManager = DalFactoryParentLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IB09_Region_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Region_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Runtime.InteropServices; using Xunit; using System.Numerics; namespace System.Numerics.Tests { public class PlaneTests { // A test for Equals (Plane) [Fact] public void PlaneEqualsTest1() { Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f); Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = true; bool actual = a.Equals(b); Assert.Equal(expected, actual); // case 2: compare between different values b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z); expected = false; actual = a.Equals(b); Assert.Equal(expected, actual); } // A test for Equals (object) [Fact] public void PlaneEqualsTest() { Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f); Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values object obj = b; bool expected = true; bool actual = a.Equals(obj); Assert.Equal(expected, actual); // case 2: compare between different values b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z); obj = b; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare between different types. obj = new Quaternion(); expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare against null. obj = null; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); } // A test for operator != (Plane, Plane) [Fact] public void PlaneInequalityTest() { Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f); Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = false; bool actual = a != b; Assert.Equal(expected, actual); // case 2: compare between different values b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z); expected = true; actual = a != b; Assert.Equal(expected, actual); } // A test for operator == (Plane, Plane) [Fact] public void PlaneEqualityTest() { Plane a = new Plane(1.0f, 2.0f, 3.0f, 4.0f); Plane b = new Plane(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = true; bool actual = a == b; Assert.Equal(expected, actual); // case 2: compare between different values b.Normal = new Vector3(10.0f, b.Normal.Y, b.Normal.Z); expected = false; actual = a == b; Assert.Equal(expected, actual); } // A test for GetHashCode () [Fact] public void PlaneGetHashCodeTest() { Plane target = new Plane(1.0f, 2.0f, 3.0f, 4.0f); int expected = target.Normal.GetHashCode() + target.D.GetHashCode(); int actual = target.GetHashCode(); Assert.Equal(expected, actual); } // A test for Plane (float, float, float, float) [Fact] public void PlaneConstructorTest1() { float a = 1.0f, b = 2.0f, c = 3.0f, d = 4.0f; Plane target = new Plane(a, b, c, d); Assert.True( target.Normal.X == a && target.Normal.Y == b && target.Normal.Z == c && target.D == d, "Plane.cstor did not return the expected value."); } // A test for Plane.CreateFromVertices [Fact] public void PlaneCreateFromVerticesTest() { Vector3 point1 = new Vector3(0.0f, 1.0f, 1.0f); Vector3 point2 = new Vector3(0.0f, 0.0f, 1.0f); Vector3 point3 = new Vector3(1.0f, 0.0f, 1.0f); Plane target = Plane.CreateFromVertices(point1, point2, point3); Plane expected = new Plane(new Vector3(0, 0, 1), -1.0f); Assert.Equal(target, expected); } // A test for Plane.CreateFromVertices [Fact] public void PlaneCreateFromVerticesTest2() { Vector3 point1 = new Vector3(0.0f, 0.0f, 1.0f); Vector3 point2 = new Vector3(1.0f, 0.0f, 0.0f); Vector3 point3 = new Vector3(1.0f, 1.0f, 0.0f); Plane target = Plane.CreateFromVertices(point1, point2, point3); float invRoot2 = (float)(1 / Math.Sqrt(2)); Plane expected = new Plane(new Vector3(invRoot2, 0, invRoot2), -invRoot2); Assert.True(MathHelper.Equal(target, expected), "Plane.cstor did not return the expected value."); } // A test for Plane (Vector3f, float) [Fact] public void PlaneConstructorTest3() { Vector3 normal = new Vector3(1, 2, 3); float d = 4; Plane target = new Plane(normal, d); Assert.True( target.Normal == normal && target.D == d, "Plane.cstor did not return the expected value."); } // A test for Plane (Vector4f) [Fact] public void PlaneConstructorTest() { Vector4 value = new Vector4(1.0f, 2.0f, 3.0f, 4.0f); Plane target = new Plane(value); Assert.True( target.Normal.X == value.X && target.Normal.Y == value.Y && target.Normal.Z == value.Z && target.D == value.W, "Plane.cstor did not return the expected value."); } [Fact] public void PlaneDotTest() { Plane target = new Plane(2, 3, 4, 5); Vector4 value = new Vector4(5, 4, 3, 2); float expected = 10 + 12 + 12 + 10; float actual = Plane.Dot(target, value); Assert.True(MathHelper.Equal(expected, actual), "Plane.Dot returns unexpected value."); } [Fact] public void PlaneDotCoordinateTest() { Plane target = new Plane(2, 3, 4, 5); Vector3 value = new Vector3(5, 4, 3); float expected = 10 + 12 + 12 + 5; float actual = Plane.DotCoordinate(target, value); Assert.True(MathHelper.Equal(expected, actual), "Plane.DotCoordinate returns unexpected value."); } [Fact] public void PlaneDotNormalTest() { Plane target = new Plane(2, 3, 4, 5); Vector3 value = new Vector3(5, 4, 3); float expected = 10 + 12 + 12; float actual = Plane.DotNormal(target, value); Assert.True(MathHelper.Equal(expected, actual), "Plane.DotCoordinate returns unexpected value."); } [Fact] public void PlaneNormalizeTest() { Plane target = new Plane(1, 2, 3, 4); float f = target.Normal.LengthSquared(); float invF = 1.0f / (float)Math.Sqrt(f); Plane expected = new Plane(target.Normal * invF, target.D * invF); Plane actual = Plane.Normalize(target); Assert.True(MathHelper.Equal(expected, actual), "Plane.Normalize returns unexpected value."); // normalize, normalized normal. actual = Plane.Normalize(actual); Assert.True(MathHelper.Equal(expected, actual), "Plane.Normalize returns unexpected value."); } [Fact] // Transform by matrix public void PlaneTransformTest1() { Plane target = new Plane(1, 2, 3, 4); target = Plane.Normalize(target); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); m.M41 = 10.0f; m.M42 = 20.0f; m.M43 = 30.0f; Plane expected = new Plane(); Matrix4x4 inv; Matrix4x4.Invert(m, out inv); Matrix4x4 itm = Matrix4x4.Transpose(inv); float x = target.Normal.X, y = target.Normal.Y, z = target.Normal.Z, w = target.D; expected.Normal = new Vector3( x * itm.M11 + y * itm.M21 + z * itm.M31 + w * itm.M41, x * itm.M12 + y * itm.M22 + z * itm.M32 + w * itm.M42, x * itm.M13 + y * itm.M23 + z * itm.M33 + w * itm.M43); expected.D = x * itm.M14 + y * itm.M24 + z * itm.M34 + w * itm.M44; Plane actual; actual = Plane.Transform(target, m); Assert.True(MathHelper.Equal(expected, actual), "Plane.Transform did not return the expected value."); } [Fact] // Transform by quaternion public void PlaneTransformTest2() { Plane target = new Plane(1, 2, 3, 4); target = Plane.Normalize(target); Matrix4x4 m = Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) * Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f)); Quaternion q = Quaternion.CreateFromRotationMatrix(m); Plane expected = new Plane(); float x = target.Normal.X, y = target.Normal.Y, z = target.Normal.Z, w = target.D; expected.Normal = new Vector3( x * m.M11 + y * m.M21 + z * m.M31 + w * m.M41, x * m.M12 + y * m.M22 + z * m.M32 + w * m.M42, x * m.M13 + y * m.M23 + z * m.M33 + w * m.M43); expected.D = x * m.M14 + y * m.M24 + z * m.M34 + w * m.M44; Plane actual; actual = Plane.Transform(target, q); Assert.True(MathHelper.Equal(expected, actual), "Plane.Transform did not return the expected value."); } // A test for Plane comparison involving NaN values [Fact] public void PlaneEqualsNanTest() { Plane a = new Plane(float.NaN, 0, 0, 0); Plane b = new Plane(0, float.NaN, 0, 0); Plane c = new Plane(0, 0, float.NaN, 0); Plane d = new Plane(0, 0, 0, float.NaN); Assert.False(a == new Plane(0, 0, 0, 0)); Assert.False(b == new Plane(0, 0, 0, 0)); Assert.False(c == new Plane(0, 0, 0, 0)); Assert.False(d == new Plane(0, 0, 0, 0)); Assert.True(a != new Plane(0, 0, 0, 0)); Assert.True(b != new Plane(0, 0, 0, 0)); Assert.True(c != new Plane(0, 0, 0, 0)); Assert.True(d != new Plane(0, 0, 0, 0)); Assert.False(a.Equals(new Plane(0, 0, 0, 0))); Assert.False(b.Equals(new Plane(0, 0, 0, 0))); Assert.False(c.Equals(new Plane(0, 0, 0, 0))); Assert.False(d.Equals(new Plane(0, 0, 0, 0))); // Counterintuitive result - IEEE rules for NaN comparison are weird! Assert.False(a.Equals(a)); Assert.False(b.Equals(b)); Assert.False(c.Equals(c)); Assert.False(d.Equals(d)); } /* Enable when size of Vector3 is correct // A test to make sure these types are blittable directly into GPU buffer memory layouts [Fact] public unsafe void PlaneSizeofTest() { Assert.Equal(16, sizeof(Plane)); Assert.Equal(32, sizeof(Plane_2x)); Assert.Equal(20, sizeof(PlanePlusFloat)); Assert.Equal(40, sizeof(PlanePlusFloat_2x)); } */ [StructLayout(LayoutKind.Sequential)] struct Plane_2x { Plane a; Plane b; } [StructLayout(LayoutKind.Sequential)] struct PlanePlusFloat { Plane v; float f; } [StructLayout(LayoutKind.Sequential)] struct PlanePlusFloat_2x { PlanePlusFloat a; PlanePlusFloat b; } //// A test to make sure the fields are laid out how we expect //[Fact] //public unsafe void PlaneFieldOffsetTest() //{ // Plane* ptr = (Plane*)0; // Assert.Equal(new IntPtr(0), new IntPtr(&ptr->Normal)); // Assert.Equal(new IntPtr(12), new IntPtr(&ptr->D)); //} } }
#region Using using System; #endregion namespace SharpCompress.Compressor.PPMd.I1 { /// <summary> /// A structure containing a single address representing a position in the <see cref="Memory"/> array. This /// is intended to mimic the behaviour of a pointer in C/C++. /// </summary> /// <remarks> /// <para> /// This must be a structure rather than a class because several places in the associated code assume that /// <see cref="Pointer"/> is a value type (meaning that assignment creates a completely new copy of the /// instance rather than just copying a reference to the same instance). /// </para> /// <para> /// Note that <see cref="Address"/> is a field rather than a property for performance reasons. /// </para> /// </remarks> internal struct Pointer { public uint Address; public byte[] Memory; public static readonly Pointer Zero = new Pointer(0, null); public const int Size = 1; /// <summary> /// Initializes a new instance of the <see cref="Pointer"/> structure. /// </summary> public Pointer(uint address, byte[] memory) { Address = address; Memory = memory; } /// <summary> /// Gets or sets the byte at the given <paramref name="offset"/>. /// </summary> /// <param name="offset"></param> /// <returns></returns> public byte this[int offset] { get { #if DEBUG if (Address == 0) throw new InvalidOperationException("The pointer being indexed is a null pointer."); #endif return Memory[Address + offset]; } set { #if DEBUG if (Address == 0) throw new InvalidOperationException("The pointer being indexed is a null pointer."); #endif Memory[Address + offset] = value; } } /// <summary> /// Allow a <see cref="MemoryNode"/> to be implicitly converted to a <see cref="Pointer"/>. /// </summary> /// <param name="memoryNode"></param> /// <returns></returns> public static implicit operator Pointer(MemoryNode memoryNode) { return new Pointer(memoryNode.Address, memoryNode.Memory); } /// <summary> /// Allow a <see cref="Model.PpmContext"/> to be implicitly converted to a <see cref="Pointer"/>. /// </summary> /// <param name="context"></param> /// <returns></returns> public static implicit operator Pointer(Model.PpmContext context) { return new Pointer(context.Address, context.Memory); } /// <summary> /// Allow a <see cref="PpmState"/> to be implicitly converted to a <see cref="Pointer"/>. /// </summary> /// <param name="state"></param> /// <returns></returns> public static implicit operator Pointer(PpmState state) { return new Pointer(state.Address, state.Memory); } /// <summary> /// Increase the address of a pointer by the given number of bytes. /// </summary> /// <param name="pointer"></param> /// <param name="offset"></param> /// <returns></returns> public static Pointer operator +(Pointer pointer, int offset) { #if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer is a null pointer."); #endif pointer.Address = (uint) (pointer.Address + offset); return pointer; } /// <summary> /// Increase the address of a pointer by the given number of bytes. /// </summary> /// <param name="pointer"></param> /// <param name="offset"></param> /// <returns></returns> public static Pointer operator +(Pointer pointer, uint offset) { #if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer is a null pointer."); #endif pointer.Address += offset; return pointer; } /// <summary> /// Increment the address of a pointer. /// </summary> /// <param name="pointer"></param> /// <returns></returns> public static Pointer operator ++(Pointer pointer) { #if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer being incremented is a null pointer."); #endif pointer.Address++; return pointer; } /// <summary> /// Decrease the address of a pointer by the given number of bytes. /// </summary> /// <param name="pointer"></param> /// <param name="offset"></param> /// <returns></returns> public static Pointer operator -(Pointer pointer, int offset) { #if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer is a null pointer."); #endif pointer.Address = (uint) (pointer.Address - offset); return pointer; } /// <summary> /// Decrease the address of a pointer by the given number of bytes. /// </summary> /// <param name="pointer"></param> /// <param name="offset"></param> /// <returns></returns> public static Pointer operator -(Pointer pointer, uint offset) { #if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer is a null pointer."); #endif pointer.Address -= offset; return pointer; } /// <summary> /// Decrement the address of a pointer. /// </summary> /// <param name="pointer"></param> /// <returns></returns> public static Pointer operator --(Pointer pointer) { #if DEBUG if (pointer.Address == 0) throw new InvalidOperationException("The pointer being decremented is a null pointer."); #endif pointer.Address--; return pointer; } /// <summary> /// Subtract two pointers. /// </summary> /// <param name="pointer1"></param> /// <param name="pointer2"></param> /// <returns>The number of bytes between the two pointers.</returns> public static uint operator -(Pointer pointer1, Pointer pointer2) { #if DEBUG if (pointer1.Address == 0) throw new InvalidOperationException( "The pointer to the left of the subtraction operator is a null pointer."); if (pointer2.Address == 0) throw new InvalidOperationException( "The pointer to the right of the subtraction operator is a null pointer."); #endif return pointer1.Address - pointer2.Address; } /// <summary> /// Compare pointers. /// </summary> /// <param name="pointer1"></param> /// <param name="pointer2"></param> /// <returns></returns> public static bool operator <(Pointer pointer1, Pointer pointer2) { #if DEBUG if (pointer1.Address == 0) throw new InvalidOperationException( "The pointer to the left of the less than operator is a null pointer."); if (pointer2.Address == 0) throw new InvalidOperationException( "The pointer to the right of the less than operator is a null pointer."); #endif return pointer1.Address < pointer2.Address; } /// <summary> /// Compare two pointers. /// </summary> /// <param name="pointer1"></param> /// <param name="pointer2"></param> /// <returns></returns> public static bool operator <=(Pointer pointer1, Pointer pointer2) { #if DEBUG if (pointer1.Address == 0) throw new InvalidOperationException( "The pointer to the left of the less than or equal to operator is a null pointer."); if (pointer2.Address == 0) throw new InvalidOperationException( "The pointer to the right of the less than or equal to operator is a null pointer."); #endif return pointer1.Address <= pointer2.Address; } /// <summary> /// Compare two pointers. /// </summary> /// <param name="pointer1"></param> /// <param name="pointer2"></param> /// <returns></returns> public static bool operator >(Pointer pointer1, Pointer pointer2) { #if DEBUG if (pointer1.Address == 0) throw new InvalidOperationException( "The pointer to the left of the greater than operator is a null pointer."); if (pointer2.Address == 0) throw new InvalidOperationException( "The pointer to the right of the greater than operator is a null pointer."); #endif return pointer1.Address > pointer2.Address; } /// <summary> /// Compare two pointers. /// </summary> /// <param name="pointer1"></param> /// <param name="pointer2"></param> /// <returns></returns> public static bool operator >=(Pointer pointer1, Pointer pointer2) { #if DEBUG if (pointer1.Address == 0) throw new InvalidOperationException( "The pointer to the left of the greater than or equal to operator is a null pointer."); if (pointer2.Address == 0) throw new InvalidOperationException( "The pointer to the right of the greater than or equal to operator is a null pointer."); #endif return pointer1.Address >= pointer2.Address; } /// <summary> /// Compare two pointers. /// </summary> /// <param name="pointer1"></param> /// <param name="pointer2"></param> /// <returns></returns> public static bool operator ==(Pointer pointer1, Pointer pointer2) { return pointer1.Address == pointer2.Address; } /// <summary> /// Compare two pointers. /// </summary> /// <param name="pointer1"></param> /// <param name="pointer2"></param> /// <returns></returns> public static bool operator !=(Pointer pointer1, Pointer pointer2) { return pointer1.Address != pointer2.Address; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <returns>true if obj and this instance are the same type and represent the same value; otherwise, false.</returns> /// <param name="obj">Another object to compare to.</param> public override bool Equals(object obj) { if (obj is Pointer) { Pointer pointer = (Pointer) obj; return pointer.Address == Address; } return base.Equals(obj); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A 32-bit signed integer that is the hash code for this instance.</returns> public override int GetHashCode() { return Address.GetHashCode(); } } }
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 Benjamin.React.MVC.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 => { var range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { var maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { var minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { var strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { var dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { var 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"); } var underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; var 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) { var genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { var enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { var dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } var keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { var 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) { var jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { var 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) { var jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); var xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); var ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); var nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); var apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); var 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) { var annotations = new List<ParameterAnnotation>(); var attributes = property.GetCustomAttributes(); foreach (var 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 (var annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { var collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { var complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); var hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; var properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { var 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); } } var fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (var field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { var 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) { var keyModelDescription = GetOrCreateModelDescription(keyType); var valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { var enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; var hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (var field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { var 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) { var keyModelDescription = GetOrCreateModelDescription(keyType); var valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { var simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; namespace Free.Database.Dao.Net { public class DBEngine { internal DAO.DBEngineClass dbe; public DBEngine() { dbe=new DAO.DBEngineClass(); } [Obsolete("Use CreateWorkspace instead.", false)] public Workspace _30_CreateWorkspace(string name, string user, string password) { return new Workspace(dbe._30_CreateWorkspace(name, user, password)); } public void BeginTrans() { dbe.BeginTrans(); } public void CommitTrans() { dbe.CommitTrans(0); } public void CommitTrans(CommitTransOptions option) { dbe.CommitTrans((int)option); } public void CompactDatabase(string olddb, string newdb) { dbe.CompactDatabase(olddb, newdb, Type.Missing, Type.Missing, Type.Missing); } public void CompactDatabase(string olddb, string newdb, string locale) { dbe.CompactDatabase(olddb, newdb, locale, Type.Missing, Type.Missing); } public void CompactDatabase(string olddb, string newdb, string locale, DatabaseType options) { dbe.CompactDatabase(olddb, newdb, locale, options, Type.Missing); } public void CompactDatabase(string olddb, string newdb, string locale, DatabaseType options, string password) { dbe.CompactDatabase(olddb, newdb, locale, options, password); } public Database CreateDatabase(string name, string locale) { return new Database(dbe.CreateDatabase(name, locale, Type.Missing)); } public Database CreateDatabase(string name, string locale, DatabaseType options) { return new Database(dbe.CreateDatabase(name, locale, options)); } public Workspace CreateWorkspace(string name, string user, string password) { return new Workspace(dbe.CreateWorkspace(name, user, password, Type.Missing)); } public Workspace CreateWorkspace(string name, string user, string password, WorkspaceType type) { return new Workspace(dbe.CreateWorkspace(name, user, password, type)); } public void FreeLocks() { dbe.FreeLocks(); } public void Idle() { dbe.Idle(Type.Missing); } public void Idle(Idle action) { dbe.Idle(action); } public int ISAMStats(int statnum) { return dbe.ISAMStats(statnum, Type.Missing); } public int ISAMStats(int statnum, bool reset) { return dbe.ISAMStats(statnum, reset); } public Connection OpenConnection(string name) { return new Connection(dbe.OpenConnection(name, Type.Missing, Type.Missing, Type.Missing)); } public Connection OpenConnection(string name, DriverPrompt options) { return new Connection(dbe.OpenConnection(name, options, Type.Missing, Type.Missing)); } public Connection OpenConnection(string name, DriverPrompt options, bool readOnly) { return new Connection(dbe.OpenConnection(name, options, readOnly, Type.Missing)); } public Connection OpenConnection(string name, DriverPrompt options, bool readOnly, string connect) { return new Connection(dbe.OpenConnection(name, options, readOnly, connect)); } public Database OpenDatabase(string dbname) { return new Database(dbe.OpenDatabase(dbname, Type.Missing, Type.Missing, Type.Missing)); } public Database OpenDatabase(string dbname, DriverPrompt options) { return new Database(dbe.OpenDatabase(dbname, options, Type.Missing, Type.Missing)); } public Database OpenDatabase(string dbname, bool options) { return new Database(dbe.OpenDatabase(dbname, options, Type.Missing, Type.Missing)); } public Database OpenDatabase(string dbname, DriverPrompt options, bool readOnly) { return new Database(dbe.OpenDatabase(dbname, options, readOnly, Type.Missing)); } public Database OpenDatabase(string dbname, bool options, bool readOnly) { return new Database(dbe.OpenDatabase(dbname, options, readOnly, Type.Missing)); } public Database OpenDatabase(string dbname, DriverPrompt options, bool readOnly, string connect) { return new Database(dbe.OpenDatabase(dbname, options, readOnly, connect)); } public Database OpenDatabase(string dbname, bool options, bool readOnly, string connect) { return new Database(dbe.OpenDatabase(dbname, options, readOnly, connect)); } public void RegisterDatabase(string dbname, string driver, bool silent, string attributes) { dbe.RegisterDatabase(dbname, driver, silent, attributes); } public void RepairDatabase(string dbname) { dbe.RepairDatabase(dbname); } public void Rollback() { dbe.Rollback(); } [Obsolete("Use DBEngine.IniPath instead.", false)] public void SetDataAccessOption(short option, object val) { dbe.SetDataAccessOption(option, val); } [Obsolete("Use DBEngine.DefaultUser and DBEngine.DefaultPassword instead.", false)] public void SetDefaultWorkspace(string name, string password) { dbe.SetDefaultWorkspace(name, password); } public void SetOption(SetOption option, int val) { dbe.SetOption((int)option, val); } public void SetOption(SetOption option, string val) { dbe.SetOption((int)option, val); } public string DefaultPassword { set { dbe.DefaultPassword=value; } } public WorkspaceType DefaultType { get { return (WorkspaceType)dbe.DefaultType; } set { dbe.DefaultType=(int)value; } } public string DefaultUser { set { dbe.DefaultUser=value; } } public Errors Errors { get { return new Errors(dbe.Errors); } } public string IniPath { get { return dbe.IniPath; } set { dbe.IniPath=value; } } public short LoginTimeout { get { return dbe.LoginTimeout; } set { dbe.LoginTimeout=value; } } public Properties Properties { get { return new Properties(dbe.Properties); } } public string SystemDB { get { return dbe.SystemDB; } set { dbe.SystemDB=value; } } public string Version { get { return dbe.Version; } } public Workspaces Workspaces { get { return new Workspaces(dbe.Workspaces); } } } }
namespace Nancy.Bootstrappers.Unity { using System; using System.Collections.Generic; using Diagnostics; using Microsoft.Practices.Unity; using Nancy.Configuration; using Bootstrapper; using ViewEngines; /// <summary> /// Nancy bootstrapper for the Unity container. /// </summary> public abstract class UnityNancyBootstrapper : NancyBootstrapperWithRequestContainerBase<IUnityContainer> { /// <summary> /// Gets the diagnostics for intialisation /// </summary> /// <returns>An <see cref="IDiagnostics"/> implementation</returns> protected override IDiagnostics GetDiagnostics() { return this.ApplicationContainer.Resolve<IDiagnostics>(); } /// <summary> /// Gets all registered startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances. </returns> protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks() { return this.ApplicationContainer.ResolveAll<IApplicationStartup>(); } /// <summary> /// Registers and resolves all request startup tasks /// </summary> /// <param name="container">Container to use</param> /// <param name="requestStartupTypes">Types to register</param> /// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns> protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(IUnityContainer container, Type[] requestStartupTypes) { foreach (var requestStartupType in requestStartupTypes) { container.RegisterType( typeof(IRequestStartup), requestStartupType, requestStartupType.ToString(), new ContainerControlledLifetimeManager()); } return container.ResolveAll<IRequestStartup>(); } /// <summary> /// Gets all registered application registration tasks /// </summary> /// <returns>An <see cref="System.Collections.Generic.IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns> protected override IEnumerable<IRegistrations> GetRegistrationTasks() { return this.ApplicationContainer.ResolveAll<IRegistrations>(); } /// <summary> /// Resolve <see cref="INancyEngine"/> /// </summary> /// <returns>An <see cref="INancyEngine"/> implementation</returns> protected override INancyEngine GetEngineInternal() { return this.ApplicationContainer.Resolve<INancyEngine>(); } /// <summary> /// Gets the <see cref="INancyEnvironmentConfigurator"/> used by th. /// </summary> /// <returns>An <see cref="INancyEnvironmentConfigurator"/> instance.</returns> protected override INancyEnvironmentConfigurator GetEnvironmentConfigurator() { return this.ApplicationContainer.Resolve<INancyEnvironmentConfigurator>(); } /// <summary> /// Registers an <see cref="INancyEnvironment"/> instance in the container. /// </summary> /// <param name="container">The container to register into.</param> /// <param name="environment">The <see cref="INancyEnvironment"/> instance to register.</param> protected override void RegisterNancyEnvironment(IUnityContainer container, INancyEnvironment environment) { container.RegisterInstance(environment); } /// <summary> /// Gets the application level container /// </summary> /// <returns>Container instance</returns> protected override IUnityContainer GetApplicationContainer() { return new UnityContainer(); } /// <summary> /// Register the bootstrapper's implemented types into the container. /// This is necessary so a user can pass in a populated container but not have /// to take the responsibility of registering things like <see cref="INancyModuleCatalog"/> manually. /// </summary> /// <param name="applicationContainer">Application container to register into</param> protected override void RegisterBootstrapperTypes(IUnityContainer applicationContainer) { // This is here to add the EnumerableExtension, even though someone // used an external IUnityContainer (not created by this bootstrapper). // It's probably not the best place for it, but it's called right after // GetApplicationContainer in NancyBootstrapperBase. applicationContainer.AddNewExtension<EnumerableExtension>(); applicationContainer.RegisterInstance<INancyModuleCatalog>(this, new ContainerControlledLifetimeManager()); } /// <summary> /// Register the default implementations of internally used types into the container as singletons /// </summary> /// <param name="container">Container to register into</param> /// <param name="typeRegistrations">Type registrations to register</param> protected override void RegisterTypes(IUnityContainer container, IEnumerable<TypeRegistration> typeRegistrations) { foreach (var typeRegistration in typeRegistrations) { switch (typeRegistration.Lifetime) { case Lifetime.Transient: container.RegisterType( typeRegistration.RegistrationType, typeRegistration.ImplementationType, new TransientLifetimeManager()); break; case Lifetime.Singleton: container.RegisterType( typeRegistration.RegistrationType, typeRegistration.ImplementationType, new ContainerControlledLifetimeManager()); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); default: throw new ArgumentOutOfRangeException(); } } // Added this in here because Unity doesn't seem to support // resolving using the greediest resolvable constructor container.RegisterType<IFileSystemReader, DefaultFileSystemReader>(new ContainerControlledLifetimeManager()); } /// <summary> /// Register the various collections into the container as singletons to later be resolved /// by IEnumerable{Type} constructor dependencies. /// </summary> /// <param name="container">Container to register into</param> /// <param name="collectionTypeRegistrations">Collection type registrations to register</param> protected override void RegisterCollectionTypes(IUnityContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations) { foreach (var collectionTypeRegistration in collectionTypeRegistrations) { foreach (var implementationType in collectionTypeRegistration.ImplementationTypes) { switch (collectionTypeRegistration.Lifetime) { case Lifetime.Transient: container.RegisterType( collectionTypeRegistration.RegistrationType, implementationType, implementationType.ToString(), new TransientLifetimeManager()); break; case Lifetime.Singleton: container.RegisterType( collectionTypeRegistration.RegistrationType, implementationType, implementationType.ToString(), new ContainerControlledLifetimeManager()); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); default: throw new ArgumentOutOfRangeException(); } } } } /// <summary> /// Register the given instances into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="instanceRegistrations">Instance registration types</param> protected override void RegisterInstances(IUnityContainer container, IEnumerable<InstanceRegistration> instanceRegistrations) { foreach (var instanceRegistration in instanceRegistrations) { container.RegisterInstance( instanceRegistration.RegistrationType, instanceRegistration.Implementation, new ContainerControlledLifetimeManager()); } } /// <summary> /// Creates a per request child/nested container /// </summary> /// <param name="context">Current context</param> /// <returns>Request container instance</returns> protected override IUnityContainer CreateRequestContainer(NancyContext context) { return this.ApplicationContainer.CreateChildContainer(); } /// <summary> /// Register the given module types into the request container /// </summary> /// <param name="container">Container to register into</param> /// <param name="moduleRegistrationTypes">An <see cref="INancyModule"/> types</param> protected override void RegisterRequestContainerModules(IUnityContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes) { foreach (var moduleRegistrationType in moduleRegistrationTypes) { container.RegisterType( typeof(INancyModule), moduleRegistrationType.ModuleType, moduleRegistrationType.ModuleType.FullName, new ContainerControlledLifetimeManager()); } } /// <summary> /// Retrieve all module instances from the container /// </summary> /// <param name="container">Container to use</param> /// <returns>Collection of An <see cref="INancyModule"/> instances</returns> protected override IEnumerable<INancyModule> GetAllModules(IUnityContainer container) { return container.ResolveAll<INancyModule>(); } /// <summary> /// Retreive a specific module instance from the container /// </summary> /// <param name="container">Container to use</param> /// <param name="moduleType">Type of the module</param> /// <returns>An <see cref="INancyModule"/> instance</returns> protected override INancyModule GetModule(IUnityContainer container, Type moduleType) { container.RegisterType(typeof(INancyModule), moduleType, new ContainerControlledLifetimeManager()); return container.Resolve<INancyModule>(); } } }
using System; using MyGeneration.dOOdads; namespace MyGeneration.dOOdads.Tests.Access { /// <summary> /// Description of RefreshDatabase. /// </summary> public class UnitTestBase { static UnitTestBase() { } public static void RefreshDatabase() { AggregateTest testData = new AggregateTest(); testData.ConnectionStringConfig = "AccessConnection"; testData.LoadAll(); testData.DeleteAll(); testData.Save(); testData.AddNew(); testData.s_DepartmentID = "3"; testData.s_FirstName = "David"; testData.s_LastName = "Doe"; testData.s_Age = "16"; testData.s_HireDate = "2000-02-16 00:00:00"; testData.s_Salary = "34.71"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "1"; testData.s_FirstName = "Sarah"; testData.s_LastName = "McDonald"; testData.s_Age = "28"; testData.s_HireDate = "1999-03-25 00:00:00"; testData.s_Salary = "11.06"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "3"; testData.s_FirstName = "David"; testData.s_LastName = "Vincent"; testData.s_Age = "43"; testData.s_HireDate = "2000-10-17 00:00:00"; testData.s_Salary = "10.27"; testData.s_IsActive = "false"; testData.AddNew(); testData.s_DepartmentID = "2"; testData.s_FirstName = "Fred"; testData.s_LastName = "Smith"; testData.s_Age = "15"; testData.s_HireDate = "1999-03-15 00:00:00"; testData.s_Salary = "15.15"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "3"; testData.s_FirstName = "Sally"; testData.s_LastName = "Johnson"; testData.s_Age = "30"; testData.s_HireDate = "2000-10-07 00:00:00"; testData.s_Salary = "14.36"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "5"; testData.s_FirstName = "Jane"; testData.s_LastName = "Rapaport"; testData.s_Age = "44"; testData.s_HireDate = "2002-05-02 00:00:00"; testData.s_Salary = "13.56"; testData.s_IsActive = "false"; testData.AddNew(); testData.s_DepartmentID = "4"; testData.s_FirstName = "Paul"; testData.s_LastName = "Gellar"; testData.s_Age = "16"; testData.s_HireDate = "2000-09-27 00:00:00"; testData.s_Salary = "18.44"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "2"; testData.s_FirstName = "John"; testData.s_LastName = "Jones"; testData.s_Age = "31"; testData.s_HireDate = "2002-04-22 00:00:00"; testData.s_Salary = "17.65"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "3"; testData.s_FirstName = "Michelle"; testData.s_LastName = "Johnson"; testData.s_Age = "45"; testData.s_HireDate = "2003-11-14 00:00:00"; testData.s_Salary = "16.86"; testData.s_IsActive = "false"; testData.AddNew(); testData.s_DepartmentID = "2"; testData.s_FirstName = "David"; testData.s_LastName = "Costner"; testData.s_Age = "17"; testData.s_HireDate = "2002-04-11 00:00:00"; testData.s_Salary = "21.74"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "4"; testData.s_FirstName = "William"; testData.s_LastName = "Gellar"; testData.s_Age = "32"; testData.s_HireDate = "2003-11-04 00:00:00"; testData.s_Salary = "20.94"; testData.s_IsActive = "false"; testData.AddNew(); testData.s_DepartmentID = "3"; testData.s_FirstName = "Sally"; testData.s_LastName = "Rapaport"; testData.s_Age = "39"; testData.s_HireDate = "2002-04-01 00:00:00"; testData.s_Salary = "25.82"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "5"; testData.s_FirstName = "Jane"; testData.s_LastName = "Vincent"; testData.s_Age = "18"; testData.s_HireDate = "2003-10-25 00:00:00"; testData.s_Salary = "25.03"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "2"; testData.s_FirstName = "Fred"; testData.s_LastName = "Costner"; testData.s_Age = "33"; testData.s_HireDate = "1998-05-20 00:00:00"; testData.s_Salary = "24.24"; testData.s_IsActive = "false"; testData.AddNew(); testData.s_DepartmentID = "1"; testData.s_FirstName = "John"; testData.s_LastName = "Johnson"; testData.s_Age = "40"; testData.s_HireDate = "2003-10-15 00:00:00"; testData.s_Salary = "29.12"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "3"; testData.s_FirstName = "Michelle"; testData.s_LastName = "Rapaport"; testData.s_Age = "19"; testData.s_HireDate = "1998-05-10 00:00:00"; testData.s_Salary = "28.32"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "4"; testData.s_FirstName = "Sarah"; testData.s_LastName = "Doe"; testData.s_Age = "34"; testData.s_HireDate = "1999-12-03 00:00:00"; testData.s_Salary = "27.53"; testData.s_IsActive = "false"; testData.AddNew(); testData.s_DepartmentID = "4"; testData.s_FirstName = "William"; testData.s_LastName = "Jones"; testData.s_Age = "41"; testData.s_HireDate = "1998-04-30 00:00:00"; testData.s_Salary = "32.41"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "1"; testData.s_FirstName = "Sarah"; testData.s_LastName = "McDonald"; testData.s_Age = "21"; testData.s_HireDate = "1999-11-23 00:00:00"; testData.s_Salary = "31.62"; testData.s_IsActive = "false"; testData.AddNew(); testData.s_DepartmentID = "4"; testData.s_FirstName = "Jane"; testData.s_LastName = "Costner"; testData.s_Age = "28"; testData.s_HireDate = "1998-04-20 00:00:00"; testData.s_Salary = "36.50"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "2"; testData.s_FirstName = "Fred"; testData.s_LastName = "Douglas"; testData.s_Age = "42"; testData.s_HireDate = "1999-11-13 00:00:00"; testData.s_Salary = "35.71"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "3"; testData.s_FirstName = "Paul"; testData.s_LastName = "Jones"; testData.s_Age = "22"; testData.s_HireDate = "2001-06-07 00:00:00"; testData.s_Salary = "34.91"; testData.s_IsActive = "false"; testData.AddNew(); testData.s_DepartmentID = "3"; testData.s_FirstName = "Michelle"; testData.s_LastName = "Doe"; testData.s_Age = "29"; testData.s_HireDate = "1999-11-03 00:00:00"; testData.s_Salary = "39.79"; testData.s_IsActive = "true"; testData.AddNew(); testData.s_DepartmentID = "4"; testData.s_FirstName = "Paul"; testData.s_LastName = "Costner"; testData.s_Age = "43"; testData.s_HireDate = "2001-05-28 00:00:00"; testData.s_Salary = "39.00"; testData.s_IsActive = "true"; testData.AddNew(); testData.AddNew(); testData.AddNew(); testData.AddNew(); testData.AddNew(); testData.AddNew(); testData.s_DepartmentID = "0"; testData.s_FirstName = ""; testData.s_LastName = ""; testData.s_Age = "0"; testData.s_Salary = "0"; testData.Save(); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.txt file at the root of this distribution. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; using VSConstants = Microsoft.VisualStudio.VSConstants; namespace Microsoft.VisualStudio.Project.Automation { /// <summary> /// Represents an automation object for a file in a project /// </summary> [SuppressMessage("Microsoft.Interoperability", "CA1405:ComVisibleTypeBaseTypesShouldBeComVisible")] [ComVisible(true), CLSCompliant(false)] public class OAFileItem : OAProjectItem<FileNode> { #region ctors public OAFileItem(OAProject project, FileNode node) : base(project, node) { } #endregion #region overridden methods /// <summary> /// Returns the dirty state of the document. /// </summary> /// <exception cref="InvalidOperationException">Is thrown if the project is closed or it the service provider attached to the project is invalid.</exception> /// <exception cref="ComException">Is thrown if the dirty state cannot be retrived.</exception> public override bool IsDirty { get { bool isDirty = false; ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); CheckProjectIsValid(); using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { DocumentManager manager = this.Node.GetDocumentManager(); Utilities.CheckNotNull(manager); isDirty = manager.IsDirty; } }); return isDirty; } } /// <summary> /// Gets the Document associated with the item, if one exists. /// </summary> public override EnvDTE.Document Document { get { return ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); CheckProjectIsValid(); EnvDTE.Document document = null; using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { IVsUIHierarchy hier; uint itemid; IVsWindowFrame windowFrame; VsShellUtilities.IsDocumentOpen(this.Node.ProjectMgr.Site, this.Node.Url, VSConstants.LOGVIEWID_Any, out hier, out itemid, out windowFrame); if (windowFrame != null) { object var; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var)); object documentAsObject; ErrorHandler.ThrowOnFailure(scope.Extensibility.GetDocumentFromDocCookie((int)var, out documentAsObject)); Utilities.CheckNotNull(documentAsObject); document = (Document)documentAsObject; } } return document; }); } } /// <summary> /// Opens the file item in the specified view. /// </summary> /// <param name="ViewKind">Specifies the view kind in which to open the item (file)</param> /// <returns>Window object</returns> public override EnvDTE.Window Open(string viewKind) { return ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); CheckProjectIsValid(); IVsWindowFrame windowFrame = null; IntPtr docData = IntPtr.Zero; using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { try { // Validate input params Guid logicalViewGuid = VSConstants.LOGVIEWID_Primary; try { if (!(String.IsNullOrEmpty(viewKind))) { logicalViewGuid = new Guid(viewKind); } } catch (FormatException) { // Not a valid guid throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidGuid, CultureInfo.CurrentUICulture), "viewKind"); } uint itemid; IVsHierarchy ivsHierarchy; uint docCookie; IVsRunningDocumentTable rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt == null) { throw new InvalidOperationException("Could not get running document table from the services exposed by this project"); } ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.Node.Url, out ivsHierarchy, out itemid, out docData, out docCookie)); // Open the file using the IVsProject3 interface ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.OpenItem(this.Node.ID, ref logicalViewGuid, docData, out windowFrame)); } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } } // Get the automation object and return it return ((windowFrame != null) ? VsShellUtilities.GetWindowObject(windowFrame) : null); }); } /// <summary> /// Saves the project item. /// </summary> /// <param name="fileName">The name with which to save the project or project item.</param> /// <exception cref="InvalidOperationException">Is thrown if the save operation failes.</exception> /// <exception cref="ArgumentNullException">Is thrown if fileName is null.</exception> public override void Save(string fileName) { ThreadHelper.ThrowIfNotOnUIThread(); this.DoSave(false, fileName); } /// <summary> /// Saves the project item. /// </summary> /// <param name="fileName">The file name with which to save the solution, project, or project item. If the file exists, it is overwritten</param> /// <returns>true if the rename was successful. False if Save as failes</returns> public override bool SaveAs(string fileName) { try { ThreadHelper.ThrowIfNotOnUIThread(); this.DoSave(true, fileName); } catch(InvalidOperationException) { return false; } catch(COMException) { return false; } return true; } /// <summary> /// Gets a value indicating whether the project item is open in a particular view type. /// </summary> /// <param name="viewKind">A Constants.vsViewKind* indicating the type of view to check./param> /// <returns>A Boolean value indicating true if the project is open in the given view type; false if not. </returns> public override bool get_IsOpen(string viewKind) { bool isOpen = false; ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); CheckProjectIsValid(); // Validate input params Guid logicalViewGuid = VSConstants.LOGVIEWID_Primary; try { if (!(String.IsNullOrEmpty(viewKind))) { logicalViewGuid = new Guid(viewKind); } } catch (FormatException) { // Not a valid guid throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidGuid, CultureInfo.CurrentUICulture), "viewKind"); } using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { IVsUIHierarchy hier; uint itemid; IVsWindowFrame windowFrame; isOpen = VsShellUtilities.IsDocumentOpen(this.Node.ProjectMgr.Site, this.Node.Url, logicalViewGuid, out hier, out itemid, out windowFrame); } }); return isOpen; } /// <summary> /// Gets the ProjectItems for the object. /// </summary> public override ProjectItems ProjectItems { get { return ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); if (this.Project.Project.CanFileNodesHaveChilds) return new OAProjectItems(this.Project, this.Node); else return base.ProjectItems; }); } } #endregion #region helpers /// <summary> /// Saves or Save As the file /// </summary> /// <param name="isCalledFromSaveAs">Flag determining which Save method called , the SaveAs or the Save.</param> /// <param name="fileName">The name of the project file.</param> private void DoSave(bool isCalledFromSaveAs, string fileName) { ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); Utilities.ArgumentNotNull("fileName", fileName); CheckProjectIsValid(); using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { IntPtr docData = IntPtr.Zero; try { IVsRunningDocumentTable rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt == null) { throw new InvalidOperationException("Could not get running document table from the services exposed by this project"); } // First we see if someone else has opened the requested view of the file. uint itemid; IVsHierarchy ivsHierarchy; uint docCookie; int canceled; string url = this.Node.Url; ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, url, out ivsHierarchy, out itemid, out docData, out docCookie)); // If an empty file name is passed in for Save then make the file name the project name. if (!isCalledFromSaveAs && fileName.Length == 0) { ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, url, this.Node.ID, docData, out canceled)); } else { Utilities.ValidateFileName(this.Node.ProjectMgr.Site, fileName); // Compute the fullpath from the directory of the existing Url. string fullPath = fileName; if (!Path.IsPathRooted(fileName)) { string directory = Path.GetDirectoryName(url); fullPath = Path.Combine(directory, fileName); } if (!isCalledFromSaveAs) { if (!NativeMethods.IsSamePath(this.Node.Url, fullPath)) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.ID, docData, out canceled)); } else { ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.SaveItem(VSSAVEFLAGS.VSSAVE_SilentSave, fullPath, this.Node.ID, docData, out canceled)); } } if (canceled == 1) { throw new InvalidOperationException(); } } catch (COMException e) { throw new InvalidOperationException(e.Message); } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } } }); } #endregion } }
namespace CommonDomain.Persistence.EventStore { using System; using System.Collections.Generic; using System.Linq; using NEventStore; using NEventStore.Persistence; public class EventStoreRepository : IRepository { private const string AggregateTypeHeader = "AggregateType"; private readonly IDetectConflicts _conflictDetector; private readonly IStoreEvents _eventStore; private readonly IConstructAggregates _factory; private readonly IDictionary<string, ISnapshot> _snapshots = new Dictionary<string, ISnapshot>(); private readonly IDictionary<string, IEventStream> _streams = new Dictionary<string, IEventStream>(); public EventStoreRepository(IStoreEvents eventStore, IConstructAggregates factory, IDetectConflicts conflictDetector) { _eventStore = eventStore; _factory = factory; _conflictDetector = conflictDetector; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public virtual TAggregate GetById<TAggregate>(Guid id) where TAggregate : class, IAggregate { return GetById<TAggregate>(Bucket.Default, id); } public virtual TAggregate GetById<TAggregate>(Guid id, int versionToLoad) where TAggregate : class, IAggregate { return GetById<TAggregate>(Bucket.Default, id, versionToLoad); } public TAggregate GetById<TAggregate>(string bucketId, Guid id) where TAggregate : class, IAggregate { return GetById<TAggregate>(bucketId, id, int.MaxValue); } public TAggregate GetById<TAggregate>(string bucketId, Guid id, int versionToLoad) where TAggregate : class, IAggregate { ISnapshot snapshot = GetSnapshot(bucketId, id, versionToLoad); IEventStream stream = OpenStream(bucketId, id, versionToLoad, snapshot); IAggregate aggregate = GetAggregate<TAggregate>(snapshot, stream); ApplyEventsToAggregate(versionToLoad, stream, aggregate); return aggregate as TAggregate; } public virtual void Save(IAggregate aggregate, Guid commitId, Action<IDictionary<string, object>> updateHeaders) { Save(Bucket.Default, aggregate, commitId, updateHeaders); } public void Save(string bucketId, IAggregate aggregate, Guid commitId, Action<IDictionary<string, object>> updateHeaders) { Dictionary<string, object> headers = PrepareHeaders(aggregate, updateHeaders); while (true) { IEventStream stream = PrepareStream(bucketId, aggregate, headers); int commitEventCount = stream.CommittedEvents.Count; try { stream.CommitChanges(commitId); aggregate.ClearUncommittedEvents(); return; } catch (DuplicateCommitException) { stream.ClearChanges(); return; } catch (ConcurrencyException e) { var conflict = ThrowOnConflict(stream, commitEventCount); stream.ClearChanges(); if (conflict) { throw new ConflictingCommandException(e.Message, e); } } catch (StorageException e) { throw new PersistenceException(e.Message, e); } } } protected virtual void Dispose(bool disposing) { if (!disposing) { return; } lock (_streams) { foreach (var stream in _streams) { stream.Value.Dispose(); } _snapshots.Clear(); _streams.Clear(); } } private static void ApplyEventsToAggregate(int versionToLoad, IEventStream stream, IAggregate aggregate) { if (versionToLoad == 0 || aggregate.Version < versionToLoad) { foreach (var @event in stream.CommittedEvents.Select(x => x.Body)) { aggregate.ApplyEvent(@event); } } } private IAggregate GetAggregate<TAggregate>(ISnapshot snapshot, IEventStream stream) { IMemento memento = snapshot == null ? null : snapshot.Payload as IMemento; return _factory.Build(typeof(TAggregate), stream.StreamId.ToGuid(), memento); } private ISnapshot GetSnapshot(string bucketId, Guid id, int version) { ISnapshot snapshot; var snapshotId = bucketId + id; if (!_snapshots.TryGetValue(snapshotId, out snapshot)) { _snapshots[snapshotId] = snapshot = _eventStore.Advanced.GetSnapshot(bucketId, id, version); } return snapshot; } private IEventStream OpenStream(string bucketId, Guid id, int version, ISnapshot snapshot) { IEventStream stream; var streamId = bucketId + "+" + id; if (_streams.TryGetValue(streamId, out stream)) { return stream; } stream = snapshot == null ? _eventStore.OpenStream(bucketId, id, 0, version) : _eventStore.OpenStream(snapshot, version); return _streams[streamId] = stream; } private IEventStream PrepareStream(string bucketId, IAggregate aggregate, Dictionary<string, object> headers) { IEventStream stream; var streamId = bucketId + "+" + aggregate.Id; if (!_streams.TryGetValue(streamId, out stream)) { _streams[streamId] = stream = _eventStore.CreateStream(bucketId, aggregate.Id); } foreach (var item in headers) { stream.UncommittedHeaders[item.Key] = item.Value; } aggregate.GetUncommittedEvents() .Cast<object>() .Select(x => new EventMessage { Body = x }) .ToList() .ForEach(stream.Add); return stream; } private static Dictionary<string, object> PrepareHeaders( IAggregate aggregate, Action<IDictionary<string, object>> updateHeaders) { var headers = new Dictionary<string, object>(); headers[AggregateTypeHeader] = aggregate.GetType().FullName; if (updateHeaders != null) { updateHeaders(headers); } return headers; } private bool ThrowOnConflict(IEventStream stream, int skip) { IEnumerable<object> committed = stream.CommittedEvents.Skip(skip).Select(x => x.Body); IEnumerable<object> uncommitted = stream.UncommittedEvents.Select(x => x.Body); return _conflictDetector.ConflictsWith(uncommitted, committed); } } }
using UnityEngine; using System.Collections.Generic; using System.Linq; using Eppy; public class PhysicsWorld : MonoBehaviour { static public PhysicsWorld ins; public List<PhysicsEntity> stcList; public List<PhysicsEntity> dynList; static private float EPS = 1e-6f; public PhysicsWorld () { ins = this; stcList = new List<PhysicsEntity>(); dynList = new List<PhysicsEntity>(); } public void Add(PhysicsEntity obj) { if (!obj.immovable) dynList.Add(obj); else stcList.Add(obj); } public void Remove(PhysicsEntity obj) { if (!obj.immovable) dynList.Remove(obj); else stcList.Remove(obj); } void Update () { SolveAll(); foreach (var e in dynList) { e.PhysicsUpdate(); } } void SolveAll () { for (int i = 0; i < dynList.Count; ++i) { var obj = dynList[i]; if ((Vector2)obj.moveVector != Vector2.zero) { var hitlst = GetHitObjects(i).ToList(); hitlst.Sort((a, b) => Compare(Project(a.GetWorldRectOrtho(), obj.moveVector.normalized), Project(b.GetWorldRectOrtho(), obj.moveVector.normalized))); // resolve foreach (var other in hitlst) { if (obj.isOrtho && other.isOrtho) { // resolve in the ortho way var lRc = obj.GetWorldRectOrtho(); var rRc = other.GetOldWorldRectOrtho(); if (RectOverlap(lRc, rRc)) { float hl = rRc.xMin - lRc.xMax; float hr = rRc.xMax - lRc.xMin; float h = obj.moveVector.x - other.moveVector.x > 0 ? hl : hr; float vd = rRc.yMin - lRc.yMax; float vu = rRc.yMax - lRc.yMin; float v = obj.moveVector.y - other.moveVector.y > 0 ? vd : vu; float rh = h * obj.moveVector.x > 0 ? 0 : Mathf.Abs(h) > Mathf.Abs(obj.moveVector.x) ? -obj.moveVector.x : h; float rv = v * obj.moveVector.y > 0 ? 0 : Mathf.Abs(v) > Mathf.Abs(obj.moveVector.y) ? -obj.moveVector.y : v; Vector2 resDir = Mathf.Abs(h) < Mathf.Abs(v) ? rh * Vector2.right : rv * Vector2.up; if (obj.chamfer > 0.001f || other.chamfer > 0.001f) { bool collide = true; foreach (Vector2 axis in Geometry.CrossAxesOfRotatedRect(obj.transform.rotation)) { if (!_IntersectChamferRectOnAxis(obj.shape, other.shape, obj.transform, other.transform, obj.chamfer, other.chamfer, axis, ref resDir)) { collide = false; break; } } if (!collide) continue; } if (resDir != Vector2.zero) { if (!obj.trigger && !other.trigger) obj.transform.position += (Vector3)resDir; SendCollisionMessage(resDir.normalized, obj, other); } } } else { // resolve in the rotated way Rect aRc = obj.shape, bRc = other.shape; bool collide = true; Vector2? resDir = null; foreach (Vector2 axis in Geometry.AxesOfRotatedRect(obj.transform.rotation)) { if (!_IntersectRectOnAxis (aRc, bRc, obj.transform, other.transform, axis, ref resDir)) { collide = false; break; } } if (collide) { foreach (Vector2 axis in Geometry.AxesOfRotatedRect(other.transform.rotation)) { if (!_IntersectRectOnAxis (aRc, bRc, obj.transform, other.transform, axis, ref resDir)) { collide = false; break; } } } if (collide && resDir.HasValue) { float h = resDir.Value.x; float v = resDir.Value.y; float rh = h * obj.moveVector.x > 0 ? 0 : Mathf.Abs(h) > Mathf.Abs(obj.moveVector.x) ? -obj.moveVector.x : h; float rv = v * obj.moveVector.y > 0 ? 0 : Mathf.Abs(v) > Mathf.Abs(obj.moveVector.y) ? -obj.moveVector.y : v; if (!obj.trigger && !other.trigger) obj.transform.position += new Vector3(rh, rv); SendCollisionMessage(resDir.Value.normalized, obj, other); } } } } } } private void SendCollisionMessage (Vector3 normal, PhysicsEntity obj, PhysicsEntity other) { var collisionInfo = new CollisionInfo(obj, other, normal); obj.SendMessage("OnCollide", collisionInfo, SendMessageOptions.DontRequireReceiver); other.SendMessage("OnCollide", collisionInfo.GetOtherInfo(), SendMessageOptions.DontRequireReceiver); } private IEnumerable<PhysicsEntity> GetHitObjects (int i) { for (int j = 0; j < stcList.Count; ++j) { if (dynList[i]._RoughTestIntersecting(stcList[j])) yield return stcList[j]; } for (int j = 0; j < dynList.Count; ++j) { if (j == i) continue; if (dynList[i]._RoughTestIntersecting(dynList[j])) yield return dynList[j]; } } private bool IsHitting (int i) { var objRc = dynList[i].GetWorldRectOrtho(); foreach (PhysicsEntity o in GetHitObjects(i)) { if (RectOverlap(objRc, o.GetWorldRectOrtho())) return true; } return false; } public bool RectOverlap (Rect a, Rect b) { return a.xMax > b.xMin + EPS && a.xMin + EPS < b.xMax && a.yMax > b.yMin + EPS && a.yMin + EPS < b.yMax; } static protected Rect GetOffsetRect (float x, float y, Rect rc) { return new Rect(x + rc.x, y + rc.y, rc.width, rc.height); } static protected int Compare (float a, float b) { return a < b ? -1 : (a > b ? 1 : 0); } static protected float Project (Rect rc, Vector2 direction) { return Mathf.Min(Vector2.Dot(new Vector2(rc.xMin, rc.yMin), direction), Vector2.Dot(new Vector2(rc.xMax, rc.yMin), direction), Vector2.Dot(new Vector2(rc.xMax, rc.yMax), direction), Vector2.Dot(new Vector2(rc.xMin, rc.yMax), direction)); } static protected bool _IntersectRectOnAxis (Rect aRc, Rect bRc, Transform aTrans, Transform bTrans, Vector2 axis, ref Vector2? minCross) { var aR = Geometry.ProjectRect(aRc, aTrans.position, aTrans.rotation, axis); var bR = Geometry.ProjectRect(bRc, bTrans.position, bTrans.rotation, axis); // the shortest distance to move aR out of bR float overl = Utils.SegmentInto(aR, bR); if (overl == 0) return false; else { if (minCross.HasValue) { if (Mathf.Abs(overl) < minCross.Value.magnitude) { minCross = overl * axis; } } else minCross = overl * axis; return true; } } static protected bool _IntersectChamferRectOnAxis(Rect aRc, Rect bRc, Transform aTrans, Transform bTrans, float aChamfer, float bChamfer, Vector2 axis, ref Vector2 minCross) { var aR = Geometry.ProjectRect(aRc, aTrans.position, aTrans.rotation, axis); var bR = Geometry.ProjectRect(bRc, bTrans.position, bTrans.rotation, axis); float aCutout = aChamfer / 4 * (aR.Item2 - aR.Item1); aR = new Tuple<float, float>(aR.Item1 + aCutout, aR.Item2 - aCutout); float bCutout = bChamfer / 4 * (bR.Item2 - bR.Item1); bR = new Tuple<float, float>(bR.Item1 + bCutout, bR.Item2 - bCutout); // the shortest distance to move aR out of bR float overl = Utils.SegmentInto(aR, bR); if (overl == 0) return false; else { if (Mathf.Abs(overl) < minCross.magnitude) { minCross = overl * axis; } return true; } } }
// 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 CompareEqualUInt32() { var test = new SimpleBinaryOpTest__CompareEqualUInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // 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(); // 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 SimpleBinaryOpTest__CompareEqualUInt32 { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[ElementCount]; private static UInt32[] _data2 = new UInt32[ElementCount]; private static Vector128<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector128<UInt32> _fld1; private Vector128<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32> _dataTable; static SimpleBinaryOpTest__CompareEqualUInt32() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualUInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (uint)(random.Next(0, int.MaxValue)); _data2[i] = (uint)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt32>(_data1, _data2, new UInt32[ElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareEqual( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareEqual( Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareEqual( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareEqual), new Type[] { typeof(Vector128<UInt32>), typeof(Vector128<UInt32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualUInt32(); var result = Sse2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[ElementCount]; UInt32[] inArray2 = new UInt32[ElementCount]; UInt32[] outArray = new UInt32[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[ElementCount]; UInt32[] inArray2 = new UInt32[ElementCount]; UInt32[] outArray = new UInt32[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((uint)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((uint)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareEqual)}<UInt32>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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.Diagnostics; using System.Reflection; namespace System.ComponentModel { /// <summary> /// <para> /// Declares an array of attributes for a member and defines /// the properties and methods that give you access to the attributes in the array. /// All attributes must derive from <see cref='System.Attribute'/>. /// </para> /// </summary> public abstract class MemberDescriptor { private readonly string _name; private readonly string _displayName; private readonly int _nameHash; private AttributeCollection _attributeCollection; private Attribute[] _attributes; private Attribute[] _originalAttributes; private bool _attributesFiltered; private bool _attributesFilled; private int _metadataVersion; private string _category; private string _description; private object _lockCookie = new object(); /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and no attributes. /// </para> /// </summary> protected MemberDescriptor(string name) : this(name, null) { } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <paramref name="name"/> and <paramref name="attributes "/> array. /// </para> /// </summary> protected MemberDescriptor(string name, Attribute[] attributes) { if (name == null || name.Length == 0) { throw new ArgumentException(SR.InvalidMemberName); } _name = name; _displayName = name; _nameHash = name.GetHashCode(); if (attributes != null) { _attributes = attributes; _attributesFiltered = false; } _originalAttributes = _attributes; } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the specified <see cref='System.ComponentModel.MemberDescriptor'/>. /// </para> /// </summary> protected MemberDescriptor(MemberDescriptor descr) { _name = descr.Name; _displayName = _name; _nameHash = _name.GetHashCode(); _attributes = new Attribute[descr.Attributes.Count]; descr.Attributes.CopyTo(_attributes, 0); _attributesFiltered = true; _originalAttributes = _attributes; } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.ComponentModel.MemberDescriptor'/> class with the name in the specified /// <see cref='System.ComponentModel.MemberDescriptor'/> and the attributes /// in both the old <see cref='System.ComponentModel.MemberDescriptor'/> and the <see cref='System.Attribute'/> array. /// </para> /// </summary> protected MemberDescriptor(MemberDescriptor oldMemberDescriptor, Attribute[] newAttributes) { _name = oldMemberDescriptor.Name; _displayName = oldMemberDescriptor.DisplayName; _nameHash = _name.GetHashCode(); List<Attribute> newList = new List<Attribute>(); if (oldMemberDescriptor.Attributes.Count != 0) { foreach (Attribute o in oldMemberDescriptor.Attributes) { newList.Add(o); } } if (newAttributes != null) { foreach (Attribute o in newAttributes) { newList.Add(o); } } _attributes = new Attribute[newList.Count]; newList.CopyTo(_attributes, 0); _attributesFiltered = false; _originalAttributes = _attributes; } /// <summary> /// <para> /// Gets or sets an array of /// attributes. /// </para> /// </summary> protected virtual Attribute[] AttributeArray { get { CheckAttributesValid(); FilterAttributesIfNeeded(); return _attributes; } set { lock (_lockCookie) { _attributes = value; _originalAttributes = value; _attributesFiltered = false; _attributeCollection = null; } } } /// <summary> /// <para> /// Gets the collection of attributes for this member. /// </para> /// </summary> public virtual AttributeCollection Attributes { get { CheckAttributesValid(); AttributeCollection attrs = _attributeCollection; if (attrs == null) { lock (_lockCookie) { attrs = CreateAttributeCollection(); _attributeCollection = attrs; } } return attrs; } } /// <summary> /// <para> /// Gets the name of the category that the member belongs to, as specified /// in the <see cref='System.ComponentModel.CategoryAttribute'/>. /// </para> /// </summary> public virtual string Category => _category ?? (_category = ((CategoryAttribute) Attributes[typeof(CategoryAttribute)]).Category); /// <summary> /// <para> /// Gets the description of /// the member as specified in the <see cref='System.ComponentModel.DescriptionAttribute'/>. /// </para> /// </summary> public virtual string Description => _description ?? (_description = ((DescriptionAttribute) Attributes[typeof(DescriptionAttribute)]).Description); /// <summary> /// <para> /// Gets a value indicating whether the member is browsable as specified in the /// <see cref='System.ComponentModel.BrowsableAttribute'/>. /// </para> /// </summary> public virtual bool IsBrowsable => ((BrowsableAttribute)Attributes[typeof(BrowsableAttribute)]).Browsable; /// <summary> /// <para> /// Gets the /// name of the member. /// </para> /// </summary> public virtual string Name => _name ?? ""; /// <summary> /// <para> /// Gets the hash /// code for the name of the member as specified in <see cref='System.String.GetHashCode'/>. /// </para> /// </summary> protected virtual int NameHashCode => _nameHash; /// <summary> /// <para> /// Determines whether this member should be set only at /// design time as specified in the <see cref='System.ComponentModel.DesignOnlyAttribute'/>. /// </para> /// </summary> public virtual bool DesignTimeOnly => (DesignOnlyAttribute.Yes.Equals(Attributes[typeof(DesignOnlyAttribute)])); /// <summary> /// <para> /// Gets the name that can be displayed in a window like a /// properties window. /// </para> /// </summary> public virtual string DisplayName { get { DisplayNameAttribute displayNameAttr = Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute; if (displayNameAttr == null || displayNameAttr.IsDefaultAttribute()) { return _displayName; } return displayNameAttr.DisplayName; } } /// <summary> /// Called each time we access the attributes on /// this member descriptor to give deriving classes /// a chance to change them on the fly. /// </summary> private void CheckAttributesValid() { if (_attributesFiltered) { if (_metadataVersion != TypeDescriptor.MetadataVersion) { _attributesFilled = false; _attributesFiltered = false; _attributeCollection = null; } } } /// <summary> /// <para> /// Creates a collection of attributes using the /// array of attributes that you passed to the constructor. /// </para> /// </summary> protected virtual AttributeCollection CreateAttributeCollection() { return new AttributeCollection(AttributeArray); } /// <summary> /// <para> /// Compares this instance to the specified <see cref='System.ComponentModel.MemberDescriptor'/> to see if they are equivalent. /// NOTE: If you make a change here, you likely need to change GetHashCode() as well. /// </para> /// </summary> public override bool Equals(object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (obj.GetType() != GetType()) { return false; } MemberDescriptor mdObj = (MemberDescriptor)obj; FilterAttributesIfNeeded(); mdObj.FilterAttributesIfNeeded(); if (mdObj._nameHash != _nameHash) { return false; } if ((mdObj._category == null) != (_category == null) || (_category != null && !mdObj._category.Equals(_category))) { return false; } if ((mdObj._description == null) != (_description == null) || (_description != null && !mdObj._description.Equals(_description))) { return false; } if ((mdObj._attributes == null) != (_attributes == null)) { return false; } bool sameAttrs = true; if (_attributes != null) { if (_attributes.Length != mdObj._attributes.Length) { return false; } for (int i = 0; i < _attributes.Length; i++) { if (!_attributes[i].Equals(mdObj._attributes[i])) { sameAttrs = false; break; } } } return sameAttrs; } /// <summary> /// <para> /// In an inheriting class, adds the attributes of the inheriting class to the /// specified list of attributes in the parent class. For duplicate attributes, /// the last one added to the list will be kept. /// </para> /// </summary> protected virtual void FillAttributes(IList attributeList) { if (_originalAttributes != null) { foreach (Attribute attr in _originalAttributes) { attributeList.Add(attr); } } } private void FilterAttributesIfNeeded() { if (!_attributesFiltered) { List<Attribute> list; if (!_attributesFilled) { list = new List<Attribute>(); try { FillAttributes(list); } catch (Exception e) { Debug.Fail($"{_name}>>{e}"); } } else { list = new List<Attribute>(_attributes); } var map = new Dictionary<object, int>(); for (int i = 0; i < list.Count;) { int savedIndex = -1; object typeId = list[i].TypeId; if (!map.TryGetValue(typeId, out savedIndex)) { map.Add(typeId, i); i++; } else { list[savedIndex] = list[i]; list.RemoveAt(i); } } Attribute[] newAttributes = list.ToArray(); lock (_lockCookie) { _attributes = newAttributes; _attributesFiltered = true; _attributesFilled = true; _metadataVersion = TypeDescriptor.MetadataVersion; } } } /// <summary> /// <para> /// Finds the given method through reflection. This method only looks for public methods. /// </para> /// </summary> protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType) { return FindMethod(componentClass, name, args, returnType, true); } /// <summary> /// <para> /// Finds the given method through reflection. /// </para> /// </summary> protected static MethodInfo FindMethod(Type componentClass, string name, Type[] args, Type returnType, bool publicOnly) { MethodInfo result = null; if (publicOnly) { result = componentClass.GetMethod(name, args); } else { // The original impementation requires the method https://msdn.microsoft.com/en-us/library/5fed8f59(v=vs.110).aspx which is not // available on .NET Core. The replacement will use the default BindingFlags, which may miss some methods that had been found // on .NET Framework. result = componentClass.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null); } if (result != null && !result.ReturnType.IsEquivalentTo(returnType)) { result = null; } return result; } /// <summary> /// Try to keep this reasonable in [....] with Equals(). Specifically, /// if A.Equals(B) returns true, A & B should have the same hash code. /// </summary> public override int GetHashCode() { return _nameHash; } /// <summary> /// This method returns the object that should be used during invocation of members. /// Normally the return value will be the same as the instance passed in. If /// someone associated another object with this instance, or if the instance is a /// custom type descriptor, GetInvocationTarget may return a different value. /// </summary> protected virtual object GetInvocationTarget(Type type, object instance) { if (type == null) { throw new ArgumentNullException(nameof(type)); } if (instance == null) { throw new ArgumentNullException(nameof(instance)); } return TypeDescriptor.GetAssociation(type, instance); } /// <summary> /// <para> /// Gets a component site /// for the given component. /// </para> /// </summary> protected static ISite GetSite(object component) { return (component as IComponent)?.Site; } [Obsolete("This method has been deprecated. Use GetInvocationTarget instead. http://go.microsoft.com/fwlink/?linkid=14202")] protected static object GetInvokee(Type componentClass, object component) { if (componentClass == null) { throw new ArgumentNullException(nameof(componentClass)); } if (component == null) { throw new ArgumentNullException(nameof(component)); } return TypeDescriptor.GetAssociation(componentClass, component); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.PythonTools.Django; using Microsoft.PythonTools.Infrastructure; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools; using TestUtilities; using TestUtilities.UI; using TestUtilities.UI.Python; using TestUtilities.UI.Python.Django; using PythonConstants = Microsoft.PythonTools.PythonConstants; namespace DjangoUITests { public class DjangoProjectUITests { public void NewDjangoProject(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { var project = app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.DjangoWebProjectTemplate, TestData.GetTempPath(), "NewDjangoProject" ); var folder = project.ProjectItems.Item(project.Name); Assert.IsNotNull(project.ProjectItems.Item("manage.py")); Assert.IsNotNull(folder.ProjectItems.Item("settings.py")); Assert.IsNotNull(folder.ProjectItems.Item("urls.py")); Assert.IsNotNull(folder.ProjectItems.Item("__init__.py")); Assert.IsNotNull(folder.ProjectItems.Item("wsgi.py")); } public void NewDjangoProjectSafeProjectName(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { var project = app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.DjangoWebProjectTemplate, TestData.GetTempPath(), "Django Project $100" ); var folder = project.ProjectItems.Item("Django_Project__100"); Assert.IsNotNull(project.ProjectItems.Item("manage.py")); Assert.IsNotNull(folder.ProjectItems.Item("settings.py")); Assert.IsNotNull(folder.ProjectItems.Item("urls.py")); Assert.IsNotNull(folder.ProjectItems.Item("__init__.py")); Assert.IsNotNull(folder.ProjectItems.Item("wsgi.py")); var settings = app.ServiceProvider.GetUIThread().Invoke(() => project.GetPythonProject().GetProperty("DjangoSettingsModule")); Assert.AreEqual("Django_Project__100.settings", settings); } public void DjangoCollectStaticFilesCommand(PythonVisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { var sln = app.CopyProjectForTest(@"TestData\DjangoApplication.sln"); var project = app.OpenProject(sln); app.SolutionExplorerTreeView.SelectProject(project); app.Dte.ExecuteCommand("Project.CollectStaticFiles"); using (var console = app.GetInteractiveWindow("Django Management Console - " + project.Name)) { Assert.IsNotNull(console); console.WaitForTextEnd("The interactive Python process has exited.", ">"); Assert.IsTrue(console.TextView.TextSnapshot.GetText().Contains("0 static files copied")); } } public void DjangoShellCommand(PythonVisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { // Open a project that has some models defined, and make sure they can be imported without errors var sln = app.CopyProjectForTest(@"TestData\DjangoAnalysisTestApp.sln"); var project = app.OpenProject(sln); app.SolutionExplorerTreeView.SelectProject(project); app.Dte.ExecuteCommand("Project.OpenDjangoShell"); using (var console = app.GetInteractiveWindow("Django Management Console - " + project.Name)) { Assert.IsNotNull(console); bool started = false; for (int i = 0; i < 20; i++) { if (console.TextView.TextSnapshot.GetText().Contains("Starting Django")) { started = true; break; } Thread.Sleep(250); } Assert.IsTrue(started, "Did not see 'Starting Django <ver> shell' message"); console.WaitForTextEnd(">"); console.SubmitCode("import myapp.models"); console.WaitForTextEnd(">import myapp.models", ">"); } } public void DjangoCommandsNonDjangoApp(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { var project = app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.PythonApplicationTemplate, TestData.GetTempPath(), "DjangoCommandsNoDjangoApp" ); app.SolutionExplorerTreeView.SelectProject(project); try { app.Dte.ExecuteCommand("Project.ValidateDjangoApp"); Assert.Fail("Expected COMException"); } catch (COMException e) { // requires a Django project Assert.IsTrue(e.Message.Contains("is not valid"), e.ToString()); } try { app.Dte.ExecuteCommand("Project.DjangoSyncDB"); Assert.Fail("Expected COMException"); } catch (COMException e) { // requires a Django project Assert.IsTrue(e.Message.Contains("is not valid"), e.ToString()); } } public void StartNewApp(PythonVisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { var project = app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.DjangoWebProjectTemplate, TestData.GetTempPath(), "StartNewApp" ); app.SolutionExplorerTreeView.SelectProject(project); using (var newAppDialog = NewAppDialog.FromDte(app)) { newAppDialog.AppName = "Fob"; newAppDialog.OK(); } app.SolutionExplorerTreeView.WaitForItem( app.Dte.Solution.FullName, app.Dte.Solution.Projects.Item(1).Name, "Fob", "models.py" ); var appFolder = project.ProjectItems.Item("Fob"); Assert.IsNotNull(appFolder.ProjectItems.Item("models.py")); Assert.IsNotNull(appFolder.ProjectItems.Item("tests.py")); Assert.IsNotNull(appFolder.ProjectItems.Item("views.py")); Assert.IsNotNull(appFolder.ProjectItems.Item("__init__.py")); var templatesFolder = appFolder.ProjectItems.Item("templates"); var templatesAppFolder = templatesFolder.ProjectItems.Item("Fob"); Assert.IsNotNull(templatesAppFolder.ProjectItems.Item("index.html")); app.SolutionExplorerTreeView.SelectProject(project); app.Dte.ExecuteCommand("Project.DjangoCheckDjango17"); using (var console = app.GetInteractiveWindow("Django Management Console - " + project.Name)) { Assert.IsNotNull(console); console.WaitForTextEnd("The interactive Python process has exited.", ">"); var consoleText = console.TextView.TextSnapshot.GetText(); AssertUtil.Contains(consoleText, "Executing manage.py check"); AssertUtil.Contains(consoleText, "System check identified no issues (0 silenced)."); } app.SolutionExplorerTreeView.SelectProject(project); using (var newItem = NewItemDialog.FromDte(app)) { var htmlPage = newItem.ProjectTypes.FindItem("HTML Page"); htmlPage.Select(); newItem.FileName = "NewPage.html"; newItem.OK(); } System.Threading.Thread.Sleep(1000); Assert.IsNotNull(project.ProjectItems.Item("NewPage.html")); } public void StartNewAppDuplicateName(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { var project = app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.DjangoWebProjectTemplate, TestData.GetTempPath(), "StartNewAppDuplicateName" ); app.SolutionExplorerTreeView.SelectProject(project); using (var newAppDialog = NewAppDialog.FromDte(app)) { newAppDialog.AppName = "Fob"; newAppDialog.OK(); } app.SolutionExplorerTreeView.WaitForItem( app.Dte.Solution.FullName, app.Dte.Solution.Projects.Item(1).Name, "Fob", "models.py" ); app.Dte.Documents.CloseAll(EnvDTE.vsSaveChanges.vsSaveChangesNo); app.SolutionExplorerTreeView.SelectProject(project); using (var newAppDialog = NewAppDialog.FromDte(app)) { newAppDialog.AppName = "Fob"; newAppDialog.OK(); } using (var dlg = AutomationDialog.WaitForDialog(app)) { } } public void StartNewAppSameAsProjectName(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { var project = app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.DjangoWebProjectTemplate, TestData.GetTempPath(), "StartNewAppSameAsProjectName" ); app.SolutionExplorerTreeView.SelectProject(project); using (var newAppDialog = NewAppDialog.FromDte(app)) { newAppDialog.AppName = app.Dte.Solution.Projects.Item(1).Name; newAppDialog.OK(); } using (var dlg = AutomationDialog.WaitForDialog(app)) { } } public void DebugProjectProperties(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { var project = app.CreateProject( PythonVisualStudioApp.TemplateLanguageName, PythonVisualStudioApp.DjangoWebProjectTemplate, TestData.GetTempPath(), "DebugProjectProperties" ); app.SolutionExplorerTreeView.SelectProject(project); app.Dte.ExecuteCommand("Project.Properties"); var window = app.Dte.Windows.OfType<EnvDTE.Window>().FirstOrDefault(w => w.Caption == project.Name); Assert.IsNotNull(window); window.Activate(); var hwnd = window.HWnd; var projProps = new ProjectPropertiesWindow(hwnd); // FYI This is broken on Dev15 (15.0 up to latest build as of now 15.3 build 26507) // Active page can't be changed via UI automation. // Bug 433488 has been filed. // - InvokePattern is not available // - SelectionItemPattern is available (according to Inspect) but does not work // - Default action does nothing var debugPage = projProps[new Guid(PythonConstants.DebugPropertyPageGuid)]; Assert.IsNotNull(debugPage); var dbgProps = new PythonProjectDebugProperties(debugPage); Assert.AreEqual("Django Web launcher", dbgProps.LaunchMode); dbgProps.AssertMatchesProject(project.GetPythonProject()); } public void DjangoProjectWithSubdirectory(VisualStudioApp app, DjangoInterpreterSetter interpreterSetter) { var sln = app.CopyProjectForTest(@"TestData\DjangoProjectWithSubDirectory.sln"); var slnDir = PathUtils.GetParent(sln); var project = app.OpenProject(sln); var pyProj = project.GetPythonProject(); var dsm = pyProj.Site.GetUIThread().Invoke(() => pyProj.GetProperty("DjangoSettingsModule")); Assert.AreEqual("config.settings", dsm); var workDir = pyProj.Site.GetUIThread().Invoke(() => pyProj.GetWorkingDirectory()).TrimEnd('\\'); Assert.AreEqual(Path.Combine(slnDir, "DjangoProjectWithSubDirectory", "project"), workDir, true); var cmd = pyProj.FindCommand("DjangoCollectStaticCommand"); pyProj.Site.GetUIThread().Invoke(() => { Assert.IsTrue(cmd.CanExecute(pyProj), "Cannot execute DjangoCollectStaticCommand"); cmd.Execute(pyProj); }); // The static dir is 'test_static', check that the admin files // are copied into there. Assert.IsTrue(Directory.Exists(Path.Combine(workDir, "test_static", "admin")), "admin static directory was not created"); Assert.IsTrue(File.Exists(Path.Combine(workDir, "test_static", "admin", "css", "base.css")), "admin static files were not copied"); } } }
using Signum.Engine.Maps; using System.Collections.ObjectModel; using System.Collections.Immutable; namespace Signum.Engine.Linq; internal class EntityCompleter : DbExpressionVisitor { readonly QueryBinder binder; ImmutableStack<Type> previousTypes = ImmutableStack<Type>.Empty; public EntityCompleter(QueryBinder binder) { this.binder = binder; } public static Expression Complete(Expression source, QueryBinder binder) { EntityCompleter pc = new EntityCompleter(binder); var result = pc.Visit(source); var expandedResul = QueryJoinExpander.ExpandJoins(result, binder, cleanRequests: true, binder.systemTime); return expandedResul; } protected internal override Expression VisitLiteReference(LiteReferenceExpression lite) { if (lite.EagerEntity) return base.VisitLiteReference(lite); var id = lite.Reference is ImplementedByAllExpression || lite.Reference is ImplementedByExpression ib && ib.Implementations.Select(imp=>imp.Value.ExternalId.ValueType.Nullify()).Distinct().Count() > 1 ? (Expression)binder.GetIdString(lite.Reference) : (Expression)binder.GetId(lite.Reference); var typeId = binder.GetEntityType(lite.Reference); var toStr = LiteToString(lite, typeId); //var toStr2 = Visit(toStr); //AdditionalBinding in embedded requires it, but makes problems in many other lites in Nominator return new LiteValueExpression(lite.Type, typeId, id, toStr); } private Expression? LiteToString(LiteReferenceExpression lite, Expression typeId) { if (lite.CustomToStr != null) return Visit(lite.CustomToStr); if (lite.Reference is ImplementedByAllExpression) return null; if (lite.LazyToStr) return null; if (IsCacheable(typeId)) return null; if (lite.Reference is EntityExpression entityExp) { if (entityExp.AvoidExpandOnRetrieving) return null; return binder.BindMethodCall(Expression.Call(entityExp, EntityExpression.ToStringMethod)); } if (lite.Reference is ImplementedByExpression ibe) { if (ibe.Implementations.Any(imp => imp.Value.AvoidExpandOnRetrieving)) return null; return ibe.Implementations.Values.Select(ee => new When(SmartEqualizer.NotEqualNullable(ee.ExternalId, QueryBinder.NullId(ee.ExternalId.ValueType)), binder.BindMethodCall(Expression.Call(ee, EntityExpression.ToStringMethod))) ).ToCondition(typeof(string)); } return binder.BindMethodCall(Expression.Call(lite.Reference, EntityExpression.ToStringMethod)); } private static bool IsCacheable(Expression newTypeId) { if (newTypeId is TypeEntityExpression tfie) return IsCached(tfie.TypeValue); if (newTypeId is TypeImplementedByExpression tibe) return tibe.TypeImplementations.All(t => IsCached(t.Key)); return false; } protected internal override Expression VisitEntity(EntityExpression ee) { if (previousTypes.Contains(ee.Type) || IsCached(ee.Type) || ee.AvoidExpandOnRetrieving) { ee = new EntityExpression(ee.Type, ee.ExternalId, null, null, null, null, null /*ee.SystemPeriod TODO*/ , ee.AvoidExpandOnRetrieving); } else ee = binder.Completed(ee); previousTypes = previousTypes.Push(ee.Type); var bindings = VisitBindings(ee.Bindings!); var mixins = Visit(ee.Mixins!, VisitMixinEntity); var id = (PrimaryKeyExpression)Visit(ee.ExternalId); var result = new EntityExpression(ee.Type, id, ee.ExternalPeriod, ee.TableAlias, bindings, mixins, ee.TablePeriod, ee.AvoidExpandOnRetrieving); previousTypes = previousTypes.Pop(); return result; } private ReadOnlyCollection<FieldBinding> VisitBindings(ReadOnlyCollection<FieldBinding> bindings) { return bindings.Select(b => { var newB = Visit(b.Binding); if (newB != null) return new FieldBinding(b.FieldInfo, newB); return null; }).NotNull().ToReadOnly(); } protected internal override Expression VisitEmbeddedEntity(EmbeddedEntityExpression eee) { var bindings = VisitBindings(eee.Bindings); var mixins = eee.Mixins == null ? null : Visit(eee.Mixins, VisitMixinEntity); var hasValue = Visit(eee.HasValue); if (eee.Bindings != bindings || eee.HasValue != hasValue || eee.EntityContext != null) { return new EmbeddedEntityExpression(eee.Type, hasValue, bindings, mixins, eee.FieldEmbedded, eee.ViewTable, null); } return eee; } protected internal override MixinEntityExpression VisitMixinEntity(MixinEntityExpression me) { var bindings = VisitBindings(me.Bindings); if (me.Bindings != bindings || me.EntityContext != null) { return new MixinEntityExpression(me.Type, bindings, me.MainEntityAlias, me.FieldMixin, null); } return me; } private static bool IsCached(Type type) { var cc = Schema.Current.CacheController(type); if (cc != null && cc.Enabled) { cc.Load(); /*just to force cache before executing the query*/ return true; } return false; } protected internal override Expression VisitMList(MListExpression ml) { var proj = binder.MListProjection(ml, withRowId: true); var newProj = (ProjectionExpression)this.Visit(proj); return new MListProjectionExpression(ml.Type, newProj); } protected internal override Expression VisitAdditionalField(AdditionalFieldExpression afe) { var exp = binder.BindAdditionalField(afe, entityCompleter: true); var newEx = this.Visit(exp)!; if (newEx is ProjectionExpression newProj && newProj.Projector.Type.IsInstantiationOf(typeof(MList<>.RowIdElement))) return new MListProjectionExpression(afe.Type, newProj); return newEx; } protected internal override Expression VisitProjection(ProjectionExpression proj) { Expression projector; SelectExpression select = proj.Select; using (binder.SetCurrentSource(proj.Select)) projector = this.Visit(proj.Projector); Alias alias = binder.aliasGenerator.NextSelectAlias(); ProjectedColumns pc = ColumnProjector.ProjectColumns(projector, alias); projector = pc.Projector; select = new SelectExpression(alias, false, null, pc.Columns, select, null, null, null, 0); if (projector != proj.Projector) return new ProjectionExpression(select, projector, proj.UniqueFunction, proj.Type); return proj; } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.8009 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by wsdl, Version=2.0.50727.3038. // namespace WebsitePanel.EnterpriseServer { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; using WebsitePanel.Providers.SharePoint; using WebsitePanel.Providers; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="esHostedSharePointServersSoap", Namespace="http://smbsaas/websitepanel/enterpriseserver")] [System.Xml.Serialization.XmlIncludeAttribute(typeof(ServiceProviderItem))] public partial class esHostedSharePointServers : Microsoft.Web.Services3.WebServicesClientProtocol { private System.Threading.SendOrPostCallback GetSiteCollectionsPagedOperationCompleted; private System.Threading.SendOrPostCallback GetSupportedLanguagesOperationCompleted; private System.Threading.SendOrPostCallback GetSiteCollectionsOperationCompleted; private System.Threading.SendOrPostCallback SetStorageSettingsOperationCompleted; private System.Threading.SendOrPostCallback GetSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback GetSiteCollectionByDomainOperationCompleted; private System.Threading.SendOrPostCallback AddSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback DeleteSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback DeleteSiteCollectionsOperationCompleted; private System.Threading.SendOrPostCallback BackupSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback RestoreSiteCollectionOperationCompleted; private System.Threading.SendOrPostCallback GetBackupBinaryChunkOperationCompleted; private System.Threading.SendOrPostCallback AppendBackupBinaryChunkOperationCompleted; private System.Threading.SendOrPostCallback CalculateSharePointSitesDiskSpaceOperationCompleted; private System.Threading.SendOrPostCallback UpdateQuotaOperationCompleted; /// <remarks/> public esHostedSharePointServers() { this.Url = "http://localhost:9002/esHostedSharePointServers.asmx"; } /// <remarks/> public event GetSiteCollectionsPagedCompletedEventHandler GetSiteCollectionsPagedCompleted; /// <remarks/> public event GetSupportedLanguagesCompletedEventHandler GetSupportedLanguagesCompleted; /// <remarks/> public event GetSiteCollectionsCompletedEventHandler GetSiteCollectionsCompleted; /// <remarks/> public event SetStorageSettingsCompletedEventHandler SetStorageSettingsCompleted; /// <remarks/> public event GetSiteCollectionCompletedEventHandler GetSiteCollectionCompleted; /// <remarks/> public event GetSiteCollectionByDomainCompletedEventHandler GetSiteCollectionByDomainCompleted; /// <remarks/> public event AddSiteCollectionCompletedEventHandler AddSiteCollectionCompleted; /// <remarks/> public event DeleteSiteCollectionCompletedEventHandler DeleteSiteCollectionCompleted; /// <remarks/> public event DeleteSiteCollectionsCompletedEventHandler DeleteSiteCollectionsCompleted; /// <remarks/> public event BackupSiteCollectionCompletedEventHandler BackupSiteCollectionCompleted; /// <remarks/> public event RestoreSiteCollectionCompletedEventHandler RestoreSiteCollectionCompleted; /// <remarks/> public event GetBackupBinaryChunkCompletedEventHandler GetBackupBinaryChunkCompleted; /// <remarks/> public event AppendBackupBinaryChunkCompletedEventHandler AppendBackupBinaryChunkCompleted; /// <remarks/> public event CalculateSharePointSitesDiskSpaceCompletedEventHandler CalculateSharePointSitesDiskSpaceCompleted; /// <remarks/> public event UpdateQuotaCompletedEventHandler UpdateQuotaCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetSiteCollectionsPaged", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SharePointSiteCollectionListPaged GetSiteCollectionsPaged(int packageId, int organizationId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { object[] results = this.Invoke("GetSiteCollectionsPaged", new object[] { packageId, organizationId, filterColumn, filterValue, sortColumn, startRow, maximumRows}); return ((SharePointSiteCollectionListPaged)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetSiteCollectionsPaged(int packageId, int organizationId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetSiteCollectionsPaged", new object[] { packageId, organizationId, filterColumn, filterValue, sortColumn, startRow, maximumRows}, callback, asyncState); } /// <remarks/> public SharePointSiteCollectionListPaged EndGetSiteCollectionsPaged(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((SharePointSiteCollectionListPaged)(results[0])); } /// <remarks/> public void GetSiteCollectionsPagedAsync(int packageId, int organizationId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { this.GetSiteCollectionsPagedAsync(packageId, organizationId, filterColumn, filterValue, sortColumn, startRow, maximumRows, null); } /// <remarks/> public void GetSiteCollectionsPagedAsync(int packageId, int organizationId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows, object userState) { if ((this.GetSiteCollectionsPagedOperationCompleted == null)) { this.GetSiteCollectionsPagedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSiteCollectionsPagedOperationCompleted); } this.InvokeAsync("GetSiteCollectionsPaged", new object[] { packageId, organizationId, filterColumn, filterValue, sortColumn, startRow, maximumRows}, this.GetSiteCollectionsPagedOperationCompleted, userState); } private void OnGetSiteCollectionsPagedOperationCompleted(object arg) { if ((this.GetSiteCollectionsPagedCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetSiteCollectionsPagedCompleted(this, new GetSiteCollectionsPagedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetSupportedLanguages", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int[] GetSupportedLanguages(int packageId) { object[] results = this.Invoke("GetSupportedLanguages", new object[] { packageId}); return ((int[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetSupportedLanguages(int packageId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetSupportedLanguages", new object[] { packageId}, callback, asyncState); } /// <remarks/> public int[] EndGetSupportedLanguages(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int[])(results[0])); } /// <remarks/> public void GetSupportedLanguagesAsync(int packageId) { this.GetSupportedLanguagesAsync(packageId, null); } /// <remarks/> public void GetSupportedLanguagesAsync(int packageId, object userState) { if ((this.GetSupportedLanguagesOperationCompleted == null)) { this.GetSupportedLanguagesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSupportedLanguagesOperationCompleted); } this.InvokeAsync("GetSupportedLanguages", new object[] { packageId}, this.GetSupportedLanguagesOperationCompleted, userState); } private void OnGetSupportedLanguagesOperationCompleted(object arg) { if ((this.GetSupportedLanguagesCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetSupportedLanguagesCompleted(this, new GetSupportedLanguagesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetSiteCollections", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SharePointSiteCollection[] GetSiteCollections(int packageId, bool recursive) { object[] results = this.Invoke("GetSiteCollections", new object[] { packageId, recursive}); return ((SharePointSiteCollection[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetSiteCollections(int packageId, bool recursive, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetSiteCollections", new object[] { packageId, recursive}, callback, asyncState); } /// <remarks/> public SharePointSiteCollection[] EndGetSiteCollections(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((SharePointSiteCollection[])(results[0])); } /// <remarks/> public void GetSiteCollectionsAsync(int packageId, bool recursive) { this.GetSiteCollectionsAsync(packageId, recursive, null); } /// <remarks/> public void GetSiteCollectionsAsync(int packageId, bool recursive, object userState) { if ((this.GetSiteCollectionsOperationCompleted == null)) { this.GetSiteCollectionsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSiteCollectionsOperationCompleted); } this.InvokeAsync("GetSiteCollections", new object[] { packageId, recursive}, this.GetSiteCollectionsOperationCompleted, userState); } private void OnGetSiteCollectionsOperationCompleted(object arg) { if ((this.GetSiteCollectionsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetSiteCollectionsCompleted(this, new GetSiteCollectionsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/SetStorageSettings", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int SetStorageSettings(int itemId, int maxStorage, int warningStorage, bool applyToSiteCollections) { object[] results = this.Invoke("SetStorageSettings", new object[] { itemId, maxStorage, warningStorage, applyToSiteCollections}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginSetStorageSettings(int itemId, int maxStorage, int warningStorage, bool applyToSiteCollections, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("SetStorageSettings", new object[] { itemId, maxStorage, warningStorage, applyToSiteCollections}, callback, asyncState); } /// <remarks/> public int EndSetStorageSettings(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void SetStorageSettingsAsync(int itemId, int maxStorage, int warningStorage, bool applyToSiteCollections) { this.SetStorageSettingsAsync(itemId, maxStorage, warningStorage, applyToSiteCollections, null); } /// <remarks/> public void SetStorageSettingsAsync(int itemId, int maxStorage, int warningStorage, bool applyToSiteCollections, object userState) { if ((this.SetStorageSettingsOperationCompleted == null)) { this.SetStorageSettingsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetStorageSettingsOperationCompleted); } this.InvokeAsync("SetStorageSettings", new object[] { itemId, maxStorage, warningStorage, applyToSiteCollections}, this.SetStorageSettingsOperationCompleted, userState); } private void OnSetStorageSettingsOperationCompleted(object arg) { if ((this.SetStorageSettingsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.SetStorageSettingsCompleted(this, new SetStorageSettingsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetSiteCollection", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SharePointSiteCollection GetSiteCollection(int itemId) { object[] results = this.Invoke("GetSiteCollection", new object[] { itemId}); return ((SharePointSiteCollection)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetSiteCollection(int itemId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetSiteCollection", new object[] { itemId}, callback, asyncState); } /// <remarks/> public SharePointSiteCollection EndGetSiteCollection(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((SharePointSiteCollection)(results[0])); } /// <remarks/> public void GetSiteCollectionAsync(int itemId) { this.GetSiteCollectionAsync(itemId, null); } /// <remarks/> public void GetSiteCollectionAsync(int itemId, object userState) { if ((this.GetSiteCollectionOperationCompleted == null)) { this.GetSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSiteCollectionOperationCompleted); } this.InvokeAsync("GetSiteCollection", new object[] { itemId}, this.GetSiteCollectionOperationCompleted, userState); } private void OnGetSiteCollectionOperationCompleted(object arg) { if ((this.GetSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetSiteCollectionCompleted(this, new GetSiteCollectionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetSiteCollectionByDomain", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SharePointSiteCollection GetSiteCollectionByDomain(int organizationId, string domain) { object[] results = this.Invoke("GetSiteCollectionByDomain", new object[] { organizationId, domain}); return ((SharePointSiteCollection)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetSiteCollectionByDomain(int organizationId, string domain, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetSiteCollectionByDomain", new object[] { organizationId, domain}, callback, asyncState); } /// <remarks/> public SharePointSiteCollection EndGetSiteCollectionByDomain(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((SharePointSiteCollection)(results[0])); } /// <remarks/> public void GetSiteCollectionByDomainAsync(int organizationId, string domain) { this.GetSiteCollectionByDomainAsync(organizationId, domain, null); } /// <remarks/> public void GetSiteCollectionByDomainAsync(int organizationId, string domain, object userState) { if ((this.GetSiteCollectionByDomainOperationCompleted == null)) { this.GetSiteCollectionByDomainOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSiteCollectionByDomainOperationCompleted); } this.InvokeAsync("GetSiteCollectionByDomain", new object[] { organizationId, domain}, this.GetSiteCollectionByDomainOperationCompleted, userState); } private void OnGetSiteCollectionByDomainOperationCompleted(object arg) { if ((this.GetSiteCollectionByDomainCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetSiteCollectionByDomainCompleted(this, new GetSiteCollectionByDomainCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/AddSiteCollection", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int AddSiteCollection(SharePointSiteCollection item) { object[] results = this.Invoke("AddSiteCollection", new object[] { item}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginAddSiteCollection(SharePointSiteCollection item, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddSiteCollection", new object[] { item}, callback, asyncState); } /// <remarks/> public int EndAddSiteCollection(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void AddSiteCollectionAsync(SharePointSiteCollection item) { this.AddSiteCollectionAsync(item, null); } /// <remarks/> public void AddSiteCollectionAsync(SharePointSiteCollection item, object userState) { if ((this.AddSiteCollectionOperationCompleted == null)) { this.AddSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddSiteCollectionOperationCompleted); } this.InvokeAsync("AddSiteCollection", new object[] { item}, this.AddSiteCollectionOperationCompleted, userState); } private void OnAddSiteCollectionOperationCompleted(object arg) { if ((this.AddSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddSiteCollectionCompleted(this, new AddSiteCollectionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteSiteCollection", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int DeleteSiteCollection(int itemId) { object[] results = this.Invoke("DeleteSiteCollection", new object[] { itemId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginDeleteSiteCollection(int itemId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteSiteCollection", new object[] { itemId}, callback, asyncState); } /// <remarks/> public int EndDeleteSiteCollection(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void DeleteSiteCollectionAsync(int itemId) { this.DeleteSiteCollectionAsync(itemId, null); } /// <remarks/> public void DeleteSiteCollectionAsync(int itemId, object userState) { if ((this.DeleteSiteCollectionOperationCompleted == null)) { this.DeleteSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteSiteCollectionOperationCompleted); } this.InvokeAsync("DeleteSiteCollection", new object[] { itemId}, this.DeleteSiteCollectionOperationCompleted, userState); } private void OnDeleteSiteCollectionOperationCompleted(object arg) { if ((this.DeleteSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteSiteCollectionCompleted(this, new DeleteSiteCollectionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteSiteCollections", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int DeleteSiteCollections(int organizationId) { object[] results = this.Invoke("DeleteSiteCollections", new object[] { organizationId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginDeleteSiteCollections(int organizationId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteSiteCollections", new object[] { organizationId}, callback, asyncState); } /// <remarks/> public int EndDeleteSiteCollections(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void DeleteSiteCollectionsAsync(int organizationId) { this.DeleteSiteCollectionsAsync(organizationId, null); } /// <remarks/> public void DeleteSiteCollectionsAsync(int organizationId, object userState) { if ((this.DeleteSiteCollectionsOperationCompleted == null)) { this.DeleteSiteCollectionsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteSiteCollectionsOperationCompleted); } this.InvokeAsync("DeleteSiteCollections", new object[] { organizationId}, this.DeleteSiteCollectionsOperationCompleted, userState); } private void OnDeleteSiteCollectionsOperationCompleted(object arg) { if ((this.DeleteSiteCollectionsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteSiteCollectionsCompleted(this, new DeleteSiteCollectionsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/BackupSiteCollection", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string BackupSiteCollection(int itemId, string fileName, bool zipBackup, bool download, string folderName) { object[] results = this.Invoke("BackupSiteCollection", new object[] { itemId, fileName, zipBackup, download, folderName}); return ((string)(results[0])); } /// <remarks/> public System.IAsyncResult BeginBackupSiteCollection(int itemId, string fileName, bool zipBackup, bool download, string folderName, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("BackupSiteCollection", new object[] { itemId, fileName, zipBackup, download, folderName}, callback, asyncState); } /// <remarks/> public string EndBackupSiteCollection(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } /// <remarks/> public void BackupSiteCollectionAsync(int itemId, string fileName, bool zipBackup, bool download, string folderName) { this.BackupSiteCollectionAsync(itemId, fileName, zipBackup, download, folderName, null); } /// <remarks/> public void BackupSiteCollectionAsync(int itemId, string fileName, bool zipBackup, bool download, string folderName, object userState) { if ((this.BackupSiteCollectionOperationCompleted == null)) { this.BackupSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnBackupSiteCollectionOperationCompleted); } this.InvokeAsync("BackupSiteCollection", new object[] { itemId, fileName, zipBackup, download, folderName}, this.BackupSiteCollectionOperationCompleted, userState); } private void OnBackupSiteCollectionOperationCompleted(object arg) { if ((this.BackupSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.BackupSiteCollectionCompleted(this, new BackupSiteCollectionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/RestoreSiteCollection", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int RestoreSiteCollection(int itemId, string uploadedFile, string packageFile) { object[] results = this.Invoke("RestoreSiteCollection", new object[] { itemId, uploadedFile, packageFile}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginRestoreSiteCollection(int itemId, string uploadedFile, string packageFile, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("RestoreSiteCollection", new object[] { itemId, uploadedFile, packageFile}, callback, asyncState); } /// <remarks/> public int EndRestoreSiteCollection(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void RestoreSiteCollectionAsync(int itemId, string uploadedFile, string packageFile) { this.RestoreSiteCollectionAsync(itemId, uploadedFile, packageFile, null); } /// <remarks/> public void RestoreSiteCollectionAsync(int itemId, string uploadedFile, string packageFile, object userState) { if ((this.RestoreSiteCollectionOperationCompleted == null)) { this.RestoreSiteCollectionOperationCompleted = new System.Threading.SendOrPostCallback(this.OnRestoreSiteCollectionOperationCompleted); } this.InvokeAsync("RestoreSiteCollection", new object[] { itemId, uploadedFile, packageFile}, this.RestoreSiteCollectionOperationCompleted, userState); } private void OnRestoreSiteCollectionOperationCompleted(object arg) { if ((this.RestoreSiteCollectionCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.RestoreSiteCollectionCompleted(this, new RestoreSiteCollectionCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetBackupBinaryChunk", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] [return: System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] public byte[] GetBackupBinaryChunk(int itemId, string path, int offset, int length) { object[] results = this.Invoke("GetBackupBinaryChunk", new object[] { itemId, path, offset, length}); return ((byte[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetBackupBinaryChunk(int itemId, string path, int offset, int length, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetBackupBinaryChunk", new object[] { itemId, path, offset, length}, callback, asyncState); } /// <remarks/> public byte[] EndGetBackupBinaryChunk(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((byte[])(results[0])); } /// <remarks/> public void GetBackupBinaryChunkAsync(int itemId, string path, int offset, int length) { this.GetBackupBinaryChunkAsync(itemId, path, offset, length, null); } /// <remarks/> public void GetBackupBinaryChunkAsync(int itemId, string path, int offset, int length, object userState) { if ((this.GetBackupBinaryChunkOperationCompleted == null)) { this.GetBackupBinaryChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetBackupBinaryChunkOperationCompleted); } this.InvokeAsync("GetBackupBinaryChunk", new object[] { itemId, path, offset, length}, this.GetBackupBinaryChunkOperationCompleted, userState); } private void OnGetBackupBinaryChunkOperationCompleted(object arg) { if ((this.GetBackupBinaryChunkCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetBackupBinaryChunkCompleted(this, new GetBackupBinaryChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/AppendBackupBinaryChunk", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public string AppendBackupBinaryChunk(int itemId, string fileName, string path, [System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")] byte[] chunk) { object[] results = this.Invoke("AppendBackupBinaryChunk", new object[] { itemId, fileName, path, chunk}); return ((string)(results[0])); } /// <remarks/> public System.IAsyncResult BeginAppendBackupBinaryChunk(int itemId, string fileName, string path, byte[] chunk, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AppendBackupBinaryChunk", new object[] { itemId, fileName, path, chunk}, callback, asyncState); } /// <remarks/> public string EndAppendBackupBinaryChunk(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } /// <remarks/> public void AppendBackupBinaryChunkAsync(int itemId, string fileName, string path, byte[] chunk) { this.AppendBackupBinaryChunkAsync(itemId, fileName, path, chunk, null); } /// <remarks/> public void AppendBackupBinaryChunkAsync(int itemId, string fileName, string path, byte[] chunk, object userState) { if ((this.AppendBackupBinaryChunkOperationCompleted == null)) { this.AppendBackupBinaryChunkOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAppendBackupBinaryChunkOperationCompleted); } this.InvokeAsync("AppendBackupBinaryChunk", new object[] { itemId, fileName, path, chunk}, this.AppendBackupBinaryChunkOperationCompleted, userState); } private void OnAppendBackupBinaryChunkOperationCompleted(object arg) { if ((this.AppendBackupBinaryChunkCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AppendBackupBinaryChunkCompleted(this, new AppendBackupBinaryChunkCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/CalculateSharePointSitesDiskSpace", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public SharePointSiteDiskSpace[] CalculateSharePointSitesDiskSpace(int itemId, out int errorCode) { object[] results = this.Invoke("CalculateSharePointSitesDiskSpace", new object[] { itemId}); errorCode = ((int)(results[1])); return ((SharePointSiteDiskSpace[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginCalculateSharePointSitesDiskSpace(int itemId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("CalculateSharePointSitesDiskSpace", new object[] { itemId}, callback, asyncState); } /// <remarks/> public SharePointSiteDiskSpace[] EndCalculateSharePointSitesDiskSpace(System.IAsyncResult asyncResult, out int errorCode) { object[] results = this.EndInvoke(asyncResult); errorCode = ((int)(results[1])); return ((SharePointSiteDiskSpace[])(results[0])); } /// <remarks/> public void CalculateSharePointSitesDiskSpaceAsync(int itemId) { this.CalculateSharePointSitesDiskSpaceAsync(itemId, null); } /// <remarks/> public void CalculateSharePointSitesDiskSpaceAsync(int itemId, object userState) { if ((this.CalculateSharePointSitesDiskSpaceOperationCompleted == null)) { this.CalculateSharePointSitesDiskSpaceOperationCompleted = new System.Threading.SendOrPostCallback(this.OnCalculateSharePointSitesDiskSpaceOperationCompleted); } this.InvokeAsync("CalculateSharePointSitesDiskSpace", new object[] { itemId}, this.CalculateSharePointSitesDiskSpaceOperationCompleted, userState); } private void OnCalculateSharePointSitesDiskSpaceOperationCompleted(object arg) { if ((this.CalculateSharePointSitesDiskSpaceCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.CalculateSharePointSitesDiskSpaceCompleted(this, new CalculateSharePointSitesDiskSpaceCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/UpdateQuota", RequestNamespace="http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace="http://smbsaas/websitepanel/enterpriseserver", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public void UpdateQuota(int itemId, int siteCollectionId, int maxSize, int warningSize) { this.Invoke("UpdateQuota", new object[] { itemId, siteCollectionId, maxSize, warningSize}); } /// <remarks/> public System.IAsyncResult BeginUpdateQuota(int itemId, int siteCollectionId, int maxSize, int warningSize, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UpdateQuota", new object[] { itemId, siteCollectionId, maxSize, warningSize}, callback, asyncState); } /// <remarks/> public void EndUpdateQuota(System.IAsyncResult asyncResult) { this.EndInvoke(asyncResult); } /// <remarks/> public void UpdateQuotaAsync(int itemId, int siteCollectionId, int maxSize, int warningSize) { this.UpdateQuotaAsync(itemId, siteCollectionId, maxSize, warningSize, null); } /// <remarks/> public void UpdateQuotaAsync(int itemId, int siteCollectionId, int maxSize, int warningSize, object userState) { if ((this.UpdateQuotaOperationCompleted == null)) { this.UpdateQuotaOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateQuotaOperationCompleted); } this.InvokeAsync("UpdateQuota", new object[] { itemId, siteCollectionId, maxSize, warningSize}, this.UpdateQuotaOperationCompleted, userState); } private void OnUpdateQuotaOperationCompleted(object arg) { if ((this.UpdateQuotaCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UpdateQuotaCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetSiteCollectionsPagedCompletedEventHandler(object sender, GetSiteCollectionsPagedCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetSiteCollectionsPagedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSiteCollectionsPagedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SharePointSiteCollectionListPaged Result { get { this.RaiseExceptionIfNecessary(); return ((SharePointSiteCollectionListPaged)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetSupportedLanguagesCompletedEventHandler(object sender, GetSupportedLanguagesCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetSupportedLanguagesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSupportedLanguagesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int[] Result { get { this.RaiseExceptionIfNecessary(); return ((int[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetSiteCollectionsCompletedEventHandler(object sender, GetSiteCollectionsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetSiteCollectionsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSiteCollectionsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SharePointSiteCollection[] Result { get { this.RaiseExceptionIfNecessary(); return ((SharePointSiteCollection[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void SetStorageSettingsCompletedEventHandler(object sender, SetStorageSettingsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class SetStorageSettingsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal SetStorageSettingsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetSiteCollectionCompletedEventHandler(object sender, GetSiteCollectionCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetSiteCollectionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSiteCollectionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SharePointSiteCollection Result { get { this.RaiseExceptionIfNecessary(); return ((SharePointSiteCollection)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetSiteCollectionByDomainCompletedEventHandler(object sender, GetSiteCollectionByDomainCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetSiteCollectionByDomainCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSiteCollectionByDomainCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SharePointSiteCollection Result { get { this.RaiseExceptionIfNecessary(); return ((SharePointSiteCollection)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void AddSiteCollectionCompletedEventHandler(object sender, AddSiteCollectionCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class AddSiteCollectionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal AddSiteCollectionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void DeleteSiteCollectionCompletedEventHandler(object sender, DeleteSiteCollectionCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class DeleteSiteCollectionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal DeleteSiteCollectionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void DeleteSiteCollectionsCompletedEventHandler(object sender, DeleteSiteCollectionsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class DeleteSiteCollectionsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal DeleteSiteCollectionsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void BackupSiteCollectionCompletedEventHandler(object sender, BackupSiteCollectionCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class BackupSiteCollectionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal BackupSiteCollectionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public string Result { get { this.RaiseExceptionIfNecessary(); return ((string)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void RestoreSiteCollectionCompletedEventHandler(object sender, RestoreSiteCollectionCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class RestoreSiteCollectionCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal RestoreSiteCollectionCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void GetBackupBinaryChunkCompletedEventHandler(object sender, GetBackupBinaryChunkCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetBackupBinaryChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetBackupBinaryChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public byte[] Result { get { this.RaiseExceptionIfNecessary(); return ((byte[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void AppendBackupBinaryChunkCompletedEventHandler(object sender, AppendBackupBinaryChunkCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class AppendBackupBinaryChunkCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal AppendBackupBinaryChunkCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public string Result { get { this.RaiseExceptionIfNecessary(); return ((string)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void CalculateSharePointSitesDiskSpaceCompletedEventHandler(object sender, CalculateSharePointSitesDiskSpaceCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class CalculateSharePointSitesDiskSpaceCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal CalculateSharePointSitesDiskSpaceCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public SharePointSiteDiskSpace[] Result { get { this.RaiseExceptionIfNecessary(); return ((SharePointSiteDiskSpace[])(this.results[0])); } } /// <remarks/> public int errorCode { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[1])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] public delegate void UpdateQuotaCompletedEventHandler(object sender, System.ComponentModel.AsyncCompletedEventArgs e); }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Providers.Streams.Common; using Orleans.Runtime; using Orleans.Configuration; using RunState = Orleans.Configuration.StreamLifecycleOptions.RunState; using Orleans.Internal; using System.Threading; using Orleans.Streams.Filtering; using Microsoft.Extensions.DependencyInjection; namespace Orleans.Streams { internal class PersistentStreamPullingManager : SystemTarget, IPersistentStreamPullingManager, IStreamQueueBalanceListener { private static readonly TimeSpan QUEUES_PRINT_PERIOD = TimeSpan.FromMinutes(5); private readonly Dictionary<QueueId, PersistentStreamPullingAgent> queuesToAgentsMap; private readonly string streamProviderName; private readonly IStreamPubSub pubSub; private readonly StreamPullingAgentOptions options; private readonly AsyncSerialExecutor nonReentrancyGuarantor; // for non-reentrant execution of queue change notifications. private readonly ILogger logger; private readonly ILoggerFactory loggerFactory; private int latestRingNotificationSequenceNumber; private int latestCommandNumber; private IQueueAdapter queueAdapter; private readonly IQueueAdapterCache queueAdapterCache; private IStreamQueueBalancer queueBalancer; private readonly IStreamFilter streamFilter; private readonly IQueueAdapterFactory adapterFactory; private RunState managerState; private IDisposable queuePrintTimer; private int nextAgentId; private int NumberRunningAgents { get { return queuesToAgentsMap.Count; } } internal PersistentStreamPullingManager( SystemTargetGrainId managerId, string strProviderName, IStreamPubSub streamPubSub, IQueueAdapterFactory adapterFactory, IStreamQueueBalancer streamQueueBalancer, IStreamFilter streamFilter, StreamPullingAgentOptions options, ILoggerFactory loggerFactory, SiloAddress siloAddress, IQueueAdapter queueAdapter) : base(managerId, siloAddress, lowPriority: false, loggerFactory) { if (string.IsNullOrWhiteSpace(strProviderName)) { throw new ArgumentNullException("strProviderName"); } if (streamPubSub == null) { throw new ArgumentNullException("streamPubSub", "StreamPubSub reference should not be null"); } if (streamQueueBalancer == null) { throw new ArgumentNullException("streamQueueBalancer", "IStreamQueueBalancer streamQueueBalancer reference should not be null"); } queuesToAgentsMap = new Dictionary<QueueId, PersistentStreamPullingAgent>(); streamProviderName = strProviderName; pubSub = streamPubSub; this.options = options; nonReentrancyGuarantor = new AsyncSerialExecutor(); latestRingNotificationSequenceNumber = 0; latestCommandNumber = 0; queueBalancer = streamQueueBalancer; this.streamFilter = streamFilter; this.adapterFactory = adapterFactory; this.queueAdapter = queueAdapter ?? throw new ArgumentNullException(nameof(queueAdapter)); queueAdapterCache = adapterFactory.GetQueueAdapterCache(); logger = loggerFactory.CreateLogger($"{GetType().FullName}.{streamProviderName}"); Log(ErrorCode.PersistentStreamPullingManager_01, "Created {0} for Stream Provider {1}.", GetType().Name, streamProviderName); this.loggerFactory = loggerFactory; IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_PULLING_AGENTS, strProviderName), () => queuesToAgentsMap.Count); } public async Task Initialize() { Log(ErrorCode.PersistentStreamPullingManager_02, "Init."); await this.queueBalancer.Initialize(this.adapterFactory.GetStreamQueueMapper()); queueBalancer.SubscribeToQueueDistributionChangeEvents(this); List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList(); Log(ErrorCode.PersistentStreamPullingManager_03, String.Format("Initialize: I am now responsible for {0} queues: {1}.", myQueues.Count, PrintQueues(myQueues))); queuePrintTimer = this.RegisterTimer(AsyncTimerCallback, null, QUEUES_PRINT_PERIOD, QUEUES_PRINT_PERIOD); managerState = RunState.Initialized; } public async Task Stop() { await StopAgents(); if (queuePrintTimer != null) { queuePrintTimer.Dispose(); this.queuePrintTimer = null; } await this.queueBalancer.Shutdown(); this.queueBalancer = null; } public async Task StartAgents() { managerState = RunState.AgentsStarted; List<QueueId> myQueues = queueBalancer.GetMyQueues().ToList(); Log(ErrorCode.PersistentStreamPullingManager_Starting, "Starting agents for {0} queues: {1}", myQueues.Count, PrintQueues(myQueues)); await AddNewQueues(myQueues, true); Log(ErrorCode.PersistentStreamPullingManager_Started, "Started agents."); } public async Task StopAgents() { managerState = RunState.AgentsStopped; List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.ToList(); Log(ErrorCode.PersistentStreamPullingManager_Stopping, "Stopping agents for {0} queues: {1}", queuesToRemove.Count, PrintQueues(queuesToRemove)); await RemoveQueues(queuesToRemove); Log(ErrorCode.PersistentStreamPullingManager_Stopped, "Stopped agents."); } /// <summary> /// Actions to take when the queue distribution changes due to a failure or a join. /// Since this pulling manager is system target and queue distribution change notifications /// are delivered to it as grain method calls, notifications are not reentrant. To simplify /// notification handling we execute them serially, in a non-reentrant way. We also suppress /// and don't execute an older notification if a newer one was already delivered. /// </summary> public Task QueueDistributionChangeNotification() { return this.ScheduleTask(() => this.HandleQueueDistributionChangeNotification()); } public Task HandleQueueDistributionChangeNotification() { latestRingNotificationSequenceNumber++; int notificationSeqNumber = latestRingNotificationSequenceNumber; Log(ErrorCode.PersistentStreamPullingManager_04, "Got QueueChangeNotification number {0} from the queue balancer. managerState = {1}", notificationSeqNumber, managerState); if (managerState == RunState.AgentsStopped) { return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them. } return nonReentrancyGuarantor.AddNext(() => { // skip execution of an older/previous notification since already got a newer range update notification. if (notificationSeqNumber < latestRingNotificationSequenceNumber) { Log(ErrorCode.PersistentStreamPullingManager_05, "Skipping execution of QueueChangeNotification number {0} from the queue allocator since already received a later notification " + "(already have notification number {1}).", notificationSeqNumber, latestRingNotificationSequenceNumber); return Task.CompletedTask; } if (managerState == RunState.AgentsStopped) { return Task.CompletedTask; // if agents not running, no need to rebalance the queues among them. } return QueueDistributionChangeNotification(notificationSeqNumber); }); } private async Task QueueDistributionChangeNotification(int notificationSeqNumber) { HashSet<QueueId> currentQueues = queueBalancer.GetMyQueues().ToSet(); Log(ErrorCode.PersistentStreamPullingManager_06, "Executing QueueChangeNotification number {0}. Queue balancer says I should now own {1} queues: {2}", notificationSeqNumber, currentQueues.Count, PrintQueues(currentQueues)); try { Task t1 = AddNewQueues(currentQueues, false); List<QueueId> queuesToRemove = queuesToAgentsMap.Keys.Where(queueId => !currentQueues.Contains(queueId)).ToList(); Task t2 = RemoveQueues(queuesToRemove); await Task.WhenAll(t1, t2); } finally { Log(ErrorCode.PersistentStreamPullingManager_16, "Done Executing QueueChangeNotification number {0}. I now own {1} queues: {2}", notificationSeqNumber, NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys)); } } /// <summary> /// Take responsibility for a set of new queues that were assigned to me via a new range. /// We first create one pulling agent for every new queue and store them in our internal data structure, then try to initialize the agents. /// ERROR HANDLING: /// The responsibility to handle initialization and shutdown failures is inside the Agents code. /// The manager will call Initialize once and log an error. It will not call initialize again and will assume initialization has succeeded. /// Same applies to shutdown. /// </summary> /// <param name="myQueues"></param> /// <param name="failOnInit"></param> /// <returns></returns> private async Task AddNewQueues(IEnumerable<QueueId> myQueues, bool failOnInit) { // Create agents for queues in range that we don't yet have. // First create them and store in local queuesToAgentsMap. // Only after that Initialize them all. var agents = new List<PersistentStreamPullingAgent>(); foreach (var queueId in myQueues) { if (queuesToAgentsMap.ContainsKey(queueId)) continue; try { var agentIdNumber = Interlocked.Increment(ref nextAgentId); var agentId = SystemTargetGrainId.Create(Constants.StreamPullingAgentType, this.Silo, $"{streamProviderName}_{agentIdNumber}_{queueId.ToStringWithHashCode()}"); IStreamFailureHandler deliveryFailureHandler = await adapterFactory.GetDeliveryFailureHandler(queueId); var agent = new PersistentStreamPullingAgent(agentId, streamProviderName, this.loggerFactory, pubSub, streamFilter, queueId, this.options, this.Silo, queueAdapter, queueAdapterCache, deliveryFailureHandler); this.ActivationServices.GetRequiredService<Catalog>().RegisterSystemTarget(agent); queuesToAgentsMap.Add(queueId, agent); agents.Add(agent); } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingManager_07, "Exception while creating PersistentStreamPullingAgent.", exc); // What should we do? This error is not recoverable and considered a bug. But we don't want to bring the silo down. // If this is when silo is starting and agent is initializing, fail the silo startup. Otherwise, just swallow to limit impact on other receivers. if (failOnInit) throw; } } try { var initTasks = new List<Task>(); foreach (var agent in agents) { initTasks.Add(InitAgent(agent)); } await Task.WhenAll(initTasks); } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Initialize. No need to log again. } if (agents.Count > 0) { Log(ErrorCode.PersistentStreamPullingManager_08, "Added {0} new queues: {1}. Now own total of {2} queues: {3}", agents.Count, Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()), NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys)); } } private async Task InitAgent(PersistentStreamPullingAgent agent) { // Init the agent only after it was registered locally. var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>(); // Need to call it as a grain reference. var task = agentGrainRef.Initialize(); await task.LogException(logger, ErrorCode.PersistentStreamPullingManager_09, String.Format("PersistentStreamPullingAgent {0} failed to Initialize.", agent.QueueId)); } private async Task RemoveQueues(List<QueueId> queuesToRemove) { if (queuesToRemove.Count == 0) { return; } // Stop the agents that for queues that are not in my range anymore. var agents = new List<PersistentStreamPullingAgent>(queuesToRemove.Count); Log(ErrorCode.PersistentStreamPullingManager_10, "About to remove {0} agents from my responsibility: {1}", queuesToRemove.Count, Utils.EnumerableToString(queuesToRemove, q => q.ToString())); var removeTasks = new List<Task>(); foreach (var queueId in queuesToRemove) { PersistentStreamPullingAgent agent; if (!queuesToAgentsMap.TryGetValue(queueId, out agent)) continue; agents.Add(agent); queuesToAgentsMap.Remove(queueId); var agentGrainRef = agent.AsReference<IPersistentStreamPullingAgent>(); var task = OrleansTaskExtentions.SafeExecute(agentGrainRef.Shutdown); task = task.LogException(logger, ErrorCode.PersistentStreamPullingManager_11, String.Format("PersistentStreamPullingAgent {0} failed to Shutdown.", agent.QueueId)); removeTasks.Add(task); } try { await Task.WhenAll(removeTasks); } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Shutdown. No need to log again. } var catalog = ActivationServices.GetRequiredService<Catalog>(); foreach (var agent in agents) { try { catalog.UnregisterSystemTarget(agent); } catch (Exception exc) { Log(ErrorCode.PersistentStreamPullingManager_12, "Exception while UnRegisterSystemTarget of PersistentStreamPullingAgent {0}. Ignoring. Exc.Message = {1}.", ((ISystemTargetBase)agent).GrainId, exc.Message); } } if (agents.Count > 0) { Log(ErrorCode.PersistentStreamPullingManager_10, "Removed {0} queues: {1}. Now own total of {2} queues: {3}", agents.Count, Utils.EnumerableToString(agents, agent => agent.QueueId.ToString()), NumberRunningAgents, PrintQueues(queuesToAgentsMap.Keys)); } } public async Task<object> ExecuteCommand(PersistentStreamProviderCommand command, object arg) { latestCommandNumber++; int commandSeqNumber = latestCommandNumber; try { Log(ErrorCode.PersistentStreamPullingManager_13, String.Format("Got command {0}{1}: commandSeqNumber = {2}, managerState = {3}.", command, arg != null ? " with arg " + arg : String.Empty, commandSeqNumber, managerState)); switch (command) { case PersistentStreamProviderCommand.StartAgents: case PersistentStreamProviderCommand.StopAgents: await QueueCommandForExecution(command, commandSeqNumber); return null; case PersistentStreamProviderCommand.GetAgentsState: return managerState; case PersistentStreamProviderCommand.GetNumberRunningAgents: return NumberRunningAgents; default: throw new OrleansException(String.Format("PullingAgentManager does not support command {0}.", command)); } } finally { Log(ErrorCode.PersistentStreamPullingManager_15, String.Format("Done executing command {0}: commandSeqNumber = {1}, managerState = {2}, num running agents = {3}.", command, commandSeqNumber, managerState, NumberRunningAgents)); } } // Start and Stop commands are composite commands that take multiple turns. // Ee don't wnat them to interleave with other concurrent Start/Stop commands, as well as not with QueueDistributionChangeNotification. // Therefore, we serialize them all via the same nonReentrancyGuarantor. private Task QueueCommandForExecution(PersistentStreamProviderCommand command, int commandSeqNumber) { return nonReentrancyGuarantor.AddNext(() => { // skip execution of an older/previous command since already got a newer command. if (commandSeqNumber < latestCommandNumber) { Log(ErrorCode.PersistentStreamPullingManager_15, "Skipping execution of command number {0} since already received a later command (already have command number {1}).", commandSeqNumber, latestCommandNumber); return Task.CompletedTask; } switch (command) { case PersistentStreamProviderCommand.StartAgents: return StartAgents(); case PersistentStreamProviderCommand.StopAgents: return StopAgents(); default: throw new OrleansException(String.Format("PullingAgentManager got unsupported command {0}", command)); } }); } private static string PrintQueues(ICollection<QueueId> myQueues) { return Utils.EnumerableToString(myQueues, q => q.ToString()); } // Just print our queue assignment periodicaly, for easy monitoring. private Task AsyncTimerCallback(object state) { Log(ErrorCode.PersistentStreamPullingManager_PeriodicPrint, "I am responsible for a total of {0} queues on stream provider {1}: {2}.", NumberRunningAgents, streamProviderName, PrintQueues(queuesToAgentsMap.Keys)); return Task.CompletedTask; } private void Log(ErrorCode logCode, string format, params object[] args) { logger.Info(logCode, format, args); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** ** Purpose: Implements a generic, dynamically sized list as an ** array. ** ** ===========================================================*/ namespace System.Collections.Generic { using System; using System.Runtime; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Collections.ObjectModel; using System.Security.Permissions; // Implements a variable-size List that uses an array of objects to store the // elements. A List has a capacity, which is the allocated length // of the internal array. As elements are added to a List, the capacity // of the List is automatically increased as required by reallocating the // internal array. // [DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T> { private const int _defaultCapacity = 4; private T[] _items; [ContractPublicPropertyName("Count")] private int _size; private int _version; [NonSerialized] private Object _syncRoot; static readonly T[] _emptyArray = new T[0]; // Constructs a List. The list is initially empty and has a capacity // of zero. Upon adding the first element to the list the capacity is // increased to 16, and then increased in multiples of two as required. public List() { _items = _emptyArray; } // Constructs a List with a given initial capacity. The list is // initially empty, but will have room for the given number of elements // before any reallocations are required. // public List(int capacity) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); Contract.EndContractBlock(); if (capacity == 0) _items = _emptyArray; else _items = new T[capacity]; } // Constructs a List, copying the contents of the given collection. The // size and capacity of the new list will both be equal to the size of the // given collection. // public List(IEnumerable<T> collection) { if (collection==null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if( c != null) { int count = c.Count; if (count == 0) { _items = _emptyArray; } else { _items = new T[count]; c.CopyTo(_items, 0); _size = count; } } else { _size = 0; _items = _emptyArray; // This enumerable could be empty. Let Add allocate a new array, if needed. // Note it will also go to _defaultCapacity first, not 1, then 2, etc. using(IEnumerator<T> en = collection.GetEnumerator()) { while(en.MoveNext()) { Add(en.Current); } } } } // Gets and sets the capacity of this list. The capacity is the size of // the internal array used to hold items. When set, the internal // array of the list is reallocated to the given capacity. // public int Capacity { get { Contract.Ensures(Contract.Result<int>() >= 0); return _items.Length; } set { if (value < _size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value, ExceptionResource.ArgumentOutOfRange_SmallCapacity); } Contract.EndContractBlock(); if (value != _items.Length) { if (value > 0) { T[] newItems = new T[value]; if (_size > 0) { Array.Copy(_items, 0, newItems, 0, _size); } _items = newItems; } else { _items = _emptyArray; } } } } // Read-only property describing how many elements are in the List. public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return _size; } } bool System.Collections.IList.IsFixedSize { get { return false; } } // Is this List read-only? bool ICollection<T>.IsReadOnly { get { return false; } } bool System.Collections.IList.IsReadOnly { get { return false; } } // Is this List synchronized (thread-safe)? bool System.Collections.ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. Object System.Collections.ICollection.SyncRoot { get { if( _syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Sets or Gets the element at the given index. // public T this[int index] { get { // Following trick can reduce the range check by one if ((uint) index >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } Contract.EndContractBlock(); return _items[index]; } set { if ((uint) index >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } Contract.EndContractBlock(); _items[index] = value; _version++; } } private static bool IsCompatibleObject(object value) { // Non-null values are fine. Only accept nulls if T is a class or Nullable<U>. // Note that default(T) is not equal to null for value types except when T is Nullable<U>. return ((value is T) || (value == null && default(T) == null)); } Object System.Collections.IList.this[int index] { get { return this[index]; } set { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(value, ExceptionArgument.value); try { this[index] = (T)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(T)); } } } // Adds the given object to the end of this list. The size of the list is // increased by one. If required, the capacity of the list is doubled // before adding the new element. // public void Add(T item) { if (_size == _items.Length) EnsureCapacity(_size + 1); _items[_size++] = item; _version++; } int System.Collections.IList.Add(Object item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item); try { Add((T) item); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T)); } return Count - 1; } // Adds the elements of the given collection to the end of this list. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. // public void AddRange(IEnumerable<T> collection) { Contract.Ensures(Count >= Contract.OldValue(Count)); InsertRange(_size, collection); } public ReadOnlyCollection<T> AsReadOnly() { Contract.Ensures(Contract.Result<ReadOnlyCollection<T>>() != null); return new ReadOnlyCollection<T>(this); } // Searches a section of the list for a given element using a binary search // algorithm. Elements of the list are compared to the search value using // the given IComparer interface. If comparer is null, elements of // the list are compared to the search value using the IComparable // interface, which in that case must be implemented by all elements of the // list and the given search value. This method assumes that the given // section of the list is already sorted; if this is not the case, the // result will be incorrect. // // The method returns the index of the given value in the list. If the // list does not contain the given value, the method returns a negative // integer. The bitwise complement operator (~) can be applied to a // negative result to produce the index of the first element (if any) that // is larger than the given search value. This is also the index at which // the search value should be inserted into the list in order for the list // to remain sorted. // // The method uses the Array.BinarySearch method to perform the // search. // public int BinarySearch(int index, int count, T item, IComparer<T> comparer) { if (index < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.Ensures(Contract.Result<int>() <= index + count); Contract.EndContractBlock(); return Array.BinarySearch<T>(_items, index, count, item, comparer); } public int BinarySearch(T item) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, null); } public int BinarySearch(T item, IComparer<T> comparer) { Contract.Ensures(Contract.Result<int>() <= Count); return BinarySearch(0, Count, item, comparer); } // Clears the contents of List. public void Clear() { if (_size > 0) { Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references. _size = 0; } _version++; } // Contains returns true if the specified element is in the List. // It does a linear, O(n) search. Equality is determined by calling // item.Equals(). // public bool Contains(T item) { if ((Object) item == null) { for(int i=0; i<_size; i++) if ((Object) _items[i] == null) return true; return false; } else { EqualityComparer<T> c = EqualityComparer<T>.Default; for(int i=0; i<_size; i++) { if (c.Equals(_items[i], item)) return true; } return false; } } bool System.Collections.IList.Contains(Object item) { if(IsCompatibleObject(item)) { return Contains((T) item); } return false; } public List<TOutput> ConvertAll<TOutput>(Converter<T,TOutput> converter) { if( converter == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.converter); } Contract.EndContractBlock(); List<TOutput> list = new List<TOutput>(_size); for( int i = 0; i< _size; i++) { list._items[i] = converter(_items[i]); } list._size = _size; return list; } // Copies this List into array, which must be of a // compatible array type. // public void CopyTo(T[] array) { CopyTo(array, 0); } // Copies this List into array, which must be of a // compatible array type. // void System.Collections.ICollection.CopyTo(Array array, int arrayIndex) { if ((array != null) && (array.Rank != 1)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } Contract.EndContractBlock(); try { // Array.Copy will check for NULL. Array.Copy(_items, 0, array, arrayIndex, _size); } catch(ArrayTypeMismatchException){ ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } // Copies a section of this list to the given array at the given index. // // The method uses the Array.Copy method to copy the elements. // public void CopyTo(int index, T[] array, int arrayIndex, int count) { if (_size - index < count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } Contract.EndContractBlock(); // Delegate rest of error checking to Array.Copy. Array.Copy(_items, index, array, arrayIndex, count); } public void CopyTo(T[] array, int arrayIndex) { // Delegate rest of error checking to Array.Copy. Array.Copy(_items, 0, array, arrayIndex, _size); } // Ensures that the capacity of this list is at least the given minimum // value. If the currect capacity of the list is less than min, the // capacity is increased to twice the current capacity or to min, // whichever is larger. private void EnsureCapacity(int min) { if (_items.Length < min) { int newCapacity = _items.Length == 0? _defaultCapacity : _items.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > Array.MaxArrayLength) newCapacity = Array.MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } } public bool Exists(Predicate<T> match) { return FindIndex(match) != -1; } public T Find(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); for(int i = 0 ; i < _size; i++) { if(match(_items[i])) { return _items[i]; } } return default(T); } public List<T> FindAll(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); List<T> list = new List<T>(); for(int i = 0 ; i < _size; i++) { if(match(_items[i])) { list.Add(_items[i]); } } return list; } public int FindIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindIndex(0, _size, match); } public int FindIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + Count); return FindIndex(startIndex, _size - startIndex, match); } public int FindIndex(int startIndex, int count, Predicate<T> match) { if( (uint)startIndex > (uint)_size ) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } if (count < 0 || startIndex > _size - count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < startIndex + count); Contract.EndContractBlock(); int endIndex = startIndex + count; for( int i = startIndex; i < endIndex; i++) { if( match(_items[i])) return i; } return -1; } public T FindLast(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); for(int i = _size - 1 ; i >= 0; i--) { if(match(_items[i])) { return _items[i]; } } return default(T); } public int FindLastIndex(Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return FindLastIndex(_size - 1, _size, match); } public int FindLastIndex(int startIndex, Predicate<T> match) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); return FindLastIndex(startIndex, startIndex + 1, match); } public int FindLastIndex(int startIndex, int count, Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() <= startIndex); Contract.EndContractBlock(); if(_size == 0) { // Special case for 0 length List if( startIndex != -1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } } else { // Make sure we're not out of range if ( (uint)startIndex >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } } // 2nd have of this also catches when startIndex == MAXINT, so MAXINT - 0 + 1 == -1, which is < 0. if (count < 0 || startIndex - count + 1 < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } int endIndex = startIndex - count; for( int i = startIndex; i > endIndex; i--) { if( match(_items[i])) { return i; } } return -1; } public void ForEach(Action<T> action) { if( action == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); int version = _version; for(int i = 0 ; i < _size; i++) { if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) { break; } action(_items[i]); } if (version != _version && BinaryCompatibility.TargetsAtLeast_Desktop_V4_5) ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } // Returns an enumerator for this list with the given // permission for removal of elements. If modifications made to the list // while an enumeration is in progress, the MoveNext and // GetObject methods of the enumerator will throw an exception. // public Enumerator GetEnumerator() { return new Enumerator(this); } /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } public List<T> GetRange(int index, int count) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); } Contract.Ensures(Contract.Result<List<T>>() != null); Contract.EndContractBlock(); List<T> list = new List<T>(count); Array.Copy(_items, index, list._items, 0, count); list._size = count; return list; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards from beginning to end. // The elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); return Array.IndexOf(_items, item, 0, _size); } int System.Collections.IList.IndexOf(Object item) { if(IsCompatibleObject(item)) { return IndexOf((T)item); } return -1; } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and ending at count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item, int index) { if (index > _size) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, _size - index); } // Returns the index of the first occurrence of a given value in a range of // this list. The list is searched forwards, starting at index // index and upto count number of elements. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.IndexOf method to perform the // search. // public int IndexOf(T item, int index, int count) { if (index > _size) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); if (count <0 || index > _size - count) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); Contract.EndContractBlock(); return Array.IndexOf(_items, item, index, count); } // Inserts an element into this list at a given index. The size of the list // is increased by one. If required, the capacity of the list is doubled // before inserting the new element. // public void Insert(int index, T item) { // Note that insertions at the end are legal. if ((uint) index > (uint)_size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_ListInsert); } Contract.EndContractBlock(); if (_size == _items.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(_items, index, _items, index + 1, _size - index); } _items[index] = item; _size++; _version++; } void System.Collections.IList.Insert(int index, Object item) { ThrowHelper.IfNullAndNullsAreIllegalThenThrow<T>(item, ExceptionArgument.item); try { Insert(index, (T) item); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(item, typeof(T)); } } // Inserts the elements of the given collection at a given index. If // required, the capacity of the list is increased to twice the previous // capacity or the new size, whichever is larger. Ranges may be added // to the end of the list by setting index to the List's size. // public void InsertRange(int index, IEnumerable<T> collection) { if (collection==null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection); } if ((uint)index > (uint)_size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } Contract.EndContractBlock(); ICollection<T> c = collection as ICollection<T>; if( c != null ) { // if collection is ICollection<T> int count = c.Count; if (count > 0) { EnsureCapacity(_size + count); if (index < _size) { Array.Copy(_items, index, _items, index + count, _size - index); } // If we're inserting a List into itself, we want to be able to deal with that. if (this == c) { // Copy first part of _items to insert location Array.Copy(_items, 0, _items, index, index); // Copy last part of _items back to inserted location Array.Copy(_items, index+count, _items, index*2, _size-index); } else { T[] itemsToInsert = new T[count]; c.CopyTo(itemsToInsert, 0); itemsToInsert.CopyTo(_items, index); } _size += count; } } else { using(IEnumerator<T> en = collection.GetEnumerator()) { while(en.MoveNext()) { Insert(index++, en.Current); } } } _version++; } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at the end // and ending at the first element in the list. The elements of the list // are compared to the given value using the Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf(T item) { Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(Contract.Result<int>() < Count); if (_size == 0) { // Special case for empty list return -1; } else { return LastIndexOf(item, _size - 1, _size); } } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and ending at the first element in the list. The // elements of the list are compared to the given value using the // Object.Equals method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf(T item, int index) { if (index >= _size) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); return LastIndexOf(item, index, index + 1); } // Returns the index of the last occurrence of a given value in a range of // this list. The list is searched backwards, starting at index // index and upto count elements. The elements of // the list are compared to the given value using the Object.Equals // method. // // This method uses the Array.LastIndexOf method to perform the // search. // public int LastIndexOf(T item, int index, int count) { if ((Count != 0) && (index < 0)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if ((Count !=0) && (count < 0)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } Contract.Ensures(Contract.Result<int>() >= -1); Contract.Ensures(((Count == 0) && (Contract.Result<int>() == -1)) || ((Count > 0) && (Contract.Result<int>() <= index))); Contract.EndContractBlock(); if (_size == 0) { // Special case for empty list return -1; } if (index >= _size) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); } if (count > index + 1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_BiggerThanCollection); } return Array.LastIndexOf(_items, item, index, count); } // Removes the element at the given index. The size of the list is // decreased by one. // public bool Remove(T item) { int index = IndexOf(item); if (index >= 0) { RemoveAt(index); return true; } return false; } void System.Collections.IList.Remove(Object item) { if(IsCompatibleObject(item)) { Remove((T) item); } } // This method removes all items which matches the predicate. // The complexity is O(n). public int RemoveAll(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(Count)); Contract.EndContractBlock(); int freeIndex = 0; // the first free slot in items array // Find the first item which needs to be removed. while( freeIndex < _size && !match(_items[freeIndex])) freeIndex++; if( freeIndex >= _size) return 0; int current = freeIndex + 1; while( current < _size) { // Find the first item which needs to be kept. while( current < _size && match(_items[current])) current++; if( current < _size) { // copy item to the free slot. _items[freeIndex++] = _items[current++]; } } Array.Clear(_items, freeIndex, _size - freeIndex); int result = _size - freeIndex; _size = freeIndex; _version++; return result; } // Removes the element at the given index. The size of the list is // decreased by one. // public void RemoveAt(int index) { if ((uint)index >= (uint)_size) { ThrowHelper.ThrowArgumentOutOfRangeException(); } Contract.EndContractBlock(); _size--; if (index < _size) { Array.Copy(_items, index + 1, _items, index, _size - index); } _items[_size] = default(T); _version++; } // Removes a range of elements from this list. // public void RemoveRange(int index, int count) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); if (count > 0) { int i = _size; _size -= count; if (index < _size) { Array.Copy(_items, index + count, _items, index, _size - index); } Array.Clear(_items, _size, count); _version++; } } // Reverses the elements in this list. public void Reverse() { Reverse(0, Count); } // Reverses the elements in a range of this list. Following a call to this // method, an element in the range given by index and count // which was previously located at index i will now be located at // index index + (index + count - i - 1). // public void Reverse(int index, int count) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); // The non-generic Array.Reverse is not used because it does not perform // well for non-primitive value types. // If/when a generic Array.Reverse<T> becomes available, the below code // can be deleted and replaced with a call to Array.Reverse<T>. int i = index; int j = index + count - 1; T[] array = _items; while (i < j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; i++; j--; } _version++; } // Sorts the elements in this list. Uses the default comparer and // Array.Sort. public void Sort() { Sort(0, Count, null); } // Sorts the elements in this list. Uses Array.Sort with the // provided comparer. public void Sort(IComparer<T> comparer) { Sort(0, Count, comparer); } // Sorts the elements in a section of this list. The sort compares the // elements to each other using the given IComparer interface. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented by all // elements of the list. // // This method uses the Array.Sort method to sort the elements. // public void Sort(int index, int count, IComparer<T> comparer) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (_size - index < count) ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidOffLen); Contract.EndContractBlock(); Array.Sort<T>(_items, index, count, comparer); _version++; } public void Sort(Comparison<T> comparison) { if( comparison == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); if( _size > 0) { IComparer<T> comparer = new Array.FunctorComparer<T>(comparison); Array.Sort(_items, 0, _size, comparer); } } // ToArray returns a new Object array containing the contents of the List. // This requires copying the List, which is an O(n) operation. public T[] ToArray() { Contract.Ensures(Contract.Result<T[]>() != null); Contract.Ensures(Contract.Result<T[]>().Length == Count); T[] array = new T[_size]; Array.Copy(_items, 0, array, 0, _size); return array; } // Sets the capacity of this list to the size of the list. This method can // be used to minimize a list's memory overhead once it is known that no // new elements will be added to the list. To completely clear a list and // release all memory referenced by the list, execute the following // statements: // // list.Clear(); // list.TrimExcess(); // public void TrimExcess() { int threshold = (int)(((double)_items.Length) * 0.9); if( _size < threshold ) { Capacity = _size; } } public bool TrueForAll(Predicate<T> match) { if( match == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } Contract.EndContractBlock(); for(int i = 0 ; i < _size; i++) { if( !match(_items[i])) { return false; } } return true; } internal static IList<T> Synchronized(List<T> list) { return new SynchronizedList(list); } [Serializable()] internal class SynchronizedList : IList<T> { private List<T> _list; private Object _root; internal SynchronizedList(List<T> list) { _list = list; _root = ((System.Collections.ICollection)list).SyncRoot; } public int Count { get { lock (_root) { return _list.Count; } } } public bool IsReadOnly { get { return ((ICollection<T>)_list).IsReadOnly; } } public void Add(T item) { lock (_root) { _list.Add(item); } } public void Clear() { lock (_root) { _list.Clear(); } } public bool Contains(T item) { lock (_root) { return _list.Contains(item); } } public void CopyTo(T[] array, int arrayIndex) { lock (_root) { _list.CopyTo(array, arrayIndex); } } public bool Remove(T item) { lock (_root) { return _list.Remove(item); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { lock (_root) { return _list.GetEnumerator(); } } IEnumerator<T> IEnumerable<T>.GetEnumerator() { lock (_root) { return ((IEnumerable<T>)_list).GetEnumerator(); } } public T this[int index] { get { lock(_root) { return _list[index]; } } set { lock(_root) { _list[index] = value; } } } public int IndexOf(T item) { lock (_root) { return _list.IndexOf(item); } } public void Insert(int index, T item) { lock (_root) { _list.Insert(index, item); } } public void RemoveAt(int index) { lock (_root) { _list.RemoveAt(index); } } } [Serializable] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private List<T> list; private int index; private int version; private T current; internal Enumerator(List<T> list) { this.list = list; index = 0; version = list._version; current = default(T); } public void Dispose() { } public bool MoveNext() { List<T> localList = list; if (version == localList._version && ((uint)index < (uint)localList._size)) { current = localList._items[index]; index++; return true; } return MoveNextRare(); } private bool MoveNextRare() { if (version != list._version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = list._size + 1; current = default(T); return false; } public T Current { get { return current; } } Object System.Collections.IEnumerator.Current { get { if( index == 0 || index == list._size + 1) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return Current; } } void System.Collections.IEnumerator.Reset() { if (version != list._version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; current = default(T); } } } }
// 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. // // .NET SIMD to solve Burgers' equation // // Benchmark based on // https://github.com/taumuon/SIMD-Vectorisation-Burgers-Equation-CSharp // http://www.taumuon.co.uk/2014/10/net-simd-to-solve-burgers-equation.html using Microsoft.Xunit.Performance; using System; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; [assembly: OptimizeForBenchmarks] [assembly: MeasureInstructionsRetired] public class Burgers { private static double BurgersAnalytical(double t, double x, double nu) { return -2 * nu * (-(-8 * t + 2 * x) * Math.Exp(-Math.Pow((-4 * t + x), 2) / (4 * nu * (t + 1))) / (4 * nu * (t + 1)) - (-8 * t + 2 * x - 12.5663706143592) * Math.Exp(-Math.Pow(-4 * t + x - 6.28318530717959, 2) / (4 * nu * (t + 1))) / (4 * nu * (t + 1))) / (Math.Exp(-Math.Pow(-4 * t + x - 6.28318530717959, 2) / (4 * nu * (t + 1))) + Math.Exp(-Math.Pow(-4 * t + x, 2) / (4 * nu * (t + 1)))) + 4; } private static double[] linspace(double first, double last, int num) { var step = (last - first) / (double)num; return Enumerable.Range(0, num).Select(v => (v * step) + first).ToArray(); } private static double[] GetAnalytical(double[] x, double t, double nu) { double[] u = new double[x.Length]; for (int i = 0; i < x.Length; ++i) { u[i] = BurgersAnalytical(t, x[i], nu); } return u; } private static double[] GetCalculated0(int nt, int nx, double dx, double dt, double nu, double[] initial) { double[] u = new double[nx]; Array.Copy(initial, u, u.Length); for (int tStep = 0; tStep < nt; tStep++) { double[] un = new double[nx]; Array.Copy(u, un, u.Length); for (int i = 1; i < nx - 1; i++) { u[i] = un[i] - un[i] * dt / dx * (un[i] - un[i - 1]) + Math.Pow(nu * dt / dx, 2.0) * (un[i + 1] - 2 * un[i] + un[i - 1]); } u[0] = un[0] - un[0] * dt / dx * (un[0] - un[nx - 1]) + Math.Pow(nu * dt / dx, 2.0) * (un[1] - 2 * un[0] + un[nx - 1]); u[nx - 1] = un[nx - 1] - un[nx - 1] * dt / dx * (un[nx - 1] - un[nx - 2]) + Math.Pow(nu * dt / dx, 2.0) * (un[0] - 2 * un[nx - 1] + un[nx - 2]); } return u; } // Reduce new array allocation and copying, ping-pong between them private static double[] GetCalculated1(int nt, int nx, double dx, double dt, double nu, double[] initial) { double[] u = new double[nx]; double[] un = new double[nx]; Array.Copy(initial, un, un.Length); for (int tStep = 0; tStep < nt; tStep++) { for (int i = 1; i < nx - 1; i++) { u[i] = un[i] - un[i] * dt / dx * (un[i] - un[i - 1]) + Math.Pow(nu * dt / dx, 2.0) * (un[i + 1] - 2 * un[i] + un[i - 1]); } u[0] = un[0] - un[0] * dt / dx * (un[0] - un[nx - 1]) + Math.Pow(nu * dt / dx, 2.0) * (un[1] - 2 * un[0] + un[nx - 1]); u[nx - 1] = un[nx - 1] - un[nx - 1] * dt / dx * (un[nx - 1] - un[nx - 2]) + Math.Pow(nu * dt / dx, 2.0) * (un[0] - 2 * un[nx - 1] + un[nx - 2]); double[] swap = u; u = un; un = swap; } return un; } // Pull calculation of (nu * dt / dx)^2 out into a variable private static double[] GetCalculated2(int nt, int nx, double dx, double dt, double nu, double[] initial) { double[] u = new double[nx]; double[] un = new double[nx]; Array.Copy(initial, un, un.Length); double factor = Math.Pow(nu * dt / dx, 2.0); for (int tStep = 0; tStep < nt; tStep++) { for (int i = 1; i < nx - 1; i++) { u[i] = un[i] - un[i] * dt / dx * (un[i] - un[i - 1]) + factor * (un[i + 1] - 2 * un[i] + un[i - 1]); } u[0] = un[0] - un[0] * dt / dx * (un[0] - un[nx - 1]) + factor * (un[1] - 2 * un[0] + un[nx - 1]); u[nx - 1] = un[nx - 1] - un[nx - 1] * dt / dx * (un[nx - 1] - un[nx - 2]) + factor * (un[0] - 2 * un[nx - 1] + un[nx - 2]); double[] swap = u; u = un; un = swap; } return un; } // SIMD private static double[] GetCalculated3(int nt, int nx, double dx, double dt, double nu, double[] initial) { var nx2 = nx + (Vector<double>.Count - (nx % Vector<double>.Count)); double[] u = new double[nx2]; double[] un = new double[nx2]; Array.Copy(initial, un, initial.Length); double factor = Math.Pow(nu * dt / dx, 2.0); for (int tStep = 0; tStep < nt; tStep++) { for (int i = 1; i < nx2 - Vector<double>.Count + 1; i += Vector<double>.Count) { var vectorIn0 = new Vector<double>(un, i); var vectorInPrev = new Vector<double>(un, i - 1); var vectorInNext = new Vector<double>(un, i + 1); var vectorOut = vectorIn0 - vectorIn0 * (dt / dx) * (vectorIn0 - vectorInPrev) + factor * (vectorInNext - 2.0 * vectorIn0 + vectorInPrev); vectorOut.CopyTo(u, i); } u[0] = un[0] - un[0] * dt / dx * (un[0] - un[nx - 1]) + factor * (un[1] - 2 * un[0] + un[nx - 1]); u[nx - 1] = un[nx - 1] - un[nx - 1] * dt / dx * (un[nx - 1] - un[nx - 2]) + factor * (un[0] - 2 * un[nx - 1] + un[nx - 2]); double[] swap = u; u = un; un = swap; } return un; } public static int Main() { if (!Vector.IsHardwareAccelerated) { Console.WriteLine("Not hardware accelerated!"); } else { Console.WriteLine("Vector<double>.Length: " + Vector<double>.Count); } int nx = 10001; #if DEBUG int nt = 10; #else int nt = 10000; #endif double dx = 2.0 * Math.PI / (nx - 1.0); double nu = 0.07; double dt = dx * nu; double[] x = linspace(0.0, 2.0 * Math.PI, nx); double[] initial = GetAnalytical(x, 0.0, nu); // Warmup GetCalculated0(1, nx, dx, dt, nu, initial); GetCalculated1(1, nx, dx, dt, nu, initial); GetCalculated2(1, nx, dx, dt, nu, initial); GetCalculated3(1, nx, dx, dt, nu, initial); double[][] results = new double[4][]; var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); results[0] = GetCalculated0(nt, nx, dx, dt, nu, initial); stopwatch.Stop(); Console.WriteLine("Baseline: " + stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start(); results[1] = GetCalculated1(nt, nx, dx, dt, nu, initial); stopwatch.Stop(); Console.WriteLine("Reduce copy: " + stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start(); results[2] = GetCalculated2(nt, nx, dx, dt, nu, initial); stopwatch.Stop(); Console.WriteLine("CSE of Math.Pow: " + stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start(); results[3] = GetCalculated3(nt, nx, dx, dt, nu, initial); stopwatch.Stop(); Console.WriteLine("SIMD: " + stopwatch.ElapsedMilliseconds); stopwatch.Reset(); for (int i = 0; i < x.Length; i += 33) { double expected = results[0][i]; for (int j = 1; j < results.Length; j++) { bool valid = Math.Abs(expected - results[j][i]) < 1e-4; if (!valid) { Console.WriteLine("Failed to validate"); return -1; } } } return 100; } static volatile object VolatileObject; [MethodImpl(MethodImplOptions.NoInlining)] static void Escape(object obj) { VolatileObject = obj; } [Benchmark] public static void Test0() { int nx = 10001; int nt = 10000; double dx = 2.0 * Math.PI / (nx - 1.0); double nu = 0.07; double dt = dx * nu; double[] x = linspace(0.0, 2.0 * Math.PI, nx); double[] initial = GetAnalytical(x, 0.0, nu); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { double[] results = GetCalculated0(nt, nx, dx, dt, nu, initial); Escape(results); } } } [Benchmark] public static void Test1() { int nx = 10001; int nt = 10000; double dx = 2.0 * Math.PI / (nx - 1.0); double nu = 0.07; double dt = dx * nu; double[] x = linspace(0.0, 2.0 * Math.PI, nx); double[] initial = GetAnalytical(x, 0.0, nu); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { double[] results = GetCalculated1(nt, nx, dx, dt, nu, initial); Escape(results); } } } [Benchmark] public static void Test2() { int nx = 10001; int nt = 10000; double dx = 2.0 * Math.PI / (nx - 1.0); double nu = 0.07; double dt = dx * nu; double[] x = linspace(0.0, 2.0 * Math.PI, nx); double[] initial = GetAnalytical(x, 0.0, nu); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { double[] results = GetCalculated2(nt, nx, dx, dt, nu, initial); Escape(results); } } } [Benchmark] public static void Test3() { // Make SIMD version work a bit harder.... int nx = 10001; int nt = 2 * 10000; double dx = 2.0 * Math.PI / (nx - 1.0); double nu = 0.07; double dt = dx * nu; double[] x = linspace(0.0, 2.0 * Math.PI, nx); double[] initial = GetAnalytical(x, 0.0, nu); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { double[] results = GetCalculated3(nt, nx, dx, dt, nu, initial); Escape(results); } } } }
using System; using System.Runtime.InteropServices; using Axiom.Core; using Axiom.Input; using Tao.Sdl; namespace Axiom.Platforms.SDL { /// <summary> /// Platform management specialization for Microsoft Windows (r) platform. /// </summary> public class SdlInputReader : InputReader { #region Fields /// <summary> /// Is the SDL window currently visible? /// </summary> protected bool isVisible; protected int mouseX, mouseY; protected int relMouseX, relMouseY, relMouseZ; protected byte mouseKeys; protected MouseButtons mouseButtons; protected byte[] keyboardState; /// <summary> /// Array to use for holding buffered event data. /// </summary> protected Sdl.SDL_Event[] events = new Sdl.SDL_Event[BufferSize]; /// <summary> /// /// </summary> protected const int WheelStep = 60; /// <summary> /// Size of the arrays used to hold buffered input data. /// </summary> protected const int BufferSize = 16; #endregion Fields #region Constructor /// <summary> /// Constructor. /// </summary> public SdlInputReader() { // start off assuming we are visible isVisible = true; } /// <summary> /// Destructor. /// </summary> ~SdlInputReader() { // release input Sdl.SDL_WM_GrabInput(Sdl.SDL_GRAB_OFF); Sdl.SDL_ShowCursor(1); } #endregion Constructor #region InputReader Members #region Properties public override int AbsoluteMouseX { get { return mouseX; } } public override int AbsoluteMouseY { get { return mouseY; } } public override int AbsoluteMouseZ { get { return 0; } } public override int RelativeMouseX { get { return relMouseX; } } public override int RelativeMouseY { get { return relMouseY; } } public override int RelativeMouseZ { get { return relMouseZ; } } #endregion Properties #region Methods /// <summary> /// Capture the current state of SDL input. /// </summary> public override void Capture() { // if we aren't active, wait if(!isVisible) { Sdl.SDL_Event evt; while(Sdl.SDL_WaitEvent(out evt) != 0) { if(evt.type == Sdl.SDL_ACTIVEEVENT && evt.active.gain == 1) { break; } } } if(useKeyboardEvents) { ProcessBufferedKeyboard(); } if(useMouseEvents) { ProcessBufferedMouse(); } // gather input from the various devices Sdl.SDL_PumpEvents(); if(!useKeyboardEvents) { int numKeys; keyboardState = Sdl.SDL_GetKeyState(out numKeys); } if(!useMouseEvents) { // TODO: Look into awkward mouse wheel behavior mouseKeys = 0; relMouseX = 0; relMouseY = 0; relMouseZ = 0; // get mouse info if((Sdl.SDL_GetAppState() & Sdl.SDL_APPMOUSEFOCUS) != 0) { mouseKeys = Sdl.SDL_GetMouseState(out mouseX, out mouseY); Sdl.SDL_GetRelativeMouseState(out relMouseX, out relMouseY); // the value that is added to mMouseRelativeZ when the wheel // is moved one step (this value is actually added // twice per movement since a wheel movement triggers a // MOUSEBUTTONUP and a MOUSEBUTTONDOWN event) // fetch all mouse related events // TODO: SDL_PeepEvents throwing exceptions, investigate int count = 0; //Sdl.SDL_PeepEvents(events, BufferSize, Sdl.SDL_GETEVENT, // Sdl.SDL_MOUSEMOTIONMASK | Sdl.SDL_MOUSEBUTTONDOWNMASK | Sdl.SDL_MOUSEBUTTONUPMASK); if(count > 0) { for(int i = 0; i < count; i++) { if(events[i].type == Sdl.SDL_MOUSEBUTTONDOWN || events[i].type == Sdl.SDL_MOUSEBUTTONUP) { if(events[i].button.button == Sdl.SDL_BUTTON_WHEELUP) { relMouseZ += WheelStep; } else if(events[i].button.button == Sdl.SDL_BUTTON_WHEELDOWN) { relMouseZ -= WheelStep; } } } // for } // if count... } // if mouse focus mouseButtons = (mouseKeys & Sdl.SDL_BUTTON_LMASK) != 0 ? MouseButtons.Left : 0; // left mouseButtons |= (mouseKeys & Sdl.SDL_BUTTON_RMASK) != 0 ? MouseButtons.Right : 0; // right mouseButtons |= (mouseKeys & Sdl.SDL_BUTTON_MMASK) != 0 ? MouseButtons.Middle : 0; // middle } // if not using mouse events } /// <summary> /// /// </summary> /// <param name="parent"></param> /// <param name="useKeyboard"></param> /// <param name="useMouse"></param> /// <param name="useGamepad"></param> /// <param name="ownMouse"></param> public override void Initialize(Axiom.Graphics.RenderWindow parent, bool useKeyboard, bool useMouse, bool useGamepad, bool ownMouse) { if(useMouse && ownMouse) { // hide the cursor // TODO: Commented out for easier debugging //Sdl.SDL_ShowCursor(0); //Sdl.SDL_WM_GrabInput(Sdl.SDL_GRAB_ON); } // mouse starts out in the center of the window mouseX = (int)(parent.Width * 0.5f); mouseY = (int)(parent.Height * 0.5f); } /// <summary> /// Checks the current keyboard state to see if the specified key is pressed. /// </summary> /// <param name="key">KeyCode to check.</param> /// <returns>true if the key is down, false otherwise.</returns> public override bool IsKeyPressed(KeyCodes key) { int sdlKey = ConvertKeyEnum(key); return keyboardState[sdlKey] != 0; } public override bool IsMousePressed(MouseButtons button) { return (mouseButtons & button) != 0; } public override bool UseKeyboardEvents { get { return useKeyboardEvents; } set { useKeyboardEvents = value; } } public override bool UseMouseEvents { get { return useMouseEvents; } set { useMouseEvents = value; } } public override void Dispose() { } #endregion Methods #endregion InputReader Members #region Methods private void ProcessBufferedKeyboard() { int count = Sdl.SDL_PeepEvents( events, BufferSize, Sdl.SDL_GETEVENT, (Sdl.SDL_KEYDOWNMASK | Sdl.SDL_KEYUPMASK)); // no events to process if(count == 0) { return; } // fire an event for each key event for(int i = 0; i < count; i++) { bool down = (events[i].type == Sdl.SDL_KEYDOWN); Axiom.Input.KeyCodes keyCode = ConvertKeyEnum(events[i].key.keysym.sym); KeyChanged(keyCode, down); } } private void ProcessBufferedMouse() { } #region Keycode Conversions /// <summary> /// Used to convert an Axiom.Input.KeyCodes enum val to a Sdl enum val. /// </summary> /// <param name="key">Axiom keyboard code to query.</param> /// <returns>The equivalent enum value in the Sdl enum.</returns> private int ConvertKeyEnum(KeyCodes key) { // TODO: Quotes int sdlKey = 0; switch(key) { case KeyCodes.A: sdlKey = Sdl.SDLK_a; break; case KeyCodes.B: sdlKey = Sdl.SDLK_b; break; case KeyCodes.C: sdlKey = Sdl.SDLK_c; break; case KeyCodes.D: sdlKey = Sdl.SDLK_d; break; case KeyCodes.E: sdlKey = Sdl.SDLK_e; break; case KeyCodes.F: sdlKey = Sdl.SDLK_f; break; case KeyCodes.G: sdlKey = Sdl.SDLK_g; break; case KeyCodes.H: sdlKey = Sdl.SDLK_h; break; case KeyCodes.I: sdlKey = Sdl.SDLK_i; break; case KeyCodes.J: sdlKey = Sdl.SDLK_j; break; case KeyCodes.K: sdlKey = Sdl.SDLK_k; break; case KeyCodes.L: sdlKey = Sdl.SDLK_l; break; case KeyCodes.M: sdlKey = Sdl.SDLK_m; break; case KeyCodes.N: sdlKey = Sdl.SDLK_n; break; case KeyCodes.O: sdlKey = Sdl.SDLK_o; break; case KeyCodes.P: sdlKey = Sdl.SDLK_p; break; case KeyCodes.Q: sdlKey = Sdl.SDLK_q; break; case KeyCodes.R: sdlKey = Sdl.SDLK_r; break; case KeyCodes.S: sdlKey = Sdl.SDLK_s; break; case KeyCodes.T: sdlKey = Sdl.SDLK_t; break; case KeyCodes.U: sdlKey = Sdl.SDLK_u; break; case KeyCodes.V: sdlKey = Sdl.SDLK_v; break; case KeyCodes.W: sdlKey = Sdl.SDLK_w; break; case KeyCodes.X: sdlKey = Sdl.SDLK_x; break; case KeyCodes.Y: sdlKey = Sdl.SDLK_y; break; case KeyCodes.Z: sdlKey = Sdl.SDLK_z; break; case KeyCodes.Left : sdlKey = Sdl.SDLK_LEFT; break; case KeyCodes.Right: sdlKey = Sdl.SDLK_RIGHT; break; case KeyCodes.Up: sdlKey = Sdl.SDLK_UP; break; case KeyCodes.Down: sdlKey = Sdl.SDLK_DOWN; break; case KeyCodes.Escape: sdlKey = Sdl.SDLK_ESCAPE; break; case KeyCodes.F1: sdlKey = Sdl.SDLK_F1; break; case KeyCodes.F2: sdlKey = Sdl.SDLK_F2; break; case KeyCodes.F3: sdlKey = Sdl.SDLK_F3; break; case KeyCodes.F4: sdlKey = Sdl.SDLK_F4; break; case KeyCodes.F5: sdlKey = Sdl.SDLK_F5; break; case KeyCodes.F6: sdlKey = Sdl.SDLK_F6; break; case KeyCodes.F7: sdlKey = Sdl.SDLK_F7; break; case KeyCodes.F8: sdlKey = Sdl.SDLK_F8; break; case KeyCodes.F9: sdlKey = Sdl.SDLK_F9; break; case KeyCodes.F10: sdlKey = Sdl.SDLK_F10; break; case KeyCodes.D0: sdlKey = Sdl.SDLK_0; break; case KeyCodes.D1: sdlKey = Sdl.SDLK_1; break; case KeyCodes.D2: sdlKey = Sdl.SDLK_2; break; case KeyCodes.D3: sdlKey = Sdl.SDLK_3; break; case KeyCodes.D4: sdlKey = Sdl.SDLK_4; break; case KeyCodes.D5: sdlKey = Sdl.SDLK_5; break; case KeyCodes.D6: sdlKey = Sdl.SDLK_6; break; case KeyCodes.D7: sdlKey = Sdl.SDLK_7; break; case KeyCodes.D8: sdlKey = Sdl.SDLK_8; break; case KeyCodes.D9: sdlKey = Sdl.SDLK_9; break; case KeyCodes.F11: sdlKey = Sdl.SDLK_F11; break; case KeyCodes.F12: sdlKey = Sdl.SDLK_F12; break; case KeyCodes.Enter: sdlKey = Sdl.SDLK_RETURN; break; case KeyCodes.Tab: sdlKey = Sdl.SDLK_TAB; break; case KeyCodes.LeftShift: sdlKey = Sdl.SDLK_LSHIFT; break; case KeyCodes.RightShift: sdlKey = Sdl.SDLK_RSHIFT; break; case KeyCodes.LeftControl: sdlKey = Sdl.SDLK_LCTRL; break; case KeyCodes.RightControl: sdlKey = Sdl.SDLK_RCTRL; break; case KeyCodes.Period: sdlKey = Sdl.SDLK_PERIOD; break; case KeyCodes.Comma: sdlKey = Sdl.SDLK_COMMA; break; case KeyCodes.Home: sdlKey = Sdl.SDLK_HOME; break; case KeyCodes.PageUp: sdlKey = Sdl.SDLK_PAGEUP; break; case KeyCodes.PageDown: sdlKey = Sdl.SDLK_PAGEDOWN; break; case KeyCodes.End: sdlKey = Sdl.SDLK_END; break; case KeyCodes.Semicolon: sdlKey = Sdl.SDLK_SEMICOLON; break; case KeyCodes.Subtract: sdlKey = Sdl.SDLK_MINUS; break; case KeyCodes.Add: sdlKey = Sdl.SDLK_PLUS; break; case KeyCodes.Backspace: sdlKey = Sdl.SDLK_BACKSPACE; break; case KeyCodes.Delete: sdlKey = Sdl.SDLK_DELETE; break; case KeyCodes.Insert: sdlKey = Sdl.SDLK_INSERT; break; case KeyCodes.LeftAlt: sdlKey = Sdl.SDLK_LALT; break; case KeyCodes.RightAlt: sdlKey = Sdl.SDLK_RALT; break; case KeyCodes.Space: sdlKey = Sdl.SDLK_SPACE; break; case KeyCodes.Tilde: sdlKey = Sdl.SDLK_BACKQUOTE; break; case KeyCodes.OpenBracket: sdlKey = Sdl.SDLK_LEFTBRACKET; break; case KeyCodes.CloseBracket: sdlKey = Sdl.SDLK_RIGHTBRACKET; break; case KeyCodes.Plus: sdlKey = Sdl.SDLK_EQUALS; break; case KeyCodes.QuestionMark: sdlKey = Sdl.SDLK_SLASH; break; case KeyCodes.Quotes: sdlKey = Sdl.SDLK_QUOTE; break; case KeyCodes.Backslash: sdlKey = Sdl.SDLK_BACKSLASH; break; } return sdlKey; } /// <summary> /// Used to convert a Sdl enum val to a Axiom.Input.KeyCodes enum val. /// </summary> /// <param name="key">Sdl code to query.</param> /// <returns>The equivalent enum value in the Axiom.KeyCodes enum.</returns> private Axiom.Input.KeyCodes ConvertKeyEnum(int key) { // TODO: Quotes Axiom.Input.KeyCodes axiomKey = 0; switch(key) { case Sdl.SDLK_a: axiomKey = Axiom.Input.KeyCodes.A; break; case Sdl.SDLK_b: axiomKey = Axiom.Input.KeyCodes.B; break; case Sdl.SDLK_c: axiomKey = Axiom.Input.KeyCodes.C; break; case Sdl.SDLK_d: axiomKey = Axiom.Input.KeyCodes.D; break; case Sdl.SDLK_e: axiomKey = Axiom.Input.KeyCodes.E; break; case Sdl.SDLK_f: axiomKey = Axiom.Input.KeyCodes.F; break; case Sdl.SDLK_g: axiomKey = Axiom.Input.KeyCodes.G; break; case Sdl.SDLK_h: axiomKey = Axiom.Input.KeyCodes.H; break; case Sdl.SDLK_i: axiomKey = Axiom.Input.KeyCodes.I; break; case Sdl.SDLK_j: axiomKey = Axiom.Input.KeyCodes.J; break; case Sdl.SDLK_k: axiomKey = Axiom.Input.KeyCodes.K; break; case Sdl.SDLK_l: axiomKey = Axiom.Input.KeyCodes.L; break; case Sdl.SDLK_m: axiomKey = Axiom.Input.KeyCodes.M; break; case Sdl.SDLK_n: axiomKey = Axiom.Input.KeyCodes.N; break; case Sdl.SDLK_o: axiomKey = Axiom.Input.KeyCodes.O; break; case Sdl.SDLK_p: axiomKey = Axiom.Input.KeyCodes.P; break; case Sdl.SDLK_q: axiomKey = Axiom.Input.KeyCodes.Q; break; case Sdl.SDLK_r: axiomKey = Axiom.Input.KeyCodes.R; break; case Sdl.SDLK_s: axiomKey = Axiom.Input.KeyCodes.S; break; case Sdl.SDLK_t: axiomKey = Axiom.Input.KeyCodes.T; break; case Sdl.SDLK_u: axiomKey = Axiom.Input.KeyCodes.U; break; case Sdl.SDLK_v: axiomKey = Axiom.Input.KeyCodes.V; break; case Sdl.SDLK_w: axiomKey = Axiom.Input.KeyCodes.W; break; case Sdl.SDLK_x: axiomKey = Axiom.Input.KeyCodes.X; break; case Sdl.SDLK_y: axiomKey = Axiom.Input.KeyCodes.Y; break; case Sdl.SDLK_z: axiomKey = Axiom.Input.KeyCodes.Z; break; case Sdl.SDLK_LEFT: axiomKey = Axiom.Input.KeyCodes.Left; break; case Sdl.SDLK_RIGHT: axiomKey = Axiom.Input.KeyCodes.Right; break; case Sdl.SDLK_UP: axiomKey = Axiom.Input.KeyCodes.Up; break; case Sdl.SDLK_DOWN: axiomKey = Axiom.Input.KeyCodes.Down; break; case Sdl.SDLK_ESCAPE: axiomKey = Axiom.Input.KeyCodes.Escape; break; case Sdl.SDLK_F1: axiomKey = Axiom.Input.KeyCodes.F1; break; case Sdl.SDLK_F2: axiomKey = Axiom.Input.KeyCodes.F2; break; case Sdl.SDLK_F3: axiomKey = Axiom.Input.KeyCodes.F3; break; case Sdl.SDLK_F4: axiomKey = Axiom.Input.KeyCodes.F4; break; case Sdl.SDLK_F5: axiomKey = Axiom.Input.KeyCodes.F5; break; case Sdl.SDLK_F6: axiomKey = Axiom.Input.KeyCodes.F6; break; case Sdl.SDLK_F7: axiomKey = Axiom.Input.KeyCodes.F7; break; case Sdl.SDLK_F8: axiomKey = Axiom.Input.KeyCodes.F8; break; case Sdl.SDLK_F9: axiomKey = Axiom.Input.KeyCodes.F9; break; case Sdl.SDLK_F10: axiomKey = Axiom.Input.KeyCodes.F10; break; case Sdl.SDLK_0: axiomKey = Axiom.Input.KeyCodes.D0; break; case Sdl.SDLK_1: axiomKey = Axiom.Input.KeyCodes.D1; break; case Sdl.SDLK_2: axiomKey = Axiom.Input.KeyCodes.D2; break; case Sdl.SDLK_3: axiomKey = Axiom.Input.KeyCodes.D3; break; case Sdl.SDLK_4: axiomKey = Axiom.Input.KeyCodes.D4; break; case Sdl.SDLK_5: axiomKey = Axiom.Input.KeyCodes.D5; break; case Sdl.SDLK_6: axiomKey = Axiom.Input.KeyCodes.D6; break; case Sdl.SDLK_7: axiomKey = Axiom.Input.KeyCodes.D7; break; case Sdl.SDLK_8: axiomKey = Axiom.Input.KeyCodes.D8; break; case Sdl.SDLK_9: axiomKey = Axiom.Input.KeyCodes.D9; break; case Sdl.SDLK_F11: axiomKey = Axiom.Input.KeyCodes.F11; break; case Sdl.SDLK_F12: axiomKey = Axiom.Input.KeyCodes.F12; break; case Sdl.SDLK_RETURN: axiomKey = Axiom.Input.KeyCodes.Enter; break; case Sdl.SDLK_TAB: axiomKey = Axiom.Input.KeyCodes.Tab; break; case Sdl.SDLK_LSHIFT: axiomKey = Axiom.Input.KeyCodes.LeftShift; break; case Sdl.SDLK_RSHIFT: axiomKey = Axiom.Input.KeyCodes.RightShift; break; case Sdl.SDLK_LCTRL: axiomKey = Axiom.Input.KeyCodes.LeftControl; break; case Sdl.SDLK_RCTRL: axiomKey = Axiom.Input.KeyCodes.RightControl; break; case Sdl.SDLK_PERIOD: axiomKey = Axiom.Input.KeyCodes.Period; break; case Sdl.SDLK_COMMA: axiomKey = Axiom.Input.KeyCodes.Comma; break; case Sdl.SDLK_HOME: axiomKey = Axiom.Input.KeyCodes.Home; break; case Sdl.SDLK_PAGEUP: axiomKey = Axiom.Input.KeyCodes.PageUp; break; case Sdl.SDLK_PAGEDOWN: axiomKey = Axiom.Input.KeyCodes.PageDown; break; case Sdl.SDLK_END: axiomKey = Axiom.Input.KeyCodes.End; break; case Sdl.SDLK_SEMICOLON: axiomKey = Axiom.Input.KeyCodes.Semicolon; break; case Sdl.SDLK_MINUS: axiomKey = Axiom.Input.KeyCodes.Subtract; break; case Sdl.SDLK_PLUS: axiomKey = Axiom.Input.KeyCodes.Add; break; case Sdl.SDLK_BACKSPACE: axiomKey = Axiom.Input.KeyCodes.Backspace; break; case Sdl.SDLK_DELETE: axiomKey = Axiom.Input.KeyCodes.Delete; break; case Sdl.SDLK_INSERT: axiomKey = Axiom.Input.KeyCodes.Insert; break; case Sdl.SDLK_LALT: axiomKey = Axiom.Input.KeyCodes.LeftAlt; break; case Sdl.SDLK_RALT: axiomKey = Axiom.Input.KeyCodes.RightAlt; break; case Sdl.SDLK_SPACE: axiomKey = Axiom.Input.KeyCodes.Space; break; case Sdl.SDLK_BACKQUOTE: axiomKey = Axiom.Input.KeyCodes.Tilde; break; case Sdl.SDLK_LEFTBRACKET: axiomKey = Axiom.Input.KeyCodes.OpenBracket; break; case Sdl.SDLK_RIGHTBRACKET: axiomKey = Axiom.Input.KeyCodes.CloseBracket; break; case Sdl.SDLK_EQUALS: axiomKey = KeyCodes.Plus; break; case Sdl.SDLK_SLASH: axiomKey = KeyCodes.QuestionMark; break; case Sdl.SDLK_QUOTE: axiomKey = KeyCodes.Quotes; break; case Sdl.SDLK_BACKSLASH: axiomKey = KeyCodes.Backslash; break; } return axiomKey; } #endregion Keycode Conversions #endregion Methods } }
// 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.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using size_t = System.IntPtr; using libc = Interop.libc; using libcurl = Interop.libcurl; using PollFlags = Interop.libc.PollFlags; internal static partial class Interop { internal static partial class libcurl { internal sealed class SafeCurlHandle : SafeHandle { public SafeCurlHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { get { return this.handle == IntPtr.Zero; } } public static void DisposeAndClearHandle(ref SafeCurlHandle curlHandle) { if (curlHandle != null) { curlHandle.Dispose(); curlHandle = null; } } protected override bool ReleaseHandle() { libcurl.curl_easy_cleanup(this.handle); return true; } } internal sealed class SafeCurlMultiHandle : SafeHandle { private bool _pollCancelled = true; private readonly int[] _specialFds = new int[2]; private readonly HashSet<int> _fdSet = new HashSet<int>(); private int _requestCount = 0; private Timer _timer; internal bool PollCancelled { get { return _pollCancelled; } set { _pollCancelled = value; } } internal int RequestCount { get { return _requestCount; } set { _requestCount = value; } } internal Timer Timer { get { return _timer; } set { _timer = value; } } public SafeCurlMultiHandle() : base(IntPtr.Zero, true) { unsafe { fixed(int* fds = _specialFds) { while (Interop.CheckIo(libc.pipe(fds))); } } } public override bool IsInvalid { get { return this.handle == IntPtr.Zero; } } public static void DisposeAndClearHandle(ref SafeCurlMultiHandle curlHandle) { if (curlHandle != null) { curlHandle.Dispose(); curlHandle = null; } } internal void PollFds(List<libc.pollfd> readyFds) { int count; libc.pollfd[] pollFds; readyFds.Clear(); lock (this) { // TODO: Avoid the allocation when count is in 100s count = _fdSet.Count + 1; pollFds = new libc.pollfd[count]; // Always include special fd in the poll set. This is used to // return from the poll in case any fds have been added or // removed to the set of fds being polled. This prevents starvation // in case current set of fds have no activity but the new fd // is ready for a read/write. The special fd is the read end of a pipe // Whenever an fd is added/removed in _fdSet, a write happens to the // write end of the pipe thus causing the poll to return. pollFds[0].fd = _specialFds[libc.ReadEndOfPipe]; pollFds[0].events = PollFlags.POLLIN; int i = 1; foreach (int fd in _fdSet) { pollFds[i].fd = fd; pollFds[i].events = PollFlags.POLLIN | PollFlags.POLLOUT; i++; } } unsafe { fixed (libc.pollfd* fds = pollFds) { int numFds = libc.poll(fds, (uint)count, -1); if (numFds <= 0) { Debug.Assert(numFds != 0); // Since timeout is infinite // TODO: How to handle errors? throw new InvalidOperationException("Poll failure: " + Marshal.GetLastWin32Error()); } lock (this) { if (0 == _requestCount) { return; } } // Check for any fdset changes if (fds[0].revents != 0) { if (ReadSpecialFd(fds[0].revents) < 0) { // TODO: How to handle errors? throw new InvalidOperationException("Cannot read data: " + Marshal.GetLastWin32Error()); } numFds--; } // Now check for events on the remaining fds for (int i = 1; i < count && numFds > 0; i++) { if (fds[i].revents == 0) { continue; } readyFds.Add(fds[i]); numFds--; } } } } internal void SignalFdSetChange(int fd, bool isRemove) { Debug.Assert(Monitor.IsEntered(this)); bool changed = isRemove ? _fdSet.Remove(fd) : _fdSet.Add(fd); if (!changed) { return; } unsafe { // Write to special fd byte* dummyBytes = stackalloc byte[1]; if ((int)libc.write(_specialFds[libc.WriteEndOfPipe], dummyBytes, (size_t)1) <= 0) { // TODO: How to handle errors? throw new InvalidOperationException("Cannot write data: " + Marshal.GetLastWin32Error()); } } } protected override void Dispose(bool disposing) { if (disposing) { if (null != _timer) { _timer.Dispose(); } } base.Dispose(disposing); } protected override bool ReleaseHandle() { Debug.Assert(0 == _fdSet.Count); Debug.Assert(0 == _requestCount); Debug.Assert(_pollCancelled); Interop.Sys.Close(_specialFds[libc.ReadEndOfPipe]); Interop.Sys.Close(_specialFds[libc.WriteEndOfPipe]); libcurl.curl_multi_cleanup(this.handle); return true; } private int ReadSpecialFd(PollFlags revents) { PollFlags badEvents = PollFlags.POLLERR | PollFlags.POLLHUP | PollFlags.POLLNVAL; if ((revents & badEvents) != 0) { return -1; } Debug.Assert((revents & PollFlags.POLLIN) != 0); int pipeReadFd = _specialFds[libc.ReadEndOfPipe]; int bytesRead = 0; unsafe { do { // Read available data from the pipe int bufferLength = 1024; byte* dummyBytes = stackalloc byte[bufferLength]; int numBytes = (int)libc.read(pipeReadFd, dummyBytes, (size_t)bufferLength); if (numBytes <= 0) { return -1; } bytesRead += numBytes; // Check if more data is available PollFlags outFlags; int retVal = libc.poll(pipeReadFd, PollFlags.POLLIN, 0, out outFlags); if (retVal < 0) { return -1; } else if (0 == retVal) { break; } } while (true); } return bytesRead; } } internal sealed class SafeCurlSlistHandle : SafeHandle { public SafeCurlSlistHandle() : base(IntPtr.Zero, true) { } public override bool IsInvalid { get { return this.handle == IntPtr.Zero; } } public new void SetHandle(IntPtr handle) { base.SetHandle(handle); } public static void DisposeAndClearHandle(ref SafeCurlSlistHandle curlHandle) { if (curlHandle != null) { curlHandle.Dispose(); curlHandle = null; } } protected override bool ReleaseHandle() { libcurl.curl_slist_free_all(this.handle); return true; } } } }
using Serilog.Capturing; using Serilog.Core; using System; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Xunit; using MessageTemplateParser = Serilog.Parsing.MessageTemplateParser; namespace Serilog.Tests.Core { public class MessageTemplateTests { class Chair { // ReSharper disable UnusedMember.Local public string Back => "straight"; public int[] Legs => new[] { 1, 2, 3, 4 }; // ReSharper restore UnusedMember.Local public override string ToString() => "a chair"; } class Receipt { // ReSharper disable UnusedMember.Local public decimal Sum => 12.345m; public DateTime When => new(2013, 5, 20, 16, 39, 0); // ReSharper restore UnusedMember.Local public override string ToString() => "a receipt"; } class ToStringReturnsNull { public override string? ToString() => null; } class ToStringThrows { public override string ToString() => throw new ArgumentNullException("","A possible a Bug in a class"); } [Fact] public void AnObjectIsRenderedInSimpleNotation() { var m = Render("I sat at {@Chair}", new Chair()); Assert.Equal("I sat at Chair { Back: \"straight\", Legs: [1, 2, 3, 4] }", m); } [Fact] public void AnObjectIsRenderedInSimpleNotationUsingFormatProvider() { var m = Render(new CultureInfo("fr-FR"), "I received {@Receipt}", new Receipt()); Assert.Equal("I received Receipt { Sum: 12,345, When: 20/05/2013 16:39:00 }", m); } [Fact] public void AnAnonymousObjectIsRenderedInSimpleNotationWithoutType() { var m = Render("I sat at {@Chair}", new { Back = "straight", Legs = new[] { 1, 2, 3, 4 } }); Assert.Equal("I sat at { Back: \"straight\", Legs: [1, 2, 3, 4] }", m); } [Fact] public void AnAnonymousObjectIsRenderedInSimpleNotationWithoutTypeUsingFormatProvider() { var m = Render(new CultureInfo("fr-FR"), "I received {@Receipt}", new { Sum = 12.345, When = new DateTime(2013, 5, 20, 16, 39, 0) }); Assert.Equal("I received { Sum: 12,345, When: 20/05/2013 16:39:00 }", m); } [Fact] public void AnObjectWithDefaultDestructuringIsRenderedAsAStringLiteral() { var m = Render("I sat at {Chair}", new Chair()); Assert.Equal("I sat at \"a chair\"", m); var m2 = Render("I sat at {Obj}", new ToStringReturnsNull()); Assert.Equal("I sat at \"\"", m2); var m3 = Render("I sat at {Obj}", new ToStringThrows()); Assert.Equal("I sat at \"Capturing the property value threw an exception: ArgumentNullException\"", m3); } [Fact] public void AnObjectWithStringifyDestructuringIsRenderedAsAString() { var m = Render("I sat at {$Chair}", new Chair()); Assert.Equal("I sat at \"a chair\"", m); var m2 = Render("I sat at {$Obj}", new ToStringReturnsNull()); Assert.Equal("I sat at \"\"", m2); var m3 = Render("I sat at {$Obj}", new ToStringThrows()); Assert.Equal("I sat at \"Capturing the property value threw an exception: ArgumentNullException\"", m3); } [Fact] public void MultiplePropertiesAreRenderedInOrder() { var m = Render("Just biting {Fruit} number {Count}", "Apple", 12); Assert.Equal("Just biting \"Apple\" number 12", m); } [Fact] public void MultiplePropertiesUseFormatProvider() { var m = Render(new CultureInfo("fr-FR"), "Income was {Income} at {Date:d}", 1234.567, new DateTime(2013, 5, 20)); Assert.Equal("Income was 1234,567 at 20/05/2013", m); } [Fact] public void FormatStringsArePropagated() { var m = Render("Welcome, customer {CustomerId:0000}", 12); Assert.Equal("Welcome, customer 0012", m); } [Theory] [InlineData("Welcome, customer #{CustomerId,-10}, pleasure to see you", "Welcome, customer #1234 , pleasure to see you")] [InlineData("Welcome, customer #{CustomerId,-10:000000}, pleasure to see you", "Welcome, customer #001234 , pleasure to see you")] [InlineData("Welcome, customer #{CustomerId,10}, pleasure to see you", "Welcome, customer # 1234, pleasure to see you")] [InlineData("Welcome, customer #{CustomerId,10:000000}, pleasure to see you", "Welcome, customer # 001234, pleasure to see you")] [InlineData("Welcome, customer #{CustomerId,10:0,0}, pleasure to see you", "Welcome, customer # 1,234, pleasure to see you")] [InlineData("Welcome, customer #{CustomerId:0,0}, pleasure to see you", "Welcome, customer #1,234, pleasure to see you")] public void AlignmentStringsArePropagated(string value, string expected) { Assert.Equal(expected, Render(value, 1234)); } [Fact] public void FormatProviderIsUsed() { var m = Render(new CultureInfo("fr-FR"), "Please pay {Sum}", 12.345); Assert.Equal("Please pay 12,345", m); } static string Render(string messageTemplate, params object[] properties) { return Render(null, messageTemplate, properties); } static string Render(IFormatProvider? formatProvider, string messageTemplate, params object[] properties) { var mt = new MessageTemplateParser().Parse(messageTemplate); var binder = new PropertyBinder(new PropertyValueConverter(10, 1000, 1000, Enumerable.Empty<Type>(), Enumerable.Empty<IDestructuringPolicy>(), false)); var props = binder.ConstructProperties(mt, properties); var output = new StringBuilder(); var writer = new StringWriter(output); mt.Render(props.ToDictionary(p => p.Name, p => p.Value), writer, formatProvider); writer.Flush(); return output.ToString(); } [Fact] public void ATemplateWithOnlyPositionalPropertiesIsAnalyzedAndRenderedPositionally() { var m = Render("{1}, {0}", "world", "Hello"); Assert.Equal("\"Hello\", \"world\"", m); } [Fact] public void ATemplateWithOnlyPositionalPropertiesUsesFormatProvider() { var m = Render(new CultureInfo("fr-FR"), "{1}, {0}", 12.345, "Hello"); Assert.Equal("\"Hello\", 12,345", m); } // Debatable what the behavior should be, here. [Fact] public void ATemplateWithNamesAndPositionalsUsesNamesForAllValues() { var m = Render("{1}, {Place}", "world", "Hello"); Assert.Equal("\"world\", \"Hello\"", m); } [Fact] public void MissingPositionalParametersRenderAsTextLikeStandardFormats() { var m = Render("{1}, {0}", "world"); Assert.Equal("{1}, \"world\"", m); } [Fact] public void AnonymousTypeShouldBeRendered() { var anonymous = new { Test = 3M }; var m = Render("Anonymous type {value}", anonymous); Assert.Equal("Anonymous type \"{ Test = 3 }\"", m); } [Fact] public void EnumerableOfAnonymousTypeShouldBeRendered() { var anonymous = new { Foo = 4M, Bar = "Baz" }; var enumerable = Enumerable.Repeat("MyKey", 1).Select(_ => anonymous); var m = Render("Enumerable with anonymous type {enumerable}", enumerable); Assert.Equal("Enumerable with anonymous type [\"{ Foo = 4, Bar = Baz }\"]", m); } [Fact] public void DictionaryOfAnonymousTypeAsValueShouldBeRendered() { var anonymous = new { Test = 5M }; var dictionary = Enumerable.Repeat("MyKey", 1).ToDictionary(v => v, _ => anonymous); var m = Render("Dictionary with anonymous type value {dictionary}", dictionary); Assert.Equal("Dictionary with anonymous type value [(\"MyKey\": \"{ Test = 5 }\")]", m); } [Fact] public void DictionaryOfAnonymousTypeAsKeyShouldBeRendered() { var anonymous = new { Bar = 6M, Baz = 4M }; var dictionary = Enumerable.Repeat("MyValue", 1).ToDictionary(_ => anonymous, v => v); var m = Render("Dictionary with anonymous type key {dictionary}", dictionary); Assert.Equal("Dictionary with anonymous type key [\"[{ Bar = 6, Baz = 4 }, MyValue]\"]", m); } } }
namespace Microsoft.Azure.Management.StorSimple8000Series { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for BandwidthSettingsOperations. /// </summary> public static partial class BandwidthSettingsOperationsExtensions { /// <summary> /// Retrieves all the bandwidth setting in a manager. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static IEnumerable<BandwidthSetting> ListByManager(this IBandwidthSettingsOperations operations, string resourceGroupName, string managerName) { return operations.ListByManagerAsync(resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Retrieves all the bandwidth setting in a manager. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<BandwidthSetting>> ListByManagerAsync(this IBandwidthSettingsOperations operations, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByManagerWithHttpMessagesAsync(resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns the properties of the specified bandwidth setting name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The name of bandwidth setting to be fetched. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static BandwidthSetting Get(this IBandwidthSettingsOperations operations, string bandwidthSettingName, string resourceGroupName, string managerName) { return operations.GetAsync(bandwidthSettingName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Returns the properties of the specified bandwidth setting name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The name of bandwidth setting to be fetched. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BandwidthSetting> GetAsync(this IBandwidthSettingsOperations operations, string bandwidthSettingName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(bandwidthSettingName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates the bandwidth setting /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The bandwidth setting name. /// </param> /// <param name='parameters'> /// The bandwidth setting to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static BandwidthSetting CreateOrUpdate(this IBandwidthSettingsOperations operations, string bandwidthSettingName, BandwidthSetting parameters, string resourceGroupName, string managerName) { return operations.CreateOrUpdateAsync(bandwidthSettingName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the bandwidth setting /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The bandwidth setting name. /// </param> /// <param name='parameters'> /// The bandwidth setting to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BandwidthSetting> CreateOrUpdateAsync(this IBandwidthSettingsOperations operations, string bandwidthSettingName, BandwidthSetting parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(bandwidthSettingName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the bandwidth setting /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The name of the bandwidth setting. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static void Delete(this IBandwidthSettingsOperations operations, string bandwidthSettingName, string resourceGroupName, string managerName) { operations.DeleteAsync(bandwidthSettingName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the bandwidth setting /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The name of the bandwidth setting. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IBandwidthSettingsOperations operations, string bandwidthSettingName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(bandwidthSettingName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates or updates the bandwidth setting /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The bandwidth setting name. /// </param> /// <param name='parameters'> /// The bandwidth setting to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static BandwidthSetting BeginCreateOrUpdate(this IBandwidthSettingsOperations operations, string bandwidthSettingName, BandwidthSetting parameters, string resourceGroupName, string managerName) { return operations.BeginCreateOrUpdateAsync(bandwidthSettingName, parameters, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates the bandwidth setting /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The bandwidth setting name. /// </param> /// <param name='parameters'> /// The bandwidth setting to be added or updated. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<BandwidthSetting> BeginCreateOrUpdateAsync(this IBandwidthSettingsOperations operations, string bandwidthSettingName, BandwidthSetting parameters, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(bandwidthSettingName, parameters, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the bandwidth setting /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The name of the bandwidth setting. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> public static void BeginDelete(this IBandwidthSettingsOperations operations, string bandwidthSettingName, string resourceGroupName, string managerName) { operations.BeginDeleteAsync(bandwidthSettingName, resourceGroupName, managerName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the bandwidth setting /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bandwidthSettingName'> /// The name of the bandwidth setting. /// </param> /// <param name='resourceGroupName'> /// The resource group name /// </param> /// <param name='managerName'> /// The manager name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IBandwidthSettingsOperations operations, string bandwidthSettingName, string resourceGroupName, string managerName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(bandwidthSettingName, resourceGroupName, managerName, null, cancellationToken).ConfigureAwait(false); } } }
// // CairoExtensions.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007 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.Reflection; using System.Runtime.InteropServices; using Gdk; using Cairo; namespace Hyena.Gui { [Flags] public enum CairoCorners { None = 0, TopLeft = 1, TopRight = 2, BottomLeft = 4, BottomRight = 8, All = 15 } public static class CairoExtensions { public static void SetSourceColor (this Cairo.Context cr, Cairo.Color color) => cr?.SetSourceRGBA (color.R, color.G, color.B, color.A); public static Pango.Layout CreateLayout (Gtk.Widget widget, Cairo.Context cairo_context) { Pango.Layout layout = PangoCairoHelper.CreateLayout (cairo_context); layout.FontDescription = widget.PangoContext.FontDescription; double resolution = widget.Screen.Resolution; if (resolution != -1) { Pango.Context context = PangoCairoHelper.LayoutGetContext (layout); PangoCairoHelper.ContextSetResolution (context, resolution); context.Dispose (); } Log.Debug ("Creating Pango.Layout, configuring Cairo.Context"); return layout; } public static Surface CreateSurfaceForPixbuf (Cairo.Context cr, Gdk.Pixbuf pixbuf) { Surface surface = cr.GetTarget ().CreateSimilar (cr.GetTarget ().Content, pixbuf.Width, pixbuf.Height); Cairo.Context surface_cr = new Context (surface); Gdk.CairoHelper.SetSourcePixbuf (surface_cr, pixbuf, 0, 0); surface_cr.Paint (); ((IDisposable)surface_cr).Dispose (); return surface; } public static Cairo.Color AlphaBlend (Cairo.Color ca, Cairo.Color cb, double alpha) { return new Cairo.Color ( (1.0 - alpha) * ca.R + alpha * cb.R, (1.0 - alpha) * ca.G + alpha * cb.G, (1.0 - alpha) * ca.B + alpha * cb.B); } public static Cairo.Color GdkColorToCairoColor(Gdk.Color color) { return GdkColorToCairoColor(color, 1.0); } public static Cairo.Color GdkColorToCairoColor(Gdk.Color color, double alpha) { return new Cairo.Color( (double)(color.Red >> 8) / 255.0, (double)(color.Green >> 8) / 255.0, (double)(color.Blue >> 8) / 255.0, alpha); } public static Cairo.Color RgbToColor (uint rgbColor) { return RgbaToColor ((rgbColor << 8) | 0x000000ff); } public static Cairo.Color RgbaToColor (uint rgbaColor) { return new Cairo.Color ( (byte)(rgbaColor >> 24) / 255.0, (byte)(rgbaColor >> 16) / 255.0, (byte)(rgbaColor >> 8) / 255.0, (byte)(rgbaColor & 0x000000ff) / 255.0); } public static bool ColorIsDark (Cairo.Color color) { double h, s, b; HsbFromColor (color, out h, out s, out b); return b < 0.5; } public static void HsbFromColor(Cairo.Color color, out double hue, out double saturation, out double brightness) { double min, max, delta; double red = color.R; double green = color.G; double blue = color.B; hue = 0; saturation = 0; brightness = 0; if(red > green) { max = Math.Max(red, blue); min = Math.Min(green, blue); } else { max = Math.Max(green, blue); min = Math.Min(red, blue); } brightness = (max + min) / 2; if(Math.Abs(max - min) < 0.0001) { hue = 0; saturation = 0; } else { saturation = brightness <= 0.5 ? (max - min) / (max + min) : (max - min) / (2 - max - min); delta = max - min; if(red == max) { hue = (green - blue) / delta; } else if(green == max) { hue = 2 + (blue - red) / delta; } else if(blue == max) { hue = 4 + (red - green) / delta; } hue *= 60; if(hue < 0) { hue += 360; } } } private static double Modula(double number, double divisor) { return ((int)number % divisor) + (number - (int)number); } public static Cairo.Color ColorFromHsb(double hue, double saturation, double brightness) { int i; double [] hue_shift = { 0, 0, 0 }; double [] color_shift = { 0, 0, 0 }; double m1, m2, m3; m2 = brightness <= 0.5 ? brightness * (1 + saturation) : brightness + saturation - brightness * saturation; m1 = 2 * brightness - m2; hue_shift[0] = hue + 120; hue_shift[1] = hue; hue_shift[2] = hue - 120; color_shift[0] = color_shift[1] = color_shift[2] = brightness; i = saturation == 0 ? 3 : 0; for(; i < 3; i++) { m3 = hue_shift[i]; if(m3 > 360) { m3 = Modula(m3, 360); } else if(m3 < 0) { m3 = 360 - Modula(Math.Abs(m3), 360); } if(m3 < 60) { color_shift[i] = m1 + (m2 - m1) * m3 / 60; } else if(m3 < 180) { color_shift[i] = m2; } else if(m3 < 240) { color_shift[i] = m1 + (m2 - m1) * (240 - m3) / 60; } else { color_shift[i] = m1; } } return new Cairo.Color(color_shift[0], color_shift[1], color_shift[2]); } public static Cairo.Color ColorShade (Cairo.Color @base, double ratio) { double h, s, b; HsbFromColor (@base, out h, out s, out b); b = Math.Max (Math.Min (b * ratio, 1), 0); s = Math.Max (Math.Min (s * ratio, 1), 0); Cairo.Color color = ColorFromHsb (h, s, b); color.A = @base.A; return color; } public static Cairo.Color ColorAdjustBrightness(Cairo.Color @base, double br) { double h, s, b; HsbFromColor(@base, out h, out s, out b); b = Math.Max(Math.Min(br, 1), 0); return ColorFromHsb(h, s, b); } public static string ColorGetHex (Cairo.Color color, bool withAlpha) { if (withAlpha) { return String.Format("#{0:x2}{1:x2}{2:x2}{3:x2}", (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255), (byte)(color.A * 255)); } else { return String.Format("#{0:x2}{1:x2}{2:x2}", (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255)); } } public static void RoundedRectangle(Cairo.Context cr, double x, double y, double w, double h, double r) { RoundedRectangle(cr, x, y, w, h, r, CairoCorners.All, false); } public static void RoundedRectangle(Cairo.Context cr, double x, double y, double w, double h, double r, CairoCorners corners) { RoundedRectangle(cr, x, y, w, h, r, corners, false); } public static void RoundedRectangle(Cairo.Context cr, double x, double y, double w, double h, double r, CairoCorners corners, bool topBottomFallsThrough) { if(topBottomFallsThrough && corners == CairoCorners.None) { cr.MoveTo(x, y - r); cr.LineTo(x, y + h + r); cr.MoveTo(x + w, y - r); cr.LineTo(x + w, y + h + r); return; } else if(r < 0.0001 || corners == CairoCorners.None) { cr.Rectangle(x, y, w, h); return; } if((corners & (CairoCorners.TopLeft | CairoCorners.TopRight)) == 0 && topBottomFallsThrough) { y -= r; h += r; cr.MoveTo(x + w, y); } else { if((corners & CairoCorners.TopLeft) != 0) { cr.MoveTo(x + r, y); } else { cr.MoveTo(x, y); } if((corners & CairoCorners.TopRight) != 0) { cr.Arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2); } else { cr.LineTo(x + w, y); } } if((corners & (CairoCorners.BottomLeft | CairoCorners.BottomRight)) == 0 && topBottomFallsThrough) { h += r; cr.LineTo(x + w, y + h); cr.MoveTo(x, y + h); cr.LineTo(x, y + r); cr.Arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); } else { if((corners & CairoCorners.BottomRight) != 0) { cr.Arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5); } else { cr.LineTo(x + w, y + h); } if((corners & CairoCorners.BottomLeft) != 0) { cr.Arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI); } else { cr.LineTo(x, y + h); } if((corners & CairoCorners.TopLeft) != 0) { cr.Arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); } else { cr.LineTo(x, y); } } } public static void DisposeContext (Cairo.Context cr) { ((IDisposable)cr.GetTarget ()).Dispose (); ((IDisposable)cr).Dispose (); } private struct CairoInteropCall { public string Name; public MethodInfo ManagedMethod; public bool CallNative; public CairoInteropCall (string name) { Name = name; ManagedMethod = null; CallNative = false; } } private static bool CallCairoMethod (Cairo.Context cr, ref CairoInteropCall call) { if (call.ManagedMethod == null && !call.CallNative) { MemberInfo [] members = typeof (Cairo.Context).GetMember (call.Name, MemberTypes.Method, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public); if (members != null && members.Length > 0 && members[0] is MethodInfo) { call.ManagedMethod = (MethodInfo)members[0]; } else { call.CallNative = true; } } if (call.ManagedMethod != null) { call.ManagedMethod.Invoke (cr, null); return true; } return false; } private static bool native_push_pop_exists = true; [DllImport ("libcairo-2.dll")] private static extern void cairo_push_group (IntPtr ptr); private static CairoInteropCall cairo_push_group_call = new CairoInteropCall ("PushGroup"); public static void PushGroup (Cairo.Context cr) { if (!native_push_pop_exists) { return; } try { if (!CallCairoMethod (cr, ref cairo_push_group_call)) { cairo_push_group (cr.Handle); } } catch { native_push_pop_exists = false; } } [DllImport ("libcairo-2.dll")] private static extern void cairo_pop_group_to_source (IntPtr ptr); private static CairoInteropCall cairo_pop_group_to_source_call = new CairoInteropCall ("PopGroupToSource"); public static void PopGroupToSource (Cairo.Context cr) { if (!native_push_pop_exists) { return; } try { if (!CallCairoMethod (cr, ref cairo_pop_group_to_source_call)) { cairo_pop_group_to_source (cr.Handle); } } catch (EntryPointNotFoundException) { native_push_pop_exists = false; } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // using UnityEngine; using System.Collections.Generic; using System; #if UNITY_WSA using UnityEngine.VR.WSA.Input; #endif public class InputSourceHands : InputSourceBase, ITargetingInputSource { public event Action<InputSourceBase, bool> OnSelectChanged = delegate { }; public event Action<InputSourceBase, bool> OnMenuChanged = delegate { }; public event Action<CurrentHandState> OnFingerPressed = delegate { }; public event Action<CurrentHandState> OnFingerReleased = delegate { }; public event Action<CurrentHandState> OnHandEntered = delegate { }; public event Action<CurrentHandState> OnHandLeft = delegate { }; public event Action<CurrentHandState> OnHandMoved = delegate { }; public int NumHandsVisible { get; private set; } public int NumFingersPressed { get; private set; } public int PrevFingersPressed { get; private set; } public const int FirstHandIndex = 0; public const int SecondHandIndex = 1; bool prevDragging; public float BloomGesture_FingerHoldTime = 2f; public float FingerHoldTime; public ButtonControlState menuGesture = new ButtonControlState(); // Activation public float HandMinVisibleTime = 0.5f; public float HandMinReadyTime = 0.25f; public float HandReadyDot = 0.7f; float m_HandVisibleTime; float handReadyTime; // Special logic for a hand vector while dragging Vector3 dragLocalHandStart; Vector3 dragStartHeadPosition; Quaternion dragStartHeadRotation = Quaternion.identity; public Quaternion adjustedHandTargetRot = Quaternion.identity; // Depth gesture float dragStartDistance; float dragDistanceDeltaVel; float dragDistanceLast; Vector3 prevHandPosition; // Drag control public Vector2ControlState dragControl = new Vector2ControlState(false); private bool m_Select; private bool m_Menu; private Vector3 m_LastHandPosition = Vector3.zero; private Transform HeadTransform { get { return Camera.main.transform; } } // -------------------------------------------------------------------------------- #region Targeting source interface /// <summary> /// The item name to use for this debug item. /// </summary> bool ITargetingInputSource.ShouldActivate() { return IsDoingHoldGesture(); } Vector3 ITargetingInputSource.GetTargetOrigin() { return HeadTransform.position; } Quaternion ITargetingInputSource.GetTargetRotation() { if (IsManipulating()) { return adjustedHandTargetRot; } return HeadTransform.rotation; } bool ITargetingInputSource.IsSelectPressed() { return NumFingersPressed > 0; } bool ITargetingInputSource.IsMenuPressed() { return menuGesture.PressedOnce; } void ITargetingInputSource.OnActivate(bool activated) { m_HandVisibleTime = 0; handReadyTime = 0; FingerHoldTime = 0; } bool ITargetingInputSource.IsReady() { return m_HandVisibleTime >= HandMinVisibleTime; } bool ITargetingInputSource.IsTargetingActive() { return IsDoingHoldGesture(); } #endregion // -------------------------------------------------------------------------------- public bool IsDoingHoldGesture() { bool fingerPressed = NumFingersPressed > 0; // Consider the hand holding when visible and finger pressed. // Ignore the hand ready timeout, usually used to prevent erroneous return (IsHandVisible() && fingerPressed); } public bool IsHandVisible() { return m_HandVisibleTime >= HandMinVisibleTime; } public bool IsAnyHandVisible() { return NumHandsVisible > 0; } public bool IsPrimaryHand(CurrentHandState state) { return trackedHands.Count > 0 && trackedHands[0] == state; } // Position of hand at index public Vector3 GetWorldPosition(int idx) { if (trackedHands.Count > idx) { m_LastHandPosition = trackedHands[idx].Position; } return m_LastHandPosition; } public CurrentHandState GetHandState(int idx) { CurrentHandState handState = null; if (trackedHands.Count > idx) { handState = trackedHands[idx]; } return handState; } public override void _Update() { PrevFingersPressed = NumFingersPressed; NumHandsVisible = trackedHands.Count; NumFingersPressed = 0; foreach (CurrentHandState hand in trackedHands) { if (hand.Pressed) { ++NumFingersPressed; } } // Update hand activation UpdateHandActivationState(); // Update hand dragging, like a special hand based targeting vector while dragging and depth UpdateHandDrag(); bool prev = m_Select; m_Select = (this as ITargetingInputSource).IsSelectPressed(); if (prev != m_Select) { OnSelectChanged(this, m_Select); } prev = m_Menu; m_Menu = (this as ITargetingInputSource).IsMenuPressed(); if (prev != m_Menu) { OnMenuChanged(this, m_Menu); } base._Update(); } void UpdateHandActivationState() { // Update finger hold time and menu gesture detection if (IsDoingHoldGesture()) { FingerHoldTime += Time.deltaTime; //bCompletedMenuGesture = (FingerHoldTime - Time.deltaTime < BloomGesture_FingerHoldTime && FingerHoldTime >= BloomGesture_FingerHoldTime); } else { FingerHoldTime = 0; } menuGesture.ApplyState(FingerHoldTime >= BloomGesture_FingerHoldTime && InputShellMap.Instance.CanCompleteHoldGesture()); float startVisibleTime = m_HandVisibleTime; float startReadyTime = handReadyTime; // Update hand state timers if (NumHandsVisible > 0) { // Track the visibility time m_HandVisibleTime += Time.deltaTime; // Hand 'ready' time... raise in front of look direction Vector3 handPos = GetWorldPosition(0); if (Vector3.Dot((handPos - HeadTransform.position).normalized, HeadTransform.forward) >= HandReadyDot) { handReadyTime += Time.deltaTime; } } // If the timers didn't change, they just get reset if (m_HandVisibleTime == startVisibleTime) { m_HandVisibleTime = 0; } if (handReadyTime == startReadyTime) { handReadyTime = 0; } } void UpdateHandDrag() { bool isDragging = NumFingersPressed > 0 && IsManipulating(); Vector3 handPos = GetWorldPosition(0); if (isDragging) { if (!prevDragging) { dragStartHeadPosition = HeadTransform.position; if (handPos.y < dragStartHeadPosition.y) { dragStartHeadPosition.y = handPos.y; } dragStartHeadRotation = HeadTransform.rotation; dragLocalHandStart = Quaternion.Inverse(dragStartHeadRotation) * (handPos - dragStartHeadPosition); dragControl.ApplyPos(false, Vector2.zero); prevHandPosition = handPos; prevDragging = isDragging; UpdateHandDrag(); } else { // Use the head position pivot, but at the starting height Vector3 pivotPos = HeadTransform.position; pivotPos.y = dragStartHeadPosition.y; // Find where the hand has moved relative to the starting pose (of head and hand) Vector3 localOffsetFromStart = Quaternion.Inverse(dragStartHeadRotation) * (handPos - pivotPos); // Get the difference in rotation Quaternion handRotation = Quaternion.FromToRotation(dragLocalHandStart, localOffsetFromStart); // Apply to original head direction adjustedHandTargetRot = dragStartHeadRotation * handRotation; // Update drag distance Vector3 posDelta = handPos - prevHandPosition; float pdDot = Vector3.Dot(posDelta.normalized, HeadTransform.forward); float distDelta = pdDot * posDelta.magnitude; // Deadzone? //distDelta = Mathf.Sign(distDelta) * Mathf.Max(0, Mathf.Abs(distDelta) - dragDistanceDeadzone); // Update the drag control dragControl.ApplyDelta(true, new Vector2(0, distDelta)); } } else { dragControl.ApplyPos(false, Vector2.zero); } prevHandPosition = handPos; prevDragging = isDragging; } // -------------------------------------------------------------------------------- #region System-level hand input source public class CurrentHandState { public uint HandId; public Vector3 Position; public Vector3 Velocity; public bool Pressed; public bool LastPressed; public double SourceLossRisk; public Vector3 SourceLossMitigationDirection; } private static List<CurrentHandState> trackedHands = new List<CurrentHandState>(); // Subscribe to the hand events private void Awake() { #if UNITY_WSA InteractionManager.SourceDetected += WSASourceEntered; InteractionManager.SourceLost += WSASourceLost; InteractionManager.SourceUpdated += WSASourceUpdate; InteractionManager.SourcePressed += WSAFingerPressed; InteractionManager.SourceReleased += WSAFingerReleased; #endif } // Cleanup hand event subscriptions private void OnDestroy() { #if UNITY_WSA InteractionManager.SourceDetected -= WSASourceEntered; InteractionManager.SourceLost -= WSASourceLost; InteractionManager.SourceUpdated -= WSASourceUpdate; InteractionManager.SourcePressed -= WSAFingerPressed; InteractionManager.SourceReleased -= WSAFingerReleased; #endif } #if UNITY_WSA public void WSASourceEntered(InteractionSourceState state) { // Track Hands if (state.source.kind == InteractionSourceKind.Hand) { CurrentHandState inputState = new CurrentHandState(); state.properties.location.TryGetPosition(out inputState.Position); UpdateFromWSASource(inputState, state); SourceEntered(inputState); } } public void WSASourceUpdate(InteractionSourceState state) { if (state.source.kind == InteractionSourceKind.Hand) { Vector3 newPosition; if (state.properties.location.TryGetPosition(out newPosition)) { CurrentHandState inputState = trackedHands.Find(CurrentInputState => CurrentInputState.HandId == state.source.id); // handID UpdateFromWSASource(inputState, state); SourceUpdate(inputState, newPosition); } } } public void WSASourceLost(InteractionSourceState state) { if (state.source.kind == InteractionSourceKind.Hand) { CurrentHandState inputState = trackedHands.Find(CurrentInputState => CurrentInputState.HandId == state.source.id); // handID UpdateFromWSASource(inputState, state); SourceLost(inputState); } } private void WSAFingerReleased(InteractionSourceState state) { CurrentHandState inputState = trackedHands.Find(CurrentInputState => CurrentInputState.HandId == state.source.id); if (inputState != null) { UpdateFromWSASource(inputState, state); OnFingerReleased(inputState); } } private void WSAFingerPressed(InteractionSourceState state) { CurrentHandState inputState = trackedHands.Find(CurrentInputState => CurrentInputState.HandId == state.source.id); if (inputState != null) { UpdateFromWSASource(inputState, state); OnFingerPressed(inputState); } } #endif public void SourceEntered(CurrentHandState inputState) { trackedHands.Add(inputState); OnHandEntered(inputState); } public void SourceUpdate(CurrentHandState inputState, Vector3 newPosition) { inputState.Position = newPosition; OnHandMoved(inputState); } public void SourceLost(CurrentHandState inputState) { lock (trackedHands) { trackedHands.Remove(inputState); } OnHandLeft(inputState); if (trackedHands.Count == 0) { } else { trackedHands.Sort( delegate (CurrentHandState h1, CurrentHandState h2) { return h1.HandId == h2.HandId ? 0 : h1.HandId < h2.HandId ? -1 : 1; } ); } } #if UNITY_WSA private void UpdateFromWSASource(CurrentHandState currentInputState, InteractionSourceState state) { currentInputState.HandId = state.source.id; currentInputState.LastPressed = currentInputState.Pressed; currentInputState.Pressed = state.pressed; state.properties.location.TryGetVelocity(out currentInputState.Velocity); currentInputState.SourceLossRisk = state.properties.sourceLossRisk; currentInputState.SourceLossMitigationDirection = state.properties.sourceLossMitigationDirection; } #endif #endregion }
// <copyright file="MultinomialTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 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> namespace MathNet.Numerics.UnitTests.DistributionTests.Multivariate { using System; using System.Linq; using Distributions; using NUnit.Framework; using Statistics; /// <summary> /// Multinomial distribution tests. /// </summary> [TestFixture, Category("Distributions")] public class MultinomialTests { /// <summary> /// Bad proportion of ratios. /// </summary> private double[] _badP; /// <summary> /// Another bad proportion of ratios. /// </summary> private double[] _badP2; /// <summary> /// Small array with proportion of ratios /// </summary> private double[] _smallP; /// <summary> /// Large array with proportion of ratios /// </summary> private double[] _largeP; /// <summary> /// Set-up tests parameters. /// </summary> [SetUp] public void SetUp() { Control.CheckDistributionParameters = true; _badP = new[] { -1.0, 1.0 }; _badP2 = new[] { 0.0, 0.0 }; _smallP = new[] { 1.0, 1.0, 1.0 }; _largeP = new[] { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0 }; } /// <summary> /// Can create Multinomial /// </summary> [Test] public void CanCreateMultinomial() { var m = new Multinomial(_largeP, 4); CollectionAssert.AreEqual(_largeP, m.P); } /// <summary> /// Can create Multinomial from a histogram. /// </summary> [Test] public void CanCreateMultinomialFromHistogram() { double[] smallDataset = { 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5 }; var hist = new Histogram(smallDataset, 10, 0.0, 10.0); var m = new Multinomial(hist, 7); foreach (var t in m.P) { Assert.AreEqual(1.0, t); } } /// <summary> /// Multinomial create fails with <c>null</c> histogram. /// </summary> [Test] public void MultinomialCreateFailsWithNullHistogram() { Histogram h = null; // ReSharper disable ExpressionIsAlwaysNull Assert.That(() => new Categorical(h), Throws.TypeOf<ArgumentNullException>()); // ReSharper restore ExpressionIsAlwaysNull } /// <summary> /// Multinomial create fails with negative ratios. /// </summary> [Test] public void MultinomialCreateFailsWithNegativeRatios() { Assert.That(() => new Multinomial(_badP, 4), Throws.ArgumentException); } /// <summary> /// Multinomial create fails with all zero ratios. /// </summary> [Test] public void MultinomialCreateFailsWithAllZeroRatios() { Assert.That(() => new Multinomial(_badP2, 4), Throws.ArgumentException); } /// <summary> /// Validate ToString. /// </summary> [Test] public void ValidateToString() { var b = new Multinomial(_smallP, 4); Assert.AreEqual("Multinomial(Dimension = 3, Number of Trails = 4)", b.ToString()); } /// <summary> /// Validate skewness. /// </summary> /// <param name="p">Proportion of ratios.</param> /// <param name="n">Number of trials.</param> /// <param name="res">Expected value.</param> [TestCase(new[] { 0.3, 0.7 }, 5, new[] { 0.390360029179413, -0.390360029179413 })] [TestCase(new[] { 0.1, 0.3, 0.6 }, 10, new[] { 0.843274042711568, 0.276026223736942, -0.129099444873581 })] [TestCase(new[] { 0.15, 0.35, 0.3, 0.2 }, 20, new[] { 0.438357003759605, 0.140642169281549, 0.195180014589707, 0.335410196624968 })] public void ValidateSkewness(double[] p, int n, double[] res) { var b = new Multinomial(p, n); for (var i = 0; i < b.P.Length; i++) { AssertHelpers.AlmostEqualRelative(res[i], b.Skewness[i], 12); } } /// <summary> /// Validate variance. /// </summary> /// <param name="p">Proportion of ratios.</param> /// <param name="n">Number of trials.</param> /// <param name="res">Expected value.</param> [TestCase(new[] { 0.3, 0.7 }, 5, new[] { 1.05, 1.05 })] [TestCase(new[] { 0.1, 0.3, 0.6 }, 10, new[] { 0.9, 2.1, 2.4 })] [TestCase(new[] { 0.15, 0.35, 0.3, 0.2 }, 20, new[] { 2.55, 4.55, 4.2, 3.2 })] public void ValidateVariance(double[] p, int n, double[] res) { var b = new Multinomial(p, n); for (var i = 0; i < b.P.Length; i++) { AssertHelpers.AlmostEqualRelative(res[i], b.Variance[i], 12); } } /// <summary> /// Validate mean. /// </summary> /// <param name="p">Proportion of ratios.</param> /// <param name="n">Number of trials.</param> /// <param name="res">Expected value.</param> [TestCase(new[] { 0.3, 0.7 }, 5, new[] { 1.5, 3.5 })] [TestCase(new[] { 0.1, 0.3, 0.6 }, 10, new[] { 1.0, 3.0, 6.0 })] [TestCase(new[] { 0.15, 0.35, 0.3, 0.2 }, 20, new[] { 3.0, 7.0, 6.0, 4.0 })] public void ValidateMean(double[] p, int n, double[] res) { var b = new Multinomial(p, n); for (var i = 0; i < b.P.Length; i++) { AssertHelpers.AlmostEqualRelative(res[i], b.Mean[i], 12); } } /// <summary> /// Validate probability. /// </summary> /// <param name="p">Proportion of ratios.</param> /// <param name="x">Input X value.</param> /// <param name="res">Expected value.</param> [TestCase(new[] { 0.3, 0.7 }, new[] { 1, 9 }, 0.121060821)] [TestCase(new[] { 0.1, 0.3, 0.6 }, new[] { 1, 3, 6 }, 0.105815808)] [TestCase(new[] { 0.15, 0.35, 0.3, 0.2 }, new[] { 1, 1, 1, 7 }, 0.000145152)] public void ValidateProbability(double[] p, int[] x, double res) { var b = new Multinomial(p, x.Sum()); AssertHelpers.AlmostEqualRelative(b.Probability(x), res, 12); } /// <summary> /// Validate probability log. /// </summary> /// <param name="x">Input X value.</param> [TestCase(new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 })] [TestCase(new[] { 1, 1, 1, 2, 2, 2, 3, 3, 3 })] [TestCase(new[] { 5, 6, 7, 8, 7, 6, 5, 4, 3 })] public void ValidateProbabilityLn(int[] x) { var b = new Multinomial(_largeP, x.Sum()); AssertHelpers.AlmostEqualRelative(b.ProbabilityLn(x), Math.Log(b.Probability(x)), 12); } /// <summary> /// Can sample static. /// </summary> [Test] public void CanSampleStatic() { Multinomial.Sample(new Random(0), _largeP, 4); } /// <summary> /// Sample static fails with bad parameters. /// </summary> [Test] public void FailSampleStatic() { Assert.That(() => Multinomial.Sample(new Random(0), _badP, 4), Throws.ArgumentException); } /// <summary> /// Can sample. /// </summary> [Test] public void CanSample() { var n = new Multinomial(_largeP, 4); n.Sample(); } } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections; using System.Data; using System.Data.OleDb; using OpenADK.Library; using OpenADK.Library.Infra; using OpenADK.Library.au.Student; using OpenADK.Library.Tools.Cfg; using OpenADK.Library.Tools.Mapping; using OpenADK.Util; using OpenADK.Library.au; /// <summary> The Mappings agent demonstrates how to respond to requests for LearnerPersonal /// by reading a list of students from a Microsoft Access database using JDBC, /// then using the ADK's Mappings class to convert the field data into /// LearnerPersonal objects. The mappings can be changed in the agent.cfg /// configuration file, which is read by the program at startup using the ADK's /// AgentConfig class. /// <p> /// * /// Before this agent can be used an ODBC data source must be created. On the /// Windows platform, open the ODBC Control Panel and create a new System DSN /// with the name "MappingsDemo". This DSN should point to the Microsoft Access /// database (Students.mdb) in this agent's directory. The JDBC-ODBC bridge is /// then used to read data from that data source. /// <p> /// * /// To register the agent as the provider of LearnerPersonal objects in one or /// more zones, open the agent.cfg file and provide zone connection parameters. /// Then run the agent to register in each zone as the provider of LearnerPersonal. /// Unlike the other ADK Example agents, this one reads all zone information and /// connection settings from the agent.cfg file to demonstrate the use of the /// AgentConfig class. /// <p> /// * /// </summary> /// <author> Data Solutions /// </author> /// <version> ADK 1.0 /// /// </version> public class MappingsDemo : Agent, IPublisher, IQueryResults { /// <summary>The configuration file /// </summary> internal AgentConfig fCfg; /// <summary>The SQL connection /// </summary> internal IDbConnection fConn; /// <summary> Constructor /// </summary> public MappingsDemo() : base( "MappingsDemo" ) { Name = "Library ADK Example"; } /// <summary> Initialize and start the agent /// </summary> /// <param name="args">Command-line arguments (run with no arguments to display help) /// /// </param> public virtual void startAgent( string[] args ) { Console.WriteLine( "Initializing agent..." ); Adk.Initialize( SifVersion.LATEST, SIFVariant.SIF_AU, (int)SdoLibraryType.Student ); // Read the configuration file fCfg = new AgentConfig(); Console.WriteLine( "Reading configuration file..." ); fCfg.Read( "agent.cfg", false ); // Override the SourceId passed to the constructor with the SourceId // specified in the configuration file Id = fCfg.SourceId; // Inform the ADK of the version of SIF specified in the sifVersion= // attribute of the <agent> element SifVersion version = fCfg.Version; Adk.SifVersion = version; // Now call the superclass initialize once the configuration file has been read base.Initialize(); // // Ask the AgentConfig instance to "apply" all configuration settings // to this Agent; for example, all <property> elements that are children // of the root <agent> node are parsed and applied to this Agent's // AgentProperties object; all <zone> elements are parsed and registered // with the Agent's ZoneFactory, and so on. // fCfg.Apply( this, true ); // Establish the ODBC connection to the Students.mdb database file. // The JDBC driver and URL are specified in the agent.cfg configuration // file and were automatically added to the AgentProperties when the // apply method was called above. // Console.WriteLine( "Opening database..." ); AgentProperties props = Properties; string driver = props.GetProperty( "Connection" ); string url = props.GetProperty( "ConnectionString" ); Console.WriteLine( "- Using driver: " + driver ); Console.WriteLine( "- Connecting to URL: " + url ); // Load the DataDriver driver // Get a Connection fConn = new OleDbConnection(); fConn.ConnectionString = url; // Connect to each zone specified in the configuration file, registering // this agent as the Provider of Learner objects. Once connected, // send a request for LearnerPersonal. // Console.WriteLine( "Connecting to zones and requesting LearnerPersonal objects..." ); IZone[] allZones = ZoneFactory.GetAllZones(); for ( int i = 0; i < allZones.Length; i++ ) { try { // Connect to this zone Console.WriteLine ( "- Connecting to zone \"" + allZones[i].ZoneId + "\" at " + allZones[i].ZoneUrl ); allZones[i].SetPublisher ( this, StudentDTD.STUDENTPERSONAL, new PublishingOptions() ); allZones[i].SetQueryResults( this ); allZones[i].Connect( ProvisioningFlags.Register ); // Request all students Query q = new Query( StudentDTD.STUDENTPERSONAL ); q.UserData = "Mappings Demo"; allZones[i].Query( q ); } catch ( AdkException ex ) { Console.WriteLine( " " + ex.Message ); } } } /// <summary> Respond to SIF Requests /// </summary> public virtual void OnRequest( IDataObjectOutputStream outStream, Query query, IZone zone, IMessageInfo inf ) { SifMessageInfo info = (SifMessageInfo) inf; SifWriter debug = new SifWriter( Console.Out ); Console.WriteLine ( "Received a request for " + query.ObjectTag + " from agent \"" + info.SourceId + "\" in zone " + zone.ZoneId ); // Tell the ADK to automatically filter out any objects that don't meet the requirements // of the query conditions outStream.Filter = query; // Read all learners from the database to populate a HashMap of // field/value pairs. The field names can be whatever we choose as long // as they match the field names used in the <mappings> section of the // agent.cfg configuration file. Each time a record is read, convert it // to a LearnerPersonal object using the Mappings class and stream it to // the supplied output stream. // IDictionary data = new Hashtable(); IDbCommand command = null; Console.WriteLine( "The SIF Request was requested in the following SIF Versions" ); foreach ( SifVersion version in info.SIFRequestVersions ) { Console.WriteLine( " - " + version ); } Console.WriteLine( "This agent will respond in its latest supported version, which is: " ); Console.WriteLine( " - " + info.LatestSIFRequestVersion ); // Get the root Mappings object from the configuration file Mappings m = fCfg.Mappings.GetMappings( "Default" ).Select ( info.SourceId, zone.ZoneId, info.LatestSIFRequestVersion ); // Ask the root Mappings instance to select a Mappings from its // hierarchy. For example, you might have customized the agent.cfg // file with mappings specific to zones, versions of SIF, or // requesting agents. The Mappings.selectOutbound() method will select // the most appropriate instance from the hierarchy given the // three parameters passed to it. MappingsContext mappings = m.SelectOutbound( StudentDTD.STUDENTPERSONAL, info ); try { int count = 0; // Query the database for all students command = fConn.CreateCommand(); fConn.Open(); command.CommandText = "SELECT * FROM Students"; using ( IDataReader rs = command.ExecuteReader( CommandBehavior.CloseConnection ) ) { DataReaderAdaptor dra = new DataReaderAdaptor( rs ); while ( rs.Read() ) { count++; // Finally, create a new LearnerPersonal object and ask the // Mappings to populate it with SIF elements from the HashMap // of field/value pairs. As long as there is an <object>/<field> // definition for each entry in the HashMap, the ADK will take // care of producing the appropriate SIF element/attribute in // the LearnerPersonal object. // StudentPersonal sp = new StudentPersonal(); sp.RefId = Adk.MakeGuid(); mappings.Map( sp, dra ); // Now write out the LearnerPersonal to the output stream and // we're done publishing this student. // Console.WriteLine( "\nThe agent has read these values from the database:" ); DumpDictionaryToConsole( data ); Console.WriteLine( "To produce this LearnerPersonal object:" ); debug.Write( sp ); debug.Flush(); outStream.Write( sp ); data.Clear(); } rs.Close(); } Console.WriteLine ( "- Returned " + count + " records from the Student database in response" ); } catch ( Exception ex ) { Console.WriteLine( "- Returning a SIF_Error response: " + ex.ToString() ); throw new SifException ( SifErrorCategoryCode.RequestResponse, SifErrorCodes.REQRSP_GENERIC_ERROR_1, "An error occurred while querying the database for students", ex.ToString(), zone ); } finally { if ( command != null ) { try { fConn.Close(); } catch ( Exception ignored ) { } } } } private void DumpDictionaryToConsole( IDictionary dictionary ) { foreach ( string key in dictionary.Keys ) { Console.WriteLine( " [{0}] = \"{1}\"", key, dictionary[key] ); } } /// <summary> Called by the ADK when a SIF_Request is successfully sent to a zone /// </summary> public virtual void OnQueryPending( IMessageInfo info, IZone zone ) { // Nothing to do. } /// <summary> Handles SIF_Responses /// </summary> public virtual void OnQueryResults( IDataObjectInputStream inStream, SIF_Error error, IZone zone, IMessageInfo inf ) { SifMessageInfo info = (SifMessageInfo) inf; Console.WriteLine ( "\nReceived a query response from agent \"" + info.SourceId + "\" in zone " + zone.ZoneId ); IRequestInfo reqInfo = info.SIFRequestInfo; if ( reqInfo != null ) { Console.WriteLine ( "\nResponse was received in {0}. Object State is '{1}'", DateTime.Now.Subtract( reqInfo.RequestTime ), reqInfo.UserData ); } // // Use the Mappings class to translate the LearnerPersonal objects received // from the zone into a HashMap of field/value pairs, then dump the table // to System.out // // Always check for an error response if ( error != null ) { Console.WriteLine ( "The request for LearnerPersonal failed with an error from the provider:" ); Console.WriteLine ( " [Category=" + error.SIF_Category + "; Code=" + error.SIF_Code + "]: " + error.SIF_Desc + ". " + error.SIF_ExtendedDesc ); return; } // Get the root Mappings object from the configuration file Mappings m = fCfg.Mappings.GetMappings( "Default" ); // Ask the root Mappings instance to select a Mappings from its // hierarchy. For example, you might have customized the agent.cfg // file with mappings specific to zones, versions of SIF, or // requesting agents. The Mappings.select() method will select // the most appropriate instance from the hierarchy given the // three parameters passed to it. MappingsContext mappings = m.SelectInbound( StudentDTD.STUDENTPERSONAL, info ); Hashtable data = new Hashtable(); StringMapAdaptor sma = new StringMapAdaptor( data, Adk.Dtd.GetFormatter( SifVersion.LATEST ) ); int count = 0; while ( inStream.Available ) { Console.WriteLine( "Object Number {0}", count++ ); StudentPersonal sp = (StudentPersonal) inStream.ReadDataObject(); // Ask the Mappings object to populate the dictionary with field/value pairs // by using the mapping rules in the configuration file to decompose // the LearnerPersonal object into field values. mappings.Map( sp, sma ); // Now dump the field/value pairs to System.out DumpDictionaryToConsole( data ); Console.WriteLine(); data.Clear(); } } public override void Shutdown( ProvisioningFlags provisioningOptions ) { if ( fConn != null && fConn.State != ConnectionState.Closed ) { fConn.Close(); } base.Shutdown( provisioningOptions ); } /// <summary> Runs the agent from the command-line. /// </summary> [STAThread] public static void Main( string[] args ) { MappingsDemo agent = null; try { // Pre-parse the command line before initializing the ADK Adk.Debug = AdkDebugFlags.Moderate; // Start agent... agent = new MappingsDemo(); agent.startAgent( args ); // Wait for Ctrl-C to be pressed Console.WriteLine(); Console.WriteLine( "Agent is running (Press Ctrl-C to stop)" ); Console.WriteLine(); // Install a shutdown hook to cleanup when Ctrl+C is pressed new AdkConsoleWait().WaitForExit(); agent.Shutdown( ProvisioningFlags.None ); } catch ( Exception e ) { Console.WriteLine( e ); } } }
using System.Drawing; using System.Windows.Forms; using OpenLiveWriter.Controls; using OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl; namespace OpenLiveWriter.PostEditor.PostPropertyEditing { partial class PostPropertiesBandControl { /// <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.table = new System.Windows.Forms.TableLayoutPanel(); this.labelPageOrder = new System.Windows.Forms.Label(); this.categoryDropDown = new OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl.CategoryDropDownControlM1(); this.textTags = new OpenLiveWriter.Controls.AutoCompleteTextbox(); this.datePublishDate = new OpenLiveWriter.PostEditor.PostPropertyEditing.PublishDateTimePicker(); this.labelPageParent = new System.Windows.Forms.Label(); this.comboPageParent = new OpenLiveWriter.PostEditor.PostPropertyEditing.PageParentComboBox(); this.textPageOrder = new OpenLiveWriter.Controls.NumericTextBox(); this.panelShadow = new System.Windows.Forms.Panel(); this.linkViewAll = new System.Windows.Forms.LinkLabel(); this.table.SuspendLayout(); this.SuspendLayout(); // // table // this.table.BackColor = System.Drawing.Color.Transparent; this.table.ColumnCount = 9; this.table.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.table.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.table.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.table.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.table.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.table.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.table.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.table.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.table.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.table.Controls.Add(this.categoryDropDown, 0, 0); this.table.Controls.Add(this.textTags, 1, 0); this.table.Controls.Add(this.datePublishDate, 2, 0); this.table.Controls.Add(this.labelPageParent, 3, 0); this.table.Controls.Add(this.comboPageParent, 4, 0); this.table.Controls.Add(this.labelPageOrder, 5, 0); this.table.Controls.Add(this.textPageOrder, 6, 0); this.table.Controls.Add(this.linkViewAll, 8, 0); this.table.Dock = System.Windows.Forms.DockStyle.Fill; this.table.Location = new System.Drawing.Point(0, 0); this.table.Name = "table"; this.table.Padding = new System.Windows.Forms.Padding(8, 0, 0, 0); this.table.RowCount = 1; this.table.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.table.Size = new System.Drawing.Size(1090, 41); this.table.TabIndex = 0; // // labelPageOrder // this.labelPageOrder.Anchor = System.Windows.Forms.AnchorStyles.None; this.labelPageOrder.AutoSize = true; this.labelPageOrder.Location = new System.Drawing.Point(753, 14); this.labelPageOrder.Margin = new System.Windows.Forms.Padding(0); this.labelPageOrder.Name = "labelPageOrder"; this.labelPageOrder.Size = new System.Drawing.Size(62, 13); this.labelPageOrder.TabIndex = 5; this.labelPageOrder.Text = "Page order:"; // // categoryDropDown // this.categoryDropDown.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.categoryDropDown.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.categoryDropDown.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.categoryDropDown.FormattingEnabled = true; this.categoryDropDown.IntegralHeight = false; this.categoryDropDown.Items.AddRange(new object[] { "", "", ""}); this.categoryDropDown.Location = new System.Drawing.Point(8, 10); this.categoryDropDown.Margin = new System.Windows.Forms.Padding(0, 0, 8, 0); this.categoryDropDown.Name = "categoryDropDown"; this.categoryDropDown.Size = new System.Drawing.Size(144, 21); this.categoryDropDown.TabIndex = 0; // // textTags // this.textTags.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.textTags.DefaultText = null; this.textTags.ForeColor = System.Drawing.SystemColors.GrayText; this.textTags.Location = new System.Drawing.Point(160, 10); this.textTags.Margin = new System.Windows.Forms.Padding(0, 0, 8, 0); this.textTags.Name = "textTags"; this.textTags.ShowButton = true; this.textTags.Size = new System.Drawing.Size(198, 20); this.textTags.TabIndex = 1; // // datePublishDate // this.datePublishDate.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); this.datePublishDate.Format = DateTimePickerFormat.Custom; this.datePublishDate.Location = new System.Drawing.Point(366, 10); this.datePublishDate.Margin = new System.Windows.Forms.Padding(0, 0, 8, 0); this.datePublishDate.Name = "datePublishDate"; this.datePublishDate.RightToLeftLayout = true; this.datePublishDate.ShowCheckBox = true; this.datePublishDate.Size = new System.Drawing.Size(182, 20); this.datePublishDate.TabIndex = 2; // // labelPageParent // this.labelPageParent.Anchor = System.Windows.Forms.AnchorStyles.None; this.labelPageParent.AutoSize = true; this.labelPageParent.Location = new System.Drawing.Point(556, 14); this.labelPageParent.Margin = new System.Windows.Forms.Padding(0); this.labelPageParent.Name = "labelPageParent"; this.labelPageParent.Size = new System.Drawing.Size(68, 13); this.labelPageParent.TabIndex = 3; this.labelPageParent.Text = "Page parent:"; // // comboPageParent // this.comboPageParent.Anchor = System.Windows.Forms.AnchorStyles.None; this.comboPageParent.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.comboPageParent.FormattingEnabled = true; this.comboPageParent.IntegralHeight = false; this.comboPageParent.Location = new System.Drawing.Point(624, 10); this.comboPageParent.Margin = new System.Windows.Forms.Padding(0, 0, 8, 0); this.comboPageParent.Name = "comboPageParent"; this.comboPageParent.Size = new System.Drawing.Size(121, 20); this.comboPageParent.TabIndex = 4; // // textPageOrder // this.textPageOrder.Anchor = System.Windows.Forms.AnchorStyles.None; this.textPageOrder.Location = new System.Drawing.Point(815, 10); this.textPageOrder.Margin = new System.Windows.Forms.Padding(0, 0, 8, 0); this.textPageOrder.Name = "textPageOrder"; this.textPageOrder.Size = new System.Drawing.Size(63, 20); this.textPageOrder.TabIndex = 6; // // panelShadow // this.panelShadow.BackColor = System.Drawing.Color.Transparent; this.panelShadow.Dock = System.Windows.Forms.DockStyle.Bottom; this.panelShadow.Location = new System.Drawing.Point(0, 41); this.panelShadow.Name = "panelShadow"; this.panelShadow.Size = new System.Drawing.Size(1090, 4); this.panelShadow.TabIndex = 1; // // linkViewAll // this.linkViewAll.ActiveLinkColor = Color.FromArgb(85, 142, 213); this.linkViewAll.Anchor = System.Windows.Forms.AnchorStyles.None; this.linkViewAll.AutoSize = true; this.linkViewAll.LinkBehavior = System.Windows.Forms.LinkBehavior.HoverUnderline; this.linkViewAll.LinkColor = Color.FromArgb(85, 142, 213); this.linkViewAll.Location = new System.Drawing.Point(1038, 14); this.linkViewAll.Margin = new System.Windows.Forms.Padding(0, 0, 8, 0); this.linkViewAll.Name = "linkViewAll"; this.linkViewAll.Size = new System.Drawing.Size(43, 13); this.linkViewAll.TabIndex = 7; this.linkViewAll.TabStop = true; this.linkViewAll.Text = "View all"; this.linkViewAll.VisitedLinkColor = Color.FromArgb(85, 142, 213); this.linkViewAll.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkViewAll_LinkClicked); // // PostPropertiesBandControl // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.table); this.Controls.Add(this.panelShadow); this.Name = "PostPropertiesBandControl"; this.Size = new System.Drawing.Size(1090, 45); this.table.ResumeLayout(false); this.table.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel table; private CategoryDropDownControlM1 categoryDropDown; private AutoCompleteTextbox textTags; private System.Windows.Forms.Label labelPageOrder; private PublishDateTimePicker datePublishDate; private System.Windows.Forms.Label labelPageParent; private PageParentComboBox comboPageParent; private NumericTextBox textPageOrder; private Panel panelShadow; private LinkLabel linkViewAll; } }
namespace Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs { partial class OptionFieldDefinition { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OptionFieldDefinition)); this.label2 = new System.Windows.Forms.Label(); this.numUpDown = new System.Windows.Forms.NumericUpDown(); this.optionGroupBox = new System.Windows.Forms.GroupBox(); this.textBoxForPositioning = new System.Windows.Forms.TextBox(); this.radioButtonForPositioning = new System.Windows.Forms.RadioButton(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.textOnRight = new System.Windows.Forms.RadioButton(); this.textOnLeft = new System.Windows.Forms.RadioButton(); this.label3 = new System.Windows.Forms.Label(); this.groupBoxVerticalHorizontal = new System.Windows.Forms.GroupBox(); this.radioButtonHorizontal = new System.Windows.Forms.RadioButton(); this.radioButtonVertical = new System.Windows.Forms.RadioButton(); this.groupBoxLeftRight = new System.Windows.Forms.GroupBox(); this.radioButtonStartOnLeft = new System.Windows.Forms.RadioButton(); this.radioButtonStartOnRight = new System.Windows.Forms.RadioButton(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.numUpDown)).BeginInit(); this.optionGroupBox.SuspendLayout(); this.groupBoxVerticalHorizontal.SuspendLayout(); this.groupBoxLeftRight.SuspendLayout(); this.SuspendLayout(); // // label1 // resources.ApplyResources(this.label1, "label1"); // // txtPrompt // resources.ApplyResources(this.txtPrompt, "txtPrompt"); this.txtPrompt.TextChanged += new System.EventHandler(this.txtPrompt_TextChanged); // // lblPrompt // resources.ApplyResources(this.lblPrompt, "lblPrompt"); // // txtFieldName // resources.ApplyResources(this.txtFieldName, "txtFieldName"); this.txtFieldName.TextChanged += new System.EventHandler(this.txtFieldName_TextChanged); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // btnOk // resources.ApplyResources(this.btnOk, "btnOk"); this.btnOk.Click += new System.EventHandler(this.btnOk_Click); // // groupBox1 // resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.textOnLeft); this.groupBox1.Controls.Add(this.textOnRight); this.groupBox1.Controls.Add(this.numUpDown); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.SetChildIndex(this.label2, 0); this.groupBox1.Controls.SetChildIndex(this.numUpDown, 0); this.groupBox1.Controls.SetChildIndex(this.textOnRight, 0); this.groupBox1.Controls.SetChildIndex(this.btnPromptFont, 0); this.groupBox1.Controls.SetChildIndex(this.textOnLeft, 0); this.groupBox1.Controls.SetChildIndex(this.label3, 0); this.groupBox1.Controls.SetChildIndex(this.btnFieldFont, 0); // // btnPromptFont // resources.ApplyResources(this.btnPromptFont, "btnPromptFont"); // // btnFieldFont // resources.ApplyResources(this.btnFieldFont, "btnFieldFont"); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); this.baseImageList.Images.SetKeyName(76, ""); this.baseImageList.Images.SetKeyName(77, ""); this.baseImageList.Images.SetKeyName(78, ""); this.baseImageList.Images.SetKeyName(79, ""); this.baseImageList.Images.SetKeyName(80, ""); this.baseImageList.Images.SetKeyName(81, ""); this.baseImageList.Images.SetKeyName(82, ""); this.baseImageList.Images.SetKeyName(83, ""); this.baseImageList.Images.SetKeyName(84, ""); this.baseImageList.Images.SetKeyName(85, ""); this.baseImageList.Images.SetKeyName(86, ""); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // numUpDown // resources.ApplyResources(this.numUpDown, "numUpDown"); this.numUpDown.Maximum = new decimal(new int[] { 16, 0, 0, 0}); this.numUpDown.Minimum = new decimal(new int[] { 2, 0, 0, 0}); this.numUpDown.Name = "numUpDown"; this.toolTip1.SetToolTip(this.numUpDown, resources.GetString("numUpDown.ToolTip")); this.numUpDown.Value = new decimal(new int[] { 2, 0, 0, 0}); this.numUpDown.ValueChanged += new System.EventHandler(this.numUpDown_ValueChanged); // // optionGroupBox // resources.ApplyResources(this.optionGroupBox, "optionGroupBox"); this.optionGroupBox.Controls.Add(this.textBoxForPositioning); this.optionGroupBox.Controls.Add(this.radioButtonForPositioning); this.optionGroupBox.Name = "optionGroupBox"; this.optionGroupBox.TabStop = false; // // textBoxForPositioning // resources.ApplyResources(this.textBoxForPositioning, "textBoxForPositioning"); this.textBoxForPositioning.Name = "textBoxForPositioning"; // // radioButtonForPositioning // resources.ApplyResources(this.radioButtonForPositioning, "radioButtonForPositioning"); this.radioButtonForPositioning.Name = "radioButtonForPositioning"; this.radioButtonForPositioning.TabStop = true; this.radioButtonForPositioning.UseVisualStyleBackColor = true; // // toolTip1 // this.toolTip1.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info; // // textOnRight // resources.ApplyResources(this.textOnRight, "textOnRight"); this.textOnRight.Name = "textOnRight"; this.textOnRight.TabStop = true; this.textOnRight.UseVisualStyleBackColor = true; this.textOnRight.CheckedChanged += new System.EventHandler(this.textOnRight_CheckedChanged); // // textOnLeft // resources.ApplyResources(this.textOnLeft, "textOnLeft"); this.textOnLeft.Name = "textOnLeft"; this.textOnLeft.TabStop = true; this.textOnLeft.UseVisualStyleBackColor = true; this.textOnLeft.CheckedChanged += new System.EventHandler(this.textOnLeft_CheckedChanged); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // groupBoxVerticalHorizontal // resources.ApplyResources(this.groupBoxVerticalHorizontal, "groupBoxVerticalHorizontal"); this.groupBoxVerticalHorizontal.Controls.Add(this.radioButtonHorizontal); this.groupBoxVerticalHorizontal.Controls.Add(this.radioButtonVertical); this.groupBoxVerticalHorizontal.Name = "groupBoxVerticalHorizontal"; this.groupBoxVerticalHorizontal.TabStop = false; // // radioButtonHorizontal // resources.ApplyResources(this.radioButtonHorizontal, "radioButtonHorizontal"); this.radioButtonHorizontal.Name = "radioButtonHorizontal"; this.radioButtonHorizontal.TabStop = true; this.radioButtonHorizontal.UseVisualStyleBackColor = true; // // radioButtonVertical // resources.ApplyResources(this.radioButtonVertical, "radioButtonVertical"); this.radioButtonVertical.Name = "radioButtonVertical"; this.radioButtonVertical.TabStop = true; this.radioButtonVertical.UseVisualStyleBackColor = true; // // groupBoxLeftRight // resources.ApplyResources(this.groupBoxLeftRight, "groupBoxLeftRight"); this.groupBoxLeftRight.Controls.Add(this.radioButtonStartOnLeft); this.groupBoxLeftRight.Controls.Add(this.radioButtonStartOnRight); this.groupBoxLeftRight.Name = "groupBoxLeftRight"; this.groupBoxLeftRight.TabStop = false; // // radioButtonStartOnLeft // resources.ApplyResources(this.radioButtonStartOnLeft, "radioButtonStartOnLeft"); this.radioButtonStartOnLeft.Name = "radioButtonStartOnLeft"; this.radioButtonStartOnLeft.TabStop = true; this.radioButtonStartOnLeft.UseVisualStyleBackColor = true; // // radioButtonStartOnRight // resources.ApplyResources(this.radioButtonStartOnRight, "radioButtonStartOnRight"); this.radioButtonStartOnRight.Name = "radioButtonStartOnRight"; this.radioButtonStartOnRight.TabStop = true; this.radioButtonStartOnRight.UseVisualStyleBackColor = true; // // OptionFieldDefinition // resources.ApplyResources(this, "$this"); this.Controls.Add(this.groupBoxLeftRight); this.Controls.Add(this.groupBoxVerticalHorizontal); this.Controls.Add(this.optionGroupBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "OptionFieldDefinition"; this.ShowInTaskbar = false; this.Controls.SetChildIndex(this.groupBox1, 0); this.Controls.SetChildIndex(this.txtPrompt, 0); this.Controls.SetChildIndex(this.btnCancel, 0); this.Controls.SetChildIndex(this.lblPrompt, 0); this.Controls.SetChildIndex(this.btnOk, 0); this.Controls.SetChildIndex(this.txtFieldName, 0); this.Controls.SetChildIndex(this.label1, 0); this.Controls.SetChildIndex(this.optionGroupBox, 0); this.Controls.SetChildIndex(this.groupBoxVerticalHorizontal, 0); this.Controls.SetChildIndex(this.groupBoxLeftRight, 0); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.numUpDown)).EndInit(); this.optionGroupBox.ResumeLayout(false); this.optionGroupBox.PerformLayout(); this.groupBoxVerticalHorizontal.ResumeLayout(false); this.groupBoxVerticalHorizontal.PerformLayout(); this.groupBoxLeftRight.ResumeLayout(false); this.groupBoxLeftRight.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown numUpDown; private System.Windows.Forms.GroupBox optionGroupBox; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.RadioButton textOnRight; private System.Windows.Forms.RadioButton textOnLeft; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBoxForPositioning; private System.Windows.Forms.RadioButton radioButtonForPositioning; private System.Windows.Forms.GroupBox groupBoxVerticalHorizontal; private System.Windows.Forms.RadioButton radioButtonHorizontal; private System.Windows.Forms.RadioButton radioButtonVertical; private System.Windows.Forms.GroupBox groupBoxLeftRight; private System.Windows.Forms.RadioButton radioButtonStartOnLeft; private System.Windows.Forms.RadioButton radioButtonStartOnRight; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Protos.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Proto.Remote { /// <summary>Holder for reflection information generated from Protos.proto</summary> public static partial class ProtosReflection { #region Descriptor /// <summary>File descriptor for Protos.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ProtosReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CgxQcm90b3MucHJvdG8SBnJlbW90ZRoYUHJvdG8uQWN0b3IvcHJvdG9zLnBy", "b3RvImQKDE1lc3NhZ2VCYXRjaBISCgp0eXBlX25hbWVzGAEgAygJEhQKDHRh", "cmdldF9uYW1lcxgCIAMoCRIqCgllbnZlbG9wZXMYAyADKAsyFy5yZW1vdGUu", "TWVzc2FnZUVudmVsb3BlInsKD01lc3NhZ2VFbnZlbG9wZRIPCgd0eXBlX2lk", "GAEgASgFEhQKDG1lc3NhZ2VfZGF0YRgCIAEoDBIOCgZ0YXJnZXQYAyABKAUS", "GgoGc2VuZGVyGAQgASgLMgouYWN0b3IuUElEEhUKDXNlcmlhbGl6ZXJfaWQY", "BSABKAUiLQoPQWN0b3JQaWRSZXF1ZXN0EgwKBG5hbWUYASABKAkSDAoEa2lu", "ZBgCIAEoCSIrChBBY3RvclBpZFJlc3BvbnNlEhcKA3BpZBgBIAEoCzIKLmFj", "dG9yLlBJRCIGCgRVbml0IhAKDkNvbm5lY3RSZXF1ZXN0IjAKD0Nvbm5lY3RS", "ZXNwb25zZRIdChVkZWZhdWx0X3NlcmlhbGl6ZXJfaWQYASABKAUyfQoIUmVt", "b3RpbmcSPAoHQ29ubmVjdBIWLnJlbW90ZS5Db25uZWN0UmVxdWVzdBoXLnJl", "bW90ZS5Db25uZWN0UmVzcG9uc2UiABIzCgdSZWNlaXZlEhQucmVtb3RlLk1l", "c3NhZ2VCYXRjaBoMLnJlbW90ZS5Vbml0IgAoATABQg+qAgxQcm90by5SZW1v", "dGViBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Proto.ProtosReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Remote.MessageBatch), global::Proto.Remote.MessageBatch.Parser, new[]{ "TypeNames", "TargetNames", "Envelopes" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Remote.MessageEnvelope), global::Proto.Remote.MessageEnvelope.Parser, new[]{ "TypeId", "MessageData", "Target", "Sender", "SerializerId" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Remote.ActorPidRequest), global::Proto.Remote.ActorPidRequest.Parser, new[]{ "Name", "Kind" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Remote.ActorPidResponse), global::Proto.Remote.ActorPidResponse.Parser, new[]{ "Pid" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Remote.Unit), global::Proto.Remote.Unit.Parser, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Remote.ConnectRequest), global::Proto.Remote.ConnectRequest.Parser, null, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Proto.Remote.ConnectResponse), global::Proto.Remote.ConnectResponse.Parser, new[]{ "DefaultSerializerId" }, null, null, null) })); } #endregion } #region Messages public sealed partial class MessageBatch : pb::IMessage<MessageBatch> { private static readonly pb::MessageParser<MessageBatch> _parser = new pb::MessageParser<MessageBatch>(() => new MessageBatch()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MessageBatch> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Proto.Remote.ProtosReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MessageBatch() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MessageBatch(MessageBatch other) : this() { typeNames_ = other.typeNames_.Clone(); targetNames_ = other.targetNames_.Clone(); envelopes_ = other.envelopes_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MessageBatch Clone() { return new MessageBatch(this); } /// <summary>Field number for the "type_names" field.</summary> public const int TypeNamesFieldNumber = 1; private static readonly pb::FieldCodec<string> _repeated_typeNames_codec = pb::FieldCodec.ForString(10); private readonly pbc::RepeatedField<string> typeNames_ = new pbc::RepeatedField<string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> TypeNames { get { return typeNames_; } } /// <summary>Field number for the "target_names" field.</summary> public const int TargetNamesFieldNumber = 2; private static readonly pb::FieldCodec<string> _repeated_targetNames_codec = pb::FieldCodec.ForString(18); private readonly pbc::RepeatedField<string> targetNames_ = new pbc::RepeatedField<string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> TargetNames { get { return targetNames_; } } /// <summary>Field number for the "envelopes" field.</summary> public const int EnvelopesFieldNumber = 3; private static readonly pb::FieldCodec<global::Proto.Remote.MessageEnvelope> _repeated_envelopes_codec = pb::FieldCodec.ForMessage(26, global::Proto.Remote.MessageEnvelope.Parser); private readonly pbc::RepeatedField<global::Proto.Remote.MessageEnvelope> envelopes_ = new pbc::RepeatedField<global::Proto.Remote.MessageEnvelope>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Proto.Remote.MessageEnvelope> Envelopes { get { return envelopes_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MessageBatch); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MessageBatch other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!typeNames_.Equals(other.typeNames_)) return false; if(!targetNames_.Equals(other.targetNames_)) return false; if(!envelopes_.Equals(other.envelopes_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= typeNames_.GetHashCode(); hash ^= targetNames_.GetHashCode(); hash ^= envelopes_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { typeNames_.WriteTo(output, _repeated_typeNames_codec); targetNames_.WriteTo(output, _repeated_targetNames_codec); envelopes_.WriteTo(output, _repeated_envelopes_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += typeNames_.CalculateSize(_repeated_typeNames_codec); size += targetNames_.CalculateSize(_repeated_targetNames_codec); size += envelopes_.CalculateSize(_repeated_envelopes_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MessageBatch other) { if (other == null) { return; } typeNames_.Add(other.typeNames_); targetNames_.Add(other.targetNames_); envelopes_.Add(other.envelopes_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { typeNames_.AddEntriesFrom(input, _repeated_typeNames_codec); break; } case 18: { targetNames_.AddEntriesFrom(input, _repeated_targetNames_codec); break; } case 26: { envelopes_.AddEntriesFrom(input, _repeated_envelopes_codec); break; } } } } } public sealed partial class MessageEnvelope : pb::IMessage<MessageEnvelope> { private static readonly pb::MessageParser<MessageEnvelope> _parser = new pb::MessageParser<MessageEnvelope>(() => new MessageEnvelope()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<MessageEnvelope> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Proto.Remote.ProtosReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MessageEnvelope() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MessageEnvelope(MessageEnvelope other) : this() { typeId_ = other.typeId_; messageData_ = other.messageData_; target_ = other.target_; Sender = other.sender_ != null ? other.Sender.Clone() : null; serializerId_ = other.serializerId_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public MessageEnvelope Clone() { return new MessageEnvelope(this); } /// <summary>Field number for the "type_id" field.</summary> public const int TypeIdFieldNumber = 1; private int typeId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int TypeId { get { return typeId_; } set { typeId_ = value; } } /// <summary>Field number for the "message_data" field.</summary> public const int MessageDataFieldNumber = 2; private pb::ByteString messageData_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString MessageData { get { return messageData_; } set { messageData_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "target" field.</summary> public const int TargetFieldNumber = 3; private int target_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Target { get { return target_; } set { target_ = value; } } /// <summary>Field number for the "sender" field.</summary> public const int SenderFieldNumber = 4; private global::Proto.PID sender_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Proto.PID Sender { get { return sender_; } set { sender_ = value; } } /// <summary>Field number for the "serializer_id" field.</summary> public const int SerializerIdFieldNumber = 5; private int serializerId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int SerializerId { get { return serializerId_; } set { serializerId_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as MessageEnvelope); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(MessageEnvelope other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (TypeId != other.TypeId) return false; if (MessageData != other.MessageData) return false; if (Target != other.Target) return false; if (!object.Equals(Sender, other.Sender)) return false; if (SerializerId != other.SerializerId) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (TypeId != 0) hash ^= TypeId.GetHashCode(); if (MessageData.Length != 0) hash ^= MessageData.GetHashCode(); if (Target != 0) hash ^= Target.GetHashCode(); if (sender_ != null) hash ^= Sender.GetHashCode(); if (SerializerId != 0) hash ^= SerializerId.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (TypeId != 0) { output.WriteRawTag(8); output.WriteInt32(TypeId); } if (MessageData.Length != 0) { output.WriteRawTag(18); output.WriteBytes(MessageData); } if (Target != 0) { output.WriteRawTag(24); output.WriteInt32(Target); } if (sender_ != null) { output.WriteRawTag(34); output.WriteMessage(Sender); } if (SerializerId != 0) { output.WriteRawTag(40); output.WriteInt32(SerializerId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (TypeId != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(TypeId); } if (MessageData.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(MessageData); } if (Target != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Target); } if (sender_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Sender); } if (SerializerId != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(SerializerId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(MessageEnvelope other) { if (other == null) { return; } if (other.TypeId != 0) { TypeId = other.TypeId; } if (other.MessageData.Length != 0) { MessageData = other.MessageData; } if (other.Target != 0) { Target = other.Target; } if (other.sender_ != null) { if (sender_ == null) { sender_ = new global::Proto.PID(); } Sender.MergeFrom(other.Sender); } if (other.SerializerId != 0) { SerializerId = other.SerializerId; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { TypeId = input.ReadInt32(); break; } case 18: { MessageData = input.ReadBytes(); break; } case 24: { Target = input.ReadInt32(); break; } case 34: { if (sender_ == null) { sender_ = new global::Proto.PID(); } input.ReadMessage(sender_); break; } case 40: { SerializerId = input.ReadInt32(); break; } } } } } public sealed partial class ActorPidRequest : pb::IMessage<ActorPidRequest> { private static readonly pb::MessageParser<ActorPidRequest> _parser = new pb::MessageParser<ActorPidRequest>(() => new ActorPidRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ActorPidRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Proto.Remote.ProtosReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorPidRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorPidRequest(ActorPidRequest other) : this() { name_ = other.name_; kind_ = other.kind_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorPidRequest Clone() { return new ActorPidRequest(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "kind" field.</summary> public const int KindFieldNumber = 2; private string kind_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Kind { get { return kind_; } set { kind_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ActorPidRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ActorPidRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Kind != other.Kind) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Kind.Length != 0) hash ^= Kind.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Kind.Length != 0) { output.WriteRawTag(18); output.WriteString(Kind); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Kind.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Kind); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ActorPidRequest other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Kind.Length != 0) { Kind = other.Kind; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { Kind = input.ReadString(); break; } } } } } public sealed partial class ActorPidResponse : pb::IMessage<ActorPidResponse> { private static readonly pb::MessageParser<ActorPidResponse> _parser = new pb::MessageParser<ActorPidResponse>(() => new ActorPidResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ActorPidResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Proto.Remote.ProtosReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorPidResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorPidResponse(ActorPidResponse other) : this() { Pid = other.pid_ != null ? other.Pid.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ActorPidResponse Clone() { return new ActorPidResponse(this); } /// <summary>Field number for the "pid" field.</summary> public const int PidFieldNumber = 1; private global::Proto.PID pid_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Proto.PID Pid { get { return pid_; } set { pid_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ActorPidResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ActorPidResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Pid, other.Pid)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (pid_ != null) hash ^= Pid.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (pid_ != null) { output.WriteRawTag(10); output.WriteMessage(Pid); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (pid_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Pid); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ActorPidResponse other) { if (other == null) { return; } if (other.pid_ != null) { if (pid_ == null) { pid_ = new global::Proto.PID(); } Pid.MergeFrom(other.Pid); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (pid_ == null) { pid_ = new global::Proto.PID(); } input.ReadMessage(pid_); break; } } } } } public sealed partial class Unit : pb::IMessage<Unit> { private static readonly pb::MessageParser<Unit> _parser = new pb::MessageParser<Unit>(() => new Unit()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Unit> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Proto.Remote.ProtosReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Unit() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Unit(Unit other) : this() { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Unit Clone() { return new Unit(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Unit); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Unit other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Unit other) { if (other == null) { return; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } } public sealed partial class ConnectRequest : pb::IMessage<ConnectRequest> { private static readonly pb::MessageParser<ConnectRequest> _parser = new pb::MessageParser<ConnectRequest>(() => new ConnectRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ConnectRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Proto.Remote.ProtosReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConnectRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConnectRequest(ConnectRequest other) : this() { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConnectRequest Clone() { return new ConnectRequest(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ConnectRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ConnectRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ConnectRequest other) { if (other == null) { return; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; } } } } public sealed partial class ConnectResponse : pb::IMessage<ConnectResponse> { private static readonly pb::MessageParser<ConnectResponse> _parser = new pb::MessageParser<ConnectResponse>(() => new ConnectResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ConnectResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Proto.Remote.ProtosReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConnectResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConnectResponse(ConnectResponse other) : this() { defaultSerializerId_ = other.defaultSerializerId_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ConnectResponse Clone() { return new ConnectResponse(this); } /// <summary>Field number for the "default_serializer_id" field.</summary> public const int DefaultSerializerIdFieldNumber = 1; private int defaultSerializerId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int DefaultSerializerId { get { return defaultSerializerId_; } set { defaultSerializerId_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ConnectResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ConnectResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (DefaultSerializerId != other.DefaultSerializerId) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (DefaultSerializerId != 0) hash ^= DefaultSerializerId.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (DefaultSerializerId != 0) { output.WriteRawTag(8); output.WriteInt32(DefaultSerializerId); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (DefaultSerializerId != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(DefaultSerializerId); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ConnectResponse other) { if (other == null) { return; } if (other.DefaultSerializerId != 0) { DefaultSerializerId = other.DefaultSerializerId; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { DefaultSerializerId = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
// --------------------------------------------------------------------------- // <copyright file="ExtendedProperty.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the ExtendedProperty class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <summary> /// Represents an extended property. /// </summary> public sealed class ExtendedProperty : ComplexProperty { private ExtendedPropertyDefinition propertyDefinition; private object value; /// <summary> /// Initializes a new instance of the <see cref="ExtendedProperty"/> class. /// </summary> internal ExtendedProperty() { } /// <summary> /// Initializes a new instance of the <see cref="ExtendedProperty"/> class. /// </summary> /// <param name="propertyDefinition">The definition of the extended property.</param> internal ExtendedProperty(ExtendedPropertyDefinition propertyDefinition) : this() { EwsUtilities.ValidateParam(propertyDefinition, "propertyDefinition"); this.propertyDefinition = propertyDefinition; } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.ExtendedFieldURI: this.propertyDefinition = new ExtendedPropertyDefinition(); this.propertyDefinition.LoadFromXml(reader); return true; case XmlElementNames.Value: EwsUtilities.Assert( this.PropertyDefinition != null, "ExtendedProperty.TryReadElementFromXml", "PropertyDefintion is missing"); string stringValue = reader.ReadElementValue(); this.value = MapiTypeConverter.ConvertToValue(this.PropertyDefinition.MapiType, stringValue); return true; case XmlElementNames.Values: EwsUtilities.Assert( this.PropertyDefinition != null, "ExtendedProperty.TryReadElementFromXml", "PropertyDefintion is missing"); StringList stringList = new StringList(XmlElementNames.Value); stringList.LoadFromXml(reader, reader.LocalName); this.value = MapiTypeConverter.ConvertToValue(this.PropertyDefinition.MapiType, stringList); return true; default: return false; } } /// <summary> /// Loads from json. /// </summary> /// <param name="jsonProperty">The json property.</param> /// <param name="service">The service.</param> internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service) { foreach (string key in jsonProperty.Keys) { switch (key) { case XmlElementNames.ExtendedFieldURI: this.propertyDefinition = new ExtendedPropertyDefinition(); this.propertyDefinition.LoadFromJson(jsonProperty.ReadAsJsonObject(key)); break; case XmlElementNames.Value: EwsUtilities.Assert( this.PropertyDefinition != null, "ExtendedProperty.TryReadElementFromXml", "PropertyDefintion is missing"); string stringValue = jsonProperty.ReadAsString(key); this.value = MapiTypeConverter.ConvertToValue(this.PropertyDefinition.MapiType, stringValue); break; case XmlElementNames.Values: EwsUtilities.Assert( this.PropertyDefinition != null, "ExtendedProperty.TryReadElementFromXml", "PropertyDefintion is missing"); StringList stringList = new StringList(XmlElementNames.Value); ((IJsonCollectionDeserializer)stringList).CreateFromJsonCollection(jsonProperty.ReadAsArray(key), service); this.value = MapiTypeConverter.ConvertToValue(this.PropertyDefinition.MapiType, stringList); break; default: break; } } } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { this.PropertyDefinition.WriteToXml(writer); if (MapiTypeConverter.IsArrayType(this.PropertyDefinition.MapiType)) { Array array = this.Value as Array; writer.WriteStartElement(XmlNamespace.Types, XmlElementNames.Values); for (int index = array.GetLowerBound(0); index <= array.GetUpperBound(0); index++) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Value, MapiTypeConverter.ConvertToString(this.PropertyDefinition.MapiType, array.GetValue(index))); } writer.WriteEndElement(); } else { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.Value, MapiTypeConverter.ConvertToString(this.PropertyDefinition.MapiType, this.Value)); } } /// <summary> /// Serializes the property to a Json value. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> internal override object InternalToJson(ExchangeService service) { JsonObject jsonExtendedProp = new JsonObject(); JsonObject jsonExtendedFieldUri = new JsonObject(); this.PropertyDefinition.AddJsonProperties(jsonExtendedFieldUri, service); jsonExtendedProp.Add(XmlElementNames.ExtendedFieldURI, jsonExtendedFieldUri); if (MapiTypeConverter.IsArrayType(this.PropertyDefinition.MapiType)) { List<object> values = new List<object>(); foreach (object value in this.Value as Array) { values.Add(MapiTypeConverter.ConvertToString(this.PropertyDefinition.MapiType, value)); } jsonExtendedProp.Add(XmlElementNames.Values, values.ToArray()); } else { jsonExtendedProp.Add( XmlElementNames.Value, MapiTypeConverter.ConvertToString(this.PropertyDefinition.MapiType, this.Value)); } return jsonExtendedProp; } /// <summary> /// Gets the definition of the extended property. /// </summary> public ExtendedPropertyDefinition PropertyDefinition { get { return this.propertyDefinition; } } /// <summary> /// Gets or sets the value of the extended property. /// </summary> public object Value { get { return this.value; } set { EwsUtilities.ValidateParam(value, "value"); this.SetFieldValue<object>( ref this.value, MapiTypeConverter.ChangeType(this.PropertyDefinition.MapiType, value)); } } /// <summary> /// Gets the string value. /// </summary> /// <returns>Value as string.</returns> private string GetStringValue() { if (MapiTypeConverter.IsArrayType(this.PropertyDefinition.MapiType)) { Array array = this.Value as Array; if (array == null) { return string.Empty; } else { StringBuilder sb = new StringBuilder(); sb.Append("["); for (int index = array.GetLowerBound(0); index <= array.GetUpperBound(0); index++) { sb.Append( MapiTypeConverter.ConvertToString( this.PropertyDefinition.MapiType, array.GetValue(index))); sb.Append(","); } sb.Append("]"); return sb.ToString(); } } else { return MapiTypeConverter.ConvertToString(this.PropertyDefinition.MapiType, this.Value); } } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception> public override bool Equals(object obj) { ExtendedProperty other = obj as ExtendedProperty; if ((other != null) && other.PropertyDefinition.Equals(this.PropertyDefinition)) { return this.GetStringValue().Equals(other.GetStringValue()); } else { return false; } } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return string.Concat( (this.PropertyDefinition != null) ? this.PropertyDefinition.GetPrintableName() : string.Empty, this.GetStringValue()).GetHashCode(); } } }
using System; using System.IO; using NUnit.Framework; using MongoDB; namespace MongoDB.GridFS { [TestFixture] public class GridFileStreamTest : GridTestBase { GridFile fs; String filesystem = "gfstream"; public override string TestFileSystems { get { return filesystem; } } public override void OnInit (){ fs = new GridFile(DB, filesystem); } [Test] public void TestWrite(){ GridFileStream gfs = fs.Create("test.txt"); Object id = gfs.GridFileInfo.Id; for(byte b = (byte)0; b < 128; b++){ gfs.WriteByte(b); } gfs.Close(); Assert.AreEqual(1, CountChunks(filesystem,id)); Document chunk = GrabChunk(id, 0); Binary bin = (Binary)chunk["data"]; Assert.AreEqual(127, bin.Bytes[127]); Assert.AreEqual(0, bin.Bytes[0]); } [Test] public void TestWriteMultipleBytes(){ GridFileStream gfs = fs.Create("multiplebytes.txt"); Object id = gfs.GridFileInfo.Id; for(int x = 0; x < 256; x++){ gfs.Write(BitConverter.GetBytes(x),0,4); } gfs.Close(); Assert.AreEqual(1, CountChunks(filesystem,id)); } [Test] public void TestWriteTo3Chunks(){ GridFileStream gfs = fs.Create("largewrite.txt"); Object id = gfs.GridFileInfo.Id; int chunks = 3; int buffsize = 256 * 1024 * chunks; Byte[] buff = CreateBuffer(buffsize, (byte)6); gfs.Write(buff,0,buff.Length); Assert.AreEqual(buff.Length, gfs.Position); gfs.Close(); Assert.AreEqual(chunks, CountChunks(filesystem,id)); } [Test] public void TestWriteWithMultipleFlushes(){ string filename = "multiflush.txt"; GridFileStream gfs = fs.Create(filename); Object id = gfs.GridFileInfo.Id; int size = gfs.GridFileInfo.ChunkSize * 2; byte[] buff; int x = 0; for(int i = 0; i < size; i+=4){ buff = BitConverter.GetBytes(x); gfs.Write(buff,0,buff.Length); x++; if(i % size/4 == 0){ gfs.Flush(); } } gfs.Close(); gfs = fs.OpenRead(filename); int read; int val; buff = new byte[4]; for(int i = 0; i < size/4; i++){ read = gfs.Read(buff,0,4); val = BitConverter.ToInt32(buff, 0); Assert.AreEqual(4, read, "Not enough bytes were read. Pos: " + gfs.Position); Assert.AreEqual(i,val, "value read back was not the same as written. Pos: " + gfs.Position); } } [Test] public void TestWriteMultipleBytesWithOffset(){ String filename = "multioffset.txt"; int offset = 4; int chunks = 2; int chunksize = 100; int size = chunks * chunksize; Object id = CreateDummyFile(filename, size, chunksize, offset); Assert.AreEqual(2, CountChunks(filesystem,id)); GridFileStream gfs = fs.OpenRead(filename); byte[] buff = new Byte[4]; int read; int val; for(int i = 1; i <= size/4 - offset; i++){ read = gfs.Read(buff,0,4); val = BitConverter.ToInt32(buff, 0); Assert.AreEqual(4, read, "Not enough bytes were read. Pos: " + gfs.Position); Assert.AreEqual(i,val, "value read back was not the same as written. Pos: " + gfs.Position); } } [Test] public void TestNonSequentialWriteToOneChunk(){ string filename = "nonsequential1.txt"; GridFileStream gfs = fs.Create(filename); Object id = gfs.GridFileInfo.Id; int chunksize = gfs.GridFileInfo.ChunkSize; gfs.Seek(chunksize/2, SeekOrigin.Begin); byte[] two = new byte[]{2}; for(int i = chunksize; i > chunksize/2; i--){ gfs.Write(two, 0, 1); } gfs.Seek(0, SeekOrigin.Begin); byte[] one = new byte[]{1}; for(int i = 0; i < chunksize/2; i++){ gfs.Write(one, 0, 1); } gfs.Close(); Assert.AreEqual(1, CountChunks(filesystem,id)); Document chunk = GrabChunk(id, 0); Binary b = (Binary)chunk["data"]; Assert.AreEqual(2, b.Bytes[chunksize-1]); Assert.AreEqual(2, b.Bytes[chunksize/2]); Assert.AreEqual(1, b.Bytes[chunksize/2 -1]); Assert.AreEqual(1, b.Bytes[0]); } [Test] public void TestNonSequentialWriteToPartialChunk(){ string filename = "nonsequentialpartial.txt"; GridFileStream gfs = fs.Create(filename); Object id = gfs.GridFileInfo.Id; int chunksize = gfs.GridFileInfo.ChunkSize; gfs.Write(BitConverter.GetBytes(0),0,4); Assert.AreEqual(4, gfs.Position); gfs.Write(BitConverter.GetBytes(7),0,4); Assert.AreEqual(8, gfs.Position); gfs.Seek(0, SeekOrigin.Begin); gfs.Write(BitConverter.GetBytes(15),0,4); gfs.Close(); Document chunk = GrabChunk(id, 0); Binary b = (Binary)chunk["data"]; Assert.AreEqual(8,b.Bytes.Length); } [Test] public void TestNonSequentialWriteToTwoChunks(){ GridFileStream gfs = fs.Create("nonsequential2.txt"); Object id = gfs.GridFileInfo.Id; int chunks = 3; int buffsize = 256 * 1024; for(int c = 0; c < chunks; c++){ Byte[] buff = CreateBuffer(buffsize, (byte)c); if(c == 2){ gfs.Seek(0, SeekOrigin.Begin); //On last chunk seek to start. } gfs.Write(buff,0,buff.Length); } Assert.AreEqual(buffsize, gfs.Position, "Position is incorrect"); gfs.Close(); Assert.AreEqual(chunks - 1, CountChunks(filesystem,id)); Document chunk = GrabChunk(id, 0); Binary b = (Binary)chunk["data"]; Assert.AreEqual(2, b.Bytes[buffsize-1]); Assert.AreEqual(2, b.Bytes[0]); chunk = GrabChunk(id, 1); b = (Binary)chunk["data"]; Assert.AreEqual(1, b.Bytes[buffsize-1]); } [Test] public void TestRead(){ string filename = "readme.txt"; GridFileStream gfs = fs.Create(filename); for(int i = 1; i <= 50; i++){ gfs.Write(BitConverter.GetBytes(i), 0, 4); } gfs.Close(); gfs = fs.OpenRead(filename); Byte[] buff = new Byte[4]; int read; for(int i = 1; i <= 50; i++){ read = gfs.Read(buff,0,4); Assert.AreEqual(4, read, "Not enough bytes were read"); Assert.AreEqual(i,BitConverter.ToInt32(buff, 0), "value read back was not the same as written"); } } [Test] public void TestReadIntoBufferBiggerThanChunk(){ string filename = "largereadbuffer.txt"; int size = 100; Object id = CreateDummyFile(filename,size,50,0); GridFileStream gfs = fs.OpenRead(filename); byte[] buff = new byte[size]; int read = gfs.Read(buff,0,size); Assert.AreEqual(size, read, "Not all bytes read back from file."); int expected = 0; for(int i = 0; i < size; i+=4){ int val = BitConverter.ToInt32(buff,i); Assert.AreEqual(expected, val, "Val was not same as expected. Pos: " + i); expected++; } } [Test] public void TestReadFrom3Chunks(){ string filename = "read3chunks.txt"; int chunks = 3; int chunkSize = 256 * 1024; int size = (256 * 1024 * chunks) - 5000; Object id = CreateDummyFile(filename,size,chunkSize,0); using(GridFileStream gfs = fs.OpenRead(filename)){ int buffsize = 10240; Byte[] buff = new Byte[buffsize]; int read = 0; int totalRead = 0; while((read = gfs.Read(buff,0,buffsize)) != 0){ totalRead += read; } Assert.AreEqual(size,totalRead,"Not all bytes read back"); } } [Test] public void TestSetLengthBigger(){ string filename = "setlengthbigger.txt"; GridFileStream gfs = fs.Create(filename); Object id = gfs.GridFileInfo.Id; long length = 256 * 1024 * 5; gfs.WriteByte(1); gfs.SetLength(length); gfs.WriteByte(2); gfs.Close(); GridFileInfo gfi = new GridFileInfo(DB,filesystem,filename); Assert.AreEqual(length + 1, gfi.Length); Assert.AreEqual(6, CountChunks(filesystem,id)); } [Test] public void TestSetLengthSmaller(){ string filename = "setlengthsmaller.txt"; int chunksize = 256 * 1024; int chunks = 4; int size = chunks * chunksize; int newsize = (size / 2) - (chunksize/2); Object id = this.CreateDummyFile(filename, size,chunksize,0); GridFileStream gfs = fs.Open(filename,FileMode.Open,FileAccess.ReadWrite); gfs.SetLength(newsize); gfs.Close(); Assert.AreEqual(newsize, gfs.GridFileInfo.Length); } [Test] public void TestReadLengthIsSameAsWriteLength(){ string filename = "readwritelength.txt"; GridFileStream gfs = fs.Create(filename); int length = 0; for(int i = 1; i <= 50; i++){ gfs.Write(BitConverter.GetBytes(i), 0, 4); length += 4; } gfs.Close(); Assert.AreEqual(length, gfs.GridFileInfo.Length, "File length written is not the same as in gridfileinfo"); gfs = fs.OpenRead(filename); byte[] buffer = new byte[16]; int read = 0; int readLength = read; while((read = gfs.Read(buffer,0,buffer.Length)) > 0){ readLength += read; } Assert.AreEqual(length, readLength, "Too much read back."); } #region File API compatibility [Test] public void TestSeekingBeyondEOF(){ int buffsize = 256; string filename = "seektest.txt"; FileStream gfs = File.Create(filename,buffsize);//,FileOptions.DeleteOnClose); int chunks = 3; //int buffsize = 256 * 1024; for(int c = 0; c < chunks; c++){ Byte[] buff = new byte[buffsize]; for(int i = 0; i < buff.Length; i++){ buff[i] = (byte)(c); } if(c == 2) gfs.Seek(0, SeekOrigin.Begin); //On last chunk seek to start. gfs.Write(buff,0,buff.Length); gfs.Seek(5,SeekOrigin.Current); } gfs.Seek(50,SeekOrigin.End); gfs.Write(new byte[]{5},0,1); gfs.Close(); File.Delete(filename); } #endregion protected Document GrabChunk(Object fileid, int chunk){ return DB[filesystem + ".chunks"].FindOne(new Document().Add("files_id", fileid).Add("n", chunk)); } protected Object CreateDummyFile(string filename, int size, int chunksize, int initialOffset){ GridFileInfo gfi = new GridFileInfo(DB, "gfstream", filename); gfi.ChunkSize = chunksize; GridFileStream gfs = gfi.Create(); Object id = gfs.GridFileInfo.Id; byte[] buff = CreateIntBuffer(size); gfs.Write(buff,initialOffset,buff.Length - initialOffset); gfs.Close(); return id; } protected byte[] CreateBuffer(int size, byte fill){ Byte[] buff = new byte[size]; for(int i = 0; i < buff.Length; i++){ buff[i] = fill; } return buff; } protected byte[] CreateIntBuffer(int size){ byte[] buff = new byte[size]; int x = 1; for(int i = 4; i < buff.Length; i+=4){ Array.Copy(BitConverter.GetBytes(x++),0,buff,i,4); } return buff; } } }
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 imageupload.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using Avalonia.Controls.Primitives; using Avalonia.Input; using Avalonia.Platform; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests { public class GridSplitterTests { public GridSplitterTests() { var cursorFactoryImpl = new Mock<IStandardCursorFactory>(); AvaloniaLocator.CurrentMutable.Bind<IStandardCursorFactory>().ToConstant(cursorFactoryImpl.Object); } [Fact] public void Detects_Horizontal_Orientation() { var grid = new Grid() { RowDefinitions = new RowDefinitions("*,Auto,*"), ColumnDefinitions = new ColumnDefinitions("*,*"), Children = { new Border { [Grid.RowProperty] = 0 }, new GridSplitter { [Grid.RowProperty] = 1, Name = "splitter" }, new Border { [Grid.RowProperty] = 2 } } }; var root = new TestRoot { Child = grid }; root.Measure(new Size(100, 300)); root.Arrange(new Rect(0, 0, 100, 300)); Assert.Contains(grid.FindControl<GridSplitter>("splitter").Classes, ":horizontal".Equals); } [Fact] public void Detects_Vertical_Orientation() { var grid = new Grid() { ColumnDefinitions = new ColumnDefinitions("*,Auto,*"), RowDefinitions = new RowDefinitions("*,*"), Children = { new Border { [Grid.ColumnProperty] = 0 }, new GridSplitter { [Grid.ColumnProperty] = 1, Name = "splitter" }, new Border { [Grid.ColumnProperty] = 2 }, } }; var root = new TestRoot { Child = grid }; root.Measure(new Size(100, 300)); root.Arrange(new Rect(0, 0, 100, 300)); Assert.Contains(grid.FindControl<GridSplitter>("splitter").Classes, ":vertical".Equals); } [Fact] public void Detects_With_Both_Auto() { var grid = new Grid() { ColumnDefinitions = new ColumnDefinitions("Auto,Auto,Auto"), RowDefinitions = new RowDefinitions("Auto,Auto"), Children = { new Border { [Grid.ColumnProperty] = 0 }, new GridSplitter { [Grid.ColumnProperty] = 1, Name = "splitter" }, new Border { [Grid.ColumnProperty] = 2 }, } }; var root = new TestRoot { Child = grid }; root.Measure(new Size(100, 300)); root.Arrange(new Rect(0, 0, 100, 300)); Assert.Contains(grid.FindControl<GridSplitter>("splitter").Classes, ":vertical".Equals); } [Fact] public void Horizontal_Stays_Within_Constraints() { var control1 = new Border { [Grid.RowProperty] = 0 }; var splitter = new GridSplitter { [Grid.RowProperty] = 1, }; var control2 = new Border { [Grid.RowProperty] = 2 }; var rowDefinitions = new RowDefinitions() { new RowDefinition(1, GridUnitType.Star) { MinHeight = 70, MaxHeight = 110 }, new RowDefinition(GridLength.Auto), new RowDefinition(1, GridUnitType.Star) { MinHeight = 10, MaxHeight = 140 }, }; var grid = new Grid() { RowDefinitions = rowDefinitions, Children = { control1, splitter, control2 } }; var root = new TestRoot { Child = grid }; root.Measure(new Size(100, 200)); root.Arrange(new Rect(0, 0, 100, 200)); splitter.RaiseEvent(new VectorEventArgs { RoutedEvent = Thumb.DragDeltaEvent, Vector = new Vector(0, -100) }); Assert.Equal(rowDefinitions[0].Height, new GridLength(70, GridUnitType.Star)); Assert.Equal(rowDefinitions[2].Height, new GridLength(130, GridUnitType.Star)); splitter.RaiseEvent(new VectorEventArgs { RoutedEvent = Thumb.DragDeltaEvent, Vector = new Vector(0, 100) }); Assert.Equal(rowDefinitions[0].Height, new GridLength(110, GridUnitType.Star)); Assert.Equal(rowDefinitions[2].Height, new GridLength(90, GridUnitType.Star)); } [Fact] public void In_First_Position_Doesnt_Throw_Exception() { var grid = new Grid() { ColumnDefinitions = new ColumnDefinitions("Auto,*,*"), RowDefinitions = new RowDefinitions("*,*"), Children = { new GridSplitter { [Grid.ColumnProperty] = 0, Name = "splitter" }, new Border { [Grid.ColumnProperty] = 1 }, new Border { [Grid.ColumnProperty] = 2 }, } }; var root = new TestRoot { Child = grid }; root.Measure(new Size(100, 300)); root.Arrange(new Rect(0, 0, 100, 300)); var splitter = grid.FindControl<GridSplitter>("splitter"); splitter.RaiseEvent(new VectorEventArgs { RoutedEvent = Thumb.DragDeltaEvent, Vector = new Vector(100, 1000) }); } [Fact] public void Vertical_Stays_Within_Constraints() { var control1 = new Border { [Grid.ColumnProperty] = 0 }; var splitter = new GridSplitter { [Grid.ColumnProperty] = 1, }; var control2 = new Border { [Grid.ColumnProperty] = 2 }; var columnDefinitions = new ColumnDefinitions() { new ColumnDefinition(1, GridUnitType.Star) { MinWidth = 10, MaxWidth = 190 }, new ColumnDefinition(GridLength.Auto), new ColumnDefinition(1, GridUnitType.Star) { MinWidth = 80, MaxWidth = 120 }, }; var grid = new Grid() { ColumnDefinitions = columnDefinitions, Children = { control1, splitter, control2 } }; var root = new TestRoot { Child = grid }; root.Measure(new Size(200, 100)); root.Arrange(new Rect(0, 0, 200, 100)); splitter.RaiseEvent(new VectorEventArgs { RoutedEvent = Thumb.DragDeltaEvent, Vector = new Vector(-100, 0) }); Assert.Equal(columnDefinitions[0].Width, new GridLength(80, GridUnitType.Star)); Assert.Equal(columnDefinitions[2].Width, new GridLength(120, GridUnitType.Star)); splitter.RaiseEvent(new VectorEventArgs { RoutedEvent = Thumb.DragDeltaEvent, Vector = new Vector(100, 0) }); Assert.Equal(columnDefinitions[0].Width, new GridLength(120, GridUnitType.Star)); Assert.Equal(columnDefinitions[2].Width, new GridLength(80, GridUnitType.Star)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Web; using JabbR.Commands; using JabbR.ContentProviders.Core; using JabbR.Infrastructure; using JabbR.Models; using JabbR.Services; using JabbR.ViewModels; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using Newtonsoft.Json; namespace JabbR { public class Chat : Hub, INotificationService { private readonly IJabbrRepository _repository; private readonly IChatService _service; private readonly ICache _cache; private readonly IResourceProcessor _resourceProcessor; private readonly IApplicationSettings _settings; private static readonly Version _version = typeof(Chat).Assembly.GetName().Version; private static readonly string _versionString = _version.ToString(); public Chat(IApplicationSettings settings, IResourceProcessor resourceProcessor, IChatService service, IJabbrRepository repository, ICache cache) { _settings = settings; _resourceProcessor = resourceProcessor; _service = service; _repository = repository; _cache = cache; } private string UserAgent { get { if (Context.Headers != null) { return Context.Headers["User-Agent"]; } return null; } } private bool OutOfSync { get { string version = Clients.Caller.version; return String.IsNullOrEmpty(version) || new Version(version) != _version; } } public bool Join() { SetVersion(); // Get the client state ClientState clientState = GetClientState(); // Try to get the user from the client state ChatUser user = _repository.GetUserById(clientState.UserId); // Threre's no user being tracked if (user == null) { return false; } // Migrate all users to use new auth if (!String.IsNullOrEmpty(_settings.AuthApiKey) && String.IsNullOrEmpty(user.Identity)) { return false; } // Update some user values _service.UpdateActivity(user, Context.ConnectionId, UserAgent); _repository.CommitChanges(); OnUserInitialize(clientState, user); return true; } private void SetVersion() { // Set the version on the client Clients.Caller.version = _versionString; } public bool CheckStatus() { bool outOfSync = OutOfSync; SetVersion(); return outOfSync; } private void OnUserInitialize(ClientState clientState, ChatUser user) { // Update the active room on the client (only if it's still a valid room) if (user.Rooms.Any(room => room.Name.Equals(clientState.ActiveRoom, StringComparison.OrdinalIgnoreCase))) { // Update the active room on the client (only if it's still a valid room) Clients.Caller.activeRoom = clientState.ActiveRoom; } LogOn(user, Context.ConnectionId); } public bool Send(string content, string roomName) { var message = new ClientMessage { Content = content, Id = Guid.NewGuid().ToString("d"), Room = roomName }; return Send(message); } public bool Send(ClientMessage message) { bool outOfSync = OutOfSync; SetVersion(); // Sanitize the content (strip and bad html out) message.Content = HttpUtility.HtmlEncode(message.Content); // See if this is a valid command (starts with /) if (TryHandleCommand(message.Content, message.Room)) { return outOfSync; } string id = GetUserId(); ChatUser user = _repository.VerifyUserId(id); ChatRoom room = _repository.VerifyUserRoom(_cache, user, message.Room); // REVIEW: Is it better to use _repository.VerifyRoom(message.Room, mustBeOpen: false) // here? if (room.Closed) { throw new InvalidOperationException(String.Format("You cannot post messages to '{0}'. The room is closed.", message.Room)); } // Update activity *after* ensuring the user, this forces them to be active UpdateActivity(user, room); HashSet<string> links; var messageText = ParseChatMessageText(message.Content, out links); ChatMessage chatMessage = _service.AddMessage(user, room, message.Id, messageText); var messageViewModel = new MessageViewModel(chatMessage); Clients.Group(room.Name).addMessage(messageViewModel, room.Name); _repository.CommitChanges(); string clientMessageId = chatMessage.Id; // Update the id on the message chatMessage.Id = Guid.NewGuid().ToString("d"); _repository.CommitChanges(); if (!links.Any()) { return outOfSync; } ProcessUrls(links, room.Name, clientMessageId, chatMessage.Id); return outOfSync; } private string ParseChatMessageText(string content, out HashSet<string> links) { var textTransform = new TextTransform(_repository); string message = textTransform.Parse(content); return TextTransform.TransformAndExtractUrls(message, out links); } public UserViewModel GetUserInfo() { string id = GetUserId(); ChatUser user = _repository.VerifyUserId(id); return new UserViewModel(user); } public override Task OnReconnected() { string id = GetUserId(); if (String.IsNullOrEmpty(id)) { return null; } ChatUser user = _repository.VerifyUserId(id); // Make sure this client is being tracked _service.AddClient(user, Context.ConnectionId, UserAgent); var currentStatus = (UserStatus)user.Status; if (currentStatus == UserStatus.Offline) { // Mark the user as inactive user.Status = (int)UserStatus.Inactive; _repository.CommitChanges(); // If the user was offline that means they are not in the user list so we need to tell // everyone the user is really in the room var userViewModel = new UserViewModel(user); foreach (var room in user.Rooms) { var isOwner = user.OwnedRooms.Contains(room); // Tell the people in this room that you've joined Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner).Wait(); // Add the caller to the group so they receive messages Groups.Add(Context.ConnectionId, room.Name); } } return base.OnReconnected(); } public override Task OnDisconnected() { DisconnectClient(Context.ConnectionId); return base.OnDisconnected(); } public object GetCommands() { return CommandManager.GetCommandsMetaData(); } public object GetShortcuts() { return new[] { new { Name = "Tab or Shift + Tab", Category = "shortcut", Description = "Go to the next open room tab or Go to the previous open room tab." }, new { Name = "Alt + L", Category = "shortcut", Description = "Go to the Lobby."}, new { Name = "Alt + Number", Category = "shortcut", Description = "Go to specific Tab."} }; } public IEnumerable<LobbyRoomViewModel> GetRooms() { string id = GetUserId(); ChatUser user = _repository.VerifyUserId(id); var rooms = _repository.GetAllowedRooms(user).Select(r => new LobbyRoomViewModel { Name = r.Name, Count = r.Users.Count(u => u.Status != (int)UserStatus.Offline), Private = r.Private, Closed = r.Closed }).ToList(); return rooms; } public IEnumerable<MessageViewModel> GetPreviousMessages(string messageId) { var previousMessages = (from m in _repository.GetPreviousMessages(messageId) orderby m.When descending select m).Take(100); return previousMessages.AsEnumerable() .Reverse() .Select(m => new MessageViewModel(m)); } public RoomViewModel GetRoomInfo(string roomName) { if (String.IsNullOrEmpty(roomName)) { return null; } ChatRoom room = _repository.GetRoomByName(roomName); if (room == null) { return null; } var recentMessages = (from m in _repository.GetMessagesByRoom(room) orderby m.When descending select m).Take(30).ToList(); // Reverse them since we want to get them in chronological order recentMessages.Reverse(); // Get online users through the repository IEnumerable<ChatUser> onlineUsers = _repository.GetOnlineUsers(room).ToList(); return new RoomViewModel { Name = room.Name, Users = from u in onlineUsers select new UserViewModel(u), Owners = from u in room.Owners.Online() select u.Name, RecentMessages = recentMessages.Select(m => new MessageViewModel(m)), Topic = ConvertUrlsAndRoomLinks(room.Topic ?? ""), Welcome = ConvertUrlsAndRoomLinks(room.Welcome ?? ""), Closed = room.Closed }; } private string ConvertUrlsAndRoomLinks(string message) { TextTransform textTransform = new TextTransform(_repository); message = textTransform.ConvertHashtagsToRoomLinks(message); HashSet<string> urls; return TextTransform.TransformAndExtractUrls(message, out urls); } // TODO: Deprecate public void Typing() { string roomName = Clients.Caller.activeRoom; Typing(roomName); } public void Typing(string roomName) { string id = GetUserId(); ChatUser user = _repository.GetUserById(id); if (user == null) { return; } ChatRoom room = _repository.VerifyUserRoom(_cache, user, roomName); UpdateActivity(user, room); var userViewModel = new UserViewModel(user); Clients.Group(room.Name).setTyping(userViewModel, room.Name); } private void LogOn(ChatUser user, string clientId) { // Update the client state Clients.Caller.id = user.Id; Clients.Caller.name = user.Name; Clients.Caller.hash = user.Hash; var userViewModel = new UserViewModel(user); var rooms = new List<RoomViewModel>(); var ownedRooms = user.OwnedRooms.Select(r => r.Key); foreach (var room in user.Rooms) { var isOwner = ownedRooms.Contains(room.Key); // Tell the people in this room that you've joined Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner).Wait(); // Add the caller to the group so they receive messages Groups.Add(clientId, room.Name); // Add to the list of room names rooms.Add(new RoomViewModel { Name = room.Name, Private = room.Private, Closed = room.Closed }); } // Initialize the chat with the rooms the user is in Clients.Caller.logOn(rooms); } private void UpdateActivity(ChatUser user, ChatRoom room) { UpdateActivity(user); OnUpdateActivity(user, room); } private void UpdateActivity(ChatUser user) { _service.UpdateActivity(user, Context.ConnectionId, UserAgent); _repository.CommitChanges(); } private void ProcessUrls(IEnumerable<string> links, string roomName, string clientMessageId, string messageId) { var contentTasks = links.Select(_resourceProcessor.ExtractResource).ToArray(); Task.Factory.ContinueWhenAll(contentTasks, tasks => { foreach (var task in tasks) { if (task.IsFaulted) { Trace.TraceError(task.Exception.GetBaseException().Message); continue; } if (task.Result == null || String.IsNullOrEmpty(task.Result.Content)) { continue; } // Try to get content from each url we're resolved in the query string extractedContent = "<p>" + task.Result.Content + "</p>"; // Notify the room Clients.Group(roomName).addMessageContent(clientMessageId, extractedContent, roomName); _service.AppendMessage(messageId, extractedContent); } }); } private bool TryHandleCommand(string command, string room) { string clientId = Context.ConnectionId; string userId = GetUserId(); var commandManager = new CommandManager(clientId, UserAgent, userId, room, _service, _repository, _cache, this); return commandManager.TryHandleCommand(command); } private void DisconnectClient(string clientId) { string userId = _service.DisconnectClient(clientId); if (String.IsNullOrEmpty(userId)) { return; } // Query for the user to get the updated status ChatUser user = _repository.GetUserById(userId); // There's no associated user for this client id if (user == null) { return; } // The user will be marked as offline if all clients leave if (user.Status == (int)UserStatus.Offline) { foreach (var room in user.Rooms) { var userViewModel = new UserViewModel(user); Clients.Group(room.Name).leave(userViewModel, room.Name); } } } private void OnUpdateActivity(ChatUser user, ChatRoom room) { var userViewModel = new UserViewModel(user); Clients.Group(room.Name).updateActivity(userViewModel, room.Name); } private void LeaveRoom(ChatUser user, ChatRoom room) { var userViewModel = new UserViewModel(user); Clients.Group(room.Name).leave(userViewModel, room.Name).Wait(); foreach (var client in user.ConnectedClients) { Groups.Remove(client.Id, room.Name); } OnRoomChanged(room); } void INotificationService.LogOn(ChatUser user, string clientId) { LogOn(user, clientId); } void INotificationService.ChangePassword() { Clients.Caller.changePassword(); } void INotificationService.SetPassword() { Clients.Caller.setPassword(); } void INotificationService.KickUser(ChatUser targetUser, ChatRoom room) { foreach (var client in targetUser.ConnectedClients) { // Kick the user from this room Clients.Client(client.Id).kick(room.Name); // Remove the user from this the room group so he doesn't get the leave message Groups.Remove(client.Id, room.Name); } // Tell the room the user left LeaveRoom(targetUser, room); } void INotificationService.OnUserCreated(ChatUser user) { // Set some client state Clients.Caller.name = user.Name; Clients.Caller.id = user.Id; Clients.Caller.hash = user.Hash; // Tell the client a user was created Clients.Caller.userCreated(); } void INotificationService.JoinRoom(ChatUser user, ChatRoom room) { var userViewModel = new UserViewModel(user); var roomViewModel = new RoomViewModel { Name = room.Name, Private = room.Private, Welcome = ConvertUrlsAndRoomLinks(room.Welcome ?? ""), Closed = room.Closed }; var isOwner = user.OwnedRooms.Contains(room); // Tell all clients to join this room foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).joinRoom(roomViewModel); } // Tell the people in this room that you've joined Clients.Group(room.Name).addUser(userViewModel, room.Name, isOwner).Wait(); // Notify users of the room count change OnRoomChanged(room); foreach (var client in user.ConnectedClients) { Groups.Add(client.Id, room.Name); } } void INotificationService.AllowUser(ChatUser targetUser, ChatRoom targetRoom) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's an owner Clients.Client(client.Id).allowUser(targetRoom.Name); } // Tell the calling client the granting permission into the room was successful Clients.Caller.userAllowed(targetUser.Name, targetRoom.Name); } void INotificationService.UnallowUser(ChatUser targetUser, ChatRoom targetRoom) { // Kick the user from the room when they are unallowed ((INotificationService)this).KickUser(targetUser, targetRoom); foreach (var client in targetUser.ConnectedClients) { // Tell this client it's an owner Clients.Client(client.Id).unallowUser(targetRoom.Name); } // Tell the calling client the granting permission into the room was successful Clients.Caller.userUnallowed(targetUser.Name, targetRoom.Name); } void INotificationService.AddOwner(ChatUser targetUser, ChatRoom targetRoom) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's an owner Clients.Client(client.Id).makeOwner(targetRoom.Name); } var userViewModel = new UserViewModel(targetUser); // If the target user is in the target room. // Tell everyone in the target room that a new owner was added if (_repository.IsUserInRoom(_cache, targetUser, targetRoom)) { Clients.Group(targetRoom.Name).addOwner(userViewModel, targetRoom.Name); } // Tell the calling client the granting of ownership was successful Clients.Caller.ownerMade(targetUser.Name, targetRoom.Name); } void INotificationService.RemoveOwner(ChatUser targetUser, ChatRoom targetRoom) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's no longer an owner Clients.Client(client.Id).demoteOwner(targetRoom.Name); } var userViewModel = new UserViewModel(targetUser); // If the target user is in the target room. // Tell everyone in the target room that the owner was removed if (_repository.IsUserInRoom(_cache, targetUser, targetRoom)) { Clients.Group(targetRoom.Name).removeOwner(userViewModel, targetRoom.Name); } // Tell the calling client the removal of ownership was successful Clients.Caller.ownerRemoved(targetUser.Name, targetRoom.Name); } void INotificationService.ChangeGravatar(ChatUser user) { Clients.Caller.hash = user.Hash; // Update the calling client foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).gravatarChanged(); } // Create the view model var userViewModel = new UserViewModel(user); // Tell all users in rooms to change the gravatar foreach (var room in user.Rooms) { Clients.Group(room.Name).changeGravatar(userViewModel, room.Name); } } void INotificationService.OnSelfMessage(ChatRoom room, ChatUser user, string content) { Clients.Group(room.Name).sendMeMessage(user.Name, content, room.Name); } void INotificationService.SendPrivateMessage(ChatUser fromUser, ChatUser toUser, string messageText) { // Send a message to the sender and the sendee foreach (var client in fromUser.ConnectedClients) { Clients.Client(client.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText); } foreach (var client in toUser.ConnectedClients) { Clients.Client(client.Id).sendPrivateMessage(fromUser.Name, toUser.Name, messageText); } } void INotificationService.PostNotification(ChatRoom room, ChatUser user, string message) { foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).postNotification(message, room.Name); } } void INotificationService.ListRooms(ChatUser user) { string userId = GetUserId(); var userModel = new UserViewModel(user); Clients.Caller.showUsersRoomList(userModel, user.Rooms.Allowed(userId).Select(r => r.Name)); } void INotificationService.ListUsers() { var users = _repository.Users.Online().Select(s => s.Name).OrderBy(s => s); Clients.Caller.listUsers(users); } void INotificationService.ListUsers(IEnumerable<ChatUser> users) { Clients.Caller.listUsers(users.Select(s => s.Name)); } void INotificationService.ListUsers(ChatRoom room, IEnumerable<string> names) { Clients.Caller.showUsersInRoom(room.Name, names); } void INotificationService.LockRoom(ChatUser targetUser, ChatRoom room) { var userViewModel = new UserViewModel(targetUser); // Tell the room it's locked Clients.All.lockRoom(userViewModel, room.Name); // Tell the caller the room was successfully locked Clients.Caller.roomLocked(room.Name); // Notify people of the change OnRoomChanged(room); } void INotificationService.CloseRoom(IEnumerable<ChatUser> users, ChatRoom room) { // notify all members of room that it is now closed foreach (var user in users) { foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).roomClosed(room.Name); } } } void INotificationService.UnCloseRoom(IEnumerable<ChatUser> users, ChatRoom room) { // notify all members of room that it is now re-opened foreach (var user in users) { foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).roomUnClosed(room.Name); } } } void INotificationService.LogOut(ChatUser user, string clientId) { DisconnectClient(clientId); var rooms = user.Rooms.Select(r => r.Name); Clients.Caller.logOut(rooms); } void INotificationService.ShowUserInfo(ChatUser user) { string userId = GetUserId(); Clients.Caller.showUserInfo(new { Name = user.Name, OwnedRooms = user.OwnedRooms .Allowed(userId) .Where(r => !r.Closed) .Select(r => r.Name), Status = ((UserStatus)user.Status).ToString(), LastActivity = user.LastActivity, IsAfk = user.IsAfk, AfkNote = user.AfkNote, Note = user.Note, Hash = user.Hash, Rooms = user.Rooms.Allowed(userId).Select(r => r.Name) }); } void INotificationService.ShowHelp() { Clients.Caller.showCommands(); } void INotificationService.Invite(ChatUser user, ChatUser targetUser, ChatRoom targetRoom) { var transform = new TextTransform(_repository); string roomLink = transform.ConvertHashtagsToRoomLinks("#" + targetRoom.Name); // Send the invite message to the sendee foreach (var client in targetUser.ConnectedClients) { Clients.Client(client.Id).sendInvite(user.Name, targetUser.Name, roomLink); } // Send the invite notification to the sender foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).sendInvite(user.Name, targetUser.Name, roomLink); } } void INotificationService.NugeUser(ChatUser user, ChatUser targetUser) { // Send a nudge message to the sender and the sendee foreach (var client in targetUser.ConnectedClients) { Clients.Client(client.Id).nudge(user.Name, targetUser.Name); } foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).sendPrivateMessage(user.Name, targetUser.Name, "nudged " + targetUser.Name); } } void INotificationService.NudgeRoom(ChatRoom room, ChatUser user) { Clients.Group(room.Name).nudge(user.Name); } void INotificationService.LeaveRoom(ChatUser user, ChatRoom room) { LeaveRoom(user, room); } void INotificationService.OnUserNameChanged(ChatUser user, string oldUserName, string newUserName) { // Create the view model var userViewModel = new UserViewModel(user); // Tell the user's connected clients that the name changed foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).userNameChanged(userViewModel); } // Notify all users in the rooms foreach (var room in user.Rooms) { Clients.Group(room.Name).changeUserName(oldUserName, userViewModel, room.Name); } } void INotificationService.ChangeNote(ChatUser user) { bool isNoteCleared = user.Note == null; // Update the calling client foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).noteChanged(user.IsAfk, isNoteCleared); } // Create the view model var userViewModel = new UserViewModel(user); // Tell all users in rooms to change the note foreach (var room in user.Rooms) { Clients.Group(room.Name).changeNote(userViewModel, room.Name); } } void INotificationService.ChangeFlag(ChatUser user) { bool isFlagCleared = String.IsNullOrWhiteSpace(user.Flag); // Create the view model var userViewModel = new UserViewModel(user); // Update the calling client foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).flagChanged(isFlagCleared, userViewModel.Country); } // Tell all users in rooms to change the flag foreach (var room in user.Rooms) { Clients.Group(room.Name).changeFlag(userViewModel, room.Name); } } void INotificationService.ChangeTopic(ChatUser user, ChatRoom room) { bool isTopicCleared = String.IsNullOrWhiteSpace(room.Topic); var parsedTopic = ConvertUrlsAndRoomLinks(room.Topic ?? ""); Clients.Group(room.Name).topicChanged(room.Name, isTopicCleared, parsedTopic, user.Name); // Create the view model var roomViewModel = new RoomViewModel { Name = room.Name, Topic = parsedTopic, Closed = room.Closed }; Clients.Group(room.Name).changeTopic(roomViewModel); } void INotificationService.ChangeWelcome(ChatUser user, ChatRoom room) { bool isWelcomeCleared = String.IsNullOrWhiteSpace(room.Welcome); var parsedWelcome = ConvertUrlsAndRoomLinks(room.Welcome ?? ""); foreach (var client in user.ConnectedClients) { Clients.Client(client.Id).welcomeChanged(isWelcomeCleared, parsedWelcome); } } void INotificationService.AddAdmin(ChatUser targetUser) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's an owner Clients.Client(client.Id).makeAdmin(); } var userViewModel = new UserViewModel(targetUser); // Tell all users in rooms to change the admin status foreach (var room in targetUser.Rooms) { Clients.Group(room.Name).addAdmin(userViewModel, room.Name); } // Tell the calling client the granting of admin status was successful Clients.Caller.adminMade(targetUser.Name); } void INotificationService.RemoveAdmin(ChatUser targetUser) { foreach (var client in targetUser.ConnectedClients) { // Tell this client it's no longer an owner Clients.Client(client.Id).demoteAdmin(); } var userViewModel = new UserViewModel(targetUser); // Tell all users in rooms to change the admin status foreach (var room in targetUser.Rooms) { Clients.Group(room.Name).removeAdmin(userViewModel, room.Name); } // Tell the calling client the removal of admin status was successful Clients.Caller.adminRemoved(targetUser.Name); } void INotificationService.BroadcastMessage(ChatUser user, string messageText) { // Tell all users in all rooms about this message foreach (var room in _repository.Rooms) { Clients.Group(room.Name).broadcastMessage(messageText, room.Name); } } void INotificationService.ForceUpdate() { Clients.All.forceUpdate(); } private void OnRoomChanged(ChatRoom room) { var roomViewModel = new RoomViewModel { Name = room.Name, Private = room.Private, Closed = room.Closed }; // Update the room count Clients.All.updateRoomCount(roomViewModel, _repository.GetOnlineUsers(room).Count()); } private string GetUserId() { ClientState state = GetClientState(); return state.UserId; } private ClientState GetClientState() { // New client state var jabbrState = GetCookieValue("jabbr.state"); ClientState clientState = null; if (String.IsNullOrEmpty(jabbrState)) { clientState = new ClientState(); } else { clientState = JsonConvert.DeserializeObject<ClientState>(jabbrState); } // Read the id from the caller if there's no cookie clientState.UserId = clientState.UserId ?? Clients.Caller.id; return clientState; } private string GetCookieValue(string key) { Cookie cookie; Context.RequestCookies.TryGetValue(key, out cookie); string value = cookie != null ? cookie.Value : null; return value != null ? HttpUtility.UrlDecode(value) : null; } void INotificationService.BanUser(ChatUser targetUser) { var rooms = targetUser.Rooms.Select(x => x.Name); foreach (var room in rooms) { foreach (var client in targetUser.ConnectedClients) { // Kick the user from this room Clients.Client(client.Id).kick(room); // Remove the user from this the room group so he doesn't get the leave message Groups.Remove(client.Id, room); } } Clients.Client(targetUser.ConnectedClients.First().Id).logOut(rooms); } protected override void Dispose(bool disposing) { if (disposing) { _repository.Dispose(); } base.Dispose(disposing); } } }
/* * 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 OpenMetaverse; using log4net; using Nini.Config; using System.Reflection; using OpenSim.Services.Base; using OpenSim.Services.Interfaces; using OpenSim.Data; using OpenSim.Framework; namespace OpenSim.Services.InventoryService { public class XInventoryService : ServiceBase, IInventoryService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); protected IXInventoryData m_Database; protected bool m_AllowDelete = true; public XInventoryService(IConfigSource config) : base(config) { string dllName = String.Empty; string connString = String.Empty; //string realm = "Inventory"; // OSG version doesn't use this // // Try reading the [InventoryService] section first, if it exists // IConfig authConfig = config.Configs["InventoryService"]; if (authConfig != null) { dllName = authConfig.GetString("StorageProvider", dllName); connString = authConfig.GetString("ConnectionString", connString); m_AllowDelete = authConfig.GetBoolean("AllowDelete", true); // realm = authConfig.GetString("Realm", realm); } // // Try reading the [DatabaseService] section, if it exists // IConfig dbConfig = config.Configs["DatabaseService"]; if (dbConfig != null) { if (dllName == String.Empty) dllName = dbConfig.GetString("StorageProvider", String.Empty); if (connString == String.Empty) connString = dbConfig.GetString("ConnectionString", String.Empty); } // // We tried, but this doesn't exist. We can't proceed. // if (dllName == String.Empty) throw new Exception("No StorageProvider configured"); m_Database = LoadPlugin<IXInventoryData>(dllName, new Object[] {connString, String.Empty}); if (m_Database == null) throw new Exception("Could not find a storage interface in the given module"); } public bool CreateUserInventory(UUID principalID) { // This is braindeaad. We can't ever communicate that we fixed // an existing inventory. Well, just return root folder status, // but check sanity anyway. // bool result = false; InventoryFolderBase rootFolder = GetRootFolder(principalID); if (rootFolder == null) { rootFolder = ConvertToOpenSim(CreateFolder(principalID, UUID.Zero, (int)AssetType.Folder, "My Inventory")); result = true; } XInventoryFolder[] sysFolders = GetSystemFolders(principalID); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Animation) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.Animation, "Animations"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Bodypart) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.Bodypart, "Body Parts"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.CallingCard) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.CallingCard, "Calling Cards"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Clothing) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.Clothing, "Clothing"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Gesture) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.Gesture, "Gestures"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Landmark) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.Landmark, "Landmarks"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.LostAndFoundFolder) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.LostAndFoundFolder, "Lost And Found"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Notecard) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.Notecard, "Notecards"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Object) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.Object, "Objects"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.SnapshotFolder) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.SnapshotFolder, "Photo Album"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.LSLText) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.LSLText, "Scripts"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Sound) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.Sound, "Sounds"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.Texture) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.Texture, "Textures"); if (!Array.Exists(sysFolders, delegate (XInventoryFolder f) { if (f.type == (int)AssetType.TrashFolder) return true; return false; })) CreateFolder(principalID, rootFolder.ID, (int)AssetType.TrashFolder, "Trash"); return result; } private XInventoryFolder CreateFolder(UUID principalID, UUID parentID, int type, string name) { XInventoryFolder newFolder = new XInventoryFolder(); newFolder.folderName = name; newFolder.type = type; newFolder.version = 1; newFolder.folderID = UUID.Random(); newFolder.agentID = principalID; newFolder.parentFolderID = parentID; m_Database.StoreFolder(newFolder); return newFolder; } private XInventoryFolder[] GetSystemFolders(UUID principalID) { XInventoryFolder[] allFolders = m_Database.GetFolders( new string[] { "agentID" }, new string[] { principalID.ToString() }); XInventoryFolder[] sysFolders = Array.FindAll( allFolders, delegate (XInventoryFolder f) { if (f.type > 0) return true; return false; }); return sysFolders; } public List<InventoryFolderBase> GetInventorySkeleton(UUID principalID) { XInventoryFolder[] allFolders = m_Database.GetFolders( new string[] { "agentID" }, new string[] { principalID.ToString() }); if (allFolders.Length == 0) return null; List<InventoryFolderBase> folders = new List<InventoryFolderBase>(); foreach (XInventoryFolder x in allFolders) { m_log.DebugFormat("[INVENTORY]: Adding folder {0} to skeleton", x.folderName); folders.Add(ConvertToOpenSim(x)); } return folders; } public InventoryFolderBase GetRootFolder(UUID principalID) { XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "parentFolderID"}, new string[] { principalID.ToString(), UUID.Zero.ToString() }); if (folders.Length == 0) return null; return ConvertToOpenSim(folders[0]); } public InventoryFolderBase GetFolderForType(UUID principalID, AssetType type) { XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "agentID", "type"}, new string[] { principalID.ToString(), ((int)type).ToString() }); if (folders.Length == 0) return null; return ConvertToOpenSim(folders[0]); } public InventoryCollection GetFolderContent(UUID principalID, UUID folderID) { // This method doesn't receive a valud principal id from the // connector. So we disregard the principal and look // by ID. // m_log.DebugFormat("[INVENTORY]: Fetch contents for folder {0}", folderID.ToString()); InventoryCollection inventory = new InventoryCollection(); inventory.UserID = principalID; inventory.Folders = new List<InventoryFolderBase>(); inventory.Items = new List<InventoryItemBase>(); XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "parentFolderID"}, new string[] { folderID.ToString() }); foreach (XInventoryFolder x in folders) { m_log.DebugFormat("[INVENTORY]: Adding folder {0} to response", x.folderName); inventory.Folders.Add(ConvertToOpenSim(x)); } XInventoryItem[] items = m_Database.GetItems( new string[] { "parentFolderID"}, new string[] { folderID.ToString() }); foreach (XInventoryItem i in items) { m_log.DebugFormat("[INVENTORY]: Adding item {0} to response", i.inventoryName); inventory.Items.Add(ConvertToOpenSim(i)); } return inventory; } public List<InventoryItemBase> GetFolderItems(UUID principalID, UUID folderID) { // Since we probably don't get a valid principal here, either ... // List<InventoryItemBase> invItems = new List<InventoryItemBase>(); XInventoryItem[] items = m_Database.GetItems( new string[] { "parentFolderID"}, new string[] { UUID.Zero.ToString() }); foreach (XInventoryItem i in items) invItems.Add(ConvertToOpenSim(i)); return invItems; } public bool AddFolder(InventoryFolderBase folder) { InventoryFolderBase check = GetFolder(folder); if (check != null) return false; XInventoryFolder xFolder = ConvertFromOpenSim(folder); return m_Database.StoreFolder(xFolder); } public bool UpdateFolder(InventoryFolderBase folder) { XInventoryFolder xFolder = ConvertFromOpenSim(folder); InventoryFolderBase check = GetFolder(folder); if (check == null) return AddFolder(folder); if (check.Type != -1 || xFolder.type != -1) { if (xFolder.version > check.Version) return false; check.Version = (ushort)xFolder.version; xFolder = ConvertFromOpenSim(check); return m_Database.StoreFolder(xFolder); } if (xFolder.version < check.Version) xFolder.version = check.Version; xFolder.folderID = check.ID; return m_Database.StoreFolder(xFolder); } public bool MoveFolder(InventoryFolderBase folder) { XInventoryFolder[] x = m_Database.GetFolders( new string[] { "folderID" }, new string[] { folder.ID.ToString() }); if (x.Length == 0) return false; x[0].parentFolderID = folder.ParentID; return m_Database.StoreFolder(x[0]); } // We don't check the principal's ID here // public bool DeleteFolders(UUID principalID, List<UUID> folderIDs) { if (!m_AllowDelete) return false; // Ignore principal ID, it's bogus at connector level // foreach (UUID id in folderIDs) { if (!ParentIsTrash(id)) continue; InventoryFolderBase f = new InventoryFolderBase(); f.ID = id; PurgeFolder(f); m_Database.DeleteFolders("folderID", id.ToString()); } return true; } public bool PurgeFolder(InventoryFolderBase folder) { if (!m_AllowDelete) return false; if (!ParentIsTrash(folder.ID)) return false; XInventoryFolder[] subFolders = m_Database.GetFolders( new string[] { "parentFolderID" }, new string[] { folder.ID.ToString() }); foreach (XInventoryFolder x in subFolders) { PurgeFolder(ConvertToOpenSim(x)); m_Database.DeleteFolders("folderID", x.folderID.ToString()); } m_Database.DeleteItems("parentFolderID", folder.ID.ToString()); return true; } public bool AddItem(InventoryItemBase item) { return m_Database.StoreItem(ConvertFromOpenSim(item)); } public bool UpdateItem(InventoryItemBase item) { return m_Database.StoreItem(ConvertFromOpenSim(item)); } public bool MoveItems(UUID principalID, List<InventoryItemBase> items) { // Principal is b0rked. *sigh* // foreach (InventoryItemBase i in items) { m_Database.MoveItem(i.ID.ToString(), i.Folder.ToString()); } return true; } public bool DeleteItems(UUID principalID, List<UUID> itemIDs) { if (!m_AllowDelete) return false; // Just use the ID... *facepalms* // foreach (UUID id in itemIDs) m_Database.DeleteItems("inventoryID", id.ToString()); return true; } public InventoryItemBase GetItem(InventoryItemBase item) { XInventoryItem[] items = m_Database.GetItems( new string[] { "inventoryID" }, new string[] { item.ID.ToString() }); if (items.Length == 0) return null; return ConvertToOpenSim(items[0]); } public InventoryFolderBase GetFolder(InventoryFolderBase folder) { XInventoryFolder[] folders = m_Database.GetFolders( new string[] { "folderID"}, new string[] { folder.ID.ToString() }); if (folders.Length == 0) return null; return ConvertToOpenSim(folders[0]); } public List<InventoryItemBase> GetActiveGestures(UUID principalID) { XInventoryItem[] items = m_Database.GetActiveGestures(principalID); if (items.Length == 0) return null; List<InventoryItemBase> ret = new List<InventoryItemBase>(); foreach (XInventoryItem x in items) ret.Add(ConvertToOpenSim(x)); return ret; } public int GetAssetPermissions(UUID principalID, UUID assetID) { return m_Database.GetAssetPermissions(principalID, assetID); } // CM never needed those. Left unimplemented. // Obsolete in core // public InventoryCollection GetUserInventory(UUID userID) { return null; } public void GetUserInventory(UUID userID, InventoryReceiptCallback callback) { } // Unused. // public bool HasInventoryForUser(UUID userID) { return false; } // CM Helpers // private InventoryFolderBase ConvertToOpenSim(XInventoryFolder folder) { InventoryFolderBase newFolder = new InventoryFolderBase(); newFolder.ParentID = folder.parentFolderID; newFolder.Type = (short)folder.type; newFolder.Version = (ushort)folder.version; newFolder.Name = folder.folderName; newFolder.Owner = folder.agentID; newFolder.ID = folder.folderID; return newFolder; } private XInventoryFolder ConvertFromOpenSim(InventoryFolderBase folder) { XInventoryFolder newFolder = new XInventoryFolder(); newFolder.parentFolderID = folder.ParentID; newFolder.type = (int)folder.Type; newFolder.version = (int)folder.Version; newFolder.folderName = folder.Name; newFolder.agentID = folder.Owner; newFolder.folderID = folder.ID; return newFolder; } private InventoryItemBase ConvertToOpenSim(XInventoryItem item) { InventoryItemBase newItem = new InventoryItemBase(); newItem.AssetID = item.assetID; newItem.AssetType = item.assetType; newItem.Name = item.inventoryName; newItem.Owner = item.avatarID; newItem.ID = item.inventoryID; newItem.InvType = item.invType; newItem.Folder = item.parentFolderID; newItem.CreatorId = item.creatorID.ToString(); newItem.Description = item.inventoryDescription; newItem.NextPermissions = (uint)item.inventoryNextPermissions; newItem.CurrentPermissions = (uint)item.inventoryCurrentPermissions; newItem.BasePermissions = (uint)item.inventoryBasePermissions; newItem.EveryOnePermissions = (uint)item.inventoryEveryOnePermissions; newItem.GroupPermissions = (uint)item.inventoryGroupPermissions; newItem.GroupID = item.groupID; newItem.GroupOwned = item.groupOwned; newItem.SalePrice = item.salePrice; newItem.SaleType = (byte)item.saleType; newItem.Flags = (uint)item.flags; newItem.CreationDate = item.creationDate; return newItem; } private XInventoryItem ConvertFromOpenSim(InventoryItemBase item) { XInventoryItem newItem = new XInventoryItem(); newItem.assetID = item.AssetID; newItem.assetType = item.AssetType; newItem.inventoryName = item.Name; newItem.avatarID = item.Owner; newItem.inventoryID = item.ID; newItem.invType = item.InvType; newItem.parentFolderID = item.Folder; newItem.creatorID = item.CreatorIdAsUuid; newItem.inventoryDescription = item.Description; newItem.inventoryNextPermissions = (int)item.NextPermissions; newItem.inventoryCurrentPermissions = (int)item.CurrentPermissions; newItem.inventoryBasePermissions = (int)item.BasePermissions; newItem.inventoryEveryOnePermissions = (int)item.EveryOnePermissions; newItem.inventoryGroupPermissions = (int)item.GroupPermissions; newItem.groupID = item.GroupID; newItem.groupOwned = item.GroupOwned; newItem.salePrice = item.SalePrice; newItem.saleType = (int)item.SaleType; newItem.flags = (int)item.Flags; newItem.creationDate = item.CreationDate; return newItem; } private bool ParentIsTrash(UUID folderID) { XInventoryFolder[] folder = m_Database.GetFolders(new string[] {"folderID"}, new string[] {folderID.ToString()}); if (folder.Length < 1) return false; UUID parentFolder = folder[0].parentFolderID; while (parentFolder != UUID.Zero) { XInventoryFolder[] parent = m_Database.GetFolders(new string[] {"folderID"}, new string[] {parentFolder.ToString()}); if (parent.Length < 1) return false; if (parent[0].type == (int)AssetType.TrashFolder) return true; if (parent[0].type == (int)AssetType.RootFolder) return false; parentFolder = parent[0].parentFolderID; } return false; } } }
/* * Copyright (c) 2009 Jim Radford http://www.jimradford.com * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Microsoft.Win32; using System.Web; using SuperPutty.Data; using SuperPutty.Utils; using SuperPutty.Gui; using log4net; namespace SuperPutty { public partial class dlgEditSession : Form { private static readonly ILog Log = LogManager.GetLogger(typeof(dlgEditSession)); public delegate bool SessionNameValidationHandler(string name, out string error); private SessionData Session; private String OldHostname; private bool isInitialized = false; private ImageListPopup imgPopup = null; public dlgEditSession(SessionData session, ImageList iconList) { Session = session; InitializeComponent(); // get putty saved settings from the registry to populate // the dropdown PopulatePuttySettings(); if (!String.IsNullOrEmpty(Session.SessionName)) { this.Text = "Edit session: " + session.SessionName; this.textBoxSessionName.Text = Session.SessionName; this.textBoxHostname.Text = Session.Host; this.textBoxPort.Text = Session.Port.ToString(); this.textBoxExtraArgs.Text = Session.ExtraArgs; this.textBoxUsername.Text = Session.Username; switch (Session.Proto) { case ConnectionProtocol.Raw: radioButtonRaw.Checked = true; break; case ConnectionProtocol.Rlogin: radioButtonRlogin.Checked = true; break; case ConnectionProtocol.Serial: radioButtonSerial.Checked = true; break; case ConnectionProtocol.SSH: radioButtonSSH.Checked = true; break; case ConnectionProtocol.Telnet: radioButtonTelnet.Checked = true; break; case ConnectionProtocol.Cygterm: radioButtonCygterm.Checked = true; break; case ConnectionProtocol.Mintty: radioButtonMintty.Checked = true; break; default: radioButtonSSH.Checked = true; break; } foreach(String settings in this.comboBoxPuttyProfile.Items){ if (settings == session.PuttySession) { this.comboBoxPuttyProfile.SelectedItem = settings; break; } } //KiTTY local session, not discovered in registry if (this.comboBoxPuttyProfile.Text != Session.PuttySession) { this.comboBoxPuttyProfile.Items.Add(Session.PuttySession); this.comboBoxPuttyProfile.SelectedItem = Session.PuttySession; } this.buttonSave.Enabled = true; } else { this.Text = "Create new session"; radioButtonSSH.Checked = true; this.buttonSave.Enabled = false; } // Setup icon chooser this.buttonImageSelect.ImageList = iconList; this.buttonImageSelect.ImageKey = string.IsNullOrEmpty(Session.ImageKey) ? SessionTreeview.ImageKeySession : Session.ImageKey; this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey); this.isInitialized = true; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); this.BeginInvoke(new MethodInvoker(delegate { this.textBoxSessionName.Focus(); })); } private void PopulatePuttySettings() { foreach (String sessionName in PuttyDataHelper.GetSessionNames()) { comboBoxPuttyProfile.Items.Add(sessionName); } comboBoxPuttyProfile.SelectedItem = PuttyDataHelper.SessionDefaultSettings; } private void buttonCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } private void buttonSave_Click(object sender, EventArgs e) { Session.SessionName = textBoxSessionName.Text.Trim(); Session.PuttySession = comboBoxPuttyProfile.Text.Trim(); Session.Host = textBoxHostname.Text.Trim(); Session.ExtraArgs = textBoxExtraArgs.Text.Trim(); Session.Port = int.Parse(textBoxPort.Text.Trim()); Session.Username = textBoxUsername.Text.Trim(); Session.SessionId = SessionData.CombineSessionIds(SessionData.GetSessionParentId(Session.SessionId), Session.SessionName); Session.ImageKey = buttonImageSelect.ImageKey; for (int i = 0; i < groupBox1.Controls.Count; i++) { RadioButton rb = (RadioButton)groupBox1.Controls[i]; if (rb.Checked) { Session.Proto = (ConnectionProtocol)rb.Tag; } } DialogResult = DialogResult.OK; } /// <summary> /// Special UI handling for cygterm or mintty sessions /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void radioButtonCygterm_CheckedChanged(object sender, EventArgs e) { string host = this.textBoxHostname.Text; bool isLocalShell = this.radioButtonCygterm.Checked || this.radioButtonMintty.Checked; this.textBoxPort.Enabled = !isLocalShell; this.textBoxExtraArgs.Enabled = !isLocalShell; this.textBoxUsername.Enabled = !isLocalShell; if (isLocalShell) { if (String.IsNullOrEmpty(host) || !host.StartsWith(CygtermStartInfo.LocalHost)) { OldHostname = this.textBoxHostname.Text; this.textBoxHostname.Text = CygtermStartInfo.LocalHost; } } } private void radioButtonRaw_CheckedChanged(object sender, EventArgs e) { if (this.radioButtonRaw.Checked && this.isInitialized) { if (!string.IsNullOrEmpty(OldHostname)) { this.textBoxHostname.Text = OldHostname; OldHostname = null; } } } private void radioButtonTelnet_CheckedChanged(object sender, EventArgs e) { if (this.radioButtonTelnet.Checked && this.isInitialized) { if (!string.IsNullOrEmpty(OldHostname)) { this.textBoxHostname.Text = OldHostname; OldHostname = null; } this.textBoxPort.Text = "23"; } } private void radioButtonRlogin_CheckedChanged(object sender, EventArgs e) { if (this.radioButtonRlogin.Checked && this.isInitialized) { if (!string.IsNullOrEmpty(OldHostname)) { this.textBoxHostname.Text = OldHostname; OldHostname = null; } this.textBoxPort.Text = "513"; } } private void radioButtonSSH_CheckedChanged(object sender, EventArgs e) { if (this.radioButtonSSH.Checked && this.isInitialized) { if (!string.IsNullOrEmpty(OldHostname)) { this.textBoxHostname.Text = OldHostname; OldHostname = null; } this.textBoxPort.Text = "22"; } } public static int GetDefaultPort(ConnectionProtocol protocol) { int port = 22; switch (protocol) { case ConnectionProtocol.Raw: break; case ConnectionProtocol.Rlogin: port = 513; break; case ConnectionProtocol.Serial: break; case ConnectionProtocol.Telnet: port = 23; break; } return port; } #region Icon private void buttonImageSelect_Click(object sender, EventArgs e) { if (this.imgPopup == null) { int n = buttonImageSelect.ImageList.Images.Count; int x = (int) Math.Floor(Math.Sqrt(n)) + 1; int cols = x; int rows = x; imgPopup = new ImageListPopup(); imgPopup.BackgroundColor = Color.FromArgb(241, 241, 241); imgPopup.BackgroundOverColor = Color.FromArgb(102, 154, 204); imgPopup.Init(this.buttonImageSelect.ImageList, 8, 8, cols, rows); imgPopup.ItemClick += new ImageListPopupEventHandler(this.OnItemClicked); } Point pt = PointToScreen(new Point(buttonImageSelect.Left, buttonImageSelect.Bottom)); imgPopup.Show(pt.X + 2, pt.Y); } private void OnItemClicked(object sender, ImageListPopupEventArgs e) { if (imgPopup == sender) { buttonImageSelect.ImageKey = e.SelectedItem; this.toolTip.SetToolTip(this.buttonImageSelect, buttonImageSelect.ImageKey); } } #endregion #region Validation Logic public SessionNameValidationHandler SessionNameValidator { get; set; } private void textBoxSessionName_Validating(object sender, CancelEventArgs e) { if (this.SessionNameValidator != null) { string error; if (!this.SessionNameValidator(this.textBoxSessionName.Text, out error)) { e.Cancel = true; this.SetError(this.textBoxSessionName, error ?? "Invalid Session Name"); } } } private void textBoxSessionName_Validated(object sender, EventArgs e) { this.SetError(this.textBoxSessionName, String.Empty); } private void textBoxPort_Validating(object sender, CancelEventArgs e) { int val; if (!Int32.TryParse(this.textBoxPort.Text, out val)) { e.Cancel = true; this.SetError(this.textBoxPort, "Invalid Port"); } } private void textBoxPort_Validated(object sender, EventArgs e) { this.SetError(this.textBoxPort, String.Empty); } private void textBoxHostname_Validating(object sender, CancelEventArgs e) { if (string.IsNullOrEmpty((string)this.comboBoxPuttyProfile.SelectedItem) && string.IsNullOrEmpty(this.textBoxHostname.Text.Trim())) { if (sender == this.textBoxHostname) { this.SetError(this.textBoxHostname, "A host name must be specified if a Putty Session Profile is not selected"); } else if (sender == this.comboBoxPuttyProfile) { this.SetError(this.comboBoxPuttyProfile, "A Putty Session Profile must be selected if a Host Name is not provided"); } } else { this.SetError(this.textBoxHostname, String.Empty); this.SetError(this.comboBoxPuttyProfile, String.Empty); } } private void comboBoxPuttyProfile_Validating(object sender, CancelEventArgs e) { this.textBoxHostname_Validating(sender, e); } private void comboBoxPuttyProfile_SelectedIndexChanged(object sender, EventArgs e) { this.ValidateChildren(ValidationConstraints.ImmediateChildren); } void SetError(Control control, string error) { this.errorProvider.SetError(control, error); this.EnableDisableSaveButton(); } void EnableDisableSaveButton() { this.buttonSave.Enabled = ( this.errorProvider.GetError(this.textBoxSessionName) == String.Empty && this.errorProvider.GetError(this.textBoxHostname) == String.Empty && this.errorProvider.GetError(this.textBoxPort) == String.Empty && this.errorProvider.GetError(this.comboBoxPuttyProfile) == String.Empty); } #endregion } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Org.Achartengine.Chart { // Metadata.xml XPath class reference: path="/api/package[@name='org.achartengine.chart']/class[@name='LineChart']" [global::Android.Runtime.Register ("org/achartengine/chart/LineChart", DoNotGenerateAcw=true)] public partial class LineChart : global::Org.Achartengine.Chart.XYChart { // Metadata.xml XPath field reference: path="/api/package[@name='org.achartengine.chart']/class[@name='LineChart']/field[@name='TYPE']" [Register ("TYPE")] public const string Type = (string) "Line"; internal static new IntPtr java_class_handle; internal static new IntPtr class_ref { get { return JNIEnv.FindClass ("org/achartengine/chart/LineChart", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (LineChart); } } protected LineChart (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_ctor_Lorg_achartengine_model_XYMultipleSeriesDataset_Lorg_achartengine_renderer_XYMultipleSeriesRenderer_; // Metadata.xml XPath constructor reference: path="/api/package[@name='org.achartengine.chart']/class[@name='LineChart']/constructor[@name='LineChart' and count(parameter)=2 and parameter[1][@type='org.achartengine.model.XYMultipleSeriesDataset'] and parameter[2][@type='org.achartengine.renderer.XYMultipleSeriesRenderer']]" [Register (".ctor", "(Lorg/achartengine/model/XYMultipleSeriesDataset;Lorg/achartengine/renderer/XYMultipleSeriesRenderer;)V", "")] public LineChart (global::Org.Achartengine.Model.XYMultipleSeriesDataset p0, global::Org.Achartengine.Renderer.XYMultipleSeriesRenderer p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { if (Handle != IntPtr.Zero) return; if (GetType () != typeof (LineChart)) { SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lorg/achartengine/model/XYMultipleSeriesDataset;Lorg/achartengine/renderer/XYMultipleSeriesRenderer;)V", new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lorg/achartengine/model/XYMultipleSeriesDataset;Lorg/achartengine/renderer/XYMultipleSeriesRenderer;)V", new JValue (p0), new JValue (p1)); return; } if (id_ctor_Lorg_achartengine_model_XYMultipleSeriesDataset_Lorg_achartengine_renderer_XYMultipleSeriesRenderer_ == IntPtr.Zero) id_ctor_Lorg_achartengine_model_XYMultipleSeriesDataset_Lorg_achartengine_renderer_XYMultipleSeriesRenderer_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lorg/achartengine/model/XYMultipleSeriesDataset;Lorg/achartengine/renderer/XYMultipleSeriesRenderer;)V"); SetHandle ( global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lorg_achartengine_model_XYMultipleSeriesDataset_Lorg_achartengine_renderer_XYMultipleSeriesRenderer_, new JValue (p0), new JValue (p1)), JniHandleOwnership.TransferLocalRef); JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lorg_achartengine_model_XYMultipleSeriesDataset_Lorg_achartengine_renderer_XYMultipleSeriesRenderer_, new JValue (p0), new JValue (p1)); } static Delegate cb_getChartType; #pragma warning disable 0169 static Delegate GetGetChartTypeHandler () { if (cb_getChartType == null) cb_getChartType = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetChartType); return cb_getChartType; } static IntPtr n_GetChartType (IntPtr jnienv, IntPtr native__this) { global::Org.Achartengine.Chart.LineChart __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.LineChart> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return JNIEnv.NewString (__this.ChartType); } #pragma warning restore 0169 static IntPtr id_getChartType; public override string ChartType { // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='LineChart']/method[@name='getChartType' and count(parameter)=0]" [Register ("getChartType", "()Ljava/lang/String;", "GetGetChartTypeHandler")] get { if (id_getChartType == IntPtr.Zero) id_getChartType = JNIEnv.GetMethodID (class_ref, "getChartType", "()Ljava/lang/String;"); if (GetType () == ThresholdType) return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getChartType), JniHandleOwnership.TransferLocalRef); else return JNIEnv.GetString (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_getChartType), JniHandleOwnership.TransferLocalRef); } } static Delegate cb_clickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII; #pragma warning disable 0169 static Delegate GetClickableAreasForPoints_Ljava_util_List_Ljava_util_List_FIIHandler () { if (cb_clickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII == null) cb_clickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr, float, int, int, IntPtr>) n_ClickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII); return cb_clickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII; } static IntPtr n_ClickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, float p2, int p3, int p4) { global::Org.Achartengine.Chart.LineChart __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.LineChart> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); System.Collections.Generic.IList<Java.Lang.Float> p0 = global::Android.Runtime.JavaList<global::Java.Lang.Float>.FromJniHandle (native_p0, JniHandleOwnership.DoNotTransfer); System.Collections.Generic.IList<Java.Lang.Double> p1 = global::Android.Runtime.JavaList<global::Java.Lang.Double>.FromJniHandle (native_p1, JniHandleOwnership.DoNotTransfer); IntPtr __ret = JNIEnv.NewArray (__this.ClickableAreasForPoints (p0, p1, p2, p3, p4)); return __ret; } #pragma warning restore 0169 static IntPtr id_clickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='LineChart']/method[@name='clickableAreasForPoints' and count(parameter)=5 and parameter[1][@type='java.util.List'] and parameter[2][@type='java.util.List'] and parameter[3][@type='float'] and parameter[4][@type='int'] and parameter[5][@type='int']]" [Register ("clickableAreasForPoints", "(Ljava/util/List;Ljava/util/List;FII)[Lorg/achartengine/chart/ClickableArea;", "GetClickableAreasForPoints_Ljava_util_List_Ljava_util_List_FIIHandler")] protected override global::Org.Achartengine.Chart.ClickableArea[] ClickableAreasForPoints (global::System.Collections.Generic.IList<global::Java.Lang.Float> p0, global::System.Collections.Generic.IList<global::Java.Lang.Double> p1, float p2, int p3, int p4) { if (id_clickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII == IntPtr.Zero) id_clickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII = JNIEnv.GetMethodID (class_ref, "clickableAreasForPoints", "(Ljava/util/List;Ljava/util/List;FII)[Lorg/achartengine/chart/ClickableArea;"); IntPtr native_p0 = global::Android.Runtime.JavaList<global::Java.Lang.Float>.ToLocalJniHandle (p0); IntPtr native_p1 = global::Android.Runtime.JavaList<global::Java.Lang.Double>.ToLocalJniHandle (p1); global::Org.Achartengine.Chart.ClickableArea[] __ret; if (GetType () == ThresholdType) __ret = (global::Org.Achartengine.Chart.ClickableArea[]) JNIEnv.GetArray (JNIEnv.CallObjectMethod (Handle, id_clickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII, new JValue (Java.Interop.JavaObjectExtensions.ToInteroperableCollection (p0)), new JValue (Java.Interop.JavaObjectExtensions.ToInteroperableCollection (p1)), new JValue (p2), new JValue (p3), new JValue (p4)), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Achartengine.Chart.ClickableArea)); else __ret = (global::Org.Achartengine.Chart.ClickableArea[]) JNIEnv.GetArray (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, id_clickableAreasForPoints_Ljava_util_List_Ljava_util_List_FII, new JValue (Java.Interop.JavaObjectExtensions.ToInteroperableCollection (p0)), new JValue (Java.Interop.JavaObjectExtensions.ToInteroperableCollection (p1)), new JValue (p2), new JValue (p3), new JValue (p4)), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Achartengine.Chart.ClickableArea)); JNIEnv.DeleteLocalRef (native_p0); JNIEnv.DeleteLocalRef (native_p1); return __ret; } static Delegate cb_drawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_; #pragma warning disable 0169 static Delegate GetDrawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_Handler () { if (cb_drawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_ == null) cb_drawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_ = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr, float, float, int, IntPtr>) n_DrawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_); return cb_drawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_; } static void n_DrawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, float p2, float p3, int p4, IntPtr native_p5) { global::Org.Achartengine.Chart.LineChart __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.LineChart> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Android.Graphics.Canvas p0 = global::Java.Lang.Object.GetObject<global::Android.Graphics.Canvas> (native_p0, JniHandleOwnership.DoNotTransfer); global::Org.Achartengine.Renderer.SimpleSeriesRenderer p1 = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.SimpleSeriesRenderer> (native_p1, JniHandleOwnership.DoNotTransfer); global::Android.Graphics.Paint p5 = global::Java.Lang.Object.GetObject<global::Android.Graphics.Paint> (native_p5, JniHandleOwnership.DoNotTransfer); __this.DrawLegendShape (p0, p1, p2, p3, p4, p5); } #pragma warning restore 0169 static IntPtr id_drawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='LineChart']/method[@name='drawLegendShape' and count(parameter)=6 and parameter[1][@type='android.graphics.Canvas'] and parameter[2][@type='org.achartengine.renderer.SimpleSeriesRenderer'] and parameter[3][@type='float'] and parameter[4][@type='float'] and parameter[5][@type='int'] and parameter[6][@type='android.graphics.Paint']]" [Register ("drawLegendShape", "(Landroid/graphics/Canvas;Lorg/achartengine/renderer/SimpleSeriesRenderer;FFILandroid/graphics/Paint;)V", "GetDrawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_Handler")] public override void DrawLegendShape (global::Android.Graphics.Canvas p0, global::Org.Achartengine.Renderer.SimpleSeriesRenderer p1, float p2, float p3, int p4, global::Android.Graphics.Paint p5) { if (id_drawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_ == IntPtr.Zero) id_drawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_ = JNIEnv.GetMethodID (class_ref, "drawLegendShape", "(Landroid/graphics/Canvas;Lorg/achartengine/renderer/SimpleSeriesRenderer;FFILandroid/graphics/Paint;)V"); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_drawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_, new JValue (p0), new JValue (p1), new JValue (p2), new JValue (p3), new JValue (p4), new JValue (p5)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_drawLegendShape_Landroid_graphics_Canvas_Lorg_achartengine_renderer_SimpleSeriesRenderer_FFILandroid_graphics_Paint_, new JValue (p0), new JValue (p1), new JValue (p2), new JValue (p3), new JValue (p4), new JValue (p5)); } static Delegate cb_drawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII; #pragma warning disable 0169 static Delegate GetDrawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FIIHandler () { if (cb_drawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII == null) cb_drawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, IntPtr, float, int, int>) n_DrawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII); return cb_drawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII; } static void n_DrawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII (IntPtr jnienv, IntPtr native__this, IntPtr native_p0, IntPtr native_p1, IntPtr native_p2, IntPtr native_p3, float p4, int p5, int p6) { global::Org.Achartengine.Chart.LineChart __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.LineChart> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); global::Android.Graphics.Canvas p0 = global::Java.Lang.Object.GetObject<global::Android.Graphics.Canvas> (native_p0, JniHandleOwnership.DoNotTransfer); global::Android.Graphics.Paint p1 = global::Java.Lang.Object.GetObject<global::Android.Graphics.Paint> (native_p1, JniHandleOwnership.DoNotTransfer); System.Collections.Generic.IList<Java.Lang.Float> p2 = global::Android.Runtime.JavaList<global::Java.Lang.Float>.FromJniHandle (native_p2, JniHandleOwnership.DoNotTransfer); global::Org.Achartengine.Renderer.SimpleSeriesRenderer p3 = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Renderer.SimpleSeriesRenderer> (native_p3, JniHandleOwnership.DoNotTransfer); __this.DrawSeries (p0, p1, p2, p3, p4, p5, p6); } #pragma warning restore 0169 static IntPtr id_drawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='LineChart']/method[@name='drawSeries' and count(parameter)=7 and parameter[1][@type='android.graphics.Canvas'] and parameter[2][@type='android.graphics.Paint'] and parameter[3][@type='java.util.List'] and parameter[4][@type='org.achartengine.renderer.SimpleSeriesRenderer'] and parameter[5][@type='float'] and parameter[6][@type='int'] and parameter[7][@type='int']]" [Register ("drawSeries", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;Ljava/util/List;Lorg/achartengine/renderer/SimpleSeriesRenderer;FII)V", "GetDrawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FIIHandler")] public override void DrawSeries (global::Android.Graphics.Canvas p0, global::Android.Graphics.Paint p1, global::System.Collections.Generic.IList<global::Java.Lang.Float> p2, global::Org.Achartengine.Renderer.SimpleSeriesRenderer p3, float p4, int p5, int p6) { if (id_drawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII == IntPtr.Zero) id_drawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII = JNIEnv.GetMethodID (class_ref, "drawSeries", "(Landroid/graphics/Canvas;Landroid/graphics/Paint;Ljava/util/List;Lorg/achartengine/renderer/SimpleSeriesRenderer;FII)V"); IntPtr native_p2 = global::Android.Runtime.JavaList<global::Java.Lang.Float>.ToLocalJniHandle (p2); if (GetType () == ThresholdType) JNIEnv.CallVoidMethod (Handle, id_drawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII, new JValue (p0), new JValue (p1), new JValue (Java.Interop.JavaObjectExtensions.ToInteroperableCollection (p2)), new JValue (p3), new JValue (p4), new JValue (p5), new JValue (p6)); else JNIEnv.CallNonvirtualVoidMethod (Handle, ThresholdClass, id_drawSeries_Landroid_graphics_Canvas_Landroid_graphics_Paint_Ljava_util_List_Lorg_achartengine_renderer_SimpleSeriesRenderer_FII, new JValue (p0), new JValue (p1), new JValue (Java.Interop.JavaObjectExtensions.ToInteroperableCollection (p2)), new JValue (p3), new JValue (p4), new JValue (p5), new JValue (p6)); JNIEnv.DeleteLocalRef (native_p2); } static Delegate cb_getLegendShapeWidth_I; #pragma warning disable 0169 static Delegate GetGetLegendShapeWidth_IHandler () { if (cb_getLegendShapeWidth_I == null) cb_getLegendShapeWidth_I = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, int, int>) n_GetLegendShapeWidth_I); return cb_getLegendShapeWidth_I; } static int n_GetLegendShapeWidth_I (IntPtr jnienv, IntPtr native__this, int p0) { global::Org.Achartengine.Chart.LineChart __this = global::Java.Lang.Object.GetObject<global::Org.Achartengine.Chart.LineChart> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); return __this.GetLegendShapeWidth (p0); } #pragma warning restore 0169 static IntPtr id_getLegendShapeWidth_I; // Metadata.xml XPath method reference: path="/api/package[@name='org.achartengine.chart']/class[@name='LineChart']/method[@name='getLegendShapeWidth' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("getLegendShapeWidth", "(I)I", "GetGetLegendShapeWidth_IHandler")] public override int GetLegendShapeWidth (int p0) { if (id_getLegendShapeWidth_I == IntPtr.Zero) id_getLegendShapeWidth_I = JNIEnv.GetMethodID (class_ref, "getLegendShapeWidth", "(I)I"); if (GetType () == ThresholdType) return JNIEnv.CallIntMethod (Handle, id_getLegendShapeWidth_I, new JValue (p0)); else return JNIEnv.CallNonvirtualIntMethod (Handle, ThresholdClass, id_getLegendShapeWidth_I, new JValue (p0)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { internal partial class LambdaCompiler { private void EmitBinaryExpression(Expression expr) { EmitBinaryExpression(expr, CompilationFlags.EmitAsNoTail); } private void EmitBinaryExpression(Expression expr, CompilationFlags flags) { BinaryExpression b = (BinaryExpression)expr; Debug.Assert(b.NodeType != ExpressionType.AndAlso && b.NodeType != ExpressionType.OrElse && b.NodeType != ExpressionType.Coalesce); if (b.Method != null) { EmitBinaryMethod(b, flags); return; } // For EQ and NE, if there is a user-specified method, use it. // Otherwise implement the C# semantics that allow equality // comparisons on non-primitive nullable structs that don't // overload "==" if ((b.NodeType == ExpressionType.Equal || b.NodeType == ExpressionType.NotEqual) && (b.Type == typeof(bool) || b.Type == typeof(bool?))) { // If we have x==null, x!=null, null==x or null!=x where x is // nullable but not null, then generate a call to x.HasValue. Debug.Assert(!b.IsLiftedToNull || b.Type == typeof(bool?)); if (ConstantCheck.IsNull(b.Left) && !ConstantCheck.IsNull(b.Right) && TypeUtils.IsNullableType(b.Right.Type)) { EmitNullEquality(b.NodeType, b.Right, b.IsLiftedToNull); return; } if (ConstantCheck.IsNull(b.Right) && !ConstantCheck.IsNull(b.Left) && TypeUtils.IsNullableType(b.Left.Type)) { EmitNullEquality(b.NodeType, b.Left, b.IsLiftedToNull); return; } // For EQ and NE, we can avoid some conversions if we're // ultimately just comparing two managed pointers. EmitExpression(GetEqualityOperand(b.Left)); EmitExpression(GetEqualityOperand(b.Right)); } else { // Otherwise generate it normally EmitExpression(b.Left); EmitExpression(b.Right); } EmitBinaryOperator(b.NodeType, b.Left.Type, b.Right.Type, b.Type, b.IsLiftedToNull); } private void EmitNullEquality(ExpressionType op, Expression e, bool isLiftedToNull) { Debug.Assert(TypeUtils.IsNullableType(e.Type)); Debug.Assert(op == ExpressionType.Equal || op == ExpressionType.NotEqual); // If we are lifted to null then just evaluate the expression for its side effects, discard, // and generate null. If we are not lifted to null then generate a call to HasValue. if (isLiftedToNull) { EmitExpressionAsVoid(e); _ilg.EmitDefault(typeof(bool?)); } else { EmitAddress(e, e.Type); _ilg.EmitHasValue(e.Type); if (op == ExpressionType.Equal) { _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); } } } private void EmitBinaryMethod(BinaryExpression b, CompilationFlags flags) { if (b.IsLifted) { ParameterExpression p1 = Expression.Variable(TypeUtils.GetNonNullableType(b.Left.Type), null); ParameterExpression p2 = Expression.Variable(TypeUtils.GetNonNullableType(b.Right.Type), null); MethodCallExpression mc = Expression.Call(null, b.Method, p1, p2); Type resultType = null; if (b.IsLiftedToNull) { resultType = TypeUtils.GetNullableType(mc.Type); } else { switch (b.NodeType) { case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: if (mc.Type != typeof(bool)) { throw Error.ArgumentMustBeBoolean(); } resultType = typeof(bool); break; default: resultType = TypeUtils.GetNullableType(mc.Type); break; } } var variables = new ParameterExpression[] { p1, p2 }; var arguments = new Expression[] { b.Left, b.Right }; ValidateLift(variables, arguments); EmitLift(b.NodeType, resultType, mc, variables, arguments); } else { EmitMethodCallExpression(Expression.Call(null, b.Method, b.Left, b.Right), flags); } } private void EmitBinaryOperator(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull) { bool leftIsNullable = TypeUtils.IsNullableType(leftType); bool rightIsNullable = TypeUtils.IsNullableType(rightType); switch (op) { case ExpressionType.ArrayIndex: if (rightType != typeof(int)) { throw ContractUtils.Unreachable; } EmitGetArrayElement(leftType); return; case ExpressionType.Coalesce: throw Error.UnexpectedCoalesceOperator(); } if (leftIsNullable || rightIsNullable) { EmitLiftedBinaryOp(op, leftType, rightType, resultType, liftedToNull); } else { EmitUnliftedBinaryOp(op, leftType, rightType); EmitConvertArithmeticResult(op, resultType); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private void EmitUnliftedBinaryOp(ExpressionType op, Type leftType, Type rightType) { Debug.Assert(!TypeUtils.IsNullableType(leftType)); Debug.Assert(!TypeUtils.IsNullableType(rightType)); if (op == ExpressionType.Equal || op == ExpressionType.NotEqual) { EmitUnliftedEquality(op, leftType); return; } if (!leftType.GetTypeInfo().IsPrimitive) { throw Error.OperatorNotImplementedForType(op, leftType); } switch (op) { case ExpressionType.Add: _ilg.Emit(OpCodes.Add); break; case ExpressionType.AddChecked: if (TypeUtils.IsFloatingPoint(leftType)) { _ilg.Emit(OpCodes.Add); } else if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Add_Ovf_Un); } else { _ilg.Emit(OpCodes.Add_Ovf); } break; case ExpressionType.Subtract: _ilg.Emit(OpCodes.Sub); break; case ExpressionType.SubtractChecked: if (TypeUtils.IsFloatingPoint(leftType)) { _ilg.Emit(OpCodes.Sub); } else if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Sub_Ovf_Un); } else { _ilg.Emit(OpCodes.Sub_Ovf); } break; case ExpressionType.Multiply: _ilg.Emit(OpCodes.Mul); break; case ExpressionType.MultiplyChecked: if (TypeUtils.IsFloatingPoint(leftType)) { _ilg.Emit(OpCodes.Mul); } else if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Mul_Ovf_Un); } else { _ilg.Emit(OpCodes.Mul_Ovf); } break; case ExpressionType.Divide: if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Div_Un); } else { _ilg.Emit(OpCodes.Div); } break; case ExpressionType.Modulo: if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Rem_Un); } else { _ilg.Emit(OpCodes.Rem); } break; case ExpressionType.And: case ExpressionType.AndAlso: _ilg.Emit(OpCodes.And); break; case ExpressionType.Or: case ExpressionType.OrElse: _ilg.Emit(OpCodes.Or); break; case ExpressionType.LessThan: if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Clt_Un); } else { _ilg.Emit(OpCodes.Clt); } break; case ExpressionType.LessThanOrEqual: { Label labFalse = _ilg.DefineLabel(); Label labEnd = _ilg.DefineLabel(); if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Ble_Un_S, labFalse); } else { _ilg.Emit(OpCodes.Ble_S, labFalse); } _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br_S, labEnd); _ilg.MarkLabel(labFalse); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.MarkLabel(labEnd); } break; case ExpressionType.GreaterThan: if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Cgt_Un); } else { _ilg.Emit(OpCodes.Cgt); } break; case ExpressionType.GreaterThanOrEqual: { Label labFalse = _ilg.DefineLabel(); Label labEnd = _ilg.DefineLabel(); if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Bge_Un_S, labFalse); } else { _ilg.Emit(OpCodes.Bge_S, labFalse); } _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br_S, labEnd); _ilg.MarkLabel(labFalse); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.MarkLabel(labEnd); } break; case ExpressionType.ExclusiveOr: _ilg.Emit(OpCodes.Xor); break; case ExpressionType.LeftShift: if (rightType != typeof(int)) { throw ContractUtils.Unreachable; } EmitShiftMask(leftType); _ilg.Emit(OpCodes.Shl); break; case ExpressionType.RightShift: if (rightType != typeof(int)) { throw ContractUtils.Unreachable; } EmitShiftMask(leftType); if (TypeUtils.IsUnsigned(leftType)) { _ilg.Emit(OpCodes.Shr_Un); } else { _ilg.Emit(OpCodes.Shr); } break; default: throw Error.UnhandledBinary(op); } } // Shift operations have undefined behavior if the shift amount exceeds // the number of bits in the value operand. See CLI III.3.58 and C# 7.9 // for the bit mask used below. private void EmitShiftMask(Type leftType) { int mask = TypeUtils.IsInteger64(leftType) ? 0x3F : 0x1F; _ilg.EmitInt(mask); _ilg.Emit(OpCodes.And); } // Binary/unary operations on 8 and 16 bit operand types will leave a // 32-bit value on the stack, because that's how IL works. For these // cases, we need to cast it back to the resultType, possibly using a // checked conversion if the original operator was convert private void EmitConvertArithmeticResult(ExpressionType op, Type resultType) { Debug.Assert(!resultType.IsNullableType()); switch (resultType.GetTypeCode()) { case TypeCode.Byte: _ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_U1 : OpCodes.Conv_U1); break; case TypeCode.SByte: _ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_I1 : OpCodes.Conv_I1); break; case TypeCode.UInt16: _ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_U2 : OpCodes.Conv_U2); break; case TypeCode.Int16: _ilg.Emit(IsChecked(op) ? OpCodes.Conv_Ovf_I2 : OpCodes.Conv_I2); break; } } private void EmitUnliftedEquality(ExpressionType op, Type type) { Debug.Assert(op == ExpressionType.Equal || op == ExpressionType.NotEqual); if (!type.GetTypeInfo().IsPrimitive && type.GetTypeInfo().IsValueType && !type.GetTypeInfo().IsEnum) { throw Error.OperatorNotImplementedForType(op, type); } _ilg.Emit(OpCodes.Ceq); if (op == ExpressionType.NotEqual) { _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private void EmitLiftedBinaryOp(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull) { Debug.Assert(TypeUtils.IsNullableType(leftType) || TypeUtils.IsNullableType(rightType)); switch (op) { case ExpressionType.And: if (leftType == typeof(bool?)) { EmitLiftedBooleanAnd(); } else { EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType); } break; case ExpressionType.Or: if (leftType == typeof(bool?)) { EmitLiftedBooleanOr(); } else { EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType); } break; case ExpressionType.ExclusiveOr: case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.LeftShift: case ExpressionType.RightShift: EmitLiftedBinaryArithmetic(op, leftType, rightType, resultType); break; case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: EmitLiftedRelational(op, leftType, rightType, resultType, liftedToNull); break; case ExpressionType.AndAlso: case ExpressionType.OrElse: default: throw ContractUtils.Unreachable; } } private void EmitLiftedRelational(ExpressionType op, Type leftType, Type rightType, Type resultType, bool liftedToNull) { Debug.Assert(TypeUtils.IsNullableType(leftType)); Label shortCircuit = _ilg.DefineLabel(); LocalBuilder locLeft = GetLocal(leftType); LocalBuilder locRight = GetLocal(rightType); // store values (reverse order since they are already on the stack) _ilg.Emit(OpCodes.Stloc, locRight); _ilg.Emit(OpCodes.Stloc, locLeft); if (op == ExpressionType.Equal) { // test for both null -> true _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(leftType); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(rightType); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.And); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brtrue_S, shortCircuit); _ilg.Emit(OpCodes.Pop); // test for either is null -> false _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(leftType); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(rightType); _ilg.Emit(OpCodes.And); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brfalse_S, shortCircuit); _ilg.Emit(OpCodes.Pop); } else if (op == ExpressionType.NotEqual) { // test for both null -> false _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(leftType); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(rightType); _ilg.Emit(OpCodes.Or); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brfalse_S, shortCircuit); _ilg.Emit(OpCodes.Pop); // test for either is null -> true _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(leftType); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(rightType); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Or); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brtrue_S, shortCircuit); _ilg.Emit(OpCodes.Pop); } else { // test for either is null -> false _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(leftType); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(rightType); _ilg.Emit(OpCodes.And); _ilg.Emit(OpCodes.Dup); _ilg.Emit(OpCodes.Brfalse_S, shortCircuit); _ilg.Emit(OpCodes.Pop); } // do op on values _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitGetValueOrDefault(leftType); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitGetValueOrDefault(rightType); //RELEASING locLeft locRight FreeLocal(locLeft); FreeLocal(locRight); EmitBinaryOperator( op, TypeUtils.GetNonNullableType(leftType), TypeUtils.GetNonNullableType(rightType), TypeUtils.GetNonNullableType(resultType), false ); if (!liftedToNull) { _ilg.MarkLabel(shortCircuit); } if (!TypeUtils.AreEquivalent(resultType, TypeUtils.GetNonNullableType(resultType))) { _ilg.EmitConvertToType(TypeUtils.GetNonNullableType(resultType), resultType, true); } if (liftedToNull) { Label labEnd = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Br, labEnd); _ilg.MarkLabel(shortCircuit); _ilg.Emit(OpCodes.Pop); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Unbox_Any, resultType); _ilg.MarkLabel(labEnd); } } private void EmitLiftedBinaryArithmetic(ExpressionType op, Type leftType, Type rightType, Type resultType) { bool leftIsNullable = TypeUtils.IsNullableType(leftType); bool rightIsNullable = TypeUtils.IsNullableType(rightType); Debug.Assert(leftIsNullable || rightIsNullable); Label labIfNull = _ilg.DefineLabel(); Label labEnd = _ilg.DefineLabel(); LocalBuilder locLeft = GetLocal(leftType); LocalBuilder locRight = GetLocal(rightType); LocalBuilder locResult = GetLocal(resultType); // store values (reverse order since they are already on the stack) _ilg.Emit(OpCodes.Stloc, locRight); _ilg.Emit(OpCodes.Stloc, locLeft); // test for null // use short circuiting if (leftIsNullable) { _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(leftType); _ilg.Emit(OpCodes.Brfalse_S, labIfNull); } if (rightIsNullable) { _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(rightType); _ilg.Emit(OpCodes.Brfalse_S, labIfNull); } // do op on values if (leftIsNullable) { _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitGetValueOrDefault(leftType); } else { _ilg.Emit(OpCodes.Ldloc, locLeft); } if (rightIsNullable) { _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitGetValueOrDefault(rightType); } else { _ilg.Emit(OpCodes.Ldloc, locRight); } //RELEASING locLeft locRight FreeLocal(locLeft); FreeLocal(locRight); EmitBinaryOperator(op, TypeUtils.GetNonNullableType(leftType), TypeUtils.GetNonNullableType(rightType), TypeUtils.GetNonNullableType(resultType), false); // construct result type ConstructorInfo ci = resultType.GetConstructor(new Type[] { TypeUtils.GetNonNullableType(resultType) }); _ilg.Emit(OpCodes.Newobj, ci); _ilg.Emit(OpCodes.Stloc, locResult); _ilg.Emit(OpCodes.Br_S, labEnd); // if null then create a default one _ilg.MarkLabel(labIfNull); _ilg.Emit(OpCodes.Ldloca, locResult); _ilg.Emit(OpCodes.Initobj, resultType); _ilg.MarkLabel(labEnd); _ilg.Emit(OpCodes.Ldloc, locResult); //RELEASING locResult FreeLocal(locResult); } private void EmitLiftedBooleanAnd() { Type type = typeof(bool?); Label labComputeRight = _ilg.DefineLabel(); Label labReturnFalse = _ilg.DefineLabel(); Label labReturnNull = _ilg.DefineLabel(); Label labReturnValue = _ilg.DefineLabel(); Label labExit = _ilg.DefineLabel(); // store values (reverse order since they are already on the stack) LocalBuilder locLeft = GetLocal(type); LocalBuilder locRight = GetLocal(type); _ilg.Emit(OpCodes.Stloc, locRight); _ilg.Emit(OpCodes.Stloc, locLeft); // compute left _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse, labComputeRight); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brtrue, labReturnFalse); // compute right _ilg.MarkLabel(labComputeRight); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse_S, labReturnNull); _ilg.Emit(OpCodes.Ldloca, locRight); //RELEASING locRight FreeLocal(locRight); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brtrue_S, labReturnFalse); // check left for null again _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse, labReturnNull); // return true _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Br_S, labReturnValue); // return false _ilg.MarkLabel(labReturnFalse); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br_S, labReturnValue); _ilg.MarkLabel(labReturnValue); ConstructorInfo ci = type.GetConstructor(new Type[] { typeof(bool) }); _ilg.Emit(OpCodes.Newobj, ci); _ilg.Emit(OpCodes.Stloc, locLeft); _ilg.Emit(OpCodes.Br, labExit); // return null _ilg.MarkLabel(labReturnNull); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.Emit(OpCodes.Initobj, type); _ilg.MarkLabel(labExit); _ilg.Emit(OpCodes.Ldloc, locLeft); //RELEASING locLeft FreeLocal(locLeft); } private void EmitLiftedBooleanOr() { Type type = typeof(bool?); Label labComputeRight = _ilg.DefineLabel(); Label labReturnTrue = _ilg.DefineLabel(); Label labReturnNull = _ilg.DefineLabel(); Label labReturnValue = _ilg.DefineLabel(); Label labExit = _ilg.DefineLabel(); // store values (reverse order since they are already on the stack) LocalBuilder locLeft = GetLocal(type); LocalBuilder locRight = GetLocal(type); _ilg.Emit(OpCodes.Stloc, locRight); _ilg.Emit(OpCodes.Stloc, locLeft); // compute left _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse, labComputeRight); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brfalse, labReturnTrue); // compute right _ilg.MarkLabel(labComputeRight); _ilg.Emit(OpCodes.Ldloca, locRight); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse_S, labReturnNull); _ilg.Emit(OpCodes.Ldloca, locRight); //RELEASING locRight FreeLocal(locRight); _ilg.EmitGetValueOrDefault(type); _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Ceq); _ilg.Emit(OpCodes.Brfalse_S, labReturnTrue); // check left for null again _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.EmitHasValue(type); _ilg.Emit(OpCodes.Brfalse, labReturnNull); // return false _ilg.Emit(OpCodes.Ldc_I4_0); _ilg.Emit(OpCodes.Br_S, labReturnValue); // return true _ilg.MarkLabel(labReturnTrue); _ilg.Emit(OpCodes.Ldc_I4_1); _ilg.Emit(OpCodes.Br_S, labReturnValue); _ilg.MarkLabel(labReturnValue); ConstructorInfo ci = type.GetConstructor(new Type[] { typeof(bool) }); _ilg.Emit(OpCodes.Newobj, ci); _ilg.Emit(OpCodes.Stloc, locLeft); _ilg.Emit(OpCodes.Br, labExit); // return null _ilg.MarkLabel(labReturnNull); _ilg.Emit(OpCodes.Ldloca, locLeft); _ilg.Emit(OpCodes.Initobj, type); _ilg.MarkLabel(labExit); _ilg.Emit(OpCodes.Ldloc, locLeft); //RELEASING locLeft FreeLocal(locLeft); } } }
// 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.Linq; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Algorithms.Tests { public class AesGcmTests : AesAEADTests { [Theory] [InlineData(0, 1)] [InlineData(0, 30)] [InlineData(1, 1)] [InlineData(1, 100)] [InlineData(7, 12)] [InlineData(16, 16)] [InlineData(17, 29)] [InlineData(32, 7)] [InlineData(41, 25)] [InlineData(48, 22)] [InlineData(50, 5)] public static void EncryptTamperAADDecrypt(int dataLength, int additionalDataLength) { byte[] additionalData = new byte[additionalDataLength]; RandomNumberGenerator.Fill(additionalData); byte[] plaintext = Enumerable.Range(1, dataLength).Select((x) => (byte)x).ToArray(); byte[] ciphertext = new byte[dataLength]; byte[] key = new byte[16]; byte[] nonce = new byte[AesGcm.NonceByteSizes.MinSize]; byte[] tag = new byte[AesGcm.TagByteSizes.MinSize]; RandomNumberGenerator.Fill(key); RandomNumberGenerator.Fill(nonce); using (var aesGcm = new AesGcm(key)) { aesGcm.Encrypt(nonce, plaintext, ciphertext, tag, additionalData); additionalData[0] ^= 1; byte[] decrypted = new byte[dataLength]; Assert.Throws<CryptographicException>( () => aesGcm.Decrypt(nonce, ciphertext, tag, decrypted, additionalData)); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(17)] [InlineData(29)] [InlineData(33)] public static void InvalidKeyLength(int keyLength) { byte[] key = new byte[keyLength]; Assert.Throws<CryptographicException>(() => new AesGcm(key)); } [Theory] [MemberData(nameof(GetInvalidNonceSizes))] public static void InvalidNonceSize(int nonceSize) { int dataLength = 30; byte[] plaintext = Enumerable.Range(1, dataLength).Select((x) => (byte)x).ToArray(); byte[] ciphertext = new byte[dataLength]; byte[] key = new byte[16]; byte[] nonce = new byte[nonceSize]; byte[] tag = new byte[AesGcm.TagByteSizes.MinSize]; RandomNumberGenerator.Fill(key); RandomNumberGenerator.Fill(nonce); using (var aesGcm = new AesGcm(key)) { Assert.Throws<ArgumentException>("nonce", () => aesGcm.Encrypt(nonce, plaintext, ciphertext, tag)); } } [Theory] [MemberData(nameof(GetValidNonceSizes))] public static void ValidNonceSize(int nonceSize) { const int dataLength = 35; byte[] plaintext = Enumerable.Range(1, dataLength).Select((x) => (byte)x).ToArray(); byte[] ciphertext = new byte[dataLength]; byte[] key = new byte[16]; byte[] nonce = new byte[nonceSize]; byte[] tag = new byte[AesGcm.TagByteSizes.MinSize]; RandomNumberGenerator.Fill(key); RandomNumberGenerator.Fill(nonce); using (var aesGcm = new AesGcm(key)) { aesGcm.Encrypt(nonce, plaintext, ciphertext, tag); byte[] decrypted = new byte[dataLength]; aesGcm.Decrypt(nonce, ciphertext, tag, decrypted); Assert.Equal(plaintext, decrypted); } } [Theory] [MemberData(nameof(GetInvalidTagSizes))] public static void InvalidTagSize(int tagSize) { int dataLength = 30; byte[] plaintext = Enumerable.Range(1, dataLength).Select((x) => (byte)x).ToArray(); byte[] ciphertext = new byte[dataLength]; byte[] key = new byte[16]; byte[] nonce = new byte[12]; byte[] tag = new byte[tagSize]; RandomNumberGenerator.Fill(key); RandomNumberGenerator.Fill(nonce); using (var aesGcm = new AesGcm(key)) { Assert.Throws<ArgumentException>("tag", () => aesGcm.Encrypt(nonce, plaintext, ciphertext, tag)); } } [Theory] [MemberData(nameof(GetValidTagSizes))] public static void ValidTagSize(int tagSize) { const int dataLength = 35; byte[] plaintext = Enumerable.Range(1, dataLength).Select((x) => (byte)x).ToArray(); byte[] ciphertext = new byte[dataLength]; byte[] key = new byte[16]; byte[] nonce = new byte[12]; byte[] tag = new byte[tagSize]; RandomNumberGenerator.Fill(key); RandomNumberGenerator.Fill(nonce); using (var aesGcm = new AesGcm(key)) { aesGcm.Encrypt(nonce, plaintext, ciphertext, tag); byte[] decrypted = new byte[dataLength]; aesGcm.Decrypt(nonce, ciphertext, tag, decrypted); Assert.Equal(plaintext, decrypted); } } [Fact] public static void TwoEncryptionsAndDecryptionsUsingOneInstance() { byte[] key = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray(); byte[] originalData1 = Enumerable.Range(1, 15).Select((x) => (byte)x).ToArray(); byte[] originalData2 = Enumerable.Range(14, 97).Select((x) => (byte)x).ToArray(); byte[] associatedData2 = Enumerable.Range(100, 109).Select((x) => (byte)x).ToArray(); byte[] nonce1 = "b41329dd64af2c3036661b46".HexToByteArray(); byte[] nonce2 = "8ba10892e8b87d031196bf99".HexToByteArray(); byte[] expectedCiphertext1 = "f1af1fb2d4485cc536d618475d52ff".HexToByteArray(); byte[] expectedTag1 = "5ab65624c46b8160f34e81f5".HexToByteArray(); byte[] expectedCiphertext2 = ( "217bed01446d731a372a2b30ac7fcd73aed7c946d9171ae9c00b1c589ca73ba2" + "1c1bac79235d9ac0d0c899184dd8596b866fd96a6c1a28083557b43a5cbb5315" + "00e8cfbad8247c6d1deb51a7c5dfe45801a8d8d519b3fa982f546aa2d02db978" + "da").HexToByteArray(); byte[] expectedTag2 = "9c75d006640ff4fb68c60c9548a45cf8".HexToByteArray(); using (var aesGcm = new AesGcm(key)) { byte[] ciphertext1 = new byte[originalData1.Length]; byte[] tag1 = new byte[expectedTag1.Length]; aesGcm.Encrypt(nonce1, originalData1, ciphertext1, tag1); Assert.Equal(expectedCiphertext1, ciphertext1); Assert.Equal(expectedTag1, tag1); byte[] ciphertext2 = new byte[originalData2.Length]; byte[] tag2 = new byte[expectedTag2.Length]; aesGcm.Encrypt(nonce2, originalData2, ciphertext2, tag2, associatedData2); Assert.Equal(expectedCiphertext2, ciphertext2); Assert.Equal(expectedTag2, tag2); byte[] plaintext1 = new byte[originalData1.Length]; aesGcm.Decrypt(nonce1, ciphertext1, tag1, plaintext1); Assert.Equal(originalData1, plaintext1); byte[] plaintext2 = new byte[originalData2.Length]; aesGcm.Decrypt(nonce2, ciphertext2, tag2, plaintext2, associatedData2); Assert.Equal(originalData2, plaintext2); } } [Theory] [InlineData(0, 1)] [InlineData(1, 0)] [InlineData(3, 4)] [InlineData(4, 3)] [InlineData(20, 120)] [InlineData(120, 20)] public static void PlaintextAndCiphertextSizeDiffer(int ptLen, int ctLen) { byte[] key = new byte[16]; byte[] nonce = new byte[12]; byte[] plaintext = new byte[ptLen]; byte[] ciphertext = new byte[ctLen]; byte[] tag = new byte[16]; using (var aesGcm = new AesGcm(key)) { Assert.Throws<ArgumentException>(() => aesGcm.Encrypt(nonce, plaintext, ciphertext, tag)); Assert.Throws<ArgumentException>(() => aesGcm.Decrypt(nonce, ciphertext, tag, plaintext)); } } [Fact] public static void NullKey() { Assert.Throws<ArgumentNullException>(() => new AesGcm((byte[])null)); } [Fact] public static void EncryptDecryptNullNonce() { byte[] key = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray(); byte[] plaintext = new byte[0]; byte[] ciphertext = new byte[0]; byte[] tag = new byte[16]; using (var aesGcm = new AesGcm(key)) { Assert.Throws<ArgumentNullException>(() => aesGcm.Encrypt((byte[])null, plaintext, ciphertext, tag)); Assert.Throws<ArgumentNullException>(() => aesGcm.Decrypt((byte[])null, ciphertext, tag, plaintext)); } } [Fact] public static void EncryptDecryptNullPlaintext() { byte[] key = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray(); byte[] nonce = new byte[12]; byte[] ciphertext = new byte[0]; byte[] tag = new byte[16]; using (var aesGcm = new AesGcm(key)) { Assert.Throws<ArgumentNullException>(() => aesGcm.Encrypt(nonce, (byte[])null, ciphertext, tag)); Assert.Throws<ArgumentNullException>(() => aesGcm.Decrypt(nonce, ciphertext, tag, (byte[])null)); } } [Fact] public static void EncryptDecryptNullCiphertext() { byte[] key = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray(); byte[] nonce = new byte[12]; byte[] plaintext = new byte[0]; byte[] tag = new byte[16]; using (var aesGcm = new AesGcm(key)) { Assert.Throws<ArgumentNullException>(() => aesGcm.Encrypt(nonce, plaintext, (byte[])null, tag)); Assert.Throws<ArgumentNullException>(() => aesGcm.Decrypt(nonce, (byte[])null, tag, plaintext)); } } [Fact] public static void EncryptDecryptNullTag() { byte[] key = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray(); byte[] nonce = new byte[12]; byte[] plaintext = new byte[0]; byte[] ciphertext = new byte[0]; using (var aesGcm = new AesGcm(key)) { Assert.Throws<ArgumentNullException>(() => aesGcm.Encrypt(nonce, plaintext, ciphertext, (byte[])null)); Assert.Throws<ArgumentNullException>(() => aesGcm.Decrypt(nonce, ciphertext, (byte[])null, plaintext)); } } [Fact] public static void InplaceEncrypDecrypt() { byte[] key = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray(); byte[] nonce = new byte[12]; byte[] originalPlaintext = new byte[] { 1, 2, 8, 12, 16, 99, 0 }; byte[] data = (byte[])originalPlaintext.Clone(); byte[] tag = new byte[16]; RandomNumberGenerator.Fill(nonce); using (var aesGcm = new AesGcm(key)) { aesGcm.Encrypt(nonce, data, data, tag); Assert.NotEqual(originalPlaintext, data); aesGcm.Decrypt(nonce, data, tag, data); Assert.Equal(originalPlaintext, data); } } [Fact] public static void InplaceEncrypTamperTagDecrypt() { byte[] key = "d5a194ed90cfe08abecd4691997ceb2c".HexToByteArray(); byte[] nonce = new byte[12]; byte[] originalPlaintext = new byte[] { 1, 2, 8, 12, 16, 99, 0 }; byte[] data = (byte[])originalPlaintext.Clone(); byte[] tag = new byte[16]; RandomNumberGenerator.Fill(nonce); using (var aesGcm = new AesGcm(key)) { aesGcm.Encrypt(nonce, data, data, tag); Assert.NotEqual(originalPlaintext, data); tag[0] ^= 1; Assert.Throws<CryptographicException>( () => aesGcm.Decrypt(nonce, data, tag, data)); Assert.Equal(new byte[data.Length], data); } } [Theory] [MemberData(nameof(GetNistGcmTestCases))] public static void AesGcmNistTests(AEADTest testCase) { using (var aesGcm = new AesGcm(testCase.Key)) { byte[] ciphertext = new byte[testCase.Plaintext.Length]; byte[] tag = new byte[testCase.Tag.Length]; aesGcm.Encrypt(testCase.Nonce, testCase.Plaintext, ciphertext, tag, testCase.AssociatedData); Assert.Equal(testCase.Ciphertext, ciphertext); Assert.Equal(testCase.Tag, tag); byte[] plaintext = new byte[testCase.Plaintext.Length]; aesGcm.Decrypt(testCase.Nonce, ciphertext, tag, plaintext, testCase.AssociatedData); Assert.Equal(testCase.Plaintext, plaintext); } } [Theory] [MemberData(nameof(GetNistGcmTestCases))] public static void AesGcmNistTestsTamperTag(AEADTest testCase) { using (var aesGcm = new AesGcm(testCase.Key)) { byte[] ciphertext = new byte[testCase.Plaintext.Length]; byte[] tag = new byte[testCase.Tag.Length]; aesGcm.Encrypt(testCase.Nonce, testCase.Plaintext, ciphertext, tag, testCase.AssociatedData); Assert.Equal(testCase.Ciphertext, ciphertext); Assert.Equal(testCase.Tag, tag); tag[0] ^= 1; byte[] plaintext = new byte[testCase.Plaintext.Length]; RandomNumberGenerator.Fill(plaintext); Assert.Throws<CryptographicException>( () => aesGcm.Decrypt(testCase.Nonce, ciphertext, tag, plaintext, testCase.AssociatedData)); Assert.Equal(new byte[plaintext.Length], plaintext); } } [Theory] [MemberData(nameof(GetNistGcmTestCasesWithNonEmptyPT))] public static void AesGcmNistTestsTamperCiphertext(AEADTest testCase) { using (var aesGcm = new AesGcm(testCase.Key)) { byte[] ciphertext = new byte[testCase.Plaintext.Length]; byte[] tag = new byte[testCase.Tag.Length]; aesGcm.Encrypt(testCase.Nonce, testCase.Plaintext, ciphertext, tag, testCase.AssociatedData); Assert.Equal(testCase.Ciphertext, ciphertext); Assert.Equal(testCase.Tag, tag); ciphertext[0] ^= 1; byte[] plaintext = new byte[testCase.Plaintext.Length]; RandomNumberGenerator.Fill(plaintext); Assert.Throws<CryptographicException>( () => aesGcm.Decrypt(testCase.Nonce, ciphertext, tag, plaintext, testCase.AssociatedData)); Assert.Equal(new byte[plaintext.Length], plaintext); } } public static IEnumerable<object[]> GetValidNonceSizes() { return GetValidSizes(AesGcm.NonceByteSizes); } public static IEnumerable<object[]> GetInvalidNonceSizes() { return GetInvalidSizes(AesGcm.NonceByteSizes); } public static IEnumerable<object[]> GetValidTagSizes() { return GetValidSizes(AesGcm.TagByteSizes); } public static IEnumerable<object[]> GetInvalidTagSizes() { return GetInvalidSizes(AesGcm.TagByteSizes); } // https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/mac/gcmtestvectors.zip private const string NistGcmTestVectors = "NIST GCM Test Vectors"; // http://web.archive.org/web/20170811123217/http://csrc.nist.gov/groups/ST/toolkit//BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf private const string NistGcmSpecTestCases = "NIST GCM Spec test cases"; public static IEnumerable<object[]> GetNistGcmTestCases() { foreach (AEADTest test in GetNistTests()) { yield return new object[] { test }; } } public static IEnumerable<object[]> GetNistGcmTestCasesWithNonEmptyPT() { foreach (AEADTest test in GetNistTests()) { if (test.Plaintext.Length > 0) yield return new object[] { test }; } } private static IEnumerable<AEADTest> GetNistTests() { foreach (AEADTest test in s_nistGcmSpecTestCases) { yield return test; } foreach (AEADTest test in s_nistGcmTestVectorsSelectedCases) { yield return test; } } // CaseId is unique per test case private static readonly AEADTest[] s_nistGcmSpecTestCases = new AEADTest[] { new AEADTest { Source = NistGcmSpecTestCases, CaseId = 1, Key = "00000000000000000000000000000000".HexToByteArray(), Nonce = "000000000000000000000000".HexToByteArray(), Plaintext = Array.Empty<byte>(), AssociatedData = null, Ciphertext = Array.Empty<byte>(), Tag = "58e2fccefa7e3061367f1d57a4e7455a".HexToByteArray(), }, new AEADTest { Source = NistGcmSpecTestCases, CaseId = 2, Key = "00000000000000000000000000000000".HexToByteArray(), Nonce = "000000000000000000000000".HexToByteArray(), Plaintext = "00000000000000000000000000000000".HexToByteArray(), AssociatedData = null, Ciphertext = "0388dace60b6a392f328c2b971b2fe78".HexToByteArray(), Tag = "ab6e47d42cec13bdf53a67b21257bddf".HexToByteArray(), }, new AEADTest { Source = NistGcmSpecTestCases, CaseId = 3, Key = "feffe9928665731c6d6a8f9467308308".HexToByteArray(), Nonce = "cafebabefacedbaddecaf888".HexToByteArray(), Plaintext = ( "d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" + "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b391aafd255").HexToByteArray(), AssociatedData = null, Ciphertext = ( "42831ec2217774244b7221b784d0d49c" + "e3aa212f2c02a4e035c17e2329aca12e" + "21d514b25466931c7d8f6a5aac84aa05" + "1ba30b396a0aac973d58e091473f5985").HexToByteArray(), Tag = "4d5c2af327cd64a62cf35abd2ba6fab4".HexToByteArray(), }, new AEADTest { Source = NistGcmSpecTestCases, CaseId = 4, Key = "feffe9928665731c6d6a8f9467308308".HexToByteArray(), Nonce = "cafebabefacedbaddecaf888".HexToByteArray(), Plaintext = ( "d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" + "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b39").HexToByteArray(), AssociatedData = ( "feedfacedeadbeeffeedfacedeadbeef" + "abaddad2").HexToByteArray(), Ciphertext = ( "42831ec2217774244b7221b784d0d49c" + "e3aa212f2c02a4e035c17e2329aca12e" + "21d514b25466931c7d8f6a5aac84aa05" + "1ba30b396a0aac973d58e091").HexToByteArray(), Tag = "5bc94fbc3221a5db94fae95ae7121a47".HexToByteArray(), }, // cases 5, 6 have not supported nonce size new AEADTest { Source = NistGcmSpecTestCases, CaseId = 7, Key = ( "00000000000000000000000000000000" + "0000000000000000").HexToByteArray(), Nonce = "000000000000000000000000".HexToByteArray(), Plaintext = Array.Empty<byte>(), AssociatedData = null, Ciphertext = Array.Empty<byte>(), Tag = "cd33b28ac773f74ba00ed1f312572435".HexToByteArray(), }, new AEADTest { Source = NistGcmSpecTestCases, CaseId = 8, Key = ( "00000000000000000000000000000000" + "0000000000000000").HexToByteArray(), Nonce = "000000000000000000000000".HexToByteArray(), Plaintext = "00000000000000000000000000000000".HexToByteArray(), AssociatedData = null, Ciphertext = "98e7247c07f0fe411c267e4384b0f600".HexToByteArray(), Tag = "2ff58d80033927ab8ef4d4587514f0fb".HexToByteArray(), }, new AEADTest { Source = NistGcmSpecTestCases, CaseId = 9, Key = ( "feffe9928665731c6d6a8f9467308308" + "feffe9928665731c").HexToByteArray(), Nonce = "cafebabefacedbaddecaf888".HexToByteArray(), Plaintext = ( "d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" + "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b391aafd255").HexToByteArray(), Ciphertext = ( "3980ca0b3c00e841eb06fac4872a2757" + "859e1ceaa6efd984628593b40ca1e19c" + "7d773d00c144c525ac619d18c84a3f47" + "18e2448b2fe324d9ccda2710acade256").HexToByteArray(), Tag = "9924a7c8587336bfb118024db8674a14".HexToByteArray(), }, new AEADTest { Source = NistGcmSpecTestCases, CaseId = 10, Key = ( "feffe9928665731c6d6a8f9467308308" + "feffe9928665731c").HexToByteArray(), Nonce = "cafebabefacedbaddecaf888".HexToByteArray(), Plaintext = ( "d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" + "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b39").HexToByteArray(), AssociatedData = ( "feedfacedeadbeeffeedfacedeadbeef" + "abaddad2").HexToByteArray(), Ciphertext = ( "3980ca0b3c00e841eb06fac4872a2757" + "859e1ceaa6efd984628593b40ca1e19c" + "7d773d00c144c525ac619d18c84a3f47" + "18e2448b2fe324d9ccda2710").HexToByteArray(), Tag = "2519498e80f1478f37ba55bd6d27618c".HexToByteArray(), }, // cases 11, 12 have not supported nonce size new AEADTest { Source = NistGcmSpecTestCases, CaseId = 13, Key = ( "00000000000000000000000000000000" + "00000000000000000000000000000000").HexToByteArray(), Nonce = "000000000000000000000000".HexToByteArray(), Plaintext = Array.Empty<byte>(), AssociatedData = null, Ciphertext = Array.Empty<byte>(), Tag = "530f8afbc74536b9a963b4f1c4cb738b".HexToByteArray(), }, new AEADTest { Source = NistGcmSpecTestCases, CaseId = 14, Key = ( "00000000000000000000000000000000" + "00000000000000000000000000000000").HexToByteArray(), Nonce = "000000000000000000000000".HexToByteArray(), Plaintext = "00000000000000000000000000000000".HexToByteArray(), AssociatedData = null, Ciphertext = "cea7403d4d606b6e074ec5d3baf39d18".HexToByteArray(), Tag = "d0d1c8a799996bf0265b98b5d48ab919".HexToByteArray(), }, new AEADTest { Source = NistGcmSpecTestCases, CaseId = 15, Key = ( "feffe9928665731c6d6a8f9467308308" + "feffe9928665731c6d6a8f9467308308").HexToByteArray(), Nonce = "cafebabefacedbaddecaf888".HexToByteArray(), Plaintext = ( "d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" + "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b391aafd255").HexToByteArray(), AssociatedData = null, Ciphertext = ( "522dc1f099567d07f47f37a32a84427d" + "643a8cdcbfe5c0c97598a2bd2555d1aa" + "8cb08e48590dbb3da7b08b1056828838" + "c5f61e6393ba7a0abcc9f662898015ad").HexToByteArray(), Tag = "b094dac5d93471bdec1a502270e3cc6c".HexToByteArray(), }, new AEADTest { Source = NistGcmSpecTestCases, CaseId = 16, Key = ( "feffe9928665731c6d6a8f9467308308" + "feffe9928665731c6d6a8f9467308308").HexToByteArray(), Nonce = "cafebabefacedbaddecaf888".HexToByteArray(), Plaintext = ( "d9313225f88406e5a55909c5aff5269a" + "86a7a9531534f7da2e4c303d8a318a72" + "1c3c0c95956809532fcf0e2449a6b525" + "b16aedf5aa0de657ba637b39").HexToByteArray(), AssociatedData = ( "feedfacedeadbeeffeedfacedeadbeef" + "abaddad2").HexToByteArray(), Ciphertext = ( "522dc1f099567d07f47f37a32a84427d" + "643a8cdcbfe5c0c97598a2bd2555d1aa" + "8cb08e48590dbb3da7b08b1056828838" + "c5f61e6393ba7a0abcc9f662").HexToByteArray(), Tag = "76fc6ece0f4e1768cddf8853bb2d551b".HexToByteArray(), }, // cases 17, 18 have not supported nonce size }; // [ CaseId; Key.Length; Nonce.Length; Plaintext.Length; AssociatedData.Length; Tag.Length ] is unique private static readonly AEADTest[] s_nistGcmTestVectorsSelectedCases = new AEADTest[] { // key length = 128 new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "11754cd72aec309bf52f7687212e8957".HexToByteArray(), Nonce = "3c819d9a9bed087615030b65".HexToByteArray(), Plaintext = Array.Empty<byte>(), AssociatedData = null, Ciphertext = Array.Empty<byte>(), Tag = "250327c674aaf477aef2675748cf6971".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "4df7a13e43c3d7b66b1a72fac5ba398e".HexToByteArray(), Nonce = "97179a3a2d417908dcf0fb28".HexToByteArray(), Plaintext = Array.Empty<byte>(), AssociatedData = "cbb7fc0010c255661e23b07dbd804b1e06ae70ac".HexToByteArray(), Ciphertext = Array.Empty<byte>(), Tag = "37791edae6c137ea946cfb40".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "0ef21489e942ae5240e41749346a86a2".HexToByteArray(), Nonce = "431ae3f1a702cc34b55b90bf".HexToByteArray(), Plaintext = "882deb960fd0f8c98c707ade59".HexToByteArray(), AssociatedData = ( "d6d20f982bdad4b70213bbc5f3921f068e7784c30070f" + "fe5c06f0daa8019b6ed95b95ba294630c21008d749eb7" + "1e83e847fb6ca797aaa3035e714cdb13a867ad90b2eba" + "a652d50a5b6adc84e34afc1985449f45eed08cac3cb34").HexToByteArray(), Ciphertext = "ec8fdf5f4afb96ebe0e845dc3b".HexToByteArray(), Tag = "45d4b03158be4e07953767ee".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "594157ec4693202b030f33798b07176d".HexToByteArray(), Nonce = "49b12054082660803a1df3df".HexToByteArray(), Plaintext = ( "3feef98a976a1bd634f364ac428bb59cd51fb159ec178994691" + "8dbd50ea6c9d594a3a31a5269b0da6936c29d063a5fa2cc8a1c").HexToByteArray(), AssociatedData = null, Ciphertext = ( "c1b7a46a335f23d65b8db4008a49796906e225474f4fe7d39e5" + "5bf2efd97fd82d4167de082ae30fa01e465a601235d8d68bc69").HexToByteArray(), Tag = "ba92d3661ce8b04687e8788d55417dc2".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "0493024bab2833edef571ce7224750ab".HexToByteArray(), Nonce = "ab8dedbcdc57f283493fe7b3".HexToByteArray(), Plaintext = ( "5f6691c5813169d128e7af7678281085af09fb1ddacfc89e1a1" + "4cf14372d74eda6298a0772a594eb5a80a4c56b65744c2347d2").HexToByteArray(), AssociatedData = "8aca2645dd27195855b62f7d39ace11e".HexToByteArray(), Ciphertext = ( "b5d0733ade2203f5095bff60c9f5abef7770e38a56a9699e960" + "8a69969141a912a0b186f7cabe2dc187cb77331c625832510e2").HexToByteArray(), Tag = "d34a843edbf8234abffeb7de".HexToByteArray(), }, // key length = 192 new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "aa740abfadcda779220d3b406c5d7ec09a77fe9d94104539".HexToByteArray(), Nonce = "ab2265b4c168955561f04315".HexToByteArray(), Plaintext = Array.Empty<byte>(), AssociatedData = null, Ciphertext = Array.Empty<byte>(), Tag = "f149e2b5f0adaa9842ca5f45b768a8fc".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "c8ceaa125d2fb67e6d06e4c892d3ddf87081ef9be42fd9cb".HexToByteArray(), Nonce = "38b081bda77b18484252c200".HexToByteArray(), Plaintext = Array.Empty<byte>(), AssociatedData = "f284d23f6dde9a417046426f5a014b37".HexToByteArray(), Ciphertext = Array.Empty<byte>(), Tag = "a768033d680198aabb37cf09".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "c43e3bee7c89809f3f16f534a34a5526e2a1db16211dce7a".HexToByteArray(), Nonce = "62ec4fc5576ae52b5efcc715".HexToByteArray(), Plaintext = "bd4364e215aa459433f08e2fcc9184d9".HexToByteArray(), AssociatedData = null, Ciphertext = "8683a2e7241113c0c5a991d19c13d306".HexToByteArray(), Tag = "d874766acb70effd5890955f3c".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "f6fde0b9fbd2ac2105db66c94425c8db359987d9b706badf".HexToByteArray(), Nonce = "9c0df1c51d2bcbb4a3c9e759".HexToByteArray(), Plaintext = "58d0eb269f92491374de8675ce9fafa7".HexToByteArray(), AssociatedData = "a5c8d41e16165a4df9a6d59ab3556440".HexToByteArray(), Ciphertext = "bd0d9036e9f2a6ee82992936b2b3767b".HexToByteArray(), Tag = "589498ce7f55a48ecb87721308ee02".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "cf1d9456f6bd4b2fc95e40197f6950843bb2ed771f5f88dc".HexToByteArray(), Nonce = "0a34907cd0ec7e9b92258e14".HexToByteArray(), Plaintext = ( "cd67721f6e756727a0075b4e805d13f6702f14e572fe1cd7cd5" + "5bca281d6e02176c6288703d121ea73bc923d4aae919cab5878").HexToByteArray(), AssociatedData = null, Ciphertext = ( "41fb3e8030d693bbbeabfeb7346ad2b4d7518594c9ef7e2f9b0" + "3177ba2f2d9d10ae1dce68d370a79886dea990f472f2ab46e8b").HexToByteArray(), Tag = "3e169ae8466b010f51d3d88fda92".HexToByteArray(), }, // key length = 256 new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "b52c505a37d78eda5dd34f20c22540ea1b58963cf8e5bf8ffa85f9f2492505b4".HexToByteArray(), Nonce = "516c33929df5a3284ff463d7".HexToByteArray(), Plaintext = Array.Empty<byte>(), AssociatedData = null, Ciphertext = Array.Empty<byte>(), Tag = "bdc1ac884d332457a1d2664f168c76f0".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "7cb746fbd70e929a8efa65d16b1aa8a37f5b4478edc686b3a9d31631d5bf114b".HexToByteArray(), Nonce = "2f007847f97273c353af2b18".HexToByteArray(), Plaintext = Array.Empty<byte>(), AssociatedData = ( "17e84902ef33808d450f6d19b19fb3f863ca6c5476fa4" + "4105ab09a34ad530b9e606ebd606529b6d088a513fdf8" + "948ae78f44aff67b6f2429effc126d3c5de8cc2ca8b9b" + "f7a5b4417c0a8a4f90742637d73acfbb615cde7352463").HexToByteArray(), Ciphertext = Array.Empty<byte>(), Tag = "44ecc2383ae85a8cbad1f1b0".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "810bf78086dc8f630134934f9d978e0f308858e20b21dd4d319f0e6c811d6cec".HexToByteArray(), Nonce = "afc220a95ad53a376dadba12".HexToByteArray(), Plaintext = "edd60681c4919db5e32b6e44e1".HexToByteArray(), AssociatedData = null, Ciphertext = "74e5334c28504d10116371d4c9".HexToByteArray(), Tag = "e6737691a08f9a08e901b3902977".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "e29e006956c7532d40bd56df5f565d57ee1ea49037404cca7b6ea9dc9e36ab0f".HexToByteArray(), Nonce = "ed2caad30eb367d2d89a5ffb".HexToByteArray(), Plaintext = "b982ea6ff68af4c5202d71466f9f9f63614ad5378859a62d7a38ee32aa370bd9".HexToByteArray(), AssociatedData = ( "416a7b1db963ed683fd91bc2c5e9df3998944c3d0cbea2d2" + "302c8a67249973525d0dbe8d13f806174dd983ab18854ae6").HexToByteArray(), Ciphertext = "656539e12450db9dd88e4113f7890e80c6186768e6c8b1fc869c42dfad7b58bf".HexToByteArray(), Tag = "4366e2ce0396f0410ebcb893".HexToByteArray(), }, new AEADTest { Source = NistGcmTestVectors, CaseId = 0, Key = "6db07c6e834108aa97f4fb9b59378b75b6d58002f0063d8ec48af5adca3327a4".HexToByteArray(), Nonce = "cb2892bb9b841ff16ba0bee6".HexToByteArray(), Plaintext = ( "241f625f0560e9bf6bdb2c3734d79700d18ab0b6d0a2ae8d322" + "b28195705f9db1f407b9f21372a69478b2d0b960af184c556fc").HexToByteArray(), AssociatedData = ( "e739451bbc939ae0f7b1caecf23c65112969bfbfe4b5b" + "1b1c0c040cbac468e37dbef25d770f1f8b579880063c3" + "37386c7033e1d0bd65924cd4ad9609c4eefc40804730a" + "4474471e5a8cdda361b868074daab3e6feec3da5d5f0c").HexToByteArray(), Ciphertext = ( "19e1bf9c4b7c5f51de8a2fa0dc5d4d8cb8cbcd1c2b7df193688" + "d961aa106cfd5ea9bd7c62b492df4514877b209f29e11c2efa8").HexToByteArray(), Tag = "4ce8aff15debc1b23c50665b9c".HexToByteArray(), }, }; } }
//Apache2, 2012, Hernan J Gonzalez, https://github.com/leonbloy/pngcs namespace Hjg.Pngcs.Chunks { using Hjg.Pngcs; using System; using System.Collections.Generic; using System.IO; /// <summary> /// Represents a instance of a PNG chunk /// </summary> /// <remarks> /// Concrete classes should extend <c>PngChunkSingle</c> or <c>PngChunkMultiple</c> /// /// Note that some methods/fields are type-specific (GetOrderingConstraint(), AllowsMultiple()) /// some are 'almost' type-specific (Id,Crit,Pub,Safe; the exception is <c>PngUKNOWN</c>), /// and some are instance-specific /// /// Ref: http://www.libpng.org/pub/png/spec/1.2/PNG-Chunks.html /// </remarks> public abstract class PngChunk { /// <summary> /// 4 letters. The Id almost determines the concrete type (except for PngUKNOWN) /// </summary> public readonly String Id; /// <summary> /// Standard basic properties, implicit in the Id /// </summary> public readonly bool Crit, Pub, Safe; /// <summary> /// Image basic info, mostly for some checks /// </summary> protected readonly ImageInfo ImgInfo; /// <summary> /// For writing. Queued chunks with high priority will be written as soon as possible /// </summary> public bool Priority { get; set; } /// <summary> /// Chunk group where it was read or writen /// </summary> public int ChunkGroup { get; set; } public int Length { get; set; } // merely informational, for read chunks public long Offset { get; set; } // merely informational, for read chunks /// <summary> /// Restrictions for chunk ordering, for ancillary chunks /// </summary> public enum ChunkOrderingConstraint { /// <summary> /// No constraint, the chunk can go anywhere /// </summary> NONE, /// <summary> /// Before PLTE (palette) - and hence, also before IDAT /// </summary> BEFORE_PLTE_AND_IDAT, /// <summary> /// After PLTE (palette), but before IDAT /// </summary> AFTER_PLTE_BEFORE_IDAT, /// <summary> /// Before IDAT (before or after PLTE) /// </summary> BEFORE_IDAT, /// <summary> /// Does not apply /// </summary> NA } /// <summary> /// Constructs an empty chunk /// </summary> /// <param name="id"></param> /// <param name="imgInfo"></param> protected PngChunk(String id, ImageInfo imgInfo) { this.Id = id; this.ImgInfo = imgInfo; this.Crit = Hjg.Pngcs.Chunks.ChunkHelper.IsCritical(id); this.Pub = Hjg.Pngcs.Chunks.ChunkHelper.IsPublic(id); this.Safe = Hjg.Pngcs.Chunks.ChunkHelper.IsSafeToCopy(id); this.Priority = false; this.ChunkGroup = -1; this.Length = -1; this.Offset = 0; } private static Dictionary<String, Type> factoryMap = initFactory(); private static Dictionary<String, Type> initFactory() { Dictionary<String, Type> f = new Dictionary<string, System.Type>(); f.Add(ChunkHelper.IDAT, typeof(PngChunkIDAT)); f.Add(ChunkHelper.IHDR, typeof(PngChunkIHDR)); f.Add(ChunkHelper.PLTE, typeof(PngChunkPLTE)); f.Add(ChunkHelper.IEND, typeof(PngChunkIEND)); f.Add(ChunkHelper.tEXt, typeof(PngChunkTEXT)); f.Add(ChunkHelper.iTXt, typeof(PngChunkITXT)); f.Add(ChunkHelper.zTXt, typeof(PngChunkZTXT)); f.Add(ChunkHelper.bKGD, typeof(PngChunkBKGD)); f.Add(ChunkHelper.gAMA, typeof(PngChunkGAMA)); f.Add(ChunkHelper.pHYs, typeof(PngChunkPHYS)); f.Add(ChunkHelper.iCCP, typeof(PngChunkICCP)); f.Add(ChunkHelper.tIME, typeof(PngChunkTIME)); f.Add(ChunkHelper.tRNS, typeof(PngChunkTRNS)); f.Add(ChunkHelper.cHRM, typeof(PngChunkCHRM)); f.Add(ChunkHelper.sBIT, typeof(PngChunkSBIT)); f.Add(ChunkHelper.sRGB, typeof(PngChunkSRGB)); f.Add(ChunkHelper.hIST, typeof(PngChunkHIST)); f.Add(ChunkHelper.sPLT, typeof(PngChunkSPLT)); // extended f.Add(PngChunkOFFS.ID, typeof(PngChunkOFFS)); f.Add(PngChunkSTER.ID, typeof(PngChunkSTER)); return f; } /// <summary> /// Registers a Chunk ID in the factory, to instantiate a given type /// </summary> /// <remarks> /// This can be called by client code to register additional chunk types /// </remarks> /// <param name="chunkId"></param> /// <param name="type">should extend PngChunkSingle or PngChunkMultiple</param> public static void FactoryRegister(String chunkId, Type type) { factoryMap.Add(chunkId, type); } internal static bool isKnown(String id) { return factoryMap.ContainsKey(id); } internal bool mustGoBeforePLTE() { return GetOrderingConstraint() == ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT; } internal bool mustGoBeforeIDAT() { ChunkOrderingConstraint oc = GetOrderingConstraint(); return oc == ChunkOrderingConstraint.BEFORE_IDAT || oc == ChunkOrderingConstraint.BEFORE_PLTE_AND_IDAT || oc == ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; } internal bool mustGoAfterPLTE() { return GetOrderingConstraint() == ChunkOrderingConstraint.AFTER_PLTE_BEFORE_IDAT; } internal static PngChunk Factory(ChunkRaw chunk, ImageInfo info) { PngChunk c = FactoryFromId(Hjg.Pngcs.Chunks.ChunkHelper.ToString(chunk.IdBytes), info); c.Length = chunk.Len; c.ParseFromRaw(chunk); return c; } /// <summary> /// Creates one new blank chunk of the corresponding type, according to factoryMap (PngChunkUNKNOWN if not known) /// </summary> /// <param name="cid">Chunk Id</param> /// <param name="info"></param> /// <returns></returns> internal static PngChunk FactoryFromId(String cid, ImageInfo info) { PngChunk chunk = null; if (factoryMap == null) initFactory(); if (isKnown(cid)) { Type t = factoryMap[cid]; if (t == null) Console.Error.WriteLine("What?? " + cid); System.Reflection.ConstructorInfo cons = t.GetConstructor(new Type[] { typeof(ImageInfo) }); object o = cons.Invoke(new object[] { info }); chunk = (PngChunk)o; } if (chunk == null) chunk = new PngChunkUNKNOWN(cid, info); return chunk; } public ChunkRaw createEmptyChunk(int len, bool alloc) { ChunkRaw c = new ChunkRaw(len, ChunkHelper.ToBytes(Id), alloc); return c; } /* @SuppressWarnings("unchecked")*/ public static T CloneChunk<T>(T chunk, ImageInfo info) where T : PngChunk { PngChunk cn = FactoryFromId(chunk.Id, info); if ((Object)cn.GetType() != (Object)chunk.GetType()) throw new PngjException("bad class cloning chunk: " + cn.GetType() + " " + chunk.GetType()); cn.CloneDataFromRead(chunk); return (T)cn; } internal void write(Stream os) { ChunkRaw c = CreateRawChunk(); if (c == null) throw new PngjException("null chunk ! creation failed for " + this); c.WriteChunk(os); } /// <summary> /// Basic info: Id, length, Type name /// </summary> /// <returns></returns> public override String ToString() { return "chunk id= " + Id + " (len=" + Length + " off=" + Offset + ") c=" + GetType().Name; } /// <summary> /// Serialization. Creates a Raw chunk, ready for write, from this chunk content /// </summary> public abstract ChunkRaw CreateRawChunk(); /// <summary> /// Deserialization. Given a Raw chunk, just rad, fills this chunk content /// </summary> public abstract void ParseFromRaw(ChunkRaw c); /// <summary> /// Override to make a copy (normally deep) from other chunk /// </summary> /// <param name="other"></param> public abstract void CloneDataFromRead(PngChunk other); /// <summary> /// This is implemented in PngChunkMultiple/PngChunSingle /// </summary> /// <returns>Allows more than one chunk of this type in a image</returns> public abstract bool AllowsMultiple(); /// <summary> /// Get ordering constrain /// </summary> /// <returns></returns> public abstract ChunkOrderingConstraint GetOrderingConstraint(); } }
/** * PsFtpProvider * * https://github.com/Arnavion/PsFtpProvider * * Copyright 2014 Arnav Singh * * 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.ObjectModel; using System.IO; using System.Linq; using System.Management.Automation; using System.Management.Automation.Provider; using System.Net; using System.Text; using System.Xml.Linq; using FluentFTP; namespace PsFtpProvider { [CmdletProvider("PsFtp", ProviderCapabilities.Credentials)] public class FtpProvider : NavigationCmdletProvider, IContentCmdletProvider { private new FtpDriveInfo PSDriveInfo => (FtpDriveInfo)base.PSDriveInfo; #region NavigationCmdletProvider members protected override bool IsItemContainer(string path) => PSDriveInfo.IsItemContainer(path); #endregion #region ContainerCmdletProvider members protected override void GetChildItems(string path, bool recurse) { if (recurse) { throw new ArgumentOutOfRangeException(nameof(recurse), "recurse == true is not supported."); } foreach (var item in PSDriveInfo.GetChildItems(path)) { WriteItemObject(item, item.FullName, item.Type == FtpFileSystemObjectType.Directory); } } protected override bool HasChildItems(string path) => PSDriveInfo.HasChildItems(path); protected override void NewItem(string path, string itemTypeName, object newItemValue) { FtpListItem newItem = null; switch (itemTypeName) { case "File": newItem = PSDriveInfo.NewFile(path); break; case "Directory": newItem = PSDriveInfo.NewDirectory(path); break; default: throw new ArgumentOutOfRangeException(nameof(itemTypeName)); } WriteItemObject(newItem, path, newItem.Type == FtpFileSystemObjectType.Directory); } protected override void RemoveItem(string path, bool recurse) => PSDriveInfo.RemoveItem(path, recurse); #endregion #region ItemCmdletProvider members protected override void GetItem(string path) { var item = PSDriveInfo.GetItem(path); WriteItemObject(item, item.FullName, item.Type == FtpFileSystemObjectType.Directory); } protected override bool IsValidPath(string path) => PSDriveInfo != null; protected override bool ItemExists(string path) { if (PSDriveInfo == null) { return false; } try { PSDriveInfo.GetItem(path); return true; } catch { return false; } } #endregion #region DriveCmdletProvider members protected override Collection<PSDriveInfo> InitializeDefaultDrives() { try { var root = XElement.Load(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "filezilla", "sitemanager.xml")); return new Collection<PSDriveInfo>( ( from server in root.Element("Servers").Elements("Server") let passwordElement = server.Element("Pass") let password = passwordElement.Attribute("encoding")?.Value == "base64" ? Encoding.UTF8.GetString(Convert.FromBase64String(passwordElement.Value)) : passwordElement.Value let protocol = int.Parse(server.Element("Protocol").Value) select new FtpDriveInfo ( new Site ( string.Join("", from textNode in server.Nodes().OfType<XText>() select textNode.Value.Trim()), server.Element("Host").Value, ushort.Parse(server.Element("Port").Value), new NetworkCredential(server.Element("User").Value, password), (protocol == 0 || protocol == 4) ? FtpEncryptionMode.Explicit : (protocol == 3) ? FtpEncryptionMode.Implicit : (protocol == 6) ? FtpEncryptionMode.None : FtpEncryptionMode.Explicit ), ProviderInfo ) ).ToList<PSDriveInfo>() ); } catch { return new Collection<PSDriveInfo>(); } } protected override PSDriveInfo NewDrive(PSDriveInfo drive) { if (drive == null) { throw new ArgumentNullException(nameof(drive)); } if (drive is FtpDriveInfo result) { return result; } if (DynamicParameters is NewFtpDriveDynamicParameters dynamicParameters) { return new FtpDriveInfo ( new Site ( drive.Name, dynamicParameters.Hostname, dynamicParameters.Port, (drive.Credential != null && drive.Credential != PSCredential.Empty) ? new NetworkCredential(drive.Credential.UserName, drive.Credential.Password) : new NetworkCredential("anonymous", ""), dynamicParameters.EncryptionMode ), ProviderInfo ); } throw new ArgumentOutOfRangeException(nameof(drive)); } protected override object NewDriveDynamicParameters() => new NewFtpDriveDynamicParameters(); protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) => drive; #endregion #region IContentCmdletProvider members public void ClearContent(string path) { using (var writer = PSDriveInfo.GetContentWriter(path, DynamicParameters as ContentWriterDynamicParameters)) { writer.Truncate(); } } public object ClearContentDynamicParameters(string path) => null; public IContentReader GetContentReader(string path) => PSDriveInfo.GetContentReader(path, DynamicParameters as ContentReaderDynamicParameters); public object GetContentReaderDynamicParameters(string path) => new ContentReaderDynamicParameters(); public IContentWriter GetContentWriter(string path) => PSDriveInfo.GetContentWriter(path, DynamicParameters as ContentWriterDynamicParameters); public object GetContentWriterDynamicParameters(string path) => new ContentWriterDynamicParameters(); #endregion } }
using System; using UnityEngine; public class MenuTabsMultiplayer : MenuTabs { bool KeyboardSelected = true; public MenuTabsMultiplayer (MenuHandler handler) : base(handler) { this.Handler = handler; CurrentTabState = TabState.TabDefault; } protected override void GUISettings(){ if(GUI.Button(new Rect(w - tw*3.5f, h*0.5f - th*0.5f, tw*0.5f, th), " >> ")){ SetTabState(TabState.TabDefault); } GUI.Box(new Rect(w - tw*3f, th*7f, tw*3f, h - th*7f), ""); if(Handler.Inflater.TerrainVisible) MenuHandler.GUIDrawRect(new Rect(w - tw*2f, h/2 - th*1.5f, tw, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*2f, h/2 - th*1.5f, tw, th), "Terrain On/Off")){ if(Handler.Inflater.TerrainVisible){ Handler.Inflater.HideTerrain(); }else if(!Handler.Inflater.TerrainVisible){ Handler.Inflater.UnhideTerrain(); } Handler.UpdateFlags(); } if(Handler.Inflater.MapVisible) MenuHandler.GUIDrawRect(new Rect(w - tw*2f, h/2 - th*0.5f, tw, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*2f, h/2 - th*0.5f, tw, th), "Map On/Off")){ if(Handler.Inflater.MapVisible) Handler.Inflater.HideMap(); else if(!Handler.Inflater.MapVisible) Handler.Inflater.UnhideMap(); } if(Handler.GridsVisible) MenuHandler.GUIDrawRect(new Rect(w - tw*2f, h/2 + th*0.5f, tw, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*2f, h/2 + th*0.5f, tw, th), "Grids On/Off")){ if(Handler.GridsVisible) Handler.HideGrids(); else if(!Handler.GridsVisible) Handler.UnhideGrids(); } #region Controller Selection GUI.Label(new Rect(w - tw*2f, h/2 + th*2.5f, tw, th), "Controller: "); if(KeyboardSelected) MenuHandler.GUIDrawRect(new Rect(w - tw*2f, h/2 + th*3.5f, tw, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*2f, h/2 + th*3.5f, tw, th), "Keyboard")){ if(!KeyboardSelected){ Handler.ControlHandler.SetControl(ControllerHandler.ControllerType.Keyboard); KeyboardSelected = true; } } #endregion MenuHandler.GUIDrawRect(new Rect(w - tw*2.25f, h/2 + th*6.5f, tw*1.5f, th), Color.red); if(GUI.Button(new Rect(w - tw*2.25f, h/2 + th*6.5f, tw*1.5f, th), "Regenerate Terrain")){ Handler.StateSingleplayer.RegenerateCurrentTerrainMulti(); } } protected override void GUIGrids(){ if(GUI.Button(new Rect(w - tw*3.5f, h*0.5f - th*0.5f, tw*0.5f, th), " >> ")){ SetTabState(TabState.TabDefault); } // New Grid Button if(GUI.Button(new Rect(w-tw*2, th*5.5f, tw, th), "New Grid")){ SelectingGridOrientation = true; GridBeingNamed = Handler.CreateGrid("", GridData.Orientation.UP_Y); } if(SelectingGridOrientation) { GUI.Box(new Rect(w/2 - tw*1.55f, h/2 - th*4f, tw*3.1f, th*8.1f), "Select Orientation"); if(GUI.Button(new Rect(w/2 -tw*1f, h/2 - th*3.0f, tw*2f, th), "Left - Right")) { SelectingGridOrientation = false; GridData dTemp = ((GridData)GridBeingNamed.GetComponent(typeof(GridData))); dTemp.SetOrientation(GridData.Orientation.UP_X); NamingGrid = true; } if(GUI.Button(new Rect(w/2 -tw*1f, h/2 - th*1.5f, tw*2f, th), "Up - Down")) { SelectingGridOrientation = false; GridData dTemp = ((GridData)GridBeingNamed.GetComponent(typeof(GridData))); dTemp.SetOrientation(GridData.Orientation.UP_Y); NamingGrid = true; } if(GUI.Button(new Rect(w/2 -tw*1f, h/2 - th*0.0f, tw*2f, th), "Forwards - Backwards")) { SelectingGridOrientation = false; GridData dTemp = ((GridData)GridBeingNamed.GetComponent(typeof(GridData))); dTemp.SetOrientation(GridData.Orientation.UP_Z); NamingGrid = true; } } if(NamingGrid){ GUI.Box(new Rect(w/2 - tw*1.55f, h/2 - th*4f, tw*3.1f, th*8.1f), "Name Grid"); tempGridName = GUI.TextArea (new Rect (w/2 - tw*1.5f, h/2 - th*3f, tw*3f, th*6f), tempGridName); if(GUI.Button(new Rect(w/2 - tw/2, h/2 + th*3.05f, tw, th), "Done")){ GridData dTemp = ((GridData)GridBeingNamed.GetComponent(typeof(GridData))); if(tempGridName != ""){ dTemp.SetName(tempGridName); }else{ dTemp.SetName("Grid"); } if(SelectedGrid != null){ SelectedGrid.GetComponent<GridData>().SetGridSelected(false); } switch(dTemp.GetOrientation()){ case GridData.Orientation.UP_X: SelectedGridHeight = (dTemp.GetWorldValue()/Handler.Inflater.theterrain.terrainData.size.x) * 100; break; case GridData.Orientation.UP_Y: SelectedGridHeight = (dTemp.GetWorldValue()/Handler.Inflater.theterrain.terrainData.size.y) * 100; break; case GridData.Orientation.UP_Z: SelectedGridHeight = (dTemp.GetWorldValue()/Handler.Inflater.theterrain.terrainData.size.z) * 100; break; } SelectedGrid = GridBeingNamed; SelectedGridData = (GridData)SelectedGrid.GetComponent(typeof(GridData)); SelectedGridData.SetGridSelected(true); tempGridName = ""; NamingGrid = false; RPCGrid(GridBeingNamed); } } // Viewing Grid: GUI.Box(new Rect(w - tw*3f, th*7f, tw*3f, h - th*7f), ""); if(Handler.Grids.Count > 0){ MenuHandler.GUIDrawRect(new Rect(w - tw*1.5f, th*3.5f, tw*1.2f, th), Color.red); if(GUI.Button(new Rect(w - tw*1.5f, th*3.5f, tw*1.2f, th),"Delete ALL Grids")){ Handler.DeleteAllGrids(); } for(int i=0; i<Handler.Grids.Count; i++){ GridData dTemp = (GridData)Handler.Grids[i].GetComponent(typeof(GridData)); float curX = w - tw*3f,curY = th*7f + th*2f*i; float width = tw*3f, height = th*2f; if(dTemp.IsSelected()){MenuHandler.GUIDrawRect(new Rect(curX, curY, width, height), new Color(1.0f, 0.55f, 0.55f, 0.65f));} //Select Grid Button if(GUI.Button(new Rect(curX, curY, width, height), "")){ if(SelectedGrid == Handler.Grids[i]){ SelectedGrid = null; dTemp.SetGridSelected(false); }else{ if(SelectedGrid != null){ SelectedGrid.GetComponent<GridData>().SetGridSelected(false); } SelectedGrid = Handler.Grids[i]; SelectedGridData = (GridData)SelectedGrid.GetComponent(typeof(GridData)); switch(SelectedGridData.GetOrientation()){ case GridData.Orientation.UP_X: SelectedGridHeight = (SelectedGridData.GetWorldValue()/Handler.Inflater.theterrain.terrainData.size.x) * 100 + 1; break; case GridData.Orientation.UP_Y: SelectedGridHeight = (SelectedGridData.GetWorldValue()/Handler.Inflater.theterrain.terrainData.size.y) * 100 + 1; break; case GridData.Orientation.UP_Z: SelectedGridHeight = (SelectedGridData.GetWorldValue()/Handler.Inflater.theterrain.terrainData.size.z) * 100 + 1; break; } SelectedGridData.SetGridSelected(true); } } GUI.Label(new Rect(curX + width*0.05f, curY, width*0.9f, height/2), dTemp.GetName()); string PosString = ""; switch(dTemp.GetOrientation()){ case GridData.Orientation.UP_X: PosString = "Lat: " + Math.Round(dTemp.GetDataValue(), 2).ToString(); break; case GridData.Orientation.UP_Y: PosString = "Height: " + Math.Round(dTemp.GetDataValue(), 2).ToString(); break; case GridData.Orientation.UP_Z: PosString = "Long: " + Math.Round(dTemp.GetDataValue(), 2).ToString(); break; default: PosString = "Value: " + Math.Round(dTemp.GetDataValue(), 2).ToString(); break; } GUI.Label(new Rect(curX + width*0.05f, curY + height/2, width*0.9f, height/2), PosString); } } // Grid Data for SELECTED Grid if (SelectedGrid != null) { float boxX = w - tw * 3f, boxY = h - th * 6.1f, boxWidth = tw * 3f, boxHeight = th * 6.1f; GUI.Box (new Rect (boxX, boxY - th, boxWidth, boxHeight + th * 0.9f), "Selected Grid"); // Grid Height Slider GUI.Label (new Rect (w - th * 2f, h - th * 6f, th * 1.5f, th), ""); GUI.Label (new Rect (w - th * 2f, h - th * 1.1f, th * 1.5f, th), ""); MenuHandler.GUIDrawRect (new Rect (w - th * 1.2f, h - th * 5.3f, th, th * 4.5f), new Color (1f, 1f, 1f, 0.25f)); SelectedGridHeight = GUI.VerticalSlider (new Rect (w - th, h - th * 5f, th, th * 3.9f), SelectedGridHeight, 100.0f, 0.0f); // Send RPC if grid has changed position if((int)SelectedGridHeight != SelectedGridData.GetWorldPosIndex()){ Handler.Multiplayer.CallUpdateGrid(SelectedGridData.GetID (), (int)SelectedGridHeight); } SelectedGridData.SetWorldPosIndex ((int)SelectedGridHeight); SelectedGridData.SetDataPosIndex ((int)SelectedGridHeight); string selectedGridPosString = "Value: " + Math.Round (SelectedGridData.GetDataValue(), 4).ToString (); bool defaultWordWrap = GUI.skin.label.wordWrap; GUI.skin.label.wordWrap = true; GUI.Label (new Rect (boxX + boxWidth * 0.05f, boxY, boxWidth * 0.9f, th * 2f), SelectedGridData.GetName ()); GUI.skin.label.wordWrap = defaultWordWrap; GUI.Label (new Rect (boxX + boxWidth * 0.05f, boxY + th * 2.5f, boxWidth * 0.9f, th * 1f), selectedGridPosString); if (SelectedGrid.renderer.material == Handler.Inflater.GridSolidMat) MenuHandler.GUIDrawRect (new Rect (boxX + boxWidth * 0.1f, boxY + th * 3.55f, boxWidth * 0.33f, th), new Color (0.78f, 0.73f, 0.93f, 0.55f)); if (GUI.Button (new Rect (boxX + boxWidth * 0.1f, boxY + th * 3.55f, boxWidth * 0.33f, th), "Solid")) { SelectedGrid.renderer.material = Handler.Inflater.GridSolidMat; Handler.UpdateGrids (); } if (SelectedGrid.renderer.material == Handler.Inflater.GridTransparentMat) MenuHandler.GUIDrawRect (new Rect (boxX + boxWidth * 0.57f, boxY + th * 3.55f, boxWidth * 0.33f, th), new Color (0.78f, 0.73f, 0.93f, 0.55f)); if (GUI.Button (new Rect (boxX + boxWidth * 0.57f, boxY + th * 3.55f, boxWidth * 0.33f, th), "Transparent")) { SelectedGrid.renderer.material = Handler.Inflater.GridTransparentMat; Handler.UpdateGrids (); } // Delete Grid Button if (GUI.Button (new Rect (boxX + boxWidth * 0.33f, boxY + th * 4.65f, boxWidth * 0.33f, th), "Delete Grid")) { Handler.Multiplayer.CallDeleteGrid(SelectedGridData.GetID()); Handler.Grids.Remove (SelectedGrid); Main.Destroy (SelectedGrid); SelectedGrid = null; } } } protected override void GUIFlags(){ GUI.Box(new Rect(w - tw*3f, th*7f, tw*3f, h - th*5f), ""); if(!PlacingFlag && !SelectingFlag && !FlagColour && ! AnnotatingFlag){ if(GUI.Button(new Rect(w - tw*3.5f, h*0.5f - th*0.5f, tw*0.5f, th), " >> ")){ SetTabState(TabState.TabDefault); } } // Viewing Flags: if(Handler.Flags.Count > 0){ if(!PlacingFlag && !SelectingFlag && !FlagColour && ! AnnotatingFlag){ MenuHandler.GUIDrawRect(new Rect(w - tw*1.5f, th*3.5f, tw*1.2f, th), Color.red); if(GUI.Button(new Rect(w - tw*1.5f, th*3.5f, tw*1.2f, th),"Delete ALL Flags")){ Handler.DeleteAllFlags(); } } for(int i=0; i<Handler.Flags.Count; i++){ FlagData fTemp = Handler.Flags[i].GetComponent<FlagData>(); float curX = w - tw*3f, curY = th*7f + th*2f*i; float width = tw*3f, height = th*2f; if(fTemp.IsSelected()){MenuHandler.GUIDrawRect(new Rect(curX, curY, width, height), new Color(1.0f, 0.55f, 0.55f, 0.65f));} //Select Flag Button if(GUI.Button(new Rect(curX, curY, width, height), "")){ if(SelectedFlag == Handler.Flags[i]){ SelectedFlag = null; fTemp.SetFlagSelected(false); }else{ if(SelectedFlag != null){ SelectedFlag.GetComponent<FlagData>().SetFlagSelected(false); } SelectedFlag = Handler.Flags[i]; fTemp.SetFlagSelected(true); } } GUI.Label(new Rect(curX + width*0.05f, curY, width*0.9f, height/2), fTemp.GetAnnotation()); string PosString = "Lat: " + Math.Round(fTemp.GetDataPos().x, 2).ToString() + ", Long: " + Math.Round(fTemp.GetDataPos().z, 2).ToString() + ", Value: " + Math.Round(fTemp.GetDataPos().y, 2).ToString(); GUI.Label(new Rect(curX + width*0.05f, curY + height/2, width*0.9f, height/2), PosString); } } // Flag Data for SELECTED Flag if(SelectedFlag != null){ float boxX = w - tw*3f, boxY = h - th*6.1f, boxWidth = tw*3f, boxHeight = th*6.1f; GUI.Box(new Rect(boxX, boxY-th, boxWidth, boxHeight+th*0.9f), "Selected Flag"); FlagData selectedFlagData = (FlagData)SelectedFlag.GetComponent(typeof(FlagData)); string selectedFlagPosString = "Lat: " + Math.Round(selectedFlagData.GetDataPos().x, 2).ToString() + ", Long: " + Math.Round(selectedFlagData.GetDataPos().z, 2).ToString() + ", Value: " + Math.Round(selectedFlagData.GetDataPos().y, 2).ToString(); bool defaultWordWrap = GUI.skin.label.wordWrap; GUI.skin.label.wordWrap = true; GUI.Label(new Rect(boxX + boxWidth*0.05f, boxY, boxWidth*0.9f, th*3f), selectedFlagData.GetAnnotation()); GUI.skin.label.wordWrap = defaultWordWrap; GUI.Label(new Rect(boxX + boxWidth*0.05f, boxY + th*3.5f, boxWidth*0.9f, th*1f), selectedFlagPosString); // Delete Flag Button if(!PlacingFlag && !SelectingFlag && !FlagColour && ! AnnotatingFlag){ if(GUI.Button(new Rect(boxX + boxWidth*0.33f, boxY + th*4.65f, boxWidth*0.33f, th), "Delete Flag")){ Handler.Multiplayer.CallDeleteFlag(selectedFlagData.GetID()); Handler.Flags.Remove(SelectedFlag); Main.Destroy(SelectedFlag); SelectedFlag = null; } } } /******* Flag Creation *******/ if(!PlacingFlag && !SelectingFlag && !FlagColour && ! AnnotatingFlag){ if(GUI.Button(new Rect(w-tw*2, th*5.5f, tw, th), "New Flag")){ if(!PlacingFlag){ FlagBeingAnnotated = Handler.CreateFlag("", Vector3.zero); PlacingFlag = true; } } } if(SelectingFlag) { GUI.Box(new Rect(w/2 - tw*1.55f, h/2 - th*4f, tw*3.1f, th*8.1f), "Select Image"); if(GUI.Button(new Rect(w/2 -tw*0.5f, h/2 - th*3.0f, tw, th), Handler.flaghandler.FLAG_TYPE[1])) { Handler.SetFlagImage(1, Handler.flaghandler); FlagBeingAnnotated.GetComponent<FlagData>().SetFlagImageIndex(1); SelectingFlag = false; FlagColour = true; } if(GUI.Button(new Rect(w/2 -tw*0.5f, h/2 - th*1.5f, tw, th), Handler.flaghandler.FLAG_TYPE[2])) { Handler.SetFlagImage(2, Handler.flaghandler); FlagBeingAnnotated.GetComponent<FlagData>().SetFlagImageIndex(2); SelectingFlag = false; FlagColour = true; } if(GUI.Button(new Rect(w/2 -tw*0.5f, h/2 - th*0.0f, tw, th), Handler.flaghandler.FLAG_TYPE[3])) { Handler.SetFlagImage(3, Handler.flaghandler); FlagBeingAnnotated.GetComponent<FlagData>().SetFlagImageIndex(3); SelectingFlag = false; FlagColour = true; } if(GUI.Button(new Rect(w/2 -tw*0.5f, h/2 - th*-1.5f, tw, th), Handler.flaghandler.FLAG_TYPE[4])) { Handler.SetFlagImage(4, Handler.flaghandler); FlagBeingAnnotated.GetComponent<FlagData>().SetFlagImageIndex(4); SelectingFlag = false; FlagColour = true; } } if(FlagColour) { GUI.Box(new Rect(w/2 - tw*1.55f, h/2 - th*4f, tw*3.1f, th*8.1f), "Select Flag Colour"); if(GUI.Button(new Rect(w/2 -tw*0.5f, h/2 - th*3.0f, tw, th), MenuHandler.FC_WHITE)) { Handler.SetFlagColour(Color.white,MenuHandler.FC_WHITE); AnnotatingFlag = true; FlagColour = false; } if(GUI.Button(new Rect(w/2 -tw*0.5f, h/2 - th*1.5f, tw, th), MenuHandler.FC_RED)) { Handler.SetFlagColour(Color.red,MenuHandler.FC_RED); AnnotatingFlag = true; FlagColour = false; } if(GUI.Button(new Rect(w/2 -tw*0.5f, h/2 - th*0.0f, tw, th), MenuHandler.FC_YELLOW)) { Handler.SetFlagColour(Color.yellow,MenuHandler.FC_YELLOW); AnnotatingFlag = true; FlagColour = false; } if(GUI.Button(new Rect(w/2 -tw*0.5f, h/2 - th*-1.5f, tw, th), MenuHandler.FC_GREEN)) { Handler.SetFlagColour(Color.green,MenuHandler.FC_GREEN); AnnotatingFlag = true; FlagColour = false; } if(GUI.Button(new Rect(w/2 -tw*0.5f, h/2 - th*-3.0f, tw, th), MenuHandler.FC_BLUE)) { Handler.SetFlagColour(Color.blue,MenuHandler.FC_BLUE); AnnotatingFlag = true; FlagColour = false; } } if(AnnotatingFlag){ GUI.Box(new Rect(w/2 - tw*1.55f, h/2 - th*4f, tw*3.1f, th*8.1f), "Annotate Flag"); tempAnnotation = GUI.TextArea (new Rect (w/2 - tw*1.5f, h/2 - th*3f, tw*3f, th*6f), tempAnnotation); if(GUI.Button(new Rect(w/2 - tw/2, h/2 + th*3.05f, tw, th), "Annotate")){ //User clicks "Annotate" if(tempAnnotation != ""){ ((FlagData)FlagBeingAnnotated.GetComponent(typeof(FlagData))).SetAnnotation(tempAnnotation); AnnotatingFlag = true; }else{ ((FlagData)FlagBeingAnnotated.GetComponent(typeof(FlagData))).SetAnnotation("Flag"); AnnotatingFlag = true; } tempAnnotation = ""; AnnotatingFlag = false; //Final step of Flag Creation, call server to create flag for every other user. RPCFlag(FlagBeingAnnotated); } } } protected override void GUIDataPoints(){ if(GUI.Button(new Rect(w - tw*3.5f, h*0.5f - th*0.5f, tw*0.5f, th), " >> ")){ SetTabState(TabState.TabDefault); } GUI.Box(new Rect(w - tw*3f, th*7f, tw*3f, h - th*7f), ""); GUI.Label(new Rect(w - tw*2f, h/2 - th*1.5f, tw, th), "Show Data Points?"); // Button YES if(ShowDataPoints) MenuHandler.GUIDrawRect(new Rect(w - tw*2f, h/2 - th*0.5f, tw*0.45f, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*2f, h/2 - th*0.5f, tw*0.45f, th), "Yes")){ if(!ShowDataPoints) RPCAddDataPoints(NumDataPoints); ShowDataPoints = true; } // Button NO if(!ShowDataPoints) MenuHandler.GUIDrawRect(new Rect(w - tw*1.55f, h/2f - th*0.5f, tw*0.45f, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*1.55f, h/2f - th*0.5f, tw*0.45f, th), "No")){ if(ShowDataPoints) RPCRemoveDataPoints(); ShowDataPoints = false; } // Number of Data Points to be shown GUI.Label(new Rect(w - tw*2f - GUI.skin.GetStyle("Label").CalcSize(new GUIContent(NumDataPoints.ToString())).x/2f, h/2f + th, tw*1.5f, th), "# of Data Points: " + NumDataPoints.ToString()); GUI.Label(new Rect(w - tw*2.5f, h/2f + th*2.75f, tw, th), "0"); GUI.Label(new Rect(w - tw*0.6f, h/2f + th*2.75f, tw, th), MaxNumDataPoints.ToString()); MenuHandler.GUIDrawRect(new Rect(w - tw*2.6f, h/2 + th*1.9f, tw*2.2f, th*0.75f), new Color(1f,1f,1f,0.25f)); NumDataPoints = (int)GUI.HorizontalSlider(new Rect(w - tw*2.5f, h/2 + th*2f, tw*2, th), NumDataPoints, 0, MaxNumDataPoints); if(GUI.Button(new Rect(w-tw*2.25f, h/2 + th*3.25f, tw*1.5f, th*1.5f), "Regenerate Points")){ RPCResetDataPoints(); } } protected override void GUIExternalAxis(){ if(GUI.Button(new Rect(w - tw*3.5f, h*0.5f - th*0.5f, tw*0.5f, th), " >> ")){ SetTabState(TabState.TabDefault); } GUI.Box(new Rect(w - tw*3f, th*7f, tw*3f, h - th*7f), ""); #region Axis Grid Yes/No GUI.Label(new Rect(w - tw*2f, h/2 - th*4f, tw, th), "Show Axis Grid?"); // Button YES if(ShowAxisGrid) MenuHandler.GUIDrawRect(new Rect(w - tw*2f, h/2 - th*3f, tw*0.45f, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*2f, h/2 - th*3f, tw*0.45f, th), "Yes")){ /// Make Networkable if(!ShowAxisGrid){ RPCAxisOn(AxisGridSizeXRounded, AxisGridSizeYRounded, AxisGridSizeZRounded); ShowAxisGrid = true; } } // Button NO if(!ShowAxisGrid) MenuHandler.GUIDrawRect(new Rect(w - tw*1.55f, h/2f - th*3f, tw*0.45f, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*1.55f, h/2f - th*3f, tw*0.45f, th), "No")){ if(ShowAxisGrid){ RPCAxisOff(); ShowAxisGrid = false; } } #endregion #region Axis Grid LABELS Yes/No GUI.Label(new Rect(w - tw*2.25f, h/2 - th*1.5f, tw*1.5f, th), "Show Axis Labels?"); // Button YES if(ShowAxisGridLabels) MenuHandler.GUIDrawRect(new Rect(w - tw*2f, h/2 - th*0.5f, tw*0.45f, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*2f, h/2 - th*0.5f, tw*0.45f, th), "Yes")){ if(!ShowAxisGridLabels){ RPCAxisLabelsOn(AxisGridSizeXRounded, AxisGridSizeYRounded, AxisGridSizeZRounded); ShowAxisGridLabels = true; } } // Button NO if(!ShowAxisGridLabels) MenuHandler.GUIDrawRect(new Rect(w - tw*1.55f, h/2f - th*0.5f, tw*0.45f, th), new Color(0.38f, 0.57f, 0.72f, 0.55f)); if(GUI.Button(new Rect(w - tw*1.55f, h/2f - th*0.5f, tw*0.45f, th), "No")){ if(ShowAxisGridLabels){ RPCAxisLabelsOff(); ShowAxisGridLabels = false; } } #endregion // Axis Grid Size Z: GUI.Label(new Rect(w - tw*2f - GUI.skin.GetStyle("Label").CalcSize(new GUIContent(AxisGridSizeZString)).x/2f, h/2f + th, tw*2f, th), "Grid Size Latitude: " + AxisGridSizeZString); GUI.Label(new Rect(w - tw*2.5f, h/2f + th*2.75f, tw, th), "0"); GUI.Label(new Rect(w - tw*0.6f, h/2f + th*2.75f, tw, th), String.Format("{0:0.000}", (AxisMaxGridZ-AxisMinGridZ))); MenuHandler.GUIDrawRect(new Rect(w - tw*2.6f, h/2 + th*1.9f, tw*2.2f, th*0.75f), new Color(1f,1f,1f,0.25f)); AxisGridSizeZ = GUI.HorizontalSlider(new Rect(w - tw*2.5f, h/2 + th*2f, tw*2, th), AxisGridSizeZ, 0, AxisMaxGridZ-AxisMinGridZ); AxisGridSizeZString = String.Format("{0:0.000}", AxisGridSizeZRounded); // Axis Grid Size X: GUI.Label(new Rect(w - tw*2f - GUI.skin.GetStyle("Label").CalcSize(new GUIContent(AxisGridSizeXString)).x/2f, h/2f + th*3.5f, tw*2f, th), "Grid Size Longitude: " + AxisGridSizeXString); GUI.Label(new Rect(w - tw*2.5f, h/2f + th*5.25f, tw, th), "0"); GUI.Label(new Rect(w - tw*0.6f, h/2f + th*5.25f, tw, th), String.Format("{0:0.000}", (AxisMaxGridX-AxisMinGridX))); MenuHandler.GUIDrawRect(new Rect(w - tw*2.6f, h/2 + th*4.4f, tw*2.2f, th*0.75f), new Color(1f,1f,1f,0.25f)); AxisGridSizeX = GUI.HorizontalSlider(new Rect(w - tw*2.5f, h/2 + th*4.5f, tw*2, th), AxisGridSizeX, 0, AxisMaxGridX-AxisMinGridX); AxisGridSizeXString = String.Format("{0:0.000}", AxisGridSizeXRounded); // Axis Grid Size Y: GUI.Label(new Rect(w - tw*2f - GUI.skin.GetStyle("Label").CalcSize(new GUIContent(AxisGridSizeYString)).x/2f, h/2f + th*6f, tw*2f, th), "Grid Size Height: " + AxisGridSizeYString); GUI.Label(new Rect(w - tw*2.5f, h/2f + th*7.75f, tw, th), "0"); GUI.Label(new Rect(w - tw*0.6f, h/2f + th*7.75f, tw, th), String.Format("{0:0.000}", (AxisMaxGridY-AxisMinGridY))); MenuHandler.GUIDrawRect(new Rect(w - tw*2.6f, h/2 + th*6.9f, tw*2.2f, th*0.75f), new Color(1f,1f,1f,0.25f)); AxisGridSizeY = GUI.HorizontalSlider(new Rect(w - tw*2.5f, h/2 + th*7f, tw*2, th), AxisGridSizeY, 0, AxisMaxGridY-AxisMinGridY); AxisGridSizeYString = String.Format("{0:0.000}", AxisGridSizeYRounded); AxisGridSizeXRounded = RoundToNearest(AxisGridSizeX, AxisGridSizeXIT); AxisGridSizeYRounded = RoundToNearest(AxisGridSizeY, AxisGridSizeYIT); AxisGridSizeZRounded = RoundToNearest(AxisGridSizeZ, AxisGridSizeZIT); if(GUI.Button(new Rect(w-tw*2.25f, h/2 + th*8.25f, tw*1.5f, th*1.5f), "Regenerate Axis Grid")){ RPCAxisReset(); ResetAxisGrid(); } } private void RPCAxisOn(float AxisGridSizeX, float AxisGridSizeY, float AxisGridSizeZ){ Handler.Multiplayer.CallExternalAxisOn(AxisGridSizeX, AxisGridSizeY, AxisGridSizeZ); AddAxisGridsValues(AxisGridSizeX, AxisGridSizeY, AxisGridSizeZ); ApplySurfaceGridValues(AxisGridSizeX, AxisGridSizeZ); } private void RPCAxisOff(){ Handler.Multiplayer.CallExternalAxisOff(); RemoveAxisGrids(); RemoveSurfaceGrid(); } private void RPCAxisReset(){ Handler.Multiplayer.CallExternalAxisReset(AxisGridSizeXRounded, AxisGridSizeYRounded, AxisGridSizeZRounded); ResetAxisGrid(); } private void RPCAxisLabelsOn(float AxisGridSizeX, float AxisGridSizeY, float AxisGridSizeZ){ Handler.Multiplayer.CallExternalAxisLabelsOn(AxisGridSizeX, AxisGridSizeY, AxisGridSizeZ); AddAxisGridLabelsValues(AxisGridSizeX, AxisGridSizeY, AxisGridSizeZ); } private void RPCAxisLabelsOff(){ Handler.Multiplayer.CallExternalAxisLabelsOff(); RemoveAxisGridLabels(); } private void RPCAddDataPoints(int NumDataPoints){ Handler.Multiplayer.CallAddDataPoints(NumDataPoints); AddDataPoints(NumDataPoints); } private void RPCRemoveDataPoints(){ Handler.Multiplayer.CallRemoveDataPoints(); RemoveDataPoints(); } private void RPCResetDataPoints(){ Handler.Multiplayer.CallResetDataPoints(NumDataPoints); ResetDataPoints(); } private void RPCGrid(GameObject GridObject){ GridData data = GridObject.GetComponent<GridData>(); int ID = data.GetID(); int Orientation; switch(data.GetOrientation()){ case GridData.Orientation.UP_Y: Orientation = 0; break; case GridData.Orientation.UP_X: Orientation = 1; break; case GridData.Orientation.UP_Z: Orientation = 2; break; default: Orientation = 0; break; } string Name = data.GetName(); // World Index and Data Index are the same value int PositionIndex = data.GetWorldPosIndex(); /*** Make call to server to instantiate grid on every client ***/ Handler.Multiplayer.CallCreateGrid(ID, Orientation, Name, PositionIndex); } private void RPCFlag(GameObject FlagObject){ FlagData data = FlagObject.GetComponent<FlagData>(); int ID = data.GetID(); int Tex = data.GetFlagImageIndex(); string Col = data.GetFlagColorString(); String Annotation = data.GetAnnotation(); Vector3 WorldPosition = data.GetWorldPos(); Vector3 DataPosition = data.GetDataPos(); /*** Make call to server to instantiate flag on every client ***/ Handler.Multiplayer.CallCreateFlag(ID, WorldPosition, DataPosition, Annotation, Col, Tex); } }
namespace NArrange.Tests.Core { using System; using System.ComponentModel; using NArrange.Core; using NArrange.Core.CodeElements; using NArrange.Core.Configuration; using NUnit.Framework; /// <summary> /// Test fixture for the SortedInserter class. /// </summary> [TestFixture] public class SortedInserterTests { #region Methods /// <summary> /// Tests the creation of a SortedInserter instance. /// </summary> [Test] public void CreateTest() { SortBy sortBy = new SortBy(); SortedInserter sortedInserter = new SortedInserter(ElementType.NotSpecified, sortBy); } /// <summary> /// Test construction with a null configuration. /// </summary> [Test] [ExpectedException(typeof(ArgumentNullException))] public void CreateWithNullTest() { SortedInserter sortedInserter = new SortedInserter(ElementType.NotSpecified, null); } /// <summary> /// Tests inserting elements by access and name. /// </summary> [Test] public void InsertByAccessAndNameTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.Access; sortBy.Direction = SortDirection.Ascending; SortBy innerSortBy = new SortBy(); innerSortBy.By = ElementAttributeType.Name; innerSortBy.Direction = SortDirection.Ascending; sortBy.InnerSortBy = innerSortBy; SortedInserter sortedInserter = new SortedInserter(ElementType.Field, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert elements with middle access. // FieldElement field1 = new FieldElement(); field1.Access = CodeAccess.Protected | CodeAccess.Internal; field1.Name = "newField"; sortedInserter.InsertElement(regionElement, field1); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); FieldElement field2 = new FieldElement(); field2.Access = CodeAccess.Protected | CodeAccess.Internal; field2.Name = "gooField"; sortedInserter.InsertElement(regionElement, field2); Assert.AreEqual(2, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); // // Insert an element that should be sorted toward the end // FieldElement field3 = new FieldElement(); field3.Access = CodeAccess.Public; field3.Name = "zooField"; sortedInserter.InsertElement(regionElement, field3); Assert.AreEqual(3, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); FieldElement field4 = new FieldElement(); field4.Access = CodeAccess.Public; field4.Name = "tooField"; sortedInserter.InsertElement(regionElement, field4); Assert.AreEqual(4, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field4), "Element is not at the correct index."); Assert.AreEqual(3, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); // // Insert an element that should be sorted toward the beginning // FieldElement field5 = new FieldElement(); field5.Access = CodeAccess.Private; field5.Name = "booField"; sortedInserter.InsertElement(regionElement, field5); Assert.AreEqual(5, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field5), "Element was not inserted at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); Assert.AreEqual(3, regionElement.Children.IndexOf(field4), "Element is not at the correct index."); Assert.AreEqual(4, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); FieldElement field6 = new FieldElement(); field6.Access = CodeAccess.Private; field6.Name = "fooField"; sortedInserter.InsertElement(regionElement, field6); Assert.AreEqual(6, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field5), "Element was not inserted at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field6), "Element was not inserted at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(3, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); Assert.AreEqual(4, regionElement.Children.IndexOf(field4), "Element is not at the correct index."); Assert.AreEqual(5, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); } /// <summary> /// Tests inserting elements by access and name. /// </summary> [Test] public void InsertByAccessDescendingAndNameTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.Access; sortBy.Direction = SortDirection.Descending; SortBy innerSortBy = new SortBy(); innerSortBy.By = ElementAttributeType.Name; innerSortBy.Direction = SortDirection.Ascending; sortBy.InnerSortBy = innerSortBy; SortedInserter sortedInserter = new SortedInserter(ElementType.Field, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert elements with middle access. // FieldElement field1 = new FieldElement(); field1.Access = CodeAccess.Protected | CodeAccess.Internal; field1.Name = "newField"; sortedInserter.InsertElement(regionElement, field1); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); FieldElement field2 = new FieldElement(); field2.Access = CodeAccess.Protected | CodeAccess.Internal; field2.Name = "gooField"; sortedInserter.InsertElement(regionElement, field2); Assert.AreEqual(2, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); // // Insert an element that should be sorted toward the end // FieldElement field3 = new FieldElement(); field3.Access = CodeAccess.Public; field3.Name = "zooField"; sortedInserter.InsertElement(regionElement, field3); Assert.AreEqual(3, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); FieldElement field4 = new FieldElement(); field4.Access = CodeAccess.Public; field4.Name = "tooField"; sortedInserter.InsertElement(regionElement, field4); Assert.AreEqual(4, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field4), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(3, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); // // Insert an element that should be sorted toward the beginning // FieldElement field5 = new FieldElement(); field5.Access = CodeAccess.Private; field5.Name = "booField"; sortedInserter.InsertElement(regionElement, field5); Assert.AreEqual(5, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field4), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(3, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); Assert.AreEqual(4, regionElement.Children.IndexOf(field5), "Element was not inserted at the correct index."); FieldElement field6 = new FieldElement(); field6.Access = CodeAccess.Private; field6.Name = "fooField"; sortedInserter.InsertElement(regionElement, field6); Assert.AreEqual(6, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field4), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field2), "Element was not inserted at the correct index."); Assert.AreEqual(3, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); Assert.AreEqual(4, regionElement.Children.IndexOf(field5), "Element was not inserted at the correct index."); Assert.AreEqual(5, regionElement.Children.IndexOf(field6), "Element was not inserted at the correct index."); } /// <summary> /// Tests inserting elements by access. /// </summary> [Test] public void InsertByAccessTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.Access; sortBy.Direction = SortDirection.Ascending; SortedInserter sortedInserter = new SortedInserter(ElementType.Field, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert an element with a middle access. // FieldElement field1 = new FieldElement(); field1.Access = CodeAccess.Protected | CodeAccess.Internal; sortedInserter.InsertElement(regionElement, field1); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); // // Insert an element that should be sorted toward the end // FieldElement field2 = new FieldElement(); field2.Access = CodeAccess.Public; sortedInserter.InsertElement(regionElement, field2); Assert.AreEqual(2, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field2), "Element is not at the correct index."); // // Insert an element that should be sorted toward the beginning // FieldElement field3 = new FieldElement(); field3.Access = CodeAccess.Private; sortedInserter.InsertElement(regionElement, field3); Assert.AreEqual(3, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field1), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field2), "Element is not at the correct index."); } /// <summary> /// Tests inserting elements by element type then by name. /// </summary> [Test] public void InsertByElementTypeAndNameTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.ElementType; sortBy.Direction = SortDirection.Ascending; sortBy.InnerSortBy = new SortBy(); sortBy.InnerSortBy.By = ElementAttributeType.Name; sortBy.InnerSortBy.Direction = SortDirection.Ascending; SortedInserter sortedInserter = new SortedInserter(ElementType.NotSpecified, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert an element with a middle access. // ConstructorElement constructor = new ConstructorElement(); constructor.Name = "SomeClass"; constructor.Access = CodeAccess.Public; sortedInserter.InsertElement(regionElement, constructor); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(constructor), "Element was not inserted at the correct index."); // // Insert an element that should be sorted toward the end // MethodElement methodElement1 = new MethodElement(); methodElement1.Name = "SomeMethod"; methodElement1.Access = CodeAccess.Public; sortedInserter.InsertElement(regionElement, methodElement1); Assert.AreEqual(2, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(constructor), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(methodElement1), "Element is not at the correct index."); // // Insert an element that should be sorted toward the beginning // FieldElement fieldElement = new FieldElement(); fieldElement.Name = "someField"; fieldElement.Access = CodeAccess.Private; sortedInserter.InsertElement(regionElement, fieldElement); Assert.AreEqual(3, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(fieldElement), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(constructor), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(methodElement1), "Element is not at the correct index."); // // Insert an element that should be sorted by name // MethodElement methodElement2 = new MethodElement(); methodElement1.Name = "AnotherMethod"; methodElement1.Access = CodeAccess.Public; sortedInserter.InsertElement(regionElement, methodElement2); Assert.AreEqual(4, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(fieldElement), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(constructor), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(methodElement2), "Element is not at the correct index."); Assert.AreEqual(3, regionElement.Children.IndexOf(methodElement1), "Element is not at the correct index."); } /// <summary> /// Tests inserting elements by element type. /// </summary> [Test] public void InsertByElementTypeTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.ElementType; sortBy.Direction = SortDirection.Ascending; SortedInserter sortedInserter = new SortedInserter(ElementType.NotSpecified, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert an element with a middle access. // ConstructorElement constructor = new ConstructorElement(); constructor.Name = "SomeClass"; constructor.Access = CodeAccess.Public; sortedInserter.InsertElement(regionElement, constructor); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(constructor), "Element was not inserted at the correct index."); // // Insert an element that should be sorted toward the end // MethodElement methodElement = new MethodElement(); methodElement.Name = "SomeMethod"; methodElement.Access = CodeAccess.Public; sortedInserter.InsertElement(regionElement, methodElement); Assert.AreEqual(2, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(constructor), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(methodElement), "Element is not at the correct index."); // // Insert an element that should be sorted toward the beginning // FieldElement fieldElement = new FieldElement(); fieldElement.Name = "someField"; fieldElement.Access = CodeAccess.Private; sortedInserter.InsertElement(regionElement, fieldElement); Assert.AreEqual(3, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(fieldElement), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(constructor), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(methodElement), "Element is not at the correct index."); } /// <summary> /// Tests inserting elements by name in descending order. /// </summary> [Test] public void InsertByNameDescendingTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.Name; sortBy.Direction = SortDirection.Descending; SortedInserter sortedInserter = new SortedInserter(ElementType.Field, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert an element with a mid alphabet name. // FieldElement field1 = new FieldElement(); field1.Name = "newField"; sortedInserter.InsertElement(regionElement, field1); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); // // Insert an element that should be sorted toward the beginning // FieldElement field2 = new FieldElement(); field2.Name = "zooField"; sortedInserter.InsertElement(regionElement, field2); Assert.AreEqual(2, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field2), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field1), "Element is not at the correct index."); // // Insert an element that should be sorted toward the end // FieldElement field3 = new FieldElement(); field3.Name = "booField"; sortedInserter.InsertElement(regionElement, field3); Assert.AreEqual(3, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field2), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field1), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); } /// <summary> /// Tests inserting elements by name. /// </summary> [Test] public void InsertByNameTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.Name; sortBy.Direction = SortDirection.Ascending; SortedInserter sortedInserter = new SortedInserter(ElementType.Field, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert an element with a mid alphabet name. // FieldElement field1 = new FieldElement(); field1.Name = "newField"; sortedInserter.InsertElement(regionElement, field1); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); // // Insert an element that should be sorted toward the end // FieldElement field2 = new FieldElement(); field2.Name = "zooField"; sortedInserter.InsertElement(regionElement, field2); Assert.AreEqual(2, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field2), "Element is not at the correct index."); // // Insert an element that should be sorted toward the beginning // FieldElement field3 = new FieldElement(); field3.Name = "booField"; sortedInserter.InsertElement(regionElement, field3); Assert.AreEqual(3, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field1), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field2), "Element is not at the correct index."); } /// <summary> /// Tests inserting elements without any criteria. /// </summary> [Test] public void InsertByNoneTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.None; sortBy.Direction = SortDirection.Ascending; SortedInserter sortedInserter = new SortedInserter(ElementType.Field, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // With no criteria specified, elements should just be inserted // at the end of the collection. // FieldElement field1 = new FieldElement(); field1.Name = "zooField"; sortedInserter.InsertElement(regionElement, field1); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); FieldElement field2 = new FieldElement(); field1.Name = "newField"; sortedInserter.InsertElement(regionElement, field2); Assert.AreEqual(2, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field2), "Element is not at the correct index."); FieldElement field3 = new FieldElement(); field1.Name = "booField"; sortedInserter.InsertElement(regionElement, field3); Assert.AreEqual(3, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(field2), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(field3), "Element is not at the correct index."); } /// <summary> /// Tests inserting type elements by Type. /// </summary> [Test] public void InsertByTypeElementTypeDescendingTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.Type; sortBy.Direction = SortDirection.Descending; SortedInserter sortedInserter = new SortedInserter(ElementType.Type, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert an element with a mid value. // TypeElement type1 = new TypeElement(); type1.Name = "Type1"; type1.Type = TypeElementType.Structure; sortedInserter.InsertElement(regionElement, type1); // // Insert an element that should be sorted toward the end // TypeElement type2 = new TypeElement(); type2.Name = "Type2"; type2.Type = TypeElementType.Class; sortedInserter.InsertElement(regionElement, type2); // // Insert an element that should be sorted toward the middle // TypeElement type3 = new TypeElement(); type3.Name = "Type3"; type3.Type = TypeElementType.Interface; sortedInserter.InsertElement(regionElement, type3); // // Insert an element that should be sorted toward the beginning // TypeElement type4 = new TypeElement(); type4.Name = "Type4"; type4.Type = TypeElementType.Enum; sortedInserter.InsertElement(regionElement, type4); Assert.AreEqual(4, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(type4), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(type3), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(type1), "Element is not at the correct index."); Assert.AreEqual(3, regionElement.Children.IndexOf(type2), "Element is not at the correct index."); } /// <summary> /// Tests inserting elements by type. /// </summary> [Test] public void InsertByTypeTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.Type; sortBy.Direction = SortDirection.Ascending; SortedInserter sortedInserter = new SortedInserter(ElementType.Method, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert an element with a mid alphabet return type. // MethodElement method1 = new MethodElement(); method1.Name = "DoSomething"; method1.Type = "Nullable<DateTime>"; sortedInserter.InsertElement(regionElement, method1); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(method1), "Element was not inserted at the correct index."); // // Insert an element that should be sorted toward the end // MethodElement method2 = new MethodElement(); method2.Name = "DoSomething"; method2.Type = "Type"; sortedInserter.InsertElement(regionElement, method2); Assert.AreEqual(2, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(method1), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(method2), "Element is not at the correct index."); // // Insert an element that should be sorted toward the beginning // MethodElement method3 = new MethodElement(); method3.Name = "DoSomething"; method3.Type = "IEnumerable"; sortedInserter.InsertElement(regionElement, method3); Assert.AreEqual(3, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(method3), "Element is not at the correct index."); Assert.AreEqual(1, regionElement.Children.IndexOf(method1), "Element is not at the correct index."); Assert.AreEqual(2, regionElement.Children.IndexOf(method2), "Element is not at the correct index."); } /// <summary> /// Tests inserting a null element. /// </summary> [Test] public void InsertNullTest() { SortBy sortBy = new SortBy(); sortBy.By = ElementAttributeType.Name; sortBy.Direction = SortDirection.Ascending; SortedInserter sortedInserter = new SortedInserter(ElementType.Field, sortBy); // // Create a parent element // RegionElement regionElement = new RegionElement(); Assert.AreEqual(0, regionElement.Children.Count, "Parent element should not have any children."); // // Insert a non-null element // FieldElement field1 = new FieldElement(); field1.Name = "newField"; sortedInserter.InsertElement(regionElement, field1); Assert.AreEqual(1, regionElement.Children.Count, "Element was not inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element was not inserted at the correct index."); // // Insert a null element // FieldElement field2 = null; sortedInserter.InsertElement(regionElement, field2); Assert.AreEqual(1, regionElement.Children.Count, "Element should not have been inserted into the parent."); Assert.AreEqual(0, regionElement.Children.IndexOf(field1), "Element is not at the correct index."); } #endregion Methods } }
using System; using System.Collections.Generic; namespace GraduatedCylinder { public class UnitPreferences { private readonly SafeDictionary<DimensionType, UnitOfMeasure> _unitPreferences = new SafeDictionary<DimensionType, UnitOfMeasure>(); static UnitPreferences() { CultureUnitGenerators = new Dictionary<string, Func<UnitPreferences>> { { "es", () => GetMetricUnits() }, { "es-mx", () => GetMetricUnits() }, { "en", () => GetAmericanEnglishUnits() }, { "en-gb", () => GetBritishEnglishUnits() }, { "en-us", () => GetAmericanEnglishUnits() }, { "fr", () => GetMetricUnits() }, { "fr-ca", () => GetMetricUnits() } }; } public UnitPreferences() { _unitPreferences.Add(DimensionType.Acceleration, AccelerationUnit.BaseUnit); _unitPreferences.Add(DimensionType.Angle, AngleUnit.BaseUnit); _unitPreferences.Add(DimensionType.AngularAcceleration, AngularAccelerationUnit.BaseUnit); _unitPreferences.Add(DimensionType.Area, AreaUnit.BaseUnit); _unitPreferences.Add(DimensionType.ElectricCurrent, ElectricCurrentUnit.BaseUnit); _unitPreferences.Add(DimensionType.ElectricPotential, ElectricPotentialUnit.BaseUnit); _unitPreferences.Add(DimensionType.ElectricResistance, ElectricResistanceUnit.BaseUnit); _unitPreferences.Add(DimensionType.Energy, EnergyUnit.BaseUnit); _unitPreferences.Add(DimensionType.Force, ForceUnit.BaseUnit); _unitPreferences.Add(DimensionType.Frequency, FrequencyUnit.BaseUnit); _unitPreferences.Add(DimensionType.Jerk, JerkUnit.BaseUnit); _unitPreferences.Add(DimensionType.Length, LengthUnit.BaseUnit); _unitPreferences.Add(DimensionType.MassFlowRate, MassFlowRateUnit.BaseUnit); _unitPreferences.Add(DimensionType.Mass, MassUnit.BaseUnit); _unitPreferences.Add(DimensionType.MassDensity, MassDensityUnit.BaseUnit); _unitPreferences.Add(DimensionType.Momentum, MomentumUnit.BaseUnit); _unitPreferences.Add(DimensionType.Numeric, NumericUnit.BaseUnit); _unitPreferences.Add(DimensionType.Power, PowerUnit.BaseUnit); _unitPreferences.Add(DimensionType.Pressure, PressureUnit.BaseUnit); _unitPreferences.Add(DimensionType.Speed, SpeedUnit.BaseUnit); _unitPreferences.Add(DimensionType.Temperature, TemperatureUnit.BaseUnit); _unitPreferences.Add(DimensionType.Time, TimeUnit.BaseUnit); _unitPreferences.Add(DimensionType.Torque, TorqueUnit.BaseUnit); _unitPreferences.Add(DimensionType.Volume, VolumeUnit.BaseUnit); _unitPreferences.Add(DimensionType.VolumetricFlowRate, VolumetricFlowRateUnit.BaseUnit); } public UnitOfMeasure AccelerationUnits { get { return _unitPreferences[DimensionType.Acceleration]; } set { _unitPreferences[DimensionType.Acceleration] = value; } } public UnitOfMeasure AngleUnits { get { return _unitPreferences[DimensionType.Angle]; } set { _unitPreferences[DimensionType.Angle] = value; } } public UnitOfMeasure AngularAccelerationUnits { get { return _unitPreferences[DimensionType.AngularAcceleration]; } set { _unitPreferences[DimensionType.AngularAcceleration] = value; } } public UnitOfMeasure AreaUnits { get { return _unitPreferences[DimensionType.Area]; } set { _unitPreferences[DimensionType.Area] = value; } } public UnitOfMeasure CurrentUnits { get { return _unitPreferences[DimensionType.ElectricCurrent]; } set { _unitPreferences[DimensionType.ElectricCurrent] = value; } } public UnitOfMeasure ElectricPotentialUnits { get { return _unitPreferences[DimensionType.ElectricPotential]; } set { _unitPreferences[DimensionType.ElectricPotential] = value; } } public UnitOfMeasure ElectricResistanceUnits { get { return _unitPreferences[DimensionType.ElectricResistance]; } set { _unitPreferences[DimensionType.ElectricResistance] = value; } } public UnitOfMeasure EnergyUnits { get { return _unitPreferences[DimensionType.Energy]; } set { _unitPreferences[DimensionType.Energy] = value; } } public UnitOfMeasure ForceUnits { get { return _unitPreferences[DimensionType.Force]; } set { _unitPreferences[DimensionType.Force] = value; } } public UnitOfMeasure FrequencyUnits { get { return _unitPreferences[DimensionType.Frequency]; } set { _unitPreferences[DimensionType.Frequency] = value; } } public UnitOfMeasure JerkUnits { get { return _unitPreferences[DimensionType.Jerk]; } set { _unitPreferences[DimensionType.Jerk] = value; } } public UnitOfMeasure LengthUnits { get { return _unitPreferences[DimensionType.Length]; } set { _unitPreferences[DimensionType.Length] = value; } } public UnitOfMeasure MassDensityUnits { get { return _unitPreferences[DimensionType.MassDensity]; } set { _unitPreferences[DimensionType.MassDensity] = value; } } public UnitOfMeasure MassFlowRateUnits { get { return _unitPreferences[DimensionType.MassFlowRate]; } set { _unitPreferences[DimensionType.MassFlowRate] = value; } } public UnitOfMeasure MassUnits { get { return _unitPreferences[DimensionType.Mass]; } set { _unitPreferences[DimensionType.Mass] = value; } } public UnitOfMeasure MomentumUnits { get { return _unitPreferences[DimensionType.Momentum]; } set { _unitPreferences[DimensionType.Momentum] = value; } } public UnitOfMeasure NumericUnits { get { return _unitPreferences[DimensionType.Numeric]; } set { _unitPreferences[DimensionType.Numeric] = value; } } public UnitOfMeasure PowerUnits { get { return _unitPreferences[DimensionType.Power]; } set { _unitPreferences[DimensionType.Power] = value; } } public UnitOfMeasure PressureUnits { get { return _unitPreferences[DimensionType.Pressure]; } set { _unitPreferences[DimensionType.Pressure] = value; } } public UnitOfMeasure SpeedUnits { get { return _unitPreferences[DimensionType.Speed]; } set { _unitPreferences[DimensionType.Speed] = value; } } public UnitOfMeasure TemperatureUnits { get { return _unitPreferences[DimensionType.Temperature]; } set { _unitPreferences[DimensionType.Temperature] = value; } } public UnitOfMeasure TimeUnits { get { return _unitPreferences[DimensionType.Time]; } set { _unitPreferences[DimensionType.Time] = value; } } public UnitOfMeasure TorqueUnits { get { return _unitPreferences[DimensionType.Torque]; } set { _unitPreferences[DimensionType.Torque] = value; } } public UnitOfMeasure VolumetricFlowRateUnits { get { return _unitPreferences[DimensionType.VolumetricFlowRate]; } set { _unitPreferences[DimensionType.VolumetricFlowRate] = value; } } public UnitOfMeasure VolumeUnits { get { return _unitPreferences[DimensionType.Volume]; } set { _unitPreferences[DimensionType.Volume] = value; } } public UnitOfMeasure this[DimensionType dimensionType] { get { return _unitPreferences[dimensionType]; } } public void Fix(ISupportUnitOfMeasure dimension) { dimension.Units = _unitPreferences[dimension.Units.DimensionType]; } private static readonly Dictionary<string, Func<UnitPreferences>> CultureUnitGenerators; public static UnitPreferences GetAmericanEnglishUnits() { return new UnitPreferences { AccelerationUnits = AccelerationUnit.MilePerHourPerSecond, AngleUnits = AngleUnit.Degree, AreaUnits = AreaUnit.SquareMiles, EnergyUnits = EnergyUnit.KiloCalories, ForceUnits = ForceUnit.PoundForce, JerkUnits = JerkUnit.MilesPerSecondCubed, LengthUnits = LengthUnit.Mile, MassUnits = MassUnit.Pounds, MassDensityUnits = MassDensityUnit.PoundsPerCubicFeet, MassFlowRateUnits = MassFlowRateUnit.PoundsPerSecond, MomentumUnits = MomentumUnit.PoundsMilesPerHour, PowerUnits = PowerUnit.Horsepower, PressureUnits = PressureUnit.PoundsPerSquareInch, SpeedUnits = SpeedUnit.MilesPerHour, TemperatureUnits = TemperatureUnit.Fahrenheit, TimeUnits = TimeUnit.Hours, TorqueUnits = TorqueUnit.FootPounds, VolumeUnits = VolumeUnit.GallonsUSLiquid, VolumetricFlowRateUnits = VolumetricFlowRateUnit.GallonsUsPerHour }; } public static UnitPreferences GetBritishEnglishUnits() { return new UnitPreferences { AccelerationUnits = AccelerationUnit.MilePerHourPerSecond, AngleUnits = AngleUnit.Degree, AreaUnits = AreaUnit.SquareMiles, EnergyUnits = EnergyUnit.KiloCalories, ForceUnits = ForceUnit.PoundForce, JerkUnits = JerkUnit.MilesPerSecondCubed, LengthUnits = LengthUnit.Mile, MassUnits = MassUnit.Pounds, MassDensityUnits = MassDensityUnit.PoundsPerCubicFeet, MassFlowRateUnits = MassFlowRateUnit.PoundsPerSecond, MomentumUnits = MomentumUnit.PoundsMilesPerHour, PowerUnits = PowerUnit.Horsepower, PressureUnits = PressureUnit.PoundsPerSquareInch, SpeedUnits = SpeedUnit.MilesPerHour, TemperatureUnits = TemperatureUnit.Fahrenheit, TorqueUnits = TorqueUnit.FootPounds, VolumeUnits = VolumeUnit.GallonsUK, VolumetricFlowRateUnits = VolumetricFlowRateUnit.GallonsUsPerSecond }; } public static UnitPreferences GetCultureUnits(string cultureCode) { cultureCode = cultureCode.ToLowerInvariant(); return CultureUnitGenerators.ContainsKey(cultureCode) ? CultureUnitGenerators[cultureCode]() : GetMetricUnits(); } public static UnitPreferences GetMetricUnits() { return new UnitPreferences { AccelerationUnits = AccelerationUnit.KilometerPerHourPerSecond, AreaUnits = AreaUnit.KilometerSquared, EnergyUnits = EnergyUnit.NewtonMeters, JerkUnits = JerkUnit.KiloMetersPerSecondCubed, LengthUnits = LengthUnit.Kilometer, PowerUnits = PowerUnit.Kilowatts, SpeedUnits = SpeedUnit.KilometersPerHour, VolumeUnits = VolumeUnit.Liters }; } } }
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; public partial class Backoffice_Registrasi_RJAddLama : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["RegistrasiRJ"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } btnSave.Text = "<center><img alt=\"" + Resources.GetString("", "Save") + "\" src=\"" + Request.ApplicationPath + "/images/save_f2.gif\" align=\"middle\" border=\"0\" name=\"save\" value=\"save\"><center>"; btnCancel.Text = "<center><img alt=\"" + Resources.GetString("", "Cancel") + "\" src=\"" + Request.ApplicationPath + "/images/cancel_f2.gif\" align=\"middle\" border=\"0\" name=\"cancel\" value=\"cancel\"><center>"; GetListPoliklinik(); GetListHubungan(); GetListStatus(); GetListAgama(); GetListPendidikan(); txtTanggalRegistrasi.Text = DateTime.Now.ToString("dd/MM/yyyy"); string hari = DateTime.Now.DayOfWeek.ToString(); switch (hari) { case "Monday": txtHari.Text = "1"; break; case "Tuesday": txtHari.Text = "2"; break; case "Wednesday": txtHari.Text = "3"; break; case "Thursday": txtHari.Text = "4"; break; case "Friday": txtHari.Text = "5"; break; case "Saturday": txtHari.Text = "6"; break; case "Sunday": txtHari.Text = "7"; break; } GetNomorRegistrasi(); GetListSatuanKerjaPenjamin(); GetListJenisPenjamin(); } } //========= public void GetListStatus() { string StatusId = ""; SIMRS.DataAccess.RS_Status myObj = new SIMRS.DataAccess.RS_Status(); DataTable dt = myObj.GetList(); cmbStatusPenjamin.Items.Clear(); int i = 0; cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = ""; cmbStatusPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbStatusPenjamin.Items.Add(""); cmbStatusPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbStatusPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == StatusId) { cmbStatusPenjamin.SelectedIndex = i; } i++; } } public void GetListPangkatPenjamin() { string PangkatId = ""; SIMRS.DataAccess.RS_Pangkat myObj = new SIMRS.DataAccess.RS_Pangkat(); if (cmbStatusPenjamin.SelectedIndex > 0) myObj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value); DataTable dt = myObj.GetListByStatusId(); cmbPangkatPenjamin.Items.Clear(); int i = 0; cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = ""; cmbPangkatPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPangkatPenjamin.Items.Add(""); cmbPangkatPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbPangkatPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PangkatId) { cmbPangkatPenjamin.SelectedIndex = i; } i++; } } public void GetListAgama() { string AgamaId = ""; BkNet.DataAccess.Agama myObj = new BkNet.DataAccess.Agama(); DataTable dt = myObj.GetList(); cmbAgamaPenjamin.Items.Clear(); int i = 0; cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = ""; cmbAgamaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbAgamaPenjamin.Items.Add(""); cmbAgamaPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbAgamaPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == AgamaId) cmbAgamaPenjamin.SelectedIndex = i; i++; } } public void GetListPendidikan() { string PendidikanId = ""; BkNet.DataAccess.Pendidikan myObj = new BkNet.DataAccess.Pendidikan(); DataTable dt = myObj.GetList(); cmbPendidikanPenjamin.Items.Clear(); int i = 0; cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = ""; cmbPendidikanPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPendidikanPenjamin.Items.Add(""); cmbPendidikanPenjamin.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPendidikanPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PendidikanId) cmbPendidikanPenjamin.SelectedIndex = i; i++; } } //========== public void GetListPoliklinik() { string PoliklinikId = ""; SIMRS.DataAccess.RS_Poliklinik myObj = new SIMRS.DataAccess.RS_Poliklinik(); DataTable dt = myObj.GetListRJ(); cmbPoliklinik.Items.Clear(); int i = 0; cmbPoliklinik.Items.Add(""); cmbPoliklinik.Items[i].Text = ""; cmbPoliklinik.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPoliklinik.Items.Add(""); cmbPoliklinik.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString(); cmbPoliklinik.Items[i].Value = dr["Id"].ToString() + "|" + dr["KelompokPoliklinikId"].ToString(); if (dr["Id"].ToString() == PoliklinikId) cmbPoliklinik.SelectedIndex = i; i++; } } public void GetListDokter() { string DokterId = ""; SIMRS.DataAccess.RS_JadwalDokter myObj = new SIMRS.DataAccess.RS_JadwalDokter(); if (cmbPoliklinik.SelectedIndex > 0) { string[] poli = cmbPoliklinik.SelectedItem.Value.Split('|'); myObj.PoliklinikId = int.Parse(poli[0]); } myObj.HariId = int.Parse(txtHari.Text); DataTable dt = myObj.GetListDokterByPoliklinikIdAndHariId(); cmbDokter.Items.Clear(); int i = 0; cmbDokter.Items.Add(""); cmbDokter.Items[i].Text = ""; cmbDokter.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbDokter.Items.Add(""); cmbDokter.Items[i].Text = dr["DokterNama"].ToString() + " [" + dr["JamPraktek"].ToString() + "]"; cmbDokter.Items[i].Value = dr["DokterId"].ToString() + "|" + dr["JamPraktek"].ToString(); if (dr["DokterId"].ToString() == DokterId) cmbDokter.SelectedIndex = i; i++; } } public void GetNomorTunggu() { if (cmbPoliklinik.SelectedIndex > 0 && cmbDokter.SelectedIndex > 0) { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); string[] poli = cmbPoliklinik.SelectedItem.Value.Split('|'); myObj.PoliklinikId = int.Parse(poli[0]); if (poli[1] != "2")//Poli UGD { myObj.DokterId = int.Parse(txtDokterId.Text); myObj.JamPraktek = txtJamPraktek.Text; } myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNomorTunggu.Text = myObj.GetNomorTunggu().ToString(); } else txtNomorTunggu.Text = ""; } public void GetListHubungan() { string HubunganId = ""; SIMRS.DataAccess.RS_Hubungan myObj = new SIMRS.DataAccess.RS_Hubungan(); DataTable dt = myObj.GetList(); cmbHubungan.Items.Clear(); int i = 0; cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = ""; cmbHubungan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbHubungan.Items.Add(""); cmbHubungan.Items[i].Text = dr["Nama"].ToString(); cmbHubungan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == HubunganId) cmbHubungan.SelectedIndex = i; i++; } } public void GetNomorRegistrasi() { SIMRS.DataAccess.RS_RawatJalan myObj = new SIMRS.DataAccess.RS_RawatJalan(); if (cmbPoliklinik.SelectedIndex > 0) { string[] poli = cmbPoliklinik.SelectedItem.Value.Split('|'); myObj.PoliklinikId = int.Parse(poli[0]); } myObj.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); txtNoRegistrasi.Text = myObj.GetNomorRegistrasi(); lblNoRegistrasi.Text = txtNoRegistrasi.Text; } public void OnSave(Object sender, EventArgs e) { lblError.Text = ""; if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (!Page.IsValid) { return; } if (txtPasienId.Text == "") { lblError.Text = "Data Pasien Belum dipilih !"; return; } int PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex > 0) { //Input Data Penjamin SIMRS.DataAccess.RS_Penjamin myPenj = new SIMRS.DataAccess.RS_Penjamin(); myPenj.PenjaminId = 0; if (cmbJenisPenjamin.SelectedIndex == 1) { myPenj.Nama = txtNamaPenjamin.Text; if (cmbHubungan.SelectedIndex > 0) myPenj.HubunganId = int.Parse(cmbHubungan.SelectedItem.Value); myPenj.Umur = txtUmurPenjamin.Text; myPenj.Alamat = txtAlamatPenjamin.Text; myPenj.Telepon = txtTeleponPenjamin.Text; if (cmbAgamaPenjamin.SelectedIndex > 0) myPenj.AgamaId = int.Parse(cmbAgamaPenjamin.SelectedItem.Value); if (cmbPendidikanPenjamin.SelectedIndex > 0) myPenj.PendidikanId = int.Parse(cmbPendidikanPenjamin.SelectedItem.Value); if (cmbStatusPenjamin.SelectedIndex > 0) myPenj.StatusId = int.Parse(cmbStatusPenjamin.SelectedItem.Value); if (cmbPangkatPenjamin.SelectedIndex > 0) myPenj.PangkatId = int.Parse(cmbPangkatPenjamin.SelectedItem.Value); myPenj.NoKTP = txtNoKTPPenjamin.Text; myPenj.GolDarah = txtGolDarahPenjamin.Text; myPenj.NRP = txtNRPPenjamin.Text; //myPenj.Kesatuan = txtKesatuanPenjamin.Text; myPenj.Kesatuan = cmbSatuanKerjaPenjamin.SelectedItem.ToString(); myPenj.AlamatKesatuan = txtAlamatKesatuanPenjamin.Text; myPenj.Keterangan = txtKeteranganPenjamin.Text; } else { myPenj.Nama = txtNamaPerusahaan.Text; myPenj.NamaKontak = txtNamaKontak.Text; myPenj.Alamat = txtAlamatPerusahaan.Text; myPenj.Telepon = txtTeleponPerusahaan.Text; myPenj.Fax = txtFAXPerusahaan.Text; } myPenj.CreatedBy = UserId; myPenj.CreatedDate = DateTime.Now; myPenj.Insert(); PenjaminId = (int)myPenj.PenjaminId; } //Input Data Registrasi SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.RegistrasiId = 0; myReg.PasienId = Int64.Parse(txtPasienId.Text); GetNomorRegistrasi(); myReg.NoRegistrasi = txtNoRegistrasi.Text; myReg.JenisRegistrasiId = 1; myReg.TanggalRegistrasi = DateTime.Parse(txtTanggalRegistrasi.Text); myReg.JenisPenjaminId = int.Parse(cmbJenisPenjamin.SelectedItem.Value); if (PenjaminId != 0) myReg.PenjaminId = PenjaminId; myReg.CreatedBy = UserId; myReg.CreatedDate = DateTime.Now; myReg.Insert(); //Input Data Rawat Jalan SIMRS.DataAccess.RS_RawatJalan myRJ = new SIMRS.DataAccess.RS_RawatJalan(); myRJ.RawatJalanId = 0; myRJ.RegistrasiId = myReg.RegistrasiId; if (cmbPoliklinik.SelectedIndex > 0) { string[] poli = cmbPoliklinik.SelectedItem.Value.Split('|'); myRJ.PoliklinikId = int.Parse(poli[0]); } if (cmbDokter.SelectedIndex > 0) { myRJ.DokterId = int.Parse(txtDokterId.Text); myRJ.JamPraktek = txtJamPraktek.Text; } myRJ.TanggalBerobat = DateTime.Parse(txtTanggalRegistrasi.Text); GetNomorTunggu(); if (txtNomorTunggu.Text != "") myRJ.NomorTunggu = int.Parse(txtNomorTunggu.Text); myRJ.Status = 0;//Baru daftar myRJ.CreatedBy = UserId; myRJ.CreatedDate = DateTime.Now; myRJ.Insert(); string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("RJView.aspx?CurrentPage=" + CurrentPage + "&RawatJalanId=" + myRJ.RawatJalanId); } public void OnCancel(Object sender, EventArgs e) { string CurrentPage = ""; if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") CurrentPage = Request.QueryString["CurrentPage"].ToString(); Response.Redirect("RJList.aspx?CurrentPage=" + CurrentPage); } protected void cmbJenisPenjamin_SelectedIndexChanged(object sender, EventArgs e) { if (cmbJenisPenjamin.SelectedIndex == 1) { tblPenjaminKeluarga.Visible = true; tblPenjaminPerusahaan.Visible = false; if (txtPenjaminId.Text != "") { SIMRS.DataAccess.RS_Penjamin myRJ = new SIMRS.DataAccess.RS_Penjamin(); myRJ.PenjaminId = Int64.Parse(txtPenjaminId.Text); DataTable dt = myRJ.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtNamaPenjamin.Text = row["Nama"].ToString(); cmbHubungan.SelectedValue = row["HubunganId"].ToString(); txtUmurPenjamin.Text = row["Umur"].ToString(); txtAlamatPenjamin.Text = row["Alamat"].ToString(); txtTeleponPenjamin.Text = row["Telepon"].ToString(); cmbAgamaPenjamin.SelectedValue = row["AgamaId"].ToString(); cmbPendidikanPenjamin.SelectedValue = row["PendidikanId"].ToString(); cmbStatusPenjamin.SelectedValue = row["StatusId"].ToString(); cmbPangkatPenjamin.SelectedValue = row["PangkatId"].ToString(); txtNoKTPPenjamin.Text = row["NoKTP"].ToString(); txtGolDarahPenjamin.Text = row["GolDarah"].ToString(); txtNRPPenjamin.Text = row["NRP"].ToString(); //cmbSatuanKerjaPenjamin.Text = row["Kesatuan"].ToString(); txtAlamatKesatuanPenjamin.Text = row["AlamatKesatuan"].ToString(); txtKeteranganPenjamin.Text = row["Keterangan"].ToString(); } else { EmptyFormPejamin(); } } } else if (cmbJenisPenjamin.SelectedIndex == 2 || cmbJenisPenjamin.SelectedIndex == 3) { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = true; if (txtPenjaminId.Text != "") { SIMRS.DataAccess.RS_Penjamin myRJ = new SIMRS.DataAccess.RS_Penjamin(); myRJ.PenjaminId = Int64.Parse(txtPenjaminId.Text); DataTable dt = myRJ.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtNamaPerusahaan.Text = row["Nama"].ToString(); txtNamaKontak.Text = row["NamaKontak"].ToString(); txtAlamatPerusahaan.Text = row["Alamat"].ToString(); txtTeleponPerusahaan.Text = row["Telepon"].ToString(); txtFAXPerusahaan.Text = row["Fax"].ToString(); txtKeteranganPerusahaan.Text = row["Keterangan"].ToString(); } else { EmptyFormPejamin(); } } } else { tblPenjaminKeluarga.Visible = false; tblPenjaminPerusahaan.Visible = false; } } public void EmptyFormPejamin() { txtNamaPenjamin.Text = ""; cmbHubungan.SelectedValue = ""; txtUmurPenjamin.Text = ""; txtAlamatPenjamin.Text = ""; txtTeleponPenjamin.Text = ""; cmbAgamaPenjamin.SelectedIndex = 0; cmbPendidikanPenjamin.SelectedIndex = 0; cmbStatusPenjamin.SelectedIndex = 0; //cmbPangkatPenjamin.SelectedIndex = 0; txtNoKTPPenjamin.Text = ""; txtGolDarahPenjamin.Text = ""; txtNRPPenjamin.Text = ""; cmbSatuanKerjaPenjamin.SelectedIndex = 0; txtAlamatKesatuanPenjamin.Text = ""; txtKeteranganPenjamin.Text = ""; txtNamaPerusahaan.Text = ""; txtNamaKontak.Text = ""; txtAlamatPerusahaan.Text = ""; txtTeleponPerusahaan.Text = ""; txtFAXPerusahaan.Text = ""; txtKeteranganPerusahaan.Text = ""; } protected void cmbPoliklinik_SelectedIndexChanged(object sender, EventArgs e) { if (cmbPoliklinik.SelectedIndex > 0) { string[] poli = cmbPoliklinik.SelectedItem.Value.Split('|'); if (poli[1] == "2") { RVDokter.Visible = false; } else { RVDokter.Visible = true; } } GetListDokter(); GetNomorTunggu(); GetNomorRegistrasi(); } protected void cmbDokter_SelectedIndexChanged(object sender, EventArgs e) { if (cmbDokter.Items.Count > 1 && cmbDokter.SelectedIndex > 0) { string[] jadwaldokter = cmbDokter.SelectedItem.Value.Split('|'); txtDokterId.Text = jadwaldokter[0]; if (jadwaldokter.Length > 1) txtJamPraktek.Text = jadwaldokter[1]; } else { txtDokterId.Text = ""; txtJamPraktek.Text = ""; } GetNomorTunggu(); } protected void txtTanggalRegistrasi_TextChanged(object sender, EventArgs e) { DateTime tanggal = DateTime.Parse(txtTanggalRegistrasi.Text); string hari = tanggal.DayOfWeek.ToString(); switch (hari) { case "Monday": txtHari.Text = "1"; break; case "Tuesday": txtHari.Text = "2"; break; case "Wednesday": txtHari.Text = "3"; break; case "Thursday": txtHari.Text = "4"; break; case "Friday": txtHari.Text = "5"; break; case "Saturday": txtHari.Text = "6"; break; case "Sunday": txtHari.Text = "7"; break; } GetListDokter(); GetNomorTunggu(); GetNomorRegistrasi(); } protected void btnSearch_Click(object sender, EventArgs e) { GetListPasien(); EmptyFormPasien(); } public DataView GetResultSearch() { DataSet ds = new DataSet(); DataTable myData = new DataTable(); SIMRS.DataAccess.RS_Pasien myObj = new SIMRS.DataAccess.RS_Pasien(); if (txtNoRMSearch.Text != "") myObj.NoRM = txtNoRMSearch.Text; if (txtNamaSearch.Text != "") myObj.Nama = txtNamaSearch.Text; if (txtNRP.Text != "") myObj.NRP = txtNRP.Text; myData = myObj.SelectAllFilter(); DataView dv = myData.DefaultView; return dv; } public void GetListPasien() { GridViewPasien.SelectedIndex = -1; // Re-binds the grid GridViewPasien.DataSource = GetResultSearch(); GridViewPasien.DataBind(); } protected void GridViewPasien_SelectedIndexChanged(object sender, EventArgs e) { Int64 PaseinId = (Int64)GridViewPasien.SelectedValue; UpdateFormPasien(PaseinId); EmptyFormPejamin(); } public void GetListJenisPenjamin() { string JenisPenjaminId = ""; SIMRS.DataAccess.RS_JenisPenjamin myObj = new SIMRS.DataAccess.RS_JenisPenjamin(); DataTable dt = myObj.GetList(); cmbJenisPenjamin.Items.Clear(); int i = 0; foreach (DataRow dr in dt.Rows) { cmbJenisPenjamin.Items.Add(""); cmbJenisPenjamin.Items[i].Text = dr["Nama"].ToString(); cmbJenisPenjamin.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == JenisPenjaminId) cmbJenisPenjamin.SelectedIndex = i; i++; } } public void UpdateFormPasien(Int64 PaseinId) { SIMRS.DataAccess.RS_Pasien myObj = new SIMRS.DataAccess.RS_Pasien(); myObj.PasienId = PaseinId; DataTable dt = myObj.SelectOne(); if (dt.Rows.Count > 0) { DataRow row = dt.Rows[0]; txtPasienId.Text = row["PasienId"].ToString(); lblNoRMHeader.Text = row["NoRM"].ToString(); lblNoRM.Text = row["NoRM"].ToString(); lblNamaPasienHeader.Text = row["Nama"].ToString(); lblNamaPasien.Text = row["Nama"].ToString(); lblStatus.Text = row["StatusNama"].ToString(); lblPangkat.Text = row["PangkatNama"].ToString(); lblNoAskes.Text = row["NoAskes"].ToString(); lblNoKTP.Text = row["NoKTP"].ToString(); lblGolDarah.Text = row["GolDarah"].ToString(); lblNRP.Text = row["NRP"].ToString(); lblKesatuan.Text = row["Kesatuan"].ToString(); lblTempatLahir.Text = row["TempatLahir"].ToString() == "" ? "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" : row["TempatLahir"].ToString(); lblTanggalLahir.Text = row["TanggalLahir"].ToString() != "" ? ((DateTime)row["TanggalLahir"]).ToString("dd MMMM yyyy"):""; lblAlamat.Text = row["Alamat"].ToString(); lblTelepon.Text = row["Telepon"].ToString(); lblJenisKelamin.Text = row["JenisKelamin"].ToString(); lblStatusPerkawinan.Text = row["StatusPerkawinanNama"].ToString(); lblAgama.Text = row["AgamaNama"].ToString(); lblPendidikan.Text = row["PendidikanNama"].ToString(); lblPekerjaan.Text = row["Pekerjaan"].ToString(); lblAlamatKantor.Text = row["AlamatKantor"].ToString(); lblTeleponKantor.Text = row["TeleponKantor"].ToString(); lblKeterangan.Text = row["Keterangan"].ToString(); } else { EmptyFormPasien(); } SIMRS.DataAccess.RS_Registrasi myReg = new SIMRS.DataAccess.RS_Registrasi(); myReg.PasienId = Int64.Parse(txtPasienId.Text); DataTable dTbl = myReg.SelectOne_ByPasienId(); if (dTbl.Rows.Count > 0) { DataRow rs = dTbl.Rows[0]; txtPenjaminId.Text = rs["PenjaminId"].ToString(); } } public void EmptyFormPasien() { txtPasienId.Text = ""; lblNoRMHeader.Text = ""; lblNoRM.Text = ""; lblNamaPasien.Text = ""; lblNamaPasienHeader.Text = ""; lblStatus.Text = ""; lblPangkat.Text = ""; lblNoAskes.Text = ""; lblNoKTP.Text = ""; lblGolDarah.Text = ""; lblNRP.Text = ""; lblKesatuan.Text = ""; lblTempatLahir.Text = ""; lblTanggalLahir.Text = ""; lblAlamat.Text = ""; lblTelepon.Text = ""; lblJenisKelamin.Text = ""; lblStatusPerkawinan.Text = ""; lblAgama.Text = ""; lblPendidikan.Text = ""; lblPekerjaan.Text = ""; lblAlamatKantor.Text = ""; lblTeleponKantor.Text = ""; lblKeterangan.Text = ""; } protected void GridViewPasien_PageIndexChanging(object sender, GridViewPageEventArgs e) { GridViewPasien.SelectedIndex = -1; GridViewPasien.PageIndex = e.NewPageIndex; GridViewPasien.DataSource = GetResultSearch(); GridViewPasien.DataBind(); EmptyFormPasien(); } protected void cmbStatusPenjamin_SelectedIndexChanged(object sender, EventArgs e) { GetListPangkatPenjamin(); } public void GetListSatuanKerjaPenjamin() { string SatuanKerjaId = ""; SIMRS.DataAccess.RS_SatuanKerja myObj = new SIMRS.DataAccess.RS_SatuanKerja(); DataTable dt = myObj.GetList(); cmbSatuanKerjaPenjamin.Items.Clear(); int i = 0; cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = ""; cmbSatuanKerjaPenjamin.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbSatuanKerjaPenjamin.Items.Add(""); cmbSatuanKerjaPenjamin.Items[i].Text = dr["NamaSatker"].ToString(); cmbSatuanKerjaPenjamin.Items[i].Value = dr["IdSatuanKerja"].ToString(); if (dr["IdSatuanKerja"].ToString() == SatuanKerjaId) cmbSatuanKerjaPenjamin.SelectedIndex = i; i++; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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.IO; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Sensus.Shared { public class Logger { private const int MAX_LOG_SIZE_MEGABYTES = 20; private string _path; private LoggingLevel _level; private TextWriter[] _otherOutputs; private List<string> _messageBuffer; private Regex _extraWhiteSpace; public LoggingLevel Level { get { return _level; } set { _level = value; } } public Logger(string path, LoggingLevel level, params TextWriter[] otherOutputs) { _path = path; _level = level; _otherOutputs = otherOutputs; _messageBuffer = new List<string>(); _extraWhiteSpace = new Regex(@"\s\s+"); } public void Log(string message, LoggingLevel level, Type callingType, bool throwException = false) { // if we're throwing an exception, use the caller's version of the message instead of our modified version below. Exception ex = null; if (throwException) ex = new Exception(message); if (level <= _level) { // remove newlines and extra white space, and only log if the result is non-empty message = _extraWhiteSpace.Replace(message.Replace('\r', ' ').Replace('\n', ' ').Trim(), " "); if (!string.IsNullOrWhiteSpace(message)) { // add timestamp and calling type type message = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToLongTimeString() + ": " + (callingType == null ? "" : "[" + callingType.Name + "] ") + message; lock (_messageBuffer) { _messageBuffer.Add(message); if (_otherOutputs != null) foreach (TextWriter otherOutput in _otherOutputs) { try { otherOutput.WriteLine(message); } catch (Exception writeException) { Console.Error.WriteLine("Failed to write to output: " + writeException.Message); } } // append buffer to file periodically if (_messageBuffer.Count % 100 == 0) { try { CommitMessageBuffer(); } catch (Exception commitException) { // try switching the log path to a random file, since access violations might prevent us from writing the current _path (e.g., in the case of crashes) _path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), Guid.NewGuid().ToString() + ".txt"); _messageBuffer.Add("Switched log path to \"" + _path + "\" due to exception: " + commitException.Message); } } } } } if (ex != null) throw ex; } public void CommitMessageBuffer() { lock (_messageBuffer) { if (_messageBuffer.Count > 0) { try { using (StreamWriter file = new StreamWriter(_path, true)) { foreach (string bufferedMessage in _messageBuffer) file.WriteLine(bufferedMessage); } // keep log file under a certain size by reading the most recent MAX_LOG_SIZE_MEGABYTES. long currSizeBytes = new FileInfo(_path).Length; if (currSizeBytes > MAX_LOG_SIZE_MEGABYTES * 1024 * 1024) { int newSizeBytes = (MAX_LOG_SIZE_MEGABYTES - 5) * 1024 * 1024; byte[] newBytes = new byte[newSizeBytes]; using (FileStream file = new FileStream(_path, FileMode.Open, FileAccess.Read)) { file.Position = currSizeBytes - newSizeBytes; file.Read(newBytes, 0, newSizeBytes); } File.Delete(_path); File.WriteAllBytes(_path, newBytes); } } catch (Exception ex) { Log("Error committing message buffer: " + ex.Message, LoggingLevel.Normal, GetType()); } _messageBuffer.Clear(); } } } public List<string> Read(int maxMessages, bool mostRecentFirst) { lock (_messageBuffer) { CommitMessageBuffer(); List<string> messages = new List<string>(); try { using (StreamReader file = new StreamReader(_path)) { if (maxMessages > 0) { int numLines = 0; while (file.ReadLine() != null) ++numLines; file.BaseStream.Position = 0; file.DiscardBufferedData(); int linesToSkip = Math.Max(numLines - maxMessages, 0); for (int i = 1; i <= linesToSkip; ++i) file.ReadLine(); } string line; while ((line = file.ReadLine()) != null) messages.Add(line); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Error reading log file: " + ex.Message, LoggingLevel.Normal, GetType()); } if (mostRecentFirst) messages.Reverse(); return messages; } } public void CopyTo(string path) { lock (_messageBuffer) { CommitMessageBuffer(); try { File.Copy(_path, path); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to copy log file to \"" + path + "\": " + ex.Message, LoggingLevel.Normal, GetType()); } } } public virtual void Clear() { lock (_messageBuffer) { try { File.Delete(_path); } catch (Exception) { } _messageBuffer.Clear(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using ILCompiler.DependencyAnalysis.X64; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { /// <summary> /// X64 specific portions of ReadyToRunHelperNode /// </summary> public partial class ReadyToRunHelperNode { protected override void EmitCode(NodeFactory factory, ref X64Emitter encoder, bool relocsOnly) { switch (Id) { case ReadyToRunHelperId.NewHelper: { TypeDesc target = (TypeDesc)Target; encoder.EmitLEAQ(encoder.TargetRegister.Arg0, factory.ConstructedTypeSymbol(target)); encoder.EmitJMP(factory.ExternSymbol(JitHelper.GetNewObjectHelperForType(target))); } break; case ReadyToRunHelperId.VirtualCall: { MethodDesc targetMethod = (MethodDesc)Target; if (targetMethod.OwningType.IsInterface) { encoder.EmitLEAQ(Register.R10, factory.InterfaceDispatchCell((MethodDesc)Target)); AddrMode jmpAddrMode = new AddrMode(Register.R10, null, 0, 0, AddrModeSize.Int64); encoder.EmitJmpToAddrMode(ref jmpAddrMode); } else { if (relocsOnly) break; AddrMode loadFromThisPtr = new AddrMode(encoder.TargetRegister.Arg0, null, 0, 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromThisPtr); int pointerSize = factory.Target.PointerSize; int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod); Debug.Assert(slot != -1); AddrMode jmpAddrMode = new AddrMode(encoder.TargetRegister.Result, null, EETypeNode.GetVTableOffset(pointerSize) + (slot * pointerSize), 0, AddrModeSize.Int64); encoder.EmitJmpToAddrMode(ref jmpAddrMode); } } break; case ReadyToRunHelperId.IsInstanceOf: { TypeDesc target = (TypeDesc)Target; encoder.EmitLEAQ(encoder.TargetRegister.Arg1, factory.NecessaryTypeSymbol(target)); encoder.EmitJMP(factory.ExternSymbol(JitHelper.GetCastingHelperNameForType(target, false))); } break; case ReadyToRunHelperId.CastClass: { TypeDesc target = (TypeDesc)Target; encoder.EmitLEAQ(encoder.TargetRegister.Arg1, factory.NecessaryTypeSymbol(target)); encoder.EmitJMP(factory.ExternSymbol(JitHelper.GetCastingHelperNameForType(target, true))); } break; case ReadyToRunHelperId.NewArr1: { TypeDesc target = (TypeDesc)Target; // TODO: Swap argument order instead encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Arg0); encoder.EmitLEAQ(encoder.TargetRegister.Arg0, factory.ConstructedTypeSymbol(target)); encoder.EmitJMP(factory.ExternSymbol(JitHelper.GetNewArrayHelperForType(target))); } break; case ReadyToRunHelperId.GetNonGCStaticBase: { MetadataType target = (MetadataType)Target; bool hasLazyStaticConstructor = factory.TypeSystemContext.HasLazyStaticConstructor(target); encoder.EmitLEAQ(encoder.TargetRegister.Result, factory.TypeNonGCStaticsSymbol(target)); if (!hasLazyStaticConstructor) { encoder.EmitRET(); } else { // We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region. encoder.EmitLEAQ(encoder.TargetRegister.Arg0, factory.TypeNonGCStaticsSymbol(target), -NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target)); AddrMode initialized = new AddrMode(encoder.TargetRegister.Arg0, null, factory.Target.PointerSize, 0, AddrModeSize.Int32); encoder.EmitCMP(ref initialized, 1); encoder.EmitRETIfEqual(); encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result); encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnNonGCStaticBase)); } } break; case ReadyToRunHelperId.GetThreadStaticBase: { MetadataType target = (MetadataType)Target; encoder.EmitLEAQ(encoder.TargetRegister.Arg2, factory.TypeThreadStaticIndex(target)); // First arg: address of the TypeManager slot that provides the helper with // information about module index and the type manager instance (which is used // for initialization on first access). AddrMode loadFromArg2 = new AddrMode(encoder.TargetRegister.Arg2, null, 0, 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Arg0, ref loadFromArg2); // Second arg: index of the type in the ThreadStatic section of the modules AddrMode loadFromArg2AndDelta = new AddrMode(encoder.TargetRegister.Arg2, null, factory.Target.PointerSize, 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Arg1, ref loadFromArg2AndDelta); if (!factory.TypeSystemContext.HasLazyStaticConstructor(target)) { encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.GetThreadStaticBaseForType)); } else { encoder.EmitLEAQ(encoder.TargetRegister.Arg2, factory.TypeNonGCStaticsSymbol(target), - NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target)); // TODO: performance optimization - inline the check verifying whether we need to trigger the cctor encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnThreadStaticBase)); } } break; case ReadyToRunHelperId.GetGCStaticBase: { MetadataType target = (MetadataType)Target; encoder.EmitLEAQ(encoder.TargetRegister.Result, factory.TypeGCStaticsSymbol(target)); AddrMode loadFromRax = new AddrMode(encoder.TargetRegister.Result, null, 0, 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromRax); encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromRax); if (!factory.TypeSystemContext.HasLazyStaticConstructor(target)) { encoder.EmitRET(); } else { // We need to trigger the cctor before returning the base. It is stored at the beginning of the non-GC statics region. encoder.EmitLEAQ(encoder.TargetRegister.Arg0, factory.TypeNonGCStaticsSymbol(target), -NonGCStaticsNode.GetClassConstructorContextStorageSize(factory.Target, target)); AddrMode initialized = new AddrMode(encoder.TargetRegister.Arg0, null, factory.Target.PointerSize, 0, AddrModeSize.Int32); encoder.EmitCMP(ref initialized, 1); encoder.EmitRETIfEqual(); encoder.EmitMOV(encoder.TargetRegister.Arg1, encoder.TargetRegister.Result); encoder.EmitJMP(factory.HelperEntrypoint(HelperEntrypoint.EnsureClassConstructorRunAndReturnGCStaticBase)); } } break; case ReadyToRunHelperId.DelegateCtor: { DelegateCreationInfo target = (DelegateCreationInfo)Target; if (target.TargetNeedsVTableLookup) { AddrMode loadFromThisPtr = new AddrMode(encoder.TargetRegister.Arg1, null, 0, 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Arg2, ref loadFromThisPtr); int slot = 0; if (!relocsOnly) slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, target.TargetMethod); Debug.Assert(slot != -1); AddrMode loadFromSlot = new AddrMode(encoder.TargetRegister.Arg2, null, EETypeNode.GetVTableOffset(factory.Target.PointerSize) + (slot * factory.Target.PointerSize), 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Arg2, ref loadFromSlot); } else { ISymbolNode targetMethodNode = target.GetTargetNode(factory); encoder.EmitLEAQ(encoder.TargetRegister.Arg2, target.GetTargetNode(factory)); } if (target.Thunk != null) { Debug.Assert(target.Constructor.Method.Signature.Length == 3); encoder.EmitLEAQ(encoder.TargetRegister.Arg3, target.Thunk); } else { Debug.Assert(target.Constructor.Method.Signature.Length == 2); } encoder.EmitJMP(target.Constructor); } break; case ReadyToRunHelperId.ResolveVirtualFunction: { MethodDesc targetMethod = (MethodDesc)Target; if (targetMethod.OwningType.IsInterface) { encoder.EmitLEAQ(encoder.TargetRegister.Arg1, factory.InterfaceDispatchCell(targetMethod)); encoder.EmitJMP(factory.ExternSymbol("RhpResolveInterfaceMethod")); } else { if (relocsOnly) break; AddrMode loadFromThisPtr = new AddrMode(encoder.TargetRegister.Arg0, null, 0, 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromThisPtr); int slot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, targetMethod); Debug.Assert(slot != -1); AddrMode loadFromSlot = new AddrMode(encoder.TargetRegister.Result, null, EETypeNode.GetVTableOffset(factory.Target.PointerSize) + (slot * factory.Target.PointerSize), 0, AddrModeSize.Int64); encoder.EmitMOV(encoder.TargetRegister.Result, ref loadFromSlot); encoder.EmitRET(); } } break; default: throw new NotImplementedException(); } } } }
// 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.Xml; using System.Xml.Linq; using Microsoft.Test.ModuleCore; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeBuilderTests : XLinqTestCase { public partial class XObjectBuilderTest : BridgeHelpers { //[Variation(Priority = 2, Desc = "LookupPrefix(null)")] public void var_1() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); string prefix = w.LookupPrefix(null); } catch (ArgumentNullException e) { CompareParamName(e.ParamName, "ns", "prefix mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); string prefix = w.LookupPrefix(null); } catch (ArgumentNullException ae) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); CompareParamName(ae.ParamName, "ns", "prefix mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteAttributes(null, true)", Param = true)] //[Variation(Priority = 2, Desc = "WriteAttributes(null, false)", Param = false)] public void var_2() { XDocument doc = new XDocument(); bool defattr = (bool)Variation.Param; using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteAttributes(null, defattr); } catch (ArgumentNullException e) { CompareParamName(e.ParamName, "reader", "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteAttributes(null, defattr); } catch (ArgumentNullException ae) { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); CompareParamName(ae.ParamName, "reader", "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteAttributeString(null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteAttributeString(String.Empty)", Param = "")] public void var_3() { XDocument doc = new XDocument(); string name = (string)Variation.Param; using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteAttributeString(name, null); } catch (ArgumentException e) { CompareParamName(e.ParamName, null, "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteAttributeString(name, null); } catch (ArgumentException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); CompareParamName(e.ParamName, null, "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteBase64(null)")] public void var_4() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteBase64(null, 0, 0); } catch (ArgumentNullException e) { CompareParamName(e.ParamName, "buffer", "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteBase64(null, 0, 0); } catch (ArgumentNullException ae) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); CompareParamName(ae.ParamName, "buffer", "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteBinHex(null)")] public void var_5() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { w.WriteStartDocument(); w.WriteStartElement("a"); try { TestLog.Compare(w.WriteState, WriteState.Element, "Error"); w.WriteBinHex(null, 0, 0); } catch (ArgumentNullException e) { CompareParamName(e.ParamName, "buffer", "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteBinHex(null, 0, 0); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteCData(null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteCData('')", Param = "")] public void var_6() { string param = (string)Variation.Param; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { w.WriteCData(param); } catch (InvalidOperationException) { try { w.WriteCData(param); } catch (InvalidOperationException) { return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteChars(null)")] public void var_7() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { w.WriteChars(null, 0, 0); } catch (ArgumentNullException) { try { w.WriteChars(null, 0, 0); } catch (ArgumentNullException) { return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "Other APIs")] public void var_8() { XDocument doc = new XDocument(); XmlWriter w = CreateWriter(doc); TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteComment(null); TestLog.Compare(w.Equals(null), false, "Error"); w.WriteComment(""); w.LookupPrefix(""); TestLog.Compare(w.Equals(""), false, "Error"); TestLog.Compare(w.WriteState, WriteState.Prolog, "Error"); w.Flush(); w.Dispose(); TestLog.Compare(w.WriteState, WriteState.Closed, "Error"); w.Flush(); w.Dispose(); TestLog.Compare(w.WriteState, WriteState.Closed, "Error"); } //[Variation(Priority = 2, Desc = "WriteDocType(null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteDocType('')", Param = "")] public void var_9() { string param = (string)Variation.Param; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { w.WriteDocType(param, param, param, param); } catch (ArgumentException) { try { w.WriteDocType(param, param, param, param); } catch (ArgumentException) { return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteElementString(null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteElementString(String.Empty)", Param = "")] public void var_10() { XDocument doc = new XDocument(); string name = (string)Variation.Param; using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteElementString(name, null, null, null); } catch (ArgumentException e) { CompareParamName(e.ParamName, null, "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteElementString(name, null, null, null); } catch (ArgumentException ae) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); CompareParamName(ae.ParamName, null, "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteEndAttribute()")] public void var_11() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteEndAttribute(); } catch (InvalidOperationException) { try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteEndAttribute(); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteEndDocument()")] public void var_12() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteEndDocument(); } catch (InvalidOperationException) { try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteEndDocument(); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteEndElement()")] public void var_13() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteEndElement(); } catch (InvalidOperationException) { try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteEndElement(); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteEntityRef(null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteEntityRef('')", Param = "")] public void var_14() { string param = (string)Variation.Param; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { w.WriteEntityRef(param); } catch (ArgumentException) { try { w.WriteEntityRef(param); } catch (ArgumentException) { return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteFullEndElement()")] public void var_15() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteFullEndElement(); } catch (InvalidOperationException) { try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteFullEndElement(); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteName(null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteName('')", Param = "")] public void var_16() { string param = (string)Variation.Param; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteName(param); } catch (ArgumentException e) { CompareParamName(e.ParamName, "name", "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteName(param); } catch (ArgumentException ae) { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); CompareParamName(ae.ParamName, "name", "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteNmToken(null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteNmToken('')", Param = "")] public void var_17() { string param = (string)Variation.Param; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteNmToken(param); } catch (ArgumentException e) { CompareParamName(e.ParamName, null, "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteNmToken(param); } catch (ArgumentException ae) { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); CompareParamName(ae.ParamName, null, "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteNode(null)", Params = new object[] { "reader", true })] //[Variation(Priority = 2, Desc = "WriteNode(null)", Params = new object[] { "reader", false })] //[Variation(Priority = 2, Desc = "WriteNode(null)", Params = new object[] { "navigator", true })] //[Variation(Priority = 2, Desc = "WriteNode(null)", Params = new object[] { "navigator", false })] public void var_18() { string param1 = (string)Variation.Params[0]; bool param2 = (bool)Variation.Params[1]; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); switch (param1) { case ("reader"): w.WriteNode((XmlReader)null, param2); break; } } catch (ArgumentNullException e) { switch (param1) { case ("reader"): CompareParamName(e.ParamName, "reader", "mismatch"); break; case ("navigator"): CompareParamName(e.ParamName, "navigator", "mismatch"); break; } try { switch (param1) { case ("reader"): w.WriteNode((XmlReader)null, param2); break; } } catch (ArgumentNullException) { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); switch (param1) { case ("reader"): CompareParamName(e.ParamName, "reader", "mismatch"); break; } return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteProcessingInstruction(null, null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteProcessingInstruction('', '')", Param = "")] public void var_19() { string param = (string)Variation.Param; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteProcessingInstruction(param, param); } catch (ArgumentException e) { CompareParamName(e.ParamName, null, "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteProcessingInstruction(param, param); } catch (ArgumentException ae) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); CompareParamName(ae.ParamName, null, "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteQualifiedName(null, null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteQualifiedName('', '')", Param = "")] public void var_20() { string param = (string)Variation.Param; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteQualifiedName(param, param); } catch (ArgumentException e) { CompareParamName(e.ParamName, null, "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteQualifiedName(param, param); } catch (ArgumentException ae) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); CompareParamName(ae.ParamName, null, "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteRaw(null, 0, 0)")] public void var_21() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteRaw(null, 0, 0); } catch (ArgumentNullException e) { CompareParamName(e.ParamName, "buffer", "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteRaw(null, 0, 0); } catch (ArgumentNullException ae) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); CompareParamName(ae.ParamName, "buffer", "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteStartAttribute(null, null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteStartAttribute('', '')", Param = "")] public void var_22() { XDocument doc = new XDocument(); string param = (string)Variation.Param; using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartAttribute(param, param); } catch (ArgumentException e) { CompareParamName(e.ParamName, null, "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteStartAttribute(param, param); } catch (ArgumentException ae) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); CompareParamName(ae.ParamName, null, "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteStartElement(null, null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteStartElement('', '')", Param = "")] public void var_23() { XDocument doc = new XDocument(); string param = (string)Variation.Param; using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartElement(param); } catch (ArgumentException e) { CompareParamName(e.ParamName, null, "mismatch"); try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteStartElement(param); } catch (ArgumentException ae) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); CompareParamName(ae.ParamName, null, "mismatch"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteStartDocument()", Param = 1)] //[Variation(Priority = 2, Desc = "WriteStartDocument(true)", Param = 2)] //[Variation(Priority = 2, Desc = "WriteStartDocument(false)", Param = 3)] public void var_24() { XDocument doc = new XDocument(); XmlWriter w = CreateWriter(doc); int param = (int)Variation.Param; switch (param) { case 1: w.WriteStartDocument(); break; case 2: w.WriteStartDocument(true); break; case 3: w.WriteStartDocument(false); break; default: throw new TestException(TestResult.Failed, ""); } TestLog.Compare(w.WriteState, WriteState.Prolog, "Error"); w.WriteStartElement("a"); TestLog.Compare(w.WriteState, WriteState.Element, "Error"); w.Dispose(); TestLog.Compare(w.WriteState, WriteState.Closed, "Error"); if (doc.ToString() != "<a />") throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteString(null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteString('')", Param = "")] public void var_25() { XDocument doc = new XDocument(); string param = (string)Variation.Param; using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteString(param); } catch (InvalidOperationException) { try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteString(param); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); if (param == null) throw; else return; } } } if (param == null) return; else throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteValue(true)", Param = true)] //[Variation(Priority = 2, Desc = "WriteValue(false)", Param = false)] public void var_26() { bool param = (bool)Variation.Param; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteValue(param); } catch (InvalidOperationException) { try { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); w.WriteValue(param); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); return; } } } throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "WriteWhitespace(null)", Param = null)] //[Variation(Priority = 2, Desc = "WriteWhitespace('')", Param = "")] public void var_27() { string param = (string)Variation.Param; XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { w.WriteWhitespace(param); TestLog.Compare(w.WriteState, WriteState.Prolog, "Error"); } } //[Variation(Priority = 2, Desc = "EntityRef after Document should error - PROLOG")] public void var_28() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartDocument(); w.WriteEntityRef("ent"); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteEntityRef("ent"); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "EntityRef after Document should error - EPILOG")] public void var_29() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartDocument(); TestLog.Compare(w.WriteState, WriteState.Prolog, "Error"); w.WriteStartElement("Root"); TestLog.Compare(w.WriteState, WriteState.Element, "Error"); w.WriteEndElement(); TestLog.Compare(w.WriteState, WriteState.Content, "Error"); w.WriteEntityRef("ent"); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteEntityRef("ent"); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "CharEntity after Document should error - PROLOG")] public void var_30() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartDocument(); w.WriteCharEntity('\uD23E'); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteCharEntity('\uD23E'); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "CharEntity after Document should error - EPILOG")] public void var_31() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartDocument(); w.WriteStartElement("Root"); w.WriteEndElement(); w.WriteCharEntity('\uD23E'); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteCharEntity('\uD23E'); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "SurrogateCharEntity after Document should error - PROLOG")] public void var_32() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartDocument(); w.WriteSurrogateCharEntity('\uDF41', '\uD920'); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteSurrogateCharEntity('\uDF41', '\uD920'); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "SurrogateCharEntity after Document should error - EPILOG")] public void var_33() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartDocument(); w.WriteStartElement("Root"); w.WriteEndElement(); w.WriteSurrogateCharEntity('\uDF41', '\uD920'); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteSurrogateCharEntity('\uDF41', '\uD920'); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "Attribute after Document should error - PROLOG")] public void var_34() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartDocument(); w.WriteStartAttribute("attr", ""); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteStartAttribute("attr", ""); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "Attribute after Document should error - EPILOG")] public void var_35() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { TestLog.Compare(w.WriteState, WriteState.Start, "Error"); w.WriteStartDocument(); w.WriteStartElement("Root"); w.WriteEndElement(); w.WriteStartAttribute("attr", ""); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteStartAttribute("attr", ""); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "CDATA after Document should error - PROLOG")] public void var_36() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { w.WriteStartDocument(); TestLog.Compare(w.WriteState, WriteState.Prolog, "Error"); w.WriteCData("Invalid"); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteCData("Invalid"); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); } //[Variation(Priority = 2, Desc = "CDATA after Document should error - EPILOG")] public void var_37() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { w.WriteStartDocument(); w.WriteStartElement("Root"); w.WriteEndElement(); TestLog.Compare(w.WriteState, WriteState.Content, "Error"); w.WriteCData("Invalid"); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteCData("Invalid"); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "Element followed by Document should error")] public void var_38() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { w.WriteStartElement("Root"); TestLog.Compare(w.WriteState, WriteState.Element, "Error"); w.WriteStartDocument(); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteStartDocument(); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Priority = 2, Desc = "Element followed by DocType should error")] public void var_39() { XDocument doc = new XDocument(); using (XmlWriter w = CreateWriter(doc)) { try { w.WriteStartElement("Root"); TestLog.Compare(w.WriteState, WriteState.Element, "Error"); w.WriteDocType("Test", null, null, ""); } catch (InvalidOperationException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); try { w.WriteDocType("Test", null, null, ""); } catch (InvalidOperationException) { return; } } } TestLog.WriteLine("Did not throw exception"); throw new TestException(TestResult.Failed, ""); } //[Variation(Desc = "WriteBase64")] public void Variation41() { int bufferSize = 4096; byte[] buffer = new byte[bufferSize]; int readByte = 1; XDocument d = new XDocument(); XmlWriter xw = d.CreateWriter(); TestLog.Compare(xw.WriteState, WriteState.Start, "Error"); xw.WriteStartDocument(true); TestLog.Compare(xw.WriteState, WriteState.Prolog, "Error"); xw.WriteStartElement("root"); TestLog.Compare(xw.WriteState, WriteState.Element, "Error"); try { xw.WriteBase64(buffer, 0, readByte); } catch (NotSupportedException) { TestLog.Compare(xw.WriteState, WriteState.Error, "Error"); return; } throw new TestException(TestResult.Failed, ""); } //[Variation(Desc = "WriteEntityRef")] public void Variation42() { XElement d = new XElement("a"); XmlWriter w = d.CreateWriter(); try { w.WriteEntityRef("ent"); } catch (NotSupportedException) { TestLog.Compare(w.WriteState, WriteState.Error, "Error"); return; } throw new TestException(TestResult.Failed, ""); } private void CompareParamName(string actual, string expected, string message) { if (PlatformDetection.IsNetNative) // ILC optimization sets ParamName always to null. return; TestLog.Compare(actual, expected, message); } } } } }
// // typemanager.cs: C# type manager // // Author: Miguel de Icaza (miguel@gnu.org) // Ravi Pratap (ravi@ximian.com) // Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) // Copyright 2003-2011 Novell, Inc. // Copyright 2011 Xamarin Inc // using System; using System.Globalization; using System.Collections.Generic; using System.Text; using System.IO; namespace Mono.CSharp { // // All compiler built-in types (they have to exist otherwise the compiler will not work) // public class BuiltinTypes { public readonly BuiltinTypeSpec Object; public readonly BuiltinTypeSpec ValueType; public readonly BuiltinTypeSpec Attribute; public readonly BuiltinTypeSpec Int; public readonly BuiltinTypeSpec UInt; public readonly BuiltinTypeSpec Long; public readonly BuiltinTypeSpec ULong; public readonly BuiltinTypeSpec Float; public readonly BuiltinTypeSpec Double; public readonly BuiltinTypeSpec Char; public readonly BuiltinTypeSpec Short; public readonly BuiltinTypeSpec Decimal; public readonly BuiltinTypeSpec Bool; public readonly BuiltinTypeSpec SByte; public readonly BuiltinTypeSpec Byte; public readonly BuiltinTypeSpec UShort; public readonly BuiltinTypeSpec String; public readonly BuiltinTypeSpec Enum; public readonly BuiltinTypeSpec Delegate; public readonly BuiltinTypeSpec MulticastDelegate; public readonly BuiltinTypeSpec Void; public readonly BuiltinTypeSpec Array; public readonly BuiltinTypeSpec Type; public readonly BuiltinTypeSpec IEnumerator; public readonly BuiltinTypeSpec IEnumerable; public readonly BuiltinTypeSpec IDisposable; public readonly BuiltinTypeSpec IntPtr; public readonly BuiltinTypeSpec UIntPtr; public readonly BuiltinTypeSpec RuntimeFieldHandle; public readonly BuiltinTypeSpec RuntimeTypeHandle; public readonly BuiltinTypeSpec Exception; // // These are internal buil-in types which depend on other // build-in type (mostly object) // public readonly BuiltinTypeSpec Dynamic; // Predefined operators tables public readonly Binary.PredefinedOperator[] OperatorsBinaryStandard; public readonly Binary.PredefinedOperator[] OperatorsBinaryEquality; public readonly Binary.PredefinedOperator[] OperatorsBinaryUnsafe; public readonly TypeSpec[][] OperatorsUnary; public readonly TypeSpec[] OperatorsUnaryMutator; public readonly TypeSpec[] BinaryPromotionsTypes; public readonly TypeSpec[] SwitchUserTypes; readonly BuiltinTypeSpec[] types; public BuiltinTypes () { Object = new BuiltinTypeSpec (MemberKind.Class, "System", "Object", BuiltinTypeSpec.Type.Object); ValueType = new BuiltinTypeSpec (MemberKind.Class, "System", "ValueType", BuiltinTypeSpec.Type.ValueType); Attribute = new BuiltinTypeSpec (MemberKind.Class, "System", "Attribute", BuiltinTypeSpec.Type.Attribute); Int = new BuiltinTypeSpec (MemberKind.Struct, "System", "Int32", BuiltinTypeSpec.Type.Int); Long = new BuiltinTypeSpec (MemberKind.Struct, "System", "Int64", BuiltinTypeSpec.Type.Long); UInt = new BuiltinTypeSpec (MemberKind.Struct, "System", "UInt32", BuiltinTypeSpec.Type.UInt); ULong = new BuiltinTypeSpec (MemberKind.Struct, "System", "UInt64", BuiltinTypeSpec.Type.ULong); Byte = new BuiltinTypeSpec (MemberKind.Struct, "System", "Byte", BuiltinTypeSpec.Type.Byte); SByte = new BuiltinTypeSpec (MemberKind.Struct, "System", "SByte", BuiltinTypeSpec.Type.SByte); Short = new BuiltinTypeSpec (MemberKind.Struct, "System", "Int16", BuiltinTypeSpec.Type.Short); UShort = new BuiltinTypeSpec (MemberKind.Struct, "System", "UInt16", BuiltinTypeSpec.Type.UShort); IEnumerator = new BuiltinTypeSpec (MemberKind.Interface, "System.Collections", "IEnumerator", BuiltinTypeSpec.Type.IEnumerator); IEnumerable = new BuiltinTypeSpec (MemberKind.Interface, "System.Collections", "IEnumerable", BuiltinTypeSpec.Type.IEnumerable); IDisposable = new BuiltinTypeSpec (MemberKind.Interface, "System", "IDisposable", BuiltinTypeSpec.Type.IDisposable); Char = new BuiltinTypeSpec (MemberKind.Struct, "System", "Char", BuiltinTypeSpec.Type.Char); String = new BuiltinTypeSpec (MemberKind.Class, "System", "String", BuiltinTypeSpec.Type.String); Float = new BuiltinTypeSpec (MemberKind.Struct, "System", "Single", BuiltinTypeSpec.Type.Float); Double = new BuiltinTypeSpec (MemberKind.Struct, "System", "Double", BuiltinTypeSpec.Type.Double); Decimal = new BuiltinTypeSpec (MemberKind.Struct, "System", "Decimal", BuiltinTypeSpec.Type.Decimal); Bool = new BuiltinTypeSpec (MemberKind.Struct, "System", "Boolean", BuiltinTypeSpec.Type.Bool); IntPtr = new BuiltinTypeSpec (MemberKind.Struct, "System", "IntPtr", BuiltinTypeSpec.Type.IntPtr); UIntPtr = new BuiltinTypeSpec (MemberKind.Struct, "System", "UIntPtr", BuiltinTypeSpec.Type.UIntPtr); MulticastDelegate = new BuiltinTypeSpec (MemberKind.Class, "System", "MulticastDelegate", BuiltinTypeSpec.Type.MulticastDelegate); Delegate = new BuiltinTypeSpec (MemberKind.Class, "System", "Delegate", BuiltinTypeSpec.Type.Delegate); Enum = new BuiltinTypeSpec (MemberKind.Class, "System", "Enum", BuiltinTypeSpec.Type.Enum); Array = new BuiltinTypeSpec (MemberKind.Class, "System", "Array", BuiltinTypeSpec.Type.Array); Void = new BuiltinTypeSpec (MemberKind.Void, "System", "Void", BuiltinTypeSpec.Type.Other); Type = new BuiltinTypeSpec (MemberKind.Class, "System", "Type", BuiltinTypeSpec.Type.Type); Exception = new BuiltinTypeSpec (MemberKind.Class, "System", "Exception", BuiltinTypeSpec.Type.Exception); RuntimeFieldHandle = new BuiltinTypeSpec (MemberKind.Struct, "System", "RuntimeFieldHandle", BuiltinTypeSpec.Type.Other); RuntimeTypeHandle = new BuiltinTypeSpec (MemberKind.Struct, "System", "RuntimeTypeHandle", BuiltinTypeSpec.Type.Other); // TODO: Maybe I should promote it to different kind for faster compares Dynamic = new BuiltinTypeSpec ("dynamic", BuiltinTypeSpec.Type.Dynamic); OperatorsBinaryStandard = Binary.CreateStandardOperatorsTable (this); OperatorsBinaryEquality = Binary.CreateEqualityOperatorsTable (this); OperatorsBinaryUnsafe = Binary.CreatePointerOperatorsTable (this); OperatorsUnary = Unary.CreatePredefinedOperatorsTable (this); OperatorsUnaryMutator = UnaryMutator.CreatePredefinedOperatorsTable (this); BinaryPromotionsTypes = ConstantFold.CreateBinaryPromotionsTypes (this); SwitchUserTypes = Switch.CreateSwitchUserTypes (this); types = new BuiltinTypeSpec[] { Object, ValueType, Attribute, Int, UInt, Long, ULong, Float, Double, Char, Short, Decimal, Bool, SByte, Byte, UShort, String, Enum, Delegate, MulticastDelegate, Void, Array, Type, IEnumerator, IEnumerable, IDisposable, IntPtr, UIntPtr, RuntimeFieldHandle, RuntimeTypeHandle, Exception }; } public BuiltinTypeSpec[] AllTypes { get { return types; } } public bool CheckDefinitions (ModuleContainer module) { var ctx = module.Compiler; foreach (var p in types) { var found = PredefinedType.Resolve (module, p.Kind, p.Namespace, p.Name, p.Arity, true, true); if (found == null || found == p) continue; var tc = found.MemberDefinition as TypeDefinition; if (tc != null) { var ns = module.GlobalRootNamespace.GetNamespace (p.Namespace, false); ns.SetBuiltinType (p); tc.SetPredefinedSpec (p); p.SetDefinition (found); } } if (ctx.Report.Errors != 0) return false; // Set internal build-in types Dynamic.SetDefinition (Object); return true; } } // // Compiler predefined types. Usually used for compiler generated // code or for comparison against well known framework type. They // may not exist as they are optional // class PredefinedTypes { public readonly PredefinedType ArgIterator; public readonly PredefinedType TypedReference; public readonly PredefinedType MarshalByRefObject; public readonly PredefinedType RuntimeHelpers; public readonly PredefinedType IAsyncResult; public readonly PredefinedType AsyncCallback; public readonly PredefinedType RuntimeArgumentHandle; public readonly PredefinedType CharSet; public readonly PredefinedType IsVolatile; public readonly PredefinedType IEnumeratorGeneric; public readonly PredefinedType IListGeneric; public readonly PredefinedType ICollectionGeneric; public readonly PredefinedType IEnumerableGeneric; public readonly PredefinedType Nullable; public readonly PredefinedType Activator; public readonly PredefinedType Interlocked; public readonly PredefinedType Monitor; public readonly PredefinedType NotSupportedException; public readonly PredefinedType RuntimeFieldHandle; public readonly PredefinedType RuntimeMethodHandle; public readonly PredefinedType SecurityAction; public readonly PredefinedType Dictionary; public readonly PredefinedType Hashtable; // // C# 3.0 // public readonly PredefinedType Expression; public readonly PredefinedType ExpressionGeneric; public readonly PredefinedType ParameterExpression; public readonly PredefinedType FieldInfo; public readonly PredefinedType MethodBase; public readonly PredefinedType MethodInfo; public readonly PredefinedType ConstructorInfo; public readonly PredefinedType MemberBinding; // // C# 4.0 // public readonly PredefinedType Binder; public readonly PredefinedType CallSite; public readonly PredefinedType CallSiteGeneric; public readonly PredefinedType BinderFlags; // // C# 5.0 // public readonly PredefinedType AsyncVoidMethodBuilder; public readonly PredefinedType AsyncTaskMethodBuilder; public readonly PredefinedType AsyncTaskMethodBuilderGeneric; public readonly PredefinedType Action; public readonly PredefinedType Task; public readonly PredefinedType TaskGeneric; public readonly PredefinedType IAsyncStateMachine; public readonly PredefinedType INotifyCompletion; public readonly PredefinedType ICriticalNotifyCompletion; public PredefinedTypes (ModuleContainer module) { TypedReference = new PredefinedType (module, MemberKind.Struct, "System", "TypedReference"); ArgIterator = new PredefinedType (module, MemberKind.Struct, "System", "ArgIterator"); MarshalByRefObject = new PredefinedType (module, MemberKind.Class, "System", "MarshalByRefObject"); RuntimeHelpers = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "RuntimeHelpers"); IAsyncResult = new PredefinedType (module, MemberKind.Interface, "System", "IAsyncResult"); AsyncCallback = new PredefinedType (module, MemberKind.Delegate, "System", "AsyncCallback"); RuntimeArgumentHandle = new PredefinedType (module, MemberKind.Struct, "System", "RuntimeArgumentHandle"); CharSet = new PredefinedType (module, MemberKind.Enum, "System.Runtime.InteropServices", "CharSet"); IsVolatile = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "IsVolatile"); IEnumeratorGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IEnumerator", 1); IListGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IList", 1); ICollectionGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "ICollection", 1); IEnumerableGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IEnumerable", 1); Nullable = new PredefinedType (module, MemberKind.Struct, "System", "Nullable", 1); Activator = new PredefinedType (module, MemberKind.Class, "System", "Activator"); Interlocked = new PredefinedType (module, MemberKind.Class, "System.Threading", "Interlocked"); Monitor = new PredefinedType (module, MemberKind.Class, "System.Threading", "Monitor"); NotSupportedException = new PredefinedType (module, MemberKind.Class, "System", "NotSupportedException"); RuntimeFieldHandle = new PredefinedType (module, MemberKind.Struct, "System", "RuntimeFieldHandle"); RuntimeMethodHandle = new PredefinedType (module, MemberKind.Struct, "System", "RuntimeMethodHandle"); SecurityAction = new PredefinedType (module, MemberKind.Enum, "System.Security.Permissions", "SecurityAction"); Dictionary = new PredefinedType (module, MemberKind.Class, "System.Collections.Generic", "Dictionary", 2); Hashtable = new PredefinedType (module, MemberKind.Class, "System.Collections", "Hashtable"); Expression = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "Expression"); ExpressionGeneric = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "Expression", 1); MemberBinding = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "MemberBinding"); ParameterExpression = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "ParameterExpression"); FieldInfo = new PredefinedType (module, MemberKind.Class, "System.Reflection", "FieldInfo"); MethodBase = new PredefinedType (module, MemberKind.Class, "System.Reflection", "MethodBase"); MethodInfo = new PredefinedType (module, MemberKind.Class, "System.Reflection", "MethodInfo"); ConstructorInfo = new PredefinedType (module, MemberKind.Class, "System.Reflection", "ConstructorInfo"); CallSite = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "CallSite"); CallSiteGeneric = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "CallSite", 1); Binder = new PredefinedType (module, MemberKind.Class, "Microsoft.CSharp.RuntimeBinder", "Binder"); BinderFlags = new PredefinedType (module, MemberKind.Enum, "Microsoft.CSharp.RuntimeBinder", "CSharpBinderFlags"); Action = new PredefinedType (module, MemberKind.Delegate, "System", "Action"); AsyncVoidMethodBuilder = new PredefinedType (module, MemberKind.Struct, "System.Runtime.CompilerServices", "AsyncVoidMethodBuilder"); AsyncTaskMethodBuilder = new PredefinedType (module, MemberKind.Struct, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder"); AsyncTaskMethodBuilderGeneric = new PredefinedType (module, MemberKind.Struct, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder", 1); Task = new PredefinedType (module, MemberKind.Class, "System.Threading.Tasks", "Task"); TaskGeneric = new PredefinedType (module, MemberKind.Class, "System.Threading.Tasks", "Task", 1); IAsyncStateMachine = new PredefinedType (module, MemberKind.Interface, "System.Runtime.CompilerServices", "IAsyncStateMachine"); INotifyCompletion = new PredefinedType (module, MemberKind.Interface, "System.Runtime.CompilerServices", "INotifyCompletion"); ICriticalNotifyCompletion = new PredefinedType (module, MemberKind.Interface, "System.Runtime.CompilerServices", "ICriticalNotifyCompletion"); // // Define types which are used for comparison. It does not matter // if they don't exist as no error report is needed // if (TypedReference.Define ()) TypedReference.TypeSpec.IsSpecialRuntimeType = true; if (ArgIterator.Define ()) ArgIterator.TypeSpec.IsSpecialRuntimeType = true; if (IEnumerableGeneric.Define ()) IEnumerableGeneric.TypeSpec.IsGenericIterateInterface = true; if (IListGeneric.Define ()) IListGeneric.TypeSpec.IsGenericIterateInterface = true; if (ICollectionGeneric.Define ()) ICollectionGeneric.TypeSpec.IsGenericIterateInterface = true; if (Nullable.Define ()) Nullable.TypeSpec.IsNullableType = true; if (ExpressionGeneric.Define ()) ExpressionGeneric.TypeSpec.IsExpressionTreeType = true; Task.Define (); if (TaskGeneric.Define ()) TaskGeneric.TypeSpec.IsGenericTask = true; } } class PredefinedMembers { public readonly PredefinedMember<MethodSpec> ActivatorCreateInstance; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderCreate; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderStart; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderSetResult; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderSetException; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderSetStateMachine; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderOnCompleted; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderOnCompletedUnsafe; public readonly PredefinedMember<PropertySpec> AsyncTaskMethodBuilderTask; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericCreate; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericStart; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericSetResult; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericSetException; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericSetStateMachine; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericOnCompleted; public readonly PredefinedMember<MethodSpec> AsyncTaskMethodBuilderGenericOnCompletedUnsafe; public readonly PredefinedMember<PropertySpec> AsyncTaskMethodBuilderGenericTask; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderCreate; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderStart; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderSetException; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderSetResult; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderSetStateMachine; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderOnCompleted; public readonly PredefinedMember<MethodSpec> AsyncVoidMethodBuilderOnCompletedUnsafe; public readonly PredefinedMember<MethodSpec> AsyncStateMachineAttributeCtor; public readonly PredefinedMember<MethodSpec> DebuggerBrowsableAttributeCtor; public readonly PredefinedMember<MethodSpec> DecimalCtor; public readonly PredefinedMember<MethodSpec> DecimalCtorInt; public readonly PredefinedMember<MethodSpec> DecimalCtorLong; public readonly PredefinedMember<MethodSpec> DecimalConstantAttributeCtor; public readonly PredefinedMember<MethodSpec> DefaultMemberAttributeCtor; public readonly PredefinedMember<MethodSpec> DelegateCombine; public readonly PredefinedMember<MethodSpec> DelegateEqual; public readonly PredefinedMember<MethodSpec> DelegateInequal; public readonly PredefinedMember<MethodSpec> DelegateRemove; public readonly PredefinedMember<MethodSpec> DynamicAttributeCtor; public readonly PredefinedMember<MethodSpec> FieldInfoGetFieldFromHandle; public readonly PredefinedMember<MethodSpec> FieldInfoGetFieldFromHandle2; public readonly PredefinedMember<MethodSpec> IDisposableDispose; public readonly PredefinedMember<MethodSpec> IEnumerableGetEnumerator; public readonly PredefinedMember<MethodSpec> InterlockedCompareExchange; public readonly PredefinedMember<MethodSpec> InterlockedCompareExchange_T; public readonly PredefinedMember<MethodSpec> IteratorStateMachineAttributeCtor; public readonly PredefinedMember<MethodSpec> FixedBufferAttributeCtor; public readonly PredefinedMember<MethodSpec> MethodInfoGetMethodFromHandle; public readonly PredefinedMember<MethodSpec> MethodInfoGetMethodFromHandle2; public readonly PredefinedMember<MethodSpec> MonitorEnter; public readonly PredefinedMember<MethodSpec> MonitorEnter_v4; public readonly PredefinedMember<MethodSpec> MonitorExit; public readonly PredefinedMember<PropertySpec> RuntimeCompatibilityWrapNonExceptionThrows; public readonly PredefinedMember<MethodSpec> RuntimeHelpersInitializeArray; public readonly PredefinedMember<PropertySpec> RuntimeHelpersOffsetToStringData; public readonly PredefinedMember<ConstSpec> SecurityActionRequestMinimum; public readonly PredefinedMember<FieldSpec> StringEmpty; public readonly PredefinedMember<MethodSpec> StringEqual; public readonly PredefinedMember<MethodSpec> StringInequal; public readonly PredefinedMember<MethodSpec> StructLayoutAttributeCtor; public readonly PredefinedMember<FieldSpec> StructLayoutCharSet; public readonly PredefinedMember<FieldSpec> StructLayoutSize; public readonly PredefinedMember<MethodSpec> TypeGetTypeFromHandle; public PredefinedMembers (ModuleContainer module) { var types = module.PredefinedTypes; var atypes = module.PredefinedAttributes; var btypes = module.Compiler.BuiltinTypes; var tp = new TypeParameter (0, new MemberName ("T"), null, null, Variance.None); ActivatorCreateInstance = new PredefinedMember<MethodSpec> (module, types.Activator, MemberFilter.Method ("CreateInstance", 1, ParametersCompiled.EmptyReadOnlyParameters, null)); AsyncTaskMethodBuilderCreate = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder, MemberFilter.Method ("Create", 0, ParametersCompiled.EmptyReadOnlyParameters, types.AsyncTaskMethodBuilder.TypeSpec)); AsyncTaskMethodBuilderSetResult = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder, MemberFilter.Method ("SetResult", 0, ParametersCompiled.EmptyReadOnlyParameters, btypes.Void)); AsyncTaskMethodBuilderSetStateMachine = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder, "SetStateMachine", MemberKind.Method, () => new[] { types.IAsyncStateMachine.TypeSpec }, btypes.Void); AsyncTaskMethodBuilderSetException = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder, MemberFilter.Method ("SetException", 0, ParametersCompiled.CreateFullyResolved (btypes.Exception), btypes.Void)); AsyncTaskMethodBuilderOnCompleted = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder, MemberFilter.Method ("AwaitOnCompleted", 2, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), new ParameterData (null, Parameter.Modifier.REF) }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null) }, false), btypes.Void)); AsyncTaskMethodBuilderOnCompletedUnsafe = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder, MemberFilter.Method ("AwaitUnsafeOnCompleted", 2, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), new ParameterData (null, Parameter.Modifier.REF) }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null) }, false), btypes.Void)); AsyncTaskMethodBuilderStart = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilder, MemberFilter.Method ("Start", 1, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), }, false), btypes.Void)); AsyncTaskMethodBuilderTask = new PredefinedMember<PropertySpec> (module, types.AsyncTaskMethodBuilder, MemberFilter.Property ("Task", null)); AsyncTaskMethodBuilderGenericCreate = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric, MemberFilter.Method ("Create", 0, ParametersCompiled.EmptyReadOnlyParameters, types.AsyncVoidMethodBuilder.TypeSpec)); AsyncTaskMethodBuilderGenericSetResult = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric, "SetResult", MemberKind.Method, () => new TypeSpec[] { types.AsyncTaskMethodBuilderGeneric.TypeSpec.MemberDefinition.TypeParameters[0] }, btypes.Void); AsyncTaskMethodBuilderGenericSetStateMachine = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric, "SetStateMachine", MemberKind.Method, () => new[] { types.IAsyncStateMachine.TypeSpec }, btypes.Void); AsyncTaskMethodBuilderGenericSetException = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric, MemberFilter.Method ("SetException", 0, ParametersCompiled.CreateFullyResolved (btypes.Exception), btypes.Void)); AsyncTaskMethodBuilderGenericOnCompleted = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric, MemberFilter.Method ("AwaitOnCompleted", 2, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), new ParameterData (null, Parameter.Modifier.REF) }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null) }, false), btypes.Void)); AsyncTaskMethodBuilderGenericOnCompletedUnsafe = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric, MemberFilter.Method ("AwaitUnsafeOnCompleted", 2, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), new ParameterData (null, Parameter.Modifier.REF) }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null) }, false), btypes.Void)); AsyncTaskMethodBuilderGenericStart = new PredefinedMember<MethodSpec> (module, types.AsyncTaskMethodBuilderGeneric, MemberFilter.Method ("Start", 1, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), }, false), btypes.Void)); AsyncTaskMethodBuilderGenericTask = new PredefinedMember<PropertySpec> (module, types.AsyncTaskMethodBuilderGeneric, MemberFilter.Property ("Task", null)); AsyncVoidMethodBuilderCreate = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder, MemberFilter.Method ("Create", 0, ParametersCompiled.EmptyReadOnlyParameters, types.AsyncVoidMethodBuilder.TypeSpec)); AsyncVoidMethodBuilderSetException = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder, MemberFilter.Method ("SetException", 0, null, btypes.Void)); AsyncVoidMethodBuilderSetResult = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder, MemberFilter.Method ("SetResult", 0, ParametersCompiled.EmptyReadOnlyParameters, btypes.Void)); AsyncVoidMethodBuilderSetStateMachine = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder, "SetStateMachine", MemberKind.Method, () => new[] { types.IAsyncStateMachine.TypeSpec }, btypes.Void); AsyncVoidMethodBuilderOnCompleted = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder, MemberFilter.Method ("AwaitOnCompleted", 2, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), new ParameterData (null, Parameter.Modifier.REF) }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null) }, false), btypes.Void)); AsyncVoidMethodBuilderOnCompletedUnsafe = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder, MemberFilter.Method ("AwaitUnsafeOnCompleted", 2, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), new ParameterData (null, Parameter.Modifier.REF) }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), new TypeParameterSpec (1, tp, SpecialConstraint.None, Variance.None, null) }, false), btypes.Void)); AsyncVoidMethodBuilderStart = new PredefinedMember<MethodSpec> (module, types.AsyncVoidMethodBuilder, MemberFilter.Method ("Start", 1, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), }, false), btypes.Void)); AsyncStateMachineAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.AsyncStateMachine, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved ( btypes.Type))); DebuggerBrowsableAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.DebuggerBrowsable, MemberFilter.Constructor (null)); DecimalCtor = new PredefinedMember<MethodSpec> (module, btypes.Decimal, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved ( btypes.Int, btypes.Int, btypes.Int, btypes.Bool, btypes.Byte))); DecimalCtorInt = new PredefinedMember<MethodSpec> (module, btypes.Decimal, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.Int))); DecimalCtorLong = new PredefinedMember<MethodSpec> (module, btypes.Decimal, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.Long))); DecimalConstantAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.DecimalConstant, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved ( btypes.Byte, btypes.Byte, btypes.UInt, btypes.UInt, btypes.UInt))); DefaultMemberAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.DefaultMember, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.String))); DelegateCombine = new PredefinedMember<MethodSpec> (module, btypes.Delegate, "Combine", btypes.Delegate, btypes.Delegate); DelegateRemove = new PredefinedMember<MethodSpec> (module, btypes.Delegate, "Remove", btypes.Delegate, btypes.Delegate); DelegateEqual = new PredefinedMember<MethodSpec> (module, btypes.Delegate, new MemberFilter (Operator.GetMetadataName (Operator.OpType.Equality), 0, MemberKind.Operator, null, btypes.Bool)); DelegateInequal = new PredefinedMember<MethodSpec> (module, btypes.Delegate, new MemberFilter (Operator.GetMetadataName (Operator.OpType.Inequality), 0, MemberKind.Operator, null, btypes.Bool)); DynamicAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.Dynamic, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved ( ArrayContainer.MakeType (module, btypes.Bool)))); FieldInfoGetFieldFromHandle = new PredefinedMember<MethodSpec> (module, types.FieldInfo, "GetFieldFromHandle", MemberKind.Method, types.RuntimeFieldHandle); FieldInfoGetFieldFromHandle2 = new PredefinedMember<MethodSpec> (module, types.FieldInfo, "GetFieldFromHandle", MemberKind.Method, types.RuntimeFieldHandle, new PredefinedType (btypes.RuntimeTypeHandle)); FixedBufferAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.FixedBuffer, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.Type, btypes.Int))); IDisposableDispose = new PredefinedMember<MethodSpec> (module, btypes.IDisposable, "Dispose", TypeSpec.EmptyTypes); IEnumerableGetEnumerator = new PredefinedMember<MethodSpec> (module, btypes.IEnumerable, "GetEnumerator", TypeSpec.EmptyTypes); InterlockedCompareExchange = new PredefinedMember<MethodSpec> (module, types.Interlocked, MemberFilter.Method ("CompareExchange", 0, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), new ParameterData (null, Parameter.Modifier.NONE), new ParameterData (null, Parameter.Modifier.NONE) }, new[] { btypes.Int, btypes.Int, btypes.Int }, false), btypes.Int)); InterlockedCompareExchange_T = new PredefinedMember<MethodSpec> (module, types.Interlocked, MemberFilter.Method ("CompareExchange", 1, new ParametersImported ( new[] { new ParameterData (null, Parameter.Modifier.REF), new ParameterData (null, Parameter.Modifier.NONE), new ParameterData (null, Parameter.Modifier.NONE) }, new[] { new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), new TypeParameterSpec (0, tp, SpecialConstraint.None, Variance.None, null), }, false), null)); IteratorStateMachineAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.IteratorStateMachine, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved ( btypes.Type))); MethodInfoGetMethodFromHandle = new PredefinedMember<MethodSpec> (module, types.MethodBase, "GetMethodFromHandle", MemberKind.Method, types.RuntimeMethodHandle); MethodInfoGetMethodFromHandle2 = new PredefinedMember<MethodSpec> (module, types.MethodBase, "GetMethodFromHandle", MemberKind.Method, types.RuntimeMethodHandle, new PredefinedType (btypes.RuntimeTypeHandle)); MonitorEnter = new PredefinedMember<MethodSpec> (module, types.Monitor, "Enter", btypes.Object); MonitorEnter_v4 = new PredefinedMember<MethodSpec> (module, types.Monitor, MemberFilter.Method ("Enter", 0, new ParametersImported (new[] { new ParameterData (null, Parameter.Modifier.NONE), new ParameterData (null, Parameter.Modifier.REF) }, new[] { btypes.Object, btypes.Bool }, false), null)); MonitorExit = new PredefinedMember<MethodSpec> (module, types.Monitor, "Exit", btypes.Object); RuntimeCompatibilityWrapNonExceptionThrows = new PredefinedMember<PropertySpec> (module, atypes.RuntimeCompatibility, MemberFilter.Property ("WrapNonExceptionThrows", btypes.Bool)); RuntimeHelpersInitializeArray = new PredefinedMember<MethodSpec> (module, types.RuntimeHelpers, "InitializeArray", btypes.Array, btypes.RuntimeFieldHandle); RuntimeHelpersOffsetToStringData = new PredefinedMember<PropertySpec> (module, types.RuntimeHelpers, MemberFilter.Property ("OffsetToStringData", btypes.Int)); SecurityActionRequestMinimum = new PredefinedMember<ConstSpec> (module, types.SecurityAction, "RequestMinimum", MemberKind.Field, types.SecurityAction); StringEmpty = new PredefinedMember<FieldSpec> (module, btypes.String, MemberFilter.Field ("Empty", btypes.String)); StringEqual = new PredefinedMember<MethodSpec> (module, btypes.String, new MemberFilter (Operator.GetMetadataName (Operator.OpType.Equality), 0, MemberKind.Operator, null, btypes.Bool)); StringInequal = new PredefinedMember<MethodSpec> (module, btypes.String, new MemberFilter (Operator.GetMetadataName (Operator.OpType.Inequality), 0, MemberKind.Operator, null, btypes.Bool)); StructLayoutAttributeCtor = new PredefinedMember<MethodSpec> (module, atypes.StructLayout, MemberFilter.Constructor (ParametersCompiled.CreateFullyResolved (btypes.Short))); StructLayoutCharSet = new PredefinedMember<FieldSpec> (module, atypes.StructLayout, "CharSet", MemberKind.Field, types.CharSet); StructLayoutSize = new PredefinedMember<FieldSpec> (module, atypes.StructLayout, MemberFilter.Field ("Size", btypes.Int)); TypeGetTypeFromHandle = new PredefinedMember<MethodSpec> (module, btypes.Type, "GetTypeFromHandle", btypes.RuntimeTypeHandle); } } public class PredefinedType { readonly string name; readonly string ns; readonly int arity; readonly MemberKind kind; protected readonly ModuleContainer module; protected TypeSpec type; public PredefinedType (ModuleContainer module, MemberKind kind, string ns, string name, int arity) : this (module, kind, ns, name) { this.arity = arity; } public PredefinedType (ModuleContainer module, MemberKind kind, string ns, string name) { this.module = module; this.kind = kind; this.name = name; this.ns = ns; } public PredefinedType (BuiltinTypeSpec type) { this.kind = type.Kind; this.name = type.Name; this.ns = type.Namespace; this.type = type; } #region Properties public int Arity { get { return arity; } } public bool IsDefined { get { return type != null; } } public string Name { get { return name; } } public string Namespace { get { return ns; } } public TypeSpec TypeSpec { get { return type; } } #endregion public bool Define () { if (type != null) return true; type = Resolve (module, kind, ns, name, arity, false, false); return type != null; } public string GetSignatureForError () { return ns + "." + name; } public static TypeSpec Resolve (ModuleContainer module, MemberKind kind, string ns, string name, int arity, bool required, bool reportErrors) { // // Cannot call it with true because it could create non-existent namespaces for // predefined types. It's set to true only for build-in types which all must // exist therefore it does not matter, for predefined types we don't want to create // fake namespaces when type is optional and does not exist (e.g. System.Linq). // Namespace type_ns = module.GlobalRootNamespace.GetNamespace (ns, required); IList<TypeSpec> found = null; if (type_ns != null) found = type_ns.GetAllTypes (name); if (found == null) { if (reportErrors ) module.Compiler.Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported", ns, name); return null; } TypeSpec best_match = null; foreach (var candidate in found) { if (candidate.Kind != kind) { if (candidate.Kind == MemberKind.Struct && kind == MemberKind.Void && candidate.MemberDefinition is TypeContainer) { // Void is declared as struct but we keep it internally as // special kind, the swap will be done by caller } else { continue; } } if (candidate.Arity != arity) continue; if ((candidate.Modifiers & Modifiers.INTERNAL) != 0 && !candidate.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly)) continue; if (best_match == null) { best_match = candidate; continue; } var other_match = best_match; if (!best_match.MemberDefinition.IsImported && module.Compiler.BuiltinTypes.Object.MemberDefinition.DeclaringAssembly == candidate.MemberDefinition.DeclaringAssembly) { best_match = candidate; } string location; if (best_match.MemberDefinition is MemberCore) { location = ((MemberCore) best_match.MemberDefinition).Location.Name; } else { var assembly = (ImportedAssemblyDefinition) best_match.MemberDefinition.DeclaringAssembly; location = Path.GetFileName (assembly.Location); } module.Compiler.Report.SymbolRelatedToPreviousError (other_match); module.Compiler.Report.SymbolRelatedToPreviousError (candidate); module.Compiler.Report.Warning (1685, 1, "The predefined type `{0}.{1}' is defined multiple times. Using definition from `{2}'", ns, name, location); break; } if (best_match == null && reportErrors) { Location loc; if (found[0].MemberDefinition is MemberCore) { loc = ((MemberCore) found[0].MemberDefinition).Location; } else { loc = Location.Null; module.Compiler.Report.SymbolRelatedToPreviousError (found[0]); } module.Compiler.Report.Error (520, loc, "The predefined type `{0}.{1}' is not declared correctly", ns, name); } return best_match; } public TypeSpec Resolve () { if (type == null) type = Resolve (module, kind, ns, name, arity, false, true); return type; } } public class PredefinedMember<T> where T : MemberSpec { readonly ModuleContainer module; T member; TypeSpec declaring_type; readonly PredefinedType declaring_type_predefined; MemberFilter filter; readonly Func<TypeSpec[]> filter_builder; public PredefinedMember (ModuleContainer module, PredefinedType type, MemberFilter filter) { this.module = module; this.declaring_type_predefined = type; this.filter = filter; } public PredefinedMember (ModuleContainer module, TypeSpec type, MemberFilter filter) { this.module = module; this.declaring_type = type; this.filter = filter; } public PredefinedMember (ModuleContainer module, PredefinedType type, string name, params TypeSpec[] types) : this (module, type, MemberFilter.Method (name, 0, ParametersCompiled.CreateFullyResolved (types), null)) { } public PredefinedMember (ModuleContainer module, PredefinedType type, string name, MemberKind kind, params PredefinedType[] types) : this (module, type, new MemberFilter (name, 0, kind, null, null)) { filter_builder = () => { var ptypes = new TypeSpec[types.Length]; for (int i = 0; i < ptypes.Length; ++i) { var p = types[i]; if (!p.Define ()) return null; ptypes[i] = p.TypeSpec; } return ptypes; }; } public PredefinedMember (ModuleContainer module, PredefinedType type, string name, MemberKind kind, Func<TypeSpec[]> typesBuilder, TypeSpec returnType) : this (module, type, new MemberFilter (name, 0, kind, null, returnType)) { filter_builder = typesBuilder; } public PredefinedMember (ModuleContainer module, BuiltinTypeSpec type, string name, params TypeSpec[] types) : this (module, type, MemberFilter.Method (name, 0, ParametersCompiled.CreateFullyResolved (types), null)) { } public T Get () { if (member != null) return member; if (declaring_type == null) { if (!declaring_type_predefined.Define ()) return null; declaring_type = declaring_type_predefined.TypeSpec; } if (filter_builder != null) { var types = filter_builder (); if (filter.Kind == MemberKind.Field) filter = new MemberFilter (filter.Name, filter.Arity, filter.Kind, null, types [0]); else filter = new MemberFilter (filter.Name, filter.Arity, filter.Kind, ParametersCompiled.CreateFullyResolved (types), filter.MemberType); } member = MemberCache.FindMember (declaring_type, filter, BindingRestriction.DeclaredOnly) as T; if (member == null) return null; if (!member.IsAccessible (module)) return null; return member; } public T Resolve (Location loc) { if (member != null) return member; if (Get () != null) return member; if (declaring_type == null) { if (declaring_type_predefined.Resolve () == null) return null; } if (filter_builder != null) { filter = new MemberFilter (filter.Name, filter.Arity, filter.Kind, ParametersCompiled.CreateFullyResolved (filter_builder ()), filter.MemberType); } string method_args = null; if (filter.Parameters != null) method_args = filter.Parameters.GetSignatureForError (); module.Compiler.Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible", declaring_type.GetSignatureForError (), filter.Name, method_args); return null; } } partial class TypeManager { /// <summary> /// Returns the C# name of a type if possible, or the full type name otherwise /// </summary> static public string CSharpName (TypeSpec t) { return t.GetSignatureForError (); } static public string CSharpName (IList<TypeSpec> types) { if (types.Count == 0) return string.Empty; StringBuilder sb = new StringBuilder (); for (int i = 0; i < types.Count; ++i) { if (i > 0) sb.Append (","); sb.Append (CSharpName (types [i])); } return sb.ToString (); } static public string GetFullNameSignature (MemberSpec mi) { return mi.GetSignatureForError (); } static public string CSharpSignature (MemberSpec mb) { return mb.GetSignatureForError (); } public static bool IsFamilyAccessible (TypeSpec type, TypeSpec parent) { // TypeParameter tparam = LookupTypeParameter (type); // TypeParameter pparam = LookupTypeParameter (parent); if (type.Kind == MemberKind.TypeParameter && parent.Kind == MemberKind.TypeParameter) { // (tparam != null) && (pparam != null)) { if (type == parent) return true; throw new NotImplementedException ("net"); // return tparam.IsSubclassOf (parent); } do { if (IsInstantiationOfSameGenericType (type, parent)) return true; type = type.BaseType; } while (type != null); return false; } // // Checks whether `type' is a nested child of `parent'. // public static bool IsNestedChildOf (TypeSpec type, ITypeDefinition parent) { if (type == null) return false; if (type.MemberDefinition == parent) return false; type = type.DeclaringType; while (type != null) { if (type.MemberDefinition == parent) return true; type = type.DeclaringType; } return false; } public static TypeSpec GetElementType (TypeSpec t) { return ((ElementTypeSpec)t).Element; } /// <summary> /// This method is not implemented by MS runtime for dynamic types /// </summary> public static bool HasElementType (TypeSpec t) { return t is ElementTypeSpec; } /// <summary> /// Utility function that can be used to probe whether a type /// is managed or not. /// </summary> public static bool VerifyUnmanaged (ModuleContainer rc, TypeSpec t, Location loc) { if (t.IsUnmanaged) return true; while (t.IsPointer) t = ((ElementTypeSpec) t).Element; rc.Compiler.Report.SymbolRelatedToPreviousError (t); rc.Compiler.Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'", CSharpName (t)); return false; } #region Generics // This method always return false for non-generic compiler, // while Type.IsGenericParameter is returned if it is supported. public static bool IsGenericParameter (TypeSpec type) { return type.IsGenericParameter; } public static bool IsGenericType (TypeSpec type) { return type.IsGeneric; } public static TypeSpec[] GetTypeArguments (TypeSpec t) { // TODO: return empty array !! return t.TypeArguments; } /// <summary> /// Check whether `type' and `parent' are both instantiations of the same /// generic type. Note that we do not check the type parameters here. /// </summary> public static bool IsInstantiationOfSameGenericType (TypeSpec type, TypeSpec parent) { return type == parent || type.MemberDefinition == parent.MemberDefinition; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type int with 4 columns and 2 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct imat4x2 : IReadOnlyList<int>, IEquatable<imat4x2> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public int m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public int m01; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public int m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public int m11; /// <summary> /// Column 2, Rows 0 /// </summary> [DataMember] public int m20; /// <summary> /// Column 2, Rows 1 /// </summary> [DataMember] public int m21; /// <summary> /// Column 3, Rows 0 /// </summary> [DataMember] public int m30; /// <summary> /// Column 3, Rows 1 /// </summary> [DataMember] public int m31; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public imat4x2(int m00, int m01, int m10, int m11, int m20, int m21, int m30, int m31) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; this.m20 = m20; this.m21 = m21; this.m30 = m30; this.m31 = m31; } /// <summary> /// Constructs this matrix from a imat2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(imat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0; this.m21 = 0; this.m30 = 0; this.m31 = 0; } /// <summary> /// Constructs this matrix from a imat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(imat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0; this.m31 = 0; } /// <summary> /// Constructs this matrix from a imat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(imat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a imat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(imat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0; this.m21 = 0; this.m30 = 0; this.m31 = 0; } /// <summary> /// Constructs this matrix from a imat3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(imat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0; this.m31 = 0; } /// <summary> /// Constructs this matrix from a imat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(imat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a imat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(imat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = 0; this.m21 = 0; this.m30 = 0; this.m31 = 0; } /// <summary> /// Constructs this matrix from a imat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(imat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = 0; this.m31 = 0; } /// <summary> /// Constructs this matrix from a imat4. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(imat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; this.m20 = m.m20; this.m21 = m.m21; this.m30 = m.m30; this.m31 = m.m31; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(ivec2 c0, ivec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = 0; this.m21 = 0; this.m30 = 0; this.m31 = 0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(ivec2 c0, ivec2 c1, ivec2 c2) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = c2.x; this.m21 = c2.y; this.m30 = 0; this.m31 = 0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public imat4x2(ivec2 c0, ivec2 c1, ivec2 c2, ivec2 c3) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; this.m20 = c2.x; this.m21 = c2.y; this.m30 = c3.x; this.m31 = c3.y; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public int[,] Values => new[,] { { m00, m01 }, { m10, m11 }, { m20, m21 }, { m30, m31 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public int[] Values1D => new[] { m00, m01, m10, m11, m20, m21, m30, m31 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public ivec2 Column0 { get { return new ivec2(m00, m01); } set { m00 = value.x; m01 = value.y; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public ivec2 Column1 { get { return new ivec2(m10, m11); } set { m10 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public ivec2 Column2 { get { return new ivec2(m20, m21); } set { m20 = value.x; m21 = value.y; } } /// <summary> /// Gets or sets the column nr 3 /// </summary> public ivec2 Column3 { get { return new ivec2(m30, m31); } set { m30 = value.x; m31 = value.y; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public ivec4 Row0 { get { return new ivec4(m00, m10, m20, m30); } set { m00 = value.x; m10 = value.y; m20 = value.z; m30 = value.w; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public ivec4 Row1 { get { return new ivec4(m01, m11, m21, m31); } set { m01 = value.x; m11 = value.y; m21 = value.z; m31 = value.w; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static imat4x2 Zero { get; } = new imat4x2(0, 0, 0, 0, 0, 0, 0, 0); /// <summary> /// Predefined all-ones matrix /// </summary> public static imat4x2 Ones { get; } = new imat4x2(1, 1, 1, 1, 1, 1, 1, 1); /// <summary> /// Predefined identity matrix /// </summary> public static imat4x2 Identity { get; } = new imat4x2(1, 0, 0, 1, 0, 0, 0, 0); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static imat4x2 AllMaxValue { get; } = new imat4x2(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static imat4x2 DiagonalMaxValue { get; } = new imat4x2(int.MaxValue, 0, 0, int.MaxValue, 0, 0, 0, 0); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static imat4x2 AllMinValue { get; } = new imat4x2(int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue, int.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static imat4x2 DiagonalMinValue { get; } = new imat4x2(int.MinValue, 0, 0, int.MinValue, 0, 0, 0, 0); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<int> GetEnumerator() { yield return m00; yield return m01; yield return m10; yield return m11; yield return m20; yield return m21; yield return m30; yield return m31; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (4 x 2 = 8). /// </summary> public int Count => 8; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public int this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m10; case 3: return m11; case 4: return m20; case 5: return m21; case 6: return m30; case 7: return m31; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m10 = value; break; case 3: this.m11 = value; break; case 4: this.m20 = value; break; case 5: this.m21 = value; break; case 6: this.m30 = value; break; case 7: this.m31 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public int this[int col, int row] { get { return this[col * 2 + row]; } set { this[col * 2 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(imat4x2 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m20.Equals(rhs.m20) && m21.Equals(rhs.m21)) && (m30.Equals(rhs.m30) && m31.Equals(rhs.m31)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is imat4x2 && Equals((imat4x2) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(imat4x2 lhs, imat4x2 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(imat4x2 lhs, imat4x2 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode()) * 397) ^ m30.GetHashCode()) * 397) ^ m31.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public imat2x4 Transposed => new imat2x4(m00, m10, m20, m30, m01, m11, m21, m31); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public int MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m10), m11), m20), m21), m30), m31); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public int MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m10), m11), m20), m21), m30), m31); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public float LengthSqr => (((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31))); /// <summary> /// Returns the sum of all fields. /// </summary> public int Sum => (((m00 + m01) + (m10 + m11)) + ((m20 + m21) + (m30 + m31))); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public float Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m10) + Math.Abs(m11))) + ((Math.Abs(m20) + Math.Abs(m21)) + (Math.Abs(m30) + Math.Abs(m31)))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + (m10*m10 + m11*m11)) + ((m20*m20 + m21*m21) + (m30*m30 + m31*m31)))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public int NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m20)), Math.Abs(m21)), Math.Abs(m30)), Math.Abs(m31)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))) + ((Math.Pow((double)Math.Abs(m20), p) + Math.Pow((double)Math.Abs(m21), p)) + (Math.Pow((double)Math.Abs(m30), p) + Math.Pow((double)Math.Abs(m31), p)))), 1 / p); /// <summary> /// Executes a matrix-matrix-multiplication imat4x2 * imat2x4 -> imat2. /// </summary> public static imat2 operator*(imat4x2 lhs, imat2x4 rhs) => new imat2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13))); /// <summary> /// Executes a matrix-matrix-multiplication imat4x2 * imat3x4 -> imat3x2. /// </summary> public static imat3x2 operator*(imat4x2 lhs, imat3x4 rhs) => new imat3x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13)), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + (lhs.m20 * rhs.m22 + lhs.m30 * rhs.m23)), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + (lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23))); /// <summary> /// Executes a matrix-matrix-multiplication imat4x2 * imat4 -> imat4x2. /// </summary> public static imat4x2 operator*(imat4x2 lhs, imat4 rhs) => new imat4x2(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + (lhs.m20 * rhs.m02 + lhs.m30 * rhs.m03)), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + (lhs.m21 * rhs.m02 + lhs.m31 * rhs.m03)), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + (lhs.m20 * rhs.m12 + lhs.m30 * rhs.m13)), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + (lhs.m21 * rhs.m12 + lhs.m31 * rhs.m13)), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + (lhs.m20 * rhs.m22 + lhs.m30 * rhs.m23)), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + (lhs.m21 * rhs.m22 + lhs.m31 * rhs.m23)), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + (lhs.m20 * rhs.m32 + lhs.m30 * rhs.m33)), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + (lhs.m21 * rhs.m32 + lhs.m31 * rhs.m33))); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static ivec2 operator*(imat4x2 m, ivec4 v) => new ivec2(((m.m00 * v.x + m.m10 * v.y) + (m.m20 * v.z + m.m30 * v.w)), ((m.m01 * v.x + m.m11 * v.y) + (m.m21 * v.z + m.m31 * v.w))); /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static imat4x2 CompMul(imat4x2 A, imat4x2 B) => new imat4x2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11, A.m20 * B.m20, A.m21 * B.m21, A.m30 * B.m30, A.m31 * B.m31); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static imat4x2 CompDiv(imat4x2 A, imat4x2 B) => new imat4x2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11, A.m20 / B.m20, A.m21 / B.m21, A.m30 / B.m30, A.m31 / B.m31); /// <summary> /// Executes a component-wise + (add). /// </summary> public static imat4x2 CompAdd(imat4x2 A, imat4x2 B) => new imat4x2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11, A.m20 + B.m20, A.m21 + B.m21, A.m30 + B.m30, A.m31 + B.m31); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static imat4x2 CompSub(imat4x2 A, imat4x2 B) => new imat4x2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11, A.m20 - B.m20, A.m21 - B.m21, A.m30 - B.m30, A.m31 - B.m31); /// <summary> /// Executes a component-wise + (add). /// </summary> public static imat4x2 operator+(imat4x2 lhs, imat4x2 rhs) => new imat4x2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21, lhs.m30 + rhs.m30, lhs.m31 + rhs.m31); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static imat4x2 operator+(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m20 + rhs, lhs.m21 + rhs, lhs.m30 + rhs, lhs.m31 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static imat4x2 operator+(int lhs, imat4x2 rhs) => new imat4x2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m20, lhs + rhs.m21, lhs + rhs.m30, lhs + rhs.m31); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static imat4x2 operator-(imat4x2 lhs, imat4x2 rhs) => new imat4x2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21, lhs.m30 - rhs.m30, lhs.m31 - rhs.m31); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static imat4x2 operator-(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m20 - rhs, lhs.m21 - rhs, lhs.m30 - rhs, lhs.m31 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static imat4x2 operator-(int lhs, imat4x2 rhs) => new imat4x2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m20, lhs - rhs.m21, lhs - rhs.m30, lhs - rhs.m31); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static imat4x2 operator/(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m20 / rhs, lhs.m21 / rhs, lhs.m30 / rhs, lhs.m31 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static imat4x2 operator/(int lhs, imat4x2 rhs) => new imat4x2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m20, lhs / rhs.m21, lhs / rhs.m30, lhs / rhs.m31); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static imat4x2 operator*(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m20 * rhs, lhs.m21 * rhs, lhs.m30 * rhs, lhs.m31 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static imat4x2 operator*(int lhs, imat4x2 rhs) => new imat4x2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m20, lhs * rhs.m21, lhs * rhs.m30, lhs * rhs.m31); /// <summary> /// Executes a component-wise % (modulo). /// </summary> public static imat4x2 operator%(imat4x2 lhs, imat4x2 rhs) => new imat4x2(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11, lhs.m20 % rhs.m20, lhs.m21 % rhs.m21, lhs.m30 % rhs.m30, lhs.m31 % rhs.m31); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static imat4x2 operator%(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m10 % rhs, lhs.m11 % rhs, lhs.m20 % rhs, lhs.m21 % rhs, lhs.m30 % rhs, lhs.m31 % rhs); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static imat4x2 operator%(int lhs, imat4x2 rhs) => new imat4x2(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m10, lhs % rhs.m11, lhs % rhs.m20, lhs % rhs.m21, lhs % rhs.m30, lhs % rhs.m31); /// <summary> /// Executes a component-wise ^ (xor). /// </summary> public static imat4x2 operator^(imat4x2 lhs, imat4x2 rhs) => new imat4x2(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11, lhs.m20 ^ rhs.m20, lhs.m21 ^ rhs.m21, lhs.m30 ^ rhs.m30, lhs.m31 ^ rhs.m31); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static imat4x2 operator^(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs, lhs.m20 ^ rhs, lhs.m21 ^ rhs, lhs.m30 ^ rhs, lhs.m31 ^ rhs); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static imat4x2 operator^(int lhs, imat4x2 rhs) => new imat4x2(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m10, lhs ^ rhs.m11, lhs ^ rhs.m20, lhs ^ rhs.m21, lhs ^ rhs.m30, lhs ^ rhs.m31); /// <summary> /// Executes a component-wise | (bitwise-or). /// </summary> public static imat4x2 operator|(imat4x2 lhs, imat4x2 rhs) => new imat4x2(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11, lhs.m20 | rhs.m20, lhs.m21 | rhs.m21, lhs.m30 | rhs.m30, lhs.m31 | rhs.m31); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static imat4x2 operator|(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m10 | rhs, lhs.m11 | rhs, lhs.m20 | rhs, lhs.m21 | rhs, lhs.m30 | rhs, lhs.m31 | rhs); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static imat4x2 operator|(int lhs, imat4x2 rhs) => new imat4x2(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m10, lhs | rhs.m11, lhs | rhs.m20, lhs | rhs.m21, lhs | rhs.m30, lhs | rhs.m31); /// <summary> /// Executes a component-wise &amp; (bitwise-and). /// </summary> public static imat4x2 operator&(imat4x2 lhs, imat4x2 rhs) => new imat4x2(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11, lhs.m20 & rhs.m20, lhs.m21 & rhs.m21, lhs.m30 & rhs.m30, lhs.m31 & rhs.m31); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static imat4x2 operator&(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m10 & rhs, lhs.m11 & rhs, lhs.m20 & rhs, lhs.m21 & rhs, lhs.m30 & rhs, lhs.m31 & rhs); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static imat4x2 operator&(int lhs, imat4x2 rhs) => new imat4x2(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m10, lhs & rhs.m11, lhs & rhs.m20, lhs & rhs.m21, lhs & rhs.m30, lhs & rhs.m31); /// <summary> /// Executes a component-wise left-shift with a scalar. /// </summary> public static imat4x2 operator<<(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m10 << rhs, lhs.m11 << rhs, lhs.m20 << rhs, lhs.m21 << rhs, lhs.m30 << rhs, lhs.m31 << rhs); /// <summary> /// Executes a component-wise right-shift with a scalar. /// </summary> public static imat4x2 operator>>(imat4x2 lhs, int rhs) => new imat4x2(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs, lhs.m20 >> rhs, lhs.m21 >> rhs, lhs.m30 >> rhs, lhs.m31 >> rhs); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat4x2 operator<(imat4x2 lhs, imat4x2 rhs) => new bmat4x2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21, lhs.m30 < rhs.m30, lhs.m31 < rhs.m31); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat4x2 operator<(imat4x2 lhs, int rhs) => new bmat4x2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m20 < rhs, lhs.m21 < rhs, lhs.m30 < rhs, lhs.m31 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat4x2 operator<(int lhs, imat4x2 rhs) => new bmat4x2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m20, lhs < rhs.m21, lhs < rhs.m30, lhs < rhs.m31); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat4x2 operator<=(imat4x2 lhs, imat4x2 rhs) => new bmat4x2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21, lhs.m30 <= rhs.m30, lhs.m31 <= rhs.m31); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator<=(imat4x2 lhs, int rhs) => new bmat4x2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs, lhs.m30 <= rhs, lhs.m31 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator<=(int lhs, imat4x2 rhs) => new bmat4x2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m20, lhs <= rhs.m21, lhs <= rhs.m30, lhs <= rhs.m31); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat4x2 operator>(imat4x2 lhs, imat4x2 rhs) => new bmat4x2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21, lhs.m30 > rhs.m30, lhs.m31 > rhs.m31); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat4x2 operator>(imat4x2 lhs, int rhs) => new bmat4x2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m20 > rhs, lhs.m21 > rhs, lhs.m30 > rhs, lhs.m31 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat4x2 operator>(int lhs, imat4x2 rhs) => new bmat4x2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m20, lhs > rhs.m21, lhs > rhs.m30, lhs > rhs.m31); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat4x2 operator>=(imat4x2 lhs, imat4x2 rhs) => new bmat4x2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21, lhs.m30 >= rhs.m30, lhs.m31 >= rhs.m31); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator>=(imat4x2 lhs, int rhs) => new bmat4x2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs, lhs.m30 >= rhs, lhs.m31 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat4x2 operator>=(int lhs, imat4x2 rhs) => new bmat4x2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m20, lhs >= rhs.m21, lhs >= rhs.m30, lhs >= rhs.m31); } }
/* ==================================================================== */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; namespace Oranikle.ReportDesigner { /// <summary> /// Summary description for ReportCtl. /// </summary> internal class ListCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty { private List<XmlNode> _ReportItems; private DesignXmlDraw _Draw; bool fDataSet, fPBBefore, fPBAfter, fNoRows, fDataInstanceElementOutput, fDataInstanceName; private System.Windows.Forms.Label label2; private Oranikle.Studio.Controls.StyledComboBox cbDataSet; private System.Windows.Forms.GroupBox groupBox1; private Oranikle.Studio.Controls.StyledCheckBox chkPBBefore; private Oranikle.Studio.Controls.StyledCheckBox chkPBAfter; private Oranikle.Studio.Controls.StyledButton bGroups; private System.Windows.Forms.Label label1; private Oranikle.Studio.Controls.CustomTextControl tbNoRows; private Oranikle.Studio.Controls.CustomTextControl tbDataInstanceName; private Oranikle.Studio.Controls.StyledCheckBox chkXmlInstances; private System.Windows.Forms.Label label3; private System.Windows.Forms.GroupBox groupBox2; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal ListCtl(DesignXmlDraw dxDraw, List<XmlNode> ris) { _ReportItems = ris; _Draw = dxDraw; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { XmlNode riNode = _ReportItems[0]; tbNoRows.Text = _Draw.GetElementValue(riNode, "NoRows", ""); cbDataSet.Items.AddRange(_Draw.DataSetNames); cbDataSet.Text = _Draw.GetDataSetNameValue(riNode); if (_Draw.GetReportItemDataRegionContainer(riNode) != null) cbDataSet.Enabled = false; chkPBBefore.Checked = _Draw.GetElementValue(riNode, "PageBreakAtStart", "false").ToLower()=="true"? true:false; chkPBAfter.Checked = _Draw.GetElementValue(riNode, "PageBreakAtEnd", "false").ToLower()=="true"? true:false; this.chkXmlInstances.Checked = _Draw.GetElementValue(riNode, "DataInstanceElementOutput", "Output")=="Output"?true:false; this.tbDataInstanceName.Text = _Draw.GetElementValue(riNode, "DataInstanceName", "Item"); fNoRows = fDataSet = fPBBefore = fPBAfter = fDataInstanceElementOutput = fDataInstanceName = false; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label2 = new System.Windows.Forms.Label(); this.cbDataSet = new Oranikle.Studio.Controls.StyledComboBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.chkPBAfter = new Oranikle.Studio.Controls.StyledCheckBox(); this.chkPBBefore = new Oranikle.Studio.Controls.StyledCheckBox(); this.bGroups = new Oranikle.Studio.Controls.StyledButton(); this.label1 = new System.Windows.Forms.Label(); this.tbNoRows = new Oranikle.Studio.Controls.CustomTextControl(); this.tbDataInstanceName = new Oranikle.Studio.Controls.CustomTextControl(); this.chkXmlInstances = new Oranikle.Studio.Controls.StyledCheckBox(); this.label3 = new System.Windows.Forms.Label(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // label2 // this.label2.Location = new System.Drawing.Point(24, 16); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(80, 23); this.label2.TabIndex = 0; this.label2.Text = "DataSet Name"; // // cbDataSet // this.cbDataSet.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDataSet.Location = new System.Drawing.Point(120, 16); this.cbDataSet.Name = "cbDataSet"; this.cbDataSet.Size = new System.Drawing.Size(304, 21); this.cbDataSet.TabIndex = 1; this.cbDataSet.SelectedIndexChanged += new System.EventHandler(this.cbDataSet_SelectedIndexChanged); // // groupBox1 // this.groupBox1.Controls.Add(this.chkPBAfter); this.groupBox1.Controls.Add(this.chkPBBefore); this.groupBox1.Location = new System.Drawing.Point(24, 88); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(400, 48); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = "Page Breaks"; // // chkPBAfter // this.chkPBAfter.Location = new System.Drawing.Point(192, 16); this.chkPBAfter.Name = "chkPBAfter"; this.chkPBAfter.Size = new System.Drawing.Size(128, 24); this.chkPBAfter.TabIndex = 1; this.chkPBAfter.Text = "Insert after List"; this.chkPBAfter.CheckedChanged += new System.EventHandler(this.chkPBAfter_CheckedChanged); // // chkPBBefore // this.chkPBBefore.Location = new System.Drawing.Point(16, 16); this.chkPBBefore.Name = "chkPBBefore"; this.chkPBBefore.Size = new System.Drawing.Size(128, 24); this.chkPBBefore.TabIndex = 0; this.chkPBBefore.Text = "Insert before List"; this.chkPBBefore.CheckedChanged += new System.EventHandler(this.chkPBBefore_CheckedChanged); // // bGroups // this.bGroups.Location = new System.Drawing.Point(24, 240); this.bGroups.Name = "bGroups"; this.bGroups.Size = new System.Drawing.Size(120, 23); this.bGroups.TabIndex = 6; this.bGroups.Text = "Group Expressions..."; this.bGroups.Click += new System.EventHandler(this.bGroups_Click); // // label1 // this.label1.Location = new System.Drawing.Point(24, 48); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(96, 23); this.label1.TabIndex = 2; this.label1.Text = "No rows message"; // // tbNoRows // this.tbNoRows.Location = new System.Drawing.Point(120, 48); this.tbNoRows.Name = "tbNoRows"; this.tbNoRows.Size = new System.Drawing.Size(304, 20); this.tbNoRows.TabIndex = 3; this.tbNoRows.Text = "textBox1"; this.tbNoRows.TextChanged += new System.EventHandler(this.tbNoRows_TextChanged); // // tbDataInstanceName // this.tbDataInstanceName.Location = new System.Drawing.Point(146, 44); this.tbDataInstanceName.Name = "tbDataInstanceName"; this.tbDataInstanceName.Size = new System.Drawing.Size(238, 20); this.tbDataInstanceName.TabIndex = 2; this.tbDataInstanceName.Text = "textBox1"; this.tbDataInstanceName.TextChanged += new System.EventHandler(this.tbDataInstanceName_TextChanged); // // chkXmlInstances // this.chkXmlInstances.Location = new System.Drawing.Point(16, 16); this.chkXmlInstances.Name = "chkXmlInstances"; this.chkXmlInstances.Size = new System.Drawing.Size(160, 24); this.chkXmlInstances.TabIndex = 0; this.chkXmlInstances.Text = "Render list instances"; this.chkXmlInstances.CheckedChanged += new System.EventHandler(this.chkXmlInstances_CheckedChanged); // // label3 // this.label3.Location = new System.Drawing.Point(16, 48); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(112, 16); this.label3.TabIndex = 1; this.label3.Text = "Data Instance Name"; // // groupBox2 // this.groupBox2.Controls.Add(this.tbDataInstanceName); this.groupBox2.Controls.Add(this.chkXmlInstances); this.groupBox2.Controls.Add(this.label3); this.groupBox2.Location = new System.Drawing.Point(24, 152); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(400, 72); this.groupBox2.TabIndex = 5; this.groupBox2.TabStop = false; this.groupBox2.Text = "XML"; // // ListCtl // this.Controls.Add(this.groupBox2); this.Controls.Add(this.tbNoRows); this.Controls.Add(this.label1); this.Controls.Add(this.bGroups); this.Controls.Add(this.groupBox1); this.Controls.Add(this.cbDataSet); this.Controls.Add(this.label2); this.Name = "ListCtl"; this.Size = new System.Drawing.Size(472, 288); this.groupBox1.ResumeLayout(false); this.groupBox2.ResumeLayout(false); this.ResumeLayout(false); } #endregion public bool IsValid() { return true; } public void Apply() { // take information in control and apply to all the style nodes // Only change information that has been marked as modified; // this way when group is selected it is possible to change just // the items you want and keep the rest the same. foreach (XmlNode riNode in this._ReportItems) ApplyChanges(riNode); // No more changes fNoRows = fDataSet = fPBBefore = fPBAfter= fDataInstanceElementOutput = fDataInstanceName = false; } public void ApplyChanges(XmlNode node) { if (fNoRows) _Draw.SetElement(node, "NoRows", this.tbNoRows.Text); if (fDataSet) _Draw.SetElement(node, "DataSetName", this.cbDataSet.Text); if (fPBBefore) _Draw.SetElement(node, "PageBreakAtStart", this.chkPBBefore.Checked? "true":"false"); if (fPBAfter) _Draw.SetElement(node, "PageBreakAtEnd", this.chkPBAfter.Checked? "true":"false"); if (fDataInstanceElementOutput) _Draw.SetElement(node, "DataInstanceElementOutput", this.chkXmlInstances.Checked? "Output":"NoOutput"); if (fDataInstanceName) { if (this.tbDataInstanceName.Text.Length > 0) _Draw.SetElement(node, "DataInstanceName", this.tbDataInstanceName.Text); else _Draw.RemoveElement(node, "DataInstanceName"); } } private void cbDataSet_SelectedIndexChanged(object sender, System.EventArgs e) { fDataSet = true; } private void chkPBBefore_CheckedChanged(object sender, System.EventArgs e) { fPBBefore = true; } private void chkPBAfter_CheckedChanged(object sender, System.EventArgs e) { fPBAfter = true; } private void tbNoRows_TextChanged(object sender, System.EventArgs e) { fNoRows = true; } private void bGroups_Click(object sender, System.EventArgs e) { PropertyDialog pd = new PropertyDialog(_Draw, _ReportItems, PropertyTypeEnum.Grouping); try { DialogResult dr = pd.ShowDialog(); if (pd.Changed || dr == DialogResult.OK) { //_DrawPanel.Invalidate(); TODO need to force change somehow????? } } finally { pd.Dispose(); } } private void chkXmlInstances_CheckedChanged(object sender, System.EventArgs e) { fDataInstanceElementOutput = true; } private void tbDataInstanceName_TextChanged(object sender, System.EventArgs e) { fDataInstanceName = true; } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Abp.Dapper.Extensions; using Abp.Dapper.Filters.Action; using Abp.Dapper.Filters.Query; using Abp.Data; using Abp.Domain.Entities; using Abp.Domain.Uow; using Abp.Events.Bus.Entities; using Dapper; using DapperExtensions; namespace Abp.Dapper.Repositories { public class DapperRepositoryBase<TEntity, TPrimaryKey> : AbpDapperRepositoryBase<TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey> { private readonly IActiveTransactionProvider _activeTransactionProvider; public DapperRepositoryBase(IActiveTransactionProvider activeTransactionProvider) { _activeTransactionProvider = activeTransactionProvider; EntityChangeEventHelper = NullEntityChangeEventHelper.Instance; DapperQueryFilterExecuter = NullDapperQueryFilterExecuter.Instance; DapperActionFilterExecuter = NullDapperActionFilterExecuter.Instance; } public IDapperQueryFilterExecuter DapperQueryFilterExecuter { get; set; } public IEntityChangeEventHelper EntityChangeEventHelper { get; set; } public IDapperActionFilterExecuter DapperActionFilterExecuter { get; set; } public virtual DbConnection Connection { get { return (DbConnection)_activeTransactionProvider.GetActiveConnection(ActiveTransactionProviderArgs.Empty); } } /// <summary> /// Gets the active transaction. If Dapper is active then <see cref="IUnitOfWork" /> should be started before /// and there must be an active transaction. /// </summary> /// <value> /// The active transaction. /// </value> public virtual DbTransaction ActiveTransaction { get { return (DbTransaction)_activeTransactionProvider.GetActiveTransaction(ActiveTransactionProviderArgs.Empty); } } public virtual int? Timeout => null; public override TEntity Single(TPrimaryKey id) { return Single(CreateEqualityExpressionForId(id)); } public override TEntity Single(Expression<Func<TEntity, bool>> predicate) { IPredicate pg = DapperQueryFilterExecuter.ExecuteFilter<TEntity, TPrimaryKey>(predicate); return Connection.GetList<TEntity>(pg, transaction: ActiveTransaction, commandTimeout: Timeout).Single(); } public override TEntity FirstOrDefault(TPrimaryKey id) { return FirstOrDefault(CreateEqualityExpressionForId(id)); } public override TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate) { IPredicate pg = DapperQueryFilterExecuter.ExecuteFilter<TEntity, TPrimaryKey>(predicate); return Connection.GetList<TEntity>(pg, transaction: ActiveTransaction, commandTimeout: Timeout).FirstOrDefault(); } public override TEntity Get(TPrimaryKey id) { TEntity item = FirstOrDefault(id); if (item == null) { throw new EntityNotFoundException(typeof(TEntity), id); } return item; } public override IEnumerable<TEntity> GetAll() { PredicateGroup predicateGroup = DapperQueryFilterExecuter.ExecuteFilter<TEntity, TPrimaryKey>(); return Connection.GetList<TEntity>(predicateGroup, transaction: ActiveTransaction, commandTimeout: Timeout); } public override IEnumerable<TEntity> Query(string query, object parameters = null) { return Connection.Query<TEntity>(query, parameters, ActiveTransaction, commandTimeout: Timeout); } public override Task<IEnumerable<TEntity>> QueryAsync(string query, object parameters = null) { return Connection.QueryAsync<TEntity>(query, parameters, ActiveTransaction, Timeout); } public override IEnumerable<TAny> Query<TAny>(string query, object parameters = null) { return Connection.Query<TAny>(query, parameters, ActiveTransaction, commandTimeout: Timeout); } public override Task<IEnumerable<TAny>> QueryAsync<TAny>(string query, object parameters = null) { return Connection.QueryAsync<TAny>(query, parameters, ActiveTransaction, Timeout); } public override int Execute(string query, object parameters = null) { return Connection.Execute(query, parameters, ActiveTransaction, Timeout); } public override Task<int> ExecuteAsync(string query, object parameters = null) { return Connection.ExecuteAsync(query, parameters, ActiveTransaction, Timeout); } public override IEnumerable<TEntity> GetAllPaged(Expression<Func<TEntity, bool>> predicate, int pageNumber, int itemsPerPage, string sortingProperty, bool ascending = true) { IPredicate filteredPredicate = DapperQueryFilterExecuter.ExecuteFilter<TEntity, TPrimaryKey>(predicate); return Connection.GetPage<TEntity>( filteredPredicate, new List<ISort> { new Sort { Ascending = ascending, PropertyName = sortingProperty } }, pageNumber, itemsPerPage, ActiveTransaction, Timeout); } public override int Count(Expression<Func<TEntity, bool>> predicate) { IPredicate filteredPredicate = DapperQueryFilterExecuter.ExecuteFilter<TEntity, TPrimaryKey>(predicate); return Connection.Count<TEntity>(filteredPredicate, ActiveTransaction, Timeout); } public override IEnumerable<TEntity> GetSet(Expression<Func<TEntity, bool>> predicate, int firstResult, int maxResults, string sortingProperty, bool ascending = true) { IPredicate filteredPredicate = DapperQueryFilterExecuter.ExecuteFilter<TEntity, TPrimaryKey>(predicate); return Connection.GetSet<TEntity>( filteredPredicate, new List<ISort> { new Sort { Ascending = ascending, PropertyName = sortingProperty } }, firstResult, maxResults, ActiveTransaction, Timeout ); } public override IEnumerable<TEntity> GetAll(Expression<Func<TEntity, bool>> predicate) { IPredicate filteredPredicate = DapperQueryFilterExecuter.ExecuteFilter<TEntity, TPrimaryKey>(predicate); return Connection.GetList<TEntity>(filteredPredicate, transaction: ActiveTransaction, commandTimeout: Timeout); } public override IEnumerable<TEntity> GetAllPaged(Expression<Func<TEntity, bool>> predicate, int pageNumber, int itemsPerPage, bool ascending = true, params Expression<Func<TEntity, object>>[] sortingExpression) { IPredicate filteredPredicate = DapperQueryFilterExecuter.ExecuteFilter<TEntity, TPrimaryKey>(predicate); return Connection.GetPage<TEntity>(filteredPredicate, sortingExpression.ToSortable(ascending), pageNumber, itemsPerPage, ActiveTransaction, Timeout); } public override IEnumerable<TEntity> GetSet(Expression<Func<TEntity, bool>> predicate, int firstResult, int maxResults, bool ascending = true, params Expression<Func<TEntity, object>>[] sortingExpression) { IPredicate filteredPredicate = DapperQueryFilterExecuter.ExecuteFilter<TEntity, TPrimaryKey>(predicate); return Connection.GetSet<TEntity>(filteredPredicate, sortingExpression.ToSortable(ascending), firstResult, maxResults, ActiveTransaction, Timeout); } public override void Insert(TEntity entity) { InsertAndGetId(entity); } public override void Update(TEntity entity) { EntityChangeEventHelper.TriggerEntityUpdatingEvent(entity); DapperActionFilterExecuter.ExecuteModificationAuditFilter<TEntity, TPrimaryKey>(entity); Connection.Update(entity, ActiveTransaction, Timeout); EntityChangeEventHelper.TriggerEntityUpdatedEventOnUowCompleted(entity); } public override void Delete(TEntity entity) { EntityChangeEventHelper.TriggerEntityDeletingEvent(entity); if (entity is ISoftDelete) { DapperActionFilterExecuter.ExecuteDeletionAuditFilter<TEntity, TPrimaryKey>(entity); Connection.Update(entity, ActiveTransaction, Timeout); } else { Connection.Delete(entity, ActiveTransaction, Timeout); } EntityChangeEventHelper.TriggerEntityDeletedEventOnUowCompleted(entity); } public override void Delete(Expression<Func<TEntity, bool>> predicate) { IEnumerable<TEntity> items = GetAll(predicate); foreach (TEntity entity in items) { Delete(entity); } } public override TPrimaryKey InsertAndGetId(TEntity entity) { EntityChangeEventHelper.TriggerEntityCreatingEvent(entity); DapperActionFilterExecuter.ExecuteCreationAuditFilter<TEntity, TPrimaryKey>(entity); TPrimaryKey primaryKey = Connection.Insert(entity, ActiveTransaction, Timeout); EntityChangeEventHelper.TriggerEntityCreatedEventOnUowCompleted(entity); return primaryKey; } } }
using KSP.UI.Screens; using UnityEngine; namespace KERBALISM { public sealed class Launcher { // click through locks private bool clickThroughLocked = false; private const ControlTypes MainGUILockTypes = ControlTypes.MANNODE_ADDEDIT | ControlTypes.MANNODE_DELETE | ControlTypes.MAP_UI | ControlTypes.TARGETING | ControlTypes.VESSEL_SWITCHING | ControlTypes.TWEAKABLES | ControlTypes.EDITOR_UI | ControlTypes.EDITOR_SOFT_LOCK | ControlTypes.UI; public Launcher() { // initialize Planner.Planner.Initialize(); monitor = new Monitor(); tooltip = new Tooltip(); GameEvents.onGUIApplicationLauncherReady.Add(Create); } public void Create() { // do nothing if button already created if (!ui_initialized) { ui_initialized = true; // create the button // note: for some weird reasons, the callbacks can be called BEFORE this function return vesselListLauncher = ApplicationLauncher.Instance.AddApplication(null, null, null, null, null, null, Textures.applauncher_vessels); // enable the launcher button for some scenes vesselListLauncher.VisibleInScenes = ApplicationLauncher.AppScenes.SPACECENTER | ApplicationLauncher.AppScenes.FLIGHT | ApplicationLauncher.AppScenes.MAPVIEW | ApplicationLauncher.AppScenes.TRACKSTATION | ApplicationLauncher.AppScenes.VAB | ApplicationLauncher.AppScenes.SPH; } if (Features.Science) { if (generalMenuLauncher == null) { generalMenuLauncher = ApplicationLauncher.Instance.AddApplication(null, null, null, null, null, null, Textures.applauncher_database); generalMenuLauncher.VisibleInScenes = ApplicationLauncher.AppScenes.SPACECENTER | ApplicationLauncher.AppScenes.FLIGHT | ApplicationLauncher.AppScenes.MAPVIEW | ApplicationLauncher.AppScenes.TRACKSTATION | ApplicationLauncher.AppScenes.VAB | ApplicationLauncher.AppScenes.SPH; generalMenuLauncher.onLeftClick = () => ScienceArchiveWindow.Toggle(); } } else { if (generalMenuLauncher != null) { generalMenuLauncher.onLeftClick = null; ApplicationLauncher.Instance.RemoveApplication(generalMenuLauncher); generalMenuLauncher = null; } } } public void Update() { // do nothing if GUI has not been initialized if (!ui_initialized) return; // do nothing if the UI is not shown if (win_rect.width == 0f) return; // update planner/monitor content if (Lib.IsEditor()) { Planner.Planner.Update(); } else { monitor.Update(); } } // called every frame public void On_gui() { // do nothing if GUI has not been initialized if (!ui_initialized) return; // render the window if (vesselListLauncher.toggleButton.Value || vesselListLauncher.IsHovering || (win_rect.width > 0f && win_rect.Contains(Mouse.screenPos))) { // hard-coded offsets // note: there is a bug in stock that only set appscale properly in non-flight-mode after you go in flight-mode at least once float at_top_offset_x = 40.0f * GameSettings.UI_SCALE * GameSettings.UI_SCALE_APPS; float at_top_offset_y = 0.0f * GameSettings.UI_SCALE * GameSettings.UI_SCALE_APPS; float at_bottom_offset_x = 0.0f * GameSettings.UI_SCALE * GameSettings.UI_SCALE_APPS; float at_bottom_offset_y = 40.0f * GameSettings.UI_SCALE * GameSettings.UI_SCALE_APPS; float at_bottom_editor_offset_x = 66.0f * GameSettings.UI_SCALE * GameSettings.UI_SCALE_APPS; // get screen size float screen_width = Screen.width; float screen_height = Screen.height; // determine app launcher position; bool is_at_top = ApplicationLauncher.Instance.IsPositionedAtTop; // get window size float width = Lib.IsEditor() ? Planner.Planner.Width() : monitor.Width(); float height = Lib.IsEditor() ? Planner.Planner.Height() : monitor.Height(); // calculate window position float left = screen_width - width; float top = is_at_top ? 0.0f : screen_height - height; if (is_at_top) { left -= at_top_offset_x; top += at_top_offset_y; } else { left -= !Lib.IsEditor() ? at_bottom_offset_x : at_bottom_editor_offset_x; top -= at_bottom_offset_y; } // store window geometry win_rect = new Rect(left, top, width, height); // begin window area GUILayout.BeginArea(win_rect, Styles.win); // a bit of spacing between title and content GUILayout.Space(Styles.ScaleFloat(10.0f)); // draw planner in the editors, monitor everywhere else if (!Lib.IsEditor()) monitor.Render(); else Planner.Planner.Render(); // end window area GUILayout.EndArea(); // draw tooltip tooltip.Draw(new Rect(0.0f, 0.0f, Screen.width, Screen.height)); } else { // set zero area win_rect win_rect.width = 0f; } // get mouse over state // bool mouse_over = win_rect.Contains(Event.current.mousePosition); bool mouse_over = win_rect.Contains(new Vector2(Input.mousePosition.x, Screen.height - Input.mousePosition.y)); // disable camera mouse scrolling on mouse over if (mouse_over) { GameSettings.AXIS_MOUSEWHEEL.primary.scale = 0.0f; } // Disable Click through if (mouse_over && !clickThroughLocked) { InputLockManager.SetControlLock(MainGUILockTypes, "KerbalismMainGUILock"); clickThroughLocked = true; } if (!mouse_over && clickThroughLocked) { InputLockManager.RemoveControlLock("KerbalismMainGUILock"); clickThroughLocked = false; } } // initialized flag bool ui_initialized; // store reference to applauncher button ApplicationLauncherButton vesselListLauncher; ApplicationLauncherButton generalMenuLauncher; // window geometry Rect win_rect; // the vessel monitor Monitor monitor; // tooltip utility Tooltip tooltip; } } // KERBALISM
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using Subtext.Scripting.Exceptions; using Subtext.Framework.Properties; namespace Subtext.Scripting { public class ScriptSplitter : IEnumerable<string> { private readonly TextReader _reader; private StringBuilder _builder = new StringBuilder(); private char _current; private char _lastChar; private ScriptReader _scriptReader; public ScriptSplitter(string script) { _reader = new StringReader(script); _scriptReader = new SeparatorLineReader(this); } internal bool HasNext { get { return _reader.Peek() != -1; } } internal char Current { get { return _current; } } internal char LastChar { get { return _lastChar; } } #region IEnumerable<string> Members public IEnumerator<string> GetEnumerator() { while(Next()) { if(Split()) { string script = _builder.ToString().Trim(); if(script.Length > 0) { yield return (script); } Reset(); } } if(_builder.Length > 0) { string scriptRemains = _builder.ToString().Trim(); if(scriptRemains.Length > 0) { yield return (scriptRemains); } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion internal bool Next() { if(!HasNext) { return false; } _lastChar = _current; _current = (char)_reader.Read(); return true; } internal int Peek() { return _reader.Peek(); } private bool Split() { return _scriptReader.ReadNextSection(); } internal void SetParser(ScriptReader newReader) { _scriptReader = newReader; } internal void Append(string text) { _builder.Append(text); } internal void Append(char c) { _builder.Append(c); } void Reset() { _current = _lastChar = char.MinValue; _builder = new StringBuilder(); } } abstract class ScriptReader { protected readonly ScriptSplitter Splitter; protected ScriptReader(ScriptSplitter splitter) { Splitter = splitter; } /// <summary> /// This acts as a template method. Specific Reader instances /// override the component methods. /// </summary> public bool ReadNextSection() { if(IsQuote) { ReadQuotedString(); return false; } if(BeginDashDashComment) { return ReadDashDashComment(); } if(BeginSlashStarComment) { ReadSlashStarComment(); return false; } return ReadNext(); } protected virtual bool ReadDashDashComment() { Splitter.Append(Current); while(Splitter.Next()) { Splitter.Append(Current); if(EndOfLine) { break; } } //We should be EndOfLine or EndOfScript here. Splitter.SetParser(new SeparatorLineReader(Splitter)); return false; } protected virtual void ReadSlashStarComment() { if(ReadSlashStarCommentWithResult()) { Splitter.SetParser(new SeparatorLineReader(Splitter)); return; } } private bool ReadSlashStarCommentWithResult() { Splitter.Append(Current); while(Splitter.Next()) { if(BeginSlashStarComment) { ReadSlashStarCommentWithResult(); continue; } Splitter.Append(Current); if(EndSlashStarComment) { return true; } } return false; } protected virtual void ReadQuotedString() { Splitter.Append(Current); while(Splitter.Next()) { Splitter.Append(Current); if(IsQuote) { return; } } } protected abstract bool ReadNext(); #region Helper methods and properties protected bool HasNext { get { return Splitter.HasNext; } } protected bool WhiteSpace { get { return char.IsWhiteSpace(Splitter.Current); } } protected bool EndOfLine { get { return '\n' == Splitter.Current; } } protected bool IsQuote { get { return '\'' == Splitter.Current; } } protected char Current { get { return Splitter.Current; } } protected char LastChar { get { return Splitter.LastChar; } } bool BeginDashDashComment { get { return Current == '-' && Peek() == '-'; } } bool BeginSlashStarComment { get { return Current == '/' && Peek() == '*'; } } bool EndSlashStarComment { get { return LastChar == '*' && Current == '/'; } } protected static bool CharEquals(char expected, char actual) { return Char.ToLowerInvariant(expected) == Char.ToLowerInvariant(actual); } protected bool CharEquals(char compare) { return CharEquals(Current, compare); } protected char Peek() { if(!HasNext) { return char.MinValue; } return (char)Splitter.Peek(); } #endregion } class SeparatorLineReader : ScriptReader { private StringBuilder _builder = new StringBuilder(); private bool _foundGo; private bool _gFound; public SeparatorLineReader(ScriptSplitter splitter) : base(splitter) { } void Reset() { _foundGo = false; _gFound = false; _builder = new StringBuilder(); } protected override bool ReadDashDashComment() { if(!_foundGo) { base.ReadDashDashComment(); return false; } base.ReadDashDashComment(); return true; } protected override void ReadSlashStarComment() { if(_foundGo) { throw new SqlParseException(Resources.SqlParseException_IncorrectSyntaxNearGo); } base.ReadSlashStarComment(); } protected override bool ReadNext() { if(EndOfLine) //End of line or script { if(!_foundGo) { _builder.Append(Current); Splitter.Append(_builder.ToString()); Splitter.SetParser(new SeparatorLineReader(Splitter)); return false; } Reset(); return true; } if(WhiteSpace) { _builder.Append(Current); return false; } if(!CharEquals('g') && !CharEquals('o')) { FoundNonEmptyCharacter(Current); return false; } if(CharEquals('o')) { if(CharEquals('g', LastChar) && !_foundGo) { _foundGo = true; } else { FoundNonEmptyCharacter(Current); } } if(CharEquals('g', Current)) { if(_gFound || (!Char.IsWhiteSpace(LastChar) && LastChar != char.MinValue)) { FoundNonEmptyCharacter(Current); return false; } _gFound = true; } if(!HasNext && _foundGo) { Reset(); return true; } _builder.Append(Current); return false; } void FoundNonEmptyCharacter(char c) { _builder.Append(c); Splitter.Append(_builder.ToString()); Splitter.SetParser(new SqlScriptReader(Splitter)); } } class SqlScriptReader : ScriptReader { public SqlScriptReader(ScriptSplitter splitter) : base(splitter) { } protected override bool ReadNext() { if(EndOfLine) //end of line { Splitter.Append(Current); Splitter.SetParser(new SeparatorLineReader(Splitter)); return false; } Splitter.Append(Current); return false; } } }
namespace SandcastleBuilder.Gui { partial class UserPreferencesDlg { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if(disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UserPreferencesDlg)); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.statusBarTextProvider1 = new SandcastleBuilder.Utils.Controls.StatusBarTextProvider(this.components); this.chkVerboseLogging = new System.Windows.Forms.CheckBox(); this.txtHTMLHelp2ViewerPath = new System.Windows.Forms.TextBox(); this.btnSelectHxSViewer = new System.Windows.Forms.Button(); this.udcASPNetDevServerPort = new System.Windows.Forms.NumericUpDown(); this.tabPreferences = new System.Windows.Forms.TabControl(); this.pgGeneral = new System.Windows.Forms.TabPage(); this.chkEnterMatching = new System.Windows.Forms.CheckBox(); this.chkShowLineNumbers = new System.Windows.Forms.CheckBox(); this.chkOpenHelp = new System.Windows.Forms.CheckBox(); this.cboBeforeBuildAction = new System.Windows.Forms.ComboBox(); this.label7 = new System.Windows.Forms.Label(); this.btnEditorFont = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.lblEditorExample = new System.Windows.Forms.Label(); this.btnBuildFont = new System.Windows.Forms.Button(); this.label4 = new System.Windows.Forms.Label(); this.btnBuildForeground = new System.Windows.Forms.Button(); this.btnBuildBackground = new System.Windows.Forms.Button(); this.label5 = new System.Windows.Forms.Label(); this.lblBuildExample = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.pgContentEditors = new System.Windows.Forms.TabPage(); this.btnDelete = new System.Windows.Forms.Button(); this.ilButton = new System.Windows.Forms.ImageList(this.components); this.btnAddFile = new System.Windows.Forms.Button(); this.pgProps = new SandcastleBuilder.Utils.Controls.CustomPropertyGrid(); this.lbContentEditors = new SandcastleBuilder.Utils.Controls.RefreshableItemListBox(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); this.epErrors = new System.Windows.Forms.ErrorProvider(this.components); this.txtMSHelpViewerPath = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.btnSelectMSHCViewer = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.udcASPNetDevServerPort)).BeginInit(); this.tabPreferences.SuspendLayout(); this.pgGeneral.SuspendLayout(); this.pgContentEditors.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.epErrors)).BeginInit(); this.SuspendLayout(); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(620, 488); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(88, 32); this.statusBarTextProvider1.SetStatusBarText(this.btnCancel, "Cancel: Close without saving preferences"); this.btnCancel.TabIndex = 2; this.btnCancel.Text = "Cancel"; this.toolTip1.SetToolTip(this.btnCancel, "Close without saving"); this.btnCancel.UseVisualStyleBackColor = true; // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOK.Location = new System.Drawing.Point(12, 488); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(88, 32); this.statusBarTextProvider1.SetStatusBarText(this.btnOK, "OK: Save preferences"); this.btnOK.TabIndex = 1; this.btnOK.Text = "OK"; this.toolTip1.SetToolTip(this.btnOK, "Save preferences"); this.btnOK.UseVisualStyleBackColor = true; // // chkVerboseLogging // this.chkVerboseLogging.Location = new System.Drawing.Point(262, 163); this.chkVerboseLogging.Name = "chkVerboseLogging"; this.chkVerboseLogging.Size = new System.Drawing.Size(292, 24); this.statusBarTextProvider1.SetStatusBarText(this.chkVerboseLogging, "Verbose Logging: Check this box to display all output messages. Uncheck to displ" + "ay summary messages only."); this.chkVerboseLogging.TabIndex = 10; this.chkVerboseLogging.Text = "&Build window verbose logging enabled"; this.chkVerboseLogging.UseVisualStyleBackColor = true; // // txtHTMLHelp2ViewerPath // this.txtHTMLHelp2ViewerPath.Location = new System.Drawing.Point(262, 18); this.txtHTMLHelp2ViewerPath.Name = "txtHTMLHelp2ViewerPath"; this.txtHTMLHelp2ViewerPath.Size = new System.Drawing.Size(358, 22); this.statusBarTextProvider1.SetStatusBarText(this.txtHTMLHelp2ViewerPath, "MS Help 2 (.HxS) Viewer: Enter the path and filename of the application used to v" + "iew MS Help 2 files"); this.txtHTMLHelp2ViewerPath.TabIndex = 1; // // btnSelectHxSViewer // this.btnSelectHxSViewer.Location = new System.Drawing.Point(621, 17); this.btnSelectHxSViewer.Name = "btnSelectHxSViewer"; this.btnSelectHxSViewer.Size = new System.Drawing.Size(32, 25); this.statusBarTextProvider1.SetStatusBarText(this.btnSelectHxSViewer, "Select Viewer: Browser for the MS Help 2 viewer application"); this.btnSelectHxSViewer.TabIndex = 2; this.btnSelectHxSViewer.Text = "..."; this.toolTip1.SetToolTip(this.btnSelectHxSViewer, "Select MS Help 2 viewer application"); this.btnSelectHxSViewer.UseVisualStyleBackColor = true; this.btnSelectHxSViewer.Click += new System.EventHandler(this.btnSelectViewer_Click); // // udcASPNetDevServerPort // this.udcASPNetDevServerPort.Location = new System.Drawing.Point(262, 74); this.udcASPNetDevServerPort.Maximum = new decimal(new int[] { 99999, 0, 0, 0}); this.udcASPNetDevServerPort.Minimum = new decimal(new int[] { 1000, 0, 0, 0}); this.udcASPNetDevServerPort.Name = "udcASPNetDevServerPort"; this.udcASPNetDevServerPort.Size = new System.Drawing.Size(70, 22); this.statusBarTextProvider1.SetStatusBarText(this.udcASPNetDevServerPort, "Server Port: Select the port to use when launching the ASP.NET Development Web Se" + "rver"); this.udcASPNetDevServerPort.TabIndex = 7; this.udcASPNetDevServerPort.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.udcASPNetDevServerPort.Value = new decimal(new int[] { 1000, 0, 0, 0}); // // tabPreferences // this.tabPreferences.Controls.Add(this.pgGeneral); this.tabPreferences.Controls.Add(this.pgContentEditors); this.tabPreferences.Location = new System.Drawing.Point(12, 12); this.tabPreferences.Name = "tabPreferences"; this.tabPreferences.SelectedIndex = 0; this.tabPreferences.Size = new System.Drawing.Size(696, 470); this.statusBarTextProvider1.SetStatusBarText(this.tabPreferences, "User preferences"); this.tabPreferences.TabIndex = 0; // // pgGeneral // this.pgGeneral.Controls.Add(this.txtMSHelpViewerPath); this.pgGeneral.Controls.Add(this.label8); this.pgGeneral.Controls.Add(this.btnSelectMSHCViewer); this.pgGeneral.Controls.Add(this.chkEnterMatching); this.pgGeneral.Controls.Add(this.chkShowLineNumbers); this.pgGeneral.Controls.Add(this.chkOpenHelp); this.pgGeneral.Controls.Add(this.cboBeforeBuildAction); this.pgGeneral.Controls.Add(this.label7); this.pgGeneral.Controls.Add(this.btnEditorFont); this.pgGeneral.Controls.Add(this.label3); this.pgGeneral.Controls.Add(this.lblEditorExample); this.pgGeneral.Controls.Add(this.btnBuildFont); this.pgGeneral.Controls.Add(this.label4); this.pgGeneral.Controls.Add(this.btnBuildForeground); this.pgGeneral.Controls.Add(this.btnBuildBackground); this.pgGeneral.Controls.Add(this.label5); this.pgGeneral.Controls.Add(this.lblBuildExample); this.pgGeneral.Controls.Add(this.label6); this.pgGeneral.Controls.Add(this.txtHTMLHelp2ViewerPath); this.pgGeneral.Controls.Add(this.udcASPNetDevServerPort); this.pgGeneral.Controls.Add(this.chkVerboseLogging); this.pgGeneral.Controls.Add(this.label2); this.pgGeneral.Controls.Add(this.label1); this.pgGeneral.Controls.Add(this.btnSelectHxSViewer); this.pgGeneral.Location = new System.Drawing.Point(4, 25); this.pgGeneral.Name = "pgGeneral"; this.pgGeneral.Padding = new System.Windows.Forms.Padding(3); this.pgGeneral.Size = new System.Drawing.Size(688, 441); this.statusBarTextProvider1.SetStatusBarText(this.pgGeneral, "General user preferences"); this.pgGeneral.TabIndex = 0; this.pgGeneral.Text = "General Preferences"; this.pgGeneral.UseVisualStyleBackColor = true; // // chkEnterMatching // this.chkEnterMatching.AutoSize = true; this.chkEnterMatching.Location = new System.Drawing.Point(92, 384); this.chkEnterMatching.Name = "chkEnterMatching"; this.chkEnterMatching.Size = new System.Drawing.Size(349, 21); this.statusBarTextProvider1.SetStatusBarText(this.chkEnterMatching, "Enter Matching: When checked, matching brackets, parentheses, and quotes will be " + "entered automatically in the text editor"); this.chkEnterMatching.TabIndex = 23; this.chkEnterMatching.Text = "E&nter matching brackets, parentheses, and quotes"; this.chkEnterMatching.UseVisualStyleBackColor = true; // // chkShowLineNumbers // this.chkShowLineNumbers.AutoSize = true; this.chkShowLineNumbers.Location = new System.Drawing.Point(92, 358); this.chkShowLineNumbers.Name = "chkShowLineNumbers"; this.chkShowLineNumbers.Size = new System.Drawing.Size(230, 21); this.statusBarTextProvider1.SetStatusBarText(this.chkShowLineNumbers, "Show Line Numbers: Check this box to show line numbers in the text editor"); this.chkShowLineNumbers.TabIndex = 19; this.chkShowLineNumbers.Text = "Sho&w line numbers in text editor"; this.chkShowLineNumbers.UseVisualStyleBackColor = true; // // chkOpenHelp // this.chkOpenHelp.Location = new System.Drawing.Point(262, 193); this.chkOpenHelp.Name = "chkOpenHelp"; this.chkOpenHelp.Size = new System.Drawing.Size(292, 24); this.statusBarTextProvider1.SetStatusBarText(this.chkOpenHelp, "Open Help: Check this to open the help file after a successful build"); this.chkOpenHelp.TabIndex = 11; this.chkOpenHelp.Text = "&Open help file after successful build"; this.chkOpenHelp.UseVisualStyleBackColor = true; // // cboBeforeBuildAction // this.cboBeforeBuildAction.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboBeforeBuildAction.FormattingEnabled = true; this.cboBeforeBuildAction.Items.AddRange(new object[] { "Save all changes", "Save changes to open documents only", "Prompt to save all changes", "Don\'t save any changes"}); this.cboBeforeBuildAction.Location = new System.Drawing.Point(262, 133); this.cboBeforeBuildAction.Name = "cboBeforeBuildAction"; this.cboBeforeBuildAction.Size = new System.Drawing.Size(292, 24); this.statusBarTextProvider1.SetStatusBarText(this.cboBeforeBuildAction, "Before Build: Select the action to take before performing a build"); this.cboBeforeBuildAction.TabIndex = 9; // // label7 // this.label7.Location = new System.Drawing.Point(135, 133); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(121, 23); this.label7.TabIndex = 8; this.label7.Text = "B&efore Building"; this.label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // btnEditorFont // this.btnEditorFont.Location = new System.Drawing.Point(487, 355); this.btnEditorFont.Name = "btnEditorFont"; this.btnEditorFont.Size = new System.Drawing.Size(32, 25); this.btnEditorFont.TabIndex = 21; this.btnEditorFont.Text = "..."; this.btnEditorFont.UseVisualStyleBackColor = true; this.btnEditorFont.Click += new System.EventHandler(this.btnFont_Click); // // label3 // this.label3.Location = new System.Drawing.Point(352, 356); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(129, 23); this.label3.TabIndex = 20; this.label3.Text = "&Text Editor Font"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // lblEditorExample // this.lblEditorExample.BackColor = System.Drawing.SystemColors.Window; this.lblEditorExample.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblEditorExample.Font = new System.Drawing.Font("Courier New", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblEditorExample.ForeColor = System.Drawing.SystemColors.WindowText; this.lblEditorExample.Location = new System.Drawing.Point(525, 330); this.lblEditorExample.Name = "lblEditorExample"; this.lblEditorExample.Size = new System.Drawing.Size(128, 75); this.lblEditorExample.TabIndex = 22; this.lblEditorExample.Text = "Example Text"; this.lblEditorExample.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // btnBuildFont // this.btnBuildFont.Location = new System.Drawing.Point(487, 265); this.btnBuildFont.Name = "btnBuildFont"; this.btnBuildFont.Size = new System.Drawing.Size(32, 25); this.btnBuildFont.TabIndex = 17; this.btnBuildFont.Text = "..."; this.btnBuildFont.UseVisualStyleBackColor = true; this.btnBuildFont.Click += new System.EventHandler(this.btnFont_Click); // // label4 // this.label4.Location = new System.Drawing.Point(435, 266); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(46, 23); this.label4.TabIndex = 16; this.label4.Text = "Font"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // btnBuildForeground // this.btnBuildForeground.Location = new System.Drawing.Point(397, 265); this.btnBuildForeground.Name = "btnBuildForeground"; this.btnBuildForeground.Size = new System.Drawing.Size(32, 25); this.btnBuildForeground.TabIndex = 15; this.btnBuildForeground.Text = "..."; this.btnBuildForeground.UseVisualStyleBackColor = true; this.btnBuildForeground.Click += new System.EventHandler(this.btnColor_Click); // // btnBuildBackground // this.btnBuildBackground.Location = new System.Drawing.Point(262, 265); this.btnBuildBackground.Name = "btnBuildBackground"; this.btnBuildBackground.Size = new System.Drawing.Size(32, 25); this.btnBuildBackground.TabIndex = 13; this.btnBuildBackground.Text = "..."; this.btnBuildBackground.UseVisualStyleBackColor = true; this.btnBuildBackground.Click += new System.EventHandler(this.btnColor_Click); // // label5 // this.label5.Location = new System.Drawing.Point(300, 266); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(91, 23); this.label5.TabIndex = 14; this.label5.Text = "Foreground"; this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // lblBuildExample // this.lblBuildExample.BackColor = System.Drawing.SystemColors.Window; this.lblBuildExample.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lblBuildExample.Font = new System.Drawing.Font("Courier New", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblBuildExample.ForeColor = System.Drawing.SystemColors.WindowText; this.lblBuildExample.Location = new System.Drawing.Point(525, 240); this.lblBuildExample.Name = "lblBuildExample"; this.lblBuildExample.Size = new System.Drawing.Size(128, 75); this.lblBuildExample.TabIndex = 18; this.lblBuildExample.Text = "Example Text"; this.lblBuildExample.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // label6 // this.label6.Location = new System.Drawing.Point(82, 266); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(174, 23); this.label6.TabIndex = 12; this.label6.Text = "B&uild Output Background"; this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label2 // this.label2.Location = new System.Drawing.Point(46, 68); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(210, 47); this.label2.TabIndex = 6; this.label2.Text = "&ASP.NET Development Web Server Port"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label1 // this.label1.Location = new System.Drawing.Point(43, 18); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(213, 23); this.label1.TabIndex = 0; this.label1.Text = "MS &Help 2 (.HxS) Viewer Path"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // pgContentEditors // this.pgContentEditors.Controls.Add(this.btnDelete); this.pgContentEditors.Controls.Add(this.btnAddFile); this.pgContentEditors.Controls.Add(this.pgProps); this.pgContentEditors.Controls.Add(this.lbContentEditors); this.pgContentEditors.Location = new System.Drawing.Point(4, 25); this.pgContentEditors.Name = "pgContentEditors"; this.pgContentEditors.Padding = new System.Windows.Forms.Padding(3); this.pgContentEditors.Size = new System.Drawing.Size(688, 441); this.statusBarTextProvider1.SetStatusBarText(this.pgContentEditors, "Content file editors"); this.pgContentEditors.TabIndex = 1; this.pgContentEditors.Text = "Content File Editors"; this.pgContentEditors.UseVisualStyleBackColor = true; // // btnDelete // this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnDelete.ImageIndex = 1; this.btnDelete.ImageList = this.ilButton; this.btnDelete.Location = new System.Drawing.Point(650, 89); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(32, 32); this.statusBarTextProvider1.SetStatusBarText(this.btnDelete, "Delete: Delete the selected definition"); this.btnDelete.TabIndex = 2; this.toolTip1.SetToolTip(this.btnDelete, "Delete the selected definition"); this.btnDelete.UseVisualStyleBackColor = true; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // ilButton // this.ilButton.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilButton.ImageStream"))); this.ilButton.TransparentColor = System.Drawing.Color.Magenta; this.ilButton.Images.SetKeyName(0, "AddItem.bmp"); this.ilButton.Images.SetKeyName(1, "Delete.bmp"); // // btnAddFile // this.btnAddFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnAddFile.ImageIndex = 0; this.btnAddFile.ImageList = this.ilButton; this.btnAddFile.Location = new System.Drawing.Point(650, 6); this.btnAddFile.Name = "btnAddFile"; this.btnAddFile.Size = new System.Drawing.Size(32, 32); this.statusBarTextProvider1.SetStatusBarText(this.btnAddFile, "Add: Add a new content file editor definition"); this.btnAddFile.TabIndex = 1; this.toolTip1.SetToolTip(this.btnAddFile, "Add a new content file editor definition"); this.btnAddFile.UseVisualStyleBackColor = true; this.btnAddFile.Click += new System.EventHandler(this.btnAddFile_Click); // // pgProps // this.pgProps.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.pgProps.Location = new System.Drawing.Point(6, 179); this.pgProps.Name = "pgProps"; this.pgProps.PropertyNamePaneWidth = 150; this.pgProps.Size = new System.Drawing.Size(676, 256); this.statusBarTextProvider1.SetStatusBarText(this.pgProps, "Edit the properties of the selected content editor"); this.pgProps.TabIndex = 3; this.pgProps.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.pgProps_PropertyValueChanged); // // lbContentEditors // this.lbContentEditors.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lbContentEditors.FormattingEnabled = true; this.lbContentEditors.IntegralHeight = false; this.lbContentEditors.ItemHeight = 16; this.lbContentEditors.Location = new System.Drawing.Point(6, 6); this.lbContentEditors.Name = "lbContentEditors"; this.lbContentEditors.Size = new System.Drawing.Size(638, 167); this.statusBarTextProvider1.SetStatusBarText(this.lbContentEditors, "Select a content editor item"); this.lbContentEditors.TabIndex = 0; this.lbContentEditors.SelectedIndexChanged += new System.EventHandler(this.lbContentEditors_SelectedIndexChanged); // // epErrors // this.epErrors.ContainerControl = this; // // txtMSHelpViewerPath // this.txtMSHelpViewerPath.Location = new System.Drawing.Point(262, 46); this.txtMSHelpViewerPath.Name = "txtMSHelpViewerPath"; this.txtMSHelpViewerPath.Size = new System.Drawing.Size(358, 22); this.statusBarTextProvider1.SetStatusBarText(this.txtMSHelpViewerPath, "MS Help Viewer (.mshc) Viewer: Enter the path and filename of the application use" + "d to view MS Help Viewer files"); this.txtMSHelpViewerPath.TabIndex = 4; // // label8 // this.label8.Location = new System.Drawing.Point(6, 46); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(250, 23); this.label8.TabIndex = 3; this.label8.Text = "MS Help Viewer (.mshc) Viewer Path"; this.label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // btnSelectMSHCViewer // this.btnSelectMSHCViewer.Location = new System.Drawing.Point(621, 45); this.btnSelectMSHCViewer.Name = "btnSelectMSHCViewer"; this.btnSelectMSHCViewer.Size = new System.Drawing.Size(32, 25); this.statusBarTextProvider1.SetStatusBarText(this.btnSelectMSHCViewer, "Select Viewer: Browser for the MS Help Viewer viewer application"); this.btnSelectMSHCViewer.TabIndex = 5; this.btnSelectMSHCViewer.Text = "..."; this.toolTip1.SetToolTip(this.btnSelectMSHCViewer, "Select MS Help Viewer viewer application"); this.btnSelectMSHCViewer.UseVisualStyleBackColor = true; this.btnSelectMSHCViewer.Click += new System.EventHandler(this.btnSelectViewer_Click); // // UserPreferencesDlg // this.AcceptButton = this.btnOK; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(720, 532); this.Controls.Add(this.tabPreferences); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "UserPreferencesDlg"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "User Preferences"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.UserPreferencesDlg_FormClosing); ((System.ComponentModel.ISupportInitialize)(this.udcASPNetDevServerPort)).EndInit(); this.tabPreferences.ResumeLayout(false); this.pgGeneral.ResumeLayout(false); this.pgGeneral.PerformLayout(); this.pgContentEditors.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.epErrors)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnCancel; private SandcastleBuilder.Utils.Controls.StatusBarTextProvider statusBarTextProvider1; private System.Windows.Forms.ToolTip toolTip1; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.CheckBox chkVerboseLogging; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox txtHTMLHelp2ViewerPath; private System.Windows.Forms.Button btnSelectHxSViewer; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown udcASPNetDevServerPort; private System.Windows.Forms.ErrorProvider epErrors; private System.Windows.Forms.TabControl tabPreferences; private System.Windows.Forms.TabPage pgGeneral; private System.Windows.Forms.TabPage pgContentEditors; private SandcastleBuilder.Utils.Controls.CustomPropertyGrid pgProps; private SandcastleBuilder.Utils.Controls.RefreshableItemListBox lbContentEditors; private System.Windows.Forms.ImageList ilButton; private System.Windows.Forms.Button btnAddFile; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.Button btnEditorFont; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label lblEditorExample; private System.Windows.Forms.Button btnBuildFont; private System.Windows.Forms.Label label4; private System.Windows.Forms.Button btnBuildForeground; private System.Windows.Forms.Button btnBuildBackground; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label lblBuildExample; private System.Windows.Forms.Label label6; private System.Windows.Forms.CheckBox chkOpenHelp; private System.Windows.Forms.ComboBox cboBeforeBuildAction; private System.Windows.Forms.Label label7; private System.Windows.Forms.CheckBox chkShowLineNumbers; private System.Windows.Forms.CheckBox chkEnterMatching; private System.Windows.Forms.TextBox txtMSHelpViewerPath; private System.Windows.Forms.Label label8; private System.Windows.Forms.Button btnSelectMSHCViewer; } }
using System; using MonoBrickFirmware.Extensions; namespace MonoBrickFirmware.Sensors { /// <summary> /// Sensor mode when using a Sonar sensor /// </summary> public enum UltraSonicMode { /// <summary> /// Result will be in centimeter /// </summary> Centimeter = UARTMode.Mode0, /// <summary> /// Result will be in centi-inch /// </summary> Inch = UARTMode.Mode1, /// <summary> /// Sensor is in listen mode /// </summary> Listen = UARTMode.Mode2 }; internal enum UltraSonicCommand { Off = 00, SingleShot = 0x01, Continuous = 0x02, EventCapture = 0x03, RequestWarmReset = 0x04 }; internal enum UltraSonicRegister : byte { Version = 0x00, ProductId = 0x08, SensorType = 0x10, FactoryZeroValue = 0x11, FactoryScaleFactor = 0x12, FactoryScaleDivisor = 0x13, MeasurementUnits = 0x14, Interval = 0x40, Command = 0x41, Result1 = 0x42, Result2 = 0x43, Result3 = 0x44, Result4 = 0x45, Result5 = 0x46, Result6 = 0x47, Result7 = 0x48, Result8 = 0x49, ZeroValue = 0x50, ScaleFactor = 0x51, ScaleDivisor = 0x52, }; internal class UltraSonicSettings{ private byte zero; private byte scaleFactor; private byte scaleDivision; public UltraSonicSettings(byte zero, byte scaleFactor, byte scaleDivision){ this.zero = zero; this.scaleFactor = scaleFactor; this.scaleDivision = scaleDivision; } public UltraSonicSettings(byte[] data){ if(data.Length == 3){ zero = data[0]; scaleFactor = data[1]; scaleDivision = data[2]; } else{ zero = 0; scaleFactor = 0; scaleDivision = 0; } } public byte Zero{get{return zero;}} public byte ScaleFactor{get{return scaleFactor;}} public byte ScaleDivision{get{return scaleFactor;}} public override string ToString(){ return "Zero: " + zero.ToString() + " Scale factor: " + scaleFactor.ToString() + " Scale division: " + scaleDivision.ToString(); } } /// <summary> /// Sonar sensor /// </summary> public class NXTUltraSonicSensor : I2CSensor{ private const byte UltraSonicAddress = 0x02; private UltraSonicMode sonarMode; /// <summary> /// Gets or sets the sonar mode. /// </summary> /// <value> /// The sonar mode /// </value> public UltraSonicMode Mode{ get{return sonarMode;} set{sonarMode = value;} } /// <summary> /// Initializes a new instance of the <see cref="MonoBrickFirmware.Sensors.NXTUltraSonicSensor"/> class. /// </summary> /// <param name="port">Senosr Port.</param> public NXTUltraSonicSensor(SensorPort port) : this(port,UltraSonicMode.Centimeter) { } /// <summary> /// Initializes a new instance of the <see cref="MonoBrickFirmware.Sensors.NXTUltraSonicSensor"/> class. /// </summary> /// <param name="port">Senosr Port.</param> /// <param name="mode">Ultrasonic Mode.</param> public NXTUltraSonicSensor(SensorPort port, UltraSonicMode mode) : base(port,UltraSonicAddress,I2CMode.LowSpeed9V) { Mode = mode; base.Initialise(); } /// <summary> /// Read the distance in either centiinches or centimeter /// </summary> public float ReadDistance() { int reading = ReadRegister((byte)UltraSonicRegister.Result1, 1)[0]; if (Mode == UltraSonicMode.Inch) return (reading * 39370) / 100; return reading; } /// <summary> /// Fire a single shot /// </summary> public void SingleShot() { SetMode(UltraSonicCommand.SingleShot); } /// <summary> /// Turn off the sonar to save power /// </summary> public void Off() { SetMode(UltraSonicCommand.Off); } /// <summary> /// Do Continuous measurements /// </summary> public void Continuous() { SetMode(UltraSonicCommand.Continuous); } /// <summary> /// Determines whether sonar is off. /// </summary> /// <returns> /// <c>true</c> if sonar is off; otherwise, <c>false</c>. /// </returns> bool IsOff() { if (GetMode() == UltraSonicCommand.Off) return true; return false; } /// <summary> /// Reset the sensor /// </summary> public new void Reset() { SetMode(UltraSonicCommand.RequestWarmReset); } private byte GetContinuousInterval() { return ReadRegister((byte)UltraSonicRegister.Interval, 1)[0]; } private void SetContinuousInterval(byte interval) { WriteRegister((byte)UltraSonicRegister.Interval, interval); System.Threading.Thread.Sleep(100); } private UltraSonicSettings GetFactorySettings() { return new UltraSonicSettings( ReadRegister((byte)UltraSonicRegister.FactoryZeroValue, 1)[0], ReadRegister((byte)UltraSonicRegister.FactoryScaleFactor, 1)[0], ReadRegister((byte)UltraSonicRegister.FactoryScaleDivisor, 1)[0]); } private UltraSonicSettings GetActualSettings() { return new UltraSonicSettings( ReadRegister((byte)UltraSonicRegister.ZeroValue, 1)[0], ReadRegister((byte)UltraSonicRegister.ScaleFactor, 1)[0], ReadRegister((byte)UltraSonicRegister.ScaleDivisor, 1)[0]); } private UltraSonicCommand GetMode() { return (UltraSonicCommand)ReadRegister((byte)UltraSonicRegister.Command, 1)[0]; } private void SetMode(UltraSonicCommand command) { WriteRegister((byte)UltraSonicRegister.Command, (byte)command); System.Threading.Thread.Sleep(100); } /// <summary> /// Reads the sensor value as a string. /// </summary> /// <returns> /// The value as a string /// </returns> public override string ReadAsString() { string s = ReadDistance().ToString(); if (Mode == UltraSonicMode.Inch) s = s + " inch"; else s = s + " cm"; return s; } public override string GetSensorName () { return "NXT Ultrasonic"; } public override void SelectNextMode() { Mode = Mode.Next(); if(Mode == UltraSonicMode.Listen) Mode = Mode.Next(); return; } public override void SelectPreviousMode () { Mode = Mode.Previous(); if(Mode == UltraSonicMode.Listen) Mode = Mode.Previous(); return; } public override int NumberOfModes () { return Enum.GetNames(typeof(UltraSonicMode)).Length-1;//listen mode not supported } public override string SelectedMode () { return Mode.ToString(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SalesforceContact.cs" company="Sitecore A/S"> // Copyright (C) 2014 by Sitecore A/S // </copyright> // <summary> // Defines the SalesforceContact type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Sitecore.Salesforce.Data { using System; using System.Collections.Generic; using System.Web.Security; using Sitecore.Caching; using Sitecore.Diagnostics; using Sitecore.Reflection; using Sitecore.Salesforce.Client.Data; using Sitecore.Salesforce.Configuration; public class SalesforceContact : SObject, ISalesforceContact { protected static readonly DateTime SalesforceMinDate = new DateTime(1700, 1, 1); protected readonly ISalesforceFieldMapping FieldMapping; // ReSharper disable InconsistentNaming protected readonly Dictionary<string, object> properties = new Dictionary<string, object>(); // ReSharper restore InconsistentNaming // ReSharper disable InconsistentNaming protected bool cacheable = true; // ReSharper restore InconsistentNaming protected bool DisableDataLengthChanged; public SalesforceContact(ISalesforceFieldMapping fieldMapping) { Assert.ArgumentNotNull(fieldMapping, "fieldMapping"); this.FieldMapping = fieldMapping; } public SalesforceContact(ISalesforceFieldMapping fieldMapping, IEnumerable<KeyValuePair<string, object>> properties) : this(fieldMapping) { Assert.ArgumentNotNull(properties, "properties"); foreach (var pair in properties) { this.properties[pair.Key] = pair.Value; } } public SalesforceContact(ISalesforceFieldMapping fieldMapping, MembershipUser user) : this(fieldMapping) { this.DisableDataLengthChanged = true; try { this.Id = user.ProviderUserKey as string; this.Login = user.UserName; this.Email = user.Email; this.Description = user.Comment; this.IsApproved = user.IsApproved; this.LastLoginDate = user.LastLoginDate.ToUniversalTime(); this.LastActivityDate = user.LastActivityDate.ToUniversalTime(); this.LastPasswordChangedDate = user.LastPasswordChangedDate.ToUniversalTime(); } finally { this.DisableDataLengthChanged = false; this.RaiseDataLengthChanged(); } } public IReadOnlyDictionary<string, object> Properties { get { return this.properties; } } public T GetProperty<T>(string name, T defaultValue = default(T)) { object obj; if (this.properties.TryGetValue(name, out obj) && obj is T) { return (T)obj; } return defaultValue; } public void SetProperty<T>(string name, T value) { this.properties[name] = value; this.RaiseDataLengthChanged(); } public string Id { get { return this.GetProperty<string>(this.FieldMapping.Id); } set { this.SetProperty(this.FieldMapping.Id, value); } } public string Login { get { return this.GetProperty<string>(this.FieldMapping.Login); } set { this.SetProperty(this.FieldMapping.Login, value); } } public string Email { get { return this.GetProperty<string>(this.FieldMapping.Email); } set { this.SetProperty(this.FieldMapping.Email, value); } } public string PasswordQuestion { get { return this.GetProperty<string>(this.FieldMapping.PasswordQuestion); } set { this.SetProperty(this.FieldMapping.PasswordQuestion, value); } } public string Description { get { return this.GetProperty<string>(this.FieldMapping.Description); } set { this.SetProperty(this.FieldMapping.Description, value); } } public bool IsApproved { get { return this.GetProperty<bool>(this.FieldMapping.IsApproved); } set { this.SetProperty(this.FieldMapping.IsApproved, value); } } public bool IsLockedOut { get { return false; } } public DateTime CreatedDate { get { return this.GetProperty(this.FieldMapping.CreatedDate, SalesforceMinDate); } set { this.SetProperty(this.FieldMapping.CreatedDate, value >= SalesforceMinDate ? value : SalesforceMinDate); } } public DateTime LastLoginDate { get { return this.GetProperty(this.FieldMapping.LastLoginDate, SalesforceMinDate); } set { this.SetProperty(this.FieldMapping.LastLoginDate, value >= SalesforceMinDate ? value : SalesforceMinDate); } } public DateTime LastActivityDate { get { return this.GetProperty(this.FieldMapping.LastActivityDate, SalesforceMinDate); } set { this.SetProperty(this.FieldMapping.LastActivityDate, value >= SalesforceMinDate ? value : SalesforceMinDate); } } public DateTime LastPasswordChangedDate { get { return this.GetProperty(this.FieldMapping.LastPasswordChangedDate, SalesforceMinDate); } set { this.SetProperty(this.FieldMapping.LastPasswordChangedDate, value >= SalesforceMinDate ? value : SalesforceMinDate); } } public DateTime LastLockoutDate { get { return SalesforceMinDate; } } #region ICacheable long ICacheable.GetDataLength() { // TODO: consider what properties should be included return TypeUtil.SizeOfString(this.Id) + TypeUtil.SizeOfString(this.Login) + TypeUtil.SizeOfString(this.Email) + TypeUtil.SizeOfString(this.Description); } bool ICacheable.Cacheable { get { return cacheable; } set { cacheable = value; } } bool ICacheable.Immutable { get { return false; } } public event DataLengthChangedDelegate DataLengthChanged; protected void RaiseDataLengthChanged() { if (this.DisableDataLengthChanged) { return; } var dataLengthChanged = this.DataLengthChanged; if (dataLengthChanged != null) { dataLengthChanged(this); } } #endregion } }
/*************************************************************************** * QueuedSqliteDatabase.cs * * Copyright (C) 2005-2006 Novell, Inc. * Written by Aaron Bockover <aaron@aaronbock.net> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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.Threading; using System.Collections.Generic; using Mono.Data.SqliteClient; namespace Banshee.Database { public class QueuedSqliteDatabase : IDisposable { private Queue<QueuedSqliteCommand> command_queue = new Queue<QueuedSqliteCommand>(); private SqliteConnection connection; private Thread queue_thread; private bool dispose_requested = false; private bool processing_queue = false; private string dbpath; private bool connected; public QueuedSqliteDatabase(string dbpath) { this.dbpath = dbpath; queue_thread = new Thread(ProcessQueue); queue_thread.IsBackground = true; queue_thread.Start(); } public void Dispose() { dispose_requested = true; WakeUp(); while(processing_queue); } private void WaitForConnection() { while(!connected); } private void QueueCommand(QueuedSqliteCommand command) { lock(command_queue) { command_queue.Enqueue(command); } WakeUp(); } public SqliteDataReader Query(DbCommand command) { WaitForConnection(); command.Connection = connection; command.CommandType = Banshee.Database.CommandType.Reader; QueueCommand(command); return command.WaitForResult() as SqliteDataReader; } public SqliteDataReader Query(object command) { return Query(new DbCommand(command.ToString())); } public object QuerySingle(DbCommand command) { WaitForConnection(); command.Connection = connection; command.CommandType = Banshee.Database.CommandType.Scalar; QueueCommand(command); return command.WaitForResult(); } public object QuerySingle(object command) { return QuerySingle(new DbCommand(command.ToString())); } public int Execute(DbCommand command) { WaitForConnection(); command.Connection = connection; command.CommandType = Banshee.Database.CommandType.Execute;; QueueCommand(command); command.WaitForResult(); return command.InsertID; } public int Execute(object command) { return Execute(new DbCommand(command.ToString())); } public bool TableExists(string table) { return Convert.ToInt32(QuerySingle(String.Format(@" SELECT COUNT(*) FROM sqlite_master WHERE Type='table' AND Name='{0}'", table))) > 0; } private void WakeUp() { Monitor.Enter(command_queue); Monitor.Pulse(command_queue); Monitor.Exit(command_queue); } private void ProcessQueue() { if(connection == null) { connection = new SqliteConnection("Version=3,URI=file:" + dbpath); connection.Open(); connected = true; } processing_queue = true; bool in_dispose_transaction = false; while(true) { while(command_queue.Count > 0) { if(dispose_requested && !in_dispose_transaction) { (new SqliteCommand("BEGIN", connection)).ExecuteNonQuery(); in_dispose_transaction = true; } QueuedSqliteCommand command; lock(command_queue) { command = command_queue.Dequeue(); } command.Execute(); } if(dispose_requested) { if(in_dispose_transaction) { (new SqliteCommand("COMMIT", connection)).ExecuteNonQuery(); } connection.Close(); processing_queue = false; return; } Monitor.Enter(command_queue); Monitor.Wait(command_queue); Monitor.Exit(command_queue); } } } public enum CommandType { Reader, Scalar, Execute } public class QueuedSqliteCommand : SqliteCommand { private CommandType command_type; private object result; private int insert_id; private Exception execution_exception; private bool finished = false; public QueuedSqliteCommand(string command) : base(command) { } public QueuedSqliteCommand(SqliteConnection connection, string command, CommandType commandType) : base(command, connection) { this.command_type = commandType; } public void Execute() { if(result != null) { throw new ApplicationException("Command has alread been executed"); } try { switch(command_type) { case Banshee.Database.CommandType.Reader: result = ExecuteReader(); break; case Banshee.Database.CommandType.Scalar: result = ExecuteScalar(); break; case Banshee.Database.CommandType.Execute: default: result = ExecuteNonQuery(); insert_id = LastInsertRowID(); break; } } catch(Exception e) { execution_exception = e; } finished = true; } public object WaitForResult() { while(!finished); if(execution_exception != null) { throw execution_exception; } return result; } public object Result { get { return result; } internal set { result = value; } } public int InsertID { get { return insert_id; } } public new CommandType CommandType { get { return command_type; } set { command_type = value; } } } public class DbCommand : QueuedSqliteCommand { public DbCommand(string command) : base(command) { } public DbCommand(string command, params object [] parameters) : this(command) { for(int i = 0; i < parameters.Length;) { SqliteParameter param; if(parameters[i] is SqliteParameter) { param = (SqliteParameter)parameters[i]; if(i < parameters.Length - 1 && !(parameters[i + 1] is SqliteParameter)) { param.Value = parameters[i + 1]; i += 2; } else { i++; } } else { param = new SqliteParameter(); param.ParameterName = (string)parameters[i]; param.Value = parameters[i + 1]; i += 2; } Parameters.Add(param); } } public void AddParameter<T>(string name, T value) { AddParameter<T>(new DbParameter<T>(name), value); } public void AddParameter<T>(DbParameter<T> param, T value) { param.Value = value; Parameters.Add(param); } } public class DbParameter<T> : SqliteParameter { public DbParameter(string name) : base() { ParameterName = name; } public new T Value { get { return (T)base.Value; } set { base.Value = value; } } } }
using UnityEditor; using UnityEngine; using System; public class MultibandCustomGUI : FilterCurveUI { private float masterGain; private float lowGain, midGain, highGain; private float lowFreq, highFreq; private float lowAttackTime, midAttackTime, highAttackTime; private float lowReleaseTime, midReleaseTime, highReleaseTime; private float lowThreshold, midThreshold, highThreshold; private float lowRatio, midRatio, highRatio; private float lowKnee, midKnee, highKnee; private float filterOrder; private bool useLogScale; private bool showSpectrum; public override string Name { get { return "Demo Multiband"; } } public override string Description { get { return "Multiband compressor demo plugin for Unity's audio plugin system"; } } public override string Vendor { get { return "Unity"; } } private void DrawFilterCurve( Rect r, float[] coeffs, float lowGain, float midGain, float highGain, Color color, bool filled, double samplerate, double magScale) { double wm = -2.0 * 3.1415926 / samplerate; AudioCurveRendering.AudioCurveEvaluator d = delegate(float x) { MathHelpers.ComplexD w = MathHelpers.ComplexD.Exp(wm * GUIHelpers.MapNormalizedFrequency((double)x, samplerate, useLogScale, true)); MathHelpers.ComplexD lpf = MathHelpers.ComplexD.Pow((w * (w * coeffs[0] + coeffs[1]) + coeffs[2]) / (w * (w * coeffs[3] + coeffs[4]) + 1.0f), filterOrder); MathHelpers.ComplexD bpf1 = MathHelpers.ComplexD.Pow((w * (w * coeffs[5] + coeffs[6]) + coeffs[7]) / (w * (w * coeffs[8] + coeffs[9]) + 1.0f), filterOrder); MathHelpers.ComplexD bpf2 = MathHelpers.ComplexD.Pow((w * (w * coeffs[10] + coeffs[11]) + coeffs[12]) / (w * (w * coeffs[13] + coeffs[14]) + 1.0f), filterOrder); MathHelpers.ComplexD hpf = MathHelpers.ComplexD.Pow((w * (w * coeffs[15] + coeffs[16]) + coeffs[17]) / (w * (w * coeffs[18] + coeffs[19]) + 1.0f), filterOrder); double h = (lpf * lowGain).Mag2() + (bpf1 * bpf2 * midGain).Mag2() + (hpf * highGain).Mag2(); double mag = masterGain + 10.0 * Math.Log10(h); return (float)(mag * magScale); }; if (filled) AudioCurveRendering.DrawFilledCurve(r, d, color); else AudioCurveRendering.DrawCurve(r, d, color); } public bool DrawControl(IAudioEffectPlugin plugin, Rect r, float samplerate) { Event evt = Event.current; int controlID = GUIUtility.GetControlID(FocusType.Passive); EventType evtType = evt.GetTypeForControl(controlID); r = AudioCurveRendering.BeginCurveFrame(r); float thr = 4.0f; bool changed = false; float x = evt.mousePosition.x - r.x; if (evtType == EventType.MouseDown && r.Contains(evt.mousePosition) && evt.button == 0) { float lf = (float)GUIHelpers.MapNormalizedFrequency(lowFreq, samplerate, useLogScale, false) * r.width; float hf = (float)GUIHelpers.MapNormalizedFrequency(highFreq, samplerate, useLogScale, false) * r.width; dragOperation = DragOperation.Mid; if (x < lf + thr) dragOperation = DragOperation.Low; else if (x > hf - thr) dragOperation = DragOperation.High; GUIUtility.hotControl = controlID; EditorGUIUtility.SetWantsMouseJumping(1); evt.Use(); } else if (evtType == EventType.MouseDrag && GUIUtility.hotControl == controlID) { if (dragOperation == DragOperation.Low || dragOperation == DragOperation.Mid) lowFreq = Mathf.Clamp((float)GUIHelpers.MapNormalizedFrequency(GUIHelpers.MapNormalizedFrequency(lowFreq, samplerate, useLogScale, false) + evt.delta.x / r.width, samplerate, useLogScale, true), 10.0f, highFreq); if (dragOperation == DragOperation.Low) lowGain = Mathf.Clamp(lowGain - evt.delta.y * 0.5f, -100.0f, 100.0f); if (dragOperation == DragOperation.Mid) midGain = Mathf.Clamp(midGain - evt.delta.y * 0.5f, -100.0f, 100.0f); if (dragOperation == DragOperation.Mid || dragOperation == DragOperation.High) highFreq = Mathf.Clamp((float)GUIHelpers.MapNormalizedFrequency(GUIHelpers.MapNormalizedFrequency(highFreq, samplerate, useLogScale, false) + evt.delta.x / r.width, samplerate, useLogScale, true), lowFreq, samplerate * 0.5f); if (dragOperation == DragOperation.High) highGain = Mathf.Clamp(highGain - evt.delta.y * 0.5f, -100.0f, 100.0f); changed = true; evt.Use(); } else if (evtType == EventType.MouseUp && evt.button == 0 && GUIUtility.hotControl == controlID) { GUIUtility.hotControl = 0; EditorGUIUtility.SetWantsMouseJumping(0); evt.Use(); } if (Event.current.type == EventType.Repaint) { float blend = plugin.IsPluginEditableAndEnabled() ? 1.0f : 0.5f; // Mark bands (low, medium and high bands) Color lowColor = new Color(0.0f, 0.0f, 0.0f, blend); Color midColor = new Color(0.5f, 0.5f, 0.5f, blend); Color highColor = new Color(1.0f, 1.0f, 1.0f, blend); DrawBandSplitMarker(plugin, r, (float)GUIHelpers.MapNormalizedFrequency(lowFreq, samplerate, useLogScale, false) * r.width, thr, GUIUtility.hotControl == controlID && (dragOperation == DragOperation.Low || dragOperation == DragOperation.Mid), lowColor); DrawBandSplitMarker(plugin, r, (float)GUIHelpers.MapNormalizedFrequency(highFreq, samplerate, useLogScale, false) * r.width, thr, GUIUtility.hotControl == controlID && (dragOperation == DragOperation.High || dragOperation == DragOperation.Mid), highColor); const float dbRange = 40.0f; const float magScale = 1.0f / dbRange; float[] liveData; plugin.GetFloatBuffer("LiveData", out liveData, 6); float[] coeffs; plugin.GetFloatBuffer("Coeffs", out coeffs, 20); if (GUIUtility.hotControl == controlID) DrawFilterCurve( r, coeffs, (dragOperation == DragOperation.Low) ? Mathf.Pow(10.0f, 0.05f * lowGain) : 0.0f, (dragOperation == DragOperation.Mid) ? Mathf.Pow(10.0f, 0.05f * midGain) : 0.0f, (dragOperation == DragOperation.High) ? Mathf.Pow(10.0f, 0.05f * highGain) : 0.0f, new Color(1.0f, 1.0f, 1.0f, 0.2f * blend), true, samplerate, magScale); DrawFilterCurve(r, coeffs, Mathf.Pow(10.0f, 0.05f * lowGain) * liveData[0], 0.0f, 0.0f, lowColor, false, samplerate, magScale); DrawFilterCurve(r, coeffs, 0.0f, Mathf.Pow(10.0f, 0.05f * midGain) * liveData[1], 0.0f, midColor, false, samplerate, magScale); DrawFilterCurve(r, coeffs, 0.0f, 0.0f, Mathf.Pow(10.0f, 0.05f * highGain) * liveData[2], highColor, false, samplerate, magScale); DrawFilterCurve( r, coeffs, Mathf.Pow(10.0f, 0.05f * lowGain) * liveData[0], Mathf.Pow(10.0f, 0.05f * midGain) * liveData[1], Mathf.Pow(10.0f, 0.05f * highGain) * liveData[2], ScaleAlpha(AudioCurveRendering.kAudioOrange, 0.5f), false, samplerate, magScale); DrawFilterCurve( r, coeffs, Mathf.Pow(10.0f, 0.05f * lowGain), Mathf.Pow(10.0f, 0.05f * midGain), Mathf.Pow(10.0f, 0.05f * highGain), AudioCurveRendering.kAudioOrange, false, samplerate, magScale); if (showSpectrum) { int specLen = (int)r.width; float[] spec; plugin.GetFloatBuffer("InputSpec", out spec, specLen); DrawSpectrum(r, useLogScale, spec, dbRange, samplerate, 0.3f, 1.0f, 0.3f, 0.5f * blend, 0.0f); plugin.GetFloatBuffer("OutputSpec", out spec, specLen); DrawSpectrum(r, useLogScale, spec, dbRange, samplerate, 1.0f, 0.3f, 0.3f, 0.5f * blend, 0.0f); } GUIHelpers.DrawFrequencyTickMarks(r, samplerate, useLogScale, new Color(1.0f, 1.0f, 1.0f, 0.3f * blend)); } AudioCurveRendering.EndCurveFrame(); return changed; } public override bool OnGUI(IAudioEffectPlugin plugin) { float useLogScaleFloat; float showSpectrumFloat; plugin.GetFloatParameter("MasterGain", out masterGain); plugin.GetFloatParameter("LowGain", out lowGain); plugin.GetFloatParameter("MidGain", out midGain); plugin.GetFloatParameter("HighGain", out highGain); plugin.GetFloatParameter("LowFreq", out lowFreq); plugin.GetFloatParameter("HighFreq", out highFreq); plugin.GetFloatParameter("LowAttackTime", out lowAttackTime); plugin.GetFloatParameter("MidAttackTime", out midAttackTime); plugin.GetFloatParameter("HighAttackTime", out highAttackTime); plugin.GetFloatParameter("LowReleaseTime", out lowReleaseTime); plugin.GetFloatParameter("MidReleaseTime", out midReleaseTime); plugin.GetFloatParameter("HighReleaseTime", out highReleaseTime); plugin.GetFloatParameter("LowThreshold", out lowThreshold); plugin.GetFloatParameter("MidThreshold", out midThreshold); plugin.GetFloatParameter("HighThreshold", out highThreshold); plugin.GetFloatParameter("LowRatio", out lowRatio); plugin.GetFloatParameter("MidRatio", out midRatio); plugin.GetFloatParameter("HighRatio", out highRatio); plugin.GetFloatParameter("LowKnee", out lowKnee); plugin.GetFloatParameter("MidKnee", out midKnee); plugin.GetFloatParameter("HighKnee", out highKnee); plugin.GetFloatParameter("FilterOrder", out filterOrder); plugin.GetFloatParameter("UseLogScale", out useLogScaleFloat); plugin.GetFloatParameter("ShowSpectrum", out showSpectrumFloat); useLogScale = useLogScaleFloat > 0.5f; showSpectrum = showSpectrumFloat > 0.5f; GUILayout.Space(5f); Rect r = GUILayoutUtility.GetRect(200, 150, GUILayout.ExpandWidth(true)); if (DrawControl(plugin, r, plugin.GetSampleRate())) { plugin.SetFloatParameter("MasterGain", masterGain); plugin.SetFloatParameter("LowGain", lowGain); plugin.SetFloatParameter("MidGain", midGain); plugin.SetFloatParameter("HighGain", highGain); plugin.SetFloatParameter("LowFreq", lowFreq); plugin.SetFloatParameter("HighFreq", highFreq); plugin.SetFloatParameter("LowAttackTime", lowAttackTime); plugin.SetFloatParameter("MidAttackTime", midAttackTime); plugin.SetFloatParameter("HighAttackTime", highAttackTime); plugin.SetFloatParameter("LowReleaseTime", lowReleaseTime); plugin.SetFloatParameter("MidReleaseTime", midReleaseTime); plugin.SetFloatParameter("HighReleaseTime", highReleaseTime); plugin.SetFloatParameter("LowThreshold", lowThreshold); plugin.SetFloatParameter("MidThreshold", midThreshold); plugin.SetFloatParameter("HighThreshold", highThreshold); plugin.SetFloatParameter("LowRatio", lowRatio); plugin.SetFloatParameter("MidRatio", midRatio); plugin.SetFloatParameter("HighRatio", highRatio); plugin.SetFloatParameter("LowKnee", lowKnee); plugin.SetFloatParameter("MidKnee", midKnee); plugin.SetFloatParameter("HighKnee", highKnee); } return true; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.CSharp; using Microsoft.VisualBasic; using Xunit; namespace System.CodeDom.Compiler.Tests { public class CodeDomProviderTests { [Fact] public void GetAllCompilerInfo_ReturnsMinimumOfCSharpAndVB() { Type[] compilerInfos = CodeDomProvider.GetAllCompilerInfo().Where(provider => provider.IsCodeDomProviderTypeValid).Select(provider => provider.CodeDomProviderType).ToArray(); Assert.True(compilerInfos.Length >= 2); Assert.Contains(typeof(CSharpCodeProvider), compilerInfos); Assert.Contains(typeof(VBCodeProvider), compilerInfos); } [Fact] public void FileExtension_ReturnsEmpty() { Assert.Empty(new NullProvider().FileExtension); } [Fact] public void LanguageOptions_ReturnsNone() { Assert.Equal(LanguageOptions.None, new NullProvider().LanguageOptions); } [Fact] public void CreateGenerator_ReturnsOverridenGenerator() { #pragma warning disable 0618 CustomProvider provider = new CustomProvider(); Assert.Same(provider.CreateGenerator(), provider.CreateGenerator("fileName")); Assert.Same(provider.CreateGenerator(), provider.CreateGenerator(new StringWriter())); #pragma warning restore 0618 } [Fact] public void CreateParser_ReturnsNull() { #pragma warning disable 0618 Assert.Null(new NoParserProvider().CreateParser()); #pragma warning restore 0618 } [Fact] public void GetConverter_ReturnsNotNull() { Assert.NotNull(new CustomProvider().GetConverter(typeof(int))); } [Fact] public void GetConverter_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => new CustomProvider().GetConverter(null)); } public static IEnumerable<object[]> CreateProvider_String_TestData() { yield return new object[] { "c#", "cs" }; yield return new object[] { " c# ", "cs" }; yield return new object[] { "cs", "cs" }; yield return new object[] { "csharp", "cs" }; yield return new object[] { "CsHaRp", "cs" }; yield return new object[] { "vb", "vb" }; yield return new object[] { "vbs", "vb" }; yield return new object[] { "visualbasic", "vb" }; yield return new object[] { "vbscript", "vb" }; yield return new object[] { "VBSCRIPT", "vb" }; } [Theory] [MemberData(nameof(CreateProvider_String_TestData))] public void CreateProvider_String(string language, string expectedFileExtension) { CodeDomProvider provider = CodeDomProvider.CreateProvider(language); Assert.Equal(expectedFileExtension, provider.FileExtension); } public static IEnumerable<object[]> CreateProvider_String_Dictionary_TestData() { yield return new object[] { "cs", new Dictionary<string, string>(), "cs" }; yield return new object[] { "cs", new Dictionary<string, string>() { { "option", "value" } }, "cs" }; yield return new object[] { "cs", new Dictionary<string, string>() { { "option1", "value1" }, { "option2", "value2" } }, "cs" }; yield return new object[] { "cs", new Dictionary<string, string>() { { "option", null } }, "cs" }; yield return new object[] { "vb", new Dictionary<string, string>(), "vb" }; yield return new object[] { "vb", new Dictionary<string, string>() { { "option", "value" } }, "vb" }; yield return new object[] { "vb", new Dictionary<string, string>() { { "option1", "value1" }, { "option2", "value2" } }, "vb" }; yield return new object[] { "vb", new Dictionary<string, string>() { { "option", null } }, "vb" }; } [Theory] [MemberData(nameof(CreateProvider_String_Dictionary_TestData))] public void CreateProvider_String_Dictionary(string language, Dictionary<string, string> providerOptions, string expectedFileExtension) { CodeDomProvider provider = CodeDomProvider.CreateProvider(language, providerOptions); Assert.Equal(expectedFileExtension, provider.FileExtension); } [Fact] public void CreateProvider_NullProviderOptions_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("providerOptions", () => CodeDomProvider.CreateProvider("cs", null)); AssertExtensions.Throws<ArgumentNullException>("providerOptions", () => CodeDomProvider.CreateProvider("vb", null)); } [Fact] public void CreateProvider_NullLanguage_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.CreateProvider(null)); AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.CreateProvider(null, new Dictionary<string, string>())); } [Theory] [InlineData("")] [InlineData(".cs")] [InlineData("no-such-language")] public void CreateProvider_NoSuchLanguage_ThrowsConfigurationErrorsException(string language) { Exception ex1 = Assert.ThrowsAny<Exception>(() => CodeDomProvider.CreateProvider(language)); AssertIsConfigurationErrorsException(ex1); Exception ex2 = Assert.ThrowsAny<Exception>(() => CodeDomProvider.CreateProvider(language, new Dictionary<string, string>())); AssertIsConfigurationErrorsException(ex2); } [Theory] [InlineData(" cs ", true)] [InlineData("cs", true)] [InlineData("c#", true)] [InlineData("csharp", true)] [InlineData("CsHaRp", true)] [InlineData("vb", true)] [InlineData("vbs", true)] [InlineData("visualbasic", true)] [InlineData("vbscript", true)] [InlineData("VB", true)] [InlineData("", false)] [InlineData(".cs", false)] [InlineData("no-such-language", false)] public void IsDefinedLanguage_ReturnsExpected(string language, bool expected) { Assert.Equal(expected, CodeDomProvider.IsDefinedLanguage(language)); } [Fact] public void IsDefinedLanguage_NullLanguage_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.IsDefinedLanguage(null)); } [Theory] [InlineData("cs", "c#")] [InlineData(" cs ", "c#")] [InlineData(".cs", "c#")] [InlineData("Cs", "c#")] [InlineData("cs", "c#")] [InlineData("vb", "vb")] [InlineData(".vb", "vb")] [InlineData("VB", "vb")] public void GetLanguageFromExtension_ReturnsExpected(string extension, string expected) { Assert.Equal(expected, CodeDomProvider.GetLanguageFromExtension(extension)); } [Fact] public void GetLanguageFromExtension_NullExtension_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("extension", () => CodeDomProvider.GetLanguageFromExtension(null)); } [Theory] [InlineData("")] [InlineData("c#")] [InlineData("no-such-extension")] public void GetLanguageFromExtension_NoSuchExtension_ThrowsConfigurationErrorsException(string extension) { Exception ex = Assert.ThrowsAny<Exception>(() => CodeDomProvider.GetLanguageFromExtension(extension)); AssertIsConfigurationErrorsException(ex); } [Theory] [InlineData("cs", true)] [InlineData(".cs", true)] [InlineData("Cs", true)] [InlineData("cs", true)] [InlineData("vb", true)] [InlineData(".vb", true)] [InlineData("VB", true)] [InlineData("", false)] [InlineData("c#", false)] [InlineData("no-such-extension", false)] public void IsDefinedExtension_ReturnsExpected(string extension, bool expected) { Assert.Equal(expected, CodeDomProvider.IsDefinedExtension(extension)); } [Fact] public void IsDefinedExtension_NullExtension_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("extension", () => CodeDomProvider.IsDefinedExtension(null)); } [Theory] [InlineData(" cs ", typeof(CSharpCodeProvider))] [InlineData("cs", typeof(CSharpCodeProvider))] [InlineData("c#", typeof(CSharpCodeProvider))] [InlineData("csharp", typeof(CSharpCodeProvider))] [InlineData("CsHaRp", typeof(CSharpCodeProvider))] [InlineData("vb", typeof(VBCodeProvider))] [InlineData("vbs", typeof(VBCodeProvider))] [InlineData("visualbasic", typeof(VBCodeProvider))] [InlineData("vbscript", typeof(VBCodeProvider))] [InlineData("VB", typeof(VBCodeProvider))] public void GetCompilerInfo_ReturnsExpected(string language, Type expectedProviderType) { Assert.Equal(expectedProviderType, CodeDomProvider.GetCompilerInfo(language).CodeDomProviderType); } [Fact] public void GetCompilerInfo_NullLanguage_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.GetCompilerInfo(null)); } [Theory] [InlineData("")] [InlineData(".cs")] [InlineData("no-such-extension")] public void GetCompilerInfo_NoSuchExtension_ThrowsKeyNotFoundException(string language) { Exception ex = Assert.ThrowsAny<Exception>(() => CodeDomProvider.GetCompilerInfo(language)); AssertIsConfigurationErrorsException(ex); } [Fact] public void CompileAssemblyFromDom_CallsCompilerMethod() { AssertExtensions.Throws<ArgumentException>(null, () => new CustomProvider().CompileAssemblyFromDom(new CompilerParameters())); } [Fact] public void CompileAssemblyFromDom_NullCompiler_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CompileAssemblyFromDom(new CompilerParameters())); } [Fact] public void CompileAssemblyFromFile_CallsCompilerMethod() { AssertExtensions.Throws<ArgumentNullException>("2", () => new CustomProvider().CompileAssemblyFromFile(new CompilerParameters())); } [Fact] public void CompileAssemblyFromFile_NullCompiler_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CompileAssemblyFromFile(new CompilerParameters())); } [Fact] public void CompileAssemblyFromSource_CallsCompilerMethod() { AssertExtensions.Throws<ArgumentOutOfRangeException>("3", () => new CustomProvider().CompileAssemblyFromSource(new CompilerParameters())); } [Fact] public void CompileAssemblyFromSource_NullCompiler_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CompileAssemblyFromSource(new CompilerParameters())); } [Fact] public void CreateEscapedIdentifier_CallsGeneratorMethod() { AssertExtensions.Throws<ArgumentException>(null, () => new CustomProvider().CreateEscapedIdentifier("value")); } [Fact] public void CreateEscapedIdentifier_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CreateEscapedIdentifier("value")); } [Fact] public void CreateValidIdentifier_CallsGeneratorMethod() { AssertExtensions.Throws<ArgumentNullException>("2", () => new CustomProvider().CreateValidIdentifier("value")); } [Fact] public void CreateValidIdentifier_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CreateValidIdentifier("value")); } [Fact] public void GenerateCodeFromCompileUnit_CallsGeneratorMethod() { AssertExtensions.Throws<ArgumentOutOfRangeException>("3", () => new CustomProvider().GenerateCodeFromCompileUnit(new CodeCompileUnit(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromCompileUnit_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromCompileUnit(new CodeCompileUnit(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromExpression_CallsGeneratorMethod() { Assert.Throws<ArithmeticException>(() => new CustomProvider().GenerateCodeFromExpression(new CodeExpression(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromExpression_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromExpression(new CodeExpression(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromNamespace_CallsGeneratorMethod() { Assert.Throws<ArrayTypeMismatchException>(() => new CustomProvider().GenerateCodeFromNamespace(new CodeNamespace(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromNamespace_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromNamespace(new CodeNamespace(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromStatement_CallsGeneratorMethod() { Assert.Throws<BadImageFormatException>(() => new CustomProvider().GenerateCodeFromStatement(new CodeStatement(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromStatement_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromStatement(new CodeStatement(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromType_CallsGeneratorMethod() { Assert.Throws<CannotUnloadAppDomainException>(() => new CustomProvider().GenerateCodeFromType(new CodeTypeDeclaration(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromType_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromType(new CodeTypeDeclaration(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GetTypeOutput_CallsGeneratorMethod() { Assert.Throws<DataMisalignedException>(() => new CustomProvider().GetTypeOutput(new CodeTypeReference())); } [Fact] public void GetTypeOutput_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GetTypeOutput(new CodeTypeReference())); } [Fact] public void IsValidIdentifier_CallsGeneratorMethod() { Assert.Throws<DirectoryNotFoundException>(() => new CustomProvider().IsValidIdentifier("value")); } [Fact] public void IsValidIdentifier_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().IsValidIdentifier("value")); } [Fact] public void Supports_CallsGeneratorMethod() { Assert.Throws<DivideByZeroException>(() => new CustomProvider().Supports(GeneratorSupport.ArraysOfArrays)); } [Fact] public void Supports_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().Supports(GeneratorSupport.ArraysOfArrays)); } [Fact] public void GenerateCodeFromMember_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromMember(new CodeTypeMember(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void Parse_CallsParserMethod() { Assert.Same(CustomParser.CompileUnit, new CustomProvider().Parse(new StringReader("abc"))); } [Fact] public void Parse_NullParser_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().Parse(new StringReader("abc"))); } private static void AssertIsConfigurationErrorsException(Exception ex) { if (!PlatformDetection.IsNetNative) // Can't do internal Reflection { Assert.Equal("ConfigurationErrorsException", ex.GetType().Name); } } protected class NullProvider : CodeDomProvider { #pragma warning disable 0672 public override ICodeCompiler CreateCompiler() => null; public override ICodeParser CreateParser() => null; public override ICodeGenerator CreateGenerator() => null; #pragma warning restore 067 } protected class NoParserProvider : CodeDomProvider { public override ICodeCompiler CreateCompiler() => null; public override ICodeGenerator CreateGenerator() => null; } protected class CustomProvider : CodeDomProvider { private ICodeCompiler _compiler = new CustomCompiler(); public override ICodeCompiler CreateCompiler() => _compiler; private ICodeGenerator _generator = new CustomGenerator(); public override ICodeGenerator CreateGenerator() => _generator; private ICodeParser _parser = new CustomParser(); public override ICodeParser CreateParser() => _parser; } protected class CustomCompiler : ICodeCompiler { public CompilerResults CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit compilationUnit) => null; public CompilerResults CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] compilationUnits) { throw new ArgumentException("1"); } public CompilerResults CompileAssemblyFromFile(CompilerParameters options, string fileName) => null; public CompilerResults CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { throw new ArgumentNullException("2"); } public CompilerResults CompileAssemblyFromSource(CompilerParameters options, string source) => null; public CompilerResults CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { throw new ArgumentOutOfRangeException("3"); } } protected class CustomGenerator : ICodeGenerator { public string CreateEscapedIdentifier(string value) { throw new ArgumentException("1"); } public string CreateValidIdentifier(string value) { throw new ArgumentNullException("2"); } public void GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o) { throw new ArgumentOutOfRangeException("3"); } public void GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o) { throw new ArithmeticException("4"); } public void GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o) { throw new ArrayTypeMismatchException("5"); } public void GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o) { throw new BadImageFormatException("6"); } public void GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o) { throw new CannotUnloadAppDomainException("7"); } public string GetTypeOutput(CodeTypeReference type) { throw new DataMisalignedException("8"); } public bool IsValidIdentifier(string value) { throw new DirectoryNotFoundException("9"); } public bool Supports(GeneratorSupport supports) { throw new DivideByZeroException("10"); } public void ValidateIdentifier(string value) { throw new DllNotFoundException("11"); } } protected class CustomParser : ICodeParser { public static CodeCompileUnit CompileUnit { get; } = new CodeCompileUnit(); public CodeCompileUnit Parse(TextReader codeStream) => CompileUnit; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading; using System.Windows.Data; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Preview; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Projection; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Options { internal abstract class AbstractOptionPreviewViewModel : AbstractNotifyPropertyChanged, IDisposable { private IComponentModel _componentModel; private IWpfTextViewHost _textViewHost; private IContentType _contentType; private IEditorOptionsFactoryService _editorOptions; private ITextEditorFactoryService _textEditorFactoryService; private ITextBufferFactoryService _textBufferFactoryService; private IProjectionBufferFactoryService _projectionBufferFactory; private IContentTypeRegistryService _contentTypeRegistryService; public List<object> Items { get; set; } public ObservableCollection<AbstractCodeStyleOptionViewModel> CodeStyleItems { get; set; } public OptionSet Options { get; set; } private readonly OptionSet _originalOptions; protected AbstractOptionPreviewViewModel(OptionSet options, IServiceProvider serviceProvider, string language) { this.Options = options; _originalOptions = options; this.Items = new List<object>(); this.CodeStyleItems = new ObservableCollection<AbstractCodeStyleOptionViewModel>(); _componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); _contentTypeRegistryService = _componentModel.GetService<IContentTypeRegistryService>(); _textBufferFactoryService = _componentModel.GetService<ITextBufferFactoryService>(); _textEditorFactoryService = _componentModel.GetService<ITextEditorFactoryService>(); _projectionBufferFactory = _componentModel.GetService<IProjectionBufferFactoryService>(); _editorOptions = _componentModel.GetService<IEditorOptionsFactoryService>(); this.Language = language; _contentType = _contentTypeRegistryService.GetContentType(ContentTypeNames.CSharpContentType); } internal OptionSet ApplyChangedOptions(OptionSet optionSet) { foreach (var optionKey in this.Options.GetChangedOptions(_originalOptions)) { optionSet = optionSet.WithChangedOption(optionKey, this.Options.GetOption(optionKey)); } return optionSet; } public void SetOptionAndUpdatePreview<T>(T value, IOption option, string preview) { if (option is Option<CodeStyleOption<T>>) { var opt = Options.GetOption((Option<CodeStyleOption<T>>)option); opt.Value = value; Options = Options.WithChangedOption((Option<CodeStyleOption<T>>)option, opt); } else if (option is PerLanguageOption<CodeStyleOption<T>>) { var opt = Options.GetOption((PerLanguageOption<CodeStyleOption<T>>)option, Language); opt.Value = value; Options = Options.WithChangedOption((PerLanguageOption<CodeStyleOption<T>>)option, Language, opt); } else if (option is Option<T>) { Options = Options.WithChangedOption((Option<T>)option, value); } else if (option is PerLanguageOption<T>) { Options = Options.WithChangedOption((PerLanguageOption<T>)option, Language, value); } else { throw new InvalidOperationException("Unexpected option type"); } UpdateDocument(preview); } public IWpfTextViewHost TextViewHost { get { return _textViewHost; } private set { // make sure we close previous view. if (_textViewHost != null) { _textViewHost.Close(); } SetProperty(ref _textViewHost, value); } } public string Language { get; } public void UpdatePreview(string text) { const string start = "//["; const string end = "//]"; var service = MefV1HostServices.Create(_componentModel.DefaultExportProvider); var workspace = new PreviewWorkspace(service); var fileName = string.Format("project.{0}", Language == "C#" ? "csproj" : "vbproj"); var project = workspace.CurrentSolution.AddProject(fileName, "assembly.dll", Language); // use the mscorlib, system, and system.core that are loaded in the current process. string[] references = { "mscorlib", "System", "System.Core" }; var metadataService = workspace.Services.GetService<IMetadataService>(); var referenceAssemblies = Thread.GetDomain().GetAssemblies() .Where(x => references.Contains(x.GetName(true).Name, StringComparer.OrdinalIgnoreCase)) .Select(a => metadataService.GetReference(a.Location, MetadataReferenceProperties.Assembly)); project = project.WithMetadataReferences(referenceAssemblies); var document = project.AddDocument("document", SourceText.From(text, Encoding.UTF8)); var formatted = Formatter.FormatAsync(document, this.Options).WaitAndGetResult(CancellationToken.None); var textBuffer = _textBufferFactoryService.CreateTextBuffer(formatted.GetTextAsync().Result.ToString(), _contentType); var container = textBuffer.AsTextContainer(); var documentBackedByTextBuffer = document.WithText(container.CurrentText); var bufferText = textBuffer.CurrentSnapshot.GetText().ToString(); var startIndex = bufferText.IndexOf(start, StringComparison.Ordinal); var endIndex = bufferText.IndexOf(end, StringComparison.Ordinal); var startLine = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(startIndex) + 1; var endLine = textBuffer.CurrentSnapshot.GetLineNumberFromPosition(endIndex); var projection = _projectionBufferFactory.CreateProjectionBufferWithoutIndentation(_contentTypeRegistryService, _editorOptions.CreateOptions(), textBuffer.CurrentSnapshot, "", LineSpan.FromBounds(startLine, endLine)); var textView = _textEditorFactoryService.CreateTextView(projection, _textEditorFactoryService.CreateTextViewRoleSet(PredefinedTextViewRoles.Interactive)); this.TextViewHost = _textEditorFactoryService.CreateTextViewHost(textView, setFocus: false); workspace.TryApplyChanges(documentBackedByTextBuffer.Project.Solution); workspace.OpenDocument(document.Id); this.TextViewHost.Closed += (s, a) => { workspace.Dispose(); workspace = null; }; } public void Dispose() { if (_textViewHost != null) { _textViewHost.Close(); _textViewHost = null; } } private void UpdateDocument(string text) { UpdatePreview(text); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives using System; using System.Management.Automation; using System.Management.Automation.SecurityAccountsManager; using System.Management.Automation.SecurityAccountsManager.Extensions; using Microsoft.PowerShell.LocalAccounts; #endregion namespace Microsoft.PowerShell.Commands { /// <summary> /// The New-LocalUser cmdlet creates a new local user account. /// </summary> [Cmdlet(VerbsCommon.New, "LocalUser", DefaultParameterSetName = "Password", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=717981")] [Alias("nlu")] public class NewLocalUserCommand : PSCmdlet { #region Static Data // Names of object- and boolean-type parameters. // Switch parameters don't need to be included. private static string[] parameterNames = new string[] { "AccountExpires", "Description", "Disabled", "FullName", "Password", "UserMayNotChangePassword" }; #endregion Static Data #region Instance Data private Sam sam = null; #endregion Instance Data #region Parameter Properties /// <summary> /// The following is the definition of the input parameter "AccountExpires". /// Specifies when the user account will expire. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public System.DateTime AccountExpires { get { return this.accountexpires;} set { this.accountexpires = value; } } private System.DateTime accountexpires; // This parameter added by hand (copied from SetLocalUserCommand), not by Cmdlet Designer /// <summary> /// The following is the definition of the input parameter "AccountNeverExpires". /// Specifies that the account will not expire. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public System.Management.Automation.SwitchParameter AccountNeverExpires { get { return this.accountneverexpires;} set { this.accountneverexpires = value; } } private System.Management.Automation.SwitchParameter accountneverexpires; /// <summary> /// The following is the definition of the input parameter "Description". /// A descriptive comment for this user account. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public string Description { get { return this.description;} set { this.description = value; } } private string description; /// <summary> /// The following is the definition of the input parameter "Disabled". /// Specifies whether this user account is enabled or disabled. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public System.Management.Automation.SwitchParameter Disabled { get { return this.disabled;} set { this.disabled = value; } } private System.Management.Automation.SwitchParameter disabled; /// <summary> /// The following is the definition of the input parameter "FullName". /// Specifies the full name of the user account. This is different from the /// username of the user account. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public string FullName { get { return this.fullname;} set { this.fullname = value; } } private string fullname; /// <summary> /// The following is the definition of the input parameter "Name". /// Specifies the user name for the local user account. This can be a local user /// account or a local user account that is connected to a Microsoft Account. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [ValidateLength(1, 20)] public string Name { get { return this.name;} set { this.name = value; } } private string name; /// <summary> /// The following is the definition of the input parameter "Password". /// Specifies the password for the local user account. A password can contain up /// to 127 characters. /// </summary> [Parameter(Mandatory = true, ParameterSetName = "Password", ValueFromPipelineByPropertyName = true)] [ValidateNotNull] public System.Security.SecureString Password { get { return this.password;} set { this.password = value; } } private System.Security.SecureString password; /// <summary> /// The following is the definition of the input parameter "PasswordChangeableDate". /// Specifies that the new User account has no password. /// </summary> [Parameter(Mandatory = true, ParameterSetName = "NoPassword", ValueFromPipelineByPropertyName = true)] public System.Management.Automation.SwitchParameter NoPassword { get { return this.nopassword; } set { this.nopassword = value; } } private System.Management.Automation.SwitchParameter nopassword; /// <summary> /// The following is the definition of the input parameter "PasswordNeverExpires". /// Specifies that the password will not expire. /// </summary> [Parameter(ParameterSetName = "Password", ValueFromPipelineByPropertyName = true)] public System.Management.Automation.SwitchParameter PasswordNeverExpires { get { return this.passwordneverexpires; } set { this.passwordneverexpires = value; } } private System.Management.Automation.SwitchParameter passwordneverexpires; /// <summary> /// The following is the definition of the input parameter "UserMayNotChangePassword". /// Specifies whether the user is allowed to change the password on this /// account. The default value is True. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public System.Management.Automation.SwitchParameter UserMayNotChangePassword { get { return this.usermaynotchangepassword;} set { this.usermaynotchangepassword = value; } } private System.Management.Automation.SwitchParameter usermaynotchangepassword; #endregion Parameter Properties #region Cmdlet Overrides /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { if (this.HasParameter("AccountExpires") && AccountNeverExpires.IsPresent) { InvalidParametersException ex = new InvalidParametersException("AccountExpires", "AccountNeverExpires"); ThrowTerminatingError(ex.MakeErrorRecord()); } sam = new Sam(); } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { if (CheckShouldProcess(Name)) { var user = new LocalUser { Name = Name, Description = Description, Enabled = true, FullName = FullName, UserMayChangePassword = true }; foreach (var paramName in parameterNames) { if (this.HasParameter(paramName)) { switch (paramName) { case "AccountExpires": user.AccountExpires = AccountExpires; break; case "Disabled": user.Enabled = !Disabled; break; case "UserMayNotChangePassword": user.UserMayChangePassword = !UserMayNotChangePassword; break; } } } if (AccountNeverExpires.IsPresent) user.AccountExpires = null; // Password will be null if NoPassword was given user = sam.CreateLocalUser(user, Password, PasswordNeverExpires.IsPresent); WriteObject(user); } } catch (Exception ex) { WriteError(ex.MakeErrorRecord()); } } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { if (sam != null) { sam.Dispose(); sam = null; } } #endregion Cmdlet Overrides #region Private Methods private bool CheckShouldProcess(string target) { return ShouldProcess(target, Strings.ActionNewUser); } #endregion Private Methods } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Runtime; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Runtime.ConsistentRing; using Orleans.Runtime.Counters; using Orleans.Runtime.GrainDirectory; using Orleans.Runtime.Messaging; using Orleans.Runtime.Providers; using Orleans.Runtime.ReminderService; using Orleans.Runtime.Scheduler; using Orleans.Services; using Orleans.ApplicationParts; using Orleans.Configuration; using Orleans.Serialization; using Orleans.Internal; namespace Orleans.Runtime { /// <summary> /// Orleans silo. /// </summary> public class Silo { /// <summary> Standard name for Primary silo. </summary> public const string PrimarySiloName = "Primary"; private static TimeSpan WaitForMessageToBeQueuedForOutbound = TimeSpan.FromSeconds(2); /// <summary> Silo Types. </summary> public enum SiloType { /// <summary> No silo type specified. </summary> None = 0, /// <summary> Primary silo. </summary> Primary, /// <summary> Secondary silo. </summary> Secondary, } private readonly ILocalSiloDetails siloDetails; private readonly MessageCenter messageCenter; private readonly LocalGrainDirectory localGrainDirectory; private readonly ActivationDirectory activationDirectory; private readonly ILogger logger; private readonly TaskCompletionSource<int> siloTerminatedTask = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); private readonly SiloStatisticsManager siloStatistics; private readonly InsideRuntimeClient runtimeClient; private IReminderService reminderService; private SystemTarget fallbackScheduler; private readonly ISiloStatusOracle siloStatusOracle; private Watchdog platformWatchdog; private readonly TimeSpan initTimeout; private readonly TimeSpan stopTimeout = TimeSpan.FromMinutes(1); private readonly Catalog catalog; private readonly object lockable = new object(); private readonly GrainFactory grainFactory; private readonly ISiloLifecycleSubject siloLifecycle; private readonly IMembershipService membershipService; private List<GrainService> grainServices = new List<GrainService>(); private readonly ILoggerFactory loggerFactory; /// <summary> /// Gets the type of this /// </summary> internal string Name => this.siloDetails.Name; internal OrleansTaskScheduler LocalScheduler { get; private set; } internal ILocalGrainDirectory LocalGrainDirectory { get { return localGrainDirectory; } } internal IConsistentRingProvider RingProvider { get; private set; } internal ICatalog Catalog => catalog; internal SystemStatus SystemStatus { get; set; } internal IServiceProvider Services { get; } /// <summary> SiloAddress for this silo. </summary> public SiloAddress SiloAddress => this.siloDetails.SiloAddress; public Task SiloTerminated { get { return this.siloTerminatedTask.Task; } } // one event for all types of termination (shutdown, stop and fast kill). private bool isFastKilledNeeded = false; // Set to true if something goes wrong in the shutdown/stop phase private IGrainContext reminderServiceContext; private LifecycleSchedulingSystemTarget lifecycleSchedulingSystemTarget; /// <summary> /// Initializes a new instance of the <see cref="Silo"/> class. /// </summary> /// <param name="siloDetails">The silo initialization parameters</param> /// <param name="services">Dependency Injection container</param> [Obsolete("This constructor is obsolete and may be removed in a future release. Use SiloHostBuilder to create an instance of ISiloHost instead.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Should not Dispose of messageCenter in this method because it continues to run / exist after this point.")] public Silo(ILocalSiloDetails siloDetails, IServiceProvider services) { string name = siloDetails.Name; // Temporarily still require this. Hopefuly gone when 2.0 is released. this.siloDetails = siloDetails; this.SystemStatus = SystemStatus.Creating; var startTime = DateTime.UtcNow; IOptions<ClusterMembershipOptions> clusterMembershipOptions = services.GetRequiredService<IOptions<ClusterMembershipOptions>>(); initTimeout = clusterMembershipOptions.Value.MaxJoinAttemptTime; if (Debugger.IsAttached) { initTimeout = StandardExtensions.Max(TimeSpan.FromMinutes(10), clusterMembershipOptions.Value.MaxJoinAttemptTime); stopTimeout = initTimeout; } var localEndpoint = this.siloDetails.SiloAddress.Endpoint; services.GetService<SerializationManager>().RegisterSerializers(services.GetService<IApplicationPartManager>()); this.Services = services; this.Services.InitializeSiloUnobservedExceptionsHandler(); //set PropagateActivityId flag from node config IOptions<SiloMessagingOptions> messagingOptions = services.GetRequiredService<IOptions<SiloMessagingOptions>>(); RequestContext.PropagateActivityId = messagingOptions.Value.PropagateActivityId; this.loggerFactory = this.Services.GetRequiredService<ILoggerFactory>(); logger = this.loggerFactory.CreateLogger<Silo>(); logger.Info(ErrorCode.SiloGcSetting, "Silo starting with GC settings: ServerGC={0} GCLatencyMode={1}", GCSettings.IsServerGC, Enum.GetName(typeof(GCLatencyMode), GCSettings.LatencyMode)); if (!GCSettings.IsServerGC) { logger.Warn(ErrorCode.SiloGcWarning, "Note: Silo not running with ServerGC turned on - recommend checking app config : <configuration>-<runtime>-<gcServer enabled=\"true\">"); logger.Warn(ErrorCode.SiloGcWarning, "Note: ServerGC only kicks in on multi-core systems (settings enabling ServerGC have no effect on single-core machines)."); } if (logger.IsEnabled(LogLevel.Debug)) { var highestLogLevel = logger.IsEnabled(LogLevel.Trace) ? nameof(LogLevel.Trace) : nameof(LogLevel.Debug); logger.LogWarning( new EventId((int)ErrorCode.SiloGcWarning), $"A verbose logging level ({highestLogLevel}) is configured. This will impact performance. The recommended log level is {nameof(LogLevel.Information)}."); } logger.Info(ErrorCode.SiloInitializing, "-------------- Initializing silo on host {0} MachineName {1} at {2}, gen {3} --------------", this.siloDetails.DnsHostName, Environment.MachineName, localEndpoint, this.siloDetails.SiloAddress.Generation); logger.Info(ErrorCode.SiloInitConfig, "Starting silo {0}", name); var siloMessagingOptions = this.Services.GetRequiredService<IOptions<SiloMessagingOptions>>(); BufferPool.InitGlobalBufferPool(siloMessagingOptions.Value); try { grainFactory = Services.GetRequiredService<GrainFactory>(); } catch (InvalidOperationException exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start, GrainFactory was not registered in Dependency Injection container", exc); throw; } // Performance metrics siloStatistics = Services.GetRequiredService<SiloStatisticsManager>(); // The scheduler LocalScheduler = Services.GetRequiredService<OrleansTaskScheduler>(); runtimeClient = Services.GetRequiredService<InsideRuntimeClient>(); // Initialize the message center messageCenter = Services.GetRequiredService<MessageCenter>(); var dispatcher = this.Services.GetRequiredService<Dispatcher>(); messageCenter.RerouteHandler = dispatcher.RerouteMessage; messageCenter.SniffIncomingMessage = runtimeClient.SniffIncomingMessage; // Now the router/directory service // This has to come after the message center //; note that it then gets injected back into the message center.; localGrainDirectory = Services.GetRequiredService<LocalGrainDirectory>(); // Now the activation directory. activationDirectory = Services.GetRequiredService<ActivationDirectory>(); // Now the consistent ring provider RingProvider = Services.GetRequiredService<IConsistentRingProvider>(); catalog = Services.GetRequiredService<Catalog>(); siloStatusOracle = Services.GetRequiredService<ISiloStatusOracle>(); this.membershipService = Services.GetRequiredService<IMembershipService>(); this.SystemStatus = SystemStatus.Created; StringValueStatistic.FindOrCreate(StatisticNames.SILO_START_TIME, () => LogFormatter.PrintDate(startTime)); // this will help troubleshoot production deployment when looking at MDS logs. this.siloLifecycle = this.Services.GetRequiredService<ISiloLifecycleSubject>(); // register all lifecycle participants IEnumerable<ILifecycleParticipant<ISiloLifecycle>> lifecycleParticipants = this.Services.GetServices<ILifecycleParticipant<ISiloLifecycle>>(); foreach(ILifecycleParticipant<ISiloLifecycle> participant in lifecycleParticipants) { participant?.Participate(this.siloLifecycle); } // register all named lifecycle participants IKeyedServiceCollection<string, ILifecycleParticipant<ISiloLifecycle>> namedLifecycleParticipantCollection = this.Services.GetService<IKeyedServiceCollection<string,ILifecycleParticipant<ISiloLifecycle>>>(); foreach (ILifecycleParticipant<ISiloLifecycle> participant in namedLifecycleParticipantCollection ?.GetServices(this.Services) ?.Select(s => s.GetService(this.Services))) { participant?.Participate(this.siloLifecycle); } // add self to lifecycle this.Participate(this.siloLifecycle); logger.Info(ErrorCode.SiloInitializingFinished, "-------------- Started silo {0}, ConsistentHashCode {1:X} --------------", SiloAddress.ToLongString(), SiloAddress.GetConsistentHashCode()); } public async Task StartAsync(CancellationToken cancellationToken) { // SystemTarget for provider init calls this.lifecycleSchedulingSystemTarget = Services.GetRequiredService<LifecycleSchedulingSystemTarget>(); this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>(); RegisterSystemTarget(lifecycleSchedulingSystemTarget); try { await this.LocalScheduler.QueueTask(() => this.siloLifecycle.OnStart(cancellationToken), this.lifecycleSchedulingSystemTarget); } catch (Exception exc) { logger.Error(ErrorCode.SiloStartError, "Exception during Silo.Start", exc); throw; } } private void CreateSystemTargets() { logger.Debug("Creating System Targets for this silo."); logger.Debug("Creating {0} System Target", "SiloControl"); var siloControl = ActivatorUtilities.CreateInstance<SiloControl>(Services); RegisterSystemTarget(siloControl); logger.Debug("Creating {0} System Target", "DeploymentLoadPublisher"); RegisterSystemTarget(Services.GetRequiredService<DeploymentLoadPublisher>()); logger.Debug("Creating {0} System Target", "RemoteGrainDirectory + CacheValidator"); RegisterSystemTarget(LocalGrainDirectory.RemoteGrainDirectory); RegisterSystemTarget(LocalGrainDirectory.CacheValidator); logger.Debug("Creating {0} System Target", "RemoteClusterGrainDirectory"); logger.Debug("Creating {0} System Target", "ClientObserverRegistrar + TypeManager"); this.RegisterSystemTarget(this.Services.GetRequiredService<ClientObserverRegistrar>()); logger.Debug("Creating {0} System Target", "MembershipOracle"); if (this.membershipService is SystemTarget) { RegisterSystemTarget((SystemTarget)this.membershipService); } logger.Debug("Finished creating System Targets for this silo."); } private async Task InjectDependencies() { catalog.SiloStatusOracle = this.siloStatusOracle; this.siloStatusOracle.SubscribeToSiloStatusEvents(localGrainDirectory); // consistentRingProvider is not a system target per say, but it behaves like the localGrainDirectory, so it is here this.siloStatusOracle.SubscribeToSiloStatusEvents((ISiloStatusListener)RingProvider); this.siloStatusOracle.SubscribeToSiloStatusEvents(Services.GetRequiredService<DeploymentLoadPublisher>()); var reminderTable = Services.GetService<IReminderTable>(); if (reminderTable != null) { logger.Info($"Creating reminder grain service for type={reminderTable.GetType()}"); // Start the reminder service system target var timerFactory = this.Services.GetRequiredService<IAsyncTimerFactory>(); reminderService = new LocalReminderService(this, reminderTable, this.initTimeout, this.loggerFactory, timerFactory); RegisterSystemTarget((SystemTarget)reminderService); } RegisterSystemTarget(catalog); await LocalScheduler.QueueActionAsync(catalog.Start, catalog) .WithTimeout(initTimeout, $"Starting Catalog failed due to timeout {initTimeout}"); // SystemTarget for provider init calls this.fallbackScheduler = Services.GetRequiredService<FallbackSystemTarget>(); RegisterSystemTarget(fallbackScheduler); } private Task OnRuntimeInitializeStart(CancellationToken ct) { lock (lockable) { if (!this.SystemStatus.Equals(SystemStatus.Created)) throw new InvalidOperationException(String.Format("Calling Silo.Start() on a silo which is not in the Created state. This silo is in the {0} state.", this.SystemStatus)); this.SystemStatus = SystemStatus.Starting; } logger.Info(ErrorCode.SiloStarting, "Silo Start()"); //TODO: setup thead pool directly to lifecycle StartTaskWithPerfAnalysis("ConfigureThreadPoolAndServicePointSettings", this.ConfigureThreadPoolAndServicePointSettings, Stopwatch.StartNew()); return Task.CompletedTask; } private void StartTaskWithPerfAnalysis(string taskName, Action task, Stopwatch stopWatch) { stopWatch.Restart(); task.Invoke(); stopWatch.Stop(); this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish"); } private async Task StartAsyncTaskWithPerfAnalysis(string taskName, Func<Task> task, Stopwatch stopWatch) { stopWatch.Restart(); await task.Invoke(); stopWatch.Stop(); this.logger.Info(ErrorCode.SiloStartPerfMeasure, $"{taskName} took {stopWatch.ElapsedMilliseconds} Milliseconds to finish"); } private async Task OnRuntimeServicesStart(CancellationToken ct) { //TODO: Setup all (or as many as possible) of the class started in this call to work directly with lifecyce var stopWatch = Stopwatch.StartNew(); // The order of these 4 is pretty much arbitrary. StartTaskWithPerfAnalysis("Start Message center",messageCenter.Start,stopWatch); StartTaskWithPerfAnalysis("Start local grain directory", LocalGrainDirectory.Start, stopWatch); this.runtimeClient.CurrentStreamProviderRuntime = this.Services.GetRequiredService<SiloProviderRuntime>(); // This has to follow the above steps that start the runtime components await StartAsyncTaskWithPerfAnalysis("Create system targets and inject dependencies", () => { CreateSystemTargets(); return InjectDependencies(); }, stopWatch); // Validate the configuration. // TODO - refactor validation - jbragg //GlobalConfig.Application.ValidateConfiguration(logger); } private async Task OnRuntimeGrainServicesStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); // Load and init grain services before silo becomes active. await StartAsyncTaskWithPerfAnalysis("Init grain services", () => CreateGrainServices(), stopWatch); try { StatisticsOptions statisticsOptions = Services.GetRequiredService<IOptions<StatisticsOptions>>().Value; StartTaskWithPerfAnalysis("Start silo statistics", () => this.siloStatistics.Start(statisticsOptions), stopWatch); logger.Debug("Silo statistics manager started successfully."); // Finally, initialize the deployment load collector, for grains with load-based placement await StartAsyncTaskWithPerfAnalysis("Start deployment load collector", StartDeploymentLoadCollector, stopWatch); async Task StartDeploymentLoadCollector() { var deploymentLoadPublisher = Services.GetRequiredService<DeploymentLoadPublisher>(); await this.LocalScheduler.QueueTask(deploymentLoadPublisher.Start, deploymentLoadPublisher) .WithTimeout(this.initTimeout, $"Starting DeploymentLoadPublisher failed due to timeout {initTimeout}"); logger.Debug("Silo deployment load publisher started successfully."); } // Start background timer tick to watch for platform execution stalls, such as when GC kicks in var healthCheckParticipants = this.Services.GetService<IEnumerable<IHealthCheckParticipant>>().ToList(); this.platformWatchdog = new Watchdog(statisticsOptions.LogWriteInterval, healthCheckParticipants, this.loggerFactory.CreateLogger<Watchdog>()); this.platformWatchdog.Start(); if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo platform watchdog started successfully."); } } catch (Exception exc) { this.SafeExecute(() => this.logger.Error(ErrorCode.Runtime_Error_100330, String.Format("Error starting silo {0}. Going to FastKill().", this.SiloAddress), exc)); throw; } if (logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Silo.Start complete: System status = {0}", this.SystemStatus); } } private Task OnBecomeActiveStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); StartTaskWithPerfAnalysis("Start gateway", StartGateway, stopWatch); void StartGateway() { // Now that we're active, we can start the gateway var mc = this.messageCenter as MessageCenter; mc?.StartGateway(this.Services.GetRequiredService<ClientObserverRegistrar>()); logger.Debug("Message gateway service started successfully."); } this.SystemStatus = SystemStatus.Running; return Task.CompletedTask; } private async Task OnActiveStart(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); if (this.reminderService != null) { await StartAsyncTaskWithPerfAnalysis("Start reminder service", StartReminderService, stopWatch); async Task StartReminderService() { // so, we have the view of the membership in the consistentRingProvider. We can start the reminder service this.reminderServiceContext = (this.reminderService as IGrainContext) ?? this.fallbackScheduler; await this.LocalScheduler.QueueTask(this.reminderService.Start, this.reminderServiceContext) .WithTimeout(this.initTimeout, $"Starting ReminderService failed due to timeout {initTimeout}"); this.logger.Debug("Reminder service started successfully."); } } foreach (var grainService in grainServices) { await StartGrainService(grainService); } } private async Task CreateGrainServices() { var grainServices = this.Services.GetServices<IGrainService>(); foreach (var grainService in grainServices) { await RegisterGrainService(grainService); } } private async Task RegisterGrainService(IGrainService service) { var grainService = (GrainService)service; RegisterSystemTarget(grainService); grainServices.Add(grainService); await this.LocalScheduler.QueueTask(() => grainService.Init(Services), grainService).WithTimeout(this.initTimeout, $"GrainService Initializing failed due to timeout {initTimeout}"); logger.Info($"Grain Service {service.GetType().FullName} registered successfully."); } private async Task StartGrainService(IGrainService service) { var grainService = (GrainService)service; await this.LocalScheduler.QueueTask(grainService.Start, grainService).WithTimeout(this.initTimeout, $"Starting GrainService failed due to timeout {initTimeout}"); logger.Info($"Grain Service {service.GetType().FullName} started successfully."); } private void ConfigureThreadPoolAndServicePointSettings() { PerformanceTuningOptions performanceTuningOptions = Services.GetRequiredService<IOptions<PerformanceTuningOptions>>().Value; if (performanceTuningOptions.MinDotNetThreadPoolSize > 0 || performanceTuningOptions.MinIOThreadPoolSize > 0) { int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); if (performanceTuningOptions.MinDotNetThreadPoolSize > workerThreads || performanceTuningOptions.MinIOThreadPoolSize > completionPortThreads) { // if at least one of the new values is larger, set the new min values to be the larger of the prev. and new config value. int newWorkerThreads = Math.Max(performanceTuningOptions.MinDotNetThreadPoolSize, workerThreads); int newCompletionPortThreads = Math.Max(performanceTuningOptions.MinIOThreadPoolSize, completionPortThreads); bool ok = ThreadPool.SetMinThreads(newWorkerThreads, newCompletionPortThreads); if (ok) { logger.Info(ErrorCode.SiloConfiguredThreadPool, "Configured ThreadPool.SetMinThreads() to values: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } else { logger.Warn(ErrorCode.SiloFailedToConfigureThreadPool, "Failed to configure ThreadPool.SetMinThreads(). Tried to set values to: {0},{1}. Previous values are: {2},{3}.", newWorkerThreads, newCompletionPortThreads, workerThreads, completionPortThreads); } } } // Set .NET ServicePointManager settings to optimize throughput performance when using Azure storage // http://blogs.msdn.com/b/windowsazurestorage/archive/2010/06/25/nagle-s-algorithm-is-not-friendly-towards-small-requests.aspx logger.Info(ErrorCode.SiloConfiguredServicePointManager, "Configured .NET ServicePointManager to Expect100Continue={0}, DefaultConnectionLimit={1}, UseNagleAlgorithm={2} to improve Azure storage performance.", performanceTuningOptions.Expect100Continue, performanceTuningOptions.DefaultConnectionLimit, performanceTuningOptions.UseNagleAlgorithm); ServicePointManager.Expect100Continue = performanceTuningOptions.Expect100Continue; ServicePointManager.DefaultConnectionLimit = performanceTuningOptions.DefaultConnectionLimit; ServicePointManager.UseNagleAlgorithm = performanceTuningOptions.UseNagleAlgorithm; } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// Grains are not deactivated. /// </summary> public void Stop() { var cancellationSource = new CancellationTokenSource(); cancellationSource.Cancel(); StopAsync(cancellationSource.Token).GetAwaiter().GetResult(); } /// <summary> /// Gracefully stop the run time system and the application. /// All grains will be properly deactivated. /// All in-flight applications requests would be awaited and finished gracefully. /// </summary> public void Shutdown() { var cancellationSource = new CancellationTokenSource(this.stopTimeout); StopAsync(cancellationSource.Token).GetAwaiter().GetResult(); } /// <summary> /// Gracefully stop the run time system only, but not the application. /// Applications requests would be abruptly terminated, while the internal system state gracefully stopped and saved as much as possible. /// </summary> public async Task StopAsync(CancellationToken cancellationToken) { bool gracefully = !cancellationToken.IsCancellationRequested; string operation = gracefully ? "Shutdown()" : "Stop()"; bool stopAlreadyInProgress = false; lock (lockable) { if (this.SystemStatus.Equals(SystemStatus.Stopping) || this.SystemStatus.Equals(SystemStatus.ShuttingDown) || this.SystemStatus.Equals(SystemStatus.Terminated)) { stopAlreadyInProgress = true; // Drop through to wait below } else if (!this.SystemStatus.Equals(SystemStatus.Running)) { throw new InvalidOperationException(String.Format("Calling Silo.{0} on a silo which is not in the Running state. This silo is in the {1} state.", operation, this.SystemStatus)); } else { if (gracefully) this.SystemStatus = SystemStatus.ShuttingDown; else this.SystemStatus = SystemStatus.Stopping; } } if (stopAlreadyInProgress) { logger.Info(ErrorCode.SiloStopInProgress, "Silo termination is in progress - Will wait for it to finish"); var pause = TimeSpan.FromSeconds(1); while (!this.SystemStatus.Equals(SystemStatus.Terminated)) { logger.Info(ErrorCode.WaitingForSiloStop, "Waiting {0} for termination to complete", pause); await Task.Delay(pause).ConfigureAwait(false); } await this.SiloTerminated.ConfigureAwait(false); return; } try { await this.LocalScheduler.QueueTask(() => this.siloLifecycle.OnStop(cancellationToken), this.lifecycleSchedulingSystemTarget).ConfigureAwait(false); } finally { // Signal to all awaiters that the silo has terminated. await Task.Run(() => this.siloTerminatedTask.TrySetResult(0)).ConfigureAwait(false); SafeExecute(LocalScheduler.Stop); SafeExecute(LocalScheduler.PrintStatistics); } } private Task OnRuntimeServicesStop(CancellationToken ct) { if (this.isFastKilledNeeded || ct.IsCancellationRequested) // No time for this return Task.CompletedTask; // Start rejecting all silo to silo application messages SafeExecute(messageCenter.BlockApplicationMessages); // Stop scheduling/executing application turns SafeExecute(LocalScheduler.StopApplicationTurns); return Task.CompletedTask; } private Task OnRuntimeInitializeStop(CancellationToken ct) { // 10, 11, 12: Write Dead in the table, Drain scheduler, Stop msg center, ... logger.Info(ErrorCode.SiloStopped, "Silo is Stopped()"); // timers if (platformWatchdog != null) SafeExecute(platformWatchdog.Stop); // Silo may be dying before platformWatchdog was set up if (!ct.IsCancellationRequested) SafeExecute(activationDirectory.PrintActivationDirectory); SafeExecute(messageCenter.Stop); SafeExecute(siloStatistics.Stop); SafeExecute(() => this.SystemStatus = SystemStatus.Terminated); return Task.CompletedTask; } private async Task OnBecomeActiveStop(CancellationToken ct) { if (this.isFastKilledNeeded) return; bool gracefully = !ct.IsCancellationRequested; string operation = gracefully ? "Shutdown()" : "Stop()"; try { if (gracefully) { logger.Info(ErrorCode.SiloShuttingDown, "Silo starting to Shutdown()"); //Stop LocalGrainDirectory await LocalScheduler.QueueTask(()=>localGrainDirectory.Stop(true), localGrainDirectory.CacheValidator) .WithCancellation(ct, "localGrainDirectory Stop failed because the task was cancelled"); SafeExecute(() => catalog.DeactivateAllActivations().Wait(ct)); //wait for all queued message sent to OutboundMessageQueue before MessageCenter stop and OutboundMessageQueue stop. await Task.Delay(WaitForMessageToBeQueuedForOutbound); } } catch (Exception exc) { logger.Error(ErrorCode.SiloFailedToStopMembership, $"Failed to {operation}. About to FastKill this silo.", exc); this.isFastKilledNeeded = true; } // Stop the gateway SafeExecute(messageCenter.StopAcceptingClientMessages); SafeExecute(() => catalog?.Stop()); } private async Task OnActiveStop(CancellationToken ct) { if (this.isFastKilledNeeded || ct.IsCancellationRequested) return; if (this.messageCenter.Gateway != null) { await this.LocalScheduler .QueueTask(() => this.messageCenter.Gateway.SendStopSendMessages(this.grainFactory), this.lifecycleSchedulingSystemTarget) .WithCancellation(ct, "Sending gateway disconnection requests failed because the task was cancelled"); } if (reminderService != null) { await this.LocalScheduler .QueueTask(reminderService.Stop, this.reminderServiceContext) .WithCancellation(ct, "Stopping ReminderService failed because the task was cancelled"); } foreach (var grainService in grainServices) { await this.LocalScheduler .QueueTask(grainService.Stop, grainService) .WithCancellation(ct, "Stopping GrainService failed because the task was cancelled"); if (this.logger.IsEnabled(LogLevel.Debug)) { logger.Debug( "{GrainServiceType} Grain Service with Id {GrainServiceId} stopped successfully.", grainService.GetType().FullName, grainService.GetPrimaryKeyLong(out string ignored)); } } } private void SafeExecute(Action action) { Utils.SafeExecute(action, logger, "Silo.Stop"); } private void HandleProcessExit(object sender, EventArgs e) { // NOTE: We need to minimize the amount of processing occurring on this code path -- we only have under approx 2-3 seconds before process exit will occur this.logger.Warn(ErrorCode.Runtime_Error_100220, "Process is exiting"); this.isFastKilledNeeded = true; this.Stop(); } internal void RegisterSystemTarget(SystemTarget target) { var providerRuntime = this.Services.GetRequiredService<SiloProviderRuntime>(); providerRuntime.RegisterSystemTarget(target); } /// <summary> Return dump of diagnostic data from this silo. </summary> /// <param name="all"></param> /// <returns>Debug data for this silo.</returns> public string GetDebugDump(bool all = true) { var sb = new StringBuilder(); foreach (var systemTarget in activationDirectory.AllSystemTargets()) sb.AppendFormat("System target {0}:", ((ISystemTargetBase)systemTarget).GrainId.ToString()).AppendLine(); var enumerator = activationDirectory.GetEnumerator(); while(enumerator.MoveNext()) { Utils.SafeExecute(() => { var activationData = enumerator.Current.Value; var workItemGroup = LocalScheduler.GetWorkItemGroup(activationData); if (workItemGroup == null) { sb.AppendFormat("Activation with no work item group!! Grain {0}, activation {1}.", activationData.GrainId, activationData.ActivationId); sb.AppendLine(); return; } if (all || activationData.State.Equals(ActivationState.Valid)) { sb.AppendLine(workItemGroup.DumpStatus()); sb.AppendLine(activationData.DumpStatus()); } }); } logger.Info(ErrorCode.SiloDebugDump, sb.ToString()); return sb.ToString(); } /// <summary> Object.ToString override -- summary info for this silo. </summary> public override string ToString() { return localGrainDirectory.ToString(); } private void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeInitialize, (ct) => Task.Run(() => OnRuntimeInitializeStart(ct)), (ct) => Task.Run(() => OnRuntimeInitializeStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeServices, (ct) => Task.Run(() => OnRuntimeServicesStart(ct)), (ct) => Task.Run(() => OnRuntimeServicesStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.RuntimeGrainServices, (ct) => Task.Run(() => OnRuntimeGrainServicesStart(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.BecomeActive, (ct) => Task.Run(() => OnBecomeActiveStart(ct)), (ct) => Task.Run(() => OnBecomeActiveStop(ct))); lifecycle.Subscribe<Silo>(ServiceLifecycleStage.Active, (ct) => Task.Run(() => OnActiveStart(ct)), (ct) => Task.Run(() => OnActiveStop(ct))); } } // A dummy system target for fallback scheduler internal class FallbackSystemTarget : SystemTarget { public FallbackSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory) : base(Constants.FallbackSystemTargetType, localSiloDetails.SiloAddress, loggerFactory) { } } // A dummy system target for fallback scheduler internal class LifecycleSchedulingSystemTarget : SystemTarget { public LifecycleSchedulingSystemTarget(ILocalSiloDetails localSiloDetails, ILoggerFactory loggerFactory) : base(Constants.LifecycleSchedulingSystemTargetType, localSiloDetails.SiloAddress, loggerFactory) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; class Program { public const int Pass = 100; public const int Fail = -1; static int Main() { SimpleReadWriteThreadStaticTest.Run(42, "SimpleReadWriteThreadStatic"); // TODO: After issue https://github.com/dotnet/corert/issues/2695 is fixed, move FinalizeTest to run at the end if (FinalizeTest.Run() != Pass) return Fail; ThreadStaticsTestWithTasks.Run(); if (ThreadTest.Run() != Pass) return Fail; if (TimerTest.Run() != Pass) return Fail; return Pass; } } class FinalizeTest { public static bool visited = false; public class Dummy { ~Dummy() { FinalizeTest.visited = true; } } public static int Run() { int iterationCount = 0; while (!visited && iterationCount++ < 10000) { GC.KeepAlive(new Dummy()); GC.Collect(); } if (visited) { Console.WriteLine("FinalizeTest passed"); return Program.Pass; } else { Console.WriteLine("FinalizeTest failed"); return Program.Fail; } } } class SimpleReadWriteThreadStaticTest { public static void Run(int intValue, string stringValue) { NonGenericReadWriteThreadStaticsTest(intValue, "NonGeneric" + stringValue); GenericReadWriteThreadStaticsTest(intValue + 1, "Generic" + stringValue); } class NonGenericType { [ThreadStatic] public static int IntValue; [ThreadStatic] public static string StringValue; } class GenericType<T, V> { [ThreadStatic] public static T ValueT; [ThreadStatic] public static V ValueV; } static void NonGenericReadWriteThreadStaticsTest(int intValue, string stringValue) { NonGenericType.IntValue = intValue; NonGenericType.StringValue = stringValue; if (NonGenericType.IntValue != intValue) { throw new Exception("SimpleReadWriteThreadStaticsTest: wrong integer value: " + NonGenericType.IntValue.ToString()); } if (NonGenericType.StringValue != stringValue) { throw new Exception("SimpleReadWriteThreadStaticsTest: wrong string value: " + NonGenericType.StringValue); } } static void GenericReadWriteThreadStaticsTest(int intValue, string stringValue) { GenericType<int, string>.ValueT = intValue; GenericType<int, string>.ValueV = stringValue; if (GenericType<int, string>.ValueT != intValue) { throw new Exception("GenericReadWriteThreadStaticsTest1a: wrong integer value: " + GenericType<int, string>.ValueT.ToString()); } if (GenericType<int, string>.ValueV != stringValue) { throw new Exception("GenericReadWriteThreadStaticsTest1b: wrong string value: " + GenericType<int, string>.ValueV); } intValue++; GenericType<int, int>.ValueT = intValue; GenericType<int, int>.ValueV = intValue + 1; if (GenericType<int, int>.ValueT != intValue) { throw new Exception("GenericReadWriteThreadStaticsTest2a: wrong integer value: " + GenericType<int, string>.ValueT.ToString()); } if (GenericType<int, int>.ValueV != (intValue + 1)) { throw new Exception("GenericReadWriteThreadStaticsTest2b: wrong integer value: " + GenericType<int, string>.ValueV.ToString()); } GenericType<string, string>.ValueT = stringValue + "a"; GenericType<string, string>.ValueV = stringValue + "b"; if (GenericType<string, string>.ValueT != (stringValue + "a")) { throw new Exception("GenericReadWriteThreadStaticsTest3a: wrong string value: " + GenericType<string, string>.ValueT); } if (GenericType<string, string>.ValueV != (stringValue + "b")) { throw new Exception("GenericReadWriteThreadStaticsTest3b: wrong string value: " + GenericType<string, string>.ValueV); } } } class ThreadStaticsTestWithTasks { static object lockObject = new object(); const int TotalTaskCount = 32; public static void Run() { Task[] tasks = new Task[TotalTaskCount]; for (int i = 0; i < tasks.Length; ++i) { tasks[i] = Task.Factory.StartNew((param) => { int index = (int)param; int intTestValue = index * 10; string stringTestValue = "ThreadStaticsTestWithTasks" + index; // Try to run the on every other task if ((index % 2) == 0) { lock (lockObject) { SimpleReadWriteThreadStaticTest.Run(intTestValue, stringTestValue); } } else { SimpleReadWriteThreadStaticTest.Run(intTestValue, stringTestValue); } }, i); } for (int i = 0; i < tasks.Length; ++i) { tasks[i].Wait(); } } } class ThreadTest { private static readonly List<Thread> s_startedThreads = new List<Thread>(); private static int s_passed; private static int s_failed; private static void Expect(bool condition, string message) { if (condition) { Interlocked.Increment(ref s_passed); } else { Interlocked.Increment(ref s_failed); Console.WriteLine("ERROR: " + message); } } private static void ExpectException<T>(Action action, string message) { Exception ex = null; try { action(); } catch (Exception e) { ex = e; } if (!(ex is T)) { message += string.Format(" (caught {0})", (ex == null) ? "no exception" : ex.GetType().Name); } Expect(ex is T, message); } private static void ExpectPassed(string testName, int expectedPassed) { // Wait for all started threads to finish execution foreach (Thread t in s_startedThreads) { t.Join(); } s_startedThreads.Clear(); Expect(s_passed == expectedPassed, string.Format("{0}: Expected s_passed == {1}, got {2}", testName, expectedPassed, s_passed)); s_passed = 0; } private static void TestStartMethod() { // Case 1: new Thread(ThreadStart).Start() var t1 = new Thread(() => Expect(true, "Expected t1 to start")); t1.Start(); s_startedThreads.Add(t1); // Case 2: new Thread(ThreadStart).Start(parameter) var t2 = new Thread(() => Expect(false, "This thread must not be started")); // InvalidOperationException: The thread was created with a ThreadStart delegate that does not accept a parameter. ExpectException<InvalidOperationException>(() => t2.Start(null), "Expected InvalidOperationException for t2.Start()"); // Case 3: new Thread(ParameterizedThreadStart).Start() var t3 = new Thread(obj => Expect(obj == null, "Expected obj == null")); t3.Start(); s_startedThreads.Add(t3); // Case 4: new Thread(ParameterizedThreadStart).Start(parameter) var t4 = new Thread(obj => Expect((int)obj == 42, "Expected (int)obj == 42")); t4.Start(42); s_startedThreads.Add(t4); // Start an unstarted resurrected thread. // CoreCLR: ThreadStateException, CoreRT: no exception. Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); unstartedResurrected.Start(); s_startedThreads.Add(unstartedResurrected); // Threads cannot started more than once t1.Join(); ExpectException<ThreadStateException>(() => t1.Start(), "Expected ThreadStateException for t1.Start()"); ExpectException<ThreadStateException>(() => Thread.CurrentThread.Start(), "Expected ThreadStateException for CurrentThread.Start()"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); ExpectException<ThreadStateException>(() => stoppedResurrected.Start(), "Expected ThreadStateException for stoppedResurrected.Start()"); ExpectPassed(nameof(TestStartMethod), 7); } private static void TestJoinMethod() { var t = new Thread(() => { }); ExpectException<InvalidOperationException>(() => t.Start(null), "Expected InvalidOperationException for t.Start()"); ExpectException<ThreadStateException>(() => t.Join(), "Expected ThreadStateException for t.Join()"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); Expect(stoppedResurrected.Join(1), "Expected stoppedResurrected.Join(1) to return true"); Expect(!Thread.CurrentThread.Join(1), "Expected CurrentThread.Join(1) to return false"); ExpectPassed(nameof(TestJoinMethod), 4); } private static void TestCurrentThreadProperty() { Thread t = null; t = new Thread(() => Expect(Thread.CurrentThread == t, "Expected CurrentThread == t on thread t")); t.Start(); s_startedThreads.Add(t); Expect(Thread.CurrentThread != t, "Expected CurrentThread != t on main thread"); ExpectPassed(nameof(TestCurrentThreadProperty), 2); } private static void TestNameProperty() { var t = new Thread(() => { }); t.Name = null; // It is OK to set the null Name multiple times t.Name = null; Expect(t.Name == null, "Expected t.Name == null"); const string ThreadName = "My thread"; t.Name = ThreadName; Expect(t.Name == ThreadName, string.Format("Expected t.Name == \"{0}\"", ThreadName)); ExpectException<InvalidOperationException>(() => { t.Name = null; }, "Expected InvalidOperationException setting Thread.Name back to null"); ExpectPassed(nameof(TestNameProperty), 3); } private static void TestIsBackgroundProperty() { // Thread created using Thread.Start var t_event = new AutoResetEvent(false); var t = new Thread(() => t_event.WaitOne()); t.Start(); s_startedThreads.Add(t); Expect(!t.IsBackground, "Expected t.IsBackground == false"); t_event.Set(); t.Join(); ExpectException<ThreadStateException>(() => Console.WriteLine(t.IsBackground), "Expected ThreadStateException for t.IsBackground"); // Thread pool thread Task.Factory.StartNew(() => Expect(Thread.CurrentThread.IsBackground, "Expected IsBackground == true")).Wait(); // Resurrected threads Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); Expect(unstartedResurrected.IsBackground == false, "Expected unstartedResurrected.IsBackground == false"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); ExpectException<ThreadStateException>(() => Console.WriteLine(stoppedResurrected.IsBackground), "Expected ThreadStateException for stoppedResurrected.IsBackground"); // Main thread Expect(!Thread.CurrentThread.IsBackground, "Expected CurrentThread.IsBackground == false"); ExpectPassed(nameof(TestIsBackgroundProperty), 6); } private static void TestIsThreadPoolThreadProperty() { #if false // The IsThreadPoolThread property is not in the contract version we compile against at present var t = new Thread(() => { }); Expect(!t.IsThreadPoolThread, "Expected t.IsThreadPoolThread == false"); Task.Factory.StartNew(() => Expect(Thread.CurrentThread.IsThreadPoolThread, "Expected IsThreadPoolThread == true")).Wait(); Expect(!Thread.CurrentThread.IsThreadPoolThread, "Expected CurrentThread.IsThreadPoolThread == false"); ExpectPassed(nameof(TestIsThreadPoolThreadProperty), 3); #endif } private static void TestManagedThreadIdProperty() { int t_id = 0; var t = new Thread(() => { Expect(Thread.CurrentThread.ManagedThreadId == t_id, "Expected CurrentTread.ManagedThreadId == t_id on thread t"); Expect(Environment.CurrentManagedThreadId == t_id, "Expected Environment.CurrentManagedThreadId == t_id on thread t"); }); t_id = t.ManagedThreadId; Expect(t_id != 0, "Expected t_id != 0"); Expect(Thread.CurrentThread.ManagedThreadId != t_id, "Expected CurrentTread.ManagedThreadId != t_id on main thread"); Expect(Environment.CurrentManagedThreadId != t_id, "Expected Environment.CurrentManagedThreadId != t_id on main thread"); t.Start(); s_startedThreads.Add(t); // Resurrected threads Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); Expect(unstartedResurrected.ManagedThreadId != 0, "Expected unstartedResurrected.ManagedThreadId != 0"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); Expect(stoppedResurrected.ManagedThreadId != 0, "Expected stoppedResurrected.ManagedThreadId != 0"); ExpectPassed(nameof(TestManagedThreadIdProperty), 7); } private static void TestThreadStateProperty() { var t_event = new AutoResetEvent(false); var t = new Thread(() => t_event.WaitOne()); Expect(t.ThreadState == ThreadState.Unstarted, "Expected t.ThreadState == ThreadState.Unstarted"); t.Start(); s_startedThreads.Add(t); Expect(t.ThreadState == ThreadState.Running || t.ThreadState == ThreadState.WaitSleepJoin, "Expected t.ThreadState is either ThreadState.Running or ThreadState.WaitSleepJoin"); t_event.Set(); t.Join(); Expect(t.ThreadState == ThreadState.Stopped, "Expected t.ThreadState == ThreadState.Stopped"); // Resurrected threads Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected(); Expect(unstartedResurrected.ThreadState == ThreadState.Unstarted, "Expected unstartedResurrected.ThreadState == ThreadState.Unstarted"); Thread stoppedResurrected = Resurrector.CreateStoppedResurrected(); Expect(stoppedResurrected.ThreadState == ThreadState.Stopped, "Expected stoppedResurrected.ThreadState == ThreadState.Stopped"); ExpectPassed(nameof(TestThreadStateProperty), 5); } private static unsafe void DoStackAlloc(int size) { byte* buffer = stackalloc byte[size]; Volatile.Write(ref buffer[0], 0); } private static void TestMaxStackSize() { #if false // The constructors with maxStackSize are not in the contract version we compile against at present // Allocate a 3 MiB buffer on the 4 MiB stack var t = new Thread(() => DoStackAlloc(3 << 20), 4 << 20); t.Start(); s_startedThreads.Add(t); #endif ExpectPassed(nameof(TestMaxStackSize), 0); } static int s_startedThreadCount = 0; private static void TestStartShutdown() { Thread[] threads = new Thread[2048]; // Creating a large number of threads for (int i = 0; i < threads.Length; i++) { threads[i] = new Thread(() => { Interlocked.Increment(ref s_startedThreadCount); }); threads[i].Start(); } // Wait for all threads to shutdown; for (int i = 0; i < threads.Length; i++) { threads[i].Join(); } Expect(s_startedThreadCount == threads.Length, String.Format("Not all threads completed. Expected: {0}, Actual: {1}", threads.Length, s_startedThreadCount)); } public static int Run() { TestStartMethod(); TestJoinMethod(); TestCurrentThreadProperty(); TestNameProperty(); TestIsBackgroundProperty(); TestIsThreadPoolThreadProperty(); TestManagedThreadIdProperty(); TestThreadStateProperty(); TestMaxStackSize(); TestStartShutdown(); return (s_failed == 0) ? Program.Pass : Program.Fail; } /// <summary> /// Creates resurrected Thread objects. /// </summary> class Resurrector { static Thread s_unstartedResurrected; static Thread s_stoppedResurrected; bool _unstarted; Thread _thread = new Thread(() => { }); Resurrector(bool unstarted) { _unstarted = unstarted; if (!unstarted) { _thread.Start(); _thread.Join(); } } ~Resurrector() { if (_unstarted && (s_unstartedResurrected == null)) { s_unstartedResurrected = _thread; } else if(!_unstarted && (s_stoppedResurrected == null)) { s_stoppedResurrected = _thread; } } [MethodImpl(MethodImplOptions.NoInlining)] static void CreateInstance(bool unstarted) { GC.KeepAlive(new Resurrector(unstarted)); } static Thread CreateResurrectedThread(ref Thread trap, bool unstarted) { trap = null; while (trap == null) { // Call twice to override the address of the first allocation on the stack (for conservative GC) CreateInstance(unstarted); CreateInstance(unstarted); GC.Collect(); GC.WaitForPendingFinalizers(); } // We would like to get a Thread object with its internal SafeHandle member disposed. // The current implementation of SafeHandle postpones disposing until the next garbage // collection. For this reason we do a couple more collections. for (int i = 0; i < 2; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } return trap; } public static Thread CreateUnstartedResurrected() { return CreateResurrectedThread(ref s_unstartedResurrected, unstarted: true); } public static Thread CreateStoppedResurrected() { return CreateResurrectedThread(ref s_stoppedResurrected, unstarted: false); } } } class TimerTest { private static AutoResetEvent s_event; private static Timer s_timer; private static volatile int s_periodicTimerCount; public static int Run() { s_event = new AutoResetEvent(false); s_timer = new Timer(TimerCallback, null, 200, Timeout.Infinite); bool timerFired = s_event.WaitOne(TimeSpan.FromSeconds(5)); if (!timerFired) { Console.WriteLine("The timer test failed: timer has not fired."); return Program.Fail; } // Change the timer to a very long value s_event.Reset(); s_timer.Change(3000000, Timeout.Infinite); timerFired = s_event.WaitOne(500); if (timerFired) { Console.WriteLine("The timer test failed: timer fired earlier than expected."); return Program.Fail; } // Try change existing timer to a small value and make sure it fires s_event.Reset(); s_timer.Change(200, Timeout.Infinite); timerFired = s_event.WaitOne(TimeSpan.FromSeconds(5)); if (!timerFired) { Console.WriteLine("The timer test failed: failed to change the existing timer."); return Program.Fail; } // Test a periodic timer s_periodicTimerCount = 0; s_event.Reset(); s_timer = new Timer(PeriodicTimerCallback, null, 200, 20); while (s_periodicTimerCount < 3) { timerFired = s_event.WaitOne(TimeSpan.FromSeconds(5)); if (!timerFired) { Console.WriteLine("The timer test failed: the periodic timer has not fired."); return Program.Fail; } } // Stop the periodic timer s_timer.Change(Timeout.Infinite, Timeout.Infinite); return Program.Pass; } private static void TimerCallback(object state) { s_event.Set(); } private static void PeriodicTimerCallback(object state) { Interlocked.Increment(ref s_periodicTimerCount); s_event.Set(); } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org. // **************************************************************** using System; using System.IO; using System.Drawing; using System.Collections; #if NET_2_0 using System.Collections.Generic; #endif namespace NUnit.Framework.Constraints { [TestFixture] public class EqualConstraintTest : ConstraintTestBase { [SetUp] public void SetUp() { theConstraint = new EqualConstraint(4); expectedDescription = "4"; stringRepresentation = "<equal 4>"; } internal object[] SuccessData = new object[] { 4, 4.0f, 4.0d, 4.0000m }; internal object[] FailureData = new object[] { 5, null, "Hello", double.NaN, double.PositiveInfinity }; internal string[] ActualValues = new string[] { "5", "null", "\"Hello\"", "NaN", "Infinity" }; [TestCase(double.NaN)] [TestCase(double.PositiveInfinity)] [TestCase(double.NegativeInfinity)] [TestCase(float.NaN)] [TestCase(float.PositiveInfinity)] [TestCase(float.NegativeInfinity)] public void CanMatchSpecialFloatingPointValues(object value) { Assert.That(value, new EqualConstraint(value)); } #region DateTime Tests [Test] public void CanMatchDates() { DateTime expected = new DateTime(2007, 4, 1); DateTime actual = new DateTime(2007, 4, 1); Assert.That(actual, new EqualConstraint(expected)); } [Test] public void CanMatchDatesWithinTimeSpan() { DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); TimeSpan tolerance = TimeSpan.FromMinutes(5.0); Assert.That(actual, new EqualConstraint(expected).Within(tolerance)); } [Test] public void CanMatchDatesWithinDays() { DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); DateTime actual = new DateTime(2007, 4, 4, 13, 0, 0); Assert.That(actual, new EqualConstraint(expected).Within(5).Days); } [Test] public void CanMatchDatesWithinHours() { DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); DateTime actual = new DateTime(2007, 4, 1, 16, 0, 0); Assert.That(actual, new EqualConstraint(expected).Within(5).Hours); } [Test] public void CanMatchDatesWithinMinutes() { DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes); } [Test] public void CanMatchTimeSpanWithinMinutes() { TimeSpan expected = new TimeSpan( 10, 0, 0); TimeSpan actual = new TimeSpan(10, 2, 30); Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes); } [Test] public void CanMatchDatesWithinSeconds() { DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); Assert.That(actual, new EqualConstraint(expected).Within(300).Seconds); } [Test] public void CanMatchDatesWithinMilliseconds() { DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); Assert.That(actual, new EqualConstraint(expected).Within(300000).Milliseconds); } [Test] public void CanMatchDatesWithinTicks() { DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0); DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0); Assert.That(actual, new EqualConstraint(expected).Within(TimeSpan.TicksPerMinute*5).Ticks); } #endregion #region Dictionary Tests // TODO: Move these to a separate fixture #if CS_3_0 [Test] public void CanMatchHashtables_SameOrder() { Assert.AreEqual(new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }, new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }); } [Test, ExpectedException(typeof(AssertionException))] public void CanMatchHashtables_Failure() { Assert.AreEqual(new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }, new Hashtable { { 0, 0 }, { 1, 5 }, { 2, 2 } }); } [Test] public void CanMatchHashtables_DifferentOrder() { Assert.AreEqual(new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }, new Hashtable { { 0, 0 }, { 2, 2 }, { 1, 1 } }); } #if NET_2_0 [Test] public void CanMatchDictionaries_SameOrder() { Assert.AreEqual(new Dictionary<int, int> { { 0, 0 }, { 1, 1 }, { 2, 2 } }, new Dictionary<int, int> { { 0, 0 }, { 1, 1 }, { 2, 2 } }); } [Test, ExpectedException(typeof(AssertionException))] public void CanMatchDictionaries_Failure() { Assert.AreEqual(new Dictionary<int, int> { { 0, 0 }, { 1, 1 }, { 2, 2 } }, new Dictionary<int, int> { { 0, 0 }, { 1, 5 }, { 2, 2 } }); } [Test] public void CanMatchDictionaries_DifferentOrder() { Assert.AreEqual(new Dictionary<int, int> { { 0, 0 }, { 1, 1 }, { 2, 2 } }, new Dictionary<int, int> { { 0, 0 }, { 2, 2 }, { 1, 1 } }); } [Test] public void CanMatchHashtableWithDictionary() { Assert.AreEqual(new Hashtable { { 0, 0 }, { 1, 1 }, { 2, 2 } }, new Dictionary<int, int> { { 0, 0 }, { 2, 2 }, { 1, 1 } }); } #endif #endif #endregion [TestCase(20000000000000004.0)] [TestCase(19999999999999996.0)] public void CanMatchDoublesWithUlpTolerance(object value) { Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps); } [ExpectedException(typeof(AssertionException))] [TestCase(20000000000000008.0)] [TestCase(19999999999999992.0)] public void FailsOnDoublesOutsideOfUlpTolerance(object value) { Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps); } [TestCase(19999998.0f)] [TestCase(20000002.0f)] public void CanMatchSinglesWithUlpTolerance(object value) { Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps); } [ExpectedException(typeof(AssertionException))] [TestCase(19999996.0f)] [TestCase(20000004.0f)] public void FailsOnSinglesOutsideOfUlpTolerance(object value) { Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps); } [TestCase(9500.0)] [TestCase(10000.0)] [TestCase(10500.0)] public void CanMatchDoublesWithRelativeTolerance(object value) { Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent); } [ExpectedException(typeof(AssertionException))] [TestCase(8500.0)] [TestCase(11500.0)] public void FailsOnDoublesOutsideOfRelativeTolerance(object value) { Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent); } [TestCase(9500.0f)] [TestCase(10000.0f)] [TestCase(10500.0f)] public void CanMatchSinglesWithRelativeTolerance(object value) { Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent); } [ExpectedException(typeof(AssertionException))] [TestCase(8500.0f)] [TestCase(11500.0f)] public void FailsOnSinglesOutsideOfRelativeTolerance(object value) { Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent); } /// <summary>Applies both the Percent and Ulps modifiers to cause an exception</summary> [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorWithPercentAndUlpsToleranceModes() { Assert.That(100.0f, new EqualConstraint(100.0f).Within(10.0f).Percent.Ulps); } /// <summary>Applies both the Ulps and Percent modifiers to cause an exception</summary> [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorWithUlpsAndPercentToleranceModes() { Assert.That(100.0f, new EqualConstraint(100.0f).Within(10.0f).Ulps.Percent); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorIfPercentPrecedesWithin() { Assert.That(1010, Is.EqualTo(1000).Percent.Within(5)); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorIfUlpsPrecedesWithin() { Assert.That(1010.0, Is.EqualTo(1000.0).Ulps.Within(5)); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorIfDaysPrecedesWithin() { Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Days.Within(5)); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorIfHoursPrecedesWithin() { Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Hours.Within(5)); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorIfMinutesPrecedesWithin() { Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Minutes.Within(5)); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorIfSecondsPrecedesWithin() { Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Seconds.Within(5)); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorIfMillisecondsPrecedesWithin() { Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Milliseconds.Within(5)); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorIfTicksPrecedesWithin() { Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Ticks.Within(5)); } [ExpectedException(typeof(InvalidOperationException))] [TestCase(1000, 1010)] [TestCase(1000U, 1010U)] [TestCase(1000L, 1010L)] [TestCase(1000UL, 1010UL)] public void ErrorIfUlpsIsUsedOnIntegralType(object x, object y) { Assert.That(y, Is.EqualTo(x).Within(2).Ulps); } [Test, ExpectedException(typeof(InvalidOperationException))] public void ErrorIfUlpsIsUsedOnDecimal() { Assert.That(100m, Is.EqualTo(100m).Within(2).Ulps); } [Test] public void UsesProvidedIComparer() { MyComparer comparer = new MyComparer(); Assert.That(2 + 2, Is.EqualTo(4).Using(comparer)); Assert.That(comparer.Called, "Comparer was not called"); } class MyComparer : IComparer { public bool Called; public int Compare(object x, object y) { Called = true; return Comparer.Default.Compare(x, y); } } #if NET_2_0 [Test] public void UsesProvidedEqualityComparer() { MyEqualityComparer comparer = new MyEqualityComparer(); Assert.That(2 + 2, Is.EqualTo(4).Using(comparer)); Assert.That(comparer.Called, "Comparer was not called"); } class MyEqualityComparer : IEqualityComparer { public bool Called; bool IEqualityComparer.Equals(object x, object y) { Called = true; return Comparer.Default.Compare(x, y) == 0; } int IEqualityComparer.GetHashCode(object x) { return x.GetHashCode(); } } [Test] public void UsesProvidedEqualityComparerOfT() { MyEqualityComparerOfT<int> comparer = new MyEqualityComparerOfT<int>(); Assert.That(2 + 2, Is.EqualTo(4).Using(comparer)); Assert.That(comparer.Called, "Comparer was not called"); } class MyEqualityComparerOfT<T> : IEqualityComparer<T> { public bool Called; bool IEqualityComparer<T>.Equals(T x, T y) { Called = true; return Comparer<T>.Default.Compare(x, y) == 0; } int IEqualityComparer<T>.GetHashCode(T x) { return x.GetHashCode(); } } [Test] public void UsesProvidedComparerOfT() { MyComparer<int> comparer = new MyComparer<int>(); Assert.That( 2+2, Is.EqualTo(4).Using(comparer)); Assert.That(comparer.Called, "Comparer was not called"); } class MyComparer<T> : IComparer<T> { public bool Called; public int Compare(T x, T y) { Called = true; return Comparer<T>.Default.Compare(x, y); } } [Test] public void UsesProvidedComparisonOfT() { MyComparison<int> comparer = new MyComparison<int>(); Assert.That(2 + 2, Is.EqualTo(4).Using(new Comparison<int>(comparer.Compare))); Assert.That(comparer.Called, "Comparer was not called"); } class MyComparison<T> { public bool Called; public int Compare(T x, T y) { Called = true; return Comparer<T>.Default.Compare(x, y); } } #if CS_3_0 [Test] public void UsesProvidedLambda_IntArgs() { Assert.That(2 + 2, Is.EqualTo(4).Using<int>( (x, y) => x.CompareTo(y) ) ); } [Test] public void UsesProvidedLambda_StringArgs() { Assert.That("hello", Is.EqualTo("HELLO").Using<string>((x,y) => String.Compare(x, y, true))); } #endif #endif } [TestFixture] public class EqualTest : IExpectException { [Test, ExpectedException(typeof(AssertionException))] public void FailedStringMatchShowsFailurePosition() { Assert.That( "abcdgfe", new EqualConstraint( "abcdefg" ) ); } static readonly string testString = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; [Test, ExpectedException(typeof(AssertionException))] public void LongStringsAreTruncated() { string expected = testString; string actual = testString.Replace('k', 'X'); Assert.That(actual, new EqualConstraint(expected)); } [Test, ExpectedException(typeof(AssertionException))] public void LongStringsAreTruncatedAtBothEndsIfNecessary() { string expected = testString; string actual = testString.Replace('Z', '?'); Assert.That(actual, new EqualConstraint(expected)); } [Test, ExpectedException(typeof(AssertionException))] public void LongStringsAreTruncatedAtFrontEndIfNecessary() { string expected = testString; string actual = testString + "+++++"; Assert.That(actual, new EqualConstraint(expected)); } // [Test] // public void NamedAndUnnamedColorsCompareAsEqual() // { // EqualConstraint.SetConstraintForType(typeof(Color), typeof(SameColorAs)); // Assert.That(System.Drawing.Color.Red, // Is.EqualTo(System.Drawing.Color.FromArgb(255, 0, 0))); // } public void HandleException(Exception ex) { StringReader rdr = new StringReader(ex.Message); /* skip */ rdr.ReadLine(); string expected = rdr.ReadLine(); if (expected != null && expected.Length > 11) expected = expected.Substring(11); string actual = rdr.ReadLine(); if (actual != null && actual.Length > 11) actual = actual.Substring(11); string line = rdr.ReadLine(); Assert.That(line, new NotConstraint(new EqualConstraint(null)), "No caret line displayed"); int caret = line.Substring(11).IndexOf('^'); int minLength = Math.Min(expected.Length, actual.Length); int minMatch = Math.Min(caret, minLength); if (caret != minLength) { if (caret > minLength || expected.Substring(0, minMatch) != actual.Substring(0, minMatch) || expected[caret] == actual[caret]) Assert.Fail("Message Error: Caret does not point at first mismatch..." + Environment.NewLine + ex.Message); } if (expected.Length > 68 || actual.Length > 68 || caret > 68) Assert.Fail("Message Error: Strings are not truncated..." + Environment.NewLine + ex.Message); } public class SameColorAs : Constraint { private Color expectedColor; public SameColorAs(Color expectedColor) { this.expectedColor = expectedColor; } public override bool Matches(object actual) { this.actual = actual; return actual is Color && ((Color)actual).ToArgb() == expectedColor.ToArgb(); } public override void WriteDescriptionTo(MessageWriter writer) { writer.WriteExpectedValue( "same color as " + expectedColor ); } } #if NET_2_0 [Test] public void TestPropertyWithPrivateSetter() { SomeClass obj = new SomeClass(); Assert.That(obj.BrokenProp, Is.EqualTo(string.Empty)); } private class SomeClass { public string BrokenProp { get { return string.Empty; } private set { } } } #endif } [TestFixture] public class EqualityComparerTests { [Test] public void CanCompareArrayContainingSelfToSelf() { object[] array = new object[1]; array[0] = array; NUnitEqualityComparer comparer = new NUnitEqualityComparer(); Assert.True(comparer.ObjectsEqual(array, array)); } } }
//#r "System.dll" //#r "System.Data.dll" using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.Odbc; using System.Data.OleDb; using System.Data.SqlClient; using System.Dynamic; using System.Threading.Tasks; using System.Linq; public class Startup { public async Task<object> Invoke(IDictionary<string, object> parameters) { JsParameterCollection pcol = new JsParameterCollection(parameters); using (DbConnection connection = CreateConnection(pcol.ConnectionString, pcol.ConnectionType)) { try { await connection.OpenAsync(); using (var command = connection.CreateCommand()) { //If there is only one command then execute it on it's own. //Otherwise run all commands as a single transaction. if (pcol.Commands.Count == 1) { var com = pcol.Commands[0]; switch (com.type) { case JsQueryTypes.query: return await ExecuteQuery(command, com); case JsQueryTypes.scalar: return await ExecuteScalar(command, com); case JsQueryTypes.command: return await ExecuteNonQuery(command, com); case JsQueryTypes.procedure: return await ExecuteProcedure(command, com); case JsQueryTypes.procedure_scalar: return await ExecuteProcedureScalar(command, com); default: throw new NotSupportedException("Unsupported type of database command. Only 'query', 'scalar', 'command' and 'procedure' are supported."); } } else { return await ExecuteTransaction(connection, command, pcol.Commands); } } } finally { connection.Close(); } } } private DbConnection CreateConnection(string connectionString, JsConnectionTypes type) { switch (type) { case JsConnectionTypes.oledb: return new OleDbConnection(connectionString); case JsConnectionTypes.odbc: return new OdbcConnection(connectionString); case JsConnectionTypes.sql: return new SqlConnection(connectionString); } throw new NotImplementedException(); } private async Task<object> ExecuteQuery(DbCommand dbCommand, JsCommand jsCommand, object prev = null) { dbCommand.CommandText = jsCommand.query; AddCommandParameters(dbCommand, jsCommand, prev); using (DbDataReader reader = dbCommand.ExecuteReader()) { List<object> results = new List<object>(); do { results.Add(await ParseReaderRow(reader)); } while (await reader.NextResultAsync()); jsCommand.result = results; } UpdateCommandParameters(dbCommand, jsCommand); return jsCommand; } private async Task<object> ExecuteScalar(DbCommand dbCommand, JsCommand jsCommand, object prev = null) { dbCommand.CommandText = jsCommand.query; AddCommandParameters(dbCommand, jsCommand, prev); jsCommand.result = await dbCommand.ExecuteScalarAsync(); UpdateCommandParameters(dbCommand, jsCommand); return jsCommand; } private async Task<object> ExecuteNonQuery(DbCommand dbCommand, JsCommand jsCommand, object prev = null) { dbCommand.CommandText = jsCommand.query; AddCommandParameters(dbCommand, jsCommand, prev); jsCommand.result = await dbCommand.ExecuteNonQueryAsync(); UpdateCommandParameters(dbCommand, jsCommand); return jsCommand; } private async Task<object> ExecuteProcedure(DbCommand dbCommand, JsCommand jsCommand, object prev = null) { dbCommand.CommandText = jsCommand.query; dbCommand.CommandType = CommandType.StoredProcedure; AddCommandParameters(dbCommand, jsCommand, prev); jsCommand.result = await dbCommand.ExecuteNonQueryAsync(); UpdateCommandParameters(dbCommand, jsCommand); return jsCommand; } private async Task<object> ExecuteProcedureScalar(DbCommand dbCommand, JsCommand jsCommand, object prev = null) { dbCommand.CommandText = jsCommand.query; dbCommand.CommandType = CommandType.StoredProcedure; AddCommandParameters(dbCommand, jsCommand, prev); jsCommand.result = await dbCommand.ExecuteScalarAsync(); UpdateCommandParameters(dbCommand, jsCommand); return jsCommand; } private async Task<object> ExecuteTransaction(DbConnection connection, DbCommand dbCommand, List<JsCommand> jsCommands) { DbTransaction transaction = null; try { transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted); dbCommand.Transaction = transaction; object prevResult = null; foreach (JsCommand jsCommand in jsCommands) { switch (jsCommand.type) { case JsQueryTypes.command: await ExecuteNonQuery(dbCommand, jsCommand, prevResult); break; case JsQueryTypes.query: await ExecuteQuery(dbCommand, jsCommand, prevResult); break; case JsQueryTypes.scalar: await ExecuteScalar(dbCommand, jsCommand, prevResult); break; case JsQueryTypes.procedure: await ExecuteProcedure(dbCommand, jsCommand, prevResult); break; case JsQueryTypes.procedure_scalar: await ExecuteProcedureScalar(dbCommand, jsCommand, prevResult); break; default: throw new NotSupportedException("Unsupported type of database command. Only 'query', 'scalar', 'command' and 'procedure' are supported."); } prevResult = jsCommand.result; } transaction.Commit(); } catch { try { transaction.Rollback(); } catch { //Do nothing here; transaction is not active. } throw; } return jsCommands; } private async Task<List<object>> ParseReaderRow(DbDataReader reader) { List<object> rows = new List<object>(); IDataRecord row = reader; while (await reader.ReadAsync()) { var data = new ExpandoObject() as IDictionary<string, object>; var result = new object[row.FieldCount]; row.GetValues(result); for (int i = 0; i < row.FieldCount; i++) { Type type = row.GetFieldType(i); if (result[i] is DBNull) result[i] = null; else if (type == typeof(byte[]) || type == typeof(char[])) result[i] = Convert.ToBase64String((byte[])result[i]); else if (type == typeof(Guid) || type == typeof(DateTime)) result[i] = result[i].ToString(); else if (type == typeof(IDataReader)) result[i] = "<IDataReader>"; data.Add(row.GetName(i), result[i]); } rows.Add(data); } return rows; } private void AddCommandParameters(DbCommand dbCommand, JsCommand jsCommand, object prev = null) { dbCommand.Parameters.Clear(); for (int i = 0; i < jsCommand.@params.Count; i++) { JsCommandParameter cp = jsCommand.@params[i]; DbParameter param = dbCommand.CreateParameter(); param.ParameterName = cp.name; object paramVal = cp.value; //Check if the parameter is a special $prev parameter. //If so, then use the prev argument. if (paramVal != null && paramVal.ToString().ToLower() == "$prev") paramVal = prev; if (paramVal == null) param.Value = DBNull.Value; else param.Value = paramVal; param.Direction = (ParameterDirection)cp.direction; param.IsNullable = cp.isNullable; if (cp.precision != null) param.Precision = (byte)cp.precision; if (cp.scale != null) param.Scale = (byte)cp.scale; if (cp.size != null) param.Size = (byte)cp.size; dbCommand.Parameters.Add(param); } } private void UpdateCommandParameters(DbCommand dbCommand, JsCommand jsCommand) { foreach (DbParameter param in dbCommand.Parameters) { JsCommandParameter jparam = jsCommand.@params.FirstOrDefault(x => x.name == param.ParameterName); if (jparam == null) continue; jparam.value = param.Value; } } } public enum JsQueryTypes { query, scalar, command, procedure, procedure_scalar } public enum JsConnectionTypes { oledb, odbc, sql } public class JsParameterCollection { private IDictionary<string, object> _Raw; public string ConnectionString { get; private set; } public JsConnectionTypes ConnectionType { get; private set; } public List<JsCommand> Commands { get; private set; } public JsParameterCollection(IDictionary<string, object> parameters) { if (parameters == null) throw new ArgumentNullException("parameters"); Commands = new List<JsCommand>(); _Raw = parameters; ParseRawParameters(); } private void ParseRawParameters() { //Extract the connection string. ConnectionString = _Raw["constring"].ToString(); if (string.IsNullOrWhiteSpace(ConnectionString)) throw new ArgumentNullException("constring"); //Extract the connection type (optional) object connectionType = null; _Raw.TryGetValue("connection", out connectionType); if (connectionType == null) connectionType = "oledb"; ConnectionType = (JsConnectionTypes)Enum.Parse(typeof(JsConnectionTypes), connectionType.ToString().ToLower()); //Extract the commands array. dynamic commands = null; _Raw.TryGetValue("commands", out commands); if (commands == null) throw new ArgumentException("The commands field is required."); for (int i = 0; i < commands.Length; i++) { dynamic com = commands[i]; if (!IsPropertyExist(com, "query")) throw new ArgumentException("The query field is required on transaction object."); JsCommand newCom = new JsCommand() { query = com.query }; if (IsPropertyExist(com, "params")) newCom.rawParameters = com.@params; else newCom.rawParameters = new object[] { }; if (IsPropertyExist(com, "type")) newCom.type = (JsQueryTypes)Enum.Parse(typeof(JsQueryTypes), com.type.ToString().ToLower()); else newCom.type = JsQueryTypes.command; Commands.Add(newCom); } } private bool IsPropertyExist(dynamic settings, string name) { if (settings is ExpandoObject) return ((IDictionary<string, object>)settings).ContainsKey(name); return settings.GetType().GetProperty(name) != null; } } public class JsCommand { public string query { get; set; } public JsQueryTypes type { get; set; } public List<JsCommandParameter> @params { get; set; } public object result { get; set; } private object[] _rawParameters; internal object[] rawParameters { get { return _rawParameters; } set { _rawParameters = value; @params = new List<JsCommandParameter>(); //Go through each command parameter and build up the command parameter //array. Work out wether to use named parameters (@myParam, @myOtherParam) //or index named parameters (@p1, @p2 ect). for (int i = 0; i < _rawParameters.Length; i++) { dynamic p = _rawParameters[i]; JsCommandParameter cp = new JsCommandParameter(); //Check if it is an expando object //if it is then extract the name and value from it. if (p is ExpandoObject) { if (IsPropertyExist(p, "name")) cp.name = p.name.ToString(); else cp.name = "p" + (i + 1).ToString(); if (IsPropertyExist(p, "value")) cp.value = p.value; else cp.value = null; try { cp.direction = (int)p.direction; } catch { cp.direction = (int)ParameterDirection.Input; } try { cp.isNullable = (bool)p.isNullable; } catch { cp.isNullable = true; } try { cp.precision = (byte)p.precision; } catch { } try { cp.scale = (byte)p.scale; } catch { } try { cp.size = (byte)p.size; } catch { } } else { cp.name = "p" + (i + 1).ToString(); cp.value = p; } @params.Add(cp); } } } private bool IsPropertyExist(dynamic obj, string name) { if (obj is ExpandoObject) return ((IDictionary<string, object>)obj).ContainsKey(name); return obj.GetType().GetProperty(name) != null; } } public class JsCommandParameter { public string name { get; set; } public object value { get; set; } public int direction { get; set; } public bool isNullable { get; set; } public byte? precision { get; set; } public byte? scale { get; set; } public byte? size { get; set; } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ServiceModel.MsmqIntegration.MsmqMessage_1.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.MsmqIntegration { sealed public partial class MsmqMessage<T> { #region Methods and constructors public MsmqMessage(T body) { } #endregion #region Properties and indexers public Nullable<System.Messaging.AcknowledgeTypes> AcknowledgeType { get { return default(Nullable<System.Messaging.AcknowledgeTypes>); } set { } } public Nullable<System.Messaging.Acknowledgment> Acknowledgment { get { return default(Nullable<System.Messaging.Acknowledgment>); } } public Uri AdministrationQueue { get { return default(Uri); } set { } } public Nullable<int> AppSpecific { get { return default(Nullable<int>); } set { } } public Nullable<DateTime> ArrivedTime { get { return default(Nullable<DateTime>); } } public Nullable<bool> Authenticated { get { return default(Nullable<bool>); } } public T Body { get { Contract.Ensures(Contract.Result<T>() != null); return default(T); } set { } } public Nullable<int> BodyType { get { return default(Nullable<int>); } set { } } public string CorrelationId { get { return default(string); } set { } } public Uri DestinationQueue { get { return default(Uri); } } public byte[] Extension { get { return default(byte[]); } set { } } public string Id { get { return default(string); } } public string Label { get { return default(string); } set { } } public Nullable<System.Messaging.MessageType> MessageType { get { return default(Nullable<System.Messaging.MessageType>); } } public Nullable<System.Messaging.MessagePriority> Priority { get { return default(Nullable<System.Messaging.MessagePriority>); } set { } } public Uri ResponseQueue { get { return default(Uri); } set { } } public byte[] SenderId { get { return default(byte[]); } } public Nullable<DateTime> SentTime { get { return default(Nullable<DateTime>); } } public Nullable<TimeSpan> TimeToReachQueue { get { return default(Nullable<TimeSpan>); } set { } } #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: The core libraries for the DotSpatial project. // // ******************************************************************************************************** // The contents of this file are subject to the Lesser GPL // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is DotSpatial.dll for the DotSpatial project // // The Initial Developer of this Original Code is Ted Dunsford. Created in September, 2007. // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Diagnostics; using DotSpatial.Data; namespace DotSpatial.Symbology { /// <summary> /// This extends the ChangeEventList by providing methods that allow access by an object Key, and will pass /// </summary> public class LayerEventList<T> : ChangeEventList<T>, ILayerEventList<T>, IDisposable, IDisposeLock where T : class, ILayer { #region Events /// <summary> /// Occurs if the maps should zoom to this layer. /// </summary> public event EventHandler<EnvelopeArgs> ZoomToLayer; /// <summary> /// Occurs when one of the layers in this collection changes visibility. /// </summary> public event EventHandler LayerVisibleChanged; /// <summary> /// Occurs when a layer is added to this item. /// </summary> public event EventHandler<LayerEventArgs> LayerAdded; /// <summary> /// Occurs when a layer is moved. /// </summary> public event EventHandler<LayerMovedEventArgs> LayerMoved; /// <summary> /// Occurs when a layer is removed from this item. /// </summary> public event EventHandler<LayerEventArgs> LayerRemoved; /// <summary> /// Occurs immediately after a layer is selected. /// </summary> public event EventHandler<LayerSelectedEventArgs> LayerSelected; /// <summary> /// Occurs when the selection on a feature layer changes. /// </summary> public event EventHandler<FeatureLayerSelectionEventArgs> SelectionChanging; /// <summary> /// Occurs after the selection has changed, and all the layers have had their selection information updated. /// </summary> public event EventHandler SelectionChanged; #endregion #region Private Variables private int _disposeLockCount; private bool _isDisposed; private bool _isInitialized; // True if layers already existed before a member change private ILayer _selectedLayer; #endregion #region Constructors #endregion #region Methods /// <summary> /// This selects the layer with the specified integer index /// </summary> /// <param name="index">THe zero based integer index</param> public void SelectLayer(int index) { SelectedLayer = this[index]; } #endregion #region Properties /// <summary> /// Gets the currently selected layer in this collection. /// </summary> public ILayer SelectedLayer { get { return _selectedLayer; } set { _selectedLayer = value; if (value != null) { value.IsSelected = true; OnLayerSelected(value, true); } } } /// <summary> /// The envelope that contains all of the layers for this data frame. Essentially this would be /// the extents to use if you want to zoom to the world view. /// </summary> public virtual Extent Extent { get { Extent env = new Extent(); if (Count == 0) return env; foreach (T lyr in this) { env.ExpandToInclude(lyr.Extent); } return env; } } #endregion /// <summary> /// Gets a value indicating whether dispose has already been called on this object. /// </summary> public bool IsDisposed { get { return _isDisposed; } } #region IDisposable Members /// <summary> /// Standard Dispose implementation since layers are now disposable. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region IDisposeLock Members /// <summary> /// Adds one request to prevent disposal of this object and its children. /// </summary> public void LockDispose() { _disposeLockCount++; } /// <summary> /// Gets a value indicating whether there are requests to prevent disposal of this object. /// </summary> public bool IsDisposeLocked { get { return _disposeLockCount > 0; } } /// <summary> /// Removes one request to prevent disposal of this object and its children. /// </summary> public void UnlockDispose() { _disposeLockCount--; } #endregion /// <summary> /// Extends the event listeners to include events like ZoomToLayer and VisibleChanged /// </summary> /// <param name="item"></param> protected override void OnInclude(T item) { item.LockDispose(); item.ZoomToLayer += Layer_ZoomToLayer; item.VisibleChanged += Layer_VisibleChanged; item.FinishedLoading += ItemFinishedLoading; item.SelectionChanged += SelectableSelectionChanged; item.LayerSelected += ItemLayerSelected; base.OnInclude(item); OnListChanged(); } private void ItemLayerSelected(object sender, LayerSelectedEventArgs e) { if (e.IsSelected) { SelectedLayer = e.Layer; } } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SelectableSelectionChanged(object sender, EventArgs e) { OnSelectionChanged(); } /// <summary> /// Occurs when the selection is changed /// </summary> protected virtual void OnSelectionChanged() { if (SelectionChanged != null) SelectionChanged(this, EventArgs.Empty); } /// <summary> /// Ensures that we re-draw the content when inserting new layers /// </summary> /// <param name="item"></param> protected override void OnIncludeComplete(T item) { OnLayerAdded(this, new LayerEventArgs(item)); } protected override void OnMoved(T item, int newPosition) { base.OnListChanged(); OnLayerMoved(this, new LayerMovedEventArgs(item, newPosition)); } /// <summary> /// Removes the extended event listeners once a layer is removed from this list. /// </summary> /// <param name="item"></param> protected override void OnExclude(T item) { item.UnlockDispose(); item.ZoomToLayer -= Layer_ZoomToLayer; item.VisibleChanged -= Layer_VisibleChanged; item.FinishedLoading -= ItemFinishedLoading; item.SelectionChanged -= SelectableSelectionChanged; item.LayerSelected -= ItemLayerSelected; //if the layer being removed is selected - //ensure that the SelectedLayer property is cleared if (item.Equals(SelectedLayer)) { SelectedLayer = null; } base.OnExclude(item); OnLayerRemoved(item); OnListChanged(); if (!item.IsDisposeLocked) { item.Dispose(); } } /// <summary> /// Fires the LayerMoved event. /// </summary> /// <param name="sender">The layer that was moved.</param> /// <param name="e">LayerEventArgs</param> protected virtual void OnLayerMoved(object sender, LayerMovedEventArgs e) { if (EventsSuspended) return; var h = LayerMoved; if (h != null) h(sender, e); } /// <summary> /// Fires the LayerRemoved event. /// </summary> /// <param name="item"></param> protected virtual void OnLayerRemoved(T item) { if (EventsSuspended) return; var h = LayerRemoved; if (h != null) h(this, new LayerEventArgs(item)); } /// <summary> /// Fires the LayerSelected event and adjusts the selected state of the layer. /// </summary> /// <param name="layer">The layer to select</param> /// <param name="selected">Boolean, true if the specified layer is selected</param> protected virtual void OnLayerSelected(ILayer layer, bool selected) { var h = LayerSelected; if (h != null) { h(this, new LayerSelectedEventArgs(layer, selected)); } } /// <summary> /// Fires the ItemChanged event and the MembersChanged event and resets any cached lists /// </summary> protected override void OnListChanged() { if (EventsSuspended) { base.OnListChanged(); return; } if (_isInitialized == false) { if (Count > 0) { _isInitialized = true; } } else { if (Count == 0) { _isInitialized = false; } } // reset cached extra lists if any base.OnListChanged(); } /// <summary> /// Fires the ZoomToLayer method when one of the layers fires its ZoomTo event /// </summary> /// <param name="sender">The layer to zoom to</param> /// <param name="e">The extent of the layer</param> protected virtual void OnZoomToLayer(object sender, EnvelopeArgs e) { // Just forward the event if (ZoomToLayer != null) ZoomToLayer(sender, e); } /// <summary> /// Fires the LayerAdded event /// </summary> /// <param name="sender">The layer that was added</param> /// <param name="e">LayerEventArgs</param> protected virtual void OnLayerAdded(object sender, LayerEventArgs e) { if (EventsSuspended) return; var h = LayerAdded; if (h != null) h(sender, e); } /// <summary> /// Fires the selection changed event /// </summary> /// <param name="sender">the object sender of the event</param> /// <param name="args">The FeatureLayerSelectionEventArgs of the layer</param> protected virtual void OnSelectionChanging(object sender, FeatureLayerSelectionEventArgs args) { if (SelectionChanging != null) SelectionChanging(sender, args); } private void ItemFinishedLoading(object sender, EventArgs e) { OnLayerAdded(this, new LayerEventArgs(sender as ILayer)); } private void Layer_VisibleChanged(object sender, EventArgs e) { if (LayerVisibleChanged != null) LayerVisibleChanged(sender, e); } private void Layer_ZoomToLayer(object sender, EnvelopeArgs e) { OnZoomToLayer(sender, e); } /// <summary> /// Finalizes an instance of the LayerEventList class. /// </summary> ~LayerEventList() { Dispose(false); } /// <summary> /// Overrides the dispose behavior. If disposeManagedMemory objects is true, then managed objects /// should be set to null, effectively removing reference counts. If it is false, then only /// unmanaged memory objects should be removed. /// </summary> /// <param name="disposeManagedMemory">Boolean, true if managed memory objects should be set to null, and /// if the Dispose method should be called on contained objects.</param> protected virtual void Dispose(bool disposeManagedMemory) { if (!_isDisposed) { // In debug mode, try to find any calls to dispose that will conflict with locks. Debug.Assert(_disposeLockCount == 0); if (disposeManagedMemory) { foreach (var layer in this) { if (layer != null) { layer.UnlockDispose(); // indicate this group no longer needs to lock the layer. if (!layer.IsDisposeLocked) layer.Dispose(); } } } } _isDisposed = true; } } }
using System.Threading.Tasks; using LockStockAuth.Auth.Managers; using LockStockAuth.Auth.Models; namespace LockStockAuth.Auth.Controllers { [Authorize] public class ManageController : Controller { private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public ManageController() { } public ManageController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } // // GET: /Manage/Index public async Task<ActionResult> Index(ManageMessageId? message) { ViewBag.StatusMessage = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var userId = User.Identity.GetUserId(); var model = new IndexViewModel { HasPassword = HasPassword(), PhoneNumber = await UserManager.GetPhoneNumberAsync(userId), TwoFactor = await UserManager.GetTwoFactorEnabledAsync(userId), Logins = await UserManager.GetLoginsAsync(userId), BrowserRemembered = await AuthenticationManager.TwoFactorBrowserRememberedAsync(userId) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> RemoveLogin(string loginProvider, string providerKey) { ManageMessageId? message; var result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(loginProvider, providerKey)); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } message = ManageMessageId.RemoveLoginSuccess; } else { message = ManageMessageId.Error; } return RedirectToAction("ManageLogins", new { Message = message }); } // // GET: /Manage/AddPhoneNumber public ActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number); if (UserManager.SmsService != null) { var message = new IdentityMessage { Destination = model.Number, Body = "Your security code is: " + code }; await UserManager.SmsService.SendAsync(message); } return RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> EnableTwoFactorAuthentication() { await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true); var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> DisableTwoFactorAuthentication() { await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false); var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", "Manage"); } // // GET: /Manage/VerifyPhoneNumber public async Task<ActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), phoneNumber); // Send an SMS through the SMS provider to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = await UserManager.ChangePhoneNumberAsync(User.Identity.GetUserId(), model.PhoneNumber, model.Code); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.AddPhoneSuccess }); } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "Failed to verify phone"); return View(model); } // // POST: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> RemovePhoneNumber() { var result = await UserManager.SetPhoneNumberAsync(User.Identity.GetUserId(), null); if (!result.Succeeded) { return RedirectToAction("Index", new { Message = ManageMessageId.Error }); } var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.RemovePhoneSuccess }); } // // GET: /Manage/ChangePassword public ActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } // // GET: /Manage/SetPassword public ActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> SetPassword(SetPasswordViewModel model) { if (ModelState.IsValid) { var result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); if (result.Succeeded) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user != null) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); } return RedirectToAction("Index", new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Manage/ManageLogins public async Task<ActionResult> ManageLogins(ManageMessageId? message) { ViewBag.StatusMessage = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user == null) { return View("Error"); } var userLogins = await UserManager.GetLoginsAsync(User.Identity.GetUserId()); var otherLogins = AuthenticationManager.GetExternalAuthenticationTypes().Where(auth => userLogins.All(ul => auth.AuthenticationType != ul.LoginProvider)).ToList(); ViewBag.ShowRemoveButton = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public ActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user return new AccountController.ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), User.Identity.GetUserId()); } // // GET: /Manage/LinkLoginCallback public async Task<ActionResult> LinkLoginCallback() { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId()); if (loginInfo == null) { return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } var result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), loginInfo.Login); return result.Succeeded ? RedirectToAction("ManageLogins") : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error }); } protected override void Dispose(bool disposing) { if (disposing && _userManager != null) { _userManager.Dispose(); _userManager = null; } base.Dispose(disposing); } #region Helpers // Used for XSRF protection when adding external logins private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private bool HasPassword() { var user = UserManager.FindById(User.Identity.GetUserId()); if (user != null) { return user.PasswordHash != null; } return false; } private bool HasPhoneNumber() { var user = UserManager.FindById(User.Identity.GetUserId()); if (user != null) { return user.PhoneNumber != null; } return false; } public enum ManageMessageId { AddPhoneSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } #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 Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace System.IO { internal sealed partial class Win32FileSystem : FileSystem { internal const int GENERIC_READ = unchecked((int)0x80000000); public override int MaxPath { get { return Interop.Kernel32.MAX_PATH; } } public override int MaxDirectoryPath { get { return Interop.Kernel32.MAX_DIRECTORY_PATH; } } public override void CopyFile(string sourceFullPath, string destFullPath, bool overwrite) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); int errorCode = Interop.Kernel32.CopyFile(sourceFullPath, destFullPath, !overwrite); if (errorCode != Interop.Errors.ERROR_SUCCESS) { string fileName = destFullPath; if (errorCode != Interop.Errors.ERROR_FILE_EXISTS) { // For a number of error codes (sharing violation, path // not found, etc) we don't know if the problem was with // the source or dest file. Try reading the source file. using (SafeFileHandle handle = Interop.Kernel32.UnsafeCreateFile(sourceFullPath, GENERIC_READ, FileShare.Read, ref secAttrs, FileMode.Open, 0, IntPtr.Zero)) { if (handle.IsInvalid) fileName = sourceFullPath; } if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) { if (DirectoryExists(destFullPath)) throw new IOException(SR.Format(SR.Arg_FileIsDirectory_Name, destFullPath), Interop.Errors.ERROR_ACCESS_DENIED); } } throw Win32Marshal.GetExceptionForWin32Error(errorCode, fileName); } } public override void ReplaceFile(string sourceFullPath, string destFullPath, string destBackupFullPath, bool ignoreMetadataErrors) { int flags = Interop.Kernel32.REPLACEFILE_WRITE_THROUGH; if (ignoreMetadataErrors) { flags |= Interop.Kernel32.REPLACEFILE_IGNORE_MERGE_ERRORS; } if (!Interop.Kernel32.ReplaceFile(destFullPath, sourceFullPath, destBackupFullPath, flags, IntPtr.Zero, IntPtr.Zero)) { throw Win32Marshal.GetExceptionForWin32Error(Marshal.GetLastWin32Error()); } } [System.Security.SecuritySafeCritical] public override void CreateDirectory(string fullPath) { if (PathInternal.IsDirectoryTooLong(fullPath)) throw new PathTooLongException(SR.IO_PathTooLong); // We can save a bunch of work if the directory we want to create already exists. This also // saves us in the case where sub paths are inaccessible (due to ERROR_ACCESS_DENIED) but the // final path is accessible and the directory already exists. For example, consider trying // to create c:\Foo\Bar\Baz, where everything already exists but ACLS prevent access to c:\Foo // and c:\Foo\Bar. In that case, this code will think it needs to create c:\Foo, and c:\Foo\Bar // and fail to due so, causing an exception to be thrown. This is not what we want. if (DirectoryExists(fullPath)) return; List<string> stackDir = new List<string>(); // Attempt to figure out which directories don't exist, and only // create the ones we need. Note that InternalExists may fail due // to Win32 ACL's preventing us from seeing a directory, and this // isn't threadsafe. bool somepathexists = false; int length = fullPath.Length; // We need to trim the trailing slash or the code will try to create 2 directories of the same name. if (length >= 2 && PathHelpers.EndsInDirectorySeparator(fullPath)) length--; int lengthRoot = PathInternal.GetRootLength(fullPath); if (length > lengthRoot) { // Special case root (fullpath = X:\\) int i = length - 1; while (i >= lengthRoot && !somepathexists) { String dir = fullPath.Substring(0, i + 1); if (!DirectoryExists(dir)) // Create only the ones missing stackDir.Add(dir); else somepathexists = true; while (i > lengthRoot && !PathInternal.IsDirectorySeparator(fullPath[i])) i--; i--; } } int count = stackDir.Count; // If we were passed a DirectorySecurity, convert it to a security // descriptor and set it in he call to CreateDirectory. Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); bool r = true; int firstError = 0; String errorString = fullPath; // If all the security checks succeeded create all the directories while (stackDir.Count > 0) { String name = stackDir[stackDir.Count - 1]; stackDir.RemoveAt(stackDir.Count - 1); r = Interop.Kernel32.CreateDirectory(name, ref secAttrs); if (!r && (firstError == 0)) { int currentError = Marshal.GetLastWin32Error(); // While we tried to avoid creating directories that don't // exist above, there are at least two cases that will // cause us to see ERROR_ALREADY_EXISTS here. InternalExists // can fail because we didn't have permission to the // directory. Secondly, another thread or process could // create the directory between the time we check and the // time we try using the directory. Thirdly, it could // fail because the target does exist, but is a file. if (currentError != Interop.Errors.ERROR_ALREADY_EXISTS) firstError = currentError; else { // If there's a file in this directory's place, or if we have ERROR_ACCESS_DENIED when checking if the directory already exists throw. if (File.InternalExists(name) || (!DirectoryExists(name, out currentError) && currentError == Interop.Errors.ERROR_ACCESS_DENIED)) { firstError = currentError; errorString = name; } } } } // We need this check to mask OS differences // Handle CreateDirectory("X:\\") when X: doesn't exist. Similarly for n/w paths. if ((count == 0) && !somepathexists) { String root = Directory.InternalGetDirectoryRoot(fullPath); if (!DirectoryExists(root)) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, root); return; } // Only throw an exception if creating the exact directory we // wanted failed to work correctly. if (!r && (firstError != 0)) throw Win32Marshal.GetExceptionForWin32Error(firstError, errorString); } public override void DeleteFile(System.String fullPath) { bool r = Interop.Kernel32.DeleteFile(fullPath); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) return; else throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override bool DirectoryExists(string fullPath) { int lastError = Interop.Errors.ERROR_SUCCESS; return DirectoryExists(fullPath, out lastError); } private bool DirectoryExists(String path, out int lastError) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); lastError = FillAttributeInfo(path, ref data, false, true); return (lastError == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) != 0); } public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { return Win32FileSystemEnumerableFactory.CreateFileNameIterator(fullPath, fullPath, searchPattern, (searchTarget & SearchTarget.Files) == SearchTarget.Files, (searchTarget & SearchTarget.Directories) == SearchTarget.Directories, searchOption); } public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget) { switch (searchTarget) { case SearchTarget.Directories: return Win32FileSystemEnumerableFactory.CreateDirectoryInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Files: return Win32FileSystemEnumerableFactory.CreateFileInfoIterator(fullPath, fullPath, searchPattern, searchOption); case SearchTarget.Both: return Win32FileSystemEnumerableFactory.CreateFileSystemInfoIterator(fullPath, fullPath, searchPattern, searchOption); default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(searchTarget)); } } // Returns 0 on success, otherwise a Win32 error code. Note that // classes should use -1 as the uninitialized state for dataInitialized. [System.Security.SecurityCritical] // auto-generated internal static int FillAttributeInfo(String path, ref Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data, bool tryagain, bool returnErrorOnNotFound) { int errorCode = 0; if (tryagain) // someone has a handle to the file open, or other error { Interop.Kernel32.WIN32_FIND_DATA findData; findData = new Interop.Kernel32.WIN32_FIND_DATA(); // Remove trailing slash since this can cause grief to FindFirstFile. You will get an invalid argument error String tempPath = path.TrimEnd(PathHelpers.DirectorySeparatorChars); // For removable media drives, normally the OS will pop up a dialog requesting insertion // of the relevant media (CD, floppy, memory card, etc.). We don't want this prompt so we // set SEM_FAILCRITICALERRORS to suppress it. // // Note that said dialog only shows once the relevant filesystem has been loaded, which // does not happen until actual media is accessed at least once since booting. uint oldMode; bool success = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { bool error = false; SafeFindHandle handle = Interop.Kernel32.FindFirstFile(tempPath, ref findData); try { if (handle.IsInvalid) { error = true; errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND || errorCode == Interop.Errors.ERROR_NOT_READY) // Removable media not inserted { if (!returnErrorOnNotFound) { // Return default value for backward compatibility errorCode = 0; data.fileAttributes = -1; } } return errorCode; } } finally { // Close the Win32 handle try { handle.Dispose(); } catch { // if we're already returning an error, don't throw another one. if (!error) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } } } finally { if (success) Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } // Copy the information to data data.PopulateFrom(ref findData); } else { // For floppy drives, normally the OS will pop up a dialog saying // there is no disk in drive A:, please insert one. We don't want that. // SetErrorMode will let us disable this, but we should set the error // mode back, since this may have wide-ranging effects. bool success = false; uint oldMode; bool errorModeSuccess = Interop.Kernel32.SetThreadErrorMode(Interop.Kernel32.SEM_FAILCRITICALERRORS, out oldMode); try { success = Interop.Kernel32.GetFileAttributesEx(path, Interop.Kernel32.GET_FILEEX_INFO_LEVELS.GetFileExInfoStandard, ref data); } finally { if (errorModeSuccess) Interop.Kernel32.SetThreadErrorMode(oldMode, out oldMode); } if (!success) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND && errorCode != Interop.Errors.ERROR_NOT_READY) // floppy device not ready { // In case someone latched onto the file. Take the perf hit only for failure return FillAttributeInfo(path, ref data, true, returnErrorOnNotFound); } else { if (!returnErrorOnNotFound) { // Return default value for backward compatibility errorCode = 0; data.fileAttributes = -1; } } } } return errorCode; } public override bool FileExists(System.String fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, true); return (errorCode == 0) && (data.fileAttributes != -1) && ((data.fileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY) == 0); } public override FileAttributes GetAttributes(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, true); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); return (FileAttributes)data.fileAttributes; } public override string GetCurrentDirectory() { StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH + 1); if (Interop.Kernel32.GetCurrentDirectory(sb.Capacity, sb) == 0) throw Win32Marshal.GetExceptionForLastWin32Error(); String currentDirectory = sb.ToString(); // Note that if we have somehow put our command prompt into short // file name mode (i.e. by running edlin or a DOS grep, etc), then // this will return a short file name. if (currentDirectory.IndexOf('~') >= 0) { int r = Interop.Kernel32.GetLongPathName(currentDirectory, sb, sb.Capacity); if (r == 0 || r >= Interop.Kernel32.MAX_PATH) { int errorCode = Marshal.GetLastWin32Error(); if (r >= Interop.Kernel32.MAX_PATH) errorCode = Interop.Errors.ERROR_FILENAME_EXCED_RANGE; if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND && errorCode != Interop.Errors.ERROR_INVALID_FUNCTION && // by design - enough said. errorCode != Interop.Errors.ERROR_ACCESS_DENIED) throw Win32Marshal.GetExceptionForWin32Error(errorCode); } currentDirectory = sb.ToString(); } StringBuilderCache.Release(sb); return currentDirectory; } public override DateTimeOffset GetCreationTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftCreationTimeHigh) << 32) | ((long)data.ftCreationTimeLow); return DateTimeOffset.FromFileTime(dt); } public override IFileSystemObject GetFileSystemInfo(string fullPath, bool asDirectory) { return asDirectory ? (IFileSystemObject)new DirectoryInfo(fullPath, null) : (IFileSystemObject)new FileInfo(fullPath, null); } public override DateTimeOffset GetLastAccessTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)(data.ftLastAccessTimeHigh) << 32) | ((long)data.ftLastAccessTimeLow); return DateTimeOffset.FromFileTime(dt); } public override DateTimeOffset GetLastWriteTime(string fullPath) { Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, false); if (errorCode != 0) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); long dt = ((long)data.ftLastWriteTimeHigh << 32) | ((long)data.ftLastWriteTimeLow); return DateTimeOffset.FromFileTime(dt); } public override void MoveDirectory(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) throw Win32Marshal.GetExceptionForWin32Error(Interop.Errors.ERROR_PATH_NOT_FOUND, sourceFullPath); // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) // WinNT throws IOException. This check is for Win9x. We can't change it for backcomp. throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, sourceFullPath), Win32Marshal.MakeHRFromErrorCode(errorCode)); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } public override void MoveFile(string sourceFullPath, string destFullPath) { if (!Interop.Kernel32.MoveFile(sourceFullPath, destFullPath)) { throw Win32Marshal.GetExceptionForLastWin32Error(); } } public override FileStream Open(string fullPath, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) { return new FileStream(fullPath, mode, access, share, bufferSize, options); } [System.Security.SecurityCritical] private static SafeFileHandle OpenHandle(string fullPath, bool asDirectory) { String root = fullPath.Substring(0, PathInternal.GetRootLength(fullPath)); if (root == fullPath && root[1] == Path.VolumeSeparatorChar) { // intentionally not fullpath, most upstack public APIs expose this as path. throw new ArgumentException(SR.Arg_PathIsVolume, "path"); } Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); SafeFileHandle handle = Interop.Kernel32.SafeCreateFile( fullPath, (int)Interop.Kernel32.GenericOperations.GENERIC_WRITE, FileShare.ReadWrite | FileShare.Delete, ref secAttrs, FileMode.Open, asDirectory ? (int)Interop.Kernel32.FileOperations.FILE_FLAG_BACKUP_SEMANTICS : (int)FileOptions.None, IntPtr.Zero ); if (handle.IsInvalid) { int errorCode = Marshal.GetLastWin32Error(); // NT5 oddity - when trying to open "C:\" as a File, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. if (!asDirectory && errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && fullPath.Equals(Directory.GetDirectoryRoot(fullPath))) errorCode = Interop.Errors.ERROR_ACCESS_DENIED; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } return handle; } public override void RemoveDirectory(string fullPath, bool recursive) { // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA data = new Interop.Kernel32.WIN32_FILE_ATTRIBUTE_DATA(); int errorCode = FillAttributeInfo(fullPath, ref data, false, true); if (errorCode != 0) { // Ensure we throw a DirectoryNotFoundException. if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } if (((FileAttributes)data.fileAttributes & FileAttributes.ReparsePoint) != 0) recursive = false; // We want extended syntax so we can delete "extended" subdirectories and files // (most notably ones with trailing whitespace or periods) RemoveDirectoryHelper(PathInternal.EnsureExtendedPrefix(fullPath), recursive, true); } [System.Security.SecurityCritical] // auto-generated private static void RemoveDirectoryHelper(string fullPath, bool recursive, bool throwOnTopLevelDirectoryNotFound) { bool r; int errorCode; Exception ex = null; // Do not recursively delete through reparse points. Perhaps in a // future version we will add a new flag to control this behavior, // but for now we're much safer if we err on the conservative side. // This applies to symbolic links and mount points. // Note the logic to check whether fullPath is a reparse point is // in Delete(String, String, bool), and will set "recursive" to false. // Note that Win32's DeleteFile and RemoveDirectory will just delete // the reparse point itself. if (recursive) { Interop.Kernel32.WIN32_FIND_DATA data = new Interop.Kernel32.WIN32_FIND_DATA(); // Open a Find handle using (SafeFindHandle hnd = Interop.Kernel32.FindFirstFile(Directory.EnsureTrailingDirectorySeparator(fullPath) + "*", ref data)) { if (hnd.IsInvalid) throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); do { bool isDir = (0 != (data.dwFileAttributes & Interop.Kernel32.FileAttributes.FILE_ATTRIBUTE_DIRECTORY)); if (isDir) { // Skip ".", "..". if (data.cFileName.Equals(".") || data.cFileName.Equals("..")) continue; // Recurse for all directories, unless they are // reparse points. Do not follow mount points nor // symbolic links, but do delete the reparse point // itself. bool shouldRecurse = (0 == (data.dwFileAttributes & (int)FileAttributes.ReparsePoint)); if (shouldRecurse) { string newFullPath = Path.Combine(fullPath, data.cFileName); try { RemoveDirectoryHelper(newFullPath, recursive, false); } catch (Exception e) { if (ex == null) ex = e; } } else { // Check to see if this is a mount point, and // unmount it. if (data.dwReserved0 == Interop.Kernel32.IOReparseOptions.IO_REPARSE_TAG_MOUNT_POINT) { // Use full path plus a trailing '\' String mountPoint = Path.Combine(fullPath, data.cFileName + PathHelpers.DirectorySeparatorCharAsString); if (!Interop.Kernel32.DeleteVolumeMountPoint(mountPoint)) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_SUCCESS && errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } // RemoveDirectory on a symbolic link will // remove the link itself. String reparsePoint = Path.Combine(fullPath, data.cFileName); r = Interop.Kernel32.RemoveDirectory(reparsePoint); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_PATH_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } } else { String fileName = Path.Combine(fullPath, data.cFileName); r = Interop.Kernel32.DeleteFile(fileName); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode != Interop.Errors.ERROR_FILE_NOT_FOUND) { try { throw Win32Marshal.GetExceptionForWin32Error(errorCode, data.cFileName); } catch (Exception e) { if (ex == null) ex = e; } } } } } while (Interop.Kernel32.FindNextFile(hnd, ref data)); // Make sure we quit with a sensible error. errorCode = Marshal.GetLastWin32Error(); } if (ex != null) throw ex; if (errorCode != 0 && errorCode != Interop.Errors.ERROR_NO_MORE_FILES) throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } r = Interop.Kernel32.RemoveDirectory(fullPath); if (!r) { errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) // A dubious error code. errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; // This check was originally put in for Win9x (unfortunately without special casing it to be for Win9x only). We can't change the NT codepath now for backcomp reasons. if (errorCode == Interop.Errors.ERROR_ACCESS_DENIED) throw new IOException(SR.Format(SR.UnauthorizedAccess_IODenied_Path, fullPath)); // don't throw the DirectoryNotFoundException since this is a subdir and // there could be a race condition between two Directory.Delete callers if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && !throwOnTopLevelDirectoryNotFound) return; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetAttributes(string fullPath, FileAttributes attributes) { SetAttributesInternal(fullPath, attributes); } private static void SetAttributesInternal(string fullPath, FileAttributes attributes) { bool r = Interop.Kernel32.SetFileAttributes(fullPath, (int)attributes); if (!r) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) throw new ArgumentException(SR.Arg_InvalidFileAttrs, nameof(attributes)); throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetCreationTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetCreationTimeInternal(fullPath, time, asDirectory); } private static void SetCreationTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, creationTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetCurrentDirectory(string fullPath) { if (!Interop.Kernel32.SetCurrentDirectory(fullPath)) { // If path doesn't exist, this sets last error to 2 (File // not Found). LEGACY: This may potentially have worked correctly // on Win9x, maybe. int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND) errorCode = Interop.Errors.ERROR_PATH_NOT_FOUND; throw Win32Marshal.GetExceptionForWin32Error(errorCode, fullPath); } } public override void SetLastAccessTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastAccessTimeInternal(fullPath, time, asDirectory); } private static void SetLastAccessTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastAccessTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override void SetLastWriteTime(string fullPath, DateTimeOffset time, bool asDirectory) { SetLastWriteTimeInternal(fullPath, time, asDirectory); } private static void SetLastWriteTimeInternal(string fullPath, DateTimeOffset time, bool asDirectory) { using (SafeFileHandle handle = OpenHandle(fullPath, asDirectory)) { bool r = Interop.Kernel32.SetFileTime(handle, lastWriteTime: time.ToFileTime()); if (!r) { throw Win32Marshal.GetExceptionForLastWin32Error(fullPath); } } } public override string[] GetLogicalDrives() { return DriveInfoInternal.GetLogicalDrives(); } } }
/* csvorbis * Copyright (C) 2000 ymnk, JCraft,Inc. * * Written by: 2000 ymnk<ymnk@jcraft.com> * Ported to C# from JOrbis by: Mark Crichton <crichton@gimp.org> * * Thanks go to the JOrbis team, for licencing the code under the * LGPL, making my job a lot easier. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Library 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 Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ using System; using System.Text; using csogg; namespace csvorbis { public class Info { private static int OV_EBADPACKET=-136; private static int OV_ENOTAUDIO=-135; private static string _vorbis="vorbis"; private static int VI_TIMEB=1; private static int VI_FLOORB=2; private static int VI_RESB=3; private static int VI_MAPB=1; private static int VI_WINDOWB=1; public int version; public int channels; public int rate; // The below bitrate declarations are *hints*. // Combinations of the three values carry the following implications: // // all three set to the same value: // implies a fixed rate bitstream // only nominal set: // implies a VBR stream that averages the nominal bitrate. No hard // upper/lower limit // upper and or lower set: // implies a VBR bitstream that obeys the bitrate limits. nominal // may also be set to give a nominal rate. // none set: // the coder does not care to speculate. internal int bitrate_upper; internal int bitrate_nominal; internal int bitrate_lower; // Vorbis supports only short and long blocks, but allows the // encoder to choose the sizes internal int[] blocksizes=new int[2]; // modes are the primary means of supporting on-the-fly different // blocksizes, different channel mappings (LR or mid-side), // different residue backends, etc. Each mode consists of a // blocksize flag and a mapping (along with the mapping setup internal int modes; internal int maps; internal int times; internal int floors; internal int residues; internal int books; internal int psys; // encode only internal InfoMode[] mode_param=null; internal int[] map_type=null; internal Object[] map_param=null; internal int[] time_type=null; internal Object[] time_param=null; internal int[] floor_type=null; internal Object[] floor_param=null; internal int[] residue_type=null; internal Object[] residue_param=null; internal StaticCodeBook[] book_param=null; internal PsyInfo[] psy_param=new PsyInfo[64]; // encode only // for block long/sort tuning; encode only //internal int envelopesa; //internal float preecho_thresh; //internal float preecho_clamp; // used by synthesis, which has a full, alloced vi public void init() { rate=0; //memset(vi,0,sizeof(vorbis_info)); } public void clear() { for(int i=0;i<modes;i++){ mode_param[i]=null; } mode_param=null; for(int i=0;i<maps;i++) { // unpack does the range checking FuncMapping.mapping_P[map_type[i]].free_info(map_param[i]); } map_param=null; for(int i=0;i<times;i++) { // unpack does the range checking FuncTime.time_P[time_type[i]].free_info(time_param[i]); } time_param=null; for(int i=0;i<floors;i++) { // unpack does the range checking FuncFloor.floor_P[floor_type[i]].free_info(floor_param[i]); } floor_param=null; for(int i=0;i<residues;i++) { // unpack does the range checking FuncResidue.residue_P[residue_type[i]].free_info(residue_param[i]); } residue_param=null; // the static codebooks *are* freed if you call info_clear, because // decode side does alloc a 'static' codebook. Calling clear on the // full codebook does not clear the static codebook (that's our // responsibility) for(int i=0;i<books;i++) { // just in case the decoder pre-cleared to save space if(book_param[i]!=null) { book_param[i].clear(); book_param[i]=null; } } //if(vi->book_param)free(vi->book_param); book_param=null; for(int i=0;i<psys;i++) { psy_param[i].free(); } //if(vi->psy_param)free(vi->psy_param); //memset(vi,0,sizeof(vorbis_info)); } // Header packing/unpacking int unpack_info(csBuffer opb) { version=opb.read(32); if(version!=0)return(-1); channels=opb.read(8); rate=opb.read(32); bitrate_upper=opb.read(32); bitrate_nominal=opb.read(32); bitrate_lower=opb.read(32); blocksizes[0]=1<<opb.read(4); blocksizes[1]=1<<opb.read(4); if((rate<1) || (channels<1)|| (blocksizes[0]<8)|| (blocksizes[1]<blocksizes[0]) || (opb.read(1)!=1)) { //goto err_out; // EOP check clear(); return(-1); } return(0); // err_out: // vorbis_info_clear(vi); // return(-1); } // all of the real encoding details are here. The modes, books, // everything int unpack_books(csBuffer opb) { //d* codebooks books=opb.read(8)+1; if(book_param==null || book_param.Length!=books) book_param=new StaticCodeBook[books]; for(int i=0;i<books;i++) { book_param[i]=new StaticCodeBook(); if(book_param[i].unpack(opb)!=0) { //goto err_out; clear(); return(-1); } } // time backend settings times=opb.read(6)+1; if(time_type==null || time_type.Length!=times) time_type=new int[times]; if(time_param==null || time_param.Length!=times) time_param=new Object[times]; for(int i=0;i<times;i++) { time_type[i]=opb.read(16); if(time_type[i]<0 || time_type[i]>=VI_TIMEB) { //goto err_out; clear(); return(-1); } time_param[i]=FuncTime.time_P[time_type[i]].unpack(this, opb); if(time_param[i]==null) { //goto err_out; clear(); return(-1); } } // floor backend settings floors=opb.read(6)+1; if(floor_type==null || floor_type.Length!=floors) floor_type=new int[floors]; if(floor_param==null || floor_param.Length!=floors) floor_param=new Object[floors]; for(int i=0;i<floors;i++) { floor_type[i]=opb.read(16); if(floor_type[i]<0 || floor_type[i]>=VI_FLOORB) { //goto err_out; clear(); return(-1); } floor_param[i]=FuncFloor.floor_P[floor_type[i]].unpack(this,opb); if(floor_param[i]==null) { //goto err_out; clear(); return(-1); } } // residue backend settings residues=opb.read(6)+1; if(residue_type==null || residue_type.Length!=residues) residue_type=new int[residues]; if(residue_param==null || residue_param.Length!=residues) residue_param=new Object[residues]; for(int i=0;i<residues;i++) { residue_type[i]=opb.read(16); if(residue_type[i]<0 || residue_type[i]>=VI_RESB) { // goto err_out; clear(); return(-1); } residue_param[i]=FuncResidue.residue_P[residue_type[i]].unpack(this,opb); if(residue_param[i]==null) { // goto err_out; clear(); return(-1); } } // map backend settings maps=opb.read(6)+1; if(map_type==null || map_type.Length!=maps) map_type=new int[maps]; if(map_param==null || map_param.Length!=maps) map_param=new Object[maps]; for(int i=0;i<maps;i++) { map_type[i]=opb.read(16); if(map_type[i]<0 || map_type[i]>=VI_MAPB) { // goto err_out; clear(); return(-1); } map_param[i]=FuncMapping.mapping_P[map_type[i]].unpack(this,opb); if(map_param[i]==null) { // goto err_out; clear(); return(-1); } } // mode settings modes=opb.read(6)+1; if(mode_param==null || mode_param.Length!=modes) mode_param=new InfoMode[modes]; for(int i=0;i<modes;i++) { mode_param[i]=new InfoMode(); mode_param[i].blockflag=opb.read(1); mode_param[i].windowtype=opb.read(16); mode_param[i].transformtype=opb.read(16); mode_param[i].mapping=opb.read(8); if((mode_param[i].windowtype>=VI_WINDOWB)|| (mode_param[i].transformtype>=VI_WINDOWB)|| (mode_param[i].mapping>=maps)) { // goto err_out; clear(); return(-1); } } if(opb.read(1)!=1) { //goto err_out; // top level EOP check clear(); return(-1); } return(0); // err_out: // vorbis_info_clear(vi); // return(-1); } // The Vorbis header is in three packets; the initial small packet in // the first page that identifies basic parameters, a second packet // with bitstream comments and a third packet that holds the // codebook. public int synthesis_headerin(Comment vc, Packet op) { csBuffer opb=new csBuffer(); if(op!=null) { opb.readinit(op.packet_base, op.packet, op.bytes); // Which of the three types of header is this? // Also verify header-ness, vorbis { byte[] buffer=new byte[6]; int packtype=opb.read(8); //memset(buffer,0,6); opb.read(buffer,6); if(buffer[0]!='v' || buffer[1]!='o' || buffer[2]!='r' || buffer[3]!='b' || buffer[4]!='i' || buffer[5]!='s') { // not a vorbis header return(-1); } switch(packtype) { case 0x01: // least significant *bit* is read first if(op.b_o_s==0) { // Not the initial packet return(-1); } if(rate!=0) { // previously initialized info header return(-1); } return(unpack_info(opb)); case 0x03: // least significant *bit* is read first if(rate==0) { // um... we didn't get the initial header return(-1); } return(vc.unpack(opb)); case 0x05: // least significant *bit* is read first if(rate==0 || vc.vendor==null) { // um... we didn;t get the initial header or comments yet return(-1); } return(unpack_books(opb)); default: // Not a valid vorbis header type //return(-1); break; } } } return(-1); } // pack side int pack_info(csBuffer opb) { Encoding AE = Encoding.UTF8; byte[] _vorbis_byt = AE.GetBytes(_vorbis); // preamble opb.write(0x01,8); opb.write(_vorbis_byt); // basic information about the stream opb.write(0x00,32); opb.write(channels,8); opb.write(rate,32); opb.write(bitrate_upper,32); opb.write(bitrate_nominal,32); opb.write(bitrate_lower,32); opb.write(ilog2(blocksizes[0]),4); opb.write(ilog2(blocksizes[1]),4); opb.write(1,1); return(0); } int pack_books(csBuffer opb) { Encoding AE = Encoding.UTF8; byte[] _vorbis_byt = AE.GetBytes(_vorbis); opb.write(0x05,8); opb.write(_vorbis_byt); // books opb.write(books-1,8); for(int i=0;i<books;i++) { if(book_param[i].pack(opb)!=0) { //goto err_out; return(-1); } } // times opb.write(times-1,6); for(int i=0;i<times;i++) { opb.write(time_type[i],16); FuncTime.time_P[time_type[i]].pack(this.time_param[i],opb); } // floors opb.write(floors-1,6); for(int i=0;i<floors;i++) { opb.write(floor_type[i],16); FuncFloor.floor_P[floor_type[i]].pack(floor_param[i],opb); } // residues opb.write(residues-1,6); for(int i=0;i<residues;i++) { opb.write(residue_type[i],16); FuncResidue.residue_P[residue_type[i]].pack(residue_param[i],opb); } // maps opb.write(maps-1,6); for(int i=0;i<maps;i++) { opb.write(map_type[i],16); FuncMapping.mapping_P[map_type[i]].pack(this,map_param[i],opb); } // modes opb.write(modes-1,6); for(int i=0;i<modes;i++) { opb.write(mode_param[i].blockflag,1); opb.write(mode_param[i].windowtype,16); opb.write(mode_param[i].transformtype,16); opb.write(mode_param[i].mapping,8); } opb.write(1,1); return(0); //err_out: //return(-1); } // static void v_writestring(csBuffer o, byte[] s){ // int i=0; // while(s[i]!=0){ // o.write(s[i++],8); // } // } // static void v_readstring(csBuffer o, byte[] buf, int bytes){ // int i=0 // while(bytes--!=0){ // buf[i++]=o.read(8); // } // } // private csBuffer opb_blocksize=new csBuffer(); public int blocksize(Packet op) { //codec_setup_info *ci=vi->codec_setup; csBuffer opb=new csBuffer(); // synchronized(opb_blocksize){ int mode; opb.readinit(op.packet_base, op.packet, op.bytes); /* Check the packet type */ if(opb.read(1)!=0) { /* Oops. This is not an audio data packet */ return(OV_ENOTAUDIO); } { int modebits=0; int v=modes; while(v>1) { modebits++; v = (int)((uint)v >> 1); } /* read our mode and pre/post windowsize */ mode=opb.read(modebits); } if(mode==-1)return(OV_EBADPACKET); return(blocksizes[mode_param[mode].blockflag]); // } } private static int ilog2(int v) { int ret=0; while(v>1) { ret++; v = (int)((uint)v >> 1); } return(ret); } public String toString() { return "version:"+ version.ToString() + ", channels:"+ channels.ToString() + ", rate:"+ rate.ToString() + ", bitrate:"+ bitrate_upper.ToString() +","+ bitrate_nominal.ToString() +","+ bitrate_lower.ToString(); } } }