context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XSSF.Model { using System; using System.Collections.Generic; using System.IO; using System.Xml; using NPOI.OpenXml4Net.OPC; using NPOI.XSSF.UserModel; using OpenXmlFormats.Spreadsheet; public class CommentsTable : POIXMLDocumentPart { private CT_Comments comments; /** * XML Beans uses a list, which is very slow * to search, so we wrap things with our own * map for fast Lookup. */ private Dictionary<String, CT_Comment> commentRefs; public CommentsTable() : base() { comments = new CT_Comments(); comments.AddNewCommentList(); comments.AddNewAuthors().AddAuthor(""); } internal CommentsTable(PackagePart part, PackageRelationship rel) : base(part, rel) { XmlDocument xml = ConvertStreamToXml(part.GetInputStream()); ReadFrom(xml); } public void ReadFrom(XmlDocument xmlDoc) { try { CommentsDocument doc = CommentsDocument.Parse(xmlDoc, NamespaceManager); comments = doc.GetComments(); } catch (XmlException e) { throw new IOException(e.Message); } } public void WriteTo(Stream out1) { CommentsDocument doc = new CommentsDocument(); doc.SetComments(comments); doc.Save(out1); } protected internal override void Commit() { PackagePart part = GetPackagePart(); Stream out1 = part.GetOutputStream(); WriteTo(out1); out1.Close(); } /** * Called after the reference is updated, so that * we can reflect that in our cache */ public void ReferenceUpdated(String oldReference, CT_Comment comment) { if (commentRefs != null) { commentRefs.Remove(oldReference); commentRefs[comment.@ref] = comment; } } public void RecreateReference() { commentRefs.Clear(); foreach (CT_Comment comment in comments.commentList.comment) { commentRefs.Add(comment.@ref, comment); } } public int GetNumberOfComments() { return comments.commentList.SizeOfCommentArray(); } public int GetNumberOfAuthors() { return comments.authors.SizeOfAuthorArray(); } public String GetAuthor(long authorId) { return comments.authors.GetAuthorArray((int)authorId); } /// <summary> /// Searches the author. If not found he is added to the list of authors. /// </summary> /// <param name="author">author to search</param> /// <returns>index of the author</returns> public int FindAuthor(String author) { for (int i = 0; i < comments.authors.SizeOfAuthorArray(); i++) { if (comments.authors.GetAuthorArray(i).Equals(author)) { return i; } } return AddNewAuthor(author); } public XSSFComment FindCellComment(String cellRef) { CT_Comment ct = GetCTComment(cellRef); return ct == null ? null : new XSSFComment(this, ct, null); } public CT_Comment GetCTComment(String cellRef) { // Create the cache if needed if (commentRefs == null) { commentRefs = new Dictionary<String, CT_Comment>(); if (comments.commentList.comment != null) { foreach (CT_Comment comment in comments.commentList.comment) { commentRefs.Add(comment.@ref, comment); } } } // Return the comment, or null if not known if (!commentRefs.ContainsKey(cellRef)) return null; return commentRefs[cellRef]; } /** * This method is deprecated and should not be used any more as * it overwrites the comment in Cell A1. * * @return */ [Obsolete] public CT_Comment NewComment() { return NewComment("A1"); } public CT_Comment NewComment(String ref1) { CT_Comment ct = comments.commentList.AddNewComment(); ct.@ref = (ref1); ct.authorId = (0); if (commentRefs != null) { commentRefs[ct.@ref] = ct; } return ct; } public bool RemoveComment(String cellRef) { CT_CommentList lst = comments.commentList; if (lst != null) for (int i = 0; i < lst.SizeOfCommentArray(); i++) { CT_Comment comment = lst.GetCommentArray(i); if (cellRef.Equals(comment.@ref)) { lst.RemoveComment(i); if (commentRefs != null) { commentRefs.Remove(cellRef); } return true; } } return false; } private int AddNewAuthor(String author) { int index = comments.authors.SizeOfAuthorArray(); comments.authors.Insert(index, author); return index; } public CT_Comments GetCTComments() { return comments; } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using GameLibrary.Dependencies.Physics.Common; using Microsoft.Xna.Framework; using System; using System.Diagnostics; namespace GameLibrary.Dependencies.Physics.Dynamics.Joints { /// <summary> /// A revolute joint rains to bodies to share a common point while they /// are free to rotate about the point. The relative rotation about the shared /// point is the joint angle. You can limit the relative rotation with /// a joint limit that specifies a lower and upper angle. You can use a motor /// to drive the relative rotation about the shared point. A maximum motor torque /// is provided so that infinite forces are not generated. /// </summary> public class RevoluteJoint : PhysicsJoint { public Vector2 LocalAnchorA; public Vector2 LocalAnchorB; private bool _enableLimit; private bool _enableMotor; private Vector3 _impulse; private LimitState _limitState; private float _lowerAngle; private Mat33 _mass; // effective mass for point-to-point constraint. private float _maxMotorTorque; private float _motorImpulse; private float _motorMass; // effective mass for motor/limit angular constraint. private float _motorSpeed; private float _referenceAngle; private float _tmpFloat1; private Vector2 _tmpVector1, _tmpVector2; private float _upperAngle; internal RevoluteJoint() { JointType = JointType.Revolute; } /// <summary> /// Initialize the bodies and local anchor. /// This requires defining an /// anchor point where the bodies are joined. The definition /// uses local anchor points so that the initial configuration /// can violate the constraint slightly. You also need to /// specify the initial relative angle for joint limits. This /// helps when saving and loading a game. /// The local anchor points are measured from the body's origin /// rather than the center of mass because: /// 1. you might not know where the center of mass will be. /// 2. if you add/remove shapes from a body and recompute the mass, /// the joints will be broken. /// </summary> /// <param name="bodyA">The first body.</param> /// <param name="bodyB">The second body.</param> /// <param name="localAnchorA">The first body anchor.</param> /// <param name="localAnchorB">The second anchor.</param> public RevoluteJoint(PhysicsBody bodyA, PhysicsBody bodyB, Vector2 localAnchorA, Vector2 localAnchorB) : base(bodyA, bodyB) { JointType = JointType.Revolute; // Changed to local coordinates. LocalAnchorA = localAnchorA; LocalAnchorB = localAnchorB; ReferenceAngle = BodyB.Rotation - BodyA.Rotation; _impulse = Vector3.Zero; _limitState = LimitState.Inactive; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } public float ReferenceAngle { get { return _referenceAngle; } set { WakeBodies(); _referenceAngle = value; } } /// <summary> /// Get the current joint angle in radians. /// </summary> /// <value></value> public float JointAngle { get { return BodyB.Sweep.A - BodyA.Sweep.A - ReferenceAngle; } } /// <summary> /// Get the current joint angle speed in radians per second. /// </summary> /// <value></value> public float JointSpeed { get { return BodyB.AngularVelocityInternal - BodyA.AngularVelocityInternal; } } /// <summary> /// Is the joint limit enabled? /// </summary> /// <value><c>true</c> if [limit enabled]; otherwise, <c>false</c>.</value> public bool LimitEnabled { get { return _enableLimit; } set { WakeBodies(); _enableLimit = value; } } /// <summary> /// Get the lower joint limit in radians. /// </summary> /// <value></value> public float LowerLimit { get { return _lowerAngle; } set { WakeBodies(); _lowerAngle = value; } } /// <summary> /// Get the upper joint limit in radians. /// </summary> /// <value></value> public float UpperLimit { get { return _upperAngle; } set { WakeBodies(); _upperAngle = value; } } /// <summary> /// Is the joint motor enabled? /// </summary> /// <value><c>true</c> if [motor enabled]; otherwise, <c>false</c>.</value> public bool MotorEnabled { get { return _enableMotor; } set { WakeBodies(); _enableMotor = value; } } /// <summary> /// Set the motor speed in radians per second. /// </summary> /// <value>The speed.</value> public float MotorSpeed { set { WakeBodies(); _motorSpeed = value; } get { return _motorSpeed; } } /// <summary> /// Set the maximum motor torque, usually in N-m. /// </summary> /// <value>The torque.</value> public float MaxMotorTorque { set { WakeBodies(); _maxMotorTorque = value; } get { return _maxMotorTorque; } } /// <summary> /// Get the current motor torque, usually in N-m. /// </summary> /// <value></value> public float MotorTorque { get { return _motorImpulse; } set { WakeBodies(); _motorImpulse = value; } } public override Vector2 GetReactionForce(float inv_dt) { Vector2 P = new Vector2(_impulse.X, _impulse.Y); return inv_dt * P; } public override float GetReactionTorque(float inv_dt) { return inv_dt * _impulse.Z; } internal override void InitVelocityConstraints(ref TimeStep step) { PhysicsBody b1 = BodyA; PhysicsBody b2 = BodyB; if (_enableMotor || _enableLimit) { // You cannot create a rotation limit between bodies that // both have fixed rotation. Debug.Assert(b1.InvI > 0.0f || b2.InvI > 0.0f); } // Compute the effective mass matrix. /*Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2);*/ Vector2 r1 = MathUtils.Multiply(ref b1.Xf.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref b2.Xf.R, LocalAnchorB - b2.LocalCenter); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ m1+r1y^2*i1+m2+r2y^2*i2, -r1y*i1*r1x-r2y*i2*r2x, -r1y*i1-r2y*i2] // [ -r1y*i1*r1x-r2y*i2*r2x, m1+r1x^2*i1+m2+r2x^2*i2, r1x*i1+r2x*i2] // [ -r1y*i1-r2y*i2, r1x*i1+r2x*i2, i1+i2] float m1 = b1.InvMass, m2 = b2.InvMass; float i1 = b1.InvI, i2 = b2.InvI; _mass.Col1.X = m1 + m2 + r1.Y * r1.Y * i1 + r2.Y * r2.Y * i2; _mass.Col2.X = -r1.Y * r1.X * i1 - r2.Y * r2.X * i2; _mass.Col3.X = -r1.Y * i1 - r2.Y * i2; _mass.Col1.Y = _mass.Col2.X; _mass.Col2.Y = m1 + m2 + r1.X * r1.X * i1 + r2.X * r2.X * i2; _mass.Col3.Y = r1.X * i1 + r2.X * i2; _mass.Col1.Z = _mass.Col3.X; _mass.Col2.Z = _mass.Col3.Y; _mass.Col3.Z = i1 + i2; _motorMass = i1 + i2; if (_motorMass > 0.0f) { _motorMass = 1.0f / _motorMass; } if (_enableMotor == false) { _motorImpulse = 0.0f; } if (_enableLimit) { float jointAngle = b2.Sweep.A - b1.Sweep.A - ReferenceAngle; if (Math.Abs(_upperAngle - _lowerAngle) < 2.0f * Settings.AngularSlop) { _limitState = LimitState.Equal; } else if (jointAngle <= _lowerAngle) { if (_limitState != LimitState.AtLower) { _impulse.Z = 0.0f; } _limitState = LimitState.AtLower; } else if (jointAngle >= _upperAngle) { if (_limitState != LimitState.AtUpper) { _impulse.Z = 0.0f; } _limitState = LimitState.AtUpper; } else { _limitState = LimitState.Inactive; _impulse.Z = 0.0f; } } else { _limitState = LimitState.Inactive; } if (Settings.EnableWarmstarting) { // Scale impulses to support a variable time step. _impulse *= step.dtRatio; _motorImpulse *= step.dtRatio; Vector2 P = new Vector2(_impulse.X, _impulse.Y); b1.LinearVelocityInternal -= m1 * P; MathUtils.Cross(ref r1, ref P, out _tmpFloat1); b1.AngularVelocityInternal -= i1 * ( /* r1 x P */_tmpFloat1 + _motorImpulse + _impulse.Z); b2.LinearVelocityInternal += m2 * P; MathUtils.Cross(ref r2, ref P, out _tmpFloat1); b2.AngularVelocityInternal += i2 * ( /* r2 x P */_tmpFloat1 + _motorImpulse + _impulse.Z); } else { _impulse = Vector3.Zero; _motorImpulse = 0.0f; } } internal override void SolveVelocityConstraints(ref TimeStep step) { PhysicsBody b1 = BodyA; PhysicsBody b2 = BodyB; Vector2 v1 = b1.LinearVelocityInternal; float w1 = b1.AngularVelocityInternal; Vector2 v2 = b2.LinearVelocityInternal; float w2 = b2.AngularVelocityInternal; float m1 = b1.InvMass, m2 = b2.InvMass; float i1 = b1.InvI, i2 = b2.InvI; // Solve motor constraint. if (_enableMotor && _limitState != LimitState.Equal) { float Cdot = w2 - w1 - _motorSpeed; float impulse = _motorMass * (-Cdot); float oldImpulse = _motorImpulse; float maxImpulse = step.dt * _maxMotorTorque; _motorImpulse = MathUtils.Clamp(_motorImpulse + impulse, -maxImpulse, maxImpulse); impulse = _motorImpulse - oldImpulse; w1 -= i1 * impulse; w2 += i2 * impulse; } // Solve limit constraint. if (_enableLimit && _limitState != LimitState.Inactive) { /*Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2);*/ Vector2 r1 = MathUtils.Multiply(ref b1.Xf.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref b2.Xf.R, LocalAnchorB - b2.LocalCenter); // Solve point-to-point constraint MathUtils.Cross(w2, ref r2, out _tmpVector2); MathUtils.Cross(w1, ref r1, out _tmpVector1); Vector2 Cdot1 = v2 + /* w2 x r2 */ _tmpVector2 - v1 - /* w1 x r1 */ _tmpVector1; float Cdot2 = w2 - w1; Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2); Vector3 impulse = _mass.Solve33(-Cdot); if (_limitState == LimitState.Equal) { _impulse += impulse; } else if (_limitState == LimitState.AtLower) { float newImpulse = _impulse.Z + impulse.Z; if (newImpulse < 0.0f) { Vector2 reduced = _mass.Solve22(-Cdot1); impulse.X = reduced.X; impulse.Y = reduced.Y; impulse.Z = -_impulse.Z; _impulse.X += reduced.X; _impulse.Y += reduced.Y; _impulse.Z = 0.0f; } } else if (_limitState == LimitState.AtUpper) { float newImpulse = _impulse.Z + impulse.Z; if (newImpulse > 0.0f) { Vector2 reduced = _mass.Solve22(-Cdot1); impulse.X = reduced.X; impulse.Y = reduced.Y; impulse.Z = -_impulse.Z; _impulse.X += reduced.X; _impulse.Y += reduced.Y; _impulse.Z = 0.0f; } } Vector2 P = new Vector2(impulse.X, impulse.Y); v1 -= m1 * P; MathUtils.Cross(ref r1, ref P, out _tmpFloat1); w1 -= i1 * ( /* r1 x P */_tmpFloat1 + impulse.Z); v2 += m2 * P; MathUtils.Cross(ref r2, ref P, out _tmpFloat1); w2 += i2 * ( /* r2 x P */_tmpFloat1 + impulse.Z); } else { /*Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2);*/ _tmpVector1 = LocalAnchorA - b1.LocalCenter; _tmpVector2 = LocalAnchorB - b2.LocalCenter; Vector2 r1 = MathUtils.Multiply(ref b1.Xf.R, ref _tmpVector1); Vector2 r2 = MathUtils.Multiply(ref b2.Xf.R, ref _tmpVector2); // Solve point-to-point constraint MathUtils.Cross(w2, ref r2, out _tmpVector2); MathUtils.Cross(w1, ref r1, out _tmpVector1); Vector2 Cdot = v2 + /* w2 x r2 */ _tmpVector2 - v1 - /* w1 x r1 */ _tmpVector1; Vector2 impulse = _mass.Solve22(-Cdot); _impulse.X += impulse.X; _impulse.Y += impulse.Y; v1 -= m1 * impulse; MathUtils.Cross(ref r1, ref impulse, out _tmpFloat1); w1 -= i1 * /* r1 x impulse */ _tmpFloat1; v2 += m2 * impulse; MathUtils.Cross(ref r2, ref impulse, out _tmpFloat1); w2 += i2 * /* r2 x impulse */ _tmpFloat1; } b1.LinearVelocityInternal = v1; b1.AngularVelocityInternal = w1; b2.LinearVelocityInternal = v2; b2.AngularVelocityInternal = w2; } internal override bool SolvePositionConstraints() { // TODO_ERIN block solve with limit. COME ON ERIN PhysicsBody b1 = BodyA; PhysicsBody b2 = BodyB; float angularError = 0.0f; float positionError; // Solve angular limit constraint. if (_enableLimit && _limitState != LimitState.Inactive) { float angle = b2.Sweep.A - b1.Sweep.A - ReferenceAngle; float limitImpulse = 0.0f; if (_limitState == LimitState.Equal) { // Prevent large angular corrections float C = MathUtils.Clamp(angle - _lowerAngle, -Settings.MaxAngularCorrection, Settings.MaxAngularCorrection); limitImpulse = -_motorMass * C; angularError = Math.Abs(C); } else if (_limitState == LimitState.AtLower) { float C = angle - _lowerAngle; angularError = -C; // Prevent large angular corrections and allow some slop. C = MathUtils.Clamp(C + Settings.AngularSlop, -Settings.MaxAngularCorrection, 0.0f); limitImpulse = -_motorMass * C; } else if (_limitState == LimitState.AtUpper) { float C = angle - _upperAngle; angularError = C; // Prevent large angular corrections and allow some slop. C = MathUtils.Clamp(C - Settings.AngularSlop, 0.0f, Settings.MaxAngularCorrection); limitImpulse = -_motorMass * C; } b1.Sweep.A -= b1.InvI * limitImpulse; b2.Sweep.A += b2.InvI * limitImpulse; b1.SynchronizeTransform(); b2.SynchronizeTransform(); } // Solve point-to-point constraint. { /*Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2);*/ Vector2 r1 = MathUtils.Multiply(ref b1.Xf.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref b2.Xf.R, LocalAnchorB - b2.LocalCenter); Vector2 C = b2.Sweep.C + r2 - b1.Sweep.C - r1; positionError = C.Length(); float invMass1 = b1.InvMass, invMass2 = b2.InvMass; float invI1 = b1.InvI, invI2 = b2.InvI; // Handle large detachment. const float k_allowedStretch = 10.0f * Settings.LinearSlop; if (C.LengthSquared() > k_allowedStretch * k_allowedStretch) { // Use a particle solution (no rotation). Vector2 u = C; u.Normalize(); float k = invMass1 + invMass2; Debug.Assert(k > Settings.Epsilon); float m = 1.0f / k; Vector2 impulse2 = m * (-C); const float k_beta = 0.5f; b1.Sweep.C -= k_beta * invMass1 * impulse2; b2.Sweep.C += k_beta * invMass2 * impulse2; C = b2.Sweep.C + r2 - b1.Sweep.C - r1; } Mat22 K1 = new Mat22(new Vector2(invMass1 + invMass2, 0.0f), new Vector2(0.0f, invMass1 + invMass2)); Mat22 K2 = new Mat22(new Vector2(invI1 * r1.Y * r1.Y, -invI1 * r1.X * r1.Y), new Vector2(-invI1 * r1.X * r1.Y, invI1 * r1.X * r1.X)); Mat22 K3 = new Mat22(new Vector2(invI2 * r2.Y * r2.Y, -invI2 * r2.X * r2.Y), new Vector2(-invI2 * r2.X * r2.Y, invI2 * r2.X * r2.X)); Mat22 Ka; Mat22.Add(ref K1, ref K2, out Ka); Mat22 K; Mat22.Add(ref Ka, ref K3, out K); Vector2 impulse = K.Solve(-C); b1.Sweep.C -= b1.InvMass * impulse; MathUtils.Cross(ref r1, ref impulse, out _tmpFloat1); b1.Sweep.A -= b1.InvI * /* r1 x impulse */ _tmpFloat1; b2.Sweep.C += b2.InvMass * impulse; MathUtils.Cross(ref r2, ref impulse, out _tmpFloat1); b2.Sweep.A += b2.InvI * /* r2 x impulse */ _tmpFloat1; b1.SynchronizeTransform(); b2.SynchronizeTransform(); } return positionError <= Settings.LinearSlop && angularError <= Settings.AngularSlop; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ThreadManager.cs" company="The Watcher"> // Copyright (c) The Watcher Partial Rights Reserved. // This software is licensed under the MIT license. See license.txt for details. // </copyright> // <summary> // Code Named: Ripper // Function : Extracts Images posted on forums and attempts to fetch them to disk. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Ripper.Core.Components { using System; using System.Collections; using System.Threading; /// <summary> /// Custom thread controller. /// Bad architecture, poor design. But it works and it works better than the more /// 'complex' models featuring thousands of lines of coding. So whatever.. /// </summary> public class ThreadManager { /// <summary> /// The thread table /// </summary> private readonly Hashtable threadTable; /// <summary> /// The thresh hold /// </summary> private int threshHold; /// <summary> /// The suspend /// </summary> private bool suspend; /// <summary> /// Initializes a new instance of the <see cref="ThreadManager"/> class. /// </summary> public ThreadManager() { this.threadTable = new Hashtable(); this.SetThreadThreshHold(3); } /// <summary> /// Gets or sets the ThreadManager instance /// </summary> public static ThreadManager Instance { get; set; } /// <summary> /// Gets the instance. /// </summary> /// <returns>Returns the Thread manager instance</returns> public static ThreadManager GetInstance() { return Instance ?? (Instance = new ThreadManager()); } /// <summary> /// Gets the thread count. /// </summary> /// <returns>Returns the Thread Count</returns> public int GetThreadCount() { return this.threadTable.Count; } /// <summary> /// Gets the thread thresh hold. /// </summary> /// <returns>Returns the thread thresh hold.</returns> public int GetThreadThreshHold() { return this.threshHold; } /// <summary> /// Sets the thread thresh hold. /// </summary> /// <param name="threshold">The Threshold.</param> public void SetThreadThreshHold(int threshold) { this.threshHold = threshold; } /// <summary> /// Launches the thread. /// </summary> /// <param name="threadId">The thread unique identifier.</param> /// <param name="start">The start.</param> /// <returns>Returns if thread was launched or not</returns> public bool LaunchThread(string threadId, ThreadStart start) { if (this.threadTable.Count >= this.threshHold || this.threadTable.ContainsKey(threadId)) { return false; } var threadGet = new Thread(start) { IsBackground = true }; this.threadTable.Add(threadId, threadGet); threadGet.Start(); return true; } /// <summary> /// Determines whether [is system ready for new thread]. /// </summary> /// <returns>Returns if system ready for new thread</returns> public bool IsSystemReadyForNewThread() { if (this.threadTable.Count >= this.threshHold) { return false; } return !this.suspend; } /// <summary> /// Removes the thread by id. /// </summary> /// <param name="threadId">The thread id.</param> public void RemoveThreadbyId(string threadId) { if (this.threadTable.ContainsKey(threadId)) { this.threadTable.Remove(threadId); } } /// <summary> /// Dismantles all threads. /// </summary> public void DismantleAllThreads() { try { var thrdEnumerator = this.threadTable.GetEnumerator(); while (thrdEnumerator.MoveNext()) { if (((Thread)thrdEnumerator.Value).IsAlive) { Monitor.Exit(thrdEnumerator.Value); } } } catch (Exception) { this.threadTable.Clear(); } finally { this.suspend = false; this.threadTable.Clear(); } } /// <summary> /// Holds all threads. /// </summary> public void HoldAllThreads() { try { var thrdEnumerator = this.threadTable.GetEnumerator(); while (thrdEnumerator.MoveNext()) { if (((Thread)thrdEnumerator.Value).IsAlive) { Monitor.Enter(thrdEnumerator.Value); } } } finally { this.suspend = true; } } /// <summary> /// Resumes all threads. /// </summary> public void ResumeAllThreads() { try { var thrdEnumerator = this.threadTable.GetEnumerator(); while (thrdEnumerator.MoveNext()) { Monitor.Exit(thrdEnumerator.Value); } } finally { this.suspend = false; } } } }
/* * 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; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using System.Xml.Serialization; using log4net; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Communications.Clients; namespace OpenSim.Region.Communications.OGS1 { public class OGS1UserDataPlugin : IUserDataPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected CommunicationsManager m_commsManager; public OGS1UserDataPlugin(CommunicationsManager commsManager) { m_log.DebugFormat("[OGS1 USER SERVICES]: {0} initialized", Name); m_commsManager = commsManager; } public string Version { get { return "0.1"; } } public string Name { get { return "Open Grid Services 1 (OGS1) User Data Plugin"; } } public void Initialise() {} public void Initialise(string connect) {} public void Dispose() {} // Arguably the presence of these means that IUserDataPlugin could be fissioned public UserAgentData GetUserAgent(string name) { return null; } public UserAgentData GetAgentByName(string name) { return null; } public UserAgentData GetAgentByName(string fname, string lname) { return null; } public void StoreWebLoginKey(UUID agentID, UUID webLoginKey) {} public void AddNewUserProfile(UserProfileData user) {} public void AddNewUserAgent(UserAgentData agent) {} public bool MoneyTransferRequest(UUID from, UUID to, uint amount) { return false; } public bool InventoryTransferRequest(UUID from, UUID to, UUID inventory) { return false; } public void ResetAttachments(UUID userID) {} public void LogoutUsers(UUID regionID) {} public virtual void AddTemporaryUserProfile(UserProfileData userProfile) { // Not interested } public UserProfileData GetUserByUri(Uri uri) { WebRequest request = WebRequest.Create(uri); WebResponse webResponse = request.GetResponse(); XmlSerializer deserializer = new XmlSerializer(typeof(XmlRpcResponse)); XmlRpcResponse xmlRpcResponse = (XmlRpcResponse)deserializer.Deserialize(webResponse.GetResponseStream()); Hashtable respData = (Hashtable)xmlRpcResponse.Value; return ConvertXMLRPCDataToUserProfile(respData); } // public Uri GetUserUri(UserProfileData userProfile) // { // throw new NotImplementedException(); // } public virtual UserAgentData GetAgentByUUID(UUID userId) { try { Hashtable param = new Hashtable(); param["avatar_uuid"] = userId.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_agent_by_uuid", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(userId), 6000); Hashtable respData = (Hashtable)resp.Value; if (respData.Contains("error_type")) { //m_log.Warn("[GRID]: " + // "Error sent by user server when trying to get agent: (" + // (string) respData["error_type"] + // "): " + (string)respData["error_desc"]); return null; } UUID sessionid = UUID.Zero; UserAgentData userAgent = new UserAgentData(); userAgent.Handle = Convert.ToUInt64((string)respData["handle"]); UUID.TryParse((string)respData["sessionid"], out sessionid); userAgent.SessionID = sessionid; if ((string)respData["agent_online"] == "TRUE") { userAgent.AgentOnline = true; } else { userAgent.AgentOnline = false; } return userAgent; } catch (Exception e) { m_log.ErrorFormat( "[OGS1 USER SERVICES]: Error when trying to fetch agent data by uuid from remote user server: {0}", e); } return null; } public virtual UserProfileData GetUserByName(string firstName, string lastName) { return GetUserProfile(firstName + " " + lastName); } public virtual List<AvatarPickerAvatar> GeneratePickerResults(UUID queryID, string query) { List<AvatarPickerAvatar> pickerlist = new List<AvatarPickerAvatar>(); Regex objAlphaNumericPattern = new Regex("[^a-zA-Z0-9 ]"); try { Hashtable param = new Hashtable(); param["queryid"] = (string)queryID.ToString(); param["avquery"] = objAlphaNumericPattern.Replace(query, String.Empty); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_avatar_picker_avatar", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000); Hashtable respData = (Hashtable)resp.Value; pickerlist = ConvertXMLRPCDataToAvatarPickerList(queryID, respData); } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to fetch Avatar Picker Response: " + e.Message); // Return Empty picker list (no results) } return pickerlist; } /// <summary> /// Get a user profile from the user server /// </summary> /// <param name="avatarID"></param> /// <returns>null if the request fails</returns> protected virtual UserProfileData GetUserProfile(string name) { try { Hashtable param = new Hashtable(); param["avatar_name"] = name; IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_user_by_name", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 30000); Hashtable respData = (Hashtable)resp.Value; return ConvertXMLRPCDataToUserProfile(respData); } catch (WebException e) { m_log.ErrorFormat( "[OGS1 USER SERVICES]: Error when trying to fetch profile data by name from remote user server: {0}", e); } return null; } /// <summary> /// Get a user profile from the user server /// </summary> /// <param name="avatarID"></param> /// <returns>null if the request fails</returns> public virtual UserProfileData GetUserByUUID(UUID avatarID) { try { Hashtable param = new Hashtable(); param["avatar_uuid"] = avatarID.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_user_by_uuid", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 30000); Hashtable respData = (Hashtable)resp.Value; return ConvertXMLRPCDataToUserProfile(respData); } catch (Exception e) { m_log.ErrorFormat( "[OGS1 USER SERVICES]: Error when trying to fetch profile data by uuid from remote user server: {0}", e); } return null; } public virtual bool UpdateUserProfile(UserProfileData userProfile) { m_log.Debug("[OGS1 USER SERVICES]: Asking UserServer to update profile."); Hashtable param = new Hashtable(); param["avatar_uuid"] = userProfile.ID.ToString(); //param["AllowPublish"] = userProfile.ToString(); param["FLImageID"] = userProfile.FirstLifeImage.ToString(); param["ImageID"] = userProfile.Image.ToString(); //param["MaturePublish"] = MaturePublish.ToString(); param["AboutText"] = userProfile.AboutText; param["FLAboutText"] = userProfile.FirstLifeAboutText; //param["ProfileURL"] = userProfile.ProfileURL.ToString(); param["home_region"] = userProfile.HomeRegion.ToString(); param["home_region_id"] = userProfile.HomeRegionID.ToString(); param["home_pos_x"] = userProfile.HomeLocationX.ToString(); param["home_pos_y"] = userProfile.HomeLocationY.ToString(); param["home_pos_z"] = userProfile.HomeLocationZ.ToString(); param["home_look_x"] = userProfile.HomeLookAtX.ToString(); param["home_look_y"] = userProfile.HomeLookAtY.ToString(); param["home_look_z"] = userProfile.HomeLookAtZ.ToString(); param["user_flags"] = userProfile.UserFlags.ToString(); param["god_level"] = userProfile.GodLevel.ToString(); param["custom_type"] = userProfile.CustomType.ToString(); param["partner"] = userProfile.Partner.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("update_user_profile", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(userProfile.ID), 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if (((string)respData["returnString"]).ToUpper() != "TRUE") { m_log.Warn("[GRID]: Unable to update user profile, User Server Reported an issue"); return false; } } else { m_log.Warn("[GRID]: Unable to update user profile, UserServer didn't understand me!"); return false; } } else { m_log.Warn("[GRID]: Unable to update user profile, UserServer didn't understand me!"); return false; } return true; } /// <summary> /// Adds a new friend to the database for XUser /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being added to</param> /// <param name="friend">The agent that being added to the friends list of the friends list owner</param> /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param> public virtual void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) { try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); param["friendID"] = friend.Guid.ToString(); param["friendPerms"] = perms.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("add_new_user_friend", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to add new friend, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to add new friend, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to add new friend, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[GRID]: Error when trying to AddNewUserFriend: " + e.Message); } } /// <summary> /// Delete friend on friendlistowner's friendlist. /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being updated</param> /// <param name="friend">The Ex-friend agent</param> public virtual void RemoveUserFriend(UUID friendlistowner, UUID friend) { try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); param["friendID"] = friend.Guid.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("remove_user_friend", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to remove friend, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to remove friend, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to remove friend, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[GRID]: Error when trying to RemoveUserFriend: " + e.Message); } } /// <summary> /// Update permissions for friend on friendlistowner's friendlist. /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being updated</param> /// <param name="friend">The agent that is getting or loosing permissions</param> /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param> public virtual void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) { try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); param["friendID"] = friend.Guid.ToString(); param["friendPerms"] = perms.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("update_user_friend_perms", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 3000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to update_user_friend_perms, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to update_user_friend_perms, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to update_user_friend_perms, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[GRID]: Error when trying to update_user_friend_perms: " + e.Message); } } /// <summary> /// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner /// </summary> /// <param name="friendlistowner">The agent that we're retreiving the friends Data.</param> public virtual List<FriendListItem> GetUserFriendList(UUID friendlistowner) { List<FriendListItem> buddylist = new List<FriendListItem>(); try { Hashtable param = new Hashtable(); param["ownerID"] = friendlistowner.Guid.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_user_friend_list", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.UserURL, 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null && respData.Contains("avcount")) { buddylist = ConvertXMLRPCDataToFriendListItemList(respData); } } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to fetch Avatar's friends list: " + e.Message); // Return Empty list (no friends) } return buddylist; } public virtual Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids) { Dictionary<UUID, FriendRegionInfo> result = new Dictionary<UUID, FriendRegionInfo>(); // ask MessageServer about the current on-/offline status and regions the friends are in ArrayList parameters = new ArrayList(); Hashtable map = new Hashtable(); ArrayList list = new ArrayList(); foreach (UUID uuid in uuids) { list.Add(uuid.ToString()); list.Add(uuid.ToString()); } map["uuids"] = list; map["recv_key"] = m_commsManager.NetworkServersInfo.UserRecvKey; map["send_key"] = m_commsManager.NetworkServersInfo.UserSendKey; parameters.Add(map); try { XmlRpcRequest req = new XmlRpcRequest("get_presence_info_bulk", parameters); XmlRpcResponse resp = req.Send(m_commsManager.NetworkServersInfo.MessagingURL, 8000); Hashtable respData = resp != null ? (Hashtable)resp.Value : null; if (respData == null || respData.ContainsKey("faultMessage")) { m_log.WarnFormat("[OGS1 USER SERVICES]: Contacting MessagingServer about user-regions resulted in error: {0}", respData == null ? "<unknown error>" : respData["faultMessage"]); } else if (!respData.ContainsKey("count")) { m_log.WarnFormat("[OGS1 USER SERVICES]: Wrong format in response for MessagingServer request get_presence_info_bulk: missing 'count' field"); } else { int count = (int)respData["count"]; m_log.DebugFormat("[OGS1 USER SERVICES]: Request returned {0} results.", count); for (int i = 0; i < count; ++i) { if (respData.ContainsKey("uuid_" + i) && respData.ContainsKey("isOnline_" + i) && respData.ContainsKey("regionHandle_" + i)) { UUID uuid; if (UUID.TryParse((string)respData["uuid_" + i], out uuid)) { FriendRegionInfo info = new FriendRegionInfo(); info.isOnline = (bool)respData["isOnline_" + i]; if (info.isOnline) { // TODO remove this after the next protocol update (say, r7800?) info.regionHandle = Convert.ToUInt64(respData["regionHandle_" + i]); // accept missing id if (respData.ContainsKey("regionID_" + i)) UUID.TryParse((string)respData["regionID_" + i], out info.regionID); } result.Add(uuid, info); } } else { m_log.WarnFormat("[OGS1 USER SERVICES]: Response to get_presence_info_bulk contained an error in entry {0}", i); } } } } catch (WebException e) { m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch friend infos: {0}", e.Message); } m_log.DebugFormat("[OGS1 USER SERVICES]: Returning {0} entries", result.Count); return result; } public virtual AvatarAppearance GetUserAppearance(UUID user) { AvatarAppearance appearance = null; try { Hashtable param = new Hashtable(); param["owner"] = user.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("get_avatar_appearance", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(user), 8000); Hashtable respData = (Hashtable)resp.Value; return ConvertXMLRPCDataToAvatarAppearance(respData); } catch (WebException e) { m_log.ErrorFormat("[OGS1 USER SERVICES]: Network problems when trying to fetch appearance for avatar {0}, {1}", user, e.Message); } return appearance; } public virtual void UpdateUserAppearance(UUID user, AvatarAppearance appearance) { try { Hashtable param = appearance.ToHashTable(); param["owner"] = user.ToString(); IList parameters = new ArrayList(); parameters.Add(param); XmlRpcRequest req = new XmlRpcRequest("update_avatar_appearance", parameters); XmlRpcResponse resp = req.Send(GetUserServerURL(user), 8000); Hashtable respData = (Hashtable)resp.Value; if (respData != null) { if (respData.Contains("returnString")) { if ((string)respData["returnString"] == "TRUE") { } else { m_log.Warn("[GRID]: Unable to update_user_appearance, User Server Reported an issue"); } } else { m_log.Warn("[GRID]: Unable to update_user_appearance, UserServer didn't understand me!"); } } else { m_log.Warn("[GRID]: Unable to update_user_appearance, UserServer didn't understand me!"); } } catch (WebException e) { m_log.Warn("[OGS1 USER SERVICES]: Error when trying to update Avatar's appearance: " + e.Message); // Return Empty list (no friends) } } protected virtual string GetUserServerURL(UUID userID) { return m_commsManager.NetworkServersInfo.UserURL; } protected UserProfileData ConvertXMLRPCDataToUserProfile(Hashtable data) { if (data.Contains("error_type")) { //m_log.Warn("[GRID]: " + // "Error sent by user server when trying to get user profile: (" + // data["error_type"] + // "): " + data["error_desc"]); return null; } UserProfileData userData = new UserProfileData(); userData.FirstName = (string)data["firstname"]; userData.SurName = (string)data["lastname"]; userData.ID = new UUID((string)data["uuid"]); userData.Created = Convert.ToInt32(data["profile_created"]); userData.UserInventoryURI = (string)data["server_inventory"]; userData.UserAssetURI = (string)data["server_asset"]; userData.FirstLifeAboutText = (string)data["profile_firstlife_about"]; userData.FirstLifeImage = new UUID((string)data["profile_firstlife_image"]); userData.CanDoMask = Convert.ToUInt32((string)data["profile_can_do"]); userData.WantDoMask = Convert.ToUInt32(data["profile_want_do"]); userData.AboutText = (string)data["profile_about"]; userData.Image = new UUID((string)data["profile_image"]); userData.LastLogin = Convert.ToInt32((string)data["profile_lastlogin"]); userData.HomeRegion = Convert.ToUInt64((string)data["home_region"]); if (data.Contains("home_region_id")) userData.HomeRegionID = new UUID((string)data["home_region_id"]); else userData.HomeRegionID = UUID.Zero; userData.HomeLocation = new Vector3((float)Convert.ToDecimal((string)data["home_coordinates_x"]), (float)Convert.ToDecimal((string)data["home_coordinates_y"]), (float)Convert.ToDecimal((string)data["home_coordinates_z"])); userData.HomeLookAt = new Vector3((float)Convert.ToDecimal((string)data["home_look_x"]), (float)Convert.ToDecimal((string)data["home_look_y"]), (float)Convert.ToDecimal((string)data["home_look_z"])); if (data.Contains("user_flags")) userData.UserFlags = Convert.ToInt32((string)data["user_flags"]); if (data.Contains("god_level")) userData.GodLevel = Convert.ToInt32((string)data["god_level"]); if (data.Contains("custom_type")) userData.CustomType = (string)data["custom_type"]; else userData.CustomType = ""; if (userData.CustomType == null) userData.CustomType = ""; if (data.Contains("partner")) userData.Partner = new UUID((string)data["partner"]); else userData.Partner = UUID.Zero; return userData; } protected AvatarAppearance ConvertXMLRPCDataToAvatarAppearance(Hashtable data) { if (data != null) { if (data.Contains("error_type")) { m_log.Warn("[GRID]: " + "Error sent by user server when trying to get user appearance: (" + data["error_type"] + "): " + data["error_desc"]); return null; } else { return new AvatarAppearance(data); } } else { m_log.Error("[GRID]: The avatar appearance is null, something bad happenend"); return null; } } protected List<AvatarPickerAvatar> ConvertXMLRPCDataToAvatarPickerList(UUID queryID, Hashtable data) { List<AvatarPickerAvatar> pickerlist = new List<AvatarPickerAvatar>(); int pickercount = Convert.ToInt32((string)data["avcount"]); UUID respqueryID = new UUID((string)data["queryid"]); if (queryID == respqueryID) { for (int i = 0; i < pickercount; i++) { AvatarPickerAvatar apicker = new AvatarPickerAvatar(); UUID avatarID = new UUID((string)data["avatarid" + i.ToString()]); string firstname = (string)data["firstname" + i.ToString()]; string lastname = (string)data["lastname" + i.ToString()]; apicker.AvatarID = avatarID; apicker.firstName = firstname; apicker.lastName = lastname; pickerlist.Add(apicker); } } else { m_log.Warn("[OGS1 USER SERVICES]: Got invalid queryID from userServer"); } return pickerlist; } protected List<FriendListItem> ConvertXMLRPCDataToFriendListItemList(Hashtable data) { List<FriendListItem> buddylist = new List<FriendListItem>(); int buddycount = Convert.ToInt32((string)data["avcount"]); for (int i = 0; i < buddycount; i++) { FriendListItem buddylistitem = new FriendListItem(); buddylistitem.FriendListOwner = new UUID((string)data["ownerID" + i.ToString()]); buddylistitem.Friend = new UUID((string)data["friendID" + i.ToString()]); buddylistitem.FriendListOwnerPerms = (uint)Convert.ToInt32((string)data["ownerPerms" + i.ToString()]); buddylistitem.FriendPerms = (uint)Convert.ToInt32((string)data["friendPerms" + i.ToString()]); buddylist.Add(buddylistitem); } return buddylist; } } }
// // AmpachePlayer.cs // // Author: // John Moore <jcwmoore@gmail.com> // // Copyright (c) 2012 John Moore // // 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.Linq; using System.Threading.Tasks; using JohnMoore.AmpacheNet.Entities; namespace JohnMoore.AmpacheNet.Logic { public abstract class AmpachePlayer { protected readonly AmpacheModel _model; protected bool _isPaused = false; private int _playerPositionMilliSecond; private static object _syncLock = new object(); protected int PlayerPositionMilliSecond { get { return _playerPositionMilliSecond; } set { _playerPositionMilliSecond = value; _model.PercentPlayed = (_playerPositionMilliSecond / _model.PlayingSong.TrackLength.TotalMilliseconds) * 100; } } protected AmpachePlayer (AmpacheModel model) { _model = model; _model.PropertyChanged += Handle_modelPropertyChanged; } void Handle_modelPropertyChanged (object sender, PropertyChangedEventArgs e) { switch (e.PropertyName) { case AmpacheModel.PLAY_PAUSE_REQUESTED: if(_model.PlayPauseRequested) Task.Factory.StartNew(() => PlayPause()); break; case AmpacheModel.NEXT_REQUESTED: if(_model.NextRequested) Task.Factory.StartNew(() => Next()); break; case AmpacheModel.PREVIOUS_REQUESTED: if(_model.PreviousRequested) Task.Factory.StartNew(() => Previous()); break; case AmpacheModel.STOP_REQUESTED: if(_model.StopRequested) { _model.PlayingSong = null; Stop(); } break; case AmpacheModel.REQUESTED_SEEK_TO_PERCENTAGE: Task.Factory.StartNew(() => Seek()); break; default: break; } } public void PlayPause () { lock(_syncLock) { Console.WriteLine ("Play Pause Requested"); if(_isPaused) { Unpause(); _isPaused = false; _model.IsPlaying = true; } else if(_model.IsPlaying) { Pause(); _isPaused = true; _model.IsPlaying = false; } else if((_model.Playlist ?? new List<AmpacheSong>()).Any()) { Console.WriteLine ("Begining Playback"); if(_model.PlayingSong == null) { Console.WriteLine ("Playback First Song"); _model.PlayingSong = _model.Playlist.First(); } try { _model.PercentPlayed = 0; _model.PercentDownloaded = 0; PlaySong (_model.PlayingSong); _isPaused = false; _model.IsPlaying = true; } catch (Exception ex) { _model.UserMessage = ex.Message; Console.WriteLine (ex.Message); } } _model.PlayPauseRequested = false; Console.WriteLine ("PlayPause done"); } } void Next () { lock(_syncLock) { Console.WriteLine ("Next Requested"); if (_model.Playlist == null || _model.Playlist.Count == 0) { if (_model.IsPlaying) { StopPlay(); _model.PercentPlayed = 0; _model.PercentDownloaded = 0; } _model.PlayingSong = null; } else { int nextIndex = 0; if(_model.Shuffling) { nextIndex = new Random().Next(0, _model.Playlist.Count - 1); } else if(_model.PlayingSong != null) { nextIndex = (_model.Playlist.IndexOf(_model.PlayingSong) + 1) % _model.Playlist.Count; } Console.WriteLine ("Playing next Song: " + _model.Playlist[nextIndex].Name); _model.PercentPlayed = 0; _model.PercentDownloaded = 0; var sng = _model.Playlist[nextIndex]; _model.PlayingSong = sng; PlaySong(sng); _model.IsPlaying = true; _isPaused = false; } _model.NextRequested = false; Console.WriteLine ("Next done"); } } void Previous () { lock(_syncLock) { Console.WriteLine ("Previous Requested"); if (_model.Playlist == null || _model.Playlist.Count == 0) { if (_model.IsPlaying) { StopPlay(); _model.PercentPlayed = 0; _model.PercentDownloaded = 0; _model.PlayingSong = null; } _model.PreviousRequested = false; return; } if(PlayerPositionMilliSecond < 2000) { _model.PlayingSong = _model.Playlist[(_model.Playlist.IndexOf(_model.PlayingSong) + _model.Playlist.Count - 1) % _model.Playlist.Count]; Console.WriteLine ("Playing Previous Song"); } _model.PercentPlayed = 0; _model.PercentDownloaded = 0; PlaySong (_model.PlayingSong); _isPaused = false; _model.PreviousRequested = false; Console.WriteLine ("Previous done"); } } void Stop () { lock (_syncLock) { Console.WriteLine ("Stop Requested"); if (_model.IsPlaying || _isPaused) { StopPlay (); _model.PercentPlayed = 0; _model.PercentDownloaded = 0; _isPaused = false; _model.IsPlaying = false; } _model.StopRequested = false; Console.WriteLine ("Stop done"); } } void Seek () { if(_model.Configuration.AllowSeeking && _model.RequestedSeekToPercentage != null && !_isPaused && _model.IsPlaying) { var seekPositionMilli = (int)(_model.RequestedSeekToPercentage * _model.PlayingSong.TrackLength.TotalMilliseconds); Console.WriteLine (seekPositionMilli); SeekTo(seekPositionMilli); _model.RequestedSeekToPercentage = null; } } protected abstract void PlaySong(AmpacheSong song); protected abstract void StopPlay(); protected abstract void Pause(); protected abstract void Unpause(); protected abstract void SeekTo(int millis); } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Diagnostics; using RdlEngine.Resources; namespace fyiReporting.RDL { ///<summary> /// Represents all the pages of a report. Needed when you need /// render based on pages. e.g. PDF ///</summary> public class Pages : IEnumerable { Bitmap _bm; // bitmap to build graphics object Graphics _g; // graphics object Report _report; // owner report List<Page> _pages; // array of pages Page _currentPage; // the current page; 1st page if null float _BottomOfPage; // the bottom of the page float _PageHeight; // default height for all pages float _PageWidth; // default width for all pages public Pages(Report r) { _report = r; _pages = new List<Page>(); // array of Page objects _bm = new Bitmap(10, 10); // create a small bitmap to base our graphics _g = Graphics.FromImage(_bm); } internal Report Report { get { return _report;} } public Page this[int index] { get {return _pages[index];} } public int Count { get {return _pages.Count;} } public void AddPage(Page p) { _pages.Add(p); _currentPage = p; } public void NextOrNew() { if (_currentPage == this.LastPage) AddPage(new Page(PageCount+1)); else { _currentPage = _pages[_currentPage.PageNumber]; _currentPage.SetEmpty(); } //Allows using PageNumber in report body. //Important! This feature is NOT included in RDL specification! //PageNumber will be wrong if element using it will cause carry to next page after render. Report.PageNumber = _currentPage.PageNumber; } /// <summary> /// CleanUp should be called after every render to reduce resource utilization. /// </summary> public void CleanUp() { if (_g != null) { _g.Dispose(); _g = null; } if (_bm != null) { _bm.Dispose(); _bm = null; } } public void SortPageItems() { foreach (Page p in this) { p.SortPageItems(); } } public float BottomOfPage { get { return _BottomOfPage; } set { _BottomOfPage = value; } } public Page CurrentPage { get { if (_currentPage != null) return _currentPage; if (_pages.Count >= 1) { _currentPage = _pages[0]; return _currentPage; } return null; } set { _currentPage = value; #if DEBUG if (value == null) return; foreach (Page p in _pages) { if (p == value) return; } throw new Exception(Strings.Pages_Error_CurrentPageMustInList); #endif } } public Page FirstPage { get { if (_pages.Count <= 0) return null; else return _pages[0]; } } public Page LastPage { get { if (_pages.Count <= 0) return null; else return _pages[_pages.Count-1]; } } public float PageHeight { get {return _PageHeight;} set {_PageHeight = value;} } public float PageWidth { get {return _PageWidth;} set {_PageWidth = value;} } public void RemoveLastPage() { Page lp = LastPage; if (lp == null) // if no last page nothing to do return; _pages.RemoveAt(_pages.Count-1); // remove the page if (this.CurrentPage == lp) // reset the current if necessary { if (_pages.Count <= 0) CurrentPage = null; else CurrentPage = _pages[_pages.Count-1]; } return; } public Graphics G { get { if (_g == null) { _bm = new Bitmap(10, 10); // create a small bitmap to base our graphics _g = Graphics.FromImage(_bm); } return _g; } } public int PageCount { get { return _pages.Count; } } #region IEnumerable Members public IEnumerator GetEnumerator() // just loop thru the pages { return _pages.GetEnumerator(); } #endregion } public class Page : IEnumerable { // note: all sizes are in points int _pageno; List<PageItem> _items; // array of items on the page float _yOffset; // current y offset; top margin, page header, other details, ... float _xOffset; // current x offset; margin, body taken into account? int _emptyItems; // # of items which constitute empty bool _needSort; // need sort int _lastZIndex; // last ZIndex System.Collections.Generic.Dictionary<string, Rows> _PageExprReferences; // needed to save page header/footer expressions public Page(int page) { _pageno = page; _items = new List<PageItem>(); _emptyItems = 0; _needSort = false; } public PageItem this[int index] { get { return _items[index]; } } public int Count { get { return _items.Count; } } public void InsertObject(PageItem pi) { AddObjectInternal(pi); _items.Insert(0, pi); } public void AddObject(PageItem pi) { AddObjectInternal(pi); _items.Add(pi); } private void AddObjectInternal(PageItem pi) { pi.Page = this; pi.ItemNumber = _items.Count; if (_items.Count == 0) _lastZIndex = pi.ZIndex; else if (_lastZIndex != pi.ZIndex) _needSort = true; // adjust the page item locations pi.X += _xOffset; pi.Y += _yOffset; if (pi is PageLine) { PageLine pl = pi as PageLine; pl.X2 += _xOffset; pl.Y2 += _yOffset; } else if (pi is PagePolygon) { PagePolygon pp = pi as PagePolygon; for (int i = 0; i < pp.Points.Length; i++ ) { pp.Points[i].X += _xOffset; pp.Points[i].Y += _yOffset; } } else if (pi is PageCurve) { PageCurve pc = pi as PageCurve; for (int i = 0; i < pc.Points.Length; i++) { pc.Points[i].X += _xOffset; pc.Points[i].Y += _yOffset; } } } public bool IsEmpty() { return _items.Count > _emptyItems? false: true; } public void SortPageItems() { if (!_needSort) return; _items.Sort(); } public void ResetEmpty() { _emptyItems = 0; } public void SetEmpty() { _emptyItems = _items.Count; } public int PageNumber { get { return _pageno;} } public float XOffset { get { return _xOffset; } set { _xOffset = value; } } public float YOffset { get { return _yOffset; } set { _yOffset = value; } } internal void AddPageExpressionRow(Report rpt, string exprname, Row r) { if (exprname == null || r == null) return; if (_PageExprReferences == null) _PageExprReferences = new Dictionary<string, Rows>(); Rows rows=null; _PageExprReferences.TryGetValue(exprname, out rows); if (rows == null) { rows = new Rows(rpt); rows.Data = new List<Row>(); _PageExprReferences.Add(exprname, rows); } Row row = new Row(rows, r); // have to make a new copy row.RowNumber = rows.Data.Count; rows.Data.Add(row); // add row to rows return; } internal Rows GetPageExpressionRows(string exprname) { if (_PageExprReferences == null) return null; Rows rows=null; _PageExprReferences.TryGetValue(exprname, out rows); return rows; } internal void ResetPageExpressions() { _PageExprReferences = null; // clear it out; not needed once page header/footer are processed } #region IEnumerable Members public IEnumerator GetEnumerator() // just loop thru the pages { return _items.GetEnumerator(); } #endregion } public class PageItem : ICloneable, IComparable { Page parent; // parent page float x; // x coordinate float y; // y coordinate float h; // height --- line redefines as Y2 float w; // width --- line redefines as X2 string hyperlink; // a hyperlink the object should link to string bookmarklink; // a hyperlink within the report object should link to string bookmark; // bookmark text for this pageItem string tooltip; // a message to display when user hovers with mouse int zindex; // zindex; items will be sorted by this int itemNumber; // original number of item StyleInfo si; // all the style information evaluated bool allowselect = true; // allow selection of this item public Page Page { get { return parent; } set { parent = value; } } public bool AllowSelect { get { return allowselect; } set { allowselect = value; } } public float X { get { return x;} set { x = value;} } public float Y { get { return y;} set { y = value;} } public int ZIndex { get { return zindex; } set { zindex = value; } } public int ItemNumber { get { return itemNumber; } set { itemNumber = value; } } public float H { get { return h;} set { h = value;} } public float W { get { return w;} set { w = value;} } public string HyperLink { get { return hyperlink;} set { hyperlink = value;} } public string BookmarkLink { get { return bookmarklink;} set { bookmarklink = value;} } public string Bookmark { get { return bookmark; } set { bookmark = value; } } public string Tooltip { get { return tooltip;} set { tooltip = value;} } public StyleInfo SI { get { return si;} set { si = value;} } #region ICloneable Members public object Clone() { return this.MemberwiseClone(); } #endregion #region IComparable Members // Sort items based on zindex, then on order items were added to array public int CompareTo(object obj) { PageItem pi = obj as PageItem; int rc = this.zindex - pi.zindex; if (rc == 0) rc = this.itemNumber - pi.itemNumber; return rc; } #endregion } public class PageImage : PageItem, ICloneable { string name; // name of object if constant image ImageFormat imf; // type of image; png, jpeg are supported byte[] imageData; int samplesW; int samplesH; ImageRepeat repeat; ImageSizingEnum sizing; public PageImage(ImageFormat im, byte[] image, int w, int h) { Debug.Assert(im == ImageFormat.Jpeg || im == ImageFormat.Png || im == ImageFormat.Gif || im == ImageFormat.Wmf, "PageImage only supports Jpeg, Gif and Png and WMF image formats (Thanks HYNE!)."); imf = im; imageData = image; samplesW = w; samplesH = h; repeat = ImageRepeat.NoRepeat; sizing = ImageSizingEnum.AutoSize; } public byte[] ImageData { get {return imageData;} } public ImageFormat ImgFormat { get {return imf;} } public string Name { get {return name;} set {name = value;} } public ImageRepeat Repeat { get {return repeat;} set {repeat = value;} } public ImageSizingEnum Sizing { get {return sizing;} set {sizing = value;} } public int SamplesW { get {return samplesW;} } public int SamplesH { get {return samplesH;} } #region ICloneable Members new public object Clone() { return this.MemberwiseClone(); } #endregion } public enum ImageRepeat { Repeat, // repeat image in both x and y directions NoRepeat, // don't repeat RepeatX, // repeat image in x direction RepeatY // repeat image in y direction } public class PageEllipse : PageItem, ICloneable { public PageEllipse() { } #region ICloneable Members new public object Clone() { return this.MemberwiseClone(); } #endregion } public class PageLine : PageItem, ICloneable { public PageLine() { } public float X2 { get {return W;} set {W = value;} } public float Y2 { get {return H;} set {H = value;} } #region ICloneable Members new public object Clone() { return this.MemberwiseClone(); } #endregion } public class PageCurve : PageItem, ICloneable { PointF[] _pointsF; int _offset; float _Tension; public PageCurve() { } public PointF[] Points { get { return _pointsF; } set { _pointsF = value; } } public int Offset { get { return _offset; } set { _offset = value; } } public float Tension { get { return _Tension; } set { _Tension = value; } } #region ICloneable Members new public object Clone() { return this.MemberwiseClone(); } #endregion } public class PagePolygon : PageItem, ICloneable { PointF[] Ps; public PagePolygon() { } public PointF[] Points { get {return Ps;} set {Ps = value;} } } public class PagePie : PageItem, ICloneable { Single SA; Single SW; public PagePie() { } public Single StartAngle { get { return SA; } set { SA = value; } } public Single SweepAngle { get { return SW; } set { SW = value; } } #region ICloneable Members new public object Clone() { return this.MemberwiseClone(); } #endregion } public class PageRectangle : PageItem, ICloneable { public PageRectangle() { } #region ICloneable Members new public object Clone() { return this.MemberwiseClone(); } #endregion } public class PageText : PageItem, ICloneable { string text; // the text float descent; // in some cases the Font descent will be recorded; 0 otherwise bool bGrow; bool _NoClip=false; // on drawing disallow clipping PageTextHtml _HtmlParent=null; public PageText(string t) { text = t; descent=0; bGrow=false; } public PageTextHtml HtmlParent { get { return _HtmlParent; } set { _HtmlParent = value; } } public string Text { get {return text;} set {text = value;} } public float Descent { get {return descent;} set {descent = value;} } public bool NoClip { get {return _NoClip;} set {_NoClip = value;} } public bool CanGrow { get {return bGrow;} set {bGrow = value;} } #region ICloneable Members new public object Clone() { return this.MemberwiseClone(); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedFeedServiceClientTest { [Category("Autogenerated")][Test] public void GetFeedRequestObject() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); GetFeedRequest request = new GetFeedRequest { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::Feed expectedResponse = new gagvr::Feed { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), Attributes = { new gagvr::FeedAttribute(), }, Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified, PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(), AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(), Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled, AttributeOperations = { new gagvr::FeedAttributeOperation(), }, Id = -6774108720365892680L, FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::Feed response = client.GetFeed(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetFeedRequestObjectAsync() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); GetFeedRequest request = new GetFeedRequest { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::Feed expectedResponse = new gagvr::Feed { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), Attributes = { new gagvr::FeedAttribute(), }, Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified, PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(), AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(), Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled, AttributeOperations = { new gagvr::FeedAttributeOperation(), }, Id = -6774108720365892680L, FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Feed>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::Feed responseCallSettings = await client.GetFeedAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Feed responseCancellationToken = await client.GetFeedAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetFeed() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); GetFeedRequest request = new GetFeedRequest { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::Feed expectedResponse = new gagvr::Feed { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), Attributes = { new gagvr::FeedAttribute(), }, Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified, PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(), AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(), Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled, AttributeOperations = { new gagvr::FeedAttributeOperation(), }, Id = -6774108720365892680L, FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::Feed response = client.GetFeed(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetFeedAsync() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); GetFeedRequest request = new GetFeedRequest { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::Feed expectedResponse = new gagvr::Feed { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), Attributes = { new gagvr::FeedAttribute(), }, Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified, PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(), AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(), Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled, AttributeOperations = { new gagvr::FeedAttributeOperation(), }, Id = -6774108720365892680L, FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Feed>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::Feed responseCallSettings = await client.GetFeedAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Feed responseCancellationToken = await client.GetFeedAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetFeedResourceNames() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); GetFeedRequest request = new GetFeedRequest { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::Feed expectedResponse = new gagvr::Feed { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), Attributes = { new gagvr::FeedAttribute(), }, Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified, PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(), AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(), Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled, AttributeOperations = { new gagvr::FeedAttributeOperation(), }, Id = -6774108720365892680L, FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetFeed(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::Feed response = client.GetFeed(request.ResourceNameAsFeedName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetFeedResourceNamesAsync() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); GetFeedRequest request = new GetFeedRequest { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; gagvr::Feed expectedResponse = new gagvr::Feed { ResourceNameAsFeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), Attributes = { new gagvr::FeedAttribute(), }, Origin = gagve::FeedOriginEnum.Types.FeedOrigin.Unspecified, PlacesLocationFeedData = new gagvr::Feed.Types.PlacesLocationFeedData(), AffiliateLocationFeedData = new gagvr::Feed.Types.AffiliateLocationFeedData(), Status = gagve::FeedStatusEnum.Types.FeedStatus.Enabled, AttributeOperations = { new gagvr::FeedAttributeOperation(), }, Id = -6774108720365892680L, FeedName = gagvr::FeedName.FromCustomerFeed("[CUSTOMER_ID]", "[FEED_ID]"), }; mockGrpcClient.Setup(x => x.GetFeedAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::Feed>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); gagvr::Feed responseCallSettings = await client.GetFeedAsync(request.ResourceNameAsFeedName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::Feed responseCancellationToken = await client.GetFeedAsync(request.ResourceNameAsFeedName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateFeedsRequestObject() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); MutateFeedsRequest request = new MutateFeedsRequest { CustomerId = "customer_id3b3724cb", Operations = { new FeedOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateFeedsResponse expectedResponse = new MutateFeedsResponse { Results = { new MutateFeedResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateFeeds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); MutateFeedsResponse response = client.MutateFeeds(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateFeedsRequestObjectAsync() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); MutateFeedsRequest request = new MutateFeedsRequest { CustomerId = "customer_id3b3724cb", Operations = { new FeedOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateFeedsResponse expectedResponse = new MutateFeedsResponse { Results = { new MutateFeedResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateFeedsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); MutateFeedsResponse responseCallSettings = await client.MutateFeedsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateFeedsResponse responseCancellationToken = await client.MutateFeedsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateFeeds() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); MutateFeedsRequest request = new MutateFeedsRequest { CustomerId = "customer_id3b3724cb", Operations = { new FeedOperation(), }, }; MutateFeedsResponse expectedResponse = new MutateFeedsResponse { Results = { new MutateFeedResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateFeeds(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); MutateFeedsResponse response = client.MutateFeeds(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateFeedsAsync() { moq::Mock<FeedService.FeedServiceClient> mockGrpcClient = new moq::Mock<FeedService.FeedServiceClient>(moq::MockBehavior.Strict); MutateFeedsRequest request = new MutateFeedsRequest { CustomerId = "customer_id3b3724cb", Operations = { new FeedOperation(), }, }; MutateFeedsResponse expectedResponse = new MutateFeedsResponse { Results = { new MutateFeedResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateFeedsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateFeedsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); FeedServiceClient client = new FeedServiceClientImpl(mockGrpcClient.Object, null); MutateFeedsResponse responseCallSettings = await client.MutateFeedsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateFeedsResponse responseCancellationToken = await client.MutateFeedsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// 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.Reflection; using Xunit; namespace System.Runtime.Serialization.Formatters.Tests { public class BinaryFormatterTests { [Fact] public void SerializationInfoAddGet() { var value = new Serializable(); var si = new SerializationInfo(typeof(Serializable), FormatterConverter.Default); var sc = new StreamingContext(); value.GetObjectData(si, sc); Assert.Equal(typeof(Serializable), si.ObjectType); Assert.Equal(typeof(Serializable).FullName, si.FullTypeName); Assert.Equal(typeof(Serializable).GetTypeInfo().Assembly.FullName, si.AssemblyName); Assert.Equal(15, si.MemberCount); Assert.Equal(true, si.GetBoolean("bool")); Assert.Equal("hello", si.GetString("string")); Assert.Equal('a', si.GetChar("char")); Assert.Equal(byte.MaxValue, si.GetByte("byte")); Assert.Equal(decimal.MaxValue, si.GetDecimal("decimal")); Assert.Equal(double.MaxValue, si.GetDouble("double")); Assert.Equal(short.MaxValue, si.GetInt16("short")); Assert.Equal(int.MaxValue, si.GetInt32("int")); Assert.Equal(long.MaxValue, si.GetInt64("long")); Assert.Equal(sbyte.MaxValue, si.GetSByte("sbyte")); Assert.Equal(float.MaxValue, si.GetSingle("float")); Assert.Equal(ushort.MaxValue, si.GetUInt16("ushort")); Assert.Equal(uint.MaxValue, si.GetUInt32("uint")); Assert.Equal(ulong.MaxValue, si.GetUInt64("ulong")); Assert.Equal(DateTime.MaxValue, si.GetDateTime("datetime")); } [Fact] public void SerializationInfoEnumerate() { var value = new Serializable(); var si = new SerializationInfo(typeof(Serializable), FormatterConverter.Default); var sc = new StreamingContext(); value.GetObjectData(si, sc); int items = 0; foreach (SerializationEntry entry in si) { items++; switch (entry.Name) { case "int": Assert.Equal(int.MaxValue, (int)entry.Value); Assert.Equal(typeof(int), entry.ObjectType); break; case "string": Assert.Equal("hello", (string)entry.Value); Assert.Equal(typeof(string), entry.ObjectType); break; case "bool": Assert.Equal(true, (bool)entry.Value); Assert.Equal(typeof(bool), entry.ObjectType); break; } } Assert.Equal(si.MemberCount, items); } [Fact] public void NegativeAddValueTwice() { var si = new SerializationInfo(typeof(Serializable), FormatterConverter.Default); Assert.Throws<SerializationException>(() => { si.AddValue("bool", true); si.AddValue("bool", true); }); try { si.AddValue("bool", false); } catch (Exception e) { Assert.Equal("Cannot add the same member twice to a SerializationInfo object.", e.Message); } } [Fact] public void NegativeValueNotFound() { var si = new SerializationInfo(typeof(Serializable), FormatterConverter.Default); Assert.Throws<SerializationException>(() => { si.AddValue("a", 1); si.GetInt32("b"); }); si = new SerializationInfo(typeof(Serializable), FormatterConverter.Default); try { si.AddValue("a", 1); si.GetInt32("b"); } catch (Exception e) { Assert.Equal("Member 'b' was not found.", e.Message); } } } [Serializable] internal class Serializable : ISerializable { public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("string", "hello"); info.AddValue("bool", true); info.AddValue("char", 'a'); info.AddValue("byte", byte.MaxValue); info.AddValue("decimal", decimal.MaxValue); info.AddValue("double", double.MaxValue); info.AddValue("short", short.MaxValue); info.AddValue("int", int.MaxValue); info.AddValue("long", long.MaxValue); info.AddValue("sbyte", sbyte.MaxValue); info.AddValue("float", float.MaxValue); info.AddValue("ushort", ushort.MaxValue); info.AddValue("uint", uint.MaxValue); info.AddValue("ulong", ulong.MaxValue); info.AddValue("datetime", DateTime.MaxValue); } } internal class FormatterConverter : IFormatterConverter { public static readonly FormatterConverter Default = new FormatterConverter(); public object Convert(object value, TypeCode typeCode) { throw new NotImplementedException(); } public object Convert(object value, Type type) { throw new NotImplementedException(); } public bool ToBoolean(object value) { throw new NotImplementedException(); } public byte ToByte(object value) { throw new NotImplementedException(); } public char ToChar(object value) { throw new NotImplementedException(); } public DateTime ToDateTime(object value) { throw new NotImplementedException(); } public decimal ToDecimal(object value) { throw new NotImplementedException(); } public double ToDouble(object value) { throw new NotImplementedException(); } public short ToInt16(object value) { throw new NotImplementedException(); } public int ToInt32(object value) { throw new NotImplementedException(); } public long ToInt64(object value) { throw new NotImplementedException(); } public sbyte ToSByte(object value) { throw new NotImplementedException(); } public float ToSingle(object value) { throw new NotImplementedException(); } public string ToString(object value) { throw new NotImplementedException(); } public ushort ToUInt16(object value) { throw new NotImplementedException(); } public uint ToUInt32(object value) { throw new NotImplementedException(); } public ulong ToUInt64(object value) { throw new NotImplementedException(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Xml; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.DataSnapshot.Interfaces; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.DataSnapshot { public class DataSnapshotManager : IRegionModule, IDataSnapshot { #region Class members //Information from config private bool m_enabled = false; private bool m_configLoaded = false; private List<string> m_disabledModules = new List<string>(); private Dictionary<string, string> m_gridinfo = new Dictionary<string, string>(); private string m_snapsDir = "DataSnapshot"; private string m_exposure_level = "minimum"; //Lists of stuff we need private List<Scene> m_scenes = new List<Scene>(); private List<IDataSnapshotProvider> m_dataproviders = new List<IDataSnapshotProvider>(); //Various internal objects private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); internal object m_syncInit = new object(); //DataServices and networking private string m_dataServices = "noservices"; public string m_listener_port = ConfigSettings.DefaultRegionHttpPort.ToString(); public string m_hostname = "127.0.0.1"; //Update timers private int m_period = 20; // in seconds private int m_maxStales = 500; private int m_stales = 0; private int m_lastUpdate = 0; //Program objects private SnapshotStore m_snapStore = null; #endregion #region Properties public string ExposureLevel { get { return m_exposure_level; } } #endregion #region IRegionModule public void Initialise(Scene scene, IConfigSource config) { if (!m_configLoaded) { m_configLoaded = true; //m_log.Debug("[DATASNAPSHOT]: Loading configuration"); //Read from the config for options lock (m_syncInit) { try { m_enabled = config.Configs["DataSnapshot"].GetBoolean("index_sims", m_enabled); IConfig conf = config.Configs["GridService"]; if (conf != null) m_gridinfo.Add("gridserverURL", conf.GetString("GridServerURI", "http://127.0.0.1:8003")); m_gridinfo.Add( "Name", config.Configs["DataSnapshot"].GetString("gridname", "the lost continent of hippo")); m_exposure_level = config.Configs["DataSnapshot"].GetString("data_exposure", m_exposure_level); m_period = config.Configs["DataSnapshot"].GetInt("default_snapshot_period", m_period); m_maxStales = config.Configs["DataSnapshot"].GetInt("max_changes_before_update", m_maxStales); m_snapsDir = config.Configs["DataSnapshot"].GetString("snapshot_cache_directory", m_snapsDir); m_dataServices = config.Configs["DataSnapshot"].GetString("data_services", m_dataServices); m_listener_port = config.Configs["Network"].GetString("http_listener_port", m_listener_port); String[] annoying_string_array = config.Configs["DataSnapshot"].GetString("disable_modules", "").Split(".".ToCharArray()); foreach (String bloody_wanker in annoying_string_array) { m_disabledModules.Add(bloody_wanker); } m_lastUpdate = Environment.TickCount; } catch (Exception) { m_log.Warn("[DATASNAPSHOT]: Could not load configuration. DataSnapshot will be disabled."); m_enabled = false; return; } } if (m_enabled) { //Hand it the first scene, assuming that all scenes have the same BaseHTTPServer new DataRequestHandler(scene, this); m_hostname = scene.RegionInfo.ExternalHostName; m_snapStore = new SnapshotStore(m_snapsDir, m_gridinfo, m_listener_port, m_hostname); MakeEverythingStale(); if (m_dataServices != "" && m_dataServices != "noservices") NotifyDataServices(m_dataServices, "online"); } } if (m_enabled) { m_log.Info("[DATASNAPSHOT]: Scene added to module."); m_snapStore.AddScene(scene); m_scenes.Add(scene); Assembly currentasm = Assembly.GetExecutingAssembly(); foreach (Type pluginType in currentasm.GetTypes()) { if (pluginType.IsPublic) { if (!pluginType.IsAbstract) { if (pluginType.GetInterface("IDataSnapshotProvider") != null) { IDataSnapshotProvider module = (IDataSnapshotProvider)Activator.CreateInstance(pluginType); module.Initialize(scene, this); module.OnStale += MarkDataStale; m_dataproviders.Add(module); m_snapStore.AddProvider(module); m_log.Info("[DATASNAPSHOT]: Added new data provider type: " + pluginType.Name); } } } } //scene.OnRestart += OnSimRestart; scene.EventManager.OnShutdown += delegate() { OnSimRestart(scene.RegionInfo); }; } else { //m_log.Debug("[DATASNAPSHOT]: Data snapshot disabled, not adding scene to module (or anything else)."); } } public void Close() { if (m_enabled && m_dataServices != "" && m_dataServices != "noservices") NotifyDataServices(m_dataServices, "offline"); } public bool IsSharedModule { get { return true; } } public string Name { get { return "External Data Generator"; } } public void PostInitialise() { } #endregion #region Associated helper functions public Scene SceneForName(string name) { foreach (Scene scene in m_scenes) if (scene.RegionInfo.RegionName == name) return scene; return null; } public Scene SceneForUUID(UUID id) { foreach (Scene scene in m_scenes) if (scene.RegionInfo.RegionID == id) return scene; return null; } #endregion #region [Public] Snapshot storage functions /** * Reply to the http request */ public XmlDocument GetSnapshot(string regionName) { CheckStale(); XmlDocument requestedSnap = new XmlDocument(); requestedSnap.AppendChild(requestedSnap.CreateXmlDeclaration("1.0", null, null)); requestedSnap.AppendChild(requestedSnap.CreateWhitespace("\r\n")); XmlNode regiondata = requestedSnap.CreateNode(XmlNodeType.Element, "regiondata", ""); try { if (regionName == null || regionName == "") { XmlNode timerblock = requestedSnap.CreateNode(XmlNodeType.Element, "expire", ""); timerblock.InnerText = m_period.ToString(); regiondata.AppendChild(timerblock); regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n")); foreach (Scene scene in m_scenes) { regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap)); } } else { Scene scene = SceneForName(regionName); regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap)); } requestedSnap.AppendChild(regiondata); regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n")); } catch (XmlException e) { m_log.Warn("[DATASNAPSHOT]: XmlException while trying to load snapshot: " + e.ToString()); requestedSnap = GetErrorMessage(regionName, e); } catch (Exception e) { m_log.Warn("[DATASNAPSHOT]: Caught unknown exception while trying to load snapshot: " + e.StackTrace); requestedSnap = GetErrorMessage(regionName, e); } return requestedSnap; } private XmlDocument GetErrorMessage(string regionName, Exception e) { XmlDocument errorMessage = new XmlDocument(); XmlNode error = errorMessage.CreateNode(XmlNodeType.Element, "error", ""); XmlNode region = errorMessage.CreateNode(XmlNodeType.Element, "region", ""); region.InnerText = regionName; XmlNode exception = errorMessage.CreateNode(XmlNodeType.Element, "exception", ""); exception.InnerText = e.ToString(); error.AppendChild(region); error.AppendChild(exception); errorMessage.AppendChild(error); return errorMessage; } #endregion #region External data services private void NotifyDataServices(string servicesStr, string serviceName) { Stream reply = null; string delimStr = ";"; char [] delimiter = delimStr.ToCharArray(); string[] services = servicesStr.Split(delimiter); for (int i = 0; i < services.Length; i++) { string url = services[i].Trim(); RestClient cli = new RestClient(url); cli.AddQueryParameter("service", serviceName); cli.AddQueryParameter("host", m_hostname); cli.AddQueryParameter("port", m_listener_port); cli.RequestMethod = "GET"; try { reply = cli.Request(); } catch (WebException) { m_log.Warn("[DATASNAPSHOT]: Unable to notify " + url); } catch (Exception e) { m_log.Warn("[DATASNAPSHOT]: Ignoring unknown exception " + e.ToString()); } byte[] response = new byte[1024]; // int n = 0; try { // n = reply.Read(response, 0, 1024); reply.Read(response, 0, 1024); } catch (Exception e) { m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace); } // This is not quite working, so... // string responseStr = Util.UTF8.GetString(response); m_log.Info("[DATASNAPSHOT]: data service notified: " + url); } } #endregion #region Latency-based update functions public void MarkDataStale(IDataSnapshotProvider provider) { //Behavior here: Wait m_period seconds, then update if there has not been a request in m_period seconds //or m_maxStales has been exceeded m_stales++; } private void CheckStale() { // Wrap check if (Environment.TickCount < m_lastUpdate) { m_lastUpdate = Environment.TickCount; } if (m_stales >= m_maxStales) { if (Environment.TickCount - m_lastUpdate >= 20000) { m_stales = 0; m_lastUpdate = Environment.TickCount; MakeEverythingStale(); } } else { if (m_lastUpdate + 1000 * m_period < Environment.TickCount) { m_stales = 0; m_lastUpdate = Environment.TickCount; MakeEverythingStale(); } } } public void MakeEverythingStale() { m_log.Debug("[DATASNAPSHOT]: Marking all scenes as stale."); foreach (Scene scene in m_scenes) { m_snapStore.ForceSceneStale(scene); } } #endregion public void OnSimRestart(RegionInfo thisRegion) { m_log.Info("[DATASNAPSHOT]: Region " + thisRegion.RegionName + " is restarting, removing from indexing"); Scene restartedScene = SceneForUUID(thisRegion.RegionID); m_scenes.Remove(restartedScene); m_snapStore.RemoveScene(restartedScene); //Getting around the fact that we can't remove objects from a collection we are enumerating over List<IDataSnapshotProvider> providersToRemove = new List<IDataSnapshotProvider>(); foreach (IDataSnapshotProvider provider in m_dataproviders) { if (provider.GetParentScene == restartedScene) { providersToRemove.Add(provider); } } foreach (IDataSnapshotProvider provider in providersToRemove) { m_dataproviders.Remove(provider); m_snapStore.RemoveProvider(provider); } m_snapStore.RemoveScene(restartedScene); } } }
using System; using System.Drawing; using System.IO; using System.Linq; using System.Reflection; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; namespace DockSample { public partial class MainForm : Form { private bool m_bSaveLayout = true; private DeserializeDockContent m_deserializeDockContent; private DummySolutionExplorer m_solutionExplorer; private DummyPropertyWindow m_propertyWindow; private DummyToolbox m_toolbox; private DummyOutputWindow m_outputWindow; private DummyTaskList m_taskList; private bool _showSplash; private SplashScreen _splashScreen; public MainForm() { InitializeComponent(); AutoScaleMode = AutoScaleMode.Dpi; SetSplashScreen(); CreateStandardControls(); showRightToLeft.Checked = (RightToLeft == RightToLeft.Yes); RightToLeftLayout = showRightToLeft.Checked; m_solutionExplorer.RightToLeftLayout = RightToLeftLayout; m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString); vsToolStripExtender1.DefaultRenderer = _toolStripProfessionalRenderer; SetSchema(this.menuItemSchemaVS2013Blue, null); } #region Methods private IDockContent FindDocument(string text) { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { foreach (Form form in MdiChildren) if (form.Text == text) return form as IDockContent; return null; } else { foreach (IDockContent content in dockPanel.Documents) if (content.DockHandler.TabText == text) return content; return null; } } private DummyDoc CreateNewDocument() { DummyDoc dummyDoc = new DummyDoc(); int count = 1; string text = $"Document{count}"; while (FindDocument(text) != null) { count++; text = $"Document{count}"; } dummyDoc.Text = text; return dummyDoc; } private DummyDoc CreateNewDocument(string text) { DummyDoc dummyDoc = new DummyDoc(); dummyDoc.Text = text; return dummyDoc; } private void CloseAllDocuments() { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { foreach (Form form in MdiChildren) form.Close(); } else { foreach (IDockContent document in dockPanel.DocumentsToArray()) { // IMPORANT: dispose all panes. document.DockHandler.DockPanel = null; document.DockHandler.Close(); } } } private IDockContent GetContentFromPersistString(string persistString) { if (persistString == typeof(DummySolutionExplorer).ToString()) return m_solutionExplorer; else if (persistString == typeof(DummyPropertyWindow).ToString()) return m_propertyWindow; else if (persistString == typeof(DummyToolbox).ToString()) return m_toolbox; else if (persistString == typeof(DummyOutputWindow).ToString()) return m_outputWindow; else if (persistString == typeof(DummyTaskList).ToString()) return m_taskList; else { // DummyDoc overrides GetPersistString to add extra information into persistString. // Any DockContent may override this value to add any needed information for deserialization. string[] parsedStrings = persistString.Split(new char[] { ',' }); if (parsedStrings.Length != 3) return null; if (parsedStrings[0] != typeof(DummyDoc).ToString()) return null; DummyDoc dummyDoc = new DummyDoc(); if (parsedStrings[1] != string.Empty) dummyDoc.FileName = parsedStrings[1]; if (parsedStrings[2] != string.Empty) dummyDoc.Text = parsedStrings[2]; return dummyDoc; } } private void CloseAllContents() { // we don't want to create another instance of tool window, set DockPanel to null m_solutionExplorer.DockPanel = null; m_propertyWindow.DockPanel = null; m_toolbox.DockPanel = null; m_outputWindow.DockPanel = null; m_taskList.DockPanel = null; // Close all other document windows CloseAllDocuments(); // IMPORTANT: dispose all float windows. foreach (var window in dockPanel.FloatWindows.ToList()) window.Dispose(); System.Diagnostics.Debug.Assert(dockPanel.Panes.Count == 0); System.Diagnostics.Debug.Assert(dockPanel.Contents.Count == 0); System.Diagnostics.Debug.Assert(dockPanel.FloatWindows.Count == 0); } private readonly ToolStripRenderer _toolStripProfessionalRenderer = new ToolStripProfessionalRenderer(); private void SetSchema(object sender, System.EventArgs e) { // Persist settings when rebuilding UI string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.temp.config"); dockPanel.SaveAsXml(configFile); CloseAllContents(); if (sender == this.menuItemSchemaVS2005) { this.dockPanel.Theme = this.vS2005Theme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2005, vS2005Theme1); } else if (sender == this.menuItemSchemaVS2003) { this.dockPanel.Theme = this.vS2003Theme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2003, vS2003Theme1); } else if (sender == this.menuItemSchemaVS2010Blue) { this.dockPanel.Theme = this.vS2010BlueTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2010, vS2010BlueTheme1); } else if (sender == this.menuItemSchemaVS2012Light) { this.dockPanel.Theme = this.vS2012LightTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2012, vS2012LightTheme1); } else if (sender == this.menuItemSchemaVS2012Blue) { this.dockPanel.Theme = this.vS2012BlueTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2012, vS2012BlueTheme1); } else if (sender == this.menuItemSchemaVS2012Dark) { this.dockPanel.Theme = this.vS2012DarkTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2012, vS2012DarkTheme1); } else if (sender == this.menuItemSchemaVS2013Blue) { this.dockPanel.Theme = this.vS2013BlueTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2013, vS2013BlueTheme1); } else if (sender == this.menuItemSchemaVS2013Light) { this.dockPanel.Theme = this.vS2013LightTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2013, vS2013LightTheme1); } else if (sender == this.menuItemSchemaVS2013Dark) { this.dockPanel.Theme = this.vS2013DarkTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2013, vS2013DarkTheme1); } else if (sender == this.menuItemSchemaVS2015Blue) { this.dockPanel.Theme = this.vS2015BlueTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015BlueTheme1); } else if (sender == this.menuItemSchemaVS2015Light) { this.dockPanel.Theme = this.vS2015LightTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015LightTheme1); } else if (sender == this.menuItemSchemaVS2015Dark) { this.dockPanel.Theme = this.vS2015DarkTheme1; this.EnableVSRenderer(VisualStudioToolStripExtender.VsVersion.Vs2015, vS2015DarkTheme1); } menuItemSchemaVS2005.Checked = (sender == menuItemSchemaVS2005); menuItemSchemaVS2003.Checked = (sender == menuItemSchemaVS2003); menuItemSchemaVS2010Blue.Checked = (sender == menuItemSchemaVS2010Blue); menuItemSchemaVS2012Light.Checked = (sender == menuItemSchemaVS2012Light); menuItemSchemaVS2012Blue.Checked = (sender == menuItemSchemaVS2012Blue); menuItemSchemaVS2012Dark.Checked = (sender == menuItemSchemaVS2012Dark); menuItemSchemaVS2013Light.Checked = (sender == menuItemSchemaVS2013Light); menuItemSchemaVS2013Blue.Checked = (sender == menuItemSchemaVS2013Blue); menuItemSchemaVS2013Dark.Checked = (sender == menuItemSchemaVS2013Dark); menuItemSchemaVS2015Light.Checked = (sender == menuItemSchemaVS2015Light); menuItemSchemaVS2015Blue.Checked = (sender == menuItemSchemaVS2015Blue); menuItemSchemaVS2015Dark.Checked = (sender == menuItemSchemaVS2015Dark); if (dockPanel.Theme.ColorPalette != null) { statusBar.BackColor = dockPanel.Theme.ColorPalette.MainWindowStatusBarDefault.Background; } if (File.Exists(configFile)) dockPanel.LoadFromXml(configFile, m_deserializeDockContent); } private void EnableVSRenderer(VisualStudioToolStripExtender.VsVersion version, ThemeBase theme) { vsToolStripExtender1.SetStyle(mainMenu, version, theme); vsToolStripExtender1.SetStyle(toolBar, version, theme); vsToolStripExtender1.SetStyle(statusBar, version, theme); } private void SetDocumentStyle(object sender, System.EventArgs e) { DocumentStyle oldStyle = dockPanel.DocumentStyle; DocumentStyle newStyle; if (sender == menuItemDockingMdi) newStyle = DocumentStyle.DockingMdi; else if (sender == menuItemDockingWindow) newStyle = DocumentStyle.DockingWindow; else if (sender == menuItemDockingSdi) newStyle = DocumentStyle.DockingSdi; else newStyle = DocumentStyle.SystemMdi; if (oldStyle == newStyle) return; if (oldStyle == DocumentStyle.SystemMdi || newStyle == DocumentStyle.SystemMdi) CloseAllDocuments(); dockPanel.DocumentStyle = newStyle; menuItemDockingMdi.Checked = (newStyle == DocumentStyle.DockingMdi); menuItemDockingWindow.Checked = (newStyle == DocumentStyle.DockingWindow); menuItemDockingSdi.Checked = (newStyle == DocumentStyle.DockingSdi); menuItemSystemMdi.Checked = (newStyle == DocumentStyle.SystemMdi); menuItemLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi); menuItemLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi); toolBarButtonLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi); toolBarButtonLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi); } #endregion #region Event Handlers private void menuItemExit_Click(object sender, System.EventArgs e) { Close(); } private void menuItemSolutionExplorer_Click(object sender, System.EventArgs e) { m_solutionExplorer.Show(dockPanel); } private void menuItemPropertyWindow_Click(object sender, System.EventArgs e) { m_propertyWindow.Show(dockPanel); } private void menuItemToolbox_Click(object sender, System.EventArgs e) { m_toolbox.Show(dockPanel); } private void menuItemOutputWindow_Click(object sender, System.EventArgs e) { m_outputWindow.Show(dockPanel); } private void menuItemTaskList_Click(object sender, System.EventArgs e) { m_taskList.Show(dockPanel); } private void menuItemAbout_Click(object sender, System.EventArgs e) { AboutDialog aboutDialog = new AboutDialog(); aboutDialog.ShowDialog(this); } private void menuItemNew_Click(object sender, System.EventArgs e) { DummyDoc dummyDoc = CreateNewDocument(); if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { dummyDoc.MdiParent = this; dummyDoc.Show(); } else dummyDoc.Show(dockPanel); } private void menuItemOpen_Click(object sender, System.EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.InitialDirectory = Application.ExecutablePath; openFile.Filter = "rtf files (*.rtf)|*.rtf|txt files (*.txt)|*.txt|All files (*.*)|*.*"; openFile.FilterIndex = 1; openFile.RestoreDirectory = true; if (openFile.ShowDialog() == DialogResult.OK) { string fullName = openFile.FileName; string fileName = Path.GetFileName(fullName); if (FindDocument(fileName) != null) { MessageBox.Show("The document: " + fileName + " has already opened!"); return; } DummyDoc dummyDoc = new DummyDoc(); dummyDoc.Text = fileName; if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { dummyDoc.MdiParent = this; dummyDoc.Show(); } else dummyDoc.Show(dockPanel); try { dummyDoc.FileName = fullName; } catch (Exception exception) { dummyDoc.Close(); MessageBox.Show(exception.Message); } } } private void menuItemFile_Popup(object sender, System.EventArgs e) { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { menuItemClose.Enabled = menuItemCloseAll.Enabled = menuItemCloseAllButThisOne.Enabled = (ActiveMdiChild != null); } else { menuItemClose.Enabled = (dockPanel.ActiveDocument != null); menuItemCloseAll.Enabled = menuItemCloseAllButThisOne.Enabled = (dockPanel.DocumentsCount > 0); } } private void menuItemClose_Click(object sender, System.EventArgs e) { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) ActiveMdiChild.Close(); else if (dockPanel.ActiveDocument != null) dockPanel.ActiveDocument.DockHandler.Close(); } private void menuItemCloseAll_Click(object sender, System.EventArgs e) { CloseAllDocuments(); } private void MainForm_Load(object sender, System.EventArgs e) { string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config"); if (File.Exists(configFile)) dockPanel.LoadFromXml(configFile, m_deserializeDockContent); } private void MainForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config"); if (m_bSaveLayout) dockPanel.SaveAsXml(configFile); else if (File.Exists(configFile)) File.Delete(configFile); } private void menuItemToolBar_Click(object sender, System.EventArgs e) { toolBar.Visible = menuItemToolBar.Checked = !menuItemToolBar.Checked; } private void menuItemStatusBar_Click(object sender, System.EventArgs e) { statusBar.Visible = menuItemStatusBar.Checked = !menuItemStatusBar.Checked; } private void toolBar_ButtonClick(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e) { if (e.ClickedItem == toolBarButtonNew) menuItemNew_Click(null, null); else if (e.ClickedItem == toolBarButtonOpen) menuItemOpen_Click(null, null); else if (e.ClickedItem == toolBarButtonSolutionExplorer) menuItemSolutionExplorer_Click(null, null); else if (e.ClickedItem == toolBarButtonPropertyWindow) menuItemPropertyWindow_Click(null, null); else if (e.ClickedItem == toolBarButtonToolbox) menuItemToolbox_Click(null, null); else if (e.ClickedItem == toolBarButtonOutputWindow) menuItemOutputWindow_Click(null, null); else if (e.ClickedItem == toolBarButtonTaskList) menuItemTaskList_Click(null, null); else if (e.ClickedItem == toolBarButtonLayoutByCode) menuItemLayoutByCode_Click(null, null); else if (e.ClickedItem == toolBarButtonLayoutByXml) menuItemLayoutByXml_Click(null, null); } private void menuItemNewWindow_Click(object sender, System.EventArgs e) { MainForm newWindow = new MainForm(); newWindow.Text = newWindow.Text + " - New"; newWindow.Show(); } private void menuItemTools_Popup(object sender, System.EventArgs e) { menuItemLockLayout.Checked = !this.dockPanel.AllowEndUserDocking; } private void menuItemLockLayout_Click(object sender, System.EventArgs e) { dockPanel.AllowEndUserDocking = !dockPanel.AllowEndUserDocking; } private void menuItemLayoutByCode_Click(object sender, System.EventArgs e) { dockPanel.SuspendLayout(true); CloseAllContents(); CreateStandardControls(); m_solutionExplorer.Show(dockPanel, DockState.DockRight); m_propertyWindow.Show(m_solutionExplorer.Pane, m_solutionExplorer); m_toolbox.Show(dockPanel, new Rectangle(98, 133, 200, 383)); m_outputWindow.Show(m_solutionExplorer.Pane, DockAlignment.Bottom, 0.35); m_taskList.Show(m_toolbox.Pane, DockAlignment.Left, 0.4); DummyDoc doc1 = CreateNewDocument("Document1"); DummyDoc doc2 = CreateNewDocument("Document2"); DummyDoc doc3 = CreateNewDocument("Document3"); DummyDoc doc4 = CreateNewDocument("Document4"); doc1.Show(dockPanel, DockState.Document); doc2.Show(doc1.Pane, null); doc3.Show(doc1.Pane, DockAlignment.Bottom, 0.5); doc4.Show(doc3.Pane, DockAlignment.Right, 0.5); dockPanel.ResumeLayout(true, true); } private void SetSplashScreen() { _showSplash = true; _splashScreen = new SplashScreen(); ResizeSplash(); _splashScreen.Visible = true; _splashScreen.TopMost = true; Timer _timer = new Timer(); _timer.Tick += (sender, e) => { _splashScreen.Visible = false; _timer.Enabled = false; _showSplash = false; }; _timer.Interval = 4000; _timer.Enabled = true; } private void ResizeSplash() { if (_showSplash) { var centerXMain = (this.Location.X + this.Width) / 2.0; var LocationXSplash = Math.Max(0, centerXMain - (_splashScreen.Width / 2.0)); var centerYMain = (this.Location.Y + this.Height) / 2.0; var LocationYSplash = Math.Max(0, centerYMain - (_splashScreen.Height / 2.0)); _splashScreen.Location = new Point((int)Math.Round(LocationXSplash), (int)Math.Round(LocationYSplash)); } } private void CreateStandardControls() { m_solutionExplorer = new DummySolutionExplorer(); m_propertyWindow = new DummyPropertyWindow(); m_toolbox = new DummyToolbox(); m_outputWindow = new DummyOutputWindow(); m_taskList = new DummyTaskList(); } private void menuItemLayoutByXml_Click(object sender, System.EventArgs e) { dockPanel.SuspendLayout(true); // In order to load layout from XML, we need to close all the DockContents CloseAllContents(); CreateStandardControls(); Assembly assembly = Assembly.GetAssembly(typeof(MainForm)); Stream xmlStream = assembly.GetManifestResourceStream("DockSample.Resources.DockPanel.xml"); dockPanel.LoadFromXml(xmlStream, m_deserializeDockContent); xmlStream.Close(); dockPanel.ResumeLayout(true, true); } private void menuItemCloseAllButThisOne_Click(object sender, System.EventArgs e) { if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi) { Form activeMdi = ActiveMdiChild; foreach (Form form in MdiChildren) { if (form != activeMdi) form.Close(); } } else { foreach (IDockContent document in dockPanel.DocumentsToArray()) { if (!document.DockHandler.IsActivated) document.DockHandler.Close(); } } } private void menuItemShowDocumentIcon_Click(object sender, System.EventArgs e) { dockPanel.ShowDocumentIcon = menuItemShowDocumentIcon.Checked = !menuItemShowDocumentIcon.Checked; } private void showRightToLeft_Click(object sender, EventArgs e) { CloseAllContents(); if (showRightToLeft.Checked) { this.RightToLeft = RightToLeft.No; this.RightToLeftLayout = false; } else { this.RightToLeft = RightToLeft.Yes; this.RightToLeftLayout = true; } m_solutionExplorer.RightToLeftLayout = this.RightToLeftLayout; showRightToLeft.Checked = !showRightToLeft.Checked; } private void exitWithoutSavingLayout_Click(object sender, EventArgs e) { m_bSaveLayout = false; Close(); m_bSaveLayout = true; } #endregion private void MainForm_SizeChanged(object sender, EventArgs e) { ResizeSplash(); } } }
// 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.Linq; using Xunit; namespace Test { [Trait("category", "outerloop")] public partial class ParallelQueryCombinationTests { [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Aggregate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate((x, y) => x + y)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Aggregate_Seed(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Aggregate_Result(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y, r => r)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Aggregate_Accumulator(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Aggregate_SeedFactory(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void Aggregate_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate((x, y) => x)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (x, y) => x + y, r => r)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(0, (a, x) => a + x, (l, r) => l + r, r => r)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Aggregate(() => 0, (a, x) => a + x, (l, r) => l + r, r => r)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void All_False(LabeledOperation source, LabeledOperation operation) { Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).All(x => false)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void All_True(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).All(x => seen.Add(x))); seen.AssertComplete(); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void All_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).All(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Any_False(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => !seen.Add(x))); seen.AssertComplete(); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Any_True(LabeledOperation source, LabeledOperation operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => true)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void Any_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Any(x => false)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Average(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double)DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).Average()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Average_Nullable(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize) / (double?)DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).Average(x => (int?)x)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void Average_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Average()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Cast(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int? i in operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>()) { Assert.True(i.HasValue); Assert.Equal(seen++, i.Value); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Cast_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Cast<int?>().ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Contains_True(LabeledOperation source, LabeledOperation operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize / 2)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Contains_False(LabeledOperation source, LabeledOperation operation) { Assert.False(operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void Contains_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Contains(DefaultStart + DefaultSize)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Count_Elements(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).Count()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Count_Predicate_Some(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Count_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => x < DefaultStart)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void Count_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Count()); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Count(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void DefaultIfEmpty(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty()) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void DefaultIfEmpty_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).DefaultIfEmpty().ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Distinct(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Distinct_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize * 2, source.Item).Select(x => x / 2).Distinct(); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ElementAt(LabeledOperation source, LabeledOperation operation) { ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item); int seen = DefaultStart; for (int i = 0; i < DefaultSize; i++) { Assert.Equal(seen++, query.ElementAt(i)); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void ElementAt_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ElementAt(DefaultSize - 1)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ElementAtOrDefault(LabeledOperation source, LabeledOperation operation) { ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize, source.Item); int seen = DefaultStart; for (int i = 0; i < DefaultSize; i++) { Assert.Equal(seen++, query.ElementAtOrDefault(i)); } Assert.Equal(DefaultStart + DefaultSize, seen); Assert.Equal(default(int), query.ElementAtOrDefault(-1)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void ElementAtOrDefault_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ElementAtOrDefault(DefaultSize - 1)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ElementAtOrDefault(DefaultSize + 1)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Except(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item)); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Except_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item) .Except(operation.Item(DefaultStart + DefaultSize, DefaultSize, source.Item)); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void First(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).First()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void First_Predicate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).First(x => x >= DefaultStart + DefaultSize / 2)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void First_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Throws<InvalidOperationException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).First(x => false)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void First_AggregateException(LabeledOperation source, LabeledOperation operation) { // Concat seems able to return the first element when the left query does not fail ("first" query). // This test might be flaky in the case that it decides to run the right query too... if (operation.ToString().Contains("Concat-Left")) { Assert.InRange(operation.Item(DefaultStart, DefaultSize, source.Item).First(), DefaultStart, DefaultStart + DefaultSize); } else { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).First()); } Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).First(x => false)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void FirstOrDefault(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void FirstOrDefault_Predicate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => x >= DefaultStart + DefaultSize / 2)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void FirstOrDefault_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => false)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void FirstOrDefault_AggregateException(LabeledOperation source, LabeledOperation operation) { // Concat seems able to return the first element when the left query does not fail ("first" query). // This test might be flaky in the case that it decides to run the right query too... if (operation.ToString().Contains("Concat-Left")) { Assert.InRange(operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(), DefaultStart, DefaultStart + DefaultSize); } else { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault()); } Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).FirstOrDefault(x => false)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ForAll(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); operation.Item(DefaultStart, DefaultSize, source.Item).ForAll(x => seen.Add(x)); seen.AssertComplete(); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void ForAll_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ForAll(x => { })); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void GroupBy(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor)) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement++, x)); Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void GroupBy_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor).ToList()) { Assert.Equal(seenKey++, group.Key); int seenElement = group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement++, x)); Assert.Equal(Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void GroupBy_ElementSelector(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y)) { Assert.Equal(seenKey++, group.Key); int seenElement = -group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement--, x)); Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void GroupBy_ElementSelector_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seenKey = DefaultStart / GroupFactor; foreach (IGrouping<int, int> group in operation.Item(DefaultStart, DefaultSize, source.Item).GroupBy(x => x / GroupFactor, y => -y).ToList()) { Assert.Equal(seenKey++, group.Key); int seenElement = -group.Key * GroupFactor; Assert.All(group, x => Assert.Equal(seenElement--, x)); Assert.Equal(-Math.Min((group.Key + 1) * GroupFactor, DefaultStart + DefaultSize), seenElement); } Assert.Equal((DefaultSize + (GroupFactor - 1)) / GroupFactor + 1, seenKey); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Intersect(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Intersect_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart - DefaultSize / 2, DefaultSize + DefaultSize / 2, source.Item) .Intersect(operation.Item(DefaultStart, DefaultSize + DefaultSize / 2, source.Item)); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Last(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Last_Predicate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Last(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Last_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Throws<InvalidOperationException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Last(x => false)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void Last_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Last()); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Last(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void LastOrDefault(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void LastOrDefault_Predicate(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize / 2 - 1, operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void LastOrDefault_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Equal(default(int), operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => false)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void LastOrDefault_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault()); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).LastOrDefault(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void LongCount_Elements(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultSize, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void LongCount_Predicate_Some(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => x < DefaultStart + DefaultSize / 2)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void LongCount_Predicate_None(LabeledOperation source, LabeledOperation operation) { Assert.Equal(0, operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => x < DefaultStart)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void LongCount_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).LongCount()); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).LongCount(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Max(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Max()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Max_Nullable(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart + DefaultSize - 1, operation.Item(DefaultStart, DefaultSize, source.Item).Max(x => (int?)x)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void Max_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Max()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Min(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).Min()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Min_Nullable(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, DefaultSize, source.Item).Min(x => (int?)x)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void Min_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Min()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void OfType(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>()) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void OfType_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<int>().ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void OfType_Other(LabeledOperation source, LabeledOperation operation) { Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void OfType_Other_NotPipelined(LabeledOperation source, LabeledOperation operation) { Assert.Empty(operation.Item(DefaultStart, DefaultSize, source.Item).OfType<long>().ToList()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OrderBy_Initial(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OrderBy_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OrderBy_OtherDirection(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OrderBy_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => -x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OrderByDescending_Initial(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OrderByDescending_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OrderByDescending_OtherDirection(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void OrderByDescending_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderByDescending(x => x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Reverse(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse()) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Reverse_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Reverse().ToList()) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Select(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x)) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Select_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select(x => -x).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Select_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; })) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Select_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Select((x, index) => { Assert.Equal(DefaultStart + index, x); return -x; }).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SelectMany(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x))) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SelectMany_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x)).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SelectMany_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); })) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SelectMany_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }.Select(y => y + -DefaultStart - 2 * x); }).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SelectMany_ResultSelector(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x)) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SelectMany_ResultSelector_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany(x => new[] { 0, -1 }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SelectMany_Indexed_ResultSelector(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; foreach (int i in operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x)) { Assert.Equal(seen--, i); } Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SelectMany_Indexed_ResultSelector_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = -DefaultStart; Assert.All(operation.Item(0, DefaultSize, source.Item).SelectMany((x, index) => { Assert.Equal(index, x); return new[] { 0, -1 }; }, (x, y) => y + -DefaultStart - 2 * x).ToList(), x => Assert.Equal(seen--, x)); Assert.Equal(-DefaultStart - DefaultSize * 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SequenceEqual(LabeledOperation source, LabeledOperation operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered())); Assert.True(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered().SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item))); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SequenceEqual_Self(LabeledOperation source, LabeledOperation operation) { Assert.True(operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item))); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void SequenceEqual_AggregateException(LabeledOperation source, LabeledOperation operation) { // Sequence equal double wraps queries that throw. ThrowsWrapped(() => operation.Item(DefaultStart, DefaultSize, source.Item).SequenceEqual(ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered())); ThrowsWrapped(() => ParallelEnumerable.Range(DefaultStart, DefaultSize).AsOrdered().SequenceEqual(operation.Item(DefaultStart, DefaultSize, source.Item))); } private static void ThrowsWrapped(Action query) { AggregateException outer = Assert.Throws<AggregateException>(query); Assert.All(outer.InnerExceptions, inner => { Assert.IsType<AggregateException>(inner); Assert.All(((AggregateException)inner).InnerExceptions, e => Assert.IsType<DeliberateTestException>(e)); }); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Single(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, source.Item).Single()); Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).Single(x => x == DefaultStart + DefaultSize / 2)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void Single_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, 2, source.Item).Single()); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, 2, source.Item).Single(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void SingleOrDefault(LabeledOperation source, LabeledOperation operation) { Assert.Equal(DefaultStart, operation.Item(DefaultStart, 1, source.Item).SingleOrDefault()); Assert.Equal(DefaultStart + DefaultSize / 2, operation.Item(DefaultStart, DefaultSize, source.Item).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2)); if (!operation.ToString().StartsWith("DefaultIfEmpty")) { Assert.Equal(default(int), operation.Item(DefaultStart, 0, source.Item).SingleOrDefault()); Assert.Equal(default(int), operation.Item(DefaultStart, 0, source.Item).SingleOrDefault(x => x == DefaultStart + DefaultSize / 2)); } } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void SingleOrDefault_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, 2, source.Item).SingleOrDefault()); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, 2, source.Item).SingleOrDefault(x => true)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Skip(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Skip_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Skip(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SkipWhile(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SkipWhile_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SkipWhile_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void SkipWhile_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize / 2; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).SkipWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Sum(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Sum()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void Sum_Nullable(LabeledOperation source, LabeledOperation operation) { Assert.Equal(Functions.SumRange(DefaultStart, DefaultSize), operation.Item(DefaultStart, DefaultSize, source.Item).Sum(x => (int?)x)); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] public static void Sum_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).Sum()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Take(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Take_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Take(DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void TakeWhile(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void TakeWhile_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void TakeWhile_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void TakeWhile_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).TakeWhile((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ThenBy_Initial(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ThenBy_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ThenBy_OtherDirection(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ThenBy_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenBy(x => -x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ThenByDescending_Initial(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ThenByDescending_Initial_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => -x).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ThenByDescending_OtherDirection(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x)) { Assert.Equal(--seen, i); } Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ThenByDescending_OtherDirection_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart + DefaultSize; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).OrderBy(x => 0).ThenByDescending(x => x).ToList(), x => Assert.Equal(--seen, x)); Assert.Equal(DefaultStart, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ToArray(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToArray(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void ToArray_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToArray()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ToDictionary(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x * 2), p => { seen.Add(p.Key / 2); Assert.Equal(p.Key, p.Value * 2); }); seen.AssertComplete(); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ToDictionary_ElementSelector(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seen = new IntegerRangeSet(DefaultStart, DefaultSize); Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x, y => y * 2), p => { seen.Add(p.Key); Assert.Equal(p.Key * 2, p.Value); }); seen.AssertComplete(); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void ToDictionary_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToDictionary(x => x, y => y)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void ToList(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void ToList_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToList()); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ToLookup(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2); ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, y % 2); seenInner.Add(y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] [MemberData("UnaryUnorderedOperators")] [MemberData("BinaryUnorderedOperators")] public static void ToLookup_ElementSelector(LabeledOperation source, LabeledOperation operation) { IntegerRangeSet seenOuter = new IntegerRangeSet(0, 2); ILookup<int, int> lookup = operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x % 2, y => -y); Assert.All(lookup, group => { seenOuter.Add(group.Key); IntegerRangeSet seenInner = new IntegerRangeSet(DefaultStart / 2, (DefaultSize + ((1 + group.Key) % 2)) / 2); Assert.All(group, y => { Assert.Equal(group.Key, -y % 2); seenInner.Add(-y / 2); }); seenInner.AssertComplete(); }); seenOuter.AssertComplete(); Assert.Empty(lookup[-1]); } [Theory] [MemberData("UnaryFailingOperators")] [MemberData("BinaryFailingOperators")] [MemberData("OrderFailingOperators")] public static void ToLookup_AggregateException(LabeledOperation source, LabeledOperation operation) { Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x)); Functions.AssertThrowsWrapped<DeliberateTestException>(() => operation.Item(DefaultStart, DefaultSize, source.Item).ToLookup(x => x, y => y)); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Where(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Where_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where(x => x < DefaultStart + DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Where_Indexed(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; foreach (int i in operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2)) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Where_Indexed_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; Assert.All(operation.Item(DefaultStart, DefaultSize, source.Item).Where((x, index) => index < DefaultSize / 2).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize / 2, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Zip(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(DefaultStart * 2, DefaultSize, source.Item) .Zip(operation.Item(0, DefaultSize, source.Item), (x, y) => (x + y) / 2); foreach (int i in query) { Assert.Equal(seen++, i); } Assert.Equal(DefaultStart + DefaultSize, seen); } [Theory] [MemberData("UnaryOperators")] [MemberData("BinaryOperators")] public static void Zip_NotPipelined(LabeledOperation source, LabeledOperation operation) { int seen = DefaultStart; ParallelQuery<int> query = operation.Item(0, DefaultSize, source.Item) .Zip(operation.Item(DefaultStart * 2, DefaultSize, source.Item), (x, y) => (x + y) / 2); Assert.All(query.ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(DefaultStart + DefaultSize, seen); } } }
using System; namespace Bridge.QUnit { [Ignore] public class Assert { /// <summary> /// Instruct QUnit to wait for an asynchronous operation. /// When your test has any asynchronous exit points, call assert.async() to get a unique resolution callback for each async operation. /// The callback returned from assert.async() will throw an Error if is invoked more than once. /// </summary> public virtual Action Async() { return null; } /// <summary> /// A non-strict comparison, roughly equivalent to JUnit's assertEquals. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void Equal(object actual, object expected) { } /// <summary> /// A non-strict comparison, roughly equivalent to JUnit's assertEquals. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void Equal(object actual, object expected, string message) { } /// <summary> /// A deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates and functions. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void DeepEqual(object actual, object expected) { } /// <summary> /// A deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates and functions. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void DeepEqual(object actual, object expected, string message) { } /// <summary> /// Specify how many assertions are expected to run within a test. /// If the number of assertions run does not match the expected count, the test will fail. /// </summary> /// <param name="number">Number of assertions in this test.</param> public virtual void Expect(int number) { } /// <summary> /// An inverted deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates and functions. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void NotDeepEqual(object actual, object expected) { } /// <summary> /// An inverted deep recursive comparison, working on primitive types, arrays, objects, regular expressions, dates and functions. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void NotDeepEqual(object actual, object expected, string message) { } /// <summary> /// A non-strict comparison, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void NotEqual(object actual, object expected) { } /// <summary> /// A non-strict comparison, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void NotEqual(object actual, object expected, string message) { } /// <summary> /// A strict comparison of an object's own properties, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void NotPropEqual(object actual, object expected) { } /// <summary> /// A strict comparison of an object's own properties, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void NotPropEqual(object actual, object expected, string message) { } /// <summary> /// A strict comparison, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void NotStrictEqual(object actual, object expected) { } /// <summary> /// A strict comparison, checking for inequality. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void NotStrictEqual(object actual, object expected, string message) { } /// <summary> /// A boolean check, inverse of ok() and CommonJS's assert.ok(), and equivalent to JUnit's assertFalse(). Passes if the first argument is falsy. /// </summary> /// <param name="state">Expression being tested</param> public virtual void NotOk(object state) { } /// <summary> /// A boolean check, inverse of ok() and CommonJS's assert.ok(), and equivalent to JUnit's assertFalse(). Passes if the first argument is falsy. /// </summary> /// <param name="state">Expression being tested</param> /// <param name="message">A short description of the assertion</param> public virtual void NotOk(object state, string message) { } /// <summary> /// A boolean check, equivalent to CommonJS's assert.ok() and JUnit's assertTrue(). Passes if the first argument is truthy. /// </summary> /// <param name="state">Expression being tested</param> public virtual void Ok(object state) { } /// <summary> /// A boolean check, equivalent to CommonJS's assert.ok() and JUnit's assertTrue(). Passes if the first argument is truthy. /// </summary> /// <param name="state">Expression being tested</param> /// <param name="message">A short description of the assertion</param> public virtual void Ok(object state, string message) { } /// <summary> /// A strict type and value comparison of an object's own properties. /// </summary> /// <param name="actual">Object being tested</param> /// <param name="expected">Known comparison value</param> public virtual void PropEqual(object actual, object expected) { } /// <summary> /// A strict type and value comparison of an object's own properties. /// </summary> /// <param name="actual">Object being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void PropEqual(object actual, object expected, string message) { } /// <summary> /// Report the result of a custom assertion /// </summary> /// <param name="result">Result of the assertion</param> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void Push(bool result, object actual, object expected) { } /// <summary> /// Report the result of a custom assertion /// </summary> /// <param name="result">Result of the assertion</param> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void Push(bool result, object actual, object expected, string message) { } /// <summary> /// A strict type and value comparison. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> public virtual void StrictEqual(object actual, object expected) { } /// <summary> /// A strict type and value comparison. /// </summary> /// <param name="actual">Object or Expression being tested</param> /// <param name="expected">Known comparison value</param> /// <param name="message">A short description of the assertion</param> public virtual void StrictEqual(object actual, object expected, string message) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="message">A short description of the assertion</param> public virtual void Throws(Action block, string message) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="expected">Expected error string representation or RegExp that matches (or partially matches)</param> public virtual void Throws(Action block, object expected) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="expected">Expected error string representation or RegExp that matches (or partially matches)</param> /// <param name="message">A short description of the assertion</param> public virtual void Throws(Action block, object expected, string message) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="expected">A callback Function that must return true to pass the assertion check</param> public virtual void Throws(Action block, Func<object, bool> expected) { } /// <summary> /// Test if a callback throws an exception, and optionally compare the thrown error. /// </summary> /// <param name="block">Function to execute</param> /// <param name="expected">A callback Function that must return true to pass the assertion check</param> /// <param name="message">A short description of the assertion</param> public virtual void Throws(Action block, Func<object, bool> expected, string message) { } } }
// This code was generated by the Gardens Point Parser Generator // Copyright (c) Wayne Kelly, John Gough, QUT 2005-2014 // (see accompanying GPPGcopyright.rtf) // GPPG version 1.5.2 // Machine: TAUROS // DateTime: 21.06.2017 23:16:37 // UserName: Lukas // Input file <.\TemplateParser.y - 21.06.2017 23:15:44> // options: lines using System; using System.Collections.Generic; using System.CodeDom.Compiler; using System.Globalization; using System.Text; using QUT.Gppg; namespace RailPhase.Templates.Parser { internal enum Tokens {error=2,EOF=3,TEXT=4,TAG_START_BLOCK=5,TAG_START_ENDBLOCK=6, TAG_START_IF=7,TAG_START_ENDIF=8,TAG_START_ELSE=9,TAG_START_FOR=10,TAG_START_ENDFOR=11,TAG_START_USING=12, TAG_START_DATA=13,TAG_START_EXTENDS=14,TAG_START_INCLUDE=15,TAG_END=16,KEY_IN=17,KEY_WITH=18, VALUE_START=19,VALUE_END=20}; [GeneratedCodeAttribute( "Gardens Point Parser Generator", "1.5.2")] internal partial class Parser: ShiftReduceParser<string, LexLocation> { #pragma warning disable 649 private static Dictionary<int, string> aliases; #pragma warning restore 649 private static Rule[] rules = new Rule[34]; private static State[] states = new State[67]; private static string[] nonTerms = new string[] { "root", "$accept", "content_opt", "content_list", "content", "text", "tag", "tag_value", "tag_block", "tag_if", "tag_if_else", "tag_for", "tag_using", "tag_data", "tag_extends", "tag_include", "expr", "varname", "filename", }; static Parser() { states[0] = new State(new int[]{4,8,19,11,5,17,7,25,10,38,12,47,13,51,14,55,15,59,3,-3},new int[]{-1,1,-3,3,-4,4,-5,23,-6,6,-7,9,-8,10,-9,16,-10,24,-11,36,-12,37,-13,46,-14,50,-15,54,-16,58}); states[1] = new State(new int[]{3,2}); states[2] = new State(-1); states[3] = new State(-2); states[4] = new State(new int[]{4,8,19,11,5,17,7,25,10,38,12,47,13,51,14,55,15,59,3,-4,6,-4,8,-4,9,-4,11,-4},new int[]{-5,5,-6,6,-7,9,-8,10,-9,16,-10,24,-11,36,-12,37,-13,46,-14,50,-15,54,-16,58}); states[5] = new State(-6); states[6] = new State(new int[]{4,7,19,-7,5,-7,7,-7,10,-7,12,-7,13,-7,14,-7,15,-7,3,-7,6,-7,8,-7,9,-7,11,-7}); states[7] = new State(-33); states[8] = new State(-32); states[9] = new State(-8); states[10] = new State(-9); states[11] = new State(new int[]{4,15},new int[]{-17,12}); states[12] = new State(new int[]{20,13,4,14}); states[13] = new State(-18); states[14] = new State(-31); states[15] = new State(-30); states[16] = new State(-10); states[17] = new State(new int[]{4,15},new int[]{-18,18,-17,66}); states[18] = new State(new int[]{16,19}); states[19] = new State(new int[]{4,8,19,11,5,17,7,25,10,38,12,47,13,51,14,55,15,59,6,-3},new int[]{-3,20,-4,4,-5,23,-6,6,-7,9,-8,10,-9,16,-10,24,-11,36,-12,37,-13,46,-14,50,-15,54,-16,58}); states[20] = new State(new int[]{6,21}); states[21] = new State(new int[]{16,22}); states[22] = new State(-19); states[23] = new State(-5); states[24] = new State(-11); states[25] = new State(new int[]{4,15},new int[]{-17,26}); states[26] = new State(new int[]{16,27,4,14}); states[27] = new State(new int[]{4,8,19,11,5,17,7,25,10,38,12,47,13,51,14,55,15,59,8,-3,9,-3},new int[]{-3,28,-4,4,-5,23,-6,6,-7,9,-8,10,-9,16,-10,24,-11,36,-12,37,-13,46,-14,50,-15,54,-16,58}); states[28] = new State(new int[]{8,29,9,31}); states[29] = new State(new int[]{16,30}); states[30] = new State(-20); states[31] = new State(new int[]{16,32}); states[32] = new State(new int[]{4,8,19,11,5,17,7,25,10,38,12,47,13,51,14,55,15,59,8,-3},new int[]{-3,33,-4,4,-5,23,-6,6,-7,9,-8,10,-9,16,-10,24,-11,36,-12,37,-13,46,-14,50,-15,54,-16,58}); states[33] = new State(new int[]{8,34}); states[34] = new State(new int[]{16,35}); states[35] = new State(-21); states[36] = new State(-12); states[37] = new State(-13); states[38] = new State(new int[]{4,15},new int[]{-18,39,-17,66}); states[39] = new State(new int[]{17,40}); states[40] = new State(new int[]{4,15},new int[]{-17,41}); states[41] = new State(new int[]{16,42,4,14}); states[42] = new State(new int[]{4,8,19,11,5,17,7,25,10,38,12,47,13,51,14,55,15,59,11,-3},new int[]{-3,43,-4,4,-5,23,-6,6,-7,9,-8,10,-9,16,-10,24,-11,36,-12,37,-13,46,-14,50,-15,54,-16,58}); states[43] = new State(new int[]{11,44}); states[44] = new State(new int[]{16,45}); states[45] = new State(-22); states[46] = new State(-14); states[47] = new State(new int[]{4,15},new int[]{-17,48}); states[48] = new State(new int[]{16,49,4,14}); states[49] = new State(-23); states[50] = new State(-15); states[51] = new State(new int[]{4,15},new int[]{-17,52}); states[52] = new State(new int[]{16,53,4,14}); states[53] = new State(-24); states[54] = new State(-16); states[55] = new State(new int[]{4,15},new int[]{-17,56}); states[56] = new State(new int[]{16,57,4,14}); states[57] = new State(-25); states[58] = new State(-17); states[59] = new State(new int[]{4,15},new int[]{-19,60,-17,65}); states[60] = new State(new int[]{18,61,16,64}); states[61] = new State(new int[]{4,15},new int[]{-17,62}); states[62] = new State(new int[]{16,63,4,14}); states[63] = new State(-26); states[64] = new State(-27); states[65] = new State(new int[]{4,14,18,-28,16,-28}); states[66] = new State(new int[]{4,14,16,-29,17,-29}); for (int sNo = 0; sNo < states.Length; sNo++) states[sNo].number = sNo; rules[1] = new Rule(-2, new int[]{-1,3}); rules[2] = new Rule(-1, new int[]{-3}); rules[3] = new Rule(-3, new int[]{}); rules[4] = new Rule(-3, new int[]{-4}); rules[5] = new Rule(-4, new int[]{-5}); rules[6] = new Rule(-4, new int[]{-4,-5}); rules[7] = new Rule(-5, new int[]{-6}); rules[8] = new Rule(-5, new int[]{-7}); rules[9] = new Rule(-7, new int[]{-8}); rules[10] = new Rule(-7, new int[]{-9}); rules[11] = new Rule(-7, new int[]{-10}); rules[12] = new Rule(-7, new int[]{-11}); rules[13] = new Rule(-7, new int[]{-12}); rules[14] = new Rule(-7, new int[]{-13}); rules[15] = new Rule(-7, new int[]{-14}); rules[16] = new Rule(-7, new int[]{-15}); rules[17] = new Rule(-7, new int[]{-16}); rules[18] = new Rule(-8, new int[]{19,-17,20}); rules[19] = new Rule(-9, new int[]{5,-18,16,-3,6,16}); rules[20] = new Rule(-10, new int[]{7,-17,16,-3,8,16}); rules[21] = new Rule(-11, new int[]{7,-17,16,-3,9,16,-3,8,16}); rules[22] = new Rule(-12, new int[]{10,-18,17,-17,16,-3,11,16}); rules[23] = new Rule(-13, new int[]{12,-17,16}); rules[24] = new Rule(-14, new int[]{13,-17,16}); rules[25] = new Rule(-15, new int[]{14,-17,16}); rules[26] = new Rule(-16, new int[]{15,-19,18,-17,16}); rules[27] = new Rule(-16, new int[]{15,-19,16}); rules[28] = new Rule(-19, new int[]{-17}); rules[29] = new Rule(-18, new int[]{-17}); rules[30] = new Rule(-17, new int[]{4}); rules[31] = new Rule(-17, new int[]{-17,4}); rules[32] = new Rule(-6, new int[]{4}); rules[33] = new Rule(-6, new int[]{-6,4}); } protected override void Initialize() { this.InitSpecialTokens((int)Tokens.error, (int)Tokens.EOF); this.InitStates(states); this.InitRules(rules); this.InitNonTerminals(nonTerms); } protected override void DoAction(int action) { #pragma warning disable 162, 1522 switch (action) { case 2: // root -> content_opt #line 31 ".\TemplateParser.y" { this.ResultText = ValueStack[ValueStack.Depth-1]; } #line default break; case 6: // content_list -> content_list, content #line 44 ".\TemplateParser.y" { CurrentSemanticValue = ValueStack[ValueStack.Depth-2] + "\n" + ValueStack[ValueStack.Depth-1]; } #line default break; case 7: // content -> text #line 51 ".\TemplateParser.y" { CurrentSemanticValue = "output.Append(\""+EscapeText(ValueStack[ValueStack.Depth-1])+"\");"; } #line default break; case 18: // tag_value -> VALUE_START, expr, VALUE_END #line 70 ".\TemplateParser.y" { CurrentSemanticValue = "output.Append(" + ValueStack[ValueStack.Depth-2] + ");"; } #line default break; case 19: // tag_block -> TAG_START_BLOCK, varname, TAG_END, content_opt, TAG_START_ENDBLOCK, // TAG_END #line 76 ".\TemplateParser.y" { ResultBlocks[ValueStack[ValueStack.Depth-5]] = ValueStack[ValueStack.Depth-3]; CurrentSemanticValue = "output.Append(blockRenderers[\"" + ValueStack[ValueStack.Depth-5] + "\"](Data, Context, blockRenderers));"; } #line default break; case 20: // tag_if -> TAG_START_IF, expr, TAG_END, content_opt, TAG_START_ENDIF, TAG_END #line 83 ".\TemplateParser.y" { CurrentSemanticValue = "if( "+ValueStack[ValueStack.Depth-5]+" )\n{\n" + ValueStack[ValueStack.Depth-3] + "\n}"; } #line default break; case 21: // tag_if_else -> TAG_START_IF, expr, TAG_END, content_opt, TAG_START_ELSE, // TAG_END, content_opt, TAG_START_ENDIF, TAG_END #line 89 ".\TemplateParser.y" { CurrentSemanticValue = "if( "+ValueStack[ValueStack.Depth-8]+" )\n{\n" + ValueStack[ValueStack.Depth-6] + "\n}\nelse\n{\n" + ValueStack[ValueStack.Depth-3] + "\n}"; } #line default break; case 22: // tag_for -> TAG_START_FOR, varname, KEY_IN, expr, TAG_END, content_opt, // TAG_START_ENDFOR, TAG_END #line 94 ".\TemplateParser.y" { CurrentSemanticValue = "foreach( var " + ValueStack[ValueStack.Depth-7] + " in (" + ValueStack[ValueStack.Depth-5] + ") )" + "\n{\n" + ValueStack[ValueStack.Depth-3] + "\n}\n"; } #line default break; case 23: // tag_using -> TAG_START_USING, expr, TAG_END #line 100 ".\TemplateParser.y" { ResultUsings.Add(ValueStack[ValueStack.Depth-2]); CurrentSemanticValue = ""; } #line default break; case 24: // tag_data -> TAG_START_DATA, expr, TAG_END #line 107 ".\TemplateParser.y" { ResultDataType = ValueStack[ValueStack.Depth-2]; CurrentSemanticValue = ""; } #line default break; case 25: // tag_extends -> TAG_START_EXTENDS, expr, TAG_END #line 114 ".\TemplateParser.y" { ResultExtends = ValueStack[ValueStack.Depth-2]; CurrentSemanticValue = ""; } #line default break; case 26: // tag_include -> TAG_START_INCLUDE, filename, KEY_WITH, expr, TAG_END #line 121 ".\TemplateParser.y" { CurrentSemanticValue = "output.Append(Template.FromFile(" + ValueStack[ValueStack.Depth-4] + ")(" + ValueStack[ValueStack.Depth-2] + ", Context));\n"; } #line default break; case 27: // tag_include -> TAG_START_INCLUDE, filename, TAG_END #line 125 ".\TemplateParser.y" { CurrentSemanticValue = "output.Append(Template.FromFile(" + ValueStack[ValueStack.Depth-2] + ")(null, Context));\n"; } #line default break; case 30: // expr -> TEXT #line 134 ".\TemplateParser.y" { CurrentSemanticValue = ValueStack[ValueStack.Depth-1]; } #line default break; case 31: // expr -> expr, TEXT #line 138 ".\TemplateParser.y" { CurrentSemanticValue = ValueStack[ValueStack.Depth-2] + ValueStack[ValueStack.Depth-1]; } #line default break; case 32: // text -> TEXT #line 145 ".\TemplateParser.y" { CurrentSemanticValue = ValueStack[ValueStack.Depth-1]; } #line default break; case 33: // text -> text, TEXT #line 149 ".\TemplateParser.y" { CurrentSemanticValue = ValueStack[ValueStack.Depth-2] + ValueStack[ValueStack.Depth-1]; } #line default break; } #pragma warning restore 162, 1522 } protected override string TerminalToString(int terminal) { if (aliases != null && aliases.ContainsKey(terminal)) return aliases[terminal]; else if (((Tokens)terminal).ToString() != terminal.ToString(CultureInfo.InvariantCulture)) return ((Tokens)terminal).ToString(); else return CharToString((char)terminal); } #line 155 ".\TemplateParser.y" #line default } }
// // EditorPageWidget.cs // // Author: // Ruben Vermeersch <ruben@savanne.be> // Stephane Delcroix <stephane@delcroix.org> // // Copyright (C) 2008-2010 Novell, Inc. // Copyright (C) 2008, 2010 Ruben Vermeersch // Copyright (C) 2008-2010 Stephane Delcroix // // 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 FSpot.Editors; using FSpot.UI.Dialog; using FSpot.Utils; using Gtk; using Mono.Addins; using Mono.Unix; using Hyena; using Hyena.Widgets; using System.Linq; namespace FSpot.Widgets { public class EditorPageWidget : Gtk.ScrolledWindow { VBox widgets; VButtonBox buttons; Widget active_editor; List<Editor> editors; Editor current_editor; // Used to make buttons insensitive when selecting multiple images. Dictionary<Editor, Button> editor_buttons; EditorPage page; internal EditorPage Page { get { return page; } set { page = value; ChangeButtonVisibility (); } } public EditorPageWidget () { editors = new List<Editor> (); editor_buttons = new Dictionary<Editor, Button> (); ShowTools (); AddinManager.AddExtensionNodeHandler ("/FSpot/Editors", OnExtensionChanged); } void OnExtensionChanged (object s, ExtensionNodeEventArgs args) { // FIXME: We do not do run-time removal of editors yet! if (args.Change == ExtensionChange.Add) { Editor editor = (args.ExtensionNode as EditorNode).GetEditor (); editor.ProcessingStarted += OnProcessingStarted; editor.ProcessingStep += OnProcessingStep; editor.ProcessingFinished += OnProcessingFinished; editors.Add (editor); PackButton (editor); } } ProgressDialog progress; void OnProcessingStarted (string name, int count) { progress = new ProgressDialog (name, ProgressDialog.CancelButtonType.None, count, App.Instance.Organizer.Window); } void OnProcessingStep (int done) { if (progress != null) progress.Update (string.Empty); } void OnProcessingFinished () { if (progress != null) { progress.Destroy (); progress = null; } } internal void ChangeButtonVisibility () { foreach (Editor editor in editors) { Button button; if (editor_buttons.TryGetValue (editor, out button)) button.Visible = Page.InPhotoView || editor.CanHandleMultiple; } } void PackButton (Editor editor) { Button button = new Button (editor.Label); if (editor.IconName != null) button.Image = new Image (GtkUtil.TryLoadIcon (FSpot.Settings.Global.IconTheme, editor.IconName, 22, (Gtk.IconLookupFlags)0)); button.Clicked += (o, e) => { ChooseEditor (editor); }; button.Show (); buttons.Add (button); editor_buttons.Add (editor, button); } public void ShowTools () { // Remove any open editor, if present. if (current_editor != null) { active_editor.Hide (); widgets.Remove (active_editor); active_editor = null; current_editor.Restore (); current_editor = null; } // No need to build the widget twice. if (buttons != null) { buttons.Show (); return; } if (widgets == null) { widgets = new VBox (false, 0); widgets.NoShowAll = true; widgets.Show (); Viewport widgets_port = new Viewport (); widgets_port.Add (widgets); Add (widgets_port); widgets_port.ShowAll (); } // Build the widget (first time we call this method). buttons = new VButtonBox (); buttons.BorderWidth = 5; buttons.Spacing = 5; buttons.LayoutStyle = ButtonBoxStyle.Start; foreach (Editor editor in editors) PackButton (editor); buttons.Show (); widgets.Add (buttons); } void ChooseEditor (Editor editor) { SetupEditor (editor); if (!editor.CanBeApplied || editor.HasSettings) ShowEditor (editor); else Apply (editor); // Instant apply } bool SetupEditor (Editor editor) { EditorState state = editor.CreateState (); PhotoImageView photo_view = App.Instance.Organizer.PhotoView.View; if (Page.InPhotoView && photo_view != null) { state.Selection = photo_view.Selection; state.PhotoImageView = photo_view; } else { state.Selection = Gdk.Rectangle.Zero; state.PhotoImageView = null; } if ((Page.Sidebar as Sidebar).Selection == null) return false; state.Items = (Page.Sidebar as Sidebar).Selection.Items.ToArray (); editor.Initialize (state); return true; } void Apply (Editor editor) { if (!SetupEditor (editor)) return; if (!editor.CanBeApplied) { string msg = Catalog.GetString ("No selection available"); string desc = Catalog.GetString ("This tool requires an active selection. Please select a region of the photo and try the operation again"); HigMessageDialog md = new HigMessageDialog (App.Instance.Organizer.Window, DialogFlags.DestroyWithParent, Gtk.MessageType.Error, ButtonsType.Ok, msg, desc); md.Run (); md.Destroy (); return; } // TODO: Might need to do some nicer things for multiple selections (progress?) try { editor.Apply (); } catch (Exception e) { Log.DebugException (e); string msg = Catalog.GetPluralString ("Error saving adjusted photo", "Error saving adjusted photos", editor.State.Items.Length); string desc = string.Format (Catalog.GetString ("Received exception \"{0}\". Note that you have to develop RAW files into JPEG before you can edit them."), e.Message); HigMessageDialog md = new HigMessageDialog (App.Instance.Organizer.Window, DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Ok, msg, desc); md.Run (); md.Destroy (); } ShowTools (); } void ShowEditor (Editor editor) { SetupEditor (editor); current_editor = editor; buttons.Hide (); // Top label VBox vbox = new VBox (false, 4); Label label = new Label (); label.Markup = string.Format("<big><b>{0}</b></big>", editor.Label); vbox.PackStart (label, false, false, 5); // Optional config widget Widget config = editor.ConfigurationWidget (); if (config != null) { // This is necessary because GtkBuilder widgets need to be // reparented. if (config.Parent != null) { config.Reparent (vbox); } else { vbox.PackStart (config, false, false, 0); } } // Apply / Cancel buttons HButtonBox tool_buttons = new HButtonBox (); tool_buttons.LayoutStyle = ButtonBoxStyle.End; tool_buttons.Spacing = 5; tool_buttons.BorderWidth = 5; tool_buttons.Homogeneous = false; Button cancel = new Button (Stock.Cancel); cancel.Clicked += HandleCancel; tool_buttons.Add (cancel); Button apply = new Button (editor.ApplyLabel); apply.Image = new Image (GtkUtil.TryLoadIcon (FSpot.Settings.Global.IconTheme, editor.IconName, 22, 0)); apply.Clicked += (s, e) => { Apply (editor); }; tool_buttons.Add (apply); // Pack it all together vbox.PackEnd (tool_buttons, false, false, 0); active_editor = vbox; widgets.Add (active_editor); active_editor.ShowAll (); } void HandleCancel (object sender, EventArgs args) { ShowTools (); } } }
// Copyright (c) 2012 Smarkets Limited // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using IronSmarkets.Data; using IronSmarkets.Proto.Seto; #if NET35 using IronSmarkets.System; #endif using Eto = IronSmarkets.Proto.Eto; namespace IronSmarkets.Messages { public static class Payloads { public static Payload Sequenced(Payload payload, ulong sequence) { if (payload.EtoPayload == null) payload.EtoPayload = new Eto.Payload(); payload.EtoPayload.Seq = sequence; return payload; } public static Payload Login(string username, string password) { return new Payload { Type = PayloadType.PAYLOADLOGIN, EtoPayload = new Eto.Payload { Type = Eto.PayloadType.PAYLOADLOGIN }, Login = new Login { Username = username, Password = password } }; } public static Payload LoginResponse(string session, ulong reset) { return new Payload { Type = PayloadType.PAYLOADETO, EtoPayload = new Eto.Payload { Type = Eto.PayloadType.PAYLOADLOGINRESPONSE, LoginResponse = new Eto.LoginResponse { Session = session, Reset = reset } } }; } public static Payload Logout() { return LogoutReason(Eto.LogoutReason.LOGOUTNONE); } public static Payload LogoutConfirmation() { return LogoutReason(Eto.LogoutReason.LOGOUTCONFIRMATION); } private static Payload LogoutReason(Eto.LogoutReason reason) { return new Payload { Type = PayloadType.PAYLOADETO, EtoPayload = new Eto.Payload { Type = Eto.PayloadType.PAYLOADLOGOUT, Logout = new Eto.Logout { Reason = reason } } }; } public static Payload Heartbeat() { return new Payload { Type = PayloadType.PAYLOADETO, EtoPayload = new Eto.Payload { Type = Eto.PayloadType.PAYLOADHEARTBEAT } }; } public static Payload Replay(ulong sequence) { return new Payload { Type = PayloadType.PAYLOADETO, EtoPayload = new Eto.Payload { Type = Eto.PayloadType.PAYLOADREPLAY, Replay = new Eto.Replay { Seq = sequence } } }; } public static Payload Ping() { return new Payload { Type = PayloadType.PAYLOADETO, EtoPayload = new Eto.Payload { Type = Eto.PayloadType.PAYLOADPING } }; } public static Payload Pong() { return new Payload { Type = PayloadType.PAYLOADETO, EtoPayload = new Eto.Payload { Type = Eto.PayloadType.PAYLOADPONG } }; } public static Payload MarketSubscribe(Uid market) { return new Payload { Type = PayloadType.PAYLOADMARKETSUBSCRIBE, MarketSubscribe = new MarketSubscribe { Market = market.ToUuid128() } }; } public static Payload MarketQuotes(Uid market) { return new Payload { Type = PayloadType.PAYLOADMARKETQUOTES, MarketQuotes = new Proto.Seto.MarketQuotes { Market = market.ToUuid128(), PriceType = Proto.Seto.PriceType.PRICEPERCENTODDS, QuantityType = Proto.Seto.QuantityType.QUANTITYPAYOFFCURRENCY } }; } public static Payload ContractQuotes(Uid contract, IEnumerable<Proto.Seto.Quote> bids, IEnumerable<Proto.Seto.Quote> offers) { var payload = new Payload { Type = PayloadType.PAYLOADCONTRACTQUOTES, ContractQuotes = new Proto.Seto.ContractQuotes { Contract = contract.ToUuid128() } }; payload.ContractQuotes.Bids.AddRange(bids); payload.ContractQuotes.Offers.AddRange(offers); return payload; } public static Payload MarketUnsubscribe(Uid market) { return new Payload { Type = PayloadType.PAYLOADMARKETUNSUBSCRIBE, MarketUnsubscribe = new MarketUnsubscribe { Market = market.ToUuid128() } }; } public static Payload EventsRequest(EventQuery query) { return new Payload { Type = PayloadType.PAYLOADEVENTSREQUEST, EventsRequest = query.ToEventsRequest() }; } public static Payload HttpFound(string url, ulong sequence) { return new Payload { Type = PayloadType.PAYLOADHTTPFOUND, HttpFound = new HttpFound { Seq = sequence, Url = url } }; } public static Payload AccountStateRequest(Uid? account) { var request = new AccountStateRequest(); if (account != null) request.Account = account.Value.ToUuid128(); return new Payload { Type = PayloadType.PAYLOADACCOUNTSTATEREQUEST, AccountStateRequest = request }; } public static Payload MarketQuotesRequest(Uid market) { return new Payload { Type = PayloadType.PAYLOADMARKETQUOTESREQUEST, MarketQuotesRequest = new MarketQuotesRequest { Market = market.ToUuid128() } }; } public static Payload OrdersForAccountRequest() { return new Payload { Type = PayloadType.PAYLOADORDERSFORACCOUNTREQUEST, OrdersForAccountRequest = new OrdersForAccountRequest() }; } public static Payload OrdersForAccount(IEnumerable<Data.Order> orders) { var ordersForAccount = new OrdersForAccount(); ordersForAccount.Markets.AddRange(OrdersForMarketInternal(orders)); return new Payload { Type = PayloadType.PAYLOADORDERSFORACCOUNT, OrdersForAccount = ordersForAccount }; } public static Payload OrdersForMarket(IEnumerable<Data.Order> orders) { return new Payload { Type = PayloadType.PAYLOADORDERSFORMARKET, OrdersForMarket = OrdersForMarketInternal(orders).First() }; } private static IEnumerable<OrdersForMarket> OrdersForMarketInternal(IEnumerable<Data.Order> orders) { OrdersForMarket ordersForMarket = null; OrdersForContract ordersForContract = null; OrdersForPrice ordersForPrice = null; Data.Order prevOrder = null; foreach (var order in orders.OrderBy(x => new Tuple<Uid, Uid, Data.Side, Price>(x.Market, x.Contract, x.Side, x.Price))) { if (ordersForMarket == null || order.Market != prevOrder.Market) { ordersForMarket = new OrdersForMarket { Market = order.Market.ToUuid128(), PriceType = order.Price.SetoType }; yield return ordersForMarket; } if (ordersForContract == null || order.Contract != prevOrder.Contract) { ordersForContract = new OrdersForContract { Contract = order.Contract.ToUuid128() }; ordersForMarket.Contracts.Add(ordersForContract); } if (ordersForPrice == null || order.Price != prevOrder.Price || order.Side != prevOrder.Side) { ordersForPrice = new OrdersForPrice { Price = order.Price.Raw }; if (order.Side == Data.Side.Buy) ordersForContract.Bids.Add(ordersForPrice); if (order.Side == Data.Side.Sell) ordersForContract.Offers.Add(ordersForPrice); } ordersForPrice.Orders.Add(order.State.ToSeto()); prevOrder = order; } } public static Payload OrdersForMarketRequest(Uid market) { return new Payload { Type = PayloadType.PAYLOADORDERSFORMARKETREQUEST, OrdersForMarketRequest = new OrdersForMarketRequest { Market = market.ToUuid128() } }; } public static Payload OrderCancel(Uid order) { return new Payload { Type = PayloadType.PAYLOADORDERCANCEL, OrderCancel = new OrderCancel { Order = order.ToUuid128() } }; } public static Payload OrderCreate(NewOrder order) { return new Payload { Type = PayloadType.PAYLOADORDERCREATE, OrderCreate = order.ToOrderCreate() }; } public static Payload OrderAccepted(Uid order, ulong sequence) { return new Payload { Type = PayloadType.PAYLOADORDERACCEPTED, OrderAccepted = new OrderAccepted { Seq = sequence, Order = order.ToUuid128() } }; } public static Payload OrderCancelled(Uid order) { return new Payload { Type = PayloadType.PAYLOADORDERCANCELLED, OrderCancelled = new OrderCancelled { Order = order.ToUuid128(), Reason = Proto.Seto.OrderCancelledReason.ORDERCANCELLEDMEMBERREQUESTED } }; } } }
//------------------------------------------------------------------------------ // <copyright file="TransferCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.Serialization; using TransferKey = System.Tuple<TransferLocation, TransferLocation>; /// <summary> /// A collection of transfers. /// </summary> [Serializable] internal class TransferCollection : ISerializable { /// <summary> /// Serialization field name for single object transfers. /// </summary> private const string SingleObjectTransfersName = "SingleObjectTransfers"; /// <summary> /// Serialization field name for directory transfers. /// </summary> private const string DirectoryTransfersName = "DirectoryTransfers"; /// <summary> /// All transfers in the collection. /// </summary> private ConcurrentDictionary<TransferKey, Transfer> transfers = new ConcurrentDictionary<TransferKey, Transfer>(); /// <summary> /// Overall transfer progress tracker. /// </summary> private TransferProgressTracker overallProgressTracker = new TransferProgressTracker(); /// <summary> /// Initializes a new instance of the <see cref="TransferCollection"/> class. /// </summary> internal TransferCollection() { } /// <summary> /// Initializes a new instance of the <see cref="TransferCollection"/> class. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected TransferCollection(SerializationInfo info, StreamingContext context) { if (info == null) { throw new System.ArgumentNullException("info"); } int transferCount = info.GetInt32(SingleObjectTransfersName); for (int i = 0; i < transferCount; ++i) { this.AddTransfer((SingleObjectTransfer)info.GetValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", SingleObjectTransfersName, i), typeof(SingleObjectTransfer))); } transferCount = info.GetInt32(DirectoryTransfersName); for (int i = 0; i < transferCount; ++i) { this.AddTransfer((DirectoryTransfer)info.GetValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", DirectoryTransfersName, i), typeof(DirectoryTransfer))); } foreach (Transfer transfer in this.transfers.Values) { this.OverallProgressTracker.AddProgress(transfer.ProgressTracker); } } /// <summary> /// Gets the number of transfers currently in the collection. /// </summary> public int Count { get { return this.transfers.Count; } } /// <summary> /// Gets the overall transfer progress. /// </summary> public TransferProgressTracker OverallProgressTracker { get { return this.overallProgressTracker; } } /// <summary> /// Serializes the checkpoint. /// </summary> /// <param name="info">Serialization info object.</param> /// <param name="context">Streaming context.</param> public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } List<SingleObjectTransfer> singleObjectTransfers = new List<SingleObjectTransfer>(); List<DirectoryTransfer> directoryTransfers = new List<DirectoryTransfer>(); foreach (var kv in this.transfers) { SingleObjectTransfer transfer = kv.Value as SingleObjectTransfer; if (transfer != null) { singleObjectTransfers.Add(transfer); continue; } DirectoryTransfer transfer2 = kv.Value as DirectoryTransfer; if (transfer2 != null) { directoryTransfers.Add(transfer2); continue; } } info.AddValue(SingleObjectTransfersName, singleObjectTransfers.Count); for (int i = 0; i < singleObjectTransfers.Count; ++i) { info.AddValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", SingleObjectTransfersName, i), singleObjectTransfers[i], typeof(SingleObjectTransfer)); } info.AddValue(DirectoryTransfersName, directoryTransfers.Count); for (int i = 0; i < directoryTransfers.Count; ++i) { info.AddValue(string.Format(CultureInfo.InvariantCulture, "{0}{1}", DirectoryTransfersName, i), directoryTransfers[i], typeof(DirectoryTransfer)); } } /// <summary> /// Adds a transfer. /// </summary> /// <param name="transfer">The transfer to be added.</param> public void AddTransfer(Transfer transfer) { transfer.ProgressTracker.Parent = this.OverallProgressTracker; this.overallProgressTracker.AddProgress(transfer.ProgressTracker); bool unused = this.transfers.TryAdd(new TransferKey(transfer.Source, transfer.Destination), transfer); Debug.Assert(unused, "Transfer with the same source and destination already exists"); } /// <summary> /// Remove a transfer. /// </summary> /// <param name="transfer">Transfer to be removed</param> /// <returns>True if the transfer is removed successfully, false otherwise.</returns> public bool RemoveTransfer(Transfer transfer) { Transfer unused = null; if (this.transfers.TryRemove(new TransferKey(transfer.Source, transfer.Destination), out unused)) { transfer.ProgressTracker.Parent = null; return true; } return false; } /// <summary> /// Gets a transfer with the specified source location, destination location and transfer method. /// </summary> /// <param name="sourceLocation">Source location of the transfer.</param> /// <param name="destLocation">Destination location of the transfer.</param> /// <param name="transferMethod">Transfer method.</param> /// <returns>A transfer that matches the specified source location, destination location and transfer method; Or null if no matches.</returns> public Transfer GetTransfer(TransferLocation sourceLocation, TransferLocation destLocation, TransferMethod transferMethod) { Transfer transfer = null; if (this.transfers.TryGetValue(new TransferKey(sourceLocation, destLocation), out transfer)) { if (transfer.TransferMethod == transferMethod) { return transfer; } } return null; } /// <summary> /// Get an enumerable object for all tansfers in this TransferCollection. /// </summary> /// <returns>An enumerable object for all tansfers in this TransferCollection.</returns> public IEnumerable<Transfer> GetEnumerator() { return this.transfers.Values; } /// <summary> /// Gets a static snapshot of this transfer checkpoint /// </summary> /// <returns>A snapshot of current transfer checkpoint</returns> public TransferCollection Copy() { TransferCollection copyObj = new TransferCollection(); foreach (var kv in this.transfers) { SingleObjectTransfer transfer = kv.Value as SingleObjectTransfer; if (transfer != null) { copyObj.AddTransfer(transfer.Copy()); continue; } DirectoryTransfer transfer2 = kv.Value as DirectoryTransfer; if (transfer2 != null) { copyObj.AddTransfer(transfer2.Copy()); continue; } } return copyObj; } } }
using System; using System.Collections.Generic; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: used when implementing a custom TraceLoggingTypeInfo. /// An instance of this type is provided to the TypeInfo.WriteMetadata method. /// </summary> internal class TraceLoggingMetadataCollector { private readonly Impl impl; private readonly FieldMetadata currentGroup; private int bufferedArrayFieldCount = int.MinValue; /// <summary> /// Creates a root-level collector. /// </summary> internal TraceLoggingMetadataCollector() { this.impl = new Impl(); } /// <summary> /// Creates a collector for a group. /// </summary> /// <param name="other">Parent collector</param> /// <param name="group">The field that starts the group</param> private TraceLoggingMetadataCollector( TraceLoggingMetadataCollector other, FieldMetadata group) { this.impl = other.impl; this.currentGroup = group; } /// <summary> /// The field tags to be used for the next field. /// This will be reset to None each time a field is written. /// </summary> internal EventFieldTags Tags { get; set; } internal int ScratchSize { get { return this.impl.scratchSize; } } internal int DataCount { get { return this.impl.dataCount; } } internal int PinCount { get { return this.impl.pinCount; } } private bool BeginningBufferedArray { get { return this.bufferedArrayFieldCount == 0; } } /// <summary> /// Call this method to add a group to the event and to return /// a new metadata collector that can be used to add fields to the /// group. After all of the fields in the group have been written, /// switch back to the original metadata collector to add fields /// outside of the group. /// Special-case: if name is null, no group is created, and AddGroup /// returns the original metadata collector. This is useful when /// adding the top-level group for an event. /// Note: do not use the original metadata collector while the group's /// metadata collector is in use, and do not use the group's metadata /// collector after switching back to the original. /// </summary> /// <param name="name"> /// The name of the group. If name is null, the call to AddGroup is a /// no-op (collector.AddGroup(null) returns collector). /// </param> /// <returns> /// A new metadata collector that can be used to add fields to the group. /// </returns> public TraceLoggingMetadataCollector AddGroup(string name) { TraceLoggingMetadataCollector result = this; if (name != null || // Normal. this.BeginningBufferedArray) // Error, FieldMetadata's constructor will throw the appropriate exception. { var newGroup = new FieldMetadata( name, TraceLoggingDataType.Struct, 0, this.BeginningBufferedArray); this.AddField(newGroup); result = new TraceLoggingMetadataCollector(this, newGroup); } return result; } /// <summary> /// Adds a scalar field to an event. /// </summary> /// <param name="name"> /// The name to use for the added field. This value must not be null. /// </param> /// <param name="type"> /// The type code for the added field. This must be a fixed-size type /// (e.g. string types are not supported). /// </param> public void AddScalar(string name, TraceLoggingDataType type) { int size; switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask)) { case TraceLoggingDataType.Int8: case TraceLoggingDataType.UInt8: case TraceLoggingDataType.Char8: size = 1; break; case TraceLoggingDataType.Int16: case TraceLoggingDataType.UInt16: case TraceLoggingDataType.Char16: size = 2; break; case TraceLoggingDataType.Int32: case TraceLoggingDataType.UInt32: case TraceLoggingDataType.HexInt32: case TraceLoggingDataType.Float: case TraceLoggingDataType.Boolean32: size = 4; break; case TraceLoggingDataType.Int64: case TraceLoggingDataType.UInt64: case TraceLoggingDataType.HexInt64: case TraceLoggingDataType.Double: case TraceLoggingDataType.FileTime: size = 8; break; case TraceLoggingDataType.Guid: case TraceLoggingDataType.SystemTime: size = 16; break; default: throw new ArgumentOutOfRangeException("type"); } this.impl.AddScalar(size); this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray)); } /// <summary> /// Adds a binary-format field to an event. /// Compatible with core types: Binary, CountedUtf16String, CountedMbcsString. /// Compatible with dataCollector methods: AddBinary(string), AddArray(Any8bitType[]). /// </summary> /// <param name="name"> /// The name to use for the added field. This value must not be null. /// </param> /// <param name="type"> /// The type code for the added field. This must be a Binary or CountedString type. /// </param> public void AddBinary(string name, TraceLoggingDataType type) { switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask)) { case TraceLoggingDataType.Binary: case TraceLoggingDataType.CountedMbcsString: case TraceLoggingDataType.CountedUtf16String: break; default: throw new ArgumentOutOfRangeException("type"); } this.impl.AddScalar(2); this.impl.AddNonscalar(); this.AddField(new FieldMetadata(name, type, this.Tags, this.BeginningBufferedArray)); } /// <summary> /// Adds an array field to an event. /// </summary> /// <param name="name"> /// The name to use for the added field. This value must not be null. /// </param> /// <param name="type"> /// The type code for the added field. This must be a fixed-size type /// or a string type. In the case of a string type, this adds an array /// of characters, not an array of strings. /// </param> public void AddArray(string name, TraceLoggingDataType type) { switch ((TraceLoggingDataType)((int)type & Statics.InTypeMask)) { case TraceLoggingDataType.Utf16String: case TraceLoggingDataType.MbcsString: case TraceLoggingDataType.Int8: case TraceLoggingDataType.UInt8: case TraceLoggingDataType.Int16: case TraceLoggingDataType.UInt16: case TraceLoggingDataType.Int32: case TraceLoggingDataType.UInt32: case TraceLoggingDataType.Int64: case TraceLoggingDataType.UInt64: case TraceLoggingDataType.Float: case TraceLoggingDataType.Double: case TraceLoggingDataType.Boolean32: case TraceLoggingDataType.Guid: case TraceLoggingDataType.FileTime: case TraceLoggingDataType.HexInt32: case TraceLoggingDataType.HexInt64: case TraceLoggingDataType.Char16: case TraceLoggingDataType.Char8: break; default: throw new ArgumentOutOfRangeException("type"); } if (this.BeginningBufferedArray) { throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedNestedArraysEnums")); } this.impl.AddScalar(2); this.impl.AddNonscalar(); this.AddField(new FieldMetadata(name, type, this.Tags, true)); } public void BeginBufferedArray() { if (this.bufferedArrayFieldCount >= 0) { throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedNestedArraysEnums")); } this.bufferedArrayFieldCount = 0; this.impl.BeginBuffered(); } public void EndBufferedArray() { if (this.bufferedArrayFieldCount != 1) { throw new InvalidOperationException(Environment.GetResourceString("EventSource_IncorrentlyAuthoredTypeInfo")); } this.bufferedArrayFieldCount = int.MinValue; this.impl.EndBuffered(); } /// <summary> /// Adds a custom-serialized field to an event. /// </summary> /// <param name="name"> /// The name to use for the added field. This value must not be null. /// </param> /// <param name="type">The encoding type for the field.</param> /// <param name="metadata">Additional information needed to decode the field, if any.</param> public void AddCustom(string name, TraceLoggingDataType type, byte[] metadata) { if (this.BeginningBufferedArray) { throw new NotSupportedException(Environment.GetResourceString("EventSource_NotSupportedCustomSerializedData")); } this.impl.AddScalar(2); this.impl.AddNonscalar(); this.AddField(new FieldMetadata( name, type, this.Tags, metadata)); } internal byte[] GetMetadata() { var size = this.impl.Encode(null); var metadata = new byte[size]; this.impl.Encode(metadata); return metadata; } private void AddField(FieldMetadata fieldMetadata) { this.Tags = EventFieldTags.None; this.bufferedArrayFieldCount++; this.impl.fields.Add(fieldMetadata); if (this.currentGroup != null) { this.currentGroup.IncrementStructFieldCount(); } } private class Impl { internal readonly List<FieldMetadata> fields = new List<FieldMetadata>(); internal short scratchSize; internal sbyte dataCount; internal sbyte pinCount; private int bufferNesting; private bool scalar; public void AddScalar(int size) { if (this.bufferNesting == 0) { if (!this.scalar) { this.dataCount = checked((sbyte)(this.dataCount + 1)); } this.scalar = true; this.scratchSize = checked((short)(this.scratchSize + size)); } } public void AddNonscalar() { if (this.bufferNesting == 0) { this.scalar = false; this.pinCount = checked((sbyte)(this.pinCount + 1)); this.dataCount = checked((sbyte)(this.dataCount + 1)); } } public void BeginBuffered() { if (this.bufferNesting == 0) { this.AddNonscalar(); } this.bufferNesting++; } public void EndBuffered() { this.bufferNesting--; } public int Encode(byte[] metadata) { int size = 0; foreach (var field in this.fields) { field.Encode(ref size, metadata); } return size; } } } }
// Copyright (c) 2010, Eric Maupin // 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 Gablarski nor the names of its // contributors may be used to endorse or promote products // or services 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. using System; using System.Collections.Generic; using System.Linq; using Gablarski.Client; using Gablarski.Messages; using Gablarski.Server; using NUnit.Framework; using Tempest; using Tempest.Tests; namespace Gablarski.Tests { [TestFixture] public class ClientUserHandlerTests { [SetUp] public void ManagerSetup () { this.provider = new MockConnectionProvider (GablarskiProtocol.Instance); this.provider.Start (MessageTypes.All); var connections = this.provider.GetConnections (GablarskiProtocol.Instance); this.server = new ConnectionBuffer (connections.Item2); this.client = connections.Item1; userProvider = new MockUserProvider(); context = new MockClientContext (client) { ServerInfo = new ServerInfo (new ServerSettings(), userProvider) }; var channels = new ClientChannelManager (context); ClientChannelManagerTests.PopulateChannels (channels, this.server); this.userManager = new ClientUserManager(); this.handler = new ClientUserHandler (context, userManager); context.Users = this.handler; context.Channels = channels; } [TearDown] public void ManagerTearDown () { this.userProvider = null; this.server = null; this.handler = null; this.userManager = null; this.provider = null; this.context = null; } private static void CreateUsers (IClientConnection client, ClientUserHandler handler) { handler.OnUserListReceivedMessage (new MessageEventArgs<UserInfoListMessage> (client, new UserInfoListMessage (new[] { new UserInfo ("Foo", "Foo", 1, 1, false), new UserInfo ("Bar", "Bar", 2, 1, false), new UserInfo ("Wee", "Wee", 3, 2, true), }))); Assert.AreEqual (3, handler.Count()); VerifyDefaultUsers (handler); } private static void VerifyDefaultUsers (IEnumerable<IUserInfo> manager) { Assert.AreEqual (1, manager.Count (u => u.UserId == 1 && u.Nickname == "Foo" && !u.IsMuted && u.CurrentChannelId == 1)); Assert.AreEqual (1, manager.Count (u => u.UserId == 2 && u.Nickname == "Bar" && !u.IsMuted && u.CurrentChannelId == 1)); Assert.AreEqual (1, manager.Count (u => u.UserId == 3 && u.Nickname == "Wee" && u.IsMuted && u.CurrentChannelId == 2)); } private ConnectionBuffer server; private MockConnectionProvider provider; private ClientUserHandler handler; private MockClientContext context; private MockUserProvider userProvider; private ClientUserManager userManager; private MockClientConnection client; [Test] public void NullConnection() { Assert.Throws<ArgumentNullException> (() => new ClientUserHandler (null, new ClientUserManager())); Assert.Throws<ArgumentNullException> (() => new ClientUserHandler (new MockClientContext (this.client), null)); } [Test] public void Enumerator() { CreateUsers (this.client, this.handler); } [Test] public void UserJoined() { CreateUsers (this.client, this.handler); var newGuy = new UserInfo ("New", "new", 4, 3, false); this.handler.OnUserJoinedMessage (new MessageEventArgs<UserJoinedMessage> (this.client, new UserJoinedMessage(newGuy))); VerifyDefaultUsers (this.handler); Assert.AreEqual (1, this.handler.Count ( u => u.UserId == newGuy.UserId && u.Nickname == newGuy.Nickname && u.CurrentChannelId == newGuy.CurrentChannelId)); } [Test] public void UserDisconnected() { CreateUsers (this.client, this.handler); this.handler.OnUserDisconnectedMessage (new MessageEventArgs<UserDisconnectedMessage> (this.client, new UserDisconnectedMessage (1))); Assert.AreEqual (2, this.handler.Count()); Assert.AreEqual (0, this.handler.Count (u => (int)u.UserId == 1 || u.Nickname == "Foo")); Assert.AreEqual (1, this.handler.Count (u => (int)u.UserId == 2 && u.Nickname == "Bar" && (int)u.CurrentChannelId == 1)); Assert.AreEqual (1, this.handler.Count (u => (int)u.UserId == 3 && u.Nickname == "Wee" && (int)u.CurrentChannelId == 2)); } [Test] public void ChannelUpdate() { CreateUsers (this.client, this.handler); var old = this.handler[2]; this.handler.OnUserChangedChannelMessage (new MessageEventArgs<UserChangedChannelMessage> (this.client, new UserChangedChannelMessage { ChangeInfo = new ChannelChangeInfo (2, 2, 1) })); Assert.AreEqual (this.handler[2].UserId, 2); Assert.AreEqual (this.handler[2].Nickname, old.Nickname); Assert.AreEqual (this.handler[2].CurrentChannelId, 2); } [Test] public void IgnoreUser() { CreateUsers (this.client, this.handler); var user = this.handler.First(); int userId = user.UserId; Assert.IsFalse (this.handler.GetIsIgnored (user)); Assert.IsTrue (this.handler.ToggleIgnore (user)); Assert.IsTrue (this.handler.GetIsIgnored (user)); } [Test] public void IgnoreUserPersists () { CreateUsers (this.client, this.handler); var user = this.handler.First (); int userId = user.UserId; Assert.IsFalse (this.handler.GetIsIgnored (user)); Assert.IsTrue (this.handler.ToggleIgnore (user)); Assert.IsTrue (this.handler.GetIsIgnored (user)); CreateUsers (this.client, this.handler); Assert.IsTrue (this.handler.GetIsIgnored (user)); } [Test] public void ApproveRegistrationNull() { Assert.Throws<ArgumentNullException> (() => this.handler.ApproveRegistration ((string)null)); Assert.Throws<ArgumentNullException> (() => this.handler.ApproveRegistration ((IUserInfo)null)); } [Test] public void PreApproveRegistration() { userProvider.UpdateSupported = true; userProvider.RegistrationMode = UserRegistrationMode.PreApproved; context = new MockClientContext (this.client) { ServerInfo = new ServerInfo (new ServerSettings(), userProvider) }; this.handler = new ClientUserHandler (context, this.userManager); CreateUsers (this.client, this.handler); var user = this.handler.First(); int userId = user.UserId; this.handler.ApproveRegistration (user); var msg = this.server.DequeueAndAssertMessage<RegistrationApprovalMessage>(); Assert.AreEqual (userId, msg.UserId); } [Test] public void ApproveRegistrationUnsupported() { userProvider.UpdateSupported = false; userProvider.RegistrationMode = UserRegistrationMode.None; context = new MockClientContext (this.client) { ServerInfo = new ServerInfo (new ServerSettings(), userProvider) }; this.handler = new ClientUserHandler (context, this.userManager); CreateUsers (this.client, this.handler); var user = this.handler.First(); Assert.Throws<NotSupportedException>(() => this.handler.ApproveRegistration (user)); } [Test] public void ApproveRegistration() { userProvider.UpdateSupported = true; userProvider.RegistrationMode = UserRegistrationMode.Approved; context = new MockClientContext (this.client) { ServerInfo = new ServerInfo (new ServerSettings(), userProvider) }; this.handler = new ClientUserHandler (context, this.userManager); this.handler.ApproveRegistration ("username"); var msg = this.server.DequeueAndAssertMessage<RegistrationApprovalMessage>(); Assert.AreEqual ("username", msg.Username); } [Test] public void RejectRegistrationNull() { Assert.Throws<ArgumentNullException> (() => this.handler.RejectRegistration (null)); } [Test] public void KickNull() { Assert.Throws<ArgumentNullException> (() => this.handler.Kick (null, true)); } [Test] public void KickFromServer() { CreateUsers (this.client, this.handler); var admin = this.handler.First(); var target = this.handler.Skip (1).First(); this.handler.Kick (target, true); var kick = server.DequeueAndAssertMessage<KickUserMessage>(); Assert.AreEqual (target.UserId, kick.UserId); Assert.AreEqual (true, kick.FromServer); } [Test] public void KickFromChannel() { CreateUsers (this.client, this.handler); var admin = this.handler.First(); var target = this.handler.Skip (1).First(); this.handler.Kick (target, false); var kick = server.DequeueAndAssertMessage<KickUserMessage>(); Assert.AreEqual (target.UserId, kick.UserId); Assert.AreEqual (false, kick.FromServer); } [Test] public void UserKickedFromChannel() { CreateUsers (this.client, this.handler); var target = this.handler.First(); handler.UserKickedFromChannel += (sender, e) => { Assert.AreEqual (target.UserId, e.User.UserId); Assert.Pass(); }; handler.OnUserKickedMessage (new MessageEventArgs<UserKickedMessage> (this.client, new UserKickedMessage { UserId = target.UserId, FromServer = false })); Assert.Fail ("UserKickedFromChannel event was not fired."); } [Test] public void UserKickedFromServer() { CreateUsers (this.client, this.handler); var target = this.handler.First(); handler.UserKickedFromServer += (sender, e) => { Assert.AreEqual (target.UserId, e.User.UserId); Assert.Pass(); }; handler.OnUserKickedMessage (new MessageEventArgs<UserKickedMessage> (this.client, new UserKickedMessage { UserId = target.UserId, FromServer = true})); Assert.Fail ("UserKickedFromServer event was not fired."); } } }
// // Solver.cs // // Author: // Gabriel Burt <gburt@novell.com> // // Copyright 2010 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.Linq; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Data.Sqlite; using Banshee.ServiceStack; using Banshee.Configuration; namespace Banshee.Fixup { public abstract class Solver : IDisposable { private string id; /* Find the highest TrackNumber for albums where not all tracks have it set */ //SELECT AlbumID, Max(TrackCount) as MaxTrackNum FROM CoreTracks GROUP BY AlbumID HAVING MaxTrackNum > 0 AND MaxTrackNum != Min(TrackCount); public Solver () { } // Total hack to work make unit tests work internal static bool EnableUnitTests; public string Id { get { return id; } set { if (id != null) { throw new InvalidOperationException ("Solver's Id is already set; can't change it"); } id = value; if (!EnableUnitTests) { Generation = DatabaseConfigurationClient.Client.Get<int> ("MetadataFixupGeneration", id, 0); } } } public string Name { get; set; } public string Description { get; set; } public int Generation { get; private set; } public void FindProblems () { // Bump the generation number Generation++; DatabaseConfigurationClient.Client.Set<int> ("MetadataFixupGeneration", Id, Generation); // Identify the new issues IdentifyCore (); // Unselect any problems that the user had previously unselected ServiceManager.DbConnection.Execute ( @"UPDATE MetadataProblems SET Selected = 0 WHERE ProblemType = ? AND Generation = ? AND ObjectIds IN (SELECT ObjectIds FROM MetadataProblems WHERE ProblemType = ? AND Generation = ? AND Selected = 0)", Id, Generation, Id, Generation - 1 ); // Delete the previous generation's issues ServiceManager.DbConnection.Execute ( "DELETE FROM MetadataProblems WHERE ProblemType = ? AND Generation = ?", Id, Generation - 1 ); } public virtual void Dispose () {} public void FixSelected () { Fix (Problem.Provider.FetchAllMatching ("Selected = 1")); } protected abstract void IdentifyCore (); public abstract void Fix (IEnumerable<Problem> problems); } public abstract class DuplicateSolver : Solver { private List<HyenaSqliteCommand> find_cmds = new List<HyenaSqliteCommand> (); public void AddFinder (string value_column, string id_column, string from, string condition, string group_by) { /* The val result SQL gives us the first/highest value (in descending * sort order), so Foo Fighters over foo fighters. Except it ignore all caps * ASCII values, so given the values Foo, FOO, and foo, they sort as * FOO, Foo, and foo, but we ignore FOO and pick Foo. But because sqlite's * lower/upper functions only work for ASCII, our check for whether the * value is all uppercase involves ensuring that it doesn't also appear to be * lower case (that is, it may have zero ASCII characters). * * TODO: replace with a custom SQLite function * */ find_cmds.Add (new HyenaSqliteCommand (String.Format (@" INSERT INTO MetadataProblems (ProblemType, TypeOrder, Generation, SolutionValue, SolutionOptions, ObjectIds, ObjectCount) SELECT '{0}', {1}, {2}, COALESCE ( NULLIF ( MIN(CASE (upper({3}) = {3} AND NOT lower({3}) = {3}) WHEN 1 THEN '~~~' ELSE {3} END), '~~~'), {3}) as val, substr(group_concat({3}, ';;'), 1), substr(group_concat({4}, ','), 1), count(*) as num FROM {5} WHERE {6} GROUP BY {7} HAVING num > 1 ORDER BY {3}", Id, 1, "?", // ? is for the Generation variable, which changes value_column, id_column, from, condition ?? "1=1", group_by)) ); } protected override void IdentifyCore () { // Prune artists and albums that are no longer used ServiceManager.DbConnection.Execute (@" DELETE FROM CoreAlbums WHERE AlbumID NOT IN (SELECT DISTINCT(AlbumID) FROM CoreTracks); DELETE FROM CoreArtists WHERE ArtistID NOT IN (SELECT DISTINCT(ArtistID) FROM CoreTracks) AND ArtistID NOT IN (SELECT DISTINCT(ArtistID) FROM CoreAlbums WHERE ArtistID IS NOT NULL);" ); foreach (HyenaSqliteCommand cmd in find_cmds) { ServiceManager.DbConnection.Execute (cmd, Generation); } } } public static class FixupExtensions { public static string NormalizeConjunctions (this string input) { return input.Replace (" & ", " and "); } public static string RemovePrefixedArticles (this string input) { foreach (var prefix in article_prefixes) { if (input.StartsWith (prefix)) { input = input.Substring (prefix.Length, input.Length - prefix.Length); } } return input; } public static string RemoveSuffixedArticles (this string input) { foreach (var suffix in article_suffixes) { if (input.EndsWith (suffix)) { input = input.Substring (0, input.Length - suffix.Length); } } return input; } static string [] article_prefixes; static string [] article_suffixes; static FixupExtensions () { // Translators: These are articles that might be prefixed or suffixed // on artist names or album titles. You can add as many as you need, // separated by a pipe (|) var articles = (Catalog.GetString ("a|an|the") + "|a|an|the").Split ('|').Distinct (); // Translators: This is the format commonly used in your langauge for // suffixing an article, eg in English: ", The" var suffix_format = Catalog.GetString (", {0}"); article_prefixes = articles.Select (a => a + " ") .ToArray (); article_suffixes = articles.SelectMany (a => new string [] { String.Format (suffix_format, a), ", " + a } ).Distinct ().ToArray (); } } /*public class CompilationSolver : Solver { private HyenaSqliteCommand find_cmd; public CompilationSolver () { Id = "make-compilation"; Name = Catalog.GetString ("Compilation Albums"); ShortDescription = Catalog.GetString ("Find albums that should be marked as compilation albums"); LongDescription = Catalog.GetString ("Find albums that should be marked as compilation albums but are not"); Action = Catalog.GetString ("Mark as compilation"); find_cmd = new HyenaSqliteCommand (String.Format (@" INSERT INTO MetadataProblems (ProblemType, TypeOrder, Generation, SolutionValue, Options, Summary, Count) SELECT '{0}', {1}, {2}, a.Title, a.Title, a.Title, count(*) as numtracks FROM CoreTracks t, CoreAlbums a WHERE t.PrimarySourceID = 1 AND a.IsCompilation = 0 AND t.AlbumID = a.AlbumID GROUP BY a.Title HAVING numtracks > 1 AND t.TrackCount = {3} AND a.Title != 'Unknown Album' AND a.Title != 'title' AND a.Title != 'no title' AND a.Title != 'Album' AND a.Title != 'Music' AND ( {5} > 1 AND {5} = {4} AND ( {3} = 0 OR ({3} >= {5} AND {3} >= numtracks)) OR lower(a.Title) LIKE '%soundtrack%' OR lower(a.Title) LIKE '%soundtrack%' )", Id, Order, Generation, "max(t.TrackCount)", "count(distinct(t.artistid))", "count(distinct(t.albumid))" )); } protected override void IdentifyCore () { ServiceManager.DbConnection.Execute (find_cmd); } public override void Fix (IEnumerable<Problem> problems) { Console.WriteLine ("Asked to fix compilations.."); } }*/ }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/appengine/v1/service.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 Google.Appengine.V1 { /// <summary>Holder for reflection information generated from google/appengine/v1/service.proto</summary> public static partial class ServiceReflection { #region Descriptor /// <summary>File descriptor for google/appengine/v1/service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiFnb29nbGUvYXBwZW5naW5lL3YxL3NlcnZpY2UucHJvdG8SE2dvb2dsZS5h", "cHBlbmdpbmUudjEaHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMucHJvdG8iVQoH", "U2VydmljZRIMCgRuYW1lGAEgASgJEgoKAmlkGAIgASgJEjAKBXNwbGl0GAMg", "ASgLMiEuZ29vZ2xlLmFwcGVuZ2luZS52MS5UcmFmZmljU3BsaXQi+AEKDFRy", "YWZmaWNTcGxpdBI7CghzaGFyZF9ieRgBIAEoDjIpLmdvb2dsZS5hcHBlbmdp", "bmUudjEuVHJhZmZpY1NwbGl0LlNoYXJkQnkSRwoLYWxsb2NhdGlvbnMYAiAD", "KAsyMi5nb29nbGUuYXBwZW5naW5lLnYxLlRyYWZmaWNTcGxpdC5BbGxvY2F0", "aW9uc0VudHJ5GjIKEEFsbG9jYXRpb25zRW50cnkSCwoDa2V5GAEgASgJEg0K", "BXZhbHVlGAIgASgBOgI4ASIuCgdTaGFyZEJ5Eg8KC1VOU1BFQ0lGSUVEEAAS", "CgoGQ09PS0lFEAESBgoCSVAQAkJnChdjb20uZ29vZ2xlLmFwcGVuZ2luZS52", "MUIMU2VydmljZVByb3RvUAFaPGdvb2dsZS5nb2xhbmcub3JnL2dlbnByb3Rv", "L2dvb2dsZWFwaXMvYXBwZW5naW5lL3YxO2FwcGVuZ2luZWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Appengine.V1.Service), global::Google.Appengine.V1.Service.Parser, new[]{ "Name", "Id", "Split" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Appengine.V1.TrafficSplit), global::Google.Appengine.V1.TrafficSplit.Parser, new[]{ "ShardBy", "Allocations" }, null, new[]{ typeof(global::Google.Appengine.V1.TrafficSplit.Types.ShardBy) }, new pbr::GeneratedClrTypeInfo[] { null, }) })); } #endregion } #region Messages /// <summary> /// A Service resource is a logical component of an application that can share /// state and communicate in a secure fashion with other services. /// For example, an application that handles customer requests might /// include separate services to handle tasks such as backend data /// analysis or API requests from mobile devices. Each service has a /// collection of versions that define a specific set of code used to /// implement the functionality of that service. /// </summary> public sealed partial class Service : pb::IMessage<Service> { private static readonly pb::MessageParser<Service> _parser = new pb::MessageParser<Service>(() => new Service()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Service> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Appengine.V1.ServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Service() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Service(Service other) : this() { name_ = other.name_; id_ = other.id_; Split = other.split_ != null ? other.Split.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Service Clone() { return new Service(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Full path to the Service resource in the API. /// Example: `apps/myapp/services/default`. /// /// @OutputOnly /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 2; private string id_ = ""; /// <summary> /// Relative name of the service within the application. /// Example: `default`. /// /// @OutputOnly /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Id { get { return id_; } set { id_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "split" field.</summary> public const int SplitFieldNumber = 3; private global::Google.Appengine.V1.TrafficSplit split_; /// <summary> /// Mapping that defines fractional HTTP traffic diversion to /// different versions within the service. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Appengine.V1.TrafficSplit Split { get { return split_; } set { split_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Service); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Service other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Id != other.Id) return false; if (!object.Equals(Split, other.Split)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Id.Length != 0) hash ^= Id.GetHashCode(); if (split_ != null) hash ^= Split.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 (Id.Length != 0) { output.WriteRawTag(18); output.WriteString(Id); } if (split_ != null) { output.WriteRawTag(26); output.WriteMessage(Split); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Id.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Id); } if (split_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Split); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Service other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Id.Length != 0) { Id = other.Id; } if (other.split_ != null) { if (split_ == null) { split_ = new global::Google.Appengine.V1.TrafficSplit(); } Split.MergeFrom(other.Split); } } [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: { Id = input.ReadString(); break; } case 26: { if (split_ == null) { split_ = new global::Google.Appengine.V1.TrafficSplit(); } input.ReadMessage(split_); break; } } } } } /// <summary> /// Traffic routing configuration for versions within a single service. Traffic /// splits define how traffic directed to the service is assigned to versions. /// </summary> public sealed partial class TrafficSplit : pb::IMessage<TrafficSplit> { private static readonly pb::MessageParser<TrafficSplit> _parser = new pb::MessageParser<TrafficSplit>(() => new TrafficSplit()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TrafficSplit> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Appengine.V1.ServiceReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrafficSplit() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrafficSplit(TrafficSplit other) : this() { shardBy_ = other.shardBy_; allocations_ = other.allocations_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TrafficSplit Clone() { return new TrafficSplit(this); } /// <summary>Field number for the "shard_by" field.</summary> public const int ShardByFieldNumber = 1; private global::Google.Appengine.V1.TrafficSplit.Types.ShardBy shardBy_ = 0; /// <summary> /// Mechanism used to determine which version a request is sent to. /// The traffic selection algorithm will /// be stable for either type until allocations are changed. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Appengine.V1.TrafficSplit.Types.ShardBy ShardBy { get { return shardBy_; } set { shardBy_ = value; } } /// <summary>Field number for the "allocations" field.</summary> public const int AllocationsFieldNumber = 2; private static readonly pbc::MapField<string, double>.Codec _map_allocations_codec = new pbc::MapField<string, double>.Codec(pb::FieldCodec.ForString(10), pb::FieldCodec.ForDouble(17), 18); private readonly pbc::MapField<string, double> allocations_ = new pbc::MapField<string, double>(); /// <summary> /// Mapping from version IDs within the service to fractional /// (0.000, 1] allocations of traffic for that version. Each version can /// be specified only once, but some versions in the service may not /// have any traffic allocation. Services that have traffic allocated /// cannot be deleted until either the service is deleted or /// their traffic allocation is removed. Allocations must sum to 1. /// Up to two decimal place precision is supported for IP-based splits and /// up to three decimal places is supported for cookie-based splits. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::MapField<string, double> Allocations { get { return allocations_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TrafficSplit); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TrafficSplit other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ShardBy != other.ShardBy) return false; if (!Allocations.Equals(other.Allocations)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ShardBy != 0) hash ^= ShardBy.GetHashCode(); hash ^= Allocations.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 (ShardBy != 0) { output.WriteRawTag(8); output.WriteEnum((int) ShardBy); } allocations_.WriteTo(output, _map_allocations_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ShardBy != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ShardBy); } size += allocations_.CalculateSize(_map_allocations_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TrafficSplit other) { if (other == null) { return; } if (other.ShardBy != 0) { ShardBy = other.ShardBy; } allocations_.Add(other.allocations_); } [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: { shardBy_ = (global::Google.Appengine.V1.TrafficSplit.Types.ShardBy) input.ReadEnum(); break; } case 18: { allocations_.AddEntriesFrom(input, _map_allocations_codec); break; } } } } #region Nested types /// <summary>Container for nested types declared in the TrafficSplit message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// Available sharding mechanisms. /// </summary> public enum ShardBy { /// <summary> /// Diversion method unspecified. /// </summary> [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0, /// <summary> /// Diversion based on a specially named cookie, "GOOGAPPUID." The cookie /// must be set by the application itself or no diversion will occur. /// </summary> [pbr::OriginalName("COOKIE")] Cookie = 1, /// <summary> /// Diversion based on applying the modulus operation to a fingerprint /// of the IP address. /// </summary> [pbr::OriginalName("IP")] Ip = 2, } } #endregion } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using System.Threading.Tasks; using UltimateTeam.Toolkit.Constants; using UltimateTeam.Toolkit.Exceptions; using UltimateTeam.Toolkit.Extensions; using UltimateTeam.Toolkit.Models; using UltimateTeam.Toolkit.Services; namespace UltimateTeam.Toolkit.Requests { internal class LoginRequest : FutRequestBase, IFutRequest<LoginResponse> { private readonly LoginDetails _loginDetails; private readonly ITwoFactorCodeProvider _twoFactorCodeProvider; private IHasher _hasher; private string _personaId; public IHasher Hasher { get { return _hasher ?? (_hasher = new Hasher()); } set { _hasher = value; } } public LoginRequest(LoginDetails loginDetails, ITwoFactorCodeProvider twoFactorCodeProvider) { loginDetails.ThrowIfNullArgument(); _loginDetails = loginDetails; _twoFactorCodeProvider = twoFactorCodeProvider; } public void SetCookieContainer(CookieContainer cookieContainer) { HttpClient.MessageHandler.CookieContainer = cookieContainer; } public async Task<LoginResponse> PerformRequestAsync() { try { var mainPageResponseMessage = await GetMainPageAsync().ConfigureAwait(false); if (!(await IsLoggedInAsync())) { var loginResponseMessage = await LoginAsync(_loginDetails, mainPageResponseMessage); loginResponseMessage = await SetTwoFactorCodeAsync(loginResponseMessage); await CancelUpdateAuthenticationModeAsync(loginResponseMessage); } var nucleusId = await GetNucleusIdAsync(); var shards = await GetShardsAsync(nucleusId); var userAccounts = await GetUserAccountsAsync(_loginDetails.Platform); var sessionId = await GetSessionIdAsync(userAccounts, _loginDetails.Platform); var phishingToken = await ValidateAsync(_loginDetails, sessionId); return new LoginResponse(nucleusId, shards, userAccounts, sessionId, phishingToken, _personaId); } catch (Exception e) { throw new FutException($"Unable to login to {AppVersion}", e); } } private async Task CancelUpdateAuthenticationModeAsync(HttpResponseMessage loginResponseMessage) { var contentData = await loginResponseMessage.Content.ReadAsStringAsync(); if (!contentData.Contains("Set Up an App Authenticator")) return; AddReferrerHeader(loginResponseMessage.RequestMessage.RequestUri.ToString()); var cancelSetUp = await HttpClient.PostAsync(loginResponseMessage.RequestMessage.RequestUri, new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("_eventId", "cancel"), new KeyValuePair<string, string>("appDevice","IPHONE") // ????? })); cancelSetUp.EnsureSuccessStatusCode(); } private async Task<bool> IsLoggedInAsync() { var loginResponse = await HttpClient.GetAsync(Resources.LoggedIn); var loggedInResponse = await DeserializeAsync<IsUserLoggedIn>(loginResponse); return loggedInResponse.IsLoggedIn; } private async Task<string> ValidateAsync(LoginDetails loginDetails, string sessionId) { HttpClient.AddRequestHeader(NonStandardHttpHeaders.SessionId, sessionId); var validateResponseMessage = await HttpClient.PostAsync(Resources.Validate, new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>("answer", Hasher.Hash(loginDetails.SecretAnswer)) })); var validateResponse = await DeserializeAsync<ValidateResponse>(validateResponseMessage); return validateResponse.Token; } private async Task<string> GetSessionIdAsync(UserAccounts userAccounts, Platform platform) { var persona = userAccounts .UserAccountInfo .Personas .FirstOrDefault(p => p.UserClubList.Any(club => club.Platform == GetNucleusPersonaPlatform(platform))); if (persona == null) { throw new FutException("Couldn't find a persona matching the selected platform"); } _personaId = persona.PersonaId.ToString(); var authResponseMessage = await HttpClient.PostAsync(Resources.Auth, new StringContent( string.Format(@"{{ ""isReadOnly"": false, ""sku"": ""FUT17WEB"", ""clientVersion"": 1, ""nucleusPersonaId"": {0}, ""nucleusPersonaDisplayName"": ""{1}"", ""gameSku"": ""{2}"", ""nucleusPersonaPlatform"": ""{3}"", ""locale"": ""en-GB"", ""method"": ""authcode"", ""priorityLevel"":4, ""identification"": {{ ""authCode"": """" }} }}", persona.PersonaId, persona.PersonaName, GetGameSku(platform), GetNucleusPersonaPlatform(platform)))); authResponseMessage.EnsureSuccessStatusCode(); var sessionId = Regex.Match(await authResponseMessage.Content.ReadAsStringAsync(), "\"sid\":\"\\S+\"") .Value .Split(new[] { ':' })[1] .Replace("\"", string.Empty); return sessionId; } private static string GetGameSku(Platform platform) { switch (platform) { case Platform.Ps3: return "FFA17PS3"; case Platform.Ps4: return "FFA17PS4"; case Platform.Xbox360: return "FFA17XBX"; case Platform.XboxOne: return "FFA17XBO"; case Platform.Pc: return "FFA17PCC"; default: throw new ArgumentOutOfRangeException(nameof(platform), platform, null); } } private static string GetNucleusPersonaPlatform(Platform platform) { switch (platform) { case Platform.Ps3: case Platform.Ps4: return "ps3"; case Platform.Xbox360: case Platform.XboxOne: return "360"; case Platform.Pc: return "pc"; default: throw new ArgumentOutOfRangeException(nameof(platform)); } } private async Task<UserAccounts> GetUserAccountsAsync(Platform platform) { HttpClient.RemoveRequestHeader(NonStandardHttpHeaders.Route); var route = $"https://utas.{(platform == Platform.Xbox360 || platform == Platform.XboxOne ? "external.s3" : "s2")}.fut.ea.com:443"; HttpClient.AddRequestHeader(NonStandardHttpHeaders.Route, route); var accountInfoResponseMessage = await HttpClient.GetAsync(string.Format(Resources.AccountInfo, DateTime.Now.ToUnixTime())); return await DeserializeAsync<UserAccounts>(accountInfoResponseMessage); } private async Task<Shards> GetShardsAsync(string nucleusId) { HttpClient.AddRequestHeader(NonStandardHttpHeaders.NucleusId, nucleusId); HttpClient.AddRequestHeader(NonStandardHttpHeaders.EmbedError, "true"); HttpClient.AddRequestHeader(NonStandardHttpHeaders.Route, "https://utas.fut.ea.com"); HttpClient.AddRequestHeader(NonStandardHttpHeaders.RequestedWith, "XMLHttpRequest"); AddAcceptHeader("application/json, text/javascript"); AddAcceptLanguageHeader(); AddReferrerHeader(Resources.BaseShowoff); var shardsResponseMessage = await HttpClient.GetAsync(string.Format(Resources.Shards, DateTime.Now.ToUnixTime())); return await DeserializeAsync<Shards>(shardsResponseMessage); } private async Task<string> GetNucleusIdAsync() { var nucleusResponseMessage = await HttpClient.GetAsync(Resources.NucleusId); nucleusResponseMessage.EnsureSuccessStatusCode(); var nucleusId = Regex.Match(await nucleusResponseMessage.Content.ReadAsStringAsync(), "EASW_ID = '\\d+'") .Value .Split(new[] { " = " }, StringSplitOptions.RemoveEmptyEntries)[1] .Replace("'", string.Empty); return nucleusId; } private async Task<HttpResponseMessage> LoginAsync(LoginDetails loginDetails, HttpResponseMessage mainPageResponseMessage) { var loginResponseMessage = await HttpClient.PostAsync(mainPageResponseMessage.RequestMessage.RequestUri, new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>("email", loginDetails.Username), new KeyValuePair<string, string>("password", loginDetails.Password), new KeyValuePair<string, string>("_rememberMe", "on"), new KeyValuePair<string, string>("rememberMe", "on"), new KeyValuePair<string, string>("_eventId", "submit"), new KeyValuePair<string, string>("facebookAuth", "") })); loginResponseMessage.EnsureSuccessStatusCode(); return loginResponseMessage; } private async Task<HttpResponseMessage> SetTwoFactorCodeAsync(HttpResponseMessage loginResponse) { //check if twofactorcode is required var contentData = await loginResponse.Content.ReadAsStringAsync(); if (!(contentData.Contains("We sent a security code to your") || contentData.Contains("Your security code was sent to") || contentData.Contains("Enter the 6-digit verification code generated by your App Authenticator"))) { return loginResponse; } var tfCode = await _twoFactorCodeProvider.GetTwoFactorCodeAsync(); var responseContent = await loginResponse.Content.ReadAsStringAsync(); AddReferrerHeader(loginResponse.RequestMessage.RequestUri.ToString()); var codeResponseMessage = await HttpClient.PostAsync(loginResponse.RequestMessage.RequestUri, new FormUrlEncodedContent( new[] { new KeyValuePair<string, string>(responseContent.Contains("twofactorCode") ? "twofactorCode" : "twoFactorCode", tfCode), new KeyValuePair<string, string>("_eventId", "submit"), new KeyValuePair<string, string>("_trustThisDevice", "on"), new KeyValuePair<string, string>("trustThisDevice", "on") })); codeResponseMessage.EnsureSuccessStatusCode(); var tfcResponseContent = await codeResponseMessage.Content.ReadAsStringAsync(); if (tfcResponseContent.Contains("Incorrect code entered")) throw new FutException("Incorrect TwoFactorCode entered."); return codeResponseMessage; } private async Task<HttpResponseMessage> GetMainPageAsync() { AddUserAgent(); AddAcceptEncodingHeader(); var mainPageResponseMessage = await HttpClient.GetAsync(Resources.Home); mainPageResponseMessage.EnsureSuccessStatusCode(); //check if twofactorcode is required var contentData = await mainPageResponseMessage.Content.ReadAsStringAsync(); if (contentData.Contains("We sent a security code to your") || contentData.Contains("Your security code was sent to") || contentData.Contains("Enter the 6-digit verification code generated by your App Authenticator")) { await SetTwoFactorCodeAsync(mainPageResponseMessage); } return mainPageResponseMessage; } } }
using System; using System.IO; using System.Text; using Lucene.Net.Analysis; using Lucene.Net.Analysis.Tokenattributes; using Lucene.Net.Index; using Lucene.Net.Support; using Lucene.Net.Util; namespace Lucene.Net.Documents { // javadocs /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // javadocs /// <summary> /// Expert: directly create a field for a document. Most /// users should use one of the sugar subclasses: {@link /// IntField}, <seealso cref="LongField"/>, <seealso cref="FloatField"/>, {@link /// DoubleField}, <seealso cref="BinaryDocValuesField"/>, {@link /// NumericDocValuesField}, <seealso cref="SortedDocValuesField"/>, {@link /// StringField}, <seealso cref="TextField"/>, <seealso cref="StoredField"/>. /// /// <p/> A field is a section of a Document. Each field has three /// parts: name, type and value. Values may be text /// (String, Reader or pre-analyzed TokenStream), binary /// (byte[]), or numeric (a Number). Fields are optionally stored in the /// index, so that they may be returned with hits on the document. /// /// <p/> /// NOTE: the field type is an <seealso cref="IndexableFieldType"/>. Making changes /// to the state of the IndexableFieldType will impact any /// Field it is used in. It is strongly recommended that no /// changes be made after Field instantiation. /// </summary> public class Field : IndexableField { /// <summary> /// Field's type /// </summary> protected internal readonly FieldType Type; /// <summary> /// Field's name /// </summary> protected internal readonly string Name_Renamed; /// <summary> /// Field's value </summary> protected internal object FieldsData; /// <summary> /// Pre-analyzed tokenStream for indexed fields; this is /// separate from fieldsData because you are allowed to /// have both; eg maybe field has a String value but you /// customize how it's tokenized /// </summary> protected internal TokenStream TokenStream_Renamed; [NonSerialized] private TokenStream InternalTokenStream; /// <summary> /// Field's boost </summary> /// <seealso cref= #boost() </seealso> protected internal float Boost_Renamed = 1.0f; /// <summary> /// Expert: creates a field with no initial value. /// Intended only for custom Field subclasses. </summary> /// <param name="name"> field name </param> /// <param name="type"> field type </param> /// <exception cref="ArgumentNullException"> if either the name or type /// is null. </exception> protected internal Field(string name, FieldType type) { if (name == null) { throw new System.ArgumentNullException("name", "name cannot be null"); } this.Name_Renamed = name; if (type == null) { throw new System.ArgumentNullException("type", "type cannot be null"); } this.Type = type; } /// <summary> /// Create field with Reader value. </summary> /// <param name="name"> field name </param> /// <param name="reader"> reader value </param> /// <param name="type"> field type </param> /// <exception cref="ArgumentNullException"> if either the name or type /// is null, or if the field's type is stored(), or /// if tokenized() is false. </exception> /// <exception cref="ArgumentNullException"> if the reader is null </exception> public Field(string name, TextReader reader, FieldType type) { if (name == null) { throw new System.ArgumentNullException("name", "name cannot be null"); } if (type == null) { throw new System.ArgumentNullException("type", "type cannot be null"); } if (reader == null) { throw new System.ArgumentNullException("reader", "reader cannot be null"); } if (type.Stored) { throw new System.ArgumentException("fields with a Reader value cannot be stored"); } if (type.Indexed && !type.Tokenized) { throw new System.ArgumentException("non-tokenized fields must use String values"); } this.Name_Renamed = name; this.FieldsData = reader; this.Type = type; } /// <summary> /// Create field with TokenStream value. </summary> /// <param name="name"> field name </param> /// <param name="tokenStream"> TokenStream value </param> /// <param name="type"> field type </param> /// <exception cref="ArgumentException"> if either the name or type /// is null, or if the field's type is stored(), or /// if tokenized() is false, or if indexed() is false. </exception> /// <exception cref="ArgumentNullException"> if the tokenStream is null </exception> public Field(string name, TokenStream tokenStream, FieldType type) { if (name == null) { throw new System.ArgumentNullException("name", "name cannot be null"); } if (tokenStream == null) { throw new System.ArgumentNullException("tokenStream","tokenStream cannot be null"); } if (!type.Indexed || !type.Tokenized) { throw new System.ArgumentException("TokenStream fields must be indexed and tokenized"); } if (type.Stored) { throw new System.ArgumentException("TokenStream fields cannot be stored"); } this.Name_Renamed = name; this.FieldsData = null; this.TokenStream_Renamed = tokenStream; this.Type = type; } /// <summary> /// Create field with binary value. /// /// <p>NOTE: the provided byte[] is not copied so be sure /// not to change it until you're done with this field. </summary> /// <param name="name"> field name </param> /// <param name="value"> byte array pointing to binary content (not copied) </param> /// <param name="type"> field type </param> /// <exception cref="ArgumentException"> if the field name is null, /// or the field's type is indexed() </exception> /// <exception cref="ArgumentNullException"> if the type is null </exception> public Field(string name, byte[] value, FieldType type) : this(name, value, 0, value.Length, type) { } /// <summary> /// Create field with binary value. /// /// <p>NOTE: the provided byte[] is not copied so be sure /// not to change it until you're done with this field. </summary> /// <param name="name"> field name </param> /// <param name="value"> byte array pointing to binary content (not copied) </param> /// <param name="offset"> starting position of the byte array </param> /// <param name="length"> valid length of the byte array </param> /// <param name="type"> field type </param> /// <exception cref="ArgumentException"> if the field name is null, /// or the field's type is indexed() </exception> /// <exception cref="ArgumentNullException"> if the type is null </exception> public Field(string name, byte[] value, int offset, int length, FieldType type) : this(name, new BytesRef(value, offset, length), type) { } /// <summary> /// Create field with binary value. /// /// <p>NOTE: the provided BytesRef is not copied so be sure /// not to change it until you're done with this field. </summary> /// <param name="name"> field name </param> /// <param name="bytes"> BytesRef pointing to binary content (not copied) </param> /// <param name="type"> field type </param> /// <exception cref="ArgumentException"> if the field name is null, /// or the field's type is indexed() </exception> /// <exception cref="ArgumentNullException"> if the type is null </exception> public Field(string name, BytesRef bytes, FieldType type) { if (name == null) { throw new System.ArgumentNullException("name", "name cannot be null"); } if (type.Indexed) { throw new System.ArgumentException("Fields with BytesRef values cannot be indexed"); } this.FieldsData = bytes; this.Type = type; this.Name_Renamed = name; } // TODO: allow direct construction of int, long, float, double value too..? /// <summary> /// Create field with String value. </summary> /// <param name="name"> field name </param> /// <param name="value"> string value </param> /// <param name="type"> field type </param> /// <exception cref="ArgumentException"> if either the name or value /// is null, or if the field's type is neither indexed() nor stored(), /// or if indexed() is false but storeTermVectors() is true. </exception> /// <exception cref="ArgumentNullException"> if the type is null </exception> public Field(string name, string value, FieldType type) { if (name == null) { throw new System.ArgumentNullException("name", "name cannot be null"); } if (value == null) { throw new System.ArgumentNullException("value", "value cannot be null"); } if (!type.Stored && !type.Indexed) { throw new System.ArgumentException("it doesn't make sense to have a field that " + "is neither indexed nor stored"); } if (!type.Indexed && (type.StoreTermVectors)) { throw new System.ArgumentException("cannot store term vector information " + "for a field that is not indexed"); } this.Type = type; this.Name_Renamed = name; this.FieldsData = value; } /// <summary> /// The TokenStream for this field to be used when indexing, or null. If null, /// the Reader value or String value is analyzed to produce the indexed tokens. /// </summary> public virtual TokenStream TokenStreamValue() { return TokenStream_Renamed; } /// <summary> /// <p> /// Expert: change the value of this field. this can be used during indexing to /// re-use a single Field instance to improve indexing speed by avoiding GC /// cost of new'ing and reclaiming Field instances. Typically a single /// <seealso cref="Document"/> instance is re-used as well. this helps most on small /// documents. /// </p> /// /// <p> /// Each Field instance should only be used once within a single /// <seealso cref="Document"/> instance. See <a /// href="http://wiki.apache.org/lucene-java/ImproveIndexingSpeed" /// >ImproveIndexingSpeed</a> for details. /// </p> /// </summary> public string StringValue { get { return FieldsData == null ? null : FieldsData.ToString(); /*if (FieldsData is string || FieldsData is Number) { return FieldsData.ToString(); } else { return null; }*/ } set { if (!(FieldsData is String)) { throw new ArgumentException("cannot change value type from " + FieldsData.GetType().Name + " to String"); } FieldsData = value; } } /// <summary> /// Expert: change the value of this field. See /// <seealso cref="#setStringValue(String)"/>. /// </summary> public TextReader ReaderValue { get { return FieldsData is TextReader ? (TextReader)FieldsData : null; } set { if (!(FieldsData is TextReader)) { throw new ArgumentException("cannot change value type from " + FieldsData.GetType().Name + " to Reader"); } FieldsData = value; } } /// <summary> /// Expert: change the value of this field. See /// <seealso cref="#setStringValue(String)"/>. /// /// <p>NOTE: the provided BytesRef is not copied so be sure /// not to change it until you're done with this field. /// </summary> public virtual BytesRef BytesValue { set { if (!(FieldsData is BytesRef)) { throw new System.ArgumentException("cannot change value type from " + FieldsData.GetType().Name + " to BytesRef"); } if (Type.Indexed) { throw new System.ArgumentException("cannot set a BytesRef value on an indexed field"); } FieldsData = value; } } /// <summary> /// Expert: change the value of this field. See /// <seealso cref="#setStringValue(String)"/>. /// </summary> public virtual sbyte ByteValue { set { if (!(FieldsData is sbyte?)) { throw new System.ArgumentException("cannot change value type from " + FieldsData.GetType().Name + " to Byte"); } FieldsData = Convert.ToByte(value); } } /// <summary> /// Expert: change the value of this field. See /// <seealso cref="#setStringValue(String)"/>. /// </summary> public virtual short ShortValue { set { if (!(FieldsData is short?)) { throw new System.ArgumentException("cannot change value type from " + FieldsData.GetType().Name + " to Short"); } FieldsData = Convert.ToInt16(value); } } /// <summary> /// Expert: change the value of this field. See /// <seealso cref="#setStringValue(String)"/>. /// </summary> public virtual int IntValue { set { if (!(FieldsData is int?)) { throw new System.ArgumentException("cannot change value type from " + FieldsData.GetType().Name + " to Integer"); } FieldsData = Convert.ToInt32(value); } } /// <summary> /// Expert: change the value of this field. See /// <seealso cref="#setStringValue(String)"/>. /// </summary> public virtual long LongValue { set { if (!(FieldsData is long?)) { throw new System.ArgumentException("cannot change value type from " + FieldsData.GetType().Name + " to Long"); } FieldsData = Convert.ToInt64(value); } } /// <summary> /// Expert: change the value of this field. See /// <seealso cref="#setStringValue(String)"/>. /// </summary> public virtual float FloatValue { set { if (!(FieldsData is float?)) { throw new System.ArgumentException("cannot change value type from " + FieldsData.GetType().Name + " to Float"); } FieldsData = Convert.ToSingle(value); } } /// <summary> /// Expert: change the value of this field. See /// <seealso cref="#setStringValue(String)"/>. /// </summary> public virtual double DoubleValue { set { if (!(FieldsData is double?)) { throw new System.ArgumentException("cannot change value type from " + FieldsData.GetType().Name + " to Double"); } FieldsData = Convert.ToDouble(value); } } /// <summary> /// Expert: sets the token stream to be used for indexing and causes /// isIndexed() and isTokenized() to return true. May be combined with stored /// values from stringValue() or getBinaryValue() /// </summary> public virtual TokenStream TokenStream { set { if (!Type.Indexed || !Type.Tokenized) { throw new System.ArgumentException("TokenStream fields must be indexed and tokenized"); } if (Type.NumericTypeValue != null) { throw new System.ArgumentException("cannot set private TokenStream on numeric fields"); } this.TokenStream_Renamed = value; } } public string Name() { return Name_Renamed; } /// <summary> /// {@inheritDoc} /// <p> /// The default value is <code>1.0f</code> (no boost). </summary> /// <seealso> cref= #setBoost(float) </seealso> public float GetBoost() { return Boost_Renamed; } /// <summary> /// Sets the boost factor on this field. </summary> /// <exception cref="IllegalArgumentException"> if this field is not indexed, /// or if it omits norms. </exception> /// <seealso> cref= #boost() </seealso> public virtual float Boost { set { if (value != 1.0f) { if (Type.Indexed == false || Type.OmitNorms) { throw new System.ArgumentException("You cannot set an index-time boost on an unindexed field, or one that omits norms"); } } this.Boost_Renamed = value; } } public object NumericValue { get { string str = FieldsData as string; if (str != null) { long ret; if (long.TryParse(str, out ret)) { return ret; } } if (FieldsData is int || FieldsData is float || FieldsData is double || FieldsData is long) { return FieldsData; } return null; } } public BytesRef BinaryValue() { if (FieldsData is BytesRef) { return (BytesRef)FieldsData; } else { return null; } } /// <summary> /// Prints a Field for human consumption. </summary> public override string ToString() { StringBuilder result = new StringBuilder(); result.Append(Type.ToString()); result.Append('<'); result.Append(Name_Renamed); result.Append(':'); if (FieldsData != null) { result.Append(FieldsData); } result.Append('>'); return result.ToString(); } /// <summary> /// Returns the <seealso cref="FieldType"/> for this field. </summary> public IndexableFieldType FieldType() { return Type; } public TokenStream GetTokenStream(Analyzer analyzer) { if (!((FieldType)FieldType()).Indexed) { return null; } FieldType.NumericType? numericType = ((FieldType)FieldType()).NumericTypeValue; if (numericType != null) { if (!(InternalTokenStream is NumericTokenStream)) { // lazy init the TokenStream as it is heavy to instantiate // (attributes,...) if not needed (stored field loading) InternalTokenStream = new NumericTokenStream(Type.NumericPrecisionStep); } var nts = (NumericTokenStream)InternalTokenStream; // initialize value in TokenStream object val = FieldsData; switch (numericType) { case Documents.FieldType.NumericType.INT: nts.SetIntValue(Convert.ToInt32(val)); break; case Documents.FieldType.NumericType.LONG: nts.SetLongValue(Convert.ToInt64(val)); break; case Documents.FieldType.NumericType.FLOAT: nts.SetFloatValue(Convert.ToSingle(val)); break; case Documents.FieldType.NumericType.DOUBLE: nts.SetDoubleValue(Convert.ToDouble(val)); break; default: throw new Exception("Should never get here"); } return InternalTokenStream; } if (!((FieldType)FieldType()).Tokenized) { if (StringValue == null) { throw new System.ArgumentException("Non-Tokenized Fields must have a String value"); } if (!(InternalTokenStream is StringTokenStream)) { // lazy init the TokenStream as it is heavy to instantiate // (attributes,...) if not needed (stored field loading) InternalTokenStream = new StringTokenStream(); } ((StringTokenStream)InternalTokenStream).Value = StringValue; return InternalTokenStream; } if (TokenStream_Renamed != null) { return TokenStream_Renamed; } else if (ReaderValue != null) { return analyzer.TokenStream(Name(), ReaderValue); } else if (StringValue != null) { TextReader sr = new StringReader(StringValue); return analyzer.TokenStream(Name(), sr); } throw new System.ArgumentException("Field must have either TokenStream, String, Reader or Number value; got " + this); } internal sealed class StringTokenStream : TokenStream { internal bool InstanceFieldsInitialized = false; internal void InitializeInstanceFields() { TermAttribute = AddAttribute<ICharTermAttribute>(); OffsetAttribute = AddAttribute<IOffsetAttribute>(); } internal ICharTermAttribute TermAttribute; internal IOffsetAttribute OffsetAttribute; internal bool Used = false; internal string value = null; /// <summary> /// Creates a new TokenStream that returns a String as single token. /// <p>Warning: Does not initialize the value, you must call /// <seealso cref="#setValue(String)"/> afterwards! /// </summary> internal StringTokenStream() { if (!InstanceFieldsInitialized) { InitializeInstanceFields(); InstanceFieldsInitialized = true; } } /// <summary> /// Sets the string value. </summary> internal string Value { set { this.value = value; } } public override bool IncrementToken() { if (Used) { return false; } ClearAttributes(); TermAttribute.Append(value); OffsetAttribute.SetOffset(0, value.Length); Used = true; return true; } public override void End() { base.End(); int finalOffset = value.Length; OffsetAttribute.SetOffset(finalOffset, finalOffset); } public override void Reset() { Used = false; } public void Dispose(bool disposing) { if (disposing) value = null; } } /// <summary> /// Specifies whether and how a field should be stored. </summary> public enum Store { /// <summary> /// Store the original field value in the index. this is useful for short texts /// like a document's title which should be displayed with the results. The /// value is stored in its original form, i.e. no analyzer is used before it is /// stored. /// </summary> YES, /// <summary> /// Do not store the field's value in the index. </summary> NO } // // Deprecated transition API below: // /// <summary> /// Specifies whether and how a field should be indexed. /// <summary>Specifies whether and how a field should be indexed. </summary> [Obsolete] public enum Index { /// <summary>Do not index the field value. This field can thus not be searched, /// but one can still access its contents provided it is /// <see cref="Field.Store">stored</see>. /// </summary> NO, /// <summary>Index the tokens produced by running the field's /// value through an Analyzer. This is useful for /// common text. /// </summary> ANALYZED, /// <summary>Index the field's value without using an Analyzer, so it can be searched. /// As no analyzer is used the value will be stored as a single term. This is /// useful for unique Ids like product numbers. /// </summary> NOT_ANALYZED, /// <summary>Expert: Index the field's value without an Analyzer, /// and also disable the storing of norms. Note that you /// can also separately enable/disable norms by setting /// <see cref="AbstractField.OmitNorms" />. No norms means that /// index-time field and document boosting and field /// length normalization are disabled. The benefit is /// less memory usage as norms take up one byte of RAM /// per indexed field for every document in the index, /// during searching. Note that once you index a given /// field <i>with</i> norms enabled, disabling norms will /// have no effect. In other words, for this to have the /// above described effect on a field, all instances of /// that field must be indexed with NOT_ANALYZED_NO_NORMS /// from the beginning. /// </summary> NOT_ANALYZED_NO_NORMS, /// <summary>Expert: Index the tokens produced by running the /// field's value through an Analyzer, and also /// separately disable the storing of norms. See /// <see cref="NOT_ANALYZED_NO_NORMS" /> for what norms are /// and why you may want to disable them. /// </summary> ANALYZED_NO_NORMS, } /// <summary>Specifies whether and how a field should have term vectors. </summary> [Obsolete] public enum TermVector { /// <summary>Do not store term vectors. </summary> NO, /// <summary>Store the term vectors of each document. A term vector is a list /// of the document's terms and their number of occurrences in that document. /// </summary> YES, /// <summary> Store the term vector + token position information /// /// </summary> /// <seealso cref="YES"> /// </seealso> WITH_POSITIONS, /// <summary> Store the term vector + Token offset information /// /// </summary> /// <seealso cref="YES"> /// </seealso> WITH_OFFSETS, /// <summary> Store the term vector + Token position and offset information /// /// </summary> /// <seealso cref="YES"> /// </seealso> /// <seealso cref="WITH_POSITIONS"> /// </seealso> /// <seealso cref="WITH_OFFSETS"> /// </seealso> WITH_POSITIONS_OFFSETS, } public static FieldType TranslateFieldType(Store store, Index index, TermVector termVector) { FieldType ft = new FieldType(); ft.Stored = store == Store.YES; switch (index) { case Index.ANALYZED: ft.Indexed = true; ft.Tokenized = true; break; case Index.ANALYZED_NO_NORMS: ft.Indexed = true; ft.Tokenized = true; ft.OmitNorms = true; break; case Index.NOT_ANALYZED: ft.Indexed = true; ft.Tokenized = false; break; case Index.NOT_ANALYZED_NO_NORMS: ft.Indexed = true; ft.Tokenized = false; ft.OmitNorms = true; break; case Index.NO: break; } switch (termVector) { case TermVector.NO: break; case TermVector.YES: ft.StoreTermVectors = true; break; case TermVector.WITH_POSITIONS: ft.StoreTermVectors = true; ft.StoreTermVectorPositions = true; break; case TermVector.WITH_OFFSETS: ft.StoreTermVectors = true; ft.StoreTermVectorOffsets = true; break; case TermVector.WITH_POSITIONS_OFFSETS: ft.StoreTermVectors = true; ft.StoreTermVectorPositions = true; ft.StoreTermVectorOffsets = true; break; } ft.Freeze(); return ft; } [Obsolete("Use StringField, TextField instead.")] public Field(String name, String value, Store store, Index index) : this(name, value, TranslateFieldType(store, index, TermVector.NO)) { } [Obsolete("Use StringField, TextField instead.")] public Field(String name, String value, Store store, Index index, TermVector termVector) : this(name, value, TranslateFieldType(store, index, termVector)) { } [Obsolete("Use TextField instead.")] public Field(String name, TextReader reader) : this(name, reader, TermVector.NO) { } [Obsolete("Use TextField instead.")] public Field(String name, TextReader reader, TermVector termVector) : this(name, reader, TranslateFieldType(Store.NO, Index.ANALYZED, termVector)) { } [Obsolete("Use TextField instead.")] public Field(String name, TokenStream tokenStream) : this(name, tokenStream, TermVector.NO) { } [Obsolete("Use TextField instead.")] public Field(String name, TokenStream tokenStream, TermVector termVector) : this(name, tokenStream, TranslateFieldType(Store.NO, Index.ANALYZED, termVector)) { } [Obsolete("Use StoredField instead.")] public Field(String name, byte[] value) : this(name, value, TranslateFieldType(Store.YES, Index.NO, TermVector.NO)) { } [Obsolete("Use StoredField instead.")] public Field(String name, byte[] value, int offset, int length) : this(name, value, offset, length, TranslateFieldType(Store.YES, Index.NO, TermVector.NO)) { } } public static class FieldExtensions { public static bool IsStored(this Field.Store store) { switch (store) { case Field.Store.YES: return true; case Field.Store.NO: return false; default: throw new ArgumentOutOfRangeException("store", "Invalid value for Field.Store"); } } public static bool IsIndexed(this Field.Index index) { switch (index) { case Field.Index.NO: return false; case Field.Index.ANALYZED: case Field.Index.NOT_ANALYZED: case Field.Index.NOT_ANALYZED_NO_NORMS: case Field.Index.ANALYZED_NO_NORMS: return true; default: throw new ArgumentOutOfRangeException("index", "Invalid value for Field.Index"); } } public static bool IsAnalyzed(this Field.Index index) { switch (index) { case Field.Index.NO: case Field.Index.NOT_ANALYZED: case Field.Index.NOT_ANALYZED_NO_NORMS: return false; case Field.Index.ANALYZED: case Field.Index.ANALYZED_NO_NORMS: return true; default: throw new ArgumentOutOfRangeException("index", "Invalid value for Field.Index"); } } public static bool OmitNorms(this Field.Index index) { switch (index) { case Field.Index.ANALYZED: case Field.Index.NOT_ANALYZED: return false; case Field.Index.NO: case Field.Index.NOT_ANALYZED_NO_NORMS: case Field.Index.ANALYZED_NO_NORMS: return true; default: throw new ArgumentOutOfRangeException("index", "Invalid value for Field.Index"); } } public static bool IsStored(this Field.TermVector tv) { switch (tv) { case Field.TermVector.NO: return false; case Field.TermVector.YES: case Field.TermVector.WITH_OFFSETS: case Field.TermVector.WITH_POSITIONS: case Field.TermVector.WITH_POSITIONS_OFFSETS: return true; default: throw new ArgumentOutOfRangeException("tv", "Invalid value for Field.TermVector"); } } public static bool WithPositions(this Field.TermVector tv) { switch (tv) { case Field.TermVector.NO: case Field.TermVector.YES: case Field.TermVector.WITH_OFFSETS: return false; case Field.TermVector.WITH_POSITIONS: case Field.TermVector.WITH_POSITIONS_OFFSETS: return true; default: throw new ArgumentOutOfRangeException("tv", "Invalid value for Field.TermVector"); } } public static bool WithOffsets(this Field.TermVector tv) { switch (tv) { case Field.TermVector.NO: case Field.TermVector.YES: case Field.TermVector.WITH_POSITIONS: return false; case Field.TermVector.WITH_OFFSETS: case Field.TermVector.WITH_POSITIONS_OFFSETS: return true; default: throw new ArgumentOutOfRangeException("tv", "Invalid value for Field.TermVector"); } } public static Field.Index ToIndex(bool indexed, bool analyed) { return ToIndex(indexed, analyed, false); } public static Field.Index ToIndex(bool indexed, bool analyzed, bool omitNorms) { // If it is not indexed nothing else matters if (!indexed) { return Field.Index.NO; } // typical, non-expert if (!omitNorms) { if (analyzed) { return Field.Index.ANALYZED; } return Field.Index.NOT_ANALYZED; } // Expert: Norms omitted if (analyzed) { return Field.Index.ANALYZED_NO_NORMS; } return Field.Index.NOT_ANALYZED_NO_NORMS; } /// <summary> /// Get the best representation of a TermVector given the flags. /// </summary> public static Field.TermVector ToTermVector(bool stored, bool withOffsets, bool withPositions) { // If it is not stored, nothing else matters. if (!stored) { return Field.TermVector.NO; } if (withOffsets) { if (withPositions) { return Field.TermVector.WITH_POSITIONS_OFFSETS; } return Field.TermVector.WITH_OFFSETS; } if (withPositions) { return Field.TermVector.WITH_POSITIONS; } return Field.TermVector.YES; } } }
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Jobs; using NUnit.Framework; using System; using System.Collections.Generic; namespace Aardvark.Base.Benchmarks { // AUTO GENERATED CODE - DO NOT CHANGE! [SimpleJob(RuntimeMoniker.NetCoreApp30)] // Uncomment following lines for assembly output, need to add // <DebugType>pdbonly</DebugType> // <DebugSymbols>true</DebugSymbols> // to Aardvark.Base.csproj for Release configuration. // [DisassemblyDiagnoser(printAsm: true, printSource: true)] public class AngleBetweenFloat { const int count = 10000000; readonly V3f[] A = new V3f[count]; readonly V3f[] B = new V3f[count]; readonly float[] angles = new float[count]; public AngleBetweenFloat() { var rnd = new RandomSystem(1); A.SetByIndex(i => rnd.UniformV3fDirection()); angles.SetByIndex(i => rnd.UniformFloat() * (float)Constant.Pi); B.SetByIndex(i => { V3f v; do { v = rnd.UniformV3fDirection(); } while (v.Dot(A[i]).IsTiny()); V3f axis = v.Cross(A[i]).Normalized; return M44f.Rotation(axis, angles[i]).TransformDir(A[i]); }); } private double[] ComputeRelativeError(Func<V3f, V3f, float> f) { double[] error = new double[count]; for (int i = 0; i < count; i++) { var v = (double) angles[i]; var va = (double) f(A[i], B[i]); error[i] = Fun.Abs(v - va) / Fun.Abs(v); } return error; } public void BenchmarkNumericalStability() { var methods = new Dictionary<string, Func<V3f, V3f, float>>() { { "Stable", Vec.AngleBetween }, { "Fast", Vec.AngleBetweenFast } }; Console.WriteLine("Benchmarking numerical stability for AngleBetweenFloat"); Console.WriteLine(); foreach (var m in methods) { var errors = ComputeRelativeError(m.Value); var min = errors.Min(); var max = errors.Max(); var mean = errors.Mean(); var var = errors.Variance(); Report.Begin("Relative error for '{0}'", m.Key); Report.Line("Min = {0}", min); Report.Line("Max = {0}", max); Report.Line("Mean = {0}", mean); Report.Line("Variance = {0}", var); Report.End(); Console.WriteLine(); } } [Benchmark] public float AngleBetweenStable() { float sum = 0; for (int i = 0; i < count; i++) { sum += A[i].AngleBetween(B[i]); } return sum; } [Benchmark] public float AngleBetweenFast() { float sum = 0; for (int i = 0; i < count; i++) { sum += A[i].AngleBetweenFast(B[i]); } return sum; } [Test] public void AngleBetweenStableTest() { for (int i = 0; i < count; i++) { var x = A[i].AngleBetween(B[i]); var y = angles[i]; Assert.IsTrue(Fun.ApproximateEquals(x, y, 0.01), "{0} != {1}", x, y); } } [Test] public void AngleBetweenFastTest() { for (int i = 0; i < count; i++) { var x = A[i].AngleBetweenFast(B[i]); var y = angles[i]; Assert.IsTrue(Fun.ApproximateEquals(x, y, 0.01), "{0} != {1}", x, y); } } } [SimpleJob(RuntimeMoniker.NetCoreApp30)] // Uncomment following lines for assembly output, need to add // <DebugType>pdbonly</DebugType> // <DebugSymbols>true</DebugSymbols> // to Aardvark.Base.csproj for Release configuration. // [DisassemblyDiagnoser(printAsm: true, printSource: true)] public class AngleBetweenDouble { const int count = 10000000; readonly V3d[] A = new V3d[count]; readonly V3d[] B = new V3d[count]; readonly double[] angles = new double[count]; public AngleBetweenDouble() { var rnd = new RandomSystem(1); A.SetByIndex(i => rnd.UniformV3dDirection()); angles.SetByIndex(i => rnd.UniformDouble() * (double)Constant.Pi); B.SetByIndex(i => { V3d v; do { v = rnd.UniformV3dDirection(); } while (v.Dot(A[i]).IsTiny()); V3d axis = v.Cross(A[i]).Normalized; return M44d.Rotation(axis, angles[i]).TransformDir(A[i]); }); } private double[] ComputeRelativeError(Func<V3d, V3d, double> f) { double[] error = new double[count]; for (int i = 0; i < count; i++) { var v = (double) angles[i]; var va = (double) f(A[i], B[i]); error[i] = Fun.Abs(v - va) / Fun.Abs(v); } return error; } public void BenchmarkNumericalStability() { var methods = new Dictionary<string, Func<V3d, V3d, double>>() { { "Stable", Vec.AngleBetween }, { "Fast", Vec.AngleBetweenFast } }; Console.WriteLine("Benchmarking numerical stability for AngleBetweenDouble"); Console.WriteLine(); foreach (var m in methods) { var errors = ComputeRelativeError(m.Value); var min = errors.Min(); var max = errors.Max(); var mean = errors.Mean(); var var = errors.Variance(); Report.Begin("Relative error for '{0}'", m.Key); Report.Line("Min = {0}", min); Report.Line("Max = {0}", max); Report.Line("Mean = {0}", mean); Report.Line("Variance = {0}", var); Report.End(); Console.WriteLine(); } } [Benchmark] public double AngleBetweenStable() { double sum = 0; for (int i = 0; i < count; i++) { sum += A[i].AngleBetween(B[i]); } return sum; } [Benchmark] public double AngleBetweenFast() { double sum = 0; for (int i = 0; i < count; i++) { sum += A[i].AngleBetweenFast(B[i]); } return sum; } [Test] public void AngleBetweenStableTest() { for (int i = 0; i < count; i++) { var x = A[i].AngleBetween(B[i]); var y = angles[i]; Assert.IsTrue(Fun.ApproximateEquals(x, y, 0.0001), "{0} != {1}", x, y); } } [Test] public void AngleBetweenFastTest() { for (int i = 0; i < count; i++) { var x = A[i].AngleBetweenFast(B[i]); var y = angles[i]; Assert.IsTrue(Fun.ApproximateEquals(x, y, 0.0001), "{0} != {1}", x, y); } } } }
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using System.Reflection; using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; namespace Rotorz.Tile.Editor { /// <summary> /// Provides editor functionality for tile systems. /// </summary> /// <seealso cref="TileSystemInspector"/> [CustomEditor(typeof(TileSystem)), CanEditMultipleObjects] internal sealed class TileSystemEditor : UnityEditor.Editor, IToolContext { private static FieldInfo s_fiTools_ButtonDown; static TileSystemEditor() { // Hack to workaround tool selector error. s_fiTools_ButtonDown = typeof(Tools).GetField("s_ButtonDown", BindingFlags.NonPublic | BindingFlags.Static); } private TileSystemInspector inspector; private ToolEvent toolEvent; #region IToolContext - Implementation /// <inheritdoc/> ToolManager IToolContext.ToolManager { get { return ToolManager.Instance; } } /// <inheritdoc/> ToolBase IToolContext.Tool { get { return ToolManager.Instance.CurrentTool; } } /// <inheritdoc/> TileSystem IToolContext.TileSystem { get { return ToolUtility.ActiveTileSystem; } } public object EditorEditorSceneManager { get; private set; } #endregion #region Messages and Events private void OnEnable() { var targetSystem = target as TileSystem; // Mark active target as the active tile system? // - Must be part of current user selection! // - Must not reside within an asset. if (Selection.activeGameObject == targetSystem.gameObject && Selection.instanceIDs.Length == 1) { if (!EditorUtility.IsPersistent(this.target) && ToolUtility.ActiveTileSystem != targetSystem) { ToolUtility.ActiveTileSystem = targetSystem; // Hide selected wireframe if tool is active. if (ToolManager.Instance.CurrentTool != null) { ToolUtility.HideSelectedWireframe(targetSystem); } } } } #endregion #region Inspector GUI public override void OnInspectorGUI() { if (this.inspector == null) { this.inspector = new TileSystemInspector(this); } bool restoreWideMode = EditorGUIUtility.wideMode; EditorGUIUtility.wideMode = false; this.inspector.OnGUI(); EditorGUIUtility.wideMode = restoreWideMode; } public override bool UseDefaultMargins() { // Do not assume default margins for inspector. return false; } #endregion #region Scene GUI private int sceneControlID = -1; // Tool Hack: Must correct state of View Tool when using middle or right mouse buttons. private void OnPreSceneGUI() { // This is not the active tile system, bail!! if (this.target != ToolUtility.ActiveTileSystem) { return; } this.sceneControlID = GUIUtility.GetControlID(FocusType.Passive); if (s_fiTools_ButtonDown == null) { return; } if (ToolManager.Instance.CurrentTool != null) { var e = Event.current; if (e.GetTypeForControl(this.sceneControlID) == EventType.MouseDown) { if (e.button == 1 && !e.alt && (!e.control || e.shift)) { s_fiTools_ButtonDown.SetValue(null, 0); } } } } private void OnSceneGUI() { var tileSystem = this.target as TileSystem; // This is not the active tile system, bail!! if (tileSystem != ToolUtility.ActiveTileSystem) { return; } // Skip for non-instance prefabs. if (PrefabUtility.GetPrefabType(this.target) == PrefabType.Prefab) { return; } // Tool Hack: Just in case OnPreSceneGUI is not supported in the future. if (this.sceneControlID == -1) { this.sceneControlID = GUIUtility.GetControlID(FocusType.Passive); } // Do not update the value of `ToolBase.IsEditorNearestControl` during layout // events since Unity 4.6.0f1 seems to have introduced a bug whereby the // value of `HandleUtility.nearestControl` is temporarily incorrect. if (Event.current.type != EventType.Layout) { // Determine whether tile system editor is the nearest control to the mouse pointer. // We can use this to avoid overuling other controls in the scene view (like the // viewing angle gadget in upper-right corner). ToolBase.IsEditorNearestControl = (HandleUtility.nearestControl == this.sceneControlID || GUIUtility.hotControl == this.sceneControlID); } // Should tool event data be initialized? if (this.toolEvent == null) { this.toolEvent = new ToolEvent(); this.UpdateToolEventFromCursor(Event.current.mousePosition); } ToolManager.Instance.CheckForKeyboardShortcut(); var tool = ToolManager.Instance.CurrentTool; if (tool != null) { this.DrawStatusPanel(); } // Prevent editing if tile system is not editable! if (!tileSystem.IsEditable) { return; } EventType eventType = Event.current.GetTypeForControl(this.sceneControlID); switch (eventType) { case EventType.Ignore: case EventType.Used: return; case EventType.Layout: if (tool != null) { // Prevent regular object selection when tool is active. HandleUtility.AddDefaultControl(this.sceneControlID); } break; } // Need to record whether this is a mouse event prior to tracking mouse // input since "MouseDrag" and "MouseUp" will otherwise not be properly // detected within `DoTool` since `GUIUtility.hotControl` will have been // reassigned to a value of 0. bool isMouseEvent = (ToolBase.IsEditorNearestControl && Event.current.IsMouseForControl(this.sceneControlID)); bool wasSceneActiveControl = (GUIUtility.hotControl == this.sceneControlID); ToolBase.PreviousToolEvent = this.toolEvent; this.toolEvent.Type = eventType; this.toolEvent.WasLeftButtonPressed = this.toolEvent.IsLeftButtonPressed; this.toolEvent.WasRightButtonPressed = this.toolEvent.IsRightButtonPressed; this.UpdateCursor(); if (isMouseEvent) { this.TrackMouseInput(); } // Do not proceed when a different tool is anchored (with mouse drag)! if (tool != null && (s_AnchorTool == null || s_AnchorTool == tool)) { this.DoTool(tool, isMouseEvent, wasSceneActiveControl); } } private void UpdateCursor() { if (RtsPreferences.DisableCustomCursors || !ToolBase.IsEditorNearestControl || ToolUtility.ActiveTileSystem.Locked) { return; } // Do not attempt to show custom cursor whilst alt key is being held because // this causes Unity to flash between the custom cursor and Unity's view cursor. if (Event.current.alt) { return; } var tool = ToolManager.Instance.CurrentTool; if (tool == null) { return; } if (Application.platform == RuntimePlatform.OSXEditor) { // Force basic Unity cursor to workaround bug (Case 605226) on OS X. EditorGUIUtility.AddCursorRect(new Rect(0, 0, Screen.width, Screen.height), MouseCursor.Arrow, this.sceneControlID); } if (GUIUtility.hotControl == 0 || GUIUtility.hotControl == this.sceneControlID) { CursorInfo cursor = tool.Cursor; if (cursor.Type == MouseCursor.CustomCursor) { // Can only show custom cursor if custom texture was specified. if (cursor.Texture != null) { Cursor.SetCursor(cursor.Texture, cursor.Hotspot, CursorMode.Auto); } else { return; } } // Do not bother defining cursor rectangle if arrow cursor has been specified // since this is the default anyhow. if (cursor.Type != MouseCursor.Arrow) { EditorGUIUtility.AddCursorRect(new Rect(0, 0, Screen.width, Screen.height), cursor.Type, this.sceneControlID); } } } private static ToolBase s_AnchorTool; private void TrackMouseInput() { Event e = Event.current; // Refresh status of left/right mouse button when mouse is not being dragged // or stop dragging when middle mouse button is pressed. if (e.button > 1 || this.toolEvent.Type == EventType.MouseMove) { this.toolEvent.IsRightButtonPressed = this.toolEvent.IsLeftButtonPressed = false; } switch (this.toolEvent.Type) { case EventType.MouseDown: if (!this.UpdateToolEventFromCursor(e.mousePosition)) { break; } if (ToolManager.Instance.CurrentTool != null && GUIUtility.hotControl == 0) { this.toolEvent.IsRightButtonPressed = this.toolEvent.IsLeftButtonPressed = false; // Note: Do not allow use of control or shift with right button // because otherwise it would not be possible to pan and // zoom viewport! if ((e.button == 0 || e.button == 1) && !e.alt && (!e.control || e.shift || e.button == 0)) { if (e.button == 0) { this.toolEvent.IsLeftButtonPressed = true; } else if (e.button == 1) { this.toolEvent.IsRightButtonPressed = true; } GUIUtility.hotControl = this.sceneControlID; s_AnchorTool = ToolManager.Instance.CurrentTool; } } break; case EventType.MouseUp: this.toolEvent.IsRightButtonPressed = this.toolEvent.IsLeftButtonPressed = false; if (GUIUtility.hotControl == this.sceneControlID) { GUIUtility.hotControl = 0; s_AnchorTool = null; } break; case EventType.MouseMove: case EventType.MouseDrag: this.UpdateToolEventFromCursor(e.mousePosition); break; } } private void DoTool(ToolBase tool, bool isMouseEvent, bool wasSceneActiveControl) { var tileSystem = target as TileSystem; this.toolEvent.MousePointerTileIndex = this.toolEvent.LastMousePointerTileIndex; if (!EditorApplication.isPlaying) { // Mark the current scene as being dirty. EditorSceneManager.MarkSceneDirty(tileSystem.gameObject.scene); } // Allow tool to manipulate event data if desired. tool.OnRefreshToolEvent(this.toolEvent, this); ToolUtility.ActiveTileIndex = this.toolEvent.MousePointerTileIndex; // Use currently selected tool! this.DoToolSceneGUI(tool); if (isMouseEvent) { // Tools cannot interact with locked tile systems! if (!tileSystem.Locked) { // Allow tool to respond to all mouse events. bool isSceneActiveControl = GUIUtility.hotControl == this.sceneControlID; if (wasSceneActiveControl || isSceneActiveControl) { tool.OnTool(this.toolEvent, this); switch (this.toolEvent.Type) { case EventType.MouseDown: case EventType.MouseDrag: if (isSceneActiveControl) { Event.current.Use(); } break; case EventType.MouseUp: if (wasSceneActiveControl) { tool.OnToolInactive(this.toolEvent, this); Event.current.Use(); } break; } } else { tool.OnToolInactive(this.toolEvent, this); } } // Force redraw in scene views. SceneView.RepaintAll(); // Force redraw in game views. EditorInternalUtility.RepaintAllGameViews(); } } private void DoToolSceneGUI(ToolBase tool) { var tileSystem = target as TileSystem; // Toggle preview material using control key. this.CheckSwitchImmediatePreviewMaterial(); ToolUtility.CheckToolKeyboardShortcuts(); // Preserve current state of handles. Matrix4x4 originalMatrix = Handles.matrix; Color restoreHandleColor = Handles.color; // Place handles within local space of tile system. Handles.matrix = tileSystem.transform.localToWorldMatrix; // Tools cannot interact with locked tile systems! if (!tileSystem.Locked) { tool.OnSceneGUI(this.toolEvent, this); } else { Vector3 activeCenter = Vector3.zero; activeCenter.x += this.toolEvent.MousePointerTileIndex.column * tileSystem.CellSize.x + tileSystem.CellSize.x / 2f; activeCenter.y -= this.toolEvent.MousePointerTileIndex.row * tileSystem.CellSize.y + tileSystem.CellSize.y / 2f; ToolHandleUtility.DrawWireBox(activeCenter, tileSystem.CellSize); } // Restore former state of handles. Handles.matrix = originalMatrix; Handles.color = restoreHandleColor; } private bool UpdateToolEventFromCursor(Vector2 mousePosition) { var tileSystem = target as TileSystem; // Find mouse position in 3D space. Ray mouseRay = HandleUtility.GUIPointToWorldRay(mousePosition); // Store screen position of mouse pointer. this.toolEvent.MousePointerScreenPoint = mousePosition; Plane systemPlane = new Plane(tileSystem.transform.forward, tileSystem.transform.position); // Calculate point where mouse ray intersect tile system plane. float distanceToPlane = 0f; if (!systemPlane.Raycast(mouseRay, out distanceToPlane)) { return false; } Vector3 cellSize = tileSystem.CellSize; // Calculate world position of cursor in local space of tile system. Vector3 worldPoint = mouseRay.GetPoint(distanceToPlane); Vector3 localPoint = tileSystem.transform.worldToLocalMatrix.MultiplyPoint3x4(worldPoint); // Allow tool to pre-filter local point. // For instance, to switch alignment to grid points rather than cells. var tool = ToolManager.Instance.CurrentTool; if (tool != null) { localPoint = tool.PreFilterLocalPoint(localPoint); } this.toolEvent.MousePointerLocalPoint = localPoint; // Calculate position within grid. this.toolEvent.LastMousePointerTileIndex = new TileIndex( row: Mathf.Clamp((int)(-localPoint.y / cellSize.y), 0, tileSystem.RowCount - 1), column: Mathf.Clamp((int)(localPoint.x / cellSize.x), 0, tileSystem.ColumnCount - 1) ); // We keep track of the last known mouse tile index so that it can be restored // before passing `ToolEvent` to the active tool. This is needed for non-mouse // events since tools are free to mutate `ToolUtility.tileIndex`. return true; } private void CheckSwitchImmediatePreviewMaterial() { bool isSeeThrough = Event.current.control ? !RtsPreferences.ToolImmediatePreviewsSeeThrough : RtsPreferences.ToolImmediatePreviewsSeeThrough; if (isSeeThrough != ImmediatePreviewUtility.IsSeeThroughPreviewMaterial) { ImmediatePreviewUtility.IsSeeThroughPreviewMaterial = isSeeThrough; this.Repaint(); } } private GUI.WindowFunction _statusPanelWindowFunction = (windowID) => { if (ToolManager.Instance.CurrentTool != null) { ToolManager.Instance.CurrentTool.OnStatusPanelGUI(); } }; private void DrawStatusPanel() { var tileSystem = target as TileSystem; Handles.BeginGUI(); if (tileSystem.IsEditable) { string title = tileSystem.name; if (tileSystem.Locked) { title += " <color=yellow><b>(" + TileLang.ParticularText("Status", "Locked") + ")</b></color>"; } Rect position = new Rect(0, Screen.height - 21 - 42, 380, 42); GUI.Window(0, position, this._statusPanelWindowFunction, title, RotorzEditorStyles.Instance.StatusWindow); GUI.UnfocusWindow(); } else { Rect position = new Rect(5, Screen.height - 42 - 40, 380, 40); EditorGUI.HelpBox(position, TileLang.Text("Tile system has been built and can no longer be edited."), MessageType.Warning); } Handles.EndGUI(); } #endregion #region Gizmos [DrawGizmo(GizmoType.NotInSelectionHierarchy | GizmoType.Pickable)] private static void OnDrawGizmosPickable(TileSystem system, GizmoType gizmoType) { if (!Selection.Contains(system.gameObject)) { DrawTileSystemGizmosNotSelected(system); DrawTileSystemHandle(system); } } [DrawGizmo(GizmoType.NonSelected)] private static void OnDrawGizmos(TileSystem system, GizmoType gizmoType) { if (ToolUtility.ActiveTileSystem == system && RtsPreferences.ShowActiveTileSystem) { DrawTileSystemGizmosSelected(system, 1.0f); } } private static void DrawTileSystemHandle(TileSystem system) { // Apply rotation to gizmos. Matrix4x4 originalMatrix = Gizmos.matrix; Gizmos.matrix = system.transform.localToWorldMatrix; Vector3 tileSize = new Vector3(0.5f, 0.5f, 0.5f); Vector3 boundsSize = new Vector3(tileSize.x * 3, tileSize.y * 3, 0f); // Prepare cursor to draw rows. Vector3 cursor = Vector3.zero; Vector3 cursorEnd = Vector3.zero; Gizmos.color = new Color(0.35f, 0.35f, 0.35f, 0.3f); Gizmos.DrawCube(boundsSize / 2f + new Vector3(0f, 0f, 0.01f), boundsSize); Gizmos.color = new Color(0.35f, 0.35f, 0.35f, 0.5f); cursorEnd.x += 3 * tileSize.x; // Draw rows. for (int rowIndex = 0; rowIndex < 4; ++rowIndex) { Gizmos.DrawLine(cursor, cursorEnd); cursor.y += tileSize.y; cursorEnd.y += tileSize.y; } // Prepare cursor to draw columns. cursorEnd = cursor = Vector3.zero; cursorEnd.y += 3 * tileSize.y; // Draw columns. for (int columnIndex = 0; columnIndex < 4; ++columnIndex) { Gizmos.DrawLine(cursor, cursorEnd); cursor.x += tileSize.x; cursorEnd.x += tileSize.x; } // Restore original gizmos matrix. Gizmos.matrix = originalMatrix; } [DrawGizmo(GizmoType.Active)] private static void OnDrawGizmosSelected(TileSystem system, GizmoType gizmoType) { DrawTileSystemGizmosSelected(system, 2.0f); // Do not display gizmos when tile system is locked, this would be confusing! if (system.Locked) { return; } if (!RtsPreferences.ToolImmediatePreviews) { return; } ToolBase currentTool = ToolManager.Instance.CurrentTool; if (currentTool != null && ToolBase.IsEditorNearestControl) { ImmediatePreviewUtility.PreviewMaterial.color = RtsPreferences.ToolImmediatePreviewsTintColor; currentTool.OnDrawGizmos(system); } } private static void DrawTileSystemGizmosNotSelected(TileSystem system) { // Apply rotation to gizmos. Matrix4x4 originalMatrix = Gizmos.matrix; Gizmos.matrix = system.transform.localToWorldMatrix; Gizmos.color = new Color(0.35f, 0.35f, 0.35f, 0.5f); // Prepare cursor to draw rows. Vector3 cellSize = system.CellSize; Vector3 boundsSize = new Vector3(cellSize.x * system.ColumnCount, -cellSize.y * system.RowCount, 0f); // Prepare cursor to draw rows. Vector3 cursor = Vector3.zero; Vector3 cursorEnd = Vector3.zero; cursorEnd.x += 1 * boundsSize.x; // Draw rows. for (int rowIndex = 0; rowIndex < 2; ++rowIndex) { Gizmos.DrawLine(cursor, cursorEnd); cursor.y += boundsSize.y; cursorEnd.y += boundsSize.y; } // Prepare cursor to draw columns. cursorEnd = cursor = Vector3.zero; cursorEnd.y += 1 * boundsSize.y; // Draw columns. for (int columnIndex = 0; columnIndex < 2; ++columnIndex) { Gizmos.DrawLine(cursor, cursorEnd); cursor.x += boundsSize.x; cursorEnd.x += boundsSize.x; } // Restore original gizmos matrix. Gizmos.matrix = originalMatrix; } private static void DrawTileSystemGizmosSelected(TileSystem system, float alphaFactor) { Vector3 cellSize = system.CellSize; // Apply rotation to gizmos. Matrix4x4 originalMatrix = Gizmos.matrix; Gizmos.matrix = system.transform.localToWorldMatrix; if (RtsPreferences.ShowGrid) { Vector3 boundsSize = new Vector3(cellSize.x * system.ColumnCount, -cellSize.y * system.RowCount, 0.00f); bool showChunks = (RtsPreferences.ShowChunks && system.ChunkWidth != 0 && system.ChunkHeight != 0); Color background = RtsPreferences.BackgroundGridColor; Color minor = RtsPreferences.MinorGridColor; Color major = RtsPreferences.MajorGridColor; Color chunk = RtsPreferences.ChunkGridColor; background.a = Mathf.Min(background.a * alphaFactor, 1.0f); minor.a = Mathf.Min(minor.a * alphaFactor, 1.0f); major.a = Mathf.Min(major.a * alphaFactor, 1.0f); chunk.a = Mathf.Min(chunk.a * alphaFactor, 1.0f); Gizmos.color = background; Gizmos.DrawCube(boundsSize / 2f + new Vector3(0f, 0f, 0.01f), boundsSize); // Prepare cursor to draw rows. Vector3 cursor = Vector3.zero; Vector3 cursorEnd = Vector3.zero; cursorEnd.x += system.ColumnCount * cellSize.x; // Draw rows. for (int rowIndex = 0; rowIndex <= system.RowCount; ++rowIndex) { Gizmos.color = (showChunks && rowIndex % system.ChunkHeight == 0) ? chunk : ( rowIndex % 10 == 0 ? major : minor ); Gizmos.DrawLine(cursor, cursorEnd); cursor.y -= cellSize.y; cursorEnd.y -= cellSize.y; } // Prepare cursor to draw columns. cursorEnd = cursor = Vector3.zero; cursorEnd.y -= system.RowCount * cellSize.y; // Draw columns. for (int columnIndex = 0; columnIndex <= system.ColumnCount; ++columnIndex) { Gizmos.color = (showChunks && columnIndex % system.ChunkWidth == 0) ? chunk : ( columnIndex % 10 == 0 ? major : minor ); Gizmos.DrawLine(cursor, cursorEnd); cursor.x += cellSize.x; cursorEnd.x += cellSize.x; } } // Restore original gizmos matrix. Gizmos.matrix = originalMatrix; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Diagnostics.Contracts; using System.Globalization; namespace System { // TimeSpan represents a duration of time. A TimeSpan can be negative // or positive. // // TimeSpan is internally represented as a number of milliseconds. While // this maps well into units of time such as hours and days, any // periods longer than that aren't representable in a nice fashion. // For instance, a month can be between 28 and 31 days, while a year // can contain 365 or 364 days. A decade can have between 1 and 3 leapyears, // depending on when you map the TimeSpan into the calendar. This is why // we do not provide Years() or Months(). // // Note: System.TimeSpan needs to interop with the WinRT structure // type Windows::Foundation:TimeSpan. These types are currently binary-compatible in // memory so no custom marshalling is required. If at any point the implementation // details of this type should change, or new fields added, we need to remember to add // an appropriate custom ILMarshaler to keep WInRT interop scenarios enabled. // [Serializable] public struct TimeSpan : IComparable, IComparable<TimeSpan>, IEquatable<TimeSpan>, IFormattable { public const long TicksPerMillisecond = 10000; private const double MillisecondsPerTick = 1.0 / TicksPerMillisecond; public const long TicksPerSecond = TicksPerMillisecond * 1000; // 10,000,000 private const double SecondsPerTick = 1.0 / TicksPerSecond; // 0.0001 public const long TicksPerMinute = TicksPerSecond * 60; // 600,000,000 private const double MinutesPerTick = 1.0 / TicksPerMinute; // 1.6666666666667e-9 public const long TicksPerHour = TicksPerMinute * 60; // 36,000,000,000 private const double HoursPerTick = 1.0 / TicksPerHour; // 2.77777777777777778e-11 public const long TicksPerDay = TicksPerHour * 24; // 864,000,000,000 private const double DaysPerTick = 1.0 / TicksPerDay; // 1.1574074074074074074e-12 private const int MillisPerSecond = 1000; private const int MillisPerMinute = MillisPerSecond * 60; // 60,000 private const int MillisPerHour = MillisPerMinute * 60; // 3,600,000 private const int MillisPerDay = MillisPerHour * 24; // 86,400,000 internal const long MaxSeconds = Int64.MaxValue / TicksPerSecond; internal const long MinSeconds = Int64.MinValue / TicksPerSecond; internal const long MaxMilliSeconds = Int64.MaxValue / TicksPerMillisecond; internal const long MinMilliSeconds = Int64.MinValue / TicksPerMillisecond; internal const long TicksPerTenthSecond = TicksPerMillisecond * 100; public static readonly TimeSpan Zero = new TimeSpan(0); public static readonly TimeSpan MaxValue = new TimeSpan(Int64.MaxValue); public static readonly TimeSpan MinValue = new TimeSpan(Int64.MinValue); // internal so that DateTime doesn't have to call an extra get // method for some arithmetic operations. internal long _ticks; // Do not rename (binary serialization) public TimeSpan(long ticks) { this._ticks = ticks; } public TimeSpan(int hours, int minutes, int seconds) { _ticks = TimeToTicks(hours, minutes, seconds); } public TimeSpan(int days, int hours, int minutes, int seconds) : this(days, hours, minutes, seconds, 0) { } public TimeSpan(int days, int hours, int minutes, int seconds, int milliseconds) { Int64 totalMilliSeconds = ((Int64)days * 3600 * 24 + (Int64)hours * 3600 + (Int64)minutes * 60 + seconds) * 1000 + milliseconds; if (totalMilliSeconds > MaxMilliSeconds || totalMilliSeconds < MinMilliSeconds) throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong); _ticks = (long)totalMilliSeconds * TicksPerMillisecond; } public long Ticks { get { return _ticks; } } public int Days { get { return (int)(_ticks / TicksPerDay); } } public int Hours { get { return (int)((_ticks / TicksPerHour) % 24); } } public int Milliseconds { get { return (int)((_ticks / TicksPerMillisecond) % 1000); } } public int Minutes { get { return (int)((_ticks / TicksPerMinute) % 60); } } public int Seconds { get { return (int)((_ticks / TicksPerSecond) % 60); } } public double TotalDays { get { return ((double)_ticks) * DaysPerTick; } } public double TotalHours { get { return (double)_ticks * HoursPerTick; } } public double TotalMilliseconds { get { double temp = (double)_ticks * MillisecondsPerTick; if (temp > MaxMilliSeconds) return (double)MaxMilliSeconds; if (temp < MinMilliSeconds) return (double)MinMilliSeconds; return temp; } } public double TotalMinutes { get { return (double)_ticks * MinutesPerTick; } } public double TotalSeconds { get { return (double)_ticks * SecondsPerTick; } } public TimeSpan Add(TimeSpan ts) { long result = _ticks + ts._ticks; // Overflow if signs of operands was identical and result's // sign was opposite. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((_ticks >> 63 == ts._ticks >> 63) && (_ticks >> 63 != result >> 63)) throw new OverflowException(SR.Overflow_TimeSpanTooLong); return new TimeSpan(result); } // Compares two TimeSpan values, returning an integer that indicates their // relationship. // public static int Compare(TimeSpan t1, TimeSpan t2) { if (t1._ticks > t2._ticks) return 1; if (t1._ticks < t2._ticks) return -1; return 0; } // Returns a value less than zero if this object public int CompareTo(Object value) { if (value == null) return 1; if (!(value is TimeSpan)) throw new ArgumentException(SR.Arg_MustBeTimeSpan); long t = ((TimeSpan)value)._ticks; if (_ticks > t) return 1; if (_ticks < t) return -1; return 0; } public int CompareTo(TimeSpan value) { long t = value._ticks; if (_ticks > t) return 1; if (_ticks < t) return -1; return 0; } public static TimeSpan FromDays(double value) { return Interval(value, MillisPerDay); } public TimeSpan Duration() { if (Ticks == TimeSpan.MinValue.Ticks) throw new OverflowException(SR.Overflow_Duration); Contract.EndContractBlock(); return new TimeSpan(_ticks >= 0 ? _ticks : -_ticks); } public override bool Equals(Object value) { if (value is TimeSpan) { return _ticks == ((TimeSpan)value)._ticks; } return false; } public bool Equals(TimeSpan obj) { return _ticks == obj._ticks; } public static bool Equals(TimeSpan t1, TimeSpan t2) { return t1._ticks == t2._ticks; } public override int GetHashCode() { return (int)_ticks ^ (int)(_ticks >> 32); } public static TimeSpan FromHours(double value) { return Interval(value, MillisPerHour); } private static TimeSpan Interval(double value, int scale) { if (Double.IsNaN(value)) throw new ArgumentException(SR.Arg_CannotBeNaN); Contract.EndContractBlock(); double tmp = value * scale; double millis = tmp + (value >= 0 ? 0.5 : -0.5); if ((millis > Int64.MaxValue / TicksPerMillisecond) || (millis < Int64.MinValue / TicksPerMillisecond)) throw new OverflowException(SR.Overflow_TimeSpanTooLong); return new TimeSpan((long)millis * TicksPerMillisecond); } public static TimeSpan FromMilliseconds(double value) { return Interval(value, 1); } public static TimeSpan FromMinutes(double value) { return Interval(value, MillisPerMinute); } public TimeSpan Negate() { if (Ticks == TimeSpan.MinValue.Ticks) throw new OverflowException(SR.Overflow_NegateTwosCompNum); Contract.EndContractBlock(); return new TimeSpan(-_ticks); } public static TimeSpan FromSeconds(double value) { return Interval(value, MillisPerSecond); } public TimeSpan Subtract(TimeSpan ts) { long result = _ticks - ts._ticks; // Overflow if signs of operands was different and result's // sign was opposite from the first argument's sign. // >> 63 gives the sign bit (either 64 1's or 64 0's). if ((_ticks >> 63 != ts._ticks >> 63) && (_ticks >> 63 != result >> 63)) throw new OverflowException(SR.Overflow_TimeSpanTooLong); return new TimeSpan(result); } public TimeSpan Multiply(double factor) => this * factor; public TimeSpan Divide(double divisor) => this / divisor; public double Divide(TimeSpan ts) => this / ts; public static TimeSpan FromTicks(long value) { return new TimeSpan(value); } internal static long TimeToTicks(int hour, int minute, int second) { // totalSeconds is bounded by 2^31 * 2^12 + 2^31 * 2^8 + 2^31, // which is less than 2^44, meaning we won't overflow totalSeconds. long totalSeconds = (long)hour * 3600 + (long)minute * 60 + (long)second; if (totalSeconds > MaxSeconds || totalSeconds < MinSeconds) throw new ArgumentOutOfRangeException(null, SR.Overflow_TimeSpanTooLong); return totalSeconds * TicksPerSecond; } // See System.Globalization.TimeSpanParse and System.Globalization.TimeSpanFormat #region ParseAndFormat private static void ValidateStyles(TimeSpanStyles style, String parameterName) { if (style != TimeSpanStyles.None && style != TimeSpanStyles.AssumeNegative) throw new ArgumentException(SR.Argument_InvalidTimeSpanStyles, parameterName); } public static TimeSpan Parse(String s) { /* Constructs a TimeSpan from a string. Leading and trailing white space characters are allowed. */ return TimeSpanParse.Parse(s, null); } public static TimeSpan Parse(String input, IFormatProvider formatProvider) { return TimeSpanParse.Parse(input, formatProvider); } public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider) { return TimeSpanParse.ParseExact(input, format, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider) { return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None); } public static TimeSpan ParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.ParseExact(input, format, formatProvider, styles); } public static TimeSpan ParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.ParseExactMultiple(input, formats, formatProvider, styles); } public static Boolean TryParse(String s, out TimeSpan result) { return TimeSpanParse.TryParse(s, null, out result); } public static Boolean TryParse(String input, IFormatProvider formatProvider, out TimeSpan result) { return TimeSpanParse.TryParse(input, formatProvider, out result); } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExact(input, format, formatProvider, TimeSpanStyles.None, out result); } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, out TimeSpan result) { return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, TimeSpanStyles.None, out result); } public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.TryParseExact(input, format, formatProvider, styles, out result); } public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, TimeSpanStyles styles, out TimeSpan result) { ValidateStyles(styles, nameof(styles)); return TimeSpanParse.TryParseExactMultiple(input, formats, formatProvider, styles, out result); } public override String ToString() { return TimeSpanFormat.Format(this, null, null); } public String ToString(String format) { return TimeSpanFormat.Format(this, format, null); } public String ToString(String format, IFormatProvider formatProvider) { return TimeSpanFormat.Format(this, format, formatProvider); } #endregion public static TimeSpan operator -(TimeSpan t) { if (t._ticks == TimeSpan.MinValue._ticks) throw new OverflowException(SR.Overflow_NegateTwosCompNum); return new TimeSpan(-t._ticks); } public static TimeSpan operator -(TimeSpan t1, TimeSpan t2) { return t1.Subtract(t2); } public static TimeSpan operator +(TimeSpan t) { return t; } public static TimeSpan operator +(TimeSpan t1, TimeSpan t2) { return t1.Add(t2); } public static TimeSpan operator *(TimeSpan timeSpan, double factor) { if (double.IsNaN(factor)) { throw new ArgumentException(SR.Arg_CannotBeNaN, nameof(factor)); } // Rounding to the nearest tick is as close to the result we would have with unlimited // precision as possible, and so likely to have the least potential to surprise. double ticks = Math.Round(timeSpan.Ticks * factor); if (ticks > long.MaxValue | ticks < long.MinValue) { throw new OverflowException(SR.Overflow_TimeSpanTooLong); } return FromTicks((long)ticks); } public static TimeSpan operator *(double factor, TimeSpan timeSpan) => timeSpan * factor; public static TimeSpan operator /(TimeSpan timeSpan, double divisor) { if (double.IsNaN(divisor)) { throw new ArgumentException(SR.Arg_CannotBeNaN, nameof(divisor)); } double ticks = Math.Round(timeSpan.Ticks / divisor); if (ticks > long.MaxValue | ticks < long.MinValue || double.IsNaN(ticks)) { throw new OverflowException(SR.Overflow_TimeSpanTooLong); } return FromTicks((long)ticks); } // Using floating-point arithmetic directly means that infinities can be returned, which is reasonable // if we consider TimeSpan.FromHours(1) / TimeSpan.Zero asks how many zero-second intervals there are in // an hour for which infinity is the mathematic correct answer. Having TimeSpan.Zero / TimeSpan.Zero return NaN // is perhaps less useful, but no less useful than an exception. public static double operator /(TimeSpan t1, TimeSpan t2) => t1.Ticks / (double)t2.Ticks; public static bool operator ==(TimeSpan t1, TimeSpan t2) { return t1._ticks == t2._ticks; } public static bool operator !=(TimeSpan t1, TimeSpan t2) { return t1._ticks != t2._ticks; } public static bool operator <(TimeSpan t1, TimeSpan t2) { return t1._ticks < t2._ticks; } public static bool operator <=(TimeSpan t1, TimeSpan t2) { return t1._ticks <= t2._ticks; } public static bool operator >(TimeSpan t1, TimeSpan t2) { return t1._ticks > t2._ticks; } public static bool operator >=(TimeSpan t1, TimeSpan t2) { return t1._ticks >= t2._ticks; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System; using System.Collections; using System.Globalization; using System.Text; using System.IO; using System.Diagnostics; internal sealed partial class Parser { private SchemaType _schemaType; private readonly XmlNameTable _nameTable; private readonly SchemaNames _schemaNames; private readonly ValidationEventHandler _eventHandler; private XmlNamespaceManager _namespaceManager; private XmlReader _reader; private PositionInfo _positionInfo; private bool _isProcessNamespaces; private int _schemaXmlDepth = 0; private int _markupDepth; private SchemaBuilder _builder; private XmlSchema _schema; private SchemaInfo _xdrSchema; private XmlResolver _xmlResolver = null; //to be used only by XDRBuilder //xs:Annotation perf fix private readonly XmlDocument _dummyDocument; private bool _processMarkup; private XmlNode _parentNode; private XmlNamespaceManager _annotationNSManager; private string _xmlns; //Whitespace check for text nodes private XmlCharType _xmlCharType = XmlCharType.Instance; public Parser(SchemaType schemaType, XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler) { _schemaType = schemaType; _nameTable = nameTable; _schemaNames = schemaNames; _eventHandler = eventHandler; _xmlResolver = null; _processMarkup = true; _dummyDocument = new XmlDocument(); } public SchemaType Parse(XmlReader reader, string targetNamespace) { StartParsing(reader, targetNamespace); while (ParseReaderNode() && reader.Read()) { } return FinishParsing(); } public void StartParsing(XmlReader reader, string targetNamespace) { _reader = reader; _positionInfo = PositionInfo.GetPositionInfo(reader); _namespaceManager = reader.NamespaceManager; if (_namespaceManager == null) { _namespaceManager = new XmlNamespaceManager(_nameTable); _isProcessNamespaces = true; } else { _isProcessNamespaces = false; } while (reader.NodeType != XmlNodeType.Element && reader.Read()) { } _markupDepth = int.MaxValue; _schemaXmlDepth = reader.Depth; SchemaType rootType = _schemaNames.SchemaTypeFromRoot(reader.LocalName, reader.NamespaceURI); string code; if (!CheckSchemaRoot(rootType, out code)) { throw new XmlSchemaException(code, reader.BaseURI, _positionInfo.LineNumber, _positionInfo.LinePosition); } if (_schemaType == SchemaType.XSD) { _schema = new XmlSchema(); _schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute); _builder = new XsdBuilder(reader, _namespaceManager, _schema, _nameTable, _schemaNames, _eventHandler); } else { Debug.Assert(_schemaType == SchemaType.XDR); _xdrSchema = new SchemaInfo(); _xdrSchema.SchemaType = SchemaType.XDR; _builder = new XdrBuilder(reader, _namespaceManager, _xdrSchema, targetNamespace, _nameTable, _schemaNames, _eventHandler); ((XdrBuilder)_builder).XmlResolver = _xmlResolver; } } private bool CheckSchemaRoot(SchemaType rootType, out string code) { code = null; if (_schemaType == SchemaType.None) { _schemaType = rootType; } switch (rootType) { case SchemaType.XSD: if (_schemaType != SchemaType.XSD) { code = SR.Sch_MixSchemaTypes; return false; } break; case SchemaType.XDR: if (_schemaType == SchemaType.XSD) { code = SR.Sch_XSDSchemaOnly; return false; } else if (_schemaType != SchemaType.XDR) { code = SR.Sch_MixSchemaTypes; return false; } break; case SchemaType.DTD: //Did not detect schema type that can be parsed by this parser case SchemaType.None: code = SR.Sch_SchemaRootExpected; if (_schemaType == SchemaType.XSD) { code = SR.Sch_XSDSchemaRootExpected; } return false; default: Debug.Fail($"Unexpected root type {rootType}"); break; } return true; } public SchemaType FinishParsing() { return _schemaType; } public XmlSchema XmlSchema { get { return _schema; } } internal XmlResolver XmlResolver { set { _xmlResolver = value; } } public SchemaInfo XdrSchema { get { return _xdrSchema; } } public bool ParseReaderNode() { if (_reader.Depth > _markupDepth) { if (_processMarkup) { ProcessAppInfoDocMarkup(false); } return true; } else if (_reader.NodeType == XmlNodeType.Element) { if (_builder.ProcessElement(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI)) { _namespaceManager.PushScope(); if (_reader.MoveToFirstAttribute()) { do { _builder.ProcessAttribute(_reader.Prefix, _reader.LocalName, _reader.NamespaceURI, _reader.Value); if (Ref.Equal(_reader.NamespaceURI, _schemaNames.NsXmlNs) && _isProcessNamespaces) { _namespaceManager.AddNamespace(_reader.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value); } } while (_reader.MoveToNextAttribute()); _reader.MoveToElement(); // get back to the element } _builder.StartChildren(); if (_reader.IsEmptyElement) { _namespaceManager.PopScope(); _builder.EndChildren(); if (_reader.Depth == _schemaXmlDepth) { return false; // done } } else if (!_builder.IsContentParsed()) { //AppInfo and Documentation _markupDepth = _reader.Depth; _processMarkup = true; if (_annotationNSManager == null) { _annotationNSManager = new XmlNamespaceManager(_nameTable); _xmlns = _nameTable.Add("xmlns"); } ProcessAppInfoDocMarkup(true); } } else if (!_reader.IsEmptyElement) { //UnsupportedElement in that context _markupDepth = _reader.Depth; _processMarkup = false; //Hack to not process unsupported elements } } else if (_reader.NodeType == XmlNodeType.Text) { //Check for whitespace if (!_xmlCharType.IsOnlyWhitespace(_reader.Value)) { _builder.ProcessCData(_reader.Value); } } else if (_reader.NodeType == XmlNodeType.EntityReference || _reader.NodeType == XmlNodeType.SignificantWhitespace || _reader.NodeType == XmlNodeType.CDATA) { _builder.ProcessCData(_reader.Value); } else if (_reader.NodeType == XmlNodeType.EndElement) { if (_reader.Depth == _markupDepth) { if (_processMarkup) { Debug.Assert(_parentNode != null); XmlNodeList list = _parentNode.ChildNodes; XmlNode[] markup = new XmlNode[list.Count]; for (int i = 0; i < list.Count; i++) { markup[i] = list[i]; } _builder.ProcessMarkup(markup); _namespaceManager.PopScope(); _builder.EndChildren(); } _markupDepth = int.MaxValue; } else { _namespaceManager.PopScope(); _builder.EndChildren(); } if (_reader.Depth == _schemaXmlDepth) { return false; // done } } return true; } private void ProcessAppInfoDocMarkup(bool root) { //First time reader is positioned on AppInfo or Documentation element XmlNode currentNode = null; switch (_reader.NodeType) { case XmlNodeType.Element: _annotationNSManager.PushScope(); currentNode = LoadElementNode(root); // Dev10 (TFS) #479761: The following code was to address the issue of where an in-scope namespace delaration attribute // was not added when an element follows an empty element. This fix will result in persisting schema in a consistent form // although it does not change the semantic meaning of the schema. // Since it is as a breaking change and Dev10 needs to maintain the backward compatibility, this fix is being reverted. // if (reader.IsEmptyElement) { // annotationNSManager.PopScope(); // } break; case XmlNodeType.Text: currentNode = _dummyDocument.CreateTextNode(_reader.Value); goto default; case XmlNodeType.SignificantWhitespace: currentNode = _dummyDocument.CreateSignificantWhitespace(_reader.Value); goto default; case XmlNodeType.CDATA: currentNode = _dummyDocument.CreateCDataSection(_reader.Value); goto default; case XmlNodeType.EntityReference: currentNode = _dummyDocument.CreateEntityReference(_reader.Name); goto default; case XmlNodeType.Comment: currentNode = _dummyDocument.CreateComment(_reader.Value); goto default; case XmlNodeType.ProcessingInstruction: currentNode = _dummyDocument.CreateProcessingInstruction(_reader.Name, _reader.Value); goto default; case XmlNodeType.EndEntity: break; case XmlNodeType.Whitespace: break; case XmlNodeType.EndElement: _annotationNSManager.PopScope(); _parentNode = _parentNode.ParentNode; break; default: //other possible node types: Document/DocType/DocumentFrag/Entity/Notation/Xmldecl cannot appear as children of xs:appInfo or xs:doc Debug.Assert(currentNode != null); Debug.Assert(_parentNode != null); _parentNode.AppendChild(currentNode); break; } } private XmlElement LoadElementNode(bool root) { Debug.Assert(_reader.NodeType == XmlNodeType.Element); XmlReader r = _reader; bool fEmptyElement = r.IsEmptyElement; XmlElement element = _dummyDocument.CreateElement(r.Prefix, r.LocalName, r.NamespaceURI); element.IsEmpty = fEmptyElement; if (root) { _parentNode = element; } else { XmlAttributeCollection attributes = element.Attributes; if (r.MoveToFirstAttribute()) { do { if (Ref.Equal(r.NamespaceURI, _schemaNames.NsXmlNs)) { //Namespace Attribute _annotationNSManager.AddNamespace(r.Prefix.Length == 0 ? string.Empty : _reader.LocalName, _reader.Value); } XmlAttribute attr = LoadAttributeNode(); attributes.Append(attr); } while (r.MoveToNextAttribute()); } r.MoveToElement(); string ns = _annotationNSManager.LookupNamespace(r.Prefix); if (ns == null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix)); attributes.Append(attr); } else if (ns.Length == 0) { //string.Empty prefix is mapped to string.Empty NS by default string elemNS = _namespaceManager.LookupNamespace(r.Prefix); if (elemNS != string.Empty) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, elemNS); attributes.Append(attr); } } while (r.MoveToNextAttribute()) { if (r.Prefix.Length != 0) { string attNS = _annotationNSManager.LookupNamespace(r.Prefix); if (attNS == null) { XmlAttribute attr = CreateXmlNsAttribute(r.Prefix, _namespaceManager.LookupNamespace(r.Prefix)); attributes.Append(attr); } } } r.MoveToElement(); _parentNode.AppendChild(element); if (!r.IsEmptyElement) { _parentNode = element; } } return element; } private XmlAttribute CreateXmlNsAttribute(string prefix, string value) { XmlAttribute attr; if (prefix.Length == 0) { attr = _dummyDocument.CreateAttribute(string.Empty, _xmlns, XmlReservedNs.NsXmlNs); } else { attr = _dummyDocument.CreateAttribute(_xmlns, prefix, XmlReservedNs.NsXmlNs); } attr.AppendChild(_dummyDocument.CreateTextNode(value)); _annotationNSManager.AddNamespace(prefix, value); return attr; } private XmlAttribute LoadAttributeNode() { Debug.Assert(_reader.NodeType == XmlNodeType.Attribute); XmlReader r = _reader; XmlAttribute attr = _dummyDocument.CreateAttribute(r.Prefix, r.LocalName, r.NamespaceURI); while (r.ReadAttributeValue()) { switch (r.NodeType) { case XmlNodeType.Text: attr.AppendChild(_dummyDocument.CreateTextNode(r.Value)); continue; case XmlNodeType.EntityReference: attr.AppendChild(LoadEntityReferenceInAttribute()); continue; default: throw XmlLoader.UnexpectedNodeType(r.NodeType); } } return attr; } private XmlEntityReference LoadEntityReferenceInAttribute() { Debug.Assert(_reader.NodeType == XmlNodeType.EntityReference); XmlEntityReference eref = _dummyDocument.CreateEntityReference(_reader.LocalName); if (!_reader.CanResolveEntity) { return eref; } _reader.ResolveEntity(); while (_reader.ReadAttributeValue()) { switch (_reader.NodeType) { case XmlNodeType.Text: eref.AppendChild(_dummyDocument.CreateTextNode(_reader.Value)); continue; case XmlNodeType.EndEntity: if (eref.ChildNodes.Count == 0) { eref.AppendChild(_dummyDocument.CreateTextNode(string.Empty)); } return eref; case XmlNodeType.EntityReference: eref.AppendChild(LoadEntityReferenceInAttribute()); break; default: throw XmlLoader.UnexpectedNodeType(_reader.NodeType); } } return eref; } }; } // namespace System.Xml
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Microsoft.VisualStudio.Services.Agent.Util; using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; namespace Agent.Sdk { public class ContainerInfo : ExecutionTargetInfo { private IDictionary<string, string> _userMountVolumes; private List<MountVolume> _mountVolumes; private IDictionary<string, string> _userPortMappings; private List<PortMapping> _portMappings; private List<string> _readOnlyVolumes; private Dictionary<string, string> _environmentVariables; private Dictionary<string, string> _pathMappings; private PlatformUtil.OS _imageOS; public PlatformUtil.OS ExecutionOS => _imageOS; public ContainerInfo() { this.IsJobContainer = true; if (PlatformUtil.RunningOnWindows) { _pathMappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } else { _pathMappings = new Dictionary<string, string>(); } } public ContainerInfo(Pipelines.ContainerResource container, Boolean isJobContainer = true) { ArgUtil.NotNull(container, nameof(container)); this.ContainerName = container.Alias; string containerImage = container.Properties.Get<string>("image"); ArgUtil.NotNullOrEmpty(containerImage, nameof(containerImage)); this.ContainerImage = containerImage; this.ContainerDisplayName = $"{container.Alias}_{Pipelines.Validation.NameValidation.Sanitize(containerImage)}_{Guid.NewGuid().ToString("N").Substring(0, 6)}"; this.ContainerRegistryEndpoint = container.Endpoint?.Id ?? Guid.Empty; this.ContainerCreateOptions = container.Properties.Get<string>("options"); this.SkipContainerImagePull = container.Properties.Get<bool>("localimage"); _environmentVariables = container.Environment != null ? new Dictionary<string, string>(container.Environment) : new Dictionary<string, string>(); this.ContainerCommand = container.Properties.Get<string>("command", defaultValue: ""); this.IsJobContainer = isJobContainer; // Windows has never automatically enabled Docker.Sock, but Linux does. So we need to set the default here based on OS. this.MapDockerSocket = container.Properties.Get<bool>("mapDockerSocket", !PlatformUtil.RunningOnWindows); this._imageOS = PlatformUtil.HostOS; _pathMappings = new Dictionary<string, string>( PlatformUtil.RunningOnWindows ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal); this._readOnlyVolumes = container.ReadOnlyMounts != null ? new List<string>(container.ReadOnlyMounts) : new List<string>(); if (container.Ports?.Count > 0) { foreach (var port in container.Ports) { UserPortMappings[port] = port; } } if (container.Volumes?.Count > 0) { foreach (var volume in container.Volumes) { UserMountVolumes[volume] = volume; } } } public string ContainerId { get; set; } public string ContainerDisplayName { get; private set; } public string ContainerNetwork { get; set; } public string ContainerNetworkAlias { get; set; } public string ContainerImage { get; set; } public string ContainerName { get; set; } public string ContainerCommand { get; set; } public string CustomNodePath { get; set; } public Guid ContainerRegistryEndpoint { get; private set; } public string ContainerCreateOptions { get; set; } public bool SkipContainerImagePull { get; private set; } public string CurrentUserName { get; set; } public string CurrentUserId { get; set; } public bool IsJobContainer { get; set; } public bool MapDockerSocket { get; set; } public PlatformUtil.OS ImageOS { get { return _imageOS; } set { var previousImageOS = _imageOS; _imageOS = value; if (_pathMappings != null) { var newMappings = new Dictionary<string, string>( _pathMappings.Comparer); foreach (var mapping in _pathMappings) { newMappings[mapping.Key] = TranslateContainerPathForImageOS(previousImageOS, mapping.Value); } _pathMappings = newMappings; } if (_environmentVariables != null) { var newEnvVars = new Dictionary<string, string>(_environmentVariables.Comparer); foreach (var env in _environmentVariables) { newEnvVars[env.Key] = TranslateContainerPathForImageOS(previousImageOS, env.Value); } _environmentVariables = newEnvVars; } } } public Dictionary<string, string> ContainerEnvironmentVariables { get { if (_environmentVariables == null) { _environmentVariables = new Dictionary<string, string>(); } return _environmentVariables; } } public IDictionary<string, string> UserMountVolumes { get { if (_userMountVolumes == null) { _userMountVolumes = new Dictionary<string, string>(); } return _userMountVolumes; } } public List<MountVolume> MountVolumes { get { if (_mountVolumes == null) { _mountVolumes = new List<MountVolume>(); } return _mountVolumes; } } public IDictionary<string, string> UserPortMappings { get { if (_userPortMappings == null) { _userPortMappings = new Dictionary<string, string>(); } return _userPortMappings; } } public List<PortMapping> PortMappings { get { if (_portMappings == null) { _portMappings = new List<PortMapping>(); } return _portMappings; } } public bool isReadOnlyVolume(string volumeName) { return _readOnlyVolumes.Contains(volumeName); } public Dictionary<string, string> PathMappings { get { if (_pathMappings == null) { _pathMappings = new Dictionary<string, string>(); } return _pathMappings; } } public string TranslateToContainerPath(string path) { if (!string.IsNullOrEmpty(path)) { var comparison = PlatformUtil.RunningOnWindows ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; foreach (var mapping in _pathMappings) { if (string.Equals(path, mapping.Key, comparison)) { return mapping.Value; } if (path.StartsWith(mapping.Key + Path.DirectorySeparatorChar, comparison) || path.StartsWith(mapping.Key + Path.AltDirectorySeparatorChar, comparison)) { return mapping.Value + path.Remove(0, mapping.Key.Length); } } } return path; } public string TranslateToHostPath(string path) { if (!string.IsNullOrEmpty(path)) { var comparison = PlatformUtil.RunningOnWindows ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; foreach (var mapping in _pathMappings) { string retval = null; if (string.Equals(path, mapping.Value, comparison)) { retval = mapping.Key; } else if (path.StartsWith(mapping.Value + Path.DirectorySeparatorChar, comparison) || path.StartsWith(mapping.Value + Path.AltDirectorySeparatorChar, comparison)) { retval = mapping.Key + path.Remove(0, mapping.Value.Length); } if (retval != null) { if (PlatformUtil.RunningOnWindows) { retval = retval.Replace("/", "\\"); } else { retval = retval.Replace("\\","/"); } return retval; } } } return path; } private static Regex translateWindowsDriveRegex = new Regex(@"^([a-zA-Z]):(\\|/)", RegexOptions.Compiled); public string TranslateContainerPathForImageOS(PlatformUtil.OS runningOs, string path) { if (!string.IsNullOrEmpty(path)) { if (runningOs == PlatformUtil.OS.Windows && ImageOS == PlatformUtil.OS.Linux) { return translateWindowsDriveRegex.Replace(path,"/").Replace("\\", "/"); } } return path; } public void AddPortMappings(List<PortMapping> portMappings) { ArgUtil.NotNull(portMappings, nameof(portMappings)); foreach (var port in portMappings) { PortMappings.Add(port); } } public void AddPathMappings(Dictionary<string, string> pathMappings) { ArgUtil.NotNull(pathMappings, nameof(pathMappings)); foreach (var path in pathMappings) { PathMappings.Add(path.Key, path.Value); } } } }
// Copyright Bastian Eicher // Licensed under the MIT License #if !NET20 && !NET40 using System.Threading.Tasks; #endif namespace NanoByte.Common.Collections { /// <summary> /// Provides extension methods for <see cref="IEnumerable{T}"/>s. /// </summary> public static class EnumerableExtensions { /// <summary> /// Determines whether the enumeration contains an element or is null. /// </summary> /// <param name="enumeration">The list to check.</param> /// <param name="element">The element to look for.</param> /// <remarks>Useful for lists that contain an OR-ed list of restrictions, where an empty list means no restrictions.</remarks> [Pure] public static bool ContainsOrEmpty<T>([InstantHandle] this IEnumerable<T> enumeration, T element) { #region Sanity checks if (enumeration == null) throw new ArgumentNullException(nameof(enumeration)); if (element == null) throw new ArgumentNullException(nameof(element)); #endregion // ReSharper disable PossibleMultipleEnumeration return enumeration.Contains(element) || !enumeration.Any(); // ReSharper restore PossibleMultipleEnumeration } /// <summary> /// Determines whether one enumeration of elements contains any of the elements in another. /// </summary> /// <param name="first">The first of the two enumerations to compare.</param> /// <param name="second">The first of the two enumerations to compare.</param> /// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param> /// <returns><c>true</c> if <paramref name="first"/> contains any element from <paramref name="second"/>. <c>false</c> if <paramref name="first"/> or <paramref name="second"/> is empty.</returns> [Pure] public static bool ContainsAny<T>([InstantHandle] this IEnumerable<T> first, [InstantHandle] IEnumerable<T> second, IEqualityComparer<T>? comparer = null) { #region Sanity checks if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); #endregion var set = #if !NET20 second as ISet<T> ?? #endif new HashSet<T>(first, comparer ?? EqualityComparer<T>.Default); return second.Any(set.Contains); } /// <summary> /// Determines whether two enumerations contain the same elements in the same order. /// </summary> /// <param name="first">The first of the two enumerations to compare.</param> /// <param name="second">The first of the two enumerations to compare.</param> /// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param> [Pure] public static bool SequencedEquals<T>([InstantHandle] this IEnumerable<T> first, [InstantHandle] IEnumerable<T> second, IEqualityComparer<T>? comparer = null) { #region Sanity checks if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); #endregion if (ReferenceEquals(first, second)) return true; if (first is ICollection<T> a && second is ICollection<T> b && a.Count != b.Count) return false; return first.SequenceEqual(second, comparer ?? EqualityComparer<T>.Default); } /// <summary> /// Determines whether two enumerations contain the same elements disregarding the order they are in. /// </summary> /// <param name="first">The first of the two enumerations to compare.</param> /// <param name="second">The first of the two enumerations to compare.</param> /// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param> [Pure] public static bool UnsequencedEquals<T>([InstantHandle] this IEnumerable<T> first, [InstantHandle] IEnumerable<T> second, IEqualityComparer<T>? comparer = null) { #region Sanity checks if (first == null) throw new ArgumentNullException(nameof(first)); if (second == null) throw new ArgumentNullException(nameof(second)); #endregion if (ReferenceEquals(first, second)) return true; if (first is ICollection<T> a && second is ICollection<T> b && a.Count != b.Count) return false; var set = new HashSet<T>(first, comparer ?? EqualityComparer<T>.Default); return second.All(set.Contains); } /// <summary> /// Generates a hash code for the contents of the enumeration. Changing the elements' order will change the hash. /// </summary> /// <param name="enumeration">The enumeration to generate the hash for.</param> /// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param> /// <seealso cref="SequencedEquals{T}"/> [Pure] public static int GetSequencedHashCode<T>([InstantHandle] this IEnumerable<T> enumeration, IEqualityComparer<T>? comparer = null) { #region Sanity checks if (enumeration == null) throw new ArgumentNullException(nameof(enumeration)); #endregion var hash = new HashCode(); foreach (T item in enumeration) hash.Add(item, comparer); return hash.ToHashCode(); } /// <summary> /// Generates a hash code for the contents of the enumeration. Changing the elements' order will not change the hash. /// </summary> /// <param name="enumeration">The enumeration to generate the hash for.</param> /// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param> /// <seealso cref="UnsequencedEquals{T}"/> [Pure] public static int GetUnsequencedHashCode<T>([InstantHandle] this IEnumerable<T> enumeration, IEqualityComparer<T>? comparer = null) { #region Sanity checks if (enumeration == null) throw new ArgumentNullException(nameof(enumeration)); #endregion comparer ??= EqualityComparer<T>.Default; int result = 397; // ReSharper disable once LoopCanBeConvertedToQuery foreach (T item in enumeration) { if (item != null) result ^= comparer.GetHashCode(item); } return result; } /// <summary> /// Filters a sequence of elements to remove any that match the <paramref name="predicate"/>. /// The opposite of <see cref="Enumerable.Where{TSource}(IEnumerable{TSource},Func{TSource,bool})"/>. /// </summary> [LinqTunnel] public static IEnumerable<T> Except<T>(this IEnumerable<T> enumeration, Func<T, bool> predicate) => enumeration.Where(x => !predicate(x)); /// <summary> /// Filters a sequence of elements to remove any that are equal to <paramref name="element"/>. /// </summary> [LinqTunnel] public static IEnumerable<T> Except<T>(this IEnumerable<T> enumeration, T element) => enumeration.Except(new[] {element}); /// <summary> /// Flattens a list of lists. /// </summary> [LinqTunnel] [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public static IEnumerable<T> Flatten<T>(this IEnumerable<IEnumerable<T>> enumeration) => enumeration.SelectMany(x => x); /// <summary> /// Filters a sequence of elements to remove any <c>null</c> values. /// </summary> [LinqTunnel] public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T?> enumeration) where T : class { foreach (var element in enumeration) { if (element != null) yield return element; } } /// <summary> /// Determines the element in a list that maximizes a specified expression. /// </summary> /// <typeparam name="T">The type of the elements.</typeparam> /// <typeparam name="TValue">The type of the <paramref name="expression"/>.</typeparam> /// <param name="enumeration">The elements to check.</param> /// <param name="expression">The expression to maximize.</param> /// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param> /// <returns>The element that maximizes the expression.</returns> /// <exception cref="InvalidOperationException"><paramref name="enumeration"/> contains no elements.</exception> [Pure] public static T MaxBy<T, TValue>([InstantHandle] this IEnumerable<T> enumeration, [InstantHandle] Func<T, TValue> expression, IComparer<TValue>? comparer = null) { #region Sanity checks if (enumeration == null) throw new ArgumentNullException(nameof(enumeration)); if (expression == null) throw new ArgumentNullException(nameof(expression)); #endregion comparer ??= Comparer<TValue>.Default; using var enumerator = enumeration.GetEnumerator(); if (!enumerator.MoveNext()) throw new InvalidOperationException("Enumeration contains no elements"); var maxElement = enumerator.Current; var maxValue = expression(maxElement); while (enumerator.MoveNext()) { var candidate = enumerator.Current; var candidateValue = expression(candidate); if (comparer.Compare(candidateValue, maxValue) > 0) { maxElement = candidate; maxValue = candidateValue; } } return maxElement; } /// <summary> /// Determines the element in a list that minimizes a specified expression. /// </summary> /// <typeparam name="T">The type of the elements.</typeparam> /// <typeparam name="TValue">The type of the <paramref name="expression"/>.</typeparam> /// <param name="enumeration">The elements to check.</param> /// <param name="expression">The expression to minimize.</param> /// <param name="comparer">Controls how to compare elements; leave <c>null</c> for default comparer.</param> /// <returns>The element that minimizes the expression.</returns> /// <exception cref="InvalidOperationException"><paramref name="enumeration"/> contains no elements.</exception> [Pure] public static T MinBy<T, TValue>([InstantHandle] this IEnumerable<T> enumeration, [InstantHandle] Func<T, TValue> expression, IComparer<TValue>? comparer = null) { #region Sanity checks if (enumeration == null) throw new ArgumentNullException(nameof(enumeration)); if (expression == null) throw new ArgumentNullException(nameof(expression)); #endregion comparer ??= Comparer<TValue>.Default; using var enumerator = enumeration.GetEnumerator(); if (!enumerator.MoveNext()) throw new InvalidOperationException("Enumeration contains no elements"); var minElement = enumerator.Current; var minValue = expression(minElement); while (enumerator.MoveNext()) { var candidate = enumerator.Current; var candidateValue = expression(candidate); if (comparer.Compare(candidateValue, minValue) < 0) { minElement = candidate; minValue = candidateValue; } } return minElement; } /// <summary> /// Filters a sequence of elements to remove any duplicates based on the equality of a key extracted from the elements. /// </summary> /// <param name="enumeration">The sequence of elements to filter.</param> /// <param name="keySelector">A function mapping elements to their respective equality keys.</param> [LinqTunnel] public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> enumeration, Func<T, TKey> keySelector) where T : notnull where TKey : notnull => enumeration.Distinct(new KeyEqualityComparer<T, TKey>(keySelector)); /// <summary> /// Maps elements using a selector. Calls a handler for specific exceptions, skips the element and continues enumerating with the element. /// </summary> /// <typeparam name="TSource">The type of the input elements.</typeparam> /// <typeparam name="TResult">The type of the output elements.</typeparam> /// <typeparam name="TException">The type of exceptions to handle..</typeparam> /// <param name="source">The elements to map.</param> /// <param name="selector">The selector to execute for each <paramref name="source"/> element.</param> /// <param name="exceptionHandler">A Callback to be invoked when a <typeparamref name="TException"/> is caught.</param> [LinqTunnel] public static IEnumerable<TResult> TrySelect<TSource, TResult, TException>(this IEnumerable<TSource> source, Func<TSource, TResult> selector, [InstantHandle] Action<TException> exceptionHandler) where TException : Exception { #region Sanity checks if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); #endregion foreach (var element in source) { TResult result; try { result = selector(element); } catch (TException ex) { exceptionHandler(ex); continue; } yield return result; } } /// <summary> /// Calls <see cref="ICloneable{T}.Clone"/> for every element in a enumeration and returns the results as a new enumeration. /// </summary> [LinqTunnel] public static IEnumerable<T> CloneElements<T>(this IEnumerable<T> enumerable) where T : ICloneable<T> => (enumerable ?? throw new ArgumentNullException(nameof(enumerable))).Select(x => x.Clone()); /// <summary> /// Performs a topological sort of an object graph. /// </summary> /// <param name="nodes">The set of nodes to sort.</param> /// <param name="getDependencies">A function that retrieves all dependencies of a node.</param> /// <exception cref="InvalidDataException">Cyclic dependency found.</exception> [Pure] public static IEnumerable<T> TopologicalSort<T>([InstantHandle] this IEnumerable<T> nodes, [InstantHandle] Func<T, IEnumerable<T>> getDependencies) { #region Sanity checks if (nodes == null) throw new ArgumentNullException(nameof(nodes)); if (getDependencies == null) throw new ArgumentNullException(nameof(getDependencies)); #endregion var sorted = new List<T>(); var visited = new HashSet<T>(); foreach (var item in nodes) TopologicalSortVisit(item, visited, sorted, getDependencies); return sorted; } private static void TopologicalSortVisit<T>(T node, HashSet<T> visited, List<T> sorted, Func<T, IEnumerable<T>> getDependencies) { if (visited.Contains(node)) { if (!sorted.Contains(node)) throw new InvalidDataException($"Cyclic dependency found at: {node}"); } else { visited.Add(node); foreach (var dep in getDependencies(node)) TopologicalSortVisit(dep, visited, sorted, getDependencies); sorted.Add(node); } } #if !NET20 && !NET40 /// <summary> /// Runs asynchronous operations for each element in an enumeration. Runs multiple tasks using cooperative multitasking. /// </summary> /// <param name="enumerable">The input elements to enumerate over.</param> /// <param name="taskFactory">Creates a <see cref="Task"/> for each input element.</param> /// <param name="maxParallel">The maximum number of <see cref="Task"/>s to run in parallel. Use 0 or lower for unbounded.</param> /// <exception cref="InvalidOperationException"><see cref="TaskScheduler.Current"/> is equal to <see cref="TaskScheduler.Default"/>.</exception> /// <remarks> /// <see cref="SynchronizationContext.Current"/> must not be null. /// The synchronization context is required to ensure that task continuations are scheduled sequentially and do not run in parallel. /// </remarks> public static async Task ForEachAsync<T>(this IEnumerable<T> enumerable, Func<T, Task> taskFactory, int maxParallel = 0) { if (TaskScheduler.Current == TaskScheduler.Default) throw new InvalidOperationException("TaskScheduler.Current must not be equal to TaskScheduler.Default value when using ForEachAsync()."); var tasks = new List<Task>(maxParallel); foreach (var task in enumerable.Select(taskFactory)) { tasks.Add(task); if (tasks.Count == maxParallel) { var completedTask = await Task.WhenAny(tasks.ToArray()).ConfigureAwait(true); await completedTask.ConfigureAwait(true); // observe exceptions tasks.Remove(completedTask); } } await Task.WhenAll(tasks.ToArray()).ConfigureAwait(false); } #endif /// <summary> /// Generates all possible permutations of a set of <paramref name="elements"/>. /// </summary> [LinqTunnel] public static IEnumerable<T[]> Permutate<T>(this IEnumerable<T> elements) { #region Sanity checks if (elements == null) throw new ArgumentNullException(nameof(elements)); #endregion static IEnumerable<T[]> Helper(T[] array, int index) { if (index >= array.Length - 1) yield return array; else { for (int i = index; i < array.Length; i++) { var subArray = array.ToArray(); var t1 = subArray[index]; subArray[index] = subArray[i]; subArray[i] = t1; foreach (var element in Helper(subArray, index + 1)) yield return element; } } } return Helper(elements.ToArray(), index: 0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Abp.Domain.Entities; using Abp.MultiTenancy; using Abp.Reflection.Extensions; namespace Abp.Domain.Repositories { /// <summary> /// Base class to implement <see cref="IRepository{TEntity,TPrimaryKey}"/>. /// It implements some methods in most simple way. /// </summary> /// <typeparam name="TEntity">Type of the Entity for this repository</typeparam> /// <typeparam name="TPrimaryKey">Primary key of the entity</typeparam> public abstract class AbpRepositoryBase<TEntity, TPrimaryKey> : IRepository<TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey> { /// <summary> /// The multi tenancy side /// </summary> public static MultiTenancySides? MultiTenancySide { get; private set; } static AbpRepositoryBase() { var attr = typeof (TEntity).GetSingleAttributeOfTypeOrBaseTypesOrNull<MultiTenancySideAttribute>(); if (attr != null) { MultiTenancySide = attr.Side; } } public abstract IQueryable<TEntity> GetAll(); public virtual List<TEntity> GetAllList() { return GetAll().ToList(); } public virtual Task<List<TEntity>> GetAllListAsync() { return Task.FromResult(GetAllList()); } public virtual List<TEntity> GetAllList(Expression<Func<TEntity, bool>> predicate) { return GetAll().Where(predicate).ToList(); } public virtual Task<List<TEntity>> GetAllListAsync(Expression<Func<TEntity, bool>> predicate) { return Task.FromResult(GetAllList(predicate)); } public virtual T Query<T>(Func<IQueryable<TEntity>, T> queryMethod) { return queryMethod(GetAll()); } public virtual TEntity Get(TPrimaryKey id) { var entity = FirstOrDefault(id); if (entity == null) { throw new AbpException("There is no such an entity with given primary key. Entity type: " + typeof(TEntity).FullName + ", primary key: " + id); } return entity; } public virtual async Task<TEntity> GetAsync(TPrimaryKey id) { var entity = await FirstOrDefaultAsync(id); if (entity == null) { throw new AbpException("There is no such an entity with given primary key. Entity type: " + typeof(TEntity).FullName + ", primary key: " + id); } return entity; } public virtual TEntity Single(Expression<Func<TEntity, bool>> predicate) { return GetAll().Single(predicate); } public virtual Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> predicate) { return Task.FromResult(Single(predicate)); } public virtual TEntity FirstOrDefault(TPrimaryKey id) { return GetAll().FirstOrDefault(CreateEqualityExpressionForId(id)); } public virtual Task<TEntity> FirstOrDefaultAsync(TPrimaryKey id) { return Task.FromResult(FirstOrDefault(id)); } public virtual TEntity FirstOrDefault(Expression<Func<TEntity, bool>> predicate) { return GetAll().FirstOrDefault(predicate); } public virtual Task<TEntity> FirstOrDefaultAsync(Expression<Func<TEntity, bool>> predicate) { return Task.FromResult(FirstOrDefault(predicate)); } public virtual TEntity Load(TPrimaryKey id) { return Get(id); } public abstract TEntity Insert(TEntity entity); public virtual Task<TEntity> InsertAsync(TEntity entity) { return Task.FromResult(Insert(entity)); } public virtual TPrimaryKey InsertAndGetId(TEntity entity) { return Insert(entity).Id; } public virtual Task<TPrimaryKey> InsertAndGetIdAsync(TEntity entity) { return Task.FromResult(InsertAndGetId(entity)); } public virtual TEntity InsertOrUpdate(TEntity entity) { return entity.IsTransient() ? Insert(entity) : Update(entity); } public virtual async Task<TEntity> InsertOrUpdateAsync(TEntity entity) { return entity.IsTransient() ? await InsertAsync(entity) : await UpdateAsync(entity); } public virtual TPrimaryKey InsertOrUpdateAndGetId(TEntity entity) { return InsertOrUpdate(entity).Id; } public virtual Task<TPrimaryKey> InsertOrUpdateAndGetIdAsync(TEntity entity) { return Task.FromResult(InsertOrUpdateAndGetId(entity)); } public abstract TEntity Update(TEntity entity); public virtual Task<TEntity> UpdateAsync(TEntity entity) { return Task.FromResult(Update(entity)); } public virtual TEntity Update(TPrimaryKey id, Action<TEntity> updateAction) { var entity = Get(id); updateAction(entity); return entity; } public virtual async Task<TEntity> UpdateAsync(TPrimaryKey id, Func<TEntity, Task> updateAction) { var entity = await GetAsync(id); await updateAction(entity); return entity; } public abstract void Delete(TEntity entity); public virtual Task DeleteAsync(TEntity entity) { Delete(entity); return Task.FromResult(0); } public abstract void Delete(TPrimaryKey id); public virtual Task DeleteAsync(TPrimaryKey id) { Delete(id); return Task.FromResult(0); } public virtual void Delete(Expression<Func<TEntity, bool>> predicate) { foreach (var entity in GetAll().Where(predicate).ToList()) { Delete(entity); } } public virtual async Task DeleteAsync(Expression<Func<TEntity, bool>> predicate) { Delete(predicate); } public virtual int Count() { return GetAll().Count(); } public virtual Task<int> CountAsync() { return Task.FromResult(Count()); } public virtual int Count(Expression<Func<TEntity, bool>> predicate) { return GetAll().Where(predicate).Count(); } public virtual Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate) { return Task.FromResult(Count(predicate)); } public virtual long LongCount() { return GetAll().LongCount(); } public virtual Task<long> LongCountAsync() { return Task.FromResult(LongCount()); } public virtual long LongCount(Expression<Func<TEntity, bool>> predicate) { return GetAll().Where(predicate).LongCount(); } public virtual Task<long> LongCountAsync(Expression<Func<TEntity, bool>> predicate) { return Task.FromResult(LongCount(predicate)); } protected static Expression<Func<TEntity, bool>> CreateEqualityExpressionForId(TPrimaryKey id) { var lambdaParam = Expression.Parameter(typeof(TEntity)); var lambdaBody = Expression.Equal( Expression.PropertyOrField(lambdaParam, "Id"), Expression.Constant(id, typeof(TPrimaryKey)) ); return Expression.Lambda<Func<TEntity, bool>>(lambdaBody, lambdaParam); } } }
// Transport Security Layer (TLS) // Copyright (c) 2003-2004 Carlos Guzman Alvarez // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.IO; using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading; using Mono.Security.Protocol.Tls.Handshake; namespace Mono.Security.Protocol.Tls { #region Delegates public delegate bool CertificateValidationCallback( X509Certificate certificate, int[] certificateErrors); public delegate X509Certificate CertificateSelectionCallback( X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates); public delegate AsymmetricAlgorithm PrivateKeySelectionCallback( X509Certificate certificate, string targetHost); delegate int ReadDelegate (byte [] buffer, int offset, int count); #endregion public class SslClientStream : Stream, IDisposable { #region Internal Events internal event CertificateValidationCallback ServerCertValidation; internal event CertificateSelectionCallback ClientCertSelection; internal event PrivateKeySelectionCallback PrivateKeySelection; #endregion #region Fields private Stream innerStream; private MemoryStream inputBuffer; private ClientContext context; private ClientRecordProtocol protocol; private bool ownsStream; private bool disposed; private bool checkCertRevocationStatus; private object negotiate; private object read; private object write; private ReadDelegate rd; #endregion #region Properties public override bool CanRead { get { return this.innerStream.CanRead; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return this.innerStream.CanWrite; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } // required by HttpsClientStream for proxy support internal Stream InputBuffer { get { return inputBuffer; } } #endregion #region Security Properties public bool CheckCertRevocationStatus { get { return this.checkCertRevocationStatus ; } set { this.checkCertRevocationStatus = value; } } public CipherAlgorithmType CipherAlgorithm { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.CipherAlgorithmType; } return CipherAlgorithmType.None; } } public int CipherStrength { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.EffectiveKeyBits; } return 0; } } public X509CertificateCollection ClientCertificates { get { return this.context.ClientSettings.Certificates;} } public HashAlgorithmType HashAlgorithm { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.HashAlgorithmType; } return HashAlgorithmType.None; } } public int HashStrength { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.HashSize * 8; } return 0; } } public int KeyExchangeStrength { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.ServerSettings.Certificates[0].RSA.KeySize; } return 0; } } public ExchangeAlgorithmType KeyExchangeAlgorithm { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.Cipher.ExchangeAlgorithmType; } return ExchangeAlgorithmType.None; } } public SecurityProtocolType SecurityProtocol { get { if (this.context.HandshakeState == HandshakeState.Finished) { return this.context.SecurityProtocol; } return 0; } } public X509Certificate SelectedClientCertificate { get { return this.context.ClientSettings.ClientCertificate; } } public X509Certificate ServerCertificate { get { if (this.context.HandshakeState == HandshakeState.Finished) { if (this.context.ServerSettings.Certificates != null && this.context.ServerSettings.Certificates.Count > 0) { return new X509Certificate(this.context.ServerSettings.Certificates[0].RawData); } } return null; } } // this is used by Mono's certmgr tool to download certificates internal Mono.Security.X509.X509CertificateCollection ServerCertificates { get { return context.ServerSettings.Certificates; } } #endregion #region Callback Properties public CertificateValidationCallback ServerCertValidationDelegate { get { return this.ServerCertValidation; } set { this.ServerCertValidation = value; } } public CertificateSelectionCallback ClientCertSelectionDelegate { get { return this.ClientCertSelection; } set { this.ClientCertSelection = value; } } public PrivateKeySelectionCallback PrivateKeyCertSelectionDelegate { get { return this.PrivateKeySelection; } set { this.PrivateKeySelection = value; } } #endregion #region Constructors public SslClientStream( Stream stream, string targetHost, bool ownsStream) : this( stream, targetHost, ownsStream, SecurityProtocolType.Default, null) { } public SslClientStream( Stream stream, string targetHost, X509Certificate clientCertificate) : this( stream, targetHost, false, SecurityProtocolType.Default, new X509CertificateCollection(new X509Certificate[]{clientCertificate})) { } public SslClientStream( Stream stream, string targetHost, X509CertificateCollection clientCertificates) : this( stream, targetHost, false, SecurityProtocolType.Default, clientCertificates) { } public SslClientStream( Stream stream, string targetHost, bool ownsStream, SecurityProtocolType securityProtocolType) : this( stream, targetHost, ownsStream, securityProtocolType, new X509CertificateCollection()) { } public SslClientStream( Stream stream, string targetHost, bool ownsStream, SecurityProtocolType securityProtocolType, X509CertificateCollection clientCertificates) { if (stream == null) { throw new ArgumentNullException("stream is null."); } if (!stream.CanRead || !stream.CanWrite) { throw new ArgumentNullException("stream is not both readable and writable."); } if (targetHost == null || targetHost.Length == 0) { throw new ArgumentNullException("targetHost is null or an empty string."); } this.context = new ClientContext( this, securityProtocolType, targetHost, clientCertificates); this.inputBuffer = new MemoryStream(); this.innerStream = stream; this.ownsStream = ownsStream; this.negotiate = new object (); this.read = new object (); this.write = new object (); this.protocol = new ClientRecordProtocol(innerStream, context); } #endregion #region Finalizer ~SslClientStream() { this.Dispose(false); } #endregion #region IDisposable Methods void IDisposable.Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (this.innerStream != null) { if (this.context.HandshakeState == HandshakeState.Finished && !this.context.ConnectionEnd) { // Write close notify this.protocol.SendAlert(AlertDescription.CloseNotify); } if (this.ownsStream) { // Close inner stream this.innerStream.Close(); } } this.ownsStream = false; this.innerStream = null; this.ClientCertSelection = null; this.ServerCertValidation = null; this.PrivateKeySelection = null; } this.disposed = true; } } #endregion #region Methods public override IAsyncResult BeginRead( byte[] buffer, int offset, int count, AsyncCallback callback, object state) { this.checkDisposed (); if (buffer == null) { throw new ArgumentNullException("buffer is a null reference."); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset is less than 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset is greater than the length of buffer."); } if (count < 0) { throw new ArgumentOutOfRangeException("count is less than 0."); } if (count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter."); } if (this.context.HandshakeState == HandshakeState.None) { // Note: Async code may have problem if they can't ensure that // the Negotiate phase isn't done during a read operation. // System.Net.HttpWebRequest protects itself from that problem lock (this.negotiate) { if (this.context.HandshakeState == HandshakeState.None) { this.NegotiateHandshake(); } } } IAsyncResult asyncResult = null; lock (this.read) { try { // If actual buffer is full readed reset it if (this.inputBuffer.Position == this.inputBuffer.Length && this.inputBuffer.Length > 0) { this.resetBuffer(); } if (!this.context.ConnectionEnd) { if ((this.inputBuffer.Length == this.inputBuffer.Position) && (count > 0)) { // bigger than max record length for SSL/TLS byte[] recbuf = new byte[16384]; // this will read data from the network until we have (at least) one // record to send back to the caller this.innerStream.BeginRead (recbuf, 0, recbuf.Length, new AsyncCallback (NetworkReadCallback), recbuf); if (!recordEvent.WaitOne (300000, false)) // 5 minutes { // FAILSAFE DebugHelper.WriteLine ("TIMEOUT length {0}, position {1}, count {2} - {3}\n{4}", this.inputBuffer.Length, this.inputBuffer.Position, count, GetHashCode (), Environment.StackTrace); throw new TlsException (AlertDescription.InternalError); } } } // return the record(s) to the caller rd = new ReadDelegate (this.inputBuffer.Read); asyncResult = rd.BeginInvoke (buffer, offset, count, callback, state); } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); this.Close(); throw new IOException("The authentication or decryption has failed."); } catch (Exception) { throw new IOException("IO exception during read."); } } return asyncResult; } private ManualResetEvent recordEvent = new ManualResetEvent (false); private MemoryStream recordStream = new MemoryStream (); // read encrypted data until we have enough to decrypt (at least) one // record and return are the records (may be more than one) we have private void NetworkReadCallback (IAsyncResult result) { if (this.disposed) { recordEvent.Set (); return; } byte[] recbuf = (byte[])result.AsyncState; int n = innerStream.EndRead (result); if (n > 0) { // add the just received data to the waiting data recordStream.Write (recbuf, 0, n); } bool dataToReturn = false; long pos = recordStream.Position; recordStream.Position = 0; byte[] record = null; // don't try to decode record unless we have at least 5 bytes // i.e. type (1), protocol (2) and length (2) if (recordStream.Length >= 5) { record = this.protocol.ReceiveRecord (recordStream); } // a record of 0 length is valid (and there may be more record after it) while (record != null) { // we probably received more stuff after the record, and we must keep it! long remainder = recordStream.Length - recordStream.Position; byte[] outofrecord = null; if (remainder > 0) { outofrecord = new byte[remainder]; recordStream.Read (outofrecord, 0, outofrecord.Length); } long position = this.inputBuffer.Position; if (record.Length > 0) { // Write new data to the inputBuffer this.inputBuffer.Seek (0, SeekOrigin.End); this.inputBuffer.Write (record, 0, record.Length); // Restore buffer position this.inputBuffer.Seek (position, SeekOrigin.Begin); dataToReturn = true; } recordStream.SetLength (0); record = null; if (remainder > 0) { recordStream.Write (outofrecord, 0, outofrecord.Length); // type (1), protocol (2) and length (2) if (recordStream.Length >= 5) { // try to see if another record is available recordStream.Position = 0; record = this.protocol.ReceiveRecord (recordStream); if (record == null) pos = recordStream.Length; } else pos = remainder; } else pos = 0; } if (!dataToReturn && (n > 0)) { // there is no record to return to caller and (possibly) more data waiting // so continue reading from network (and appending to stream) recordStream.Position = recordStream.Length; this.innerStream.BeginRead (recbuf, 0, recbuf.Length, new AsyncCallback (NetworkReadCallback), recbuf); } else { // we have record(s) to return -or- no more available to read from network // reset position for further reading recordStream.Position = pos; recordEvent.Set (); } } public override IAsyncResult BeginWrite( byte[] buffer, int offset, int count, AsyncCallback callback, object state) { this.checkDisposed(); if (buffer == null) { throw new ArgumentNullException("buffer is a null reference."); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset is less than 0."); } if (offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset is greater than the length of buffer."); } if (count < 0) { throw new ArgumentOutOfRangeException("count is less than 0."); } if (count > (buffer.Length - offset)) { throw new ArgumentOutOfRangeException("count is less than the length of buffer minus the value of the offset parameter."); } if (this.context.HandshakeState == HandshakeState.None) { lock (this.negotiate) { if (this.context.HandshakeState == HandshakeState.None) { this.NegotiateHandshake(); } } } IAsyncResult asyncResult; lock (this.write) { try { // Send the buffer as a TLS record byte[] record = this.protocol.EncodeRecord( ContentType.ApplicationData, buffer, offset, count); asyncResult = this.innerStream.BeginWrite( record, 0, record.Length, callback, state); } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); this.Close(); throw new IOException("The authentication or decryption has failed."); } catch (Exception) { throw new IOException("IO exception during Write."); } } return asyncResult; } public override int EndRead(IAsyncResult asyncResult) { this.checkDisposed(); if (asyncResult == null) { throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead."); } recordEvent.Reset (); return this.rd.EndInvoke (asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { this.checkDisposed(); if (asyncResult == null) { throw new ArgumentNullException("asyncResult is null or was not obtained by calling BeginRead."); } this.innerStream.EndWrite (asyncResult); } public override void Close() { ((IDisposable)this).Dispose(); } public override void Flush() { this.checkDisposed(); this.innerStream.Flush(); } public int Read(byte[] buffer) { return this.Read(buffer, 0, buffer.Length); } public override int Read(byte[] buffer, int offset, int count) { IAsyncResult res = this.BeginRead(buffer, offset, count, null, null); return this.EndRead(res); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public void Write(byte[] buffer) { this.Write(buffer, 0, buffer.Length); } public override void Write(byte[] buffer, int offset, int count) { IAsyncResult res = this.BeginWrite (buffer, offset, count, null, null); this.EndWrite(res); } #endregion #region Misc Methods private void resetBuffer() { this.inputBuffer.SetLength(0); this.inputBuffer.Position = 0; } private void checkDisposed() { if (this.disposed) { throw new ObjectDisposedException("The SslClientStream is closed."); } } #endregion #region Handsake Methods /* Client Server ClientHello --------> ServerHello Certificate* ServerKeyExchange* CertificateRequest* <-------- ServerHelloDone Certificate* ClientKeyExchange CertificateVerify* [ChangeCipherSpec] Finished --------> [ChangeCipherSpec] <-------- Finished Application Data <-------> Application Data Fig. 1 - Message flow for a full handshake */ internal void NegotiateHandshake() { try { if (this.context.HandshakeState != HandshakeState.None) { this.context.Clear(); } // Obtain supported cipher suites this.context.SupportedCiphers = CipherSuiteFactory.GetSupportedCiphers(this.context.SecurityProtocol); // Send client hello this.protocol.SendRecord(HandshakeType.ClientHello); // Read server response while (this.context.LastHandshakeMsg != HandshakeType.ServerHelloDone) { // Read next record this.protocol.ReceiveRecord (this.innerStream); } // Send client certificate if requested if (this.context.ServerSettings.CertificateRequest) { this.protocol.SendRecord(HandshakeType.Certificate); } // Send Client Key Exchange this.protocol.SendRecord(HandshakeType.ClientKeyExchange); // Now initialize session cipher with the generated keys this.context.Cipher.InitializeCipher(); // Send certificate verify if requested if (this.context.ServerSettings.CertificateRequest) { this.protocol.SendRecord(HandshakeType.CertificateVerify); } // Send Cipher Spec protocol this.protocol.SendChangeCipherSpec(); // Read record until server finished is received while (this.context.HandshakeState != HandshakeState.Finished) { // If all goes well this will process messages: // Change Cipher Spec // Server finished this.protocol.ReceiveRecord (this.innerStream); } // Clear Key Info this.context.ClearKeyInfo(); } catch (TlsException ex) { this.protocol.SendAlert(ex.Alert); this.Close(); throw new IOException("The authentication or decryption has failed."); } catch (Exception) { this.protocol.SendAlert(AlertDescription.InternalError); this.Close(); throw new IOException("The authentication or decryption has failed."); } } #endregion #region Event Methods internal virtual bool RaiseServerCertificateValidation( X509Certificate certificate, int[] certificateErrors) { if (this.ServerCertValidation != null) { return this.ServerCertValidation(certificate, certificateErrors); } return (certificateErrors != null && certificateErrors.Length == 0); } internal X509Certificate RaiseClientCertificateSelection( X509CertificateCollection clientCertificates, X509Certificate serverCertificate, string targetHost, X509CertificateCollection serverRequestedCertificates) { if (this.ClientCertSelection != null) { return this.ClientCertSelection( clientCertificates, serverCertificate, targetHost, serverRequestedCertificates); } return null; } internal AsymmetricAlgorithm RaisePrivateKeySelection( X509Certificate certificate, string targetHost) { if (this.PrivateKeySelection != null) { return this.PrivateKeySelection(certificate, targetHost); } return null; } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="BufferAllocator.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * Buffer Allocators with recycling * * Copyright (c) 1999 Microsoft Corporation */ namespace System.Web { using System.Collections; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Web.Util; ////////////////////////////////////////////////////////////////////////////// // Generic buffer recycling internal interface IBufferAllocator { object GetBuffer(); void ReuseBuffer(object buffer); void ReleaseAllBuffers(); int BufferSize { get; } } internal interface IBufferAllocator<T> : IBufferAllocator { new T[] GetBuffer(); T[] GetBuffer(int minSize); void ReuseBuffer(T[] buffer); } internal interface IAllocatorProvider { IBufferAllocator<char> CharBufferAllocator { get; } IBufferAllocator<int> IntBufferAllocator { get; } IBufferAllocator<IntPtr> IntPtrBufferAllocator { get; } void TrimMemory(); } /* * Base class for allocator doing buffer recycling */ internal abstract class BufferAllocator : IBufferAllocator { private int _maxFree; private int _numFree; private Stack _buffers; private static int s_ProcsFudgeFactor; static BufferAllocator() { s_ProcsFudgeFactor = SystemInfo.GetNumProcessCPUs(); if (s_ProcsFudgeFactor < 1) s_ProcsFudgeFactor = 1; if (s_ProcsFudgeFactor > 4) s_ProcsFudgeFactor = 4; } internal BufferAllocator(int maxFree) { _buffers = new Stack(); _numFree = 0; _maxFree = maxFree * s_ProcsFudgeFactor; } public void ReleaseAllBuffers() { if (_numFree > 0) { lock (this) { _buffers.Clear(); _numFree = 0; } } } public object GetBuffer() { Object buffer = null; if (_numFree > 0) { lock(this) { if (_numFree > 0) { buffer = _buffers.Pop(); _numFree--; } } } if (buffer == null) buffer = AllocBuffer(); return buffer; } public void ReuseBuffer(object buffer) { if (_numFree < _maxFree) { lock(this) { if (_numFree < _maxFree) { _buffers.Push(buffer); _numFree++; } } } } /* * To be implemented by a derived class */ abstract protected Object AllocBuffer(); abstract public int BufferSize { get; } } /* * Concrete allocator class for ubyte[] buffer recycling */ internal class UbyteBufferAllocator : BufferAllocator { private int _bufferSize; internal UbyteBufferAllocator(int bufferSize, int maxFree) : base(maxFree) { _bufferSize = bufferSize; } protected override Object AllocBuffer() { return new byte[_bufferSize]; } public override int BufferSize { get { return _bufferSize; } } } /* * Concrete allocator class for char[] buffer recycling */ internal class CharBufferAllocator : BufferAllocator { private int _bufferSize; internal CharBufferAllocator(int bufferSize, int maxFree) : base(maxFree) { _bufferSize = bufferSize; } protected override Object AllocBuffer() { return new char[_bufferSize]; } public override int BufferSize { get { return _bufferSize; } } } /* * Concrete allocator class for int[] buffer recycling */ internal class IntegerArrayAllocator : BufferAllocator { private int _arraySize; internal IntegerArrayAllocator(int arraySize, int maxFree) : base(maxFree) { _arraySize = arraySize; } protected override Object AllocBuffer() { return new int[_arraySize]; } public override int BufferSize { get { return _arraySize; } } } /* * Concrete allocator class for IntPtr[] buffer recycling */ internal class IntPtrArrayAllocator : BufferAllocator { private int _arraySize; internal IntPtrArrayAllocator(int arraySize, int maxFree) : base(maxFree) { _arraySize = arraySize; } protected override Object AllocBuffer() { return new IntPtr[_arraySize]; } public override int BufferSize { get { return _arraySize; } } } /* * Simple Buffer Allocator - Reusable buffers pool * Thread UNSAFE! Lock free. Caller must guarantee non-concurent access. * Use as member of already pooled instances (like HttpApplication) that prohibit concurent access to avoid taking locks */ internal class SimpleBufferAllocator<T> : IBufferAllocator<T> { private Stack<T[]> _buffers; private readonly int _bufferSize; public SimpleBufferAllocator(int bufferSize) { if (bufferSize <= 0) { throw new ArgumentOutOfRangeException("bufferSize"); } _buffers = new Stack<T[]>(); _bufferSize = bufferSize; } public T[] GetBuffer() { return GetBufferImpl(); } public T[] GetBuffer(int minSize) { if (minSize < 0) { throw new ArgumentOutOfRangeException("minSize"); } T[] buffer = null; if (minSize <= BufferSize) { // Get from the pool buffer = GetBufferImpl(); } else { // Allocate a new buffer. It will not be reused later buffer = AllocBuffer(minSize); } return buffer; } object IBufferAllocator.GetBuffer() { return GetBufferImpl(); } public void ReuseBuffer(T[] buffer) { ReuseBufferImpl(buffer); } void IBufferAllocator.ReuseBuffer(object buffer) { ReuseBufferImpl((T[]) buffer); } public void ReleaseAllBuffers() { _buffers.Clear(); } public int BufferSize { get { return _bufferSize; } } private T[] GetBufferImpl() { T[] buffer = null; if (_buffers.Count > 0) { // Get an exisitng buffer buffer = _buffers.Pop(); } else { // Create a new buffer buffer = AllocBuffer(BufferSize); } return buffer; } private void ReuseBufferImpl(T[] buffer) { // Accept back only buffers that match the orirignal buffer size if (buffer != null && buffer.Length == BufferSize) { _buffers.Push(buffer); } } private static T[] AllocBuffer(int size) { return new T[size]; } } /* * Adapter to convert IBufferAllocator to generic IBufferAllocator<> */ class BufferAllocatorWrapper<T> : IBufferAllocator<T> { private IBufferAllocator _allocator; public BufferAllocatorWrapper(IBufferAllocator allocator) { Debug.Assert(allocator != null); _allocator = allocator; } public T[] GetBuffer() { return (T[])_allocator.GetBuffer(); } public T[] GetBuffer(int minSize) { if (minSize < 0) { throw new ArgumentOutOfRangeException("minSize"); } T[] buffer = null; if (minSize <= BufferSize) { // Get from the allocator buffer = (T[])_allocator.GetBuffer(); } else { // Allocate a new buffer. It will not be reused later buffer = new T[minSize]; } return buffer; } public void ReuseBuffer(T[] buffer) { // Accept back only buffers that match the orirignal buffer size if (buffer != null && buffer.Length == BufferSize) { _allocator.ReuseBuffer(buffer); } } object IBufferAllocator.GetBuffer() { return _allocator.GetBuffer(); } void IBufferAllocator.ReuseBuffer(object buffer) { ReuseBuffer((T[])buffer); } public void ReleaseAllBuffers() { _allocator.ReleaseAllBuffers(); } public int BufferSize { get { return _allocator.BufferSize; } } } /* * Provider for different buffer allocators */ internal class AllocatorProvider : IAllocatorProvider { private IBufferAllocator<char> _charAllocator = null; private IBufferAllocator<int> _intAllocator = null; private IBufferAllocator<IntPtr> _intPtrAllocator = null; public IBufferAllocator<char> CharBufferAllocator { get { return _charAllocator; } set { if (value == null) { throw new ArgumentNullException("value"); } _charAllocator = value; } } public IBufferAllocator<int> IntBufferAllocator { get { return _intAllocator; } set { if (value == null) { throw new ArgumentNullException("value"); } _intAllocator = value; } } public IBufferAllocator<IntPtr> IntPtrBufferAllocator { get { return _intPtrAllocator; } set { if (value == null) { throw new ArgumentNullException("value"); } _intPtrAllocator = value; } } public void TrimMemory() { if (_charAllocator != null) { _charAllocator.ReleaseAllBuffers(); } if (_intAllocator != null) { _intAllocator.ReleaseAllBuffers(); } if (_intPtrAllocator != null) { _intPtrAllocator.ReleaseAllBuffers(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // namespace System.Reflection.Emit { using System; using IList = System.Collections.IList; using System.Collections.Generic; using System.Reflection; using System.Security; using System.Diagnostics; using CultureInfo = System.Globalization.CultureInfo; #if !FEATURE_CORECLR using ResourceWriter = System.Resources.ResourceWriter; #else // FEATURE_CORECLR using IResourceWriter = System.Resources.IResourceWriter; #endif // !FEATURE_CORECLR using System.IO; using System.Runtime.Versioning; using System.Diagnostics.SymbolStore; using System.Diagnostics.Contracts; // This is a package private class. This class hold all of the managed // data member for AssemblyBuilder. Note that what ever data members added to // this class cannot be accessed from the EE. internal class AssemblyBuilderData { [SecurityCritical] internal AssemblyBuilderData( InternalAssemblyBuilder assembly, String strAssemblyName, AssemblyBuilderAccess access, String dir) { m_assembly = assembly; m_strAssemblyName = strAssemblyName; m_access = access; m_moduleBuilderList = new List<ModuleBuilder>(); m_resWriterList = new List<ResWriterData>(); //Init to null/0 done for you by the CLR. FXCop has spoken if (dir == null && access != AssemblyBuilderAccess.Run) m_strDir = Environment.CurrentDirectory; else m_strDir = dir; m_peFileKind = PEFileKinds.Dll; } // Helper to add a dynamic module into the tracking list internal void AddModule(ModuleBuilder dynModule) { m_moduleBuilderList.Add(dynModule); } // Helper to add a resource information into the tracking list internal void AddResWriter(ResWriterData resData) { m_resWriterList.Add(resData); } // Helper to track CAs to persist onto disk internal void AddCustomAttribute(CustomAttributeBuilder customBuilder) { // make sure we have room for this CA if (m_CABuilders == null) { m_CABuilders = new CustomAttributeBuilder[m_iInitialSize]; } if (m_iCABuilder == m_CABuilders.Length) { CustomAttributeBuilder[] tempCABuilders = new CustomAttributeBuilder[m_iCABuilder * 2]; Array.Copy(m_CABuilders, tempCABuilders, m_iCABuilder); m_CABuilders = tempCABuilders; } m_CABuilders[m_iCABuilder] = customBuilder; m_iCABuilder++; } // Helper to track CAs to persist onto disk internal void AddCustomAttribute(ConstructorInfo con, byte[] binaryAttribute) { // make sure we have room for this CA if (m_CABytes == null) { m_CABytes = new byte[m_iInitialSize][]; m_CACons = new ConstructorInfo[m_iInitialSize]; } if (m_iCAs == m_CABytes.Length) { // enlarge the arrays byte[][] temp = new byte[m_iCAs * 2][]; ConstructorInfo[] tempCon = new ConstructorInfo[m_iCAs * 2]; for (int i=0; i < m_iCAs; i++) { temp[i] = m_CABytes[i]; tempCon[i] = m_CACons[i]; } m_CABytes = temp; m_CACons = tempCon; } byte[] attrs = new byte[binaryAttribute.Length]; Array.Copy(binaryAttribute, attrs, binaryAttribute.Length); m_CABytes[m_iCAs] = attrs; m_CACons[m_iCAs] = con; m_iCAs++; } // Helper to calculate unmanaged version info from Assembly's custom attributes. // If DefineUnmanagedVersionInfo is called, the parameter provided will override // the CA's value. // [System.Security.SecurityCritical] // auto-generated internal void FillUnmanagedVersionInfo() { // Get the lcid set on the assembly name as default if available // Note that if LCID is not avaible from neither AssemblyName or AssemblyCultureAttribute, // it is default to -1 which is treated as language neutral. // CultureInfo locale = m_assembly.GetLocale(); #if FEATURE_USE_LCID if (locale != null) m_nativeVersion.m_lcid = locale.LCID; #endif for (int i = 0; i < m_iCABuilder; i++) { // check for known attributes Type conType = m_CABuilders[i].m_con.DeclaringType; if (m_CABuilders[i].m_constructorArgs.Length == 0 || m_CABuilders[i].m_constructorArgs[0] == null) continue; if (conType.Equals(typeof(System.Reflection.AssemblyCopyrightAttribute))) { // assert that we should only have one argument for this CA and the type should // be a string. // if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { m_nativeVersion.m_strCopyright = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyTrademarkAttribute))) { // assert that we should only have one argument for this CA and the type should // be a string. // if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { m_nativeVersion.m_strTrademark = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyProductAttribute))) { if (m_OverrideUnmanagedVersionInfo == false) { // assert that we should only have one argument for this CA and the type should // be a string. // m_nativeVersion.m_strProduct = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyCompanyAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { // assert that we should only have one argument for this CA and the type should // be a string. // m_nativeVersion.m_strCompany = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyDescriptionAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } m_nativeVersion.m_strDescription = m_CABuilders[i].m_constructorArgs[0].ToString(); } else if (conType.Equals(typeof(System.Reflection.AssemblyTitleAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } m_nativeVersion.m_strTitle = m_CABuilders[i].m_constructorArgs[0].ToString(); } else if (conType.Equals(typeof(System.Reflection.AssemblyInformationalVersionAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { m_nativeVersion.m_strProductVersion = m_CABuilders[i].m_constructorArgs[0].ToString(); } } else if (conType.Equals(typeof(System.Reflection.AssemblyCultureAttribute))) { // retrieve the LCID if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } // CultureInfo attribute overrides the lcid from AssemblyName. CultureInfo culture = new CultureInfo(m_CABuilders[i].m_constructorArgs[0].ToString()); #if FEATURE_USE_LCID m_nativeVersion.m_lcid = culture.LCID; #endif } else if (conType.Equals(typeof(System.Reflection.AssemblyFileVersionAttribute))) { if (m_CABuilders[i].m_constructorArgs.Length != 1) { throw new ArgumentException(Environment.GetResourceString( "Argument_BadCAForUnmngRSC", m_CABuilders[i].m_con.ReflectedType.Name)); } if (m_OverrideUnmanagedVersionInfo == false) { m_nativeVersion.m_strFileVersion = m_CABuilders[i].m_constructorArgs[0].ToString(); } } } } // Helper to ensure the resource name is unique underneath assemblyBuilder internal void CheckResNameConflict(String strNewResName) { int size = m_resWriterList.Count; int i; for (i = 0; i < size; i++) { ResWriterData resWriter = m_resWriterList[i]; if (resWriter.m_strName.Equals(strNewResName)) { // Cannot have two resources with the same name throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateResourceName")); } } } // Helper to ensure the module name is unique underneath assemblyBuilder internal void CheckNameConflict(String strNewModuleName) { int size = m_moduleBuilderList.Count; int i; for (i = 0; i < size; i++) { ModuleBuilder moduleBuilder = m_moduleBuilderList[i]; if (moduleBuilder.m_moduleData.m_strModuleName.Equals(strNewModuleName)) { // Cannot have two dynamic modules with the same name throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateModuleName")); } } // Right now dynamic modules can only be added to dynamic assemblies in which // all modules are dynamic. Otherwise we would also need to check the static modules // with this: // if (m_assembly.GetModule(strNewModuleName) != null) // { // // Cannot have two dynamic modules with the same name // throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateModuleName")); // } } // Helper to ensure the type name is unique underneath assemblyBuilder internal void CheckTypeNameConflict(String strTypeName, TypeBuilder enclosingType) { BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.CheckTypeNameConflict( " + strTypeName + " )"); for (int i = 0; i < m_moduleBuilderList.Count; i++) { ModuleBuilder curModule = m_moduleBuilderList[i]; curModule.CheckTypeNameConflict(strTypeName, enclosingType); } // Right now dynamic modules can only be added to dynamic assemblies in which // all modules are dynamic. Otherwise we would also need to check loaded types. // We only need to make this test for non-nested types since any // duplicates in nested types will be caught at the top level. // if (enclosingType == null && m_assembly.GetType(strTypeName, false, false) != null) // { // // Cannot have two types with the same name // throw new ArgumentException(Environment.GetResourceString("Argument_DuplicateTypeName")); // } } // Helper to ensure the file name is unique underneath assemblyBuilder. This includes // modules and resources. // // // internal void CheckFileNameConflict(String strFileName) { int size = m_moduleBuilderList.Count; int i; for (i = 0; i < size; i++) { ModuleBuilder moduleBuilder = m_moduleBuilderList[i]; if (moduleBuilder.m_moduleData.m_strFileName != null) { if (String.Compare(moduleBuilder.m_moduleData.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0) { // Cannot have two dynamic module with the same name throw new ArgumentException(Environment.GetResourceString("Argument_DuplicatedFileName")); } } } size = m_resWriterList.Count; for (i = 0; i < size; i++) { ResWriterData resWriter = m_resWriterList[i]; if (resWriter.m_strFileName != null) { if (String.Compare(resWriter.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0) { // Cannot have two dynamic module with the same name throw new ArgumentException(Environment.GetResourceString("Argument_DuplicatedFileName")); } } } } // Helper to look up which module that assembly is supposed to be stored at // // // internal ModuleBuilder FindModuleWithFileName(String strFileName) { int size = m_moduleBuilderList.Count; int i; for (i = 0; i < size; i++) { ModuleBuilder moduleBuilder = m_moduleBuilderList[i]; if (moduleBuilder.m_moduleData.m_strFileName != null) { if (String.Compare(moduleBuilder.m_moduleData.m_strFileName, strFileName, StringComparison.OrdinalIgnoreCase) == 0) { return moduleBuilder; } } } return null; } // Helper to look up module by name. // // // internal ModuleBuilder FindModuleWithName(String strName) { int size = m_moduleBuilderList.Count; int i; for (i = 0; i < size; i++) { ModuleBuilder moduleBuilder = m_moduleBuilderList[i]; if (moduleBuilder.m_moduleData.m_strModuleName != null) { if (String.Compare(moduleBuilder.m_moduleData.m_strModuleName, strName, StringComparison.OrdinalIgnoreCase) == 0) return moduleBuilder; } } return null; } // add type to public COMType tracking list internal void AddPublicComType(Type type) { BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.AddPublicComType( " + type.FullName + " )"); if (m_isSaved == true) { // assembly has been saved before! throw new InvalidOperationException(Environment.GetResourceString( "InvalidOperation_CannotAlterAssembly")); } EnsurePublicComTypeCapacity(); m_publicComTypeList[m_iPublicComTypeCount] = type; m_iPublicComTypeCount++; } // add security permission requests internal void AddPermissionRequests( PermissionSet required, PermissionSet optional, PermissionSet refused) { BCLDebug.Log("DYNIL","## DYNIL LOGGING: AssemblyBuilderData.AddPermissionRequests"); if (m_isSaved == true) { // assembly has been saved before! throw new InvalidOperationException(Environment.GetResourceString( "InvalidOperation_CannotAlterAssembly")); } m_RequiredPset = required; m_OptionalPset = optional; m_RefusedPset = refused; } private void EnsurePublicComTypeCapacity() { if (m_publicComTypeList == null) { m_publicComTypeList = new Type[m_iInitialSize]; } if (m_iPublicComTypeCount == m_publicComTypeList.Length) { Type[] tempTypeList = new Type[m_iPublicComTypeCount * 2]; Array.Copy(m_publicComTypeList, tempTypeList, m_iPublicComTypeCount); m_publicComTypeList = tempTypeList; } } internal List<ModuleBuilder> m_moduleBuilderList; internal List<ResWriterData> m_resWriterList; internal String m_strAssemblyName; internal AssemblyBuilderAccess m_access; private InternalAssemblyBuilder m_assembly; internal Type[] m_publicComTypeList; internal int m_iPublicComTypeCount; internal bool m_isSaved; internal const int m_iInitialSize = 16; internal String m_strDir; // hard coding the assembly def token internal const int m_tkAssembly = 0x20000001; // Security permission requests internal PermissionSet m_RequiredPset; internal PermissionSet m_OptionalPset; internal PermissionSet m_RefusedPset; // tracking AssemblyDef's CAs for persistence to disk internal CustomAttributeBuilder[] m_CABuilders; internal int m_iCABuilder; internal byte[][] m_CABytes; internal ConstructorInfo[] m_CACons; internal int m_iCAs; internal PEFileKinds m_peFileKind; // assembly file kind internal MethodInfo m_entryPointMethod; internal Assembly m_ISymWrapperAssembly; #if !FEATURE_CORECLR internal ModuleBuilder m_entryPointModule; #endif //!FEATURE_CORECLR // For unmanaged resources internal String m_strResourceFileName; internal byte[] m_resourceBytes; internal NativeVersionInfo m_nativeVersion; internal bool m_hasUnmanagedVersionInfo; internal bool m_OverrideUnmanagedVersionInfo; } /********************************************** * * Internal structure to track the list of ResourceWriter for * AssemblyBuilder & ModuleBuilder. * **********************************************/ internal class ResWriterData { #if FEATURE_CORECLR internal ResWriterData( IResourceWriter resWriter, Stream memoryStream, String strName, String strFileName, String strFullFileName, ResourceAttributes attribute) { m_resWriter = resWriter; m_memoryStream = memoryStream; m_strName = strName; m_strFileName = strFileName; m_strFullFileName = strFullFileName; m_nextResWriter = null; m_attribute = attribute; } #else internal ResWriterData( ResourceWriter resWriter, Stream memoryStream, String strName, String strFileName, String strFullFileName, ResourceAttributes attribute) { m_resWriter = resWriter; m_memoryStream = memoryStream; m_strName = strName; m_strFileName = strFileName; m_strFullFileName = strFullFileName; m_nextResWriter = null; m_attribute = attribute; } #endif #if !FEATURE_CORECLR internal ResourceWriter m_resWriter; #else // FEATURE_CORECLR internal IResourceWriter m_resWriter; #endif // !FEATURE_CORECLR internal String m_strName; internal String m_strFileName; internal String m_strFullFileName; internal Stream m_memoryStream; internal ResWriterData m_nextResWriter; internal ResourceAttributes m_attribute; } internal class NativeVersionInfo { internal NativeVersionInfo() { m_strDescription = null; m_strCompany = null; m_strTitle = null; m_strCopyright = null; m_strTrademark = null; m_strProduct = null; m_strProductVersion = null; m_strFileVersion = null; m_lcid = -1; } internal String m_strDescription; internal String m_strCompany; internal String m_strTitle; internal String m_strCopyright; internal String m_strTrademark; internal String m_strProduct; internal String m_strProductVersion; internal String m_strFileVersion; internal int m_lcid; } }
#region Copyright (c) 2003, newtelligence AG. All rights reserved. /* // Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com) // Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // (3) Neither the name of the newtelligence AG 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. // ------------------------------------------------------------------------- // // Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com) // // newtelligence is a registered trademark of newtelligence Aktiengesellschaft. // // For portions of this software, the some additional copyright notices may apply // which can either be found in the license.txt file included in the source distribution // or following this notice. // */ #endregion using System; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web; using System.Web.UI; namespace newtelligence.DasBlog.Web.Core { /// <summary> /// This is a base class for your own Pages which implements /// automatic serialization of public and protected fields /// into session state or into cookies. /// </summary> /// <example> /// All you need to do is this: /// /// using newtelligence.Web.UI /// /// public class MyPage : SharedBaseControl /// { /// [PersistentPageState] public int pageVisitsEver; /// [PersistentPageState("Visits")] public int siteVisitsEver; /// [SessionPageState] public int pageVisitsThisSession; /// [SessionPageState("Visits")] public int siteVisitsThisSession; /// [TransientPageState] public int roundtripsThisPage; /// /// // omissions... /// /// private void Page_Load(object sender, System.EventArgs e) /// { /// pageVisitsEver++; /// siteVisitsEver++; /// pageVisitsThisSession++; /// siteVisitsThisSession++; /// roundtripsThisPage++; /// } /// /// } /// </example> /// <remarks> /// This should really be: /// /// template <class T> /// public class SharedBaseControl : T /// /// but we don't have generics, yet. Sigh. /// </remarks> public class SharedBaseControl : System.Web.UI.UserControl { private EventHandler PreRenderHandler = null; private const string keyPrefix = "__$stateManagingControl"; /// <summary> /// Public constructor. Sets up events. /// </summary> public SharedBaseControl() { Init += new EventHandler(this.SessionLoad); PreRender += PreRenderHandler = new EventHandler(this.SessionStore); } /// <summary> /// Event handler attached to "Page.Init" that recovers /// marked fields from session state /// </summary> /// <param name="o">Object firing the event</param> /// <param name="e">Event arguments</param> private void SessionLoad(object o, EventArgs e) { FieldInfo[] fields = GetType().GetFields(BindingFlags.Public| BindingFlags.NonPublic| BindingFlags.Instance); // Persistent, page scope values HttpCookie pageCookie = Request.Cookies[GetType().FullName]; if ( pageCookie != null ) { foreach( FieldInfo field in fields ) { if ( field.IsDefined(typeof(PersistentPageStateAttribute), true ) && field.FieldType.IsPrimitive ) { PersistentPageStateAttribute ppsa = (PersistentPageStateAttribute) field.GetCustomAttributes( typeof(PersistentPageStateAttribute),true)[0]; if ( ppsa.keyName == null && pageCookie[Page.Request.Path+":"+this.UniqueID+"."+field.Name] != null ) { field.SetValue(this, Convert.ChangeType(pageCookie[Page.Request.Path+":"+this.UniqueID+"."+field.Name], field.FieldType, CultureInfo.InvariantCulture)); } } } } // Persistent, user scope values HttpCookie siteCookie = Request.Cookies[keyPrefix]; if ( siteCookie != null ) { foreach( FieldInfo field in fields ) { if ( field.IsDefined(typeof(PersistentPageStateAttribute), true ) && field.FieldType.IsPrimitive ) { PersistentPageStateAttribute ppsa = (PersistentPageStateAttribute) field.GetCustomAttributes( typeof(PersistentPageStateAttribute),true)[0]; if ( ppsa.keyName != null && siteCookie[ppsa.keyName] != null ) { field.SetValue(this, Convert.ChangeType(siteCookie[ppsa.keyName], field.FieldType, CultureInfo.InvariantCulture)); } } } } // Session scope values foreach( FieldInfo field in fields ) { if ( field.IsDefined(typeof(SessionPageStateAttribute),true ) && field.FieldType.IsSerializable ) { SessionPageStateAttribute spsa = (SessionPageStateAttribute) field.GetCustomAttributes( typeof(SessionPageStateAttribute),true)[0]; if ( spsa.keyName == null ) { field.SetValue(this, Session[Page.Request.Path+":"+this.UniqueID+"."+field.Name]); } else { field.SetValue(this, Session[keyPrefix+spsa.keyName]); } } } if ( IsPostBack ) { // Conversation scope values foreach( FieldInfo field in fields) { if ( field.IsDefined(typeof(TransientPageStateAttribute), true ) && field.FieldType.IsSerializable ) { field.SetValue(this, Session[Page.Request.Path+":"+this.UniqueID+"."+field.Name]); } } } } /// <summary> /// Event handler attached to "Page.Unload" that sticks marked fields /// into session state /// </summary> /// <param name="o">Object firing the event</param> /// <param name="e">Event arguments</param> private void SessionStore(object o, EventArgs e) { FieldInfo[] fields = GetType().GetFields(BindingFlags.Public| BindingFlags.NonPublic| BindingFlags.Instance); // Persistent state HttpCookie pageCookie = new HttpCookie(GetType().FullName); HttpCookie siteCookie = Request.Cookies[keyPrefix]; if ( siteCookie == null ) { siteCookie = new HttpCookie(keyPrefix); } siteCookie.Expires = pageCookie.Expires = DateTime.Now.ToUniversalTime().AddYears(2); foreach( FieldInfo field in fields ) { if ( field.IsDefined(typeof(PersistentPageStateAttribute),true )) { if ( field.FieldType.IsPrimitive ) { PersistentPageStateAttribute ppsa = (PersistentPageStateAttribute) field.GetCustomAttributes( typeof(PersistentPageStateAttribute),true)[0]; if ( ppsa.keyName == null ) { pageCookie[Page.Request.Path+":"+this.UniqueID+"."+field.Name] = (string)Convert.ChangeType(field.GetValue(this), typeof(string), CultureInfo.InvariantCulture); } else { siteCookie[ppsa.keyName] = (string)Convert.ChangeType(field.GetValue(this), typeof(string), CultureInfo.InvariantCulture); } } else { throw new SerializationException( String.Format("Field '{0}' is not a primitive type",field.Name)); } } } if ( pageCookie.Values.Count > 0 ) { Response.AppendCookie(pageCookie); } if ( siteCookie.Values.Count > 0 ) { Response.AppendCookie(siteCookie); } // Transient & Session scope state foreach( FieldInfo field in fields) { if ( field.IsDefined(typeof(TransientPageStateAttribute),true ) || field.IsDefined(typeof(SessionPageStateAttribute),true ) ) { if ( field.FieldType.IsSerializable ) { string fieldName; fieldName = Page.Request.Path+":"+this.UniqueID+"."+field.Name; if ( field.IsDefined(typeof(SessionPageStateAttribute),true) ) { SessionPageStateAttribute spsa = (SessionPageStateAttribute) field.GetCustomAttributes( typeof(SessionPageStateAttribute),true)[0]; if ( spsa.keyName != null ) { fieldName = keyPrefix+spsa.keyName; } } Session[fieldName] = field.GetValue(this); } else { throw new SerializationException( String.Format("Type {0} of field '{0}' is not serializable", field.FieldType.FullName,field.Name)); } } } } /// <summary> /// Private utility function invoked by Transfer and Redirect. /// Clears out all transient state of the current page. /// </summary> private void SessionDiscard() { // Discard transient page state only foreach( FieldInfo field in GetType().GetFields(BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance)) { if ( field.IsDefined(typeof(TransientPageStateAttribute),true ) && field.FieldType.IsSerializable ) { Session.Remove(Page.Request.Path+":"+this.UniqueID+"."+field.Name); } } } /// <summary> /// Use this as a replacement for Server.Transfer. This /// method will discard the transient page state and /// call Server.Transfer. /// </summary> /// <param name="target"></param> public virtual void Transfer( string target ) { // ;store persistent session aspects, since PreRender isn't fired now SessionStore(null, null); // ;and then discard the transient state SessionDiscard(); Server.Transfer(target); } /// <summary> /// Use this as a replacement for Response.Redirect. This /// method will discard the transient page state and /// call Response.Redirect. /// </summary> /// <param name="target"></param> public virtual void Redirect( string target ) { // ;store persistent session aspects, since PreRender isn't fired now SessionStore(null, null); // ;and then discard the transient state SessionDiscard(); Response.Redirect(target,true); } } }
using System; using System.Diagnostics; using OTFontFile; using Win32APIs; namespace OTFontFileVal { /// <summary> /// Summary description for val_name. /// </summary> public class val_name : Table_name, ITableValidate { /************************ * constructors */ public val_name(OTTag tag, MBOBuffer buf) : base(tag, buf) { } /************************ * public methods */ public bool Validate(Validator v, OTFontVal fontOwner) { bool bRet = true; if (v.PerformTest(T.name_FormatSelector)) { if (FormatSelector == 0) { v.Pass(T.name_FormatSelector, P.name_P_FormatSelector, m_tag); } else { v.Error(T.name_FormatSelector, E.name_E_FormatSelector, m_tag, FormatSelector.ToString()); bRet = false; } } if (v.PerformTest(T.name_StringsWithinTable)) { bool bStringsWithinTable = true; uint tableLength = GetLength(); for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.StringOffset + nr.StringLength > tableLength) { v.Error(T.name_StringsWithinTable, E.name_E_StringsWithinTable, m_tag, "string# " + i); bStringsWithinTable = false; bRet = false; } } else { v.Warning(T.name_StringsWithinTable, W._TEST_W_OtherErrorsInTable, m_tag); bStringsWithinTable = false; break; } } if (bStringsWithinTable) { v.Pass(T.name_StringsWithinTable, P.name_P_StringsWithinTable, m_tag); } } if (v.PerformTest(T.name_NameRecordsSorted)) { bool bSortedOrder = true; if (NumberNameRecords > 1) { NameRecord CurrNR = GetNameRecord(0); NameRecord NextNR = null; for (uint i=0; i<NumberNameRecords-1; i++) { NextNR = GetNameRecord(i+1); if (CurrNR == null || NextNR == null) { bSortedOrder = false; break; } if (CurrNR.PlatformID > NextNR.PlatformID) { bSortedOrder = false; break; } else if (CurrNR.PlatformID == NextNR.PlatformID) { if (CurrNR.EncodingID > NextNR.EncodingID) { bSortedOrder = false; break; } else if (CurrNR.EncodingID == NextNR.EncodingID) { if (CurrNR.LanguageID > NextNR.LanguageID) { bSortedOrder = false; break; } else if (CurrNR.LanguageID == NextNR.LanguageID) { if (CurrNR.NameID > NextNR.NameID) { bSortedOrder = false; break; } } } } CurrNR = NextNR; } } if (bSortedOrder) { v.Pass(T.name_NameRecordsSorted, P.name_P_NameRecordsSorted, m_tag); } else { v.Error(T.name_NameRecordsSorted, E.name_E_NameRecordsSorted, m_tag); bRet = false; } } if (v.PerformTest(T.name_ReservedNameIDs)) { bool bReservedOk = true; for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.NameID >= 21 && nr.NameID <= 255) { string s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = " + nr.LanguageID + ", nameID = " + nr.NameID; v.Error(T.name_ReservedNameIDs, E.name_E_ReservedNameID, m_tag, s); bReservedOk = false; break; } } else { v.Warning(T.name_ReservedNameIDs, W._TEST_W_OtherErrorsInTable, m_tag); bReservedOk = false; break; } } if (bReservedOk) { v.Pass(T.name_ReservedNameIDs, P.name_P_ReservedNameID, m_tag); } } if (v.PerformTest(T.name_BothPlatforms)) { bool bMac = false; bool bMS = false; for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.PlatformID == 1) { bMac = true; } else if (nr.PlatformID == 3) { bMS = true; } } } if (bMac && bMS) { v.Pass(T.name_BothPlatforms, P.name_P_BothPlatforms, m_tag); } else if (!bMac) { v.Error(T.name_BothPlatforms, E.name_E_NoMacPlatform, m_tag); bRet = false; } else if (!bMS) { v.Error(T.name_BothPlatforms, E.name_E_NoMSPlatform, m_tag); bRet = false; } } if (v.PerformTest(T.name_VersionString)) { bool bFound = false; string sVersion = ""; for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.PlatformID == 3 // ms && (nr.EncodingID == 1 /* unicode */ || nr.EncodingID == 0 /*symbol*/) && nr.NameID == 5) // version string { bFound = true; bool bVerStringValid = false; byte [] buf = GetEncodedString(nr); string s = ""; if (buf != null) { sVersion = ""; for (int j=0; j<buf.Length/2; j++) { char c = (char)(ushort)(buf[j*2]<<8 | buf[j*2+1]); sVersion += c; } if (sVersion.Length >= 11 && sVersion.StartsWith("Version ") && Char.IsDigit(sVersion, 8)) { int j = 9; // advance past the digits in the major number while (j < sVersion.Length) { if (Char.IsDigit(sVersion, j)) { j++; } else { break; } } // if major number is followed by a period if (sVersion[j] == '.') { // advance past the period j++; // check for a digit if (Char.IsDigit(sVersion, j)) { bVerStringValid = true; } } } } s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = " + nr.LanguageID + ", \"" + sVersion + "\""; if (bVerStringValid) { v.Pass(T.name_VersionString, P.name_P_VersionStringFormat, m_tag, s); } else { v.Error(T.name_VersionString, E.name_E_VersionStringFormat, m_tag, s); bRet = false; } // compare to mac version string if present string sMacVer = GetString(1, 0, 0xffff, 5); if (sMacVer != null) { if (sVersion.CompareTo(sMacVer) != 0) { v.Warning(T.name_VersionString, W.name_W_VersionMismatch_MS_MAC, m_tag); } } // compare to 3,10 version string if present string s310Ver = GetString(3, 10, nr.LanguageID, 5); if (s310Ver != null) { if (sVersion.CompareTo(s310Ver) != 0) { string s310 = "platID = 3, encID = 10, langID = " + nr.LanguageID + ", \"" + s310Ver + "\""; v.Warning(T.name_VersionString, W.name_W_VersionMismatch_3_1_3_10, m_tag, s + " / " + s310); } } } } } if (!bFound) { v.Error(T.name_VersionString, E.name_E_VersionStringNotFound, m_tag); bRet = false; } } if (v.PerformTest(T.name_PlatformSpecificEncoding)) { bool bIDsOk = true; for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.PlatformID == 0) // unicode { if (nr.EncodingID > 3) { string s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = " + nr.LanguageID + ", nameID = " + nr.NameID; v.Error(T.name_PlatformSpecificEncoding, E.name_E_PlatformSpecificEncoding, m_tag, s); bIDsOk = false; bRet = false; } } else if (nr.PlatformID == 1) // mac { if (nr.EncodingID > 32) { string s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = " + nr.LanguageID + ", nameID = " + nr.NameID; v.Error(T.name_PlatformSpecificEncoding, E.name_E_PlatformSpecificEncoding, m_tag, s); bIDsOk = false; bRet = false; } } else if (nr.PlatformID == 2) // iso { if (nr.EncodingID > 2) { string s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = " + nr.LanguageID + ", nameID = " + nr.NameID; v.Error(T.name_PlatformSpecificEncoding, E.name_E_PlatformSpecificEncoding, m_tag, s); bIDsOk = false; bRet = false; } } else if (nr.PlatformID == 3) // MS { if (nr.EncodingID > 10) { string s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = " + nr.LanguageID + ", nameID = " + nr.NameID; v.Error(T.name_PlatformSpecificEncoding, E.name_E_PlatformSpecificEncoding, m_tag, s); bIDsOk = false; bRet = false; } } /* else if (nr.PlatformID == 4) // Custom { } */ } else { v.Warning(T.name_PlatformSpecificEncoding, W._TEST_W_OtherErrorsInTable, m_tag); bIDsOk = false; break; } } if (bIDsOk) { v.Pass(T.name_PlatformSpecificEncoding, P.name_P_PlatformSpecificEncoding, m_tag); } } if (v.PerformTest(T.name_MSLanguageIDs)) { bool bFound = false; bool bIDsOk = true; ushort [] MSLangIDs = // taken from Q224804 { 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, 0x0409, 0x040a, 0x040b, 0x040c, 0x040D, 0x040e, 0x040F, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041a, 0x041b, 0x041c, 0x041D, 0x041E, 0x041f, 0x0420, 0x0421, 0x0422, 0x0423, 0x0424, 0x0425, 0x0426, 0x0427, 0x0429, 0x042a, 0x042b, 0x042c, 0x042D, 0x042e, 0x042f, 0x0430, 0x0431, 0x0432, 0x0433, 0x0434, 0x0435, 0x0436, 0x0437, 0x0438, 0x0439, 0x043b, 0x043d, 0x043e, 0x043f, 0x0441, 0x0443, 0x0444, 0x0445, 0x0446, 0x0447, 0x0448, 0x0449, 0x044a, 0x044b, 0x044c, 0x044d, 0x044e, 0x044f, 0x0457, 0x0459, 0x0461, 0x0801, 0x0804, 0x0807, 0x0809, 0x080a, 0x080c, 0x0810, 0x0812, 0x0813, 0x0814, 0x0816, 0x0818, 0x0819, 0x081a, 0x081d, 0x0820, 0x0827, 0x082c, 0x083e, 0x0843, 0x0860, 0x0861, 0x0C01, 0x0C04, 0x0c07, 0x0c09, 0x0c0a, 0x0c0c, 0x0c1a, 0x1001, 0x1004, 0x1007, 0x1009, 0x100a, 0x100c, 0x1401, 0x1404, 0x1407, 0x1409, 0x140a, 0x140c, 0x1801, 0x1809, 0x180a, 0x180c, 0x1C01, 0x1c09, 0x1c0a, 0x2001, 0x2009, 0x200a, 0x2401, 0x2409, 0x240a, 0x2801, 0x2809, 0x280a, 0x2C01, 0x2c09, 0x2c0a, 0x3001, 0x3009, 0x300a, 0x3401, 0x3409, 0x340a, 0x3801, 0x380a, 0x3C01, 0x3c0a, 0x4001, 0x400a, 0x440a, 0x480a, 0x4c0a, 0x500a }; for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.PlatformID == 3 && nr.EncodingID == 1) { bFound = true; bool bValidID = false; for (uint j=0; j<MSLangIDs.Length; j++) { if (nr.LanguageID == MSLangIDs[j]) { bValidID = true; break; } } if (!bValidID) { string s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = 0x" + nr.LanguageID.ToString("x4") + ", nameID = " + nr.NameID; v.Error(T.name_MSLanguageIDs, E.name_E_MSLanguageID, m_tag, s); bIDsOk = false; bRet = false; } } } } if (bFound && bIDsOk) { v.Pass(T.name_MSLanguageIDs, P.name_P_MSLanguageID, m_tag); } } if (v.PerformTest(T.name_unicode_length)) { bool bLengthsOk = true; for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.PlatformID == 0 || nr.PlatformID == 2 || // unicode or iso platform (nr.PlatformID == 3 && nr.EncodingID == 1)) // microsoft platform, unicode encoding { if ((nr.StringLength & 1) == 1) { string s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = " + nr.LanguageID + ", nameID = " + nr.NameID + ", length = " + nr.StringLength; v.Error(T.name_unicode_length, E.name_E_UnicodeLength, m_tag, s); bLengthsOk = false; bRet = false; } } } else { v.Warning(T.name_unicode_length, W._TEST_W_OtherErrorsInTable, m_tag); bLengthsOk = false; break; } } if (bLengthsOk) { v.Pass(T.name_unicode_length, P.name_P_UnicodeLength, m_tag); } } if (v.PerformTest(T.name_Postscript)) { bool bPostscriptOk = true; string sPostscriptMac = GetString(1, 0, 0, 6); if (sPostscriptMac != null) { if (sPostscriptMac.Length > 63) { v.Error(T.name_Postscript, E.name_E_Postscript_length, m_tag, "name string (1, 0, 0, 6) is " + sPostscriptMac.Length + " characters long"); bRet = false; bPostscriptOk = false; } for (int i=0; i<sPostscriptMac.Length; i++) { char c = sPostscriptMac[i]; if (c < 33 || c > 126 || c=='[' || c==']' || c=='(' || c==')' || c=='{' || c=='}' || c=='<' || c=='>' || c=='/' || c=='%') { v.Error(T.name_Postscript, E.name_E_Postscript_chars, m_tag, "name string (1, 0, 0, 6) contains an illegal character at index " + i); bRet = false; bPostscriptOk = false; } } } ushort nEncoding = 1; if (fontOwner.ContainsMsSymbolEncodedCmap()) { nEncoding = 0; } string sPostscriptMS = GetString(3, nEncoding, 0x409, 6); // ms if (sPostscriptMS != null) { if (sPostscriptMS.Length > 63) { v.Error(T.name_Postscript, E.name_E_Postscript_length, m_tag, "name string (3, " + nEncoding + ", 0x409, 6) is " + sPostscriptMS.Length + " characters long"); bRet = false; bPostscriptOk = false; } for (int i=0; i<sPostscriptMS.Length; i++) { char c = sPostscriptMS[i]; if (c < 33 || c > 126 || c=='[' || c==']' || c=='(' || c==')' || c=='{' || c=='}' || c=='<' || c=='>' || c=='/' || c=='%') { v.Error(T.name_Postscript, E.name_E_Postscript_chars, m_tag, "name string (3, " + nEncoding + ", 0x409, 6) contains an illegal character at index " + i); bRet = false; bPostscriptOk = false; } } } if (sPostscriptMac==null && sPostscriptMS!=null) { v.Error(T.name_Postscript, E.name_E_Postscript_missing, m_tag, "Mac Postscript string is missing, but MS Postscript string is present"); bRet = false; bPostscriptOk = false; } else if (sPostscriptMac!=null && sPostscriptMS==null) { v.Error(T.name_Postscript, E.name_E_Postscript_missing, m_tag, "MS Postscript string is missing, but Mac Postscript string is present"); bRet = false; bPostscriptOk = false; } if (sPostscriptMac!=null && sPostscriptMS!=null) { if (sPostscriptMac != sPostscriptMS) { v.Error(T.name_Postscript, E.name_E_Postscript_unequal, m_tag, "mac postscript = " + sPostscriptMac + ", MS postscript = " + sPostscriptMS ); bRet = false; bPostscriptOk = false; } } if (sPostscriptMac!=null && sPostscriptMS!=null && bPostscriptOk) { v.Pass(T.name_Postscript, P.name_P_Postscript, m_tag); } } if (v.PerformTest(T.name_Subfamily)) { string sStyle = GetStyleString(); if (sStyle != null) { Table_OS2 OS2Table = (Table_OS2)fontOwner.GetTable("OS/2"); if (OS2Table != null) { bool bStyleOk = true; string sStyleDetails = ""; string s = sStyle.ToLower(); bool bItalic = ((OS2Table.fsSelection & 0x01) != 0 ); bool bBold = ((OS2Table.fsSelection & 0x20) != 0 ); if (bItalic) { if (s.IndexOf("italic") == -1 && s.IndexOf("oblique") == -1) { bStyleOk = false; sStyleDetails = "OS/2.fsSelection italic bit is set, but subfamily string = '" + sStyle + "'"; } } else { if (s.IndexOf("italic") != -1 || s.IndexOf("oblique") != -1) { bStyleOk = false; sStyleDetails = "OS/2.fsSelection italic bit is clear, but subfamily string = '" + sStyle + "'"; } } if (bBold) { if (s.IndexOf("bold") == -1) { bStyleOk = false; sStyleDetails = "OS/2.fsSelection bold bit is set, but subfamily string = '" + sStyle + "'"; } } else { if (s.IndexOf("bold") != -1) { bStyleOk = false; sStyleDetails = "OS/2.fsSelection bold bit is clear, but subfamily string = '" + sStyle + "'"; } } if (bStyleOk) { v.Pass(T.name_Subfamily, P.name_P_subfamily, m_tag); } else { v.Warning(T.name_Subfamily, W.name_W_subfamily_style, m_tag, sStyleDetails); } } } } if (v.PerformTest(T.name_NoFormat14)) { bool bStringOK = true; for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null && nr.NameID == 19 && nr.PlatformID == 0 && nr.EncodingID == 5 ) { string sDetails = "name string(" + nr.PlatformID + ", " + nr.EncodingID + ", 0x" + nr.LanguageID.ToString("x4") + ", " + nr.NameID + ", offset=0x" + nr.StringOffset.ToString("x4") + ")"; v.Error( T.name_NoFormat14, E.name_E_NoFormat14, m_tag, sDetails ); bRet = false; bStringOK = false; } } if ( bStringOK ) { string sDetails = "PlatformID=0, EncodingID=5 is for " + "Variation Sequences (Format 14)"; v.Pass(T.name_NoFormat14, P.name_P_NoFormat14, m_tag, sDetails ); } } if (v.PerformTest(T.name_SampleString)) { Table_cmap cmapTable = (Table_cmap)fontOwner.GetTable("cmap"); if (cmapTable != null) { for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.NameID == 19) { if ( nr.PlatformID == 0 && nr.EncodingID == 5 ) { // Unicode platform encoding ID 5 can be // used for encodings in the 'cmap' table // but not for strings in the 'name' table. // It has already been flagged as an error, // so we will just skip it here. break; } Table_cmap.Subtable CmapSubTable = cmapTable.GetSubtable(nr.PlatformID, nr.EncodingID); if (CmapSubTable != null) { bool bStringOk = true; byte[] strbuf = GetEncodedString(nr); for (uint j=0; j<strbuf.Length;) { if (CmapSubTable.MapCharToGlyph(strbuf, j, true) == 0) { string sDetails = "name string(" + nr.PlatformID + ", " + nr.EncodingID + ", 0x" + nr.LanguageID.ToString("x4") + ", " + nr.NameID + "), character at index " + j + " is not mapped"; v.Error(T.name_SampleString, E.name_E_sample, m_tag, sDetails); bStringOk = false; bRet = false; break; } j += CmapSubTable.BytesInChar(strbuf, j); } if (bStringOk) { string sDetails = "name string(" + nr.PlatformID + ", " + nr.EncodingID + ", 0x" + nr.LanguageID.ToString("x4") + ", " + nr.NameID + ")"; v.Pass(T.name_SampleString, P.name_P_sample, m_tag, sDetails); } } } } } } } if (v.PerformTest(T.name_PreferredFamily)) { bool bFound = false; for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.NameID == 16) { string sPrefFam = this.GetString(nr.PlatformID, nr.EncodingID, nr.LanguageID, 16); string s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = " + nr.LanguageID + ", nameID = " + nr.NameID + ", \"" + sPrefFam + "\""; v.Info(T.name_PreferredFamily, I.name_I_Preferred_family_present, m_tag, s); bFound = true; } } } if (!bFound) { v.Info(T.name_PreferredFamily, I.name_I_Preferred_family_not_present, m_tag); } } if (v.PerformTest(T.name_PreferredSubfamily)) { bool bFound = false; for (uint i=0; i<NumberNameRecords; i++) { NameRecord nr = GetNameRecord(i); if (nr != null) { if (nr.NameID == 17) { string sPrefSubfam = this.GetString(nr.PlatformID, nr.EncodingID, nr.LanguageID, 17); string s = "platID = " + nr.PlatformID + ", encID = " + nr.EncodingID + ", langID = " + nr.LanguageID + ", nameID = " + nr.NameID + ", \"" + sPrefSubfam + "\""; v.Info(T.name_PreferredSubfamily, I.name_I_Preferred_subfamily_present, m_tag, s); bFound = true; } } } if (!bFound) { v.Info(T.name_PreferredSubfamily, I.name_I_Preferred_subfamily_not_present, m_tag); } } if (v.PerformTest(T.name_CopyrightConsistent)) { bool bCopyrightOk = true; // get mac roman english Copyright string if present string sMac = GetString(1, 0, 0, 0); // get windows 3,0 english Copyright string if present string sWin3_0 = GetString(3, 0, 1033, 0); // get windows 3,1 english Copyright string if present string sWin3_1 = GetString(3, 1, 1033, 0); // get windows 3,10 english Copyright string if present string sWin3_10 = GetString(3, 10, 1033, 0); // compare strings if (sMac != null) { if (sWin3_0 != null) { if (sWin3_0.CompareTo(sMac) != 0) { string sDetails = "(1,0,0,0)='" + sMac + "', (3,0,1033,0)='" + sWin3_0 + "'"; v.Warning(T.name_CopyrightConsistent, W.name_W_CopyrightInconsistent, m_tag, sDetails); bCopyrightOk = false; } } if (sWin3_1 != null) { if (sWin3_1.CompareTo(sMac) != 0) { string sDetails = "(1,0,0,0)='" + sMac + "', (3,1,1033,0)='" + sWin3_1 + "'"; v.Warning(T.name_CopyrightConsistent, W.name_W_CopyrightInconsistent, m_tag, sDetails); bCopyrightOk = false; } } if (sWin3_10 != null) { if (sWin3_10.CompareTo(sMac) != 0) { string sDetails = "(1,0,0,0)='" + sMac + "', (3,10,1033,0)='" + sWin3_10 + "'"; v.Warning(T.name_CopyrightConsistent, W.name_W_CopyrightInconsistent, m_tag, sDetails); bCopyrightOk = false; } } } if (sWin3_0 != null) { if (sWin3_1 != null) { if (sWin3_1.CompareTo(sWin3_0) != 0) { string sDetails = "(3,0,1033,0)='" + sWin3_0 + "', (3,1,1033,0)='" + sWin3_1 + "'"; v.Warning(T.name_CopyrightConsistent, W.name_W_CopyrightInconsistent, m_tag, sDetails); bCopyrightOk = false; } } if (sWin3_10 != null) { if (sWin3_10.CompareTo(sWin3_0) != 0) { string sDetails = "(3,0,1033,0)='" + sWin3_0 + "', (3,10,1033,0)='" + sWin3_10 + "'"; v.Warning(T.name_CopyrightConsistent, W.name_W_CopyrightInconsistent, m_tag, sDetails); bCopyrightOk = false; } } } if (sWin3_1 != null) { if (sWin3_10 != null) { if (sWin3_10.CompareTo(sWin3_1) != 0) { string sDetails = "(3,1,1033,0)='" + sWin3_1 + "', (3,10,1033,0)='" + sWin3_10 + "'"; v.Warning(T.name_CopyrightConsistent, W.name_W_CopyrightInconsistent, m_tag, sDetails); bCopyrightOk = false; } } } if (bCopyrightOk) { v.Pass(T.name_CopyrightConsistent, P.name_P_CopyrightConsistent, m_tag); } else { //bRet = false; } } if (v.PerformTest(T.name_TrademarkConsistent)) { bool bTrademarkOk = true; // get mac roman english Trademark string if present string sMac = GetString(1, 0, 0, 7); // get windows 3,0 english Trademark string if present string sWin3_0 = GetString(3, 0, 1033, 7); // get windows 3,1 english Trademark string if present string sWin3_1 = GetString(3, 1, 1033, 7); // get windows 3,10 english Trademark string if present string sWin3_10 = GetString(3, 10, 1033, 7); // compare strings if (sMac != null) { if (sWin3_0 != null) { if (sWin3_0.CompareTo(sMac) != 0) { string sDetails = "(1,0,0,7)='" + sMac + "', (3,0,1033,7)='" + sWin3_0 + "'"; v.Warning(T.name_TrademarkConsistent, W.name_W_TrademarkInconsistent, m_tag, sDetails); bTrademarkOk = false; } } if (sWin3_1 != null) { if (sWin3_1.CompareTo(sMac) != 0) { string sDetails = "(1,0,0,7)='" + sMac + "', (3,1,1033,7)='" + sWin3_1 + "'"; v.Warning(T.name_TrademarkConsistent, W.name_W_TrademarkInconsistent, m_tag, sDetails); bTrademarkOk = false; } } if (sWin3_10 != null) { if (sWin3_10.CompareTo(sMac) != 0) { string sDetails = "(1,0,0,7)='" + sMac + "', (3,10,1033,7)='" + sWin3_10 + "'"; v.Warning(T.name_TrademarkConsistent, W.name_W_TrademarkInconsistent, m_tag, sDetails); bTrademarkOk = false; } } } if (sWin3_0 != null) { if (sWin3_1 != null) { if (sWin3_1.CompareTo(sWin3_0) != 0) { string sDetails = "(3,0,1033,7)='" + sWin3_0 + "', (3,1,1033,7)='" + sWin3_1 + "'"; v.Warning(T.name_TrademarkConsistent, W.name_W_TrademarkInconsistent, m_tag, sDetails); bTrademarkOk = false; } } if (sWin3_10 != null) { if (sWin3_10.CompareTo(sWin3_0) != 0) { string sDetails = "(3,0,1033,7)='" + sWin3_0 + "', (3,10,1033,7)='" + sWin3_10 + "'"; v.Warning(T.name_TrademarkConsistent, W.name_W_TrademarkInconsistent, m_tag, sDetails); bTrademarkOk = false; } } } if (sWin3_1 != null) { if (sWin3_10 != null) { if (sWin3_10.CompareTo(sWin3_1) != 0) { string sDetails = "(3,1,1033,7)='" + sWin3_1 + "', (3,10,1033,7)='" + sWin3_10 + "'"; v.Warning(T.name_TrademarkConsistent, W.name_W_TrademarkInconsistent, m_tag, sDetails); bTrademarkOk = false; } } } if (bTrademarkOk) { v.Pass(T.name_TrademarkConsistent, P.name_P_TrademarkConsistent, m_tag); } else { //bRet = false; } } if (v.PerformTest(T.name_DescriptionConsistent)) { bool bDescriptionOk = true; // get mac roman english Description string if present string sMac = GetString(1, 0, 0, 10); // get windows 3,0 english Description string if present string sWin3_0 = GetString(3, 0, 1033, 10); // get windows 3,1 english Description string if present string sWin3_1 = GetString(3, 1, 1033, 10); // get windows 3,10 english Description string if present string sWin3_10 = GetString(3, 10, 1033, 10); // compare strings if (sMac != null) { if (sWin3_0 != null) { if (sWin3_0.CompareTo(sMac) != 0) { string sDetails = "(1,0,0,10)='" + sMac + "', (3,0,1033,10)='" + sWin3_0 + "'"; v.Warning(T.name_DescriptionConsistent, W.name_W_DescriptionInconsistent, m_tag, sDetails); bDescriptionOk = false; } } if (sWin3_1 != null) { if (sWin3_1.CompareTo(sMac) != 0) { string sDetails = "(1,0,0,10)='" + sMac + "', (3,1,1033,10)='" + sWin3_1 + "'"; v.Warning(T.name_DescriptionConsistent, W.name_W_DescriptionInconsistent, m_tag, sDetails); bDescriptionOk = false; } } if (sWin3_10 != null) { if (sWin3_10.CompareTo(sMac) != 0) { string sDetails = "(1,0,0,10)='" + sMac + "', (3,10,1033,10)='" + sWin3_10 + "'"; v.Warning(T.name_DescriptionConsistent, W.name_W_DescriptionInconsistent, m_tag, sDetails); bDescriptionOk = false; } } } if (sWin3_0 != null) { if (sWin3_1 != null) { if (sWin3_1.CompareTo(sWin3_0) != 0) { string sDetails = "(3,0,1033,10)='" + sWin3_0 + "', (3,1,1033,10)='" + sWin3_1 + "'"; v.Warning(T.name_DescriptionConsistent, W.name_W_DescriptionInconsistent, m_tag, sDetails); bDescriptionOk = false; } } if (sWin3_10 != null) { if (sWin3_10.CompareTo(sWin3_0) != 0) { string sDetails = "(3,0,1033,10)='" + sWin3_0 + "', (3,10,1033,10)='" + sWin3_10 + "'"; v.Warning(T.name_DescriptionConsistent, W.name_W_DescriptionInconsistent, m_tag, sDetails); bDescriptionOk = false; } } } if (sWin3_1 != null) { if (sWin3_10 != null) { if (sWin3_10.CompareTo(sWin3_1) != 0) { string sDetails = "(3,1,1033,10)='" + sWin3_1 + "', (3,10,1033,10)='" + sWin3_10 + "'"; v.Warning(T.name_DescriptionConsistent, W.name_W_DescriptionInconsistent, m_tag, sDetails); bDescriptionOk = false; } } } if (bDescriptionOk) { v.Pass(T.name_DescriptionConsistent, P.name_P_DescriptionConsistent, m_tag); } else { //bRet = false; } } return bRet; } } }
// // Collection.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; namespace Mono.Collections.Generic { public class Collection<T> : IList<T>, IList { internal T [] items; internal int size; int version; public int Count { get { return size; } } public T this [int index] { get { if (index >= size) throw new ArgumentOutOfRangeException (); return items [index]; } set { CheckIndex (index); if (index == size) throw new ArgumentOutOfRangeException (); OnSet (value, index); items [index] = value; } } bool ICollection<T>.IsReadOnly { get { return false; } } bool IList.IsFixedSize { get { return false; } } bool IList.IsReadOnly { get { return false; } } object IList.this [int index] { get { return this [index]; } set { CheckIndex (index); try { this [index] = (T) value; return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException (); } } int ICollection.Count { get { return Count; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } public Collection () { items = Empty<T>.Array; } public Collection (int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException (); items = new T [capacity]; } public Collection (ICollection<T> items) { this.items = new T [items.Count]; items.CopyTo (this.items, 0); this.size = this.items.Length; } public void Add (T item) { if (size == items.Length) Grow (1); OnAdd (item, size); items [size++] = item; version++; } public bool Contains (T item) { return IndexOf (item) != -1; } public int IndexOf (T item) { return Array.IndexOf (items, item, 0, size); } public void Insert (int index, T item) { CheckIndex (index); if (size == items.Length) Grow (1); OnInsert (item, index); Shift (index, 1); items [index] = item; version++; } public void RemoveAt (int index) { if (index < 0 || index >= size) throw new ArgumentOutOfRangeException (); var item = items [index]; OnRemove (item, index); Shift (index, -1); Array.Clear (items, size, 1); version++; } public bool Remove (T item) { var index = IndexOf (item); if (index == -1) return false; OnRemove (item, index); Shift (index, -1); Array.Clear (items, size, 1); version++; return true; } public void Clear () { OnClear (); Array.Clear (items, 0, size); size = 0; version++; } public void CopyTo (T [] array, int arrayIndex) { Array.Copy (items, 0, array, arrayIndex, size); } public T [] ToArray () { var array = new T [size]; Array.Copy (items, 0, array, 0, size); return array; } void CheckIndex (int index) { if (index < 0 || index > size) throw new ArgumentOutOfRangeException (); } void Shift (int start, int delta) { if (delta < 0) start -= delta; if (start < size) Array.Copy (items, start, items, start + delta, size - start); size += delta; if (delta < 0) Array.Clear (items, size, -delta); } protected virtual void OnAdd (T item, int index) { } protected virtual void OnInsert (T item, int index) { } protected virtual void OnSet (T item, int index) { } protected virtual void OnRemove (T item, int index) { } protected virtual void OnClear () { } internal virtual void Grow (int desired) { int new_size = size + desired; if (new_size <= items.Length) return; const int default_capacity = 4; new_size = System.Math.Max ( System.Math.Max (items.Length * 2, default_capacity), new_size); #if !CF Array.Resize (ref items, new_size); #else var array = new T [new_size]; Array.Copy (items, array, size); items = array; #endif } int IList.Add (object value) { try { Add ((T) value); return size - 1; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException (); } void IList.Clear () { Clear (); } bool IList.Contains (object value) { return ((IList) this).IndexOf (value) > -1; } int IList.IndexOf (object value) { try { return IndexOf ((T) value); } catch (InvalidCastException) { } catch (NullReferenceException) { } return -1; } void IList.Insert (int index, object value) { CheckIndex (index); try { Insert (index, (T) value); return; } catch (InvalidCastException) { } catch (NullReferenceException) { } throw new ArgumentException (); } void IList.Remove (object value) { try { Remove ((T) value); } catch (InvalidCastException) { } catch (NullReferenceException) { } } void IList.RemoveAt (int index) { RemoveAt (index); } void ICollection.CopyTo (Array array, int index) { Array.Copy (items, 0, array, index, size); } public Enumerator GetEnumerator () { return new Enumerator (this); } IEnumerator IEnumerable.GetEnumerator () { return new Enumerator (this); } IEnumerator<T> IEnumerable<T>.GetEnumerator () { return new Enumerator (this); } public struct Enumerator : IEnumerator<T>, IDisposable { Collection<T> collection; T current; int next; readonly int version; public T Current { get { return current; } } object IEnumerator.Current { get { CheckState (); if (next <= 0) throw new InvalidOperationException (); return current; } } internal Enumerator (Collection<T> collection) : this () { this.collection = collection; this.version = collection.version; } public bool MoveNext () { CheckState (); if (next < 0) return false; if (next < collection.size) { current = collection.items [next++]; return true; } next = -1; return false; } public void Reset () { CheckState (); next = 0; } void CheckState () { if (collection == null) throw new ObjectDisposedException (GetType ().FullName); if (version != collection.version) throw new InvalidOperationException (); } public void Dispose () { collection = null; } } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.RDS.Model { /// <summary> /// <para> Available option. </para> /// </summary> public class OptionGroupOption { private string name; private string description; private string engineName; private string majorEngineVersion; private string minimumRequiredMinorEngineVersion; private bool? portRequired; private int? defaultPort; private List<string> optionsDependedOn = new List<string>(); private bool? persistent; private bool? permanent; private List<OptionGroupOptionSetting> optionGroupOptionSettings = new List<OptionGroupOptionSetting>(); /// <summary> /// The name of the option. /// /// </summary> public string Name { get { return this.name; } set { this.name = value; } } /// <summary> /// Sets the Name property /// </summary> /// <param name="name">The value to set for the Name property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithName(string name) { this.name = name; return this; } // Check to see if Name property is set internal bool IsSetName() { return this.name != null; } /// <summary> /// The description of the option. /// /// </summary> public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Sets the Description property /// </summary> /// <param name="description">The value to set for the Description property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithDescription(string description) { this.description = description; return this; } // Check to see if Description property is set internal bool IsSetDescription() { return this.description != null; } /// <summary> /// Engine name that this option can be applied to. /// /// </summary> public string EngineName { get { return this.engineName; } set { this.engineName = value; } } /// <summary> /// Sets the EngineName property /// </summary> /// <param name="engineName">The value to set for the EngineName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithEngineName(string engineName) { this.engineName = engineName; return this; } // Check to see if EngineName property is set internal bool IsSetEngineName() { return this.engineName != null; } /// <summary> /// Indicates the major engine version that the option is available for. /// /// </summary> public string MajorEngineVersion { get { return this.majorEngineVersion; } set { this.majorEngineVersion = value; } } /// <summary> /// Sets the MajorEngineVersion property /// </summary> /// <param name="majorEngineVersion">The value to set for the MajorEngineVersion property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithMajorEngineVersion(string majorEngineVersion) { this.majorEngineVersion = majorEngineVersion; return this; } // Check to see if MajorEngineVersion property is set internal bool IsSetMajorEngineVersion() { return this.majorEngineVersion != null; } /// <summary> /// The minimum required engine version for the option to be applied. /// /// </summary> public string MinimumRequiredMinorEngineVersion { get { return this.minimumRequiredMinorEngineVersion; } set { this.minimumRequiredMinorEngineVersion = value; } } /// <summary> /// Sets the MinimumRequiredMinorEngineVersion property /// </summary> /// <param name="minimumRequiredMinorEngineVersion">The value to set for the MinimumRequiredMinorEngineVersion property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithMinimumRequiredMinorEngineVersion(string minimumRequiredMinorEngineVersion) { this.minimumRequiredMinorEngineVersion = minimumRequiredMinorEngineVersion; return this; } // Check to see if MinimumRequiredMinorEngineVersion property is set internal bool IsSetMinimumRequiredMinorEngineVersion() { return this.minimumRequiredMinorEngineVersion != null; } /// <summary> /// Specifies whether the option requires a port. /// /// </summary> public bool PortRequired { get { return this.portRequired ?? default(bool); } set { this.portRequired = value; } } /// <summary> /// Sets the PortRequired property /// </summary> /// <param name="portRequired">The value to set for the PortRequired property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithPortRequired(bool portRequired) { this.portRequired = portRequired; return this; } // Check to see if PortRequired property is set internal bool IsSetPortRequired() { return this.portRequired.HasValue; } /// <summary> /// If the option requires a port, specifies the default port for the option. /// /// </summary> public int DefaultPort { get { return this.defaultPort ?? default(int); } set { this.defaultPort = value; } } /// <summary> /// Sets the DefaultPort property /// </summary> /// <param name="defaultPort">The value to set for the DefaultPort property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithDefaultPort(int defaultPort) { this.defaultPort = defaultPort; return this; } // Check to see if DefaultPort property is set internal bool IsSetDefaultPort() { return this.defaultPort.HasValue; } /// <summary> /// List of all options that are prerequisites for this option. /// /// </summary> public List<string> OptionsDependedOn { get { return this.optionsDependedOn; } set { this.optionsDependedOn = value; } } /// <summary> /// Adds elements to the OptionsDependedOn collection /// </summary> /// <param name="optionsDependedOn">The values to add to the OptionsDependedOn collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithOptionsDependedOn(params string[] optionsDependedOn) { foreach (string element in optionsDependedOn) { this.optionsDependedOn.Add(element); } return this; } /// <summary> /// Adds elements to the OptionsDependedOn collection /// </summary> /// <param name="optionsDependedOn">The values to add to the OptionsDependedOn collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithOptionsDependedOn(IEnumerable<string> optionsDependedOn) { foreach (string element in optionsDependedOn) { this.optionsDependedOn.Add(element); } return this; } // Check to see if OptionsDependedOn property is set internal bool IsSetOptionsDependedOn() { return this.optionsDependedOn.Count > 0; } /// <summary> /// A persistent option cannot be removed from the option group once the option group is used, but this option can be removed from the db /// instance while modifying the related data and assigning another option group without this option. /// /// </summary> public bool Persistent { get { return this.persistent ?? default(bool); } set { this.persistent = value; } } /// <summary> /// Sets the Persistent property /// </summary> /// <param name="persistent">The value to set for the Persistent property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithPersistent(bool persistent) { this.persistent = persistent; return this; } // Check to see if Persistent property is set internal bool IsSetPersistent() { return this.persistent.HasValue; } /// <summary> /// A permanent option cannot be removed from the option group once the option group is used, and it cannot be removed from the db instance /// after assigning an option group with this permanent option. /// /// </summary> public bool Permanent { get { return this.permanent ?? default(bool); } set { this.permanent = value; } } /// <summary> /// Sets the Permanent property /// </summary> /// <param name="permanent">The value to set for the Permanent property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithPermanent(bool permanent) { this.permanent = permanent; return this; } // Check to see if Permanent property is set internal bool IsSetPermanent() { return this.permanent.HasValue; } /// <summary> /// Specifies the option settings that are available (and the default value) for each option in an option group. /// /// </summary> public List<OptionGroupOptionSetting> OptionGroupOptionSettings { get { return this.optionGroupOptionSettings; } set { this.optionGroupOptionSettings = value; } } /// <summary> /// Adds elements to the OptionGroupOptionSettings collection /// </summary> /// <param name="optionGroupOptionSettings">The values to add to the OptionGroupOptionSettings collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithOptionGroupOptionSettings(params OptionGroupOptionSetting[] optionGroupOptionSettings) { foreach (OptionGroupOptionSetting element in optionGroupOptionSettings) { this.optionGroupOptionSettings.Add(element); } return this; } /// <summary> /// Adds elements to the OptionGroupOptionSettings collection /// </summary> /// <param name="optionGroupOptionSettings">The values to add to the OptionGroupOptionSettings collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public OptionGroupOption WithOptionGroupOptionSettings(IEnumerable<OptionGroupOptionSetting> optionGroupOptionSettings) { foreach (OptionGroupOptionSetting element in optionGroupOptionSettings) { this.optionGroupOptionSettings.Add(element); } return this; } // Check to see if OptionGroupOptionSettings property is set internal bool IsSetOptionGroupOptionSettings() { return this.optionGroupOptionSettings.Count > 0; } } }
namespace Zutatensuppe.DiabloInterface.Gui.Controls { using System; using System.Collections.Generic; using System.Drawing; using System.Reflection; using System.Windows.Forms; using Zutatensuppe.D2Reader.Models; using Zutatensuppe.DiabloInterface.Lib; class VerticalLayout : AbstractLayout { static readonly ILogger Logger = Logging.CreateLogger(MethodBase.GetCurrentMethod().DeclaringType); private FlowLayoutPanel outerLeftRightPanel; private FlowLayoutPanel panelRuneDisplay; private TableLayoutPanel table; public VerticalLayout(IDiabloInterface di) { this.di = di; RegisterServiceEventHandlers(); InitializeComponent(); Load += (sender, e) => UpdateConfig(di.configService.CurrentConfig); // Clean up events when disposed because services outlive us. Disposed += (sender, e) => UnregisterServiceEventHandlers(); Logger.Info("Creating vertical layout."); } protected override Panel RuneLayoutPanel => panelRuneDisplay; protected void InitializeComponent() { Add("name", new string('W', 15), (ApplicationConfig s) => Tuple.Create(s.DisplayName, s.ColorName, s.FontSizeTitle), "{}"); Add("life", "9999/9999", (ApplicationConfig s) => Tuple.Create(s.DisplayLife, s.ColorLife, s.FontSize), "LIFE: {}/{}"); Add("mana", "9999/9999", (ApplicationConfig s) => Tuple.Create(s.DisplayMana, s.ColorMana, s.FontSize), "MANA: {}/{}"); Add("hc_sc", "HARDCORE", (ApplicationConfig s) => Tuple.Create(s.DisplayHardcoreSoftcore, s.ColorHardcoreSoftcore, s.FontSize), "{}"); Add("exp_classic", "EXPANSION", (ApplicationConfig s) => Tuple.Create(s.DisplayExpansionClassic, s.ColorExpansionClassic, s.FontSize), "{}"); Add("playersx", "8", (ApplicationConfig s) => Tuple.Create(s.DisplayPlayersX, s.ColorPlayersX, s.FontSize), "/players {}"); Add("seed", "4294967295", (ApplicationConfig s) => Tuple.Create(s.DisplaySeed, s.ColorSeed, s.FontSize), "SEED: {}"); Add("deaths", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayDeathCounter, s.ColorDeaths, s.FontSize), "DEATHS: {}"); Add("runs", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayGameCounter, s.ColorGameCounter, s.FontSize), "RUNS: {}"); Add("chars", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayCharCounter, s.ColorCharCounter, s.FontSize), "CHARS: {}"); Add("gold", "2500000", (ApplicationConfig s) => Tuple.Create(s.DisplayGold, s.ColorGold, s.FontSize), "GOLD: {}"); Add("mf", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayMagicFind, s.ColorMagicFind, s.FontSize), "MF:", "{}"); Add("monstergold", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayMonsterGold, s.ColorMonsterGold, s.FontSize), "EMG:", "{}"); Add("atd", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayAttackerSelfDamage, s.ColorAttackerSelfDamage, s.FontSize), "ATD:", "{}"); Add("lvl", "99", (ApplicationConfig s) => Tuple.Create(s.DisplayLevel, s.ColorLevel, s.FontSize), "LVL:", "{}"); Add("str", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayBaseStats, s.ColorBaseStats, s.FontSize), "STR:", "{}"); Add("vit", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayBaseStats, s.ColorBaseStats, s.FontSize), "VIT:", "{}"); Add("dex", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayBaseStats, s.ColorBaseStats, s.FontSize), "DEX:", "{}"); Add("ene", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayBaseStats, s.ColorBaseStats, s.FontSize), "ENE:", "{}"); Add("ias", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayAdvancedStats, s.ColorAdvancedStats, s.FontSize), "IAS:", "{}"); Add("frw", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayAdvancedStats, s.ColorAdvancedStats, s.FontSize), "FRW:", "{}"); Add("fcr", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayAdvancedStats, s.ColorAdvancedStats, s.FontSize), "FCR:", "{}"); Add("fhr", "999", (ApplicationConfig s) => Tuple.Create(s.DisplayAdvancedStats, s.ColorAdvancedStats, s.FontSize), "FHR:", "{}"); Add("cold", "100", (ApplicationConfig s) => Tuple.Create(s.DisplayResistances, s.ColorColdRes, s.FontSize), "COLD:", "{}"); Add("ligh", "100", (ApplicationConfig s) => Tuple.Create(s.DisplayResistances, s.ColorLightningRes, s.FontSize), "LIGH:", "{}"); Add("pois", "100", (ApplicationConfig s) => Tuple.Create(s.DisplayResistances, s.ColorPoisonRes, s.FontSize), "POIS:", "{}"); Add("fire", "100", (ApplicationConfig s) => Tuple.Create(s.DisplayResistances, s.ColorFireRes, s.FontSize), "FIRE:", "{}"); Add("norm", "100", (ApplicationConfig s) => Tuple.Create(s.DisplayDifficultyPercentages, s.ColorDifficultyPercentages, s.FontSize), "NORM:", "{}%"); Add("nm", "100", (ApplicationConfig s) => Tuple.Create(s.DisplayDifficultyPercentages, s.ColorDifficultyPercentages, s.FontSize), "NM:", "{}%"); Add("hell", "100", (ApplicationConfig s) => Tuple.Create(s.DisplayDifficultyPercentages, s.ColorDifficultyPercentages, s.FontSize), "HELL:", "{}%"); table = new TableLayoutPanel(); table.SuspendLayout(); table.AutoSize = true; table.ColumnCount = 2; table.ColumnStyles.Add(new ColumnStyle()); table.ColumnStyles.Add(new ColumnStyle()); table.RowCount = 0; foreach (KeyValuePair<string, Def> pair in def) { table.RowCount++; table.RowStyles.Add(new RowStyle(SizeType.AutoSize)); for (int i = 0; i < pair.Value.labels.Length; i++) { table.Controls.Add(pair.Value.labels[i], i, table.RowCount - 1); if (i > 0) { pair.Value.labels[i].TextAlign = ContentAlignment.TopRight; } } if (pair.Value.labels.Length == 1) { table.SetColumnSpan(pair.Value.labels[0], table.ColumnCount); } } table.ResumeLayout(false); table.PerformLayout(); panelRuneDisplay = new FlowLayoutPanel(); panelRuneDisplay.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; panelRuneDisplay.AutoSize = true; panelRuneDisplay.AutoSizeMode = AutoSizeMode.GrowAndShrink; panelRuneDisplay.MaximumSize = new Size(28, 0); panelRuneDisplay.MinimumSize = new Size(28, 28); outerLeftRightPanel = new FlowLayoutPanel(); outerLeftRightPanel.SuspendLayout(); outerLeftRightPanel.AutoSize = true; outerLeftRightPanel.AutoSizeMode = AutoSizeMode.GrowAndShrink; outerLeftRightPanel.Controls.Add(panelRuneDisplay); outerLeftRightPanel.Controls.Add(table); SuspendLayout(); AutoScaleDimensions = new SizeF(6F, 13F); AutoScaleMode = AutoScaleMode.Font; AutoSize = true; AutoSizeMode = AutoSizeMode.GrowAndShrink; Margin = new Padding(0); BackColor = Color.Black; Controls.Add(this.outerLeftRightPanel); outerLeftRightPanel.ResumeLayout(false); outerLeftRightPanel.PerformLayout(); ResumeLayout(false); PerformLayout(); RunePanels = new[] { panelRuneDisplay }; } protected override void UpdateLabels(Character player, Quests quests, Game game) { UpdateLabel("name", player.Name); UpdateLabel("life", new string[] { "" + player.Life, "" + player.LifeMax }); UpdateLabel("mana", new string[] { "" + player.Mana, "" + player.ManaMax }); UpdateLabel("hc_sc", player.IsHardcore ? "HARDCORE" : "SOFTCORE"); UpdateLabel("exp_classic", player.IsExpansion ? "EXPANSION" : "CLASSIC"); UpdateLabel("playersx", game.PlayersX); UpdateLabel("seed", game.Seed, game.SeedIsArg); UpdateLabel("deaths", player.Deaths); UpdateLabel("runs", (int) game.GameCount); UpdateLabel("chars", (int) game.CharCount); UpdateLabel("gold", player.Gold + player.GoldStash); UpdateLabel("mf", player.MagicFind); UpdateLabel("monstergold", player.MonsterGold); UpdateLabel("atd", player.AttackerSelfDamage); UpdateLabel("lvl", player.Level); UpdateLabel("str", player.Strength); UpdateLabel("vit", player.Vitality); UpdateLabel("dex", player.Dexterity); UpdateLabel("ene", player.Energy); UpdateLabel("ias", realFrwIas ? player.RealIAS() : player.IncreasedAttackSpeed); UpdateLabel("frw", realFrwIas ? player.RealFRW() : player.FasterRunWalk); UpdateLabel("fcr", player.FasterCastRate); UpdateLabel("fhr", player.FasterHitRecovery); UpdateLabel("cold", player.ColdResist); UpdateLabel("ligh", player.LightningResist); UpdateLabel("pois", player.PoisonResist); UpdateLabel("fire", player.FireResist); UpdateLabel("norm", $@"{quests.ProgressByDifficulty(GameDifficulty.Normal) * 100:0}"); UpdateLabel("nm", $@"{quests.ProgressByDifficulty(GameDifficulty.Nightmare) * 100:0}"); UpdateLabel("hell", $@"{quests.ProgressByDifficulty(GameDifficulty.Hell) * 100:0}"); } protected override void UpdateConfig(ApplicationConfig config) { var padding = new Padding(0, 0, 0, config.VerticalLayoutPadding); realFrwIas = config.DisplayRealFrwIas; BackColor = config.ColorBackground; int w_full = 0; int w_left = 0; int w_right = 0; foreach (KeyValuePair<string, Def> pair in def) { Tuple<bool, Color, int> t = pair.Value.settings(config); var enabled = t.Item1; Font font = CreateFont(config.FontName, t.Item3); var labels = pair.Value.labels; var color = t.Item2; var mstr = pair.Value.maxString; var defaults = pair.Value.defaults; pair.Value.enabled = enabled; int i = 0; foreach (var l in labels) { l.Visible = enabled; if (enabled) { l.Font = font; l.ForeColor = color; var teststr = defaults[l].Replace("{}", mstr); l.Size = MeasureText(teststr, l); l.Margin = padding; if (labels.Length == 1) w_full = Math.Max(l.Size.Width, w_full); else if (i == 0) w_left = Math.Max(l.Size.Width, w_left); else w_right = Math.Max(l.Size.Width, w_right); i++; } } } foreach (KeyValuePair<string, Def> pair in def) { int i = 0; foreach (var l in pair.Value.labels) { if (pair.Value.labels.Length == 1) l.Size = new Size(w_full, l.Size.Height); else if (i == 0) l.Size = new Size(w_left, l.Size.Height); else l.Size = new Size(w_right, l.Size.Height); i++; } } if (!config.DisplayRunes) panelRuneDisplay.Hide(); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using Microsoft.Extensions.Options; using Moq; using NPoco; using NUnit.Framework; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Infrastructure.Persistence.Mappers; using Umbraco.Cms.Infrastructure.Persistence.SqlSyntax; using Umbraco.Cms.Tests.Common.TestHelpers; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.Persistence.NPocoTests { [TestFixture] public class NPocoSqlTemplateTests { [Test] public void SqlTemplates() { var sqlContext = new SqlContext(new SqlServerSyntaxProvider(Options.Create(new GlobalSettings())), DatabaseType.SqlServer2012, Mock.Of<IPocoDataFactory>()); var sqlTemplates = new SqlTemplates(sqlContext); // this can be used for queries that we know we'll use a *lot* and // want to cache as a (static) template for ever, and ever - note // that using a MemoryCache would allow us to set a size limit, or // something equivalent, to reduce risk of memory explosion Sql<ISqlContext> sql = sqlTemplates.Get("xxx", s => s .SelectAll() .From("zbThing1") .Where("id=@id", new { id = SqlTemplate.Arg("id") })).Sql(new { id = 1 }); Sql<ISqlContext> sql2 = sqlTemplates.Get("xxx", x => throw new InvalidOperationException("Should be cached.")).Sql(1); Sql<ISqlContext> sql3 = sqlTemplates.Get("xxx", x => throw new InvalidOperationException("Should be cached.")).Sql(new { id = 1 }); } [Test] public void SqlTemplateArgs() { var mappers = new NPoco.MapperCollection { new NullableDateMapper() }; var factory = new FluentPocoDataFactory((type, iPocoDataFactory) => new PocoDataBuilder(type, mappers).Init()); var sqlContext = new SqlContext(new SqlServerSyntaxProvider(Options.Create(new GlobalSettings())), DatabaseType.SQLCe, factory); var sqlTemplates = new SqlTemplates(sqlContext); const string sqlBase = "SELECT [zbThing1].[id] AS [Id], [zbThing1].[name] AS [Name] FROM [zbThing1] WHERE "; SqlTemplate template = sqlTemplates.Get("sql1", s => s.Select<Thing1Dto>().From<Thing1Dto>() .Where<Thing1Dto>(x => x.Name == SqlTemplate.Arg<string>("value"))); Sql<ISqlContext> sql = template.Sql("foo"); Assert.AreEqual(sqlBase + "(([zbThing1].[name] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual("foo", sql.Arguments[0]); sql = template.Sql(123); Assert.AreEqual(sqlBase + "(([zbThing1].[name] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual(123, sql.Arguments[0]); template = sqlTemplates.Get("sql2", s => s.Select<Thing1Dto>().From<Thing1Dto>() .Where<Thing1Dto>(x => x.Name == SqlTemplate.Arg<string>("value"))); sql = template.Sql(new { value = "foo" }); Assert.AreEqual(sqlBase + "(([zbThing1].[name] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual("foo", sql.Arguments[0]); sql = template.Sql(new { value = 123 }); Assert.AreEqual(sqlBase + "(([zbThing1].[name] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual(123, sql.Arguments[0]); Assert.Throws<InvalidOperationException>(() => template.Sql(new { xvalue = 123 })); Assert.Throws<InvalidOperationException>(() => template.Sql(new { value = 123, xvalue = 456 })); var i = 666; template = sqlTemplates.Get("sql3", s => s.Select<Thing1Dto>().From<Thing1Dto>() .Where<Thing1Dto>(x => x.Id == i)); sql = template.Sql("foo"); Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual("foo", sql.Arguments[0]); sql = template.Sql(123); Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual(123, sql.Arguments[0]); // but we cannot name them, because the arg name is the value of "i" // so we have to explicitely create the argument template = sqlTemplates.Get("sql4", s => s.Select<Thing1Dto>().From<Thing1Dto>() .Where<Thing1Dto>(x => x.Id == SqlTemplate.Arg<int>("i"))); sql = template.Sql("foo"); Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual("foo", sql.Arguments[0]); sql = template.Sql(123); Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual(123, sql.Arguments[0]); // and thanks to a patched visitor, this now works sql = template.Sql(new { i = "foo" }); Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual("foo", sql.Arguments[0]); sql = template.Sql(new { i = 123 }); Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual(123, sql.Arguments[0]); Assert.Throws<InvalidOperationException>(() => template.Sql(new { j = 123 })); Assert.Throws<InvalidOperationException>(() => template.Sql(new { i = 123, j = 456 })); // now with more arguments template = sqlTemplates.Get("sql4a", s => s.Select<Thing1Dto>().From<Thing1Dto>() .Where<Thing1Dto>(x => x.Id == SqlTemplate.Arg<int>("i") && x.Name == SqlTemplate.Arg<string>("name"))); sql = template.Sql(0, 1); Assert.AreEqual(sqlBase + "((([zbThing1].[id] = @0) AND ([zbThing1].[name] = @1)))", sql.SQL.NoCrLf()); Assert.AreEqual(2, sql.Arguments.Length); Assert.AreEqual(0, sql.Arguments[0]); Assert.AreEqual(1, sql.Arguments[1]); template = sqlTemplates.Get("sql4b", s => s.Select<Thing1Dto>().From<Thing1Dto>() .Where<Thing1Dto>(x => x.Id == SqlTemplate.Arg<int>("i")) .Where<Thing1Dto>(x => x.Name == SqlTemplate.Arg<string>("name"))); sql = template.Sql(0, 1); Assert.AreEqual(sqlBase + "(([zbThing1].[id] = @0)) AND (([zbThing1].[name] = @1))", sql.SQL.NoCrLf()); Assert.AreEqual(2, sql.Arguments.Length); Assert.AreEqual(0, sql.Arguments[0]); Assert.AreEqual(1, sql.Arguments[1]); // works, magic template = sqlTemplates.Get("sql5", s => s.Select<Thing1Dto>().From<Thing1Dto>() .WhereIn<Thing1Dto>(x => x.Id, SqlTemplate.ArgIn<int>("i"))); sql = template.Sql("foo"); Assert.AreEqual(sqlBase + "([zbThing1].[id] IN (@0))", sql.SQL.NoCrLf()); Assert.AreEqual(1, sql.Arguments.Length); Assert.AreEqual("foo", sql.Arguments[0]); sql = template.Sql(new[] { 1, 2, 3 }); Assert.AreEqual(sqlBase + "([zbThing1].[id] IN (@0,@1,@2))", sql.SQL.NoCrLf()); Assert.AreEqual(3, sql.Arguments.Length); Assert.AreEqual(1, sql.Arguments[0]); Assert.AreEqual(2, sql.Arguments[1]); Assert.AreEqual(3, sql.Arguments[2]); template = sqlTemplates.Get("sql5a", s => s.Select<Thing1Dto>().From<Thing1Dto>() .WhereIn<Thing1Dto>(x => x.Id, SqlTemplate.ArgIn<int>("i")) .Where<Thing1Dto>(x => x.Name == SqlTemplate.Arg<string>("name"))); sql = template.Sql("foo", "bar"); Assert.AreEqual(sqlBase + "([zbThing1].[id] IN (@0)) AND (([zbThing1].[name] = @1))", sql.SQL.NoCrLf()); Assert.AreEqual(2, sql.Arguments.Length); Assert.AreEqual("foo", sql.Arguments[0]); Assert.AreEqual("bar", sql.Arguments[1]); sql = template.Sql(new[] { 1, 2, 3 }, "bar"); Assert.AreEqual(sqlBase + "([zbThing1].[id] IN (@0,@1,@2)) AND (([zbThing1].[name] = @3))", sql.SQL.NoCrLf()); Assert.AreEqual(4, sql.Arguments.Length); Assert.AreEqual(1, sql.Arguments[0]); Assert.AreEqual(2, sql.Arguments[1]); Assert.AreEqual(3, sql.Arguments[2]); Assert.AreEqual("bar", sql.Arguments[3]); // note however that using WhereIn in a template means that the SQL is going // to be parsed and arguments are going to be expanded etc - it *may* be a better // idea to just add the WhereIn to a templated, immutable SQL template // more fun... template = sqlTemplates.Get("sql6", s => s.Select<Thing1Dto>().From<Thing1Dto>() // do NOT do this, this is NOT a visited expression //// .Append(" AND whatever=@0", SqlTemplate.Arg<string>("j")) // does not work anymore - due to proper TemplateArg //// instead, directly name the argument ////.Append("AND whatever=@0", "j") ////.Append("AND whatever=@0", "k") // instead, explicitely create the argument .Append("AND whatever=@0", SqlTemplate.Arg("j")) .Append("AND whatever=@0", SqlTemplate.Arg("k"))); sql = template.Sql(new { j = new[] { 1, 2, 3 }, k = "oops" }); Assert.AreEqual(sqlBase.TrimEnd("WHERE ") + "AND whatever=@0,@1,@2 AND whatever=@3", sql.SQL.NoCrLf()); Assert.AreEqual(4, sql.Arguments.Length); Assert.AreEqual(1, sql.Arguments[0]); Assert.AreEqual(2, sql.Arguments[1]); Assert.AreEqual(3, sql.Arguments[2]); Assert.AreEqual("oops", sql.Arguments[3]); } [TableName("zbThing1")] [PrimaryKey("id", AutoIncrement = false)] [ExplicitColumns] public class Thing1Dto { [Column("id")] public int Id { get; set; } [Column("name")] public string Name { get; set; } } } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009, 2013 Oracle and/or its affiliates. All rights reserved. * */ using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using BerkeleyDB.Internal; namespace BerkeleyDB { /// <summary> /// A class representing a key or data item in a Berkeley DB database /// </summary> public class DatabaseEntry : IDisposable{ internal DBT dbt; /// <summary> /// The byte buffer /// </summary> protected byte[] _data; internal static DBT getDBT(DatabaseEntry ent) { return ent == null ? null : ent.dbt; } internal static DatabaseEntry fromDBT(DBT dbt) { if (dbt.app_data != null) return dbt.app_data; else return new DatabaseEntry(dbt); } private DatabaseEntry(DBT dbtp) { dbt = dbtp; Data = (byte[])dbtp.data.Clone(); } /// <summary> /// Create a new, empty DatabaseEntry object. /// </summary> public DatabaseEntry() { dbt = new DBT(); if (!this.GetType().IsGenericType) dbt.app_data = this; } /// <summary> /// Create a new DatabaseEntry object, with the specified data /// </summary> /// <param name="data">The new object's <see cref="Data"/></param> public DatabaseEntry(byte[] data) : this() { Data = data; } /// <summary> /// Create a new partial DatabaseEntry object. /// </summary> /// <param name="offset"> /// The offset of the partial record being read or written by the /// application, in bytes /// </param> /// <param name="len"> /// The byte length of the partial record being read or written /// by the application /// </param> public DatabaseEntry(uint offset, uint len) : this() { dbt.doff = offset; dbt.dlen = len; dbt.flags |= DbConstants.DB_DBT_PARTIAL; } /// <summary> /// Create a new partial DatabaseEntry object, with the specified data /// </summary> /// <param name="data"> /// Byte array wrapped by the DatabaseEntry /// </param> /// <param name="offset"> /// The offset of the partial record being read or written by the /// application, in bytes /// </param> /// <param name="len"> /// The byte length of the partial record being read or written /// by the application /// </param> public DatabaseEntry(byte[] data, uint offset, uint len) : this() { Data = data; dbt.doff = offset; dbt.dlen = len; dbt.flags |= DbConstants.DB_DBT_PARTIAL; } /// <summary> /// The byte string stored in or retrieved from a database /// </summary> public byte[] Data { /* * Data to be stored in the DB or has been retrieved from the DB. We * keep it in C#'s managed memory here, dbt_usercopy will copy it * to/from the library as needed. Need to set the size of the DBT in * the C library so that dbt_usercopy knows there's data to copy. */ get { return _data; } set { _data = value; dbt.size = value == null ? 0 : (uint)value.Length; } } /// <summary> /// Set this DatabaseEntry as read only - that is Berkeley DB will not /// alter the entry. /// </summary> public bool ReadOnly { get { return (flags & DbConstants.DB_DBT_READONLY) != 0; } set { if (value) flags |= DbConstants.DB_DBT_READONLY; else flags &= ~DbConstants.DB_DBT_READONLY; } } /// <summary> /// Whether the DatabaseEntry is partial record. /// </summary> public bool Partial { get { return (dbt.flags & DbConstants.DB_DBT_PARTIAL) != 0; } set { if (value == true) dbt.flags |= DbConstants.DB_DBT_PARTIAL; else dbt.flags &= ~DbConstants.DB_DBT_PARTIAL; } } /// <summary> /// The byte length of the partial record being read or written by /// the application /// </summary> public uint PartialLen { get { return dbt.dlen; } set { dbt.dlen = value; } } /// <summary> /// The offset of the partial record being read or written by the /// application, in bytes. /// </summary> public uint PartialOffset { get { return dbt.doff; } set { dbt.doff = value; } } internal byte[] UserData { get { return dbt.data; } set { dbt.data = value; ulen = (uint)value.Length; flags &= ~DbConstants.DB_DBT_USERCOPY; flags |= DbConstants.DB_DBT_USERMEM; } } /// <summary> /// Release the resources held by the underlying C library. /// </summary> public virtual void Dispose() { dbt.Dispose(); } /* * Copy between the C# byte array and the C library's void * as needed. * The library will call this method when it needs data from us or has * data to give us. This prevents us from needing to copy all data in * and all data out. The callback to this method gets set when the * DatabaseEnvironment is created (or the Database if created w/o an * environment.) */ internal static int dbt_usercopy(IntPtr dbtp, uint offset, IntPtr buf, uint size, uint flags) { DBT dbt = new DBT(dbtp, false); DatabaseEntry ent = dbt.app_data; if (flags == DbConstants.DB_USERCOPY_GETDATA) Marshal.Copy(ent.Data, 0, buf, (int)size); else { /* * If the offset is zero, we're writing a new buffer and can * simply allocate byte array. If the offset is not zero, * however, we are appending to the exisiting array. Since we * can't extend it, we have to allocate a new one and copy. * * Our caller is setting dbt.size, so set ent._data directly, * since ent.Data would overwrite dbt.size. */ if (offset != 0) { byte[] t = new byte[ent.Data.Length + (int)size]; ent.Data.CopyTo(t, 0); ent._data = t; } else ent._data = new byte[(int)size]; Marshal.Copy(buf, ent.Data, (int)offset, (int)size); } return 0; } internal uint ulen { get { return dbt.ulen; } set { dbt.ulen = value; } } internal uint flags { get { return dbt.flags; } set { dbt.flags = value; } } internal uint size { get { return dbt.size; } set { dbt.size = value; } } } }
using System; using System.IO; using NUnit.Framework; using SIL.IO; using SIL.PlatformUtilities; namespace SIL.Tests.IO { [TestFixture] class FileLocationUtilitiesTests { [Test] public void GetFileDistributedWithApplication_MultipleParts_FindsCorrectly() { var path = FileLocationUtilities.GetFileDistributedWithApplication("DirectoryForTests", "SampleFileForTests.txt"); Assert.That(File.Exists(path)); } [Test] public void GetDirectoryDistributedWithApplication_MultipleParts_FindsCorrectly() { var path = FileLocationUtilities.GetDirectoryDistributedWithApplication("DirectoryForTests"); Assert.That(Directory.Exists(path)); } [Test] public void GetDirectoryDistributedWithApplication_WhenFails_ReportsAllTried() { try { FileLocationUtilities.GetDirectoryDistributedWithApplication("LookHere", "ThisWillNotExist"); } catch (ArgumentException ex) { Assert.That(ex.Message, Does.Contain(Path.Combine("LookHere", "ThisWillNotExist"))); Assert.That(ex.Message, Does.Contain(FileLocationUtilities.DirectoryOfApplicationOrSolution)); Assert.That(ex.Message, Does.Contain("DistFiles")); Assert.That(ex.Message, Does.Contain("src")); } } [Test] public void DirectoryOfApplicationOrSolution_OnDevMachine_FindsOutputDirectory() { var path = FileLocationUtilities.DirectoryOfTheApplicationExecutable; Assert.That(Directory.Exists(path)); Assert.That(path.Contains("output")); } [Test] public void LocateInProgramFiles_SendInvalidProgramNoDeepSearch_ReturnsNull() { Assert.IsNull(FileLocationUtilities.LocateInProgramFiles("blah.exe", false)); } // 12 SEP 2013, Phil Hopper: This test not valid on Mono. [Test] [Platform(Exclude = "Unix")] [Category("SkipOnTeamCity;KnownMonoIssue")] public void LocateInProgramFiles_SendValidProgramNoDeepSearch_ReturnsNull() { Assert.IsNull(FileLocationUtilities.LocateInProgramFiles("msinfo32.exe", false)); } [Test] public void LocateInProgramFiles_SendValidProgramDeepSearch_ReturnsProgramPath() { var findFile = (Platform.IsMono ? "bash" : "msinfo32.exe"); Assert.IsNotNull(FileLocationUtilities.LocateInProgramFiles(findFile, true)); } [Test] public void LocateInProgramFiles_SendValidProgramDeepSearch_SubFolderSpecified_ReturnsProgramPath() { var findFile = (Platform.IsMono ? "bash" : "msinfo32.exe"); // this will work on Mono because it ignores the subFoldersToSearch parameter Assert.IsNotNull(FileLocationUtilities.LocateInProgramFiles(findFile, true, "Common Files")); } [Test] public void LocateInProgramFiles_SendInValidSubFolder_DoesNotThrow() { var findFile = (Platform.IsMono ? "bash" : "msinfo32.exe"); Assert.DoesNotThrow(() => FileLocationUtilities.LocateInProgramFiles(findFile, true, "!~@blah")); } [Test] [Platform(Include = "Linux")] public void LocateInProgramFiles_DeepSearch_FindsFileInSubdir() { // This simulates finding RAMP which is installed as /opt/RAMP/ramp. We can't put // anything in /opt for testing, so we add our tmp directory to the path. // Setup var simulatedOptDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var pathVariable = Environment.GetEnvironmentVariable("PATH"); try { Directory.CreateDirectory(simulatedOptDir); Directory.CreateDirectory(Path.Combine(simulatedOptDir, "RAMP")); var file = Path.Combine(simulatedOptDir, "RAMP", "ramp"); File.WriteAllText(file, "Simulated RAMP starter"); Environment.SetEnvironmentVariable("PATH", $"{simulatedOptDir}{Path.PathSeparator}{pathVariable}"); // Exercise/Verify Assert.That(FileLocationUtilities.LocateInProgramFiles("ramp", true), Is.EqualTo(file)); } finally { try { Environment.SetEnvironmentVariable("PATH", pathVariable); Directory.Delete(simulatedOptDir, true); } catch { // just ignore } } } [Test] [Platform(Include = "Linux")] public void LocateInProgramFiles_ShallowSearch_FindsNothing() { // This simulates finding RAMP which is installed as /opt/RAMP/ramp. We can't put // anything in /opt for testing, so we add our tmp directory to the path. // Setup var simulatedOptDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var pathVariable = Environment.GetEnvironmentVariable("PATH"); try { Directory.CreateDirectory(simulatedOptDir); Directory.CreateDirectory(Path.Combine(simulatedOptDir, "RAMP")); var file = Path.Combine(simulatedOptDir, "RAMP", "ramp"); File.WriteAllText(file, "Simulated RAMP starter"); Environment.SetEnvironmentVariable("PATH", $"{simulatedOptDir}{Path.PathSeparator}{pathVariable}"); // Exercise/Verify Assert.That(FileLocationUtilities.LocateInProgramFiles("ramp", false), Is.Null); } finally { try { Environment.SetEnvironmentVariable("PATH", pathVariable); Directory.Delete(simulatedOptDir, true); } catch { // just ignore } } } //TODO: this could use lots more tests [Test] public void LocateExecutable_DistFiles() { Assert.That(FileLocationUtilities.LocateExecutable("DirectoryForTests", "SampleExecutable.exe"), Does.EndWith(string.Format("DistFiles{0}DirectoryForTests{0}SampleExecutable.exe", Path.DirectorySeparatorChar))); } [Test] [Platform(Exclude = "Linux")] public void LocateExecutable_PlatformSpecificInDistFiles_Windows() { Assert.That(FileLocationUtilities.LocateExecutable("DirectoryForTests", "dummy.exe"), Does.EndWith(string.Format("DistFiles{0}Windows{0}DirectoryForTests{0}dummy.exe", Path.DirectorySeparatorChar))); } [Test] [Platform(Include = "Linux")] public void LocateExecutable_PlatformSpecificInDistFiles_LinuxWithoutExtension() { Assert.That(FileLocationUtilities.LocateExecutable("DirectoryForTests", "dummy.exe"), Does.EndWith(string.Format("DistFiles{0}Linux{0}DirectoryForTests{0}dummy", Path.DirectorySeparatorChar))); } [Test] [Platform(Include = "Linux")] public void LocateExecutable_PlatformSpecificInDistFiles_Linux() { Assert.That(FileLocationUtilities.LocateExecutable("DirectoryForTests", "dummy2.exe"), Does.EndWith(string.Format("DistFiles{0}Linux{0}DirectoryForTests{0}dummy2.exe", Path.DirectorySeparatorChar))); } [Test] public void LocateExecutable_NonexistingFile() { Assert.That(FileLocationUtilities.LocateExecutable(false, "dummy", "__nonexisting.exe"), Is.Null); } [Test] public void LocateExecutable_NonexistingFileThrows() { Assert.That(() => FileLocationUtilities.LocateExecutable("dummy", "__nonexisting.exe"), Throws.Exception.TypeOf<ApplicationException>()); } } }
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // 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 ConnectQl.AsyncEnumerables.Enumerators { using System; using System.Collections.Generic; using System.Threading.Tasks; using JetBrains.Annotations; /// <summary> /// Enumerator used by the <see cref="AsyncEnumerableExtensions.Skip{T}"/> method. /// </summary> /// <typeparam name="TLeft"> /// The type of the left source elements. /// </typeparam> /// <typeparam name="TRight"> /// The type of the right source elements. /// </typeparam> /// <typeparam name="TResult"> /// The type of the result elements. /// </typeparam> internal class CrossJoinEnumerator<TLeft, TRight, TResult> : AsyncEnumeratorBase<TResult> { /// <summary> /// The left enumerator. /// </summary> private IAsyncEnumerator<TLeft> leftEnumerator; /// <summary> /// The materialized right collection. /// </summary> private IAsyncReadOnlyCollection<TRight> materializedRight; /// <summary> /// The result selector. /// </summary> private Func<TLeft, TRight, TResult> resultSelector; /// <summary> /// The right. /// </summary> private IAsyncEnumerable<TRight> right; /// <summary> /// The right enumerator. /// </summary> private IAsyncEnumerator<TRight> rightEnumerator; /// <summary> /// The state. /// </summary> private byte state; /// <summary> /// The still enumerating. /// </summary> private bool stillEnumerating; /// <summary> /// Initializes a new instance of the <see cref="CrossJoinEnumerator{TLeft,TRight,TResult}"/> class. /// </summary> /// <param name="left"> /// The left part of the union. /// </param> /// <param name="right"> /// The right part of the union. /// </param> /// <param name="resultSelector"> /// The result Selector. /// </param> public CrossJoinEnumerator([NotNull] IAsyncEnumerable<TLeft> left, IAsyncEnumerable<TRight> right, Func<TLeft, TRight, TResult> resultSelector) { this.resultSelector = resultSelector; this.leftEnumerator = left.GetAsyncEnumerator(); this.right = right; this.materializedRight = this.right as IAsyncReadOnlyCollection<TRight>; if (this.materializedRight != null) { this.rightEnumerator = this.materializedRight.GetAsyncEnumerator(); this.IsSynchronous = this.leftEnumerator.IsSynchronous && this.rightEnumerator.IsSynchronous; } } /// <summary> /// Gets a value indicating whether the enumerator is synchronous. /// When <c>false</c>, <see cref="IAsyncEnumerator{T}.NextBatchAsync"/> must be called when /// <see cref="IAsyncEnumerator{T}.MoveNext"/> returns <c>false</c>. /// </summary> public override bool IsSynchronous { get; } /// <summary> /// Disposes the <see cref="IAsyncEnumerator{T}"/>. /// </summary> /// <param name="disposing"> /// The disposing. /// </param> protected override void Dispose(bool disposing) { base.Dispose(disposing); this.state = 3; this.leftEnumerator?.Dispose(); this.rightEnumerator?.Dispose(); this.resultSelector = null; this.leftEnumerator = null; this.rightEnumerator = null; this.materializedRight = null; this.right = null; } /// <summary> /// Gets the initial batch. /// </summary> /// <returns> /// The enumerator. /// </returns> [CanBeNull] protected override IEnumerator<TResult> InitialBatch() { return this.rightEnumerator == null ? null : this.EnumerateItems(); } /// <summary> /// Gets called when the next batch is needed. /// </summary> /// <returns> /// A task returning an <see cref="IEnumerator{T}"/> containing the next batch, of <c>null</c> when all data is /// enumerated. /// </returns> protected override async Task<IEnumerator<TResult>> OnNextBatchAsync() { switch (this.state) { case 0: // Right side was not materialized, materialize it and start enumeration. this.materializedRight = await this.right.MaterializeAsync().ConfigureAwait(false); this.rightEnumerator = this.materializedRight.GetAsyncEnumerator(); return this.EnumerateItems(); case 1: // Next batch for the left side. if (await this.leftEnumerator.NextBatchAsync().ConfigureAwait(false)) { return this.EnumerateItems(); } this.state = 3; return null; case 2: // Next batch for the right side. if (!await this.rightEnumerator.NextBatchAsync().ConfigureAwait(false)) { this.rightEnumerator.Dispose(); this.rightEnumerator = this.materializedRight.GetAsyncEnumerator(); this.stillEnumerating = false; } return this.EnumerateItems(); case 3: // Done. return null; case 4: // Disposed. throw new ObjectDisposedException(this.GetType().ToString()); default: throw new InvalidOperationException($"Invalid state: {this.state}."); } } /// <summary> /// Enumerates the items. /// </summary> /// <returns> /// The <see cref="IEnumerator{TResult}"/>. /// </returns> private IEnumerator<TResult> EnumerateItems() { while (this.stillEnumerating || this.leftEnumerator.MoveNext()) { while (this.rightEnumerator.MoveNext()) { yield return this.resultSelector(this.leftEnumerator.Current, this.rightEnumerator.Current); } if (!this.rightEnumerator.IsSynchronous) { this.state = 2; this.stillEnumerating = true; yield break; } this.rightEnumerator.Dispose(); this.rightEnumerator = this.materializedRight.GetAsyncEnumerator(); this.stillEnumerating = false; } this.state = this.leftEnumerator.IsSynchronous ? (byte)3 : (byte)1; } } }
using System; using System.Drawing; using System.Xml.Serialization; using System.IO; using System.Collections.Generic; namespace QTracer { public class Tracer { private static Scene layout; public static Pixel[] start() { Pixel[] pixels = new Pixel[Constants.WIN_X * Constants.WIN_Y]; Point3 viewPlane = new Point3(-Constants.WIN_X / 2, -Constants.WIN_X / 2, 0); createScene(); for (int y = 0; y < Constants.WIN_Y; y++) { for (int x = 0; x < Constants.WIN_X; x++) { Pixel p = new Pixel(); p.rect.X = x; p.rect.Y = Constants.WIN_Y - 1 - y; Point3 viewPixel = new Point3(); viewPixel.x = viewPlane.x + x; viewPixel.y = viewPlane.y + y; viewPixel.z = viewPlane.z; Ray r = new Ray(); r.direction = Point3.vectorize(layout.Cam.Eye, viewPixel); r.start = layout.Cam.Eye; p.color = fireRay(r, Constants.MIN_DEPTH, null); pixels[y * Constants.WIN_X + x] = p; } } return pixels; } private static Color3 fireRay(Ray incomingRay, int depth, Shape fromShape) { double closest = Constants.FAR_AWAY; Color3 retColor = Constants.BGCOLOR; int whichObject = 0, hitObject = 0; Hit finalHit = new Hit(); foreach (Shape s in layout.Shapes) { Hit rayHit = s.intersect(incomingRay); whichObject++; if (rayHit.intersect.z == Constants.FAR_AWAY) continue; double dist = Point3.distance(layout.Cam.Eye, rayHit.intersect); if (dist < closest && !s.Equals(fromShape)) { closest = dist; hitObject = whichObject; finalHit = rayHit; } } if (hitObject <= 0) return Constants.BGCOLOR; Shape hitShape = layout.Shapes[hitObject - 1]; retColor = Color3.ambient(hitShape); // phongphongphongphongphongphongphongphongphongphongphongphongphongphongphongphongphongphongphongphongphongphongphong Color3 diffuseColor = Color3.Black, specularColor = Color3.Black; foreach (Light bulb in layout.Lights) { if (spawnShadow(bulb, finalHit, hitShape, fromShape)) { retColor = hitShape.colorShadow(retColor, finalHit, layout.Lights.Count * 3); } else { if (hitShape is Plane) { retColor = hitShape.colorNormal(retColor, incomingRay, finalHit, hitShape, bulb); } else { diffuseColor += Color3.diffuse(finalHit, hitShape, bulb); specularColor += Color3.specular(incomingRay, finalHit, hitShape, bulb); } } } if (hitShape is Sphere) { retColor += diffuseColor * hitShape.Material.Kd; retColor += specularColor * hitShape.Material.Ks; } if (depth < Constants.MAX_DEPTH) { Color3 reflectColor = Color3.Black; if (hitShape.Material.Kr > 0) { Ray reflectRay = new Ray(); reflectRay.start = finalHit.intersect; Vector3 normalVec = hitShape.calcNormal(finalHit); double c = -Vector3.DotProduct(normalVec, incomingRay.direction); reflectRay.direction = -(incomingRay.direction + (2 * normalVec * c)); reflectRay.direction.Normalize(); reflectColor = fireRay(reflectRay, depth + 1, hitShape); retColor += reflectColor * hitShape.Material.Kr; } if (hitShape.Material.Kt > 0) { Ray transRay = new Ray(); double indexRefract; Vector3 normalVec = Vector3.FaceForward(hitShape.calcNormal(finalHit), -incomingRay.direction); if (Vector3.DotProduct(-incomingRay.direction, hitShape.calcNormal(finalHit)) < 0) indexRefract = Constants.REFRACTION_INDEX_SPHERE / Constants.REFRACTION_INDEX_AIR; else indexRefract = Constants.REFRACTION_INDEX_AIR / Constants.REFRACTION_INDEX_SPHERE; double discrim = 1 + (Math.Pow(indexRefract, 2) * (Math.Pow(Vector3.DotProduct(-incomingRay.direction, normalVec), 2) - 1)); // Total internal reflection! if (discrim < 0) { retColor += reflectColor * hitShape.Material.Kt; } else { discrim = indexRefract * Vector3.DotProduct(-incomingRay.direction, normalVec) - Math.Sqrt(discrim); transRay.direction = (indexRefract * incomingRay.direction) + (discrim * normalVec); transRay.start = finalHit.intersect; Color3 transColor = fireRay(transRay, depth + 1, hitShape); retColor += transColor * hitShape.Material.Kt; } } } return retColor; } // spawn a shadow ray from the intersection point to the light source. private static bool spawnShadow(Light bulb, Hit finalHit, Shape hitShape, Shape fromShape) { Ray shadowRay = new Ray(); shadowRay.start = finalHit.intersect; shadowRay.direction = Point3.vectorize(shadowRay.start, bulb.Location); double shadowDist = Point3.distance(shadowRay.start, bulb.Location); foreach (Shape s in layout.Shapes) { // If this is the object we're checking from, ignore. Duh. if (s.Equals(hitShape) || s.Equals(fromShape) || s.Material.Kt > 0) continue; Hit shadowHit = s.intersect(shadowRay); if (shadowHit.intersect.z == Constants.FAR_AWAY) continue; // We need to check if hitShape object is in FRONT OF the current one. if it is, we need to ignore this current shape. Vector3 frontTest = Point3.vectorize(shadowHit.intersect, finalHit.intersect); if (frontTest.X > 0 && frontTest.Y > 0 && frontTest.Z > 0) continue; // something has to come between the light and the current shape. double shapeDist = Point3.distance(shadowRay.start, shadowHit.intersect); if (shapeDist < shadowDist) { return true; } } return false; } private static void createScene() { XmlSerializer sceneSer = new XmlSerializer(typeof(Scene)); try { using (FileStream xmlStream = File.OpenRead(Constants.SCENE)) { layout = (Scene)sceneSer.Deserialize(xmlStream); } } catch (Exception e) { Console.WriteLine(e); return; } foreach (SphereMaterial mat in layout.Spheres) { layout.Shapes.Add(new Sphere(mat)); } foreach (PlaneMaterial mat in layout.Planes) { layout.Shapes.Add(new Plane(mat, Constants.FLOOR_SHADING)); } layout.Cam.setup(); } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; using System.Drawing.Printing; using System.Text; using fyiReporting.RdlViewer.Resources; using fyiReporting.RDL; namespace fyiReporting.RdlViewer { /// <summary> /// RdlViewerFind finds text inside of the RdlViewer control /// </summary> public class RdlViewerFind : System.Windows.Forms.UserControl { private Button bClose; private Button bFindNext; private Button bFindPrevious; private CheckBox ckHighlightAll; private CheckBox ckMatchCase; private Label lFind; private Label lStatus; private TextBox tbFind; private PageItem position = null; private RdlViewer _Viewer; public RdlViewer Viewer { get { return _Viewer; } set { _Viewer = value; } } public RdlViewerFind() { InitializeComponent(); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RdlViewerFind)); this.bClose = new System.Windows.Forms.Button(); this.tbFind = new System.Windows.Forms.TextBox(); this.bFindNext = new System.Windows.Forms.Button(); this.bFindPrevious = new System.Windows.Forms.Button(); this.ckHighlightAll = new System.Windows.Forms.CheckBox(); this.ckMatchCase = new System.Windows.Forms.CheckBox(); this.lFind = new System.Windows.Forms.Label(); this.lStatus = new System.Windows.Forms.Label(); this.SuspendLayout(); // // bClose // resources.ApplyResources(this.bClose, "bClose"); this.bClose.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.bClose.FlatAppearance.BorderSize = 0; this.bClose.Name = "bClose"; this.bClose.UseVisualStyleBackColor = false; this.bClose.Click += new System.EventHandler(this.bClose_Click); // // tbFind // resources.ApplyResources(this.tbFind, "tbFind"); this.tbFind.Name = "tbFind"; this.tbFind.TextChanged += new System.EventHandler(this.tbFind_TextChanged); // // bFindNext // resources.ApplyResources(this.bFindNext, "bFindNext"); this.bFindNext.Name = "bFindNext"; this.bFindNext.UseVisualStyleBackColor = true; this.bFindNext.Click += new System.EventHandler(this.bFindNext_Click); // // bFindPrevious // resources.ApplyResources(this.bFindPrevious, "bFindPrevious"); this.bFindPrevious.Name = "bFindPrevious"; this.bFindPrevious.UseVisualStyleBackColor = true; this.bFindPrevious.Click += new System.EventHandler(this.bFindPrevious_Click); // // ckHighlightAll // resources.ApplyResources(this.ckHighlightAll, "ckHighlightAll"); this.ckHighlightAll.Name = "ckHighlightAll"; this.ckHighlightAll.UseVisualStyleBackColor = true; this.ckHighlightAll.CheckedChanged += new System.EventHandler(this.ckHighlightAll_CheckedChanged); // // ckMatchCase // resources.ApplyResources(this.ckMatchCase, "ckMatchCase"); this.ckMatchCase.Name = "ckMatchCase"; this.ckMatchCase.UseVisualStyleBackColor = true; this.ckMatchCase.CheckedChanged += new System.EventHandler(this.ckMatchCase_CheckedChanged); // // lFind // resources.ApplyResources(this.lFind, "lFind"); this.lFind.Name = "lFind"; // // lStatus // resources.ApplyResources(this.lStatus, "lStatus"); this.lStatus.ForeColor = System.Drawing.Color.Salmon; this.lStatus.Name = "lStatus"; // // RdlViewerFind // resources.ApplyResources(this, "$this"); this.Controls.Add(this.lStatus); this.Controls.Add(this.lFind); this.Controls.Add(this.ckMatchCase); this.Controls.Add(this.ckHighlightAll); this.Controls.Add(this.bFindPrevious); this.Controls.Add(this.bFindNext); this.Controls.Add(this.tbFind); this.Controls.Add(this.bClose); this.Name = "RdlViewerFind"; this.VisibleChanged += new System.EventHandler(this.RdlViewerFind_VisibleChanged); this.ResumeLayout(false); this.PerformLayout(); } private void bClose_Click(object sender, EventArgs e) { this.Visible = false; } private void bFindNext_Click(object sender, EventArgs e) { FindNext(); } public void FindNext() { if (_Viewer == null) throw new ApplicationException(Strings.RdlViewerFind_ErrorA_PropertyMustSetPriorFindNext); if (tbFind.Text.Length == 0) // must have something to find return; RdlViewerFinds findOptions = ckMatchCase.Checked ? RdlViewerFinds.MatchCase : RdlViewerFinds.None; bool begin = position == null; position = _Viewer.Find(tbFind.Text, position, findOptions); if (position == null) { if (!begin) // if we didn't start from beginning already; try from beginning position = _Viewer.Find(tbFind.Text, position, findOptions); lStatus.Text = position == null ? Strings.RdlViewerFind_FindNext_Phrase_not_found : Strings.RdlViewerFind_FindNext_Reached_end_of_report; _Viewer.HighlightPageItem = position; if (position != null) _Viewer.ScrollToPageItem(position); } else { lStatus.Text = ""; _Viewer.HighlightPageItem = position; _Viewer.ScrollToPageItem(position); } } private void bFindPrevious_Click(object sender, EventArgs e) { FindPrevious(); } public void FindPrevious() { if (_Viewer == null) throw new ApplicationException(Strings.RdlViewerFind_ErrorA_PropertyMustSetPriorFindPrevious); if (tbFind.Text.Length == 0) // must have something to find return; RdlViewerFinds findOptions = RdlViewerFinds.Backward | (ckMatchCase.Checked ? RdlViewerFinds.MatchCase : RdlViewerFinds.None); bool begin = position == null; position = _Viewer.Find(tbFind.Text, position, findOptions); if (position == null) { if (!begin) // if we didn't start from beginning already; try from bottom position = _Viewer.Find(tbFind.Text, position, findOptions); lStatus.Text = position == null ? Strings.RdlViewerFind_FindNext_Phrase_not_found : Strings.RdlViewerFind_FindPrevious_Reached_top_of_report; _Viewer.HighlightPageItem = position; if (position != null) _Viewer.ScrollToPageItem(position); } else { lStatus.Text = ""; _Viewer.HighlightPageItem = position; _Viewer.ScrollToPageItem(position); } } private void RdlViewerFind_VisibleChanged(object sender, EventArgs e) { lStatus.Text = ""; if (this.Visible) { _Viewer.HighlightText = tbFind.Text; tbFind.Focus(); FindNext(); // and go find the contents of the textbox } else { // turn off any highlighting when find control not visible _Viewer.HighlightPageItem = position = null; _Viewer.HighlightText = null; _Viewer.HighlightAll = false; ckHighlightAll.Checked = false; } } private void tbFind_TextChanged(object sender, EventArgs e) { lStatus.Text = ""; position = null; // reset position when edit changes?? todo not really _Viewer.HighlightText = tbFind.Text; ckHighlightAll.Enabled = bFindNext.Enabled = bFindPrevious.Enabled = tbFind.Text.Length > 0; if (tbFind.Text.Length > 0) FindNext(); } private void ckHighlightAll_CheckedChanged(object sender, EventArgs e) { _Viewer.HighlightAll = ckHighlightAll.Checked; } private void ckMatchCase_CheckedChanged(object sender, EventArgs e) { _Viewer.HighlightCaseSensitive = ckMatchCase.Checked; } } }
namespace Ioke.Lang { using System.Collections; using System.Collections.Generic; using System.Text; using Ioke.Lang.Util; public class Range : IokeData { IokeObject from; IokeObject to; bool inclusive; bool inverted = false; public Range(IokeObject from, IokeObject to, bool inclusive, bool inverted) { this.from = from; this.to = to; this.inclusive = inclusive; this.inverted = inverted; } public static IokeObject GetFrom(object range) { return ((Range)IokeObject.dataOf(range)).From; } public static IokeObject GetTo(object range) { return ((Range)IokeObject.dataOf(range)).To; } public static bool IsInclusive(object range) { return ((Range)IokeObject.dataOf(range)).IsInclusive(); } public IokeObject From { get { return from; } } public IokeObject To { get { return to; } } public bool IsInclusive() { return inclusive; } public class RangeIterator { private IokeObject start; private IokeObject end; private readonly bool inclusive; private IokeObject context; // private IokeObject message; private IokeObject messageToSend; private readonly Runtime runtime; private bool oneIteration = false; private bool doLast = true; public RangeIterator(IokeObject start, IokeObject end, bool inclusive, bool inverted, IokeObject context, IokeObject message) { this.runtime = context.runtime; this.start = start; this.end = end; this.inclusive = inclusive; this.context = context; // this.message = message; messageToSend = runtime.succMessage; if(inverted) { messageToSend = runtime.predMessage; } } public bool hasNext() { bool sameEndpoints = IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(runtime.eqMessage)).SendTo(runtime.eqMessage, context, start, end)); bool shouldGoOver = (doLast && inclusive); bool sameStartPoint = sameEndpoints && inclusive && !oneIteration; return !sameEndpoints || shouldGoOver || sameStartPoint; } public object next() { IokeObject obj = start; if(!IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(runtime.eqMessage)).SendTo(runtime.eqMessage, context, start, end))) { oneIteration = true; start = (IokeObject)((Message)IokeObject.dataOf(messageToSend)).SendTo(messageToSend, context, start); doLast = true; return obj; } else { if(inclusive && doLast) { doLast = false; return obj; } } return null; } } public override void Init(IokeObject obj) { Runtime runtime = obj.runtime; obj.Kind = "Range"; obj.Mimics(IokeObject.As(runtime.Mixins.GetCell(null, null, "Sequenced"), null), runtime.nul, runtime.nul); obj.RegisterMethod(runtime.NewNativeMethod("returns true if the left hand side range is equal to the right hand side range.", new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder() .ReceiverMustMimic(runtime.Range) .WithRequiredPositional("other") .Arguments, (method, on, args, keywords, context, message) => { Range d = (Range)IokeObject.dataOf(on); object other = args[0]; return ((other is IokeObject) && (IokeObject.dataOf(other) is Range) && d.inclusive == ((Range)IokeObject.dataOf(other)).inclusive && d.from.Equals(((Range)IokeObject.dataOf(other)).from) && d.to.Equals(((Range)IokeObject.dataOf(other)).to)) ? context.runtime.True : context.runtime.False; }))); obj.RegisterMethod(runtime.NewNativeMethod("will return a new inclusive Range based on the two arguments", new NativeMethod("inclusive", DefaultArgumentsDefinition.builder() .WithRequiredPositional("from") .WithRequiredPositional("to") .Arguments, (method, context, message, on, outer) => { var args = new SaneArrayList(); outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>()); object from = args[0]; object to = args[1]; bool comparing = IokeObject.IsMimic(from, IokeObject.As(context.runtime.Mixins.Cells["Comparing"], context), context); bool inverted = false; if(comparing) { object result = ((Message)IokeObject.dataOf(context.runtime.spaceShipMessage)).SendTo(context.runtime.spaceShipMessage, context, from, to); if(result != context.runtime.nil && Number.ExtractInt(result, message, context) == 1) { inverted = true; } } return runtime.NewRange(IokeObject.As(from, context), IokeObject.As(to, context), true, inverted); }))); obj.RegisterMethod(runtime.NewNativeMethod("will return a new exclusive Range based on the two arguments", new NativeMethod("exclusive", DefaultArgumentsDefinition.builder() .WithRequiredPositional("from") .WithRequiredPositional("to") .Arguments, (method, context, message, on, outer) => { var args = new SaneArrayList(); outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>()); object from = args[0]; object to = args[1]; bool comparing = IokeObject.IsMimic(from, IokeObject.As(context.runtime.Mixins.Cells["Comparing"], context), context); bool inverted = false; if(comparing) { object result = ((Message)IokeObject.dataOf(context.runtime.spaceShipMessage)).SendTo(context.runtime.spaceShipMessage, context, from, to); if(result != context.runtime.nil && Number.ExtractInt(result, message, context) == 1) { inverted = true; } } return runtime.NewRange(IokeObject.As(from, context), IokeObject.As(to, context), false, inverted); }))); obj.RegisterMethod(runtime.NewNativeMethod("returns true if the receiver is an exclusive range, false otherwise", new NativeMethod.WithNoArguments("exclusive?", (method, context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return ((Range)IokeObject.dataOf(on)).inclusive ? context.runtime.False : context.runtime.True; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns true if the receiver is an inclusive range, false otherwise", new NativeMethod.WithNoArguments("inclusive?", (method, context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return ((Range)IokeObject.dataOf(on)).inclusive ? context.runtime.True : context.runtime.False; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns the 'from' part of the range", new TypeCheckingNativeMethod.WithNoArguments("from", obj, (method, on, args, keywords, context, message) => { return ((Range)IokeObject.dataOf(on)).from; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns the 'to' part of the range", new NativeMethod.WithNoArguments("to", (method, context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return ((Range)IokeObject.dataOf(on)).to; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns a new sequence to iterate over this range", new TypeCheckingNativeMethod.WithNoArguments("seq", obj, (method, on, args, keywords, context, message) => { IokeObject ob = method.runtime.Iterator2Sequence.AllocateCopy(null, null); ob.MimicsWithoutCheck(method.runtime.Iterator2Sequence); Range r = ((Range)IokeObject.dataOf(on)); ob.Data = new Sequence.Iterator2Sequence(new RangeIterator(r.from, r.to, r.inclusive, r.inverted, context, message)); return ob; }))); obj.RegisterMethod(runtime.NewNativeMethod("takes either one or two or three arguments. if one argument is given, it should be a message chain that will be sent to each object in the range. the result will be thrown away. if two arguments are given, the first is an unevaluated name that will be set to each of the values in the range in succession, and then the second argument will be evaluated in a scope with that argument in it. if three arguments is given, the first one is an unevaluated name that will be set to the index of each element, and the other two arguments are the name of the argument for the value, and the actual code. the code will evaluate in a lexical context, and if the argument name is available outside the context, it will be shadowed. the method will return the range.", new NativeMethod("each", DefaultArgumentsDefinition.builder() .WithOptionalPositionalUnevaluated("indexOrArgOrCode") .WithOptionalPositionalUnevaluated("argOrCode") .WithOptionalPositionalUnevaluated("code") .Arguments, (method, context, message, on, outer) => { outer.ArgumentsDefinition.CheckArgumentCount(context, message, on); IokeObject from = IokeObject.As(((Range)IokeObject.dataOf(on)).from, context); IokeObject to = IokeObject.As(((Range)IokeObject.dataOf(on)).to, context); bool inclusive = ((Range)IokeObject.dataOf(on)).inclusive; IokeObject messageToSend = context.runtime.succMessage; if(((Range)IokeObject.dataOf(on)).inverted) { messageToSend = context.runtime.predMessage; } switch(message.Arguments.Count) { case 0: { return ((Message)IokeObject.dataOf(runtime.seqMessage)).SendTo(runtime.seqMessage, context, on); } case 1: { IokeObject code = IokeObject.As(message.Arguments[0], context); object current = from; while(!IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(context.runtime.eqMessage)).SendTo(context.runtime.eqMessage, context, current, to))) { ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithReceiver(code, context, context.RealContext, current); current = ((Message)IokeObject.dataOf(messageToSend)).SendTo(messageToSend, context, current); } if(inclusive) { ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithReceiver(code, context, context.RealContext, current); } break; } case 2: { LexicalContext c = new LexicalContext(context.runtime, context, "Lexical activation context for Range#each", message, context); string name = IokeObject.As(message.Arguments[0], context).Name; IokeObject code = IokeObject.As(message.Arguments[1], context); object current = from; while(!IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(context.runtime.eqMessage)).SendTo(context.runtime.eqMessage, context, current, to))) { c.SetCell(name, current); ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithoutExplicitReceiver(code, c, c.RealContext); current = ((Message)IokeObject.dataOf(messageToSend)).SendTo(messageToSend, context, current); } if(inclusive) { c.SetCell(name, current); ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithoutExplicitReceiver(code, c, c.RealContext); } break; } case 3: { LexicalContext c = new LexicalContext(context.runtime, context, "Lexical activation context for List#each", message, context); string iname = IokeObject.As(message.Arguments[0], context).Name; string name = IokeObject.As(message.Arguments[1], context).Name; IokeObject code = IokeObject.As(message.Arguments[2], context); int index = 0; object current = from; while(!IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(context.runtime.eqMessage)).SendTo(context.runtime.eqMessage, context, current, to))) { c.SetCell(name, current); c.SetCell(iname, runtime.NewNumber(index++)); ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithoutExplicitReceiver(code, c, c.RealContext); current = ((Message)IokeObject.dataOf(messageToSend)).SendTo(messageToSend, context, current); } if(inclusive) { c.SetCell(name, current); c.SetCell(iname, runtime.NewNumber(index++)); ((Message)IokeObject.dataOf(code)).EvaluateCompleteWithoutExplicitReceiver(code, c, c.RealContext); } break; } } return on; }))); obj.RegisterMethod(runtime.NewNativeMethod("returns true if the argument is within the confines of this range. how this comparison is done depends on if the object mimics Comparing. If it does, < and > will be used. If not, all the available entries in this range will be enumerated using 'succ'/'pred' until either the end or the element we're looking for is found. in that case, comparison is done with '=='", new NativeMethod("===", DefaultArgumentsDefinition.builder() .WithRequiredPositional("other") .Arguments, (method, context, message, on, outer) => { var args = new SaneArrayList(); outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>()); object other = args[0]; IokeObject from = IokeObject.As(((Range)IokeObject.dataOf(on)).from, context); IokeObject to = IokeObject.As(((Range)IokeObject.dataOf(on)).to, context); bool comparing = IokeObject.IsMimic(from, IokeObject.As(context.runtime.Mixins.Cells["Comparing"], context)); bool inclusive = ((Range)IokeObject.dataOf(on)).inclusive; if(comparing) { IokeObject firstMessage = context.runtime.lteMessage; IokeObject secondMessageInclusive = context.runtime.gteMessage; IokeObject secondMessageExclusive = context.runtime.gtMessage; if(((Range)IokeObject.dataOf(on)).inverted) { firstMessage = context.runtime.gteMessage; secondMessageInclusive = context.runtime.lteMessage; secondMessageExclusive = context.runtime.ltMessage; } if(IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(firstMessage)).SendTo(firstMessage, context, from, other)) && ((inclusive && IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(secondMessageInclusive)).SendTo(secondMessageInclusive, context, to, other))) || IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(secondMessageExclusive)).SendTo(secondMessageExclusive, context, to, other)))) { return context.runtime.True; } else { return context.runtime.False; } } else { IokeObject messageToSend = context.runtime.succMessage; if(((Range)IokeObject.dataOf(on)).inverted) { messageToSend = context.runtime.predMessage; } object current = from; while(!IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(context.runtime.eqMessage)).SendTo(context.runtime.eqMessage, context, current, to))) { if(IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(context.runtime.eqMessage)).SendTo(context.runtime.eqMessage, context, current, other))) { return context.runtime.True; } current = ((Message)IokeObject.dataOf(messageToSend)).SendTo(messageToSend, context, current); } if(inclusive && IokeObject.IsObjectTrue(((Message)IokeObject.dataOf(context.runtime.eqMessage)).SendTo(context.runtime.eqMessage, context, to, other))) { return context.runtime.True; } return context.runtime.False; } }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns a text inspection of the object", new NativeMethod.WithNoArguments("inspect", (method, context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return method.runtime.NewText(Range.GetInspect(on)); }))); obj.RegisterMethod(runtime.NewNativeMethod("Returns a brief text inspection of the object", new NativeMethod.WithNoArguments("notice", (method, context, message, on, outer) => { outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary<string, object>()); return method.runtime.NewText(Range.GetNotice(on)); }))); } public override IokeData CloneData(IokeObject obj, IokeObject m, IokeObject context) { return new Range(from, to, inclusive, inverted); } public static string GetInspect(object on) { return ((Range)(IokeObject.dataOf(on))).Inspect(on); } public static string GetNotice(object on) { return ((Range)(IokeObject.dataOf(on))).Notice(on); } public string Inspect(object obj) { StringBuilder sb = new StringBuilder(); sb.Append(IokeObject.Inspect(from)); if(inclusive) { sb.Append(".."); } else { sb.Append("..."); } sb.Append(IokeObject.Inspect(to)); return sb.ToString(); } public string Notice(object obj) { StringBuilder sb = new StringBuilder(); sb.Append(IokeObject.Notice(from)); if(inclusive) { sb.Append(".."); } else { sb.Append("..."); } sb.Append(IokeObject.Notice(to)); return sb.ToString(); } } }
// 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.Globalization; using Xunit; public static class DoubleTests { [Fact] public static void TestCtor() { Double i = new Double(); Assert.True(i == 0); i = 41; Assert.True(i == 41); i = (Double)41.3; Assert.True(i == (Double)41.3); } [Fact] public static void TestMaxValue() { Double max = Double.MaxValue; Assert.True(max == (Double)1.7976931348623157E+308); } [Fact] public static void TestMinValue() { Double min = Double.MinValue; Assert.True(min == ((Double)(-1.7976931348623157E+308))); } [Fact] public static void TestEpsilon() { // Double Double.Epsilon Assert.Equal<Double>((Double)4.9406564584124654E-324, Double.Epsilon); } [Fact] public static void TestIsInfinity() { // Boolean Double.IsInfinity(Double) Assert.True(Double.IsInfinity(Double.NegativeInfinity)); Assert.True(Double.IsInfinity(Double.PositiveInfinity)); } [Fact] public static void TestNaN() { // Double Double.NaN Assert.Equal<Double>((Double)0.0 / (Double)0.0, Double.NaN); } [Fact] public static void TestIsNaN() { // Boolean Double.IsNaN(Double) Assert.True(Double.IsNaN(Double.NaN)); } [Fact] public static void TestNegativeInfinity() { // Double Double.NegativeInfinity Assert.Equal<Double>((Double)(-1.0) / (Double)0.0, Double.NegativeInfinity); } [Fact] public static void TestIsNegativeInfinity() { // Boolean Double.IsNegativeInfinity(Double) Assert.True(Double.IsNegativeInfinity(Double.NegativeInfinity)); } [Fact] public static void TestPositiveInfinity() { // Double Double.PositiveInfinity Assert.Equal<Double>((Double)1.0 / (Double)0.0, Double.PositiveInfinity); } [Fact] public static void TestIsPositiveInfinity() { // Boolean Double.IsPositiveInfinity(Double) Assert.True(Double.IsPositiveInfinity(Double.PositiveInfinity)); } [Fact] public static void TestCompareToObject() { Double i = 234; IComparable comparable = i; Assert.Equal(1, comparable.CompareTo(null)); Assert.Equal(0, comparable.CompareTo((Double)234)); Assert.True(comparable.CompareTo(Double.MinValue) > 0); Assert.True(comparable.CompareTo((Double)0) > 0); Assert.True(comparable.CompareTo((Double)(-123)) > 0); Assert.True(comparable.CompareTo((Double)123) > 0); Assert.True(comparable.CompareTo((Double)456) < 0); Assert.True(comparable.CompareTo(Double.MaxValue) < 0); Assert.Throws<ArgumentException>(() => comparable.CompareTo("a")); } [Fact] public static void TestCompareTo() { Double i = 234; Assert.Equal(0, i.CompareTo((Double)234)); Assert.True(i.CompareTo(Double.MinValue) > 0); Assert.True(i.CompareTo((Double)0) > 0); Assert.True(i.CompareTo((Double)(-123)) > 0); Assert.True(i.CompareTo((Double)123) > 0); Assert.True(i.CompareTo((Double)456) < 0); Assert.True(i.CompareTo(Double.MaxValue) < 0); Assert.True(Double.NaN.CompareTo(Double.NaN) == 0); Assert.True(Double.NaN.CompareTo(0) < 0); Assert.True(i.CompareTo(Double.NaN) > 0); } [Fact] public static void TestEqualsObject() { Double i = 789; object obj1 = (Double)789; Assert.True(i.Equals(obj1)); object obj2 = (Double)(-789); Assert.True(!i.Equals(obj2)); object obj3 = (Double)0; Assert.True(!i.Equals(obj3)); } [Fact] public static void TestEquals() { Double i = -911; Assert.True(i.Equals((Double)(-911))); Assert.True(!i.Equals((Double)911)); Assert.True(!i.Equals((Double)0)); Assert.True(Double.NaN.Equals(Double.NaN)); } [Fact] public static void TestGetHashCode() { Double i1 = 123; Double i2 = 654; Assert.NotEqual(0, i1.GetHashCode()); Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode()); } [Fact] public static void TestToString() { Double i1 = 6310; Assert.Equal("6310", i1.ToString()); Double i2 = -8249; Assert.Equal("-8249", i2.ToString()); } [Fact] public static void TestToStringFormatProvider() { var numberFormat = new System.Globalization.NumberFormatInfo(); Double i1 = 6310; Assert.Equal("6310", i1.ToString(numberFormat)); Double i2 = -8249; Assert.Equal("-8249", i2.ToString(numberFormat)); Double i3 = -2468; // Changing the negative pattern doesn't do anything without also passing in a format string numberFormat.NumberNegativePattern = 0; Assert.Equal("-2468", i3.ToString(numberFormat)); Assert.Equal("NaN", Double.NaN.ToString(NumberFormatInfo.InvariantInfo)); Assert.Equal("Infinity", Double.PositiveInfinity.ToString(NumberFormatInfo.InvariantInfo)); Assert.Equal("-Infinity", Double.NegativeInfinity.ToString(NumberFormatInfo.InvariantInfo)); } [Fact] public static void TestToStringFormat() { Double i1 = 6310; Assert.Equal("6310", i1.ToString("G")); Double i2 = -8249; Assert.Equal("-8249", i2.ToString("g")); Double i3 = -2468; Assert.Equal("-2,468.00", i3.ToString("N")); } [Fact] public static void TestToStringFormatFormatProvider() { var numberFormat = new System.Globalization.NumberFormatInfo(); Double i1 = 6310; Assert.Equal("6310", i1.ToString("G", numberFormat)); Double i2 = -8249; Assert.Equal("-8249", i2.ToString("g", numberFormat)); numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up numberFormat.NumberGroupSeparator = "*"; numberFormat.NumberNegativePattern = 0; Double i3 = -2468; Assert.Equal("(2*468.00)", i3.ToString("N", numberFormat)); } [Fact] public static void TestParse() { Assert.Equal(123, Double.Parse("123")); Assert.Equal(-123, Double.Parse("-123")); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyle() { Assert.Equal<Double>((Double)123.1, Double.Parse("123.1", NumberStyles.AllowDecimalPoint)); Assert.Equal(1000, Double.Parse("1,000", NumberStyles.AllowThousands)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseFormatProvider() { var nfi = new NumberFormatInfo(); Assert.Equal(123, Double.Parse("123", nfi)); Assert.Equal(-123, Double.Parse("-123", nfi)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyleFormatProvider() { var nfi = new NumberFormatInfo(); Assert.Equal<Double>((Double)123.123, Double.Parse("123.123", NumberStyles.Float, nfi)); nfi.CurrencySymbol = "$"; Assert.Equal(1000, Double.Parse("$1,000", NumberStyles.Currency, nfi)); //TODO: Negative tests once we get better exception support } [Fact] public static void TestTryParse() { // Defaults AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent | AllowThousands Double i; Assert.True(Double.TryParse("123", out i)); // Simple Assert.Equal(123, i); Assert.True(Double.TryParse("-385", out i)); // LeadingSign Assert.Equal(-385, i); Assert.True(Double.TryParse(" 678 ", out i)); // Leading/Trailing whitespace Assert.Equal(678, i); Assert.True(Double.TryParse("678.90", out i)); // Decimal Assert.Equal((Double)678.90, i); Assert.True(Double.TryParse("1E23", out i)); // Exponent Assert.Equal((Double)1E23, i); Assert.True(Double.TryParse("1,000", out i)); // Thousands Assert.Equal(1000, i); Assert.False(Double.TryParse("$1000", out i)); // Currency Assert.False(Double.TryParse("abc", out i)); // Hex digits Assert.False(Double.TryParse("(135)", out i)); // Parentheses } [Fact] public static void TestTryParseNumberStyleFormatProvider() { Double i; var nfi = new NumberFormatInfo(); Assert.True(Double.TryParse("123.123", NumberStyles.Any, nfi, out i)); // Simple positive Assert.Equal((Double)123.123, i); Assert.True(Double.TryParse("123", NumberStyles.Float, nfi, out i)); // Simple Hex Assert.Equal(123, i); nfi.CurrencySymbol = "$"; Assert.True(Double.TryParse("$1,000", NumberStyles.Currency, nfi, out i)); // Currency/Thousands postive Assert.Equal(1000, i); Assert.False(Double.TryParse("abc", NumberStyles.None, nfi, out i)); // Hex Number negative Assert.False(Double.TryParse("678.90", NumberStyles.Integer, nfi, out i)); // Decimal Assert.False(Double.TryParse(" 678 ", NumberStyles.None, nfi, out i)); // Trailing/Leading whitespace negative Assert.True(Double.TryParse("(135)", NumberStyles.AllowParentheses, nfi, out i)); // Parenthese postive Assert.Equal(-135, i); Assert.True(Double.TryParse("Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(Double.IsPositiveInfinity(i)); Assert.True(Double.TryParse("-Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(Double.IsNegativeInfinity(i)); Assert.True(Double.TryParse("NaN", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i)); Assert.True(Double.IsNaN(i)); } }
using System; using System.Text; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AttributeSource = Lucene.Net.Util.AttributeSource; using BytesRef = Lucene.Net.Util.BytesRef; using Term = Lucene.Net.Index.Term; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; using ToStringUtils = Lucene.Net.Util.ToStringUtils; /// <summary> /// A <see cref="Query"/> that matches documents within an range of terms. /// /// <para/>This query matches the documents looking for terms that fall into the /// supplied range according to /// <see cref="byte.CompareTo(byte)"/>. It is not intended /// for numerical ranges; use <see cref="NumericRangeQuery"/> instead. /// /// <para/>This query uses the /// <see cref="MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT"/> /// rewrite method. /// <para/> /// @since 2.9 /// </summary> public class TermRangeQuery : MultiTermQuery { private BytesRef lowerTerm; private BytesRef upperTerm; private bool includeLower; private bool includeUpper; /// <summary> /// Constructs a query selecting all terms greater/equal than <paramref name="lowerTerm"/> /// but less/equal than <paramref name="upperTerm"/>. /// /// <para/> /// If an endpoint is <c>null</c>, it is said /// to be "open". Either or both endpoints may be open. Open endpoints may not /// be exclusive (you can't select all but the first or last term without /// explicitly specifying the term to exclude.) /// </summary> /// <param name="field"> The field that holds both lower and upper terms. </param> /// <param name="lowerTerm"> /// The term text at the lower end of the range. </param> /// <param name="upperTerm"> /// The term text at the upper end of the range. </param> /// <param name="includeLower"> /// If true, the <paramref name="lowerTerm"/> is /// included in the range. </param> /// <param name="includeUpper"> /// If true, the <paramref name="upperTerm"/> is /// included in the range. </param> public TermRangeQuery(string field, BytesRef lowerTerm, BytesRef upperTerm, bool includeLower, bool includeUpper) : base(field) { this.lowerTerm = lowerTerm; this.upperTerm = upperTerm; this.includeLower = includeLower; this.includeUpper = includeUpper; } /// <summary> /// Factory that creates a new <see cref="TermRangeQuery"/> using <see cref="string"/>s for term text. /// </summary> public static TermRangeQuery NewStringRange(string field, string lowerTerm, string upperTerm, bool includeLower, bool includeUpper) { BytesRef lower = lowerTerm == null ? null : new BytesRef(lowerTerm); BytesRef upper = upperTerm == null ? null : new BytesRef(upperTerm); return new TermRangeQuery(field, lower, upper, includeLower, includeUpper); } /// <summary> /// Returns the lower value of this range query </summary> public virtual BytesRef LowerTerm => lowerTerm; /// <summary> /// Returns the upper value of this range query </summary> public virtual BytesRef UpperTerm => upperTerm; /// <summary> /// Returns <c>true</c> if the lower endpoint is inclusive </summary> public virtual bool IncludesLower => includeLower; /// <summary> /// Returns <c>true</c> if the upper endpoint is inclusive </summary> public virtual bool IncludesUpper => includeUpper; protected override TermsEnum GetTermsEnum(Terms terms, AttributeSource atts) { if (lowerTerm != null && upperTerm != null && lowerTerm.CompareTo(upperTerm) > 0) { return TermsEnum.EMPTY; } TermsEnum tenum = terms.GetIterator(null); if ((lowerTerm == null || (includeLower && lowerTerm.Length == 0)) && upperTerm == null) { return tenum; } return new TermRangeTermsEnum(tenum, lowerTerm, upperTerm, includeLower, includeUpper); } /// <summary> /// Prints a user-readable version of this query. </summary> public override string ToString(string field) { StringBuilder buffer = new StringBuilder(); if (!Field.Equals(field, StringComparison.Ordinal)) { buffer.Append(Field); buffer.Append(":"); } buffer.Append(includeLower ? '[' : '{'); // TODO: all these toStrings for queries should just output the bytes, it might not be UTF-8! buffer.Append(lowerTerm != null ? ("*".Equals(Term.ToString(lowerTerm), StringComparison.Ordinal) ? "\\*" : Term.ToString(lowerTerm)) : "*"); buffer.Append(" TO "); buffer.Append(upperTerm != null ? ("*".Equals(Term.ToString(upperTerm), StringComparison.Ordinal) ? "\\*" : Term.ToString(upperTerm)) : "*"); buffer.Append(includeUpper ? ']' : '}'); buffer.Append(ToStringUtils.Boost(Boost)); return buffer.ToString(); } public override int GetHashCode() { const int prime = 31; int result = base.GetHashCode(); result = prime * result + (includeLower ? 1231 : 1237); result = prime * result + (includeUpper ? 1231 : 1237); result = prime * result + ((lowerTerm == null) ? 0 : lowerTerm.GetHashCode()); result = prime * result + ((upperTerm == null) ? 0 : upperTerm.GetHashCode()); return result; } public override bool Equals(object obj) { if (this == obj) { return true; } if (!base.Equals(obj)) { return false; } if (this.GetType() != obj.GetType()) { return false; } TermRangeQuery other = (TermRangeQuery)obj; if (includeLower != other.includeLower) { return false; } if (includeUpper != other.includeUpper) { return false; } if (lowerTerm == null) { if (other.lowerTerm != null) { return false; } } else if (!lowerTerm.Equals(other.lowerTerm)) { return false; } if (upperTerm == null) { if (other.upperTerm != null) { return false; } } else if (!upperTerm.Equals(other.upperTerm)) { return false; } return true; } } }
// Copyright 2016 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEditor; using System.Collections; /// A custom editor for properties on the GvrAudioSource script. This appears in the Inspector /// window of a GvrAudioSource object. [CustomEditor(typeof(GvrAudioSource))] [CanEditMultipleObjects] public class GvrAudioSourceEditor : Editor { private SerializedProperty clip = null; private SerializedProperty loop = null; private SerializedProperty mute = null; private SerializedProperty pitch = null; private SerializedProperty playOnAwake = null; private SerializedProperty priority = null; private SerializedProperty volume = null; private SerializedProperty rolloffMode = null; private SerializedProperty maxDistance = null; private SerializedProperty minDistance = null; private SerializedProperty bypassRoomEffects = null; private SerializedProperty directivityAlpha = null; private SerializedProperty directivitySharpness = null; private Texture2D directivityTexture = null; private SerializedProperty gainDb = null; private SerializedProperty hrtfEnabled = null; private SerializedProperty occlusionEnabled = null; private SerializedProperty spread = null; private GUIContent clipLabel = new GUIContent("AudioClip", "The AudioClip asset played by the GvrAudioSource."); private GUIContent loopLabel = new GUIContent("Loop", "Sets the source to loop."); private GUIContent muteLabel = new GUIContent("Mute", "Mutes the sound."); private GUIContent pitchLabel = new GUIContent("Pitch", "Sets the frequency of the sound. Use this to slow down or speed up the sound."); private GUIContent priorityLabel = new GUIContent("Priority", "Sets the priority of the source. Note that a sound with a larger priority value will more " + "likely be stolen by sounds with smaller priority values."); private GUIContent volumeLabel = new GUIContent("Volume", "Sets the overall volume of the sound."); private GUIContent rolloffModeLabel = new GUIContent("Volume Rolloff", "Which type of rolloff curve to use."); private GUIContent maxDistanceLabel = new GUIContent("Max Distance", "Max distance is the distance a sound stops attenuating at."); private GUIContent minDistanceLabel = new GUIContent("Min Distance", "Within the min distance, the volume will stay at the loudest possible. " + "Outside this min distance it will begin to attenuate."); private GUIContent playOnAwakeLabel = new GUIContent("Play On Awake", "Play the sound when the scene loads."); private GUIContent bypassRoomEffectsLabel = new GUIContent("Bypass Room Effects", "Sets whether the room effects for the source should be bypassed."); private GUIContent directivityLabel = new GUIContent("Directivity", "Controls the pattern of sound emission of the source. This can change the perceived " + "loudness of the source depending on which way it is facing relative to the listener. " + "Patterns are aligned to the 'forward' direction of the parent object."); private GUIContent directivityAlphaLabel = new GUIContent("Alpha", "Controls the balance between dipole pattern and omnidirectional pattern for source " + "emission. By varying this value, differing directivity patterns can be formed."); private GUIContent directivitySharpnessLabel = new GUIContent("Sharpness", "Sets the sharpness of the directivity pattern. Higher values will result in increased " + "directivity."); private GUIContent gainLabel = new GUIContent("Gain (dB)", "Applies a gain to the source for adjustment of relative loudness."); private GUIContent hrtfEnabledLabel = new GUIContent("Enable HRTF", "Sets HRTF binaural rendering for the source. Note that this setting has no effect when " + "stereo quality mode is selected globally."); private GUIContent occlusionLabel = new GUIContent("Enable Occlusion", "Sets whether the sound of the source should be occluded when there are other objects " + "between the source and the listener."); private GUIContent spreadLabel = new GUIContent("Spread", "Source spread in degrees."); void OnEnable () { clip = serializedObject.FindProperty("sourceClip"); loop = serializedObject.FindProperty("sourceLoop"); mute = serializedObject.FindProperty("sourceMute"); pitch = serializedObject.FindProperty("sourcePitch"); playOnAwake = serializedObject.FindProperty("playOnAwake"); priority = serializedObject.FindProperty("sourcePriority"); volume = serializedObject.FindProperty("sourceVolume"); rolloffMode = serializedObject.FindProperty("rolloffMode"); maxDistance = serializedObject.FindProperty("sourceMaxDistance"); minDistance = serializedObject.FindProperty("sourceMinDistance"); bypassRoomEffects = serializedObject.FindProperty("bypassRoomEffects"); directivityAlpha = serializedObject.FindProperty("directivityAlpha"); directivitySharpness = serializedObject.FindProperty("directivitySharpness"); directivityTexture = Texture2D.blackTexture; gainDb = serializedObject.FindProperty("gainDb"); hrtfEnabled = serializedObject.FindProperty("hrtfEnabled"); occlusionEnabled = serializedObject.FindProperty("occlusionEnabled"); spread = serializedObject.FindProperty("spread"); } /// @cond public override void OnInspectorGUI () { serializedObject.Update(); // Add clickable script field, as would have been provided by DrawDefaultInspector() MonoScript script = MonoScript.FromMonoBehaviour (target as MonoBehaviour); EditorGUI.BeginDisabledGroup (true); EditorGUILayout.ObjectField ("Script", script, typeof(MonoScript), false); EditorGUI.EndDisabledGroup (); EditorGUILayout.PropertyField(clip, clipLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(mute, muteLabel); EditorGUILayout.PropertyField(bypassRoomEffects, bypassRoomEffectsLabel); EditorGUILayout.PropertyField(playOnAwake, playOnAwakeLabel); EditorGUILayout.PropertyField(loop, loopLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(priority, priorityLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(volume, volumeLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(pitch, pitchLabel); EditorGUILayout.Separator(); EditorGUILayout.Slider(gainDb, GvrAudio.minGainDb, GvrAudio.maxGainDb, gainLabel); EditorGUILayout.Separator(); EditorGUILayout.PropertyField(spread, spreadLabel); EditorGUILayout.PropertyField(rolloffMode, rolloffModeLabel); ++EditorGUI.indentLevel; EditorGUILayout.PropertyField(minDistance, minDistanceLabel); EditorGUILayout.PropertyField(maxDistance, maxDistanceLabel); --EditorGUI.indentLevel; if (rolloffMode.enumValueIndex == (int)AudioRolloffMode.Custom) { EditorGUILayout.HelpBox("Custom rolloff mode is not supported, no distance attenuation " + "will be applied.", MessageType.Warning); } EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginVertical(); GUILayout.Label(directivityLabel); ++EditorGUI.indentLevel; EditorGUILayout.Slider(directivityAlpha, 0.0f, 1.0f, directivityAlphaLabel); EditorGUILayout.Slider(directivitySharpness, 1.0f, 10.0f, directivitySharpnessLabel); --EditorGUI.indentLevel; EditorGUILayout.EndVertical(); DrawDirectivityPattern((int)(3.0f * EditorGUIUtility.singleLineHeight)); EditorGUILayout.EndHorizontal(); EditorGUILayout.PropertyField(occlusionEnabled, occlusionLabel); EditorGUILayout.Separator(); // HRTF toggle can only be modified through the Inspector in Edit mode. GUI.enabled = !EditorApplication.isPlaying; EditorGUILayout.PropertyField(hrtfEnabled, hrtfEnabledLabel); GUI.enabled = true; serializedObject.ApplyModifiedProperties(); } /// @endcond private void DrawDirectivityPattern (int size) { directivityTexture.Resize(size, size); // Draw the axes. Color axisColor = 0.5f * Color.black; for (int i = 0; i < size; ++i) { directivityTexture.SetPixel(i, size / 2, axisColor); directivityTexture.SetPixel(size / 2, i, axisColor); } // Draw the 2D polar directivity pattern. Color cardioidColor = 0.75f * Color.blue; float offset = 0.5f * size; float cardioidSize = 0.45f * size; Vector2[] vertices = GvrAudio.Generate2dPolarPattern(directivityAlpha.floatValue, directivitySharpness.floatValue, 180); for (int i = 0; i < vertices.Length; ++i) { directivityTexture.SetPixel((int)(offset + cardioidSize * vertices[i].x), (int)(offset + cardioidSize * vertices[i].y), cardioidColor); } directivityTexture.Apply(); // Show the texture. GUILayout.Box(directivityTexture); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace BatchClientIntegrationTests { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Storage.Blobs; using BatchTestCommon; using Fixtures; using Microsoft.Azure.Batch; using Microsoft.Azure.Batch.Common; using IntegrationTestCommon; using IntegrationTestUtilities; using Microsoft.Azure.Batch.Protocol.BatchRequests; using Microsoft.Azure.Batch.Auth; using Microsoft.Azure.Batch.Integration.Tests.Infrastructure; using Microsoft.Rest.Azure; using Xunit; using Xunit.Abstractions; using Protocol = Microsoft.Azure.Batch.Protocol; using Microsoft.Azure.Batch.Integration.Tests.IntegrationTestUtilities; public class CloudPoolIntegrationTests { private readonly ITestOutputHelper testOutputHelper; private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(5); private static readonly TimeSpan TestTimeout = TimeSpan.FromMinutes(1); public CloudPoolIntegrationTests(ITestOutputHelper testOutputHelper) { this.testOutputHelper = testOutputHelper; //Note -- this class does not and should not need a pool fixture } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public async Task PoolPatch() { static async Task test() { using BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false); string poolId = "TestPatchPool-" + TestUtilities.GetMyName(); const string metadataKey = "Foo"; const string metadataValue = "Bar"; const string startTaskCommandLine = "cmd /c dir"; try { CloudPool pool = batchCli.PoolOperations.CreatePool( poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0); await pool.CommitAsync().ConfigureAwait(false); await pool.RefreshAsync().ConfigureAwait(false); pool.StartTask = new StartTask(startTaskCommandLine); pool.Metadata = new List<MetadataItem>() { new MetadataItem(metadataKey, metadataValue) }; await pool.CommitChangesAsync().ConfigureAwait(false); await pool.RefreshAsync().ConfigureAwait(false); Assert.Equal(startTaskCommandLine, pool.StartTask.CommandLine); Assert.Equal(metadataKey, pool.Metadata.Single().Name); Assert.Equal(metadataValue, pool.Metadata.Single().Value); } finally { await TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).ConfigureAwait(false); } } await SynchronizationContextHelper.RunTestAsync(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void Bug1505248SupportMultipleTasksPerComputeNodeOnPoolAndPoolUserSpec() { static void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); // create a pool with the two new props string poolId = "Bug1505248SupportMultipleTasksPerComputeNode-pool-" + TestUtilities.GetMyName(); try { CloudPool newPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0); newPool.TaskSlotsPerNode = 3; newPool.TaskSchedulingPolicy = new TaskSchedulingPolicy(Microsoft.Azure.Batch.Common.ComputeNodeFillType.Pack); newPool.Commit(); CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId); Assert.Equal(3, boundPool.TaskSlotsPerNode); Assert.Equal(ComputeNodeFillType.Pack, boundPool.TaskSchedulingPolicy.ComputeNodeFillType); } finally { TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } string jobId = "Bug1505248SupportMultipleTasksPerComputeNode-Job-" + TestUtilities.GetMyName(); try { // create a job with new props set on pooluserspec { CloudJob unboundJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation()); AutoPoolSpecification unboundAPS = new AutoPoolSpecification(); PoolSpecification unboundPS = new PoolSpecification(); unboundJob.PoolInformation.AutoPoolSpecification = unboundAPS; unboundAPS.PoolSpecification = unboundPS; unboundPS.TaskSlotsPerNode = 3; unboundAPS.PoolSpecification.TargetDedicatedComputeNodes = 0; // don't use up compute nodes for this test unboundPS.TaskSchedulingPolicy = new TaskSchedulingPolicy(Microsoft.Azure.Batch.Common.ComputeNodeFillType.Pack); // required but unrelated to test unboundPS.VirtualMachineSize = PoolFixture.VMSize; unboundPS.CloudServiceConfiguration = new CloudServiceConfiguration(PoolFixture.OSFamily); unboundAPS.PoolLifetimeOption = Microsoft.Azure.Batch.Common.PoolLifetimeOption.Job; unboundJob.Commit(); } // confirm props were set CloudJob boundJob = batchCli.JobOperations.GetJob(jobId); PoolInformation poolInformation = boundJob.PoolInformation; AutoPoolSpecification boundAPS = poolInformation.AutoPoolSpecification; PoolSpecification boundPUS = boundAPS.PoolSpecification; Assert.Equal(3, boundPUS.TaskSlotsPerNode); Assert.Equal(ComputeNodeFillType.Pack, boundPUS.TaskSchedulingPolicy.ComputeNodeFillType); // change the props //TODO: Possible change this test to use a JobSchedule here? //boundPUS.MaxTasksPerComputeNode = 2; //boundPUS.TaskSchedulingPolicy = new TaskSchedulingPolicy(Microsoft.Azure.Batch.Common.ComputeNodeFillType.Spread); //boundJob.Commit(); //boundJob.Refresh(); //boundAPS = boundJob.PoolInformation.AutoPoolSpecification; //boundPUS = boundAPS.PoolSpecification; //Debug.Assert(2 == boundPUS.MaxTasksPerComputeNode); //Debug.Assert(Microsoft.Azure.Batch.Common.ComputeNodeFillType.Spread == boundPUS.TaskSchedulingPolicy.ComputeNodeFillType); } finally { TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait(); } } SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)] public void Bug1587303StartTaskResourceFilesNotPushedToServer() { static void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = "Bug1587303Pool-" + TestUtilities.GetMyName(); const string resourceFileSas = "http://azure.com"; const string resourceFileValue = "count0ResFiles.exe"; const string envSettingName = "envName"; const string envSettingValue = "envValue"; try { // create a pool with env-settings and ResFiles { CloudPool myPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0); StartTask st = new StartTask("dir"); MakeResourceFiles(st, resourceFileSas, resourceFileValue); AddEnviornmentSettingsToStartTask(st, envSettingName, envSettingValue); // set the pool's start task so the collections get pushed myPool.StartTask = st; myPool.Commit(); } // confirm pool has correct values CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId); CheckResourceFiles(boundPool.StartTask, resourceFileSas, resourceFileValue); CheckEnvironmentSettingsOnStartTask(boundPool.StartTask, envSettingName, envSettingValue); // clear the collections boundPool.StartTask.EnvironmentSettings = null; boundPool.StartTask.ResourceFiles = null; boundPool.Commit(); boundPool.Refresh(); StartTask boundST = boundPool.StartTask; // confirm the collections are cleared/null Assert.Null(boundST.ResourceFiles); Assert.Null(boundST.EnvironmentSettings); // set the collections again MakeResourceFiles(boundST, resourceFileSas, resourceFileValue); AddEnviornmentSettingsToStartTask(boundST, envSettingName, envSettingValue); boundPool.Commit(); boundPool.Refresh(); // confirm the collectsion are correctly re-established CheckResourceFiles(boundPool.StartTask, resourceFileSas, resourceFileValue); CheckEnvironmentSettingsOnStartTask(boundPool.StartTask, envSettingName, envSettingValue); //set collections to empty-but-non-null collections IList<ResourceFile> emptyResfiles = new List<ResourceFile>(); IList<EnvironmentSetting> emptyEnvSettings = new List<EnvironmentSetting>(); boundPool.StartTask.EnvironmentSettings = emptyEnvSettings; boundPool.StartTask.ResourceFiles = emptyResfiles; boundPool.Commit(); boundPool.Refresh(); boundST = boundPool.StartTask; var count0ResFiles = boundPool.StartTask.ResourceFiles; var count0EnvSettings = boundPool.StartTask.EnvironmentSettings; // confirm that the collections are non-null and have count-0 Assert.NotNull(count0ResFiles); Assert.NotNull(count0EnvSettings); Assert.Empty(count0ResFiles); Assert.Empty(count0EnvSettings); //clean up boundPool.Delete(); System.Threading.Thread.Sleep(5000); // wait for pool to be deleted // check pool create with empty-but-non-null collections { CloudPool myPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0); StartTask st = new StartTask("dir") { // use the empty collections from above ResourceFiles = emptyResfiles, EnvironmentSettings = emptyEnvSettings }; // set the pool's start task so the collections get pushed myPool.StartTask = st; myPool.Commit(); } boundPool = batchCli.PoolOperations.GetPool(poolId); boundST = boundPool.StartTask; count0ResFiles = boundPool.StartTask.ResourceFiles; count0EnvSettings = boundPool.StartTask.EnvironmentSettings; // confirm that the collections are non-null and have count-0 Assert.NotNull(count0ResFiles); Assert.NotNull(count0EnvSettings); Assert.Empty(count0ResFiles); Assert.Empty(count0EnvSettings); } finally { // cleanup TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.MediumDuration)] public void Bug1433123PoolMissingResizeTimeout() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = "Bug1433123PoolMissingResizeTimeout-" + TestUtilities.GetMyName(); try { TimeSpan referenceRST = TimeSpan.FromMinutes(5); // create a pool with env-settings and ResFiles { CloudPool myPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0); // set the reference value myPool.ResizeTimeout = referenceRST; myPool.Commit(); } // confirm pool has correct values CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId); // confirm value is correct Assert.Equal(referenceRST, boundPool.ResizeTimeout); // confirm constraint does not allow changes to bound object TestUtilities.AssertThrows<InvalidOperationException>(() => boundPool.ResizeTimeout = TimeSpan.FromMinutes(1)); } finally { // cleanup TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void Bug1656475PoolLifetimeOption() { static void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string jsId = "Bug1656475PoolLifetimeOption-" + TestUtilities.GetMyName(); try { { CloudJobSchedule unboundJobSchedule = batchCli.JobScheduleOperations.CreateJobSchedule(); unboundJobSchedule.Schedule = new Schedule() { RecurrenceInterval = TimeSpan.FromMinutes(10) }; unboundJobSchedule.Id = jsId; AutoPoolSpecification iaps = new AutoPoolSpecification(); // test that it can be read from unbound/unset object PoolLifetimeOption defaultVal = iaps.PoolLifetimeOption; // test it can be set on unbound and read back iaps.PoolLifetimeOption = PoolLifetimeOption.JobSchedule; // read it back and confirm value Assert.Equal(PoolLifetimeOption.JobSchedule, iaps.PoolLifetimeOption); unboundJobSchedule.JobSpecification = new JobSpecification(new PoolInformation() { AutoPoolSpecification = iaps }); // make ias viable for adding the wi iaps.AutoPoolIdPrefix = Microsoft.Azure.Batch.Constants.DefaultConveniencePrefix + TestUtilities.GetMyName(); PoolSpecification ips = new PoolSpecification(); iaps.PoolSpecification = ips; ips.TargetDedicatedComputeNodes = 0; ips.VirtualMachineSize = PoolFixture.VMSize; ips.CloudServiceConfiguration = new CloudServiceConfiguration(PoolFixture.OSFamily); unboundJobSchedule.Commit(); } CloudJobSchedule boundJobSchedule = batchCli.JobScheduleOperations.GetJobSchedule(jsId); // confirm the PLO is set correctly on bound WI Assert.NotNull(boundJobSchedule); Assert.NotNull(boundJobSchedule.JobSpecification); Assert.NotNull(boundJobSchedule.JobSpecification.PoolInformation); Assert.NotNull(boundJobSchedule.JobSpecification.PoolInformation.AutoPoolSpecification); AutoPoolSpecification boundIAPS = boundJobSchedule.JobSpecification.PoolInformation.AutoPoolSpecification; Assert.Equal(PoolLifetimeOption.JobSchedule, boundIAPS.PoolLifetimeOption); // in phase 1 PLO is read-only on bound WI/APS so no tests to change it here } finally { // cleanup TestUtilities.DeleteJobScheduleIfExistsAsync(batchCli, jsId).Wait(); } } SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongDuration)] public void Bug1432812SetAutoScaleMissingOnPoolPoolMgr() { static void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = "Bug1432812-" + TestUtilities.GetMyName(); const string poolASFormulaOrig = "$TargetDedicatedNodes=0;"; const string poolASFormula2 = "$TargetDedicatedNodes=1;"; // craft exactly how it would be returned by Evaluate so indexof can work try { // create a pool.. empty for now { CloudPool unboundPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily)); unboundPool.AutoScaleEnabled = true; unboundPool.AutoScaleFormula = poolASFormulaOrig; unboundPool.Commit(); TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromSeconds(20)).Wait(); } // EvaluteAutoScale CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId); Assert.True(boundPool.AutoScaleEnabled.HasValue); Assert.True(boundPool.AutoScaleEnabled.Value); Assert.Equal(poolASFormulaOrig, boundPool.AutoScaleFormula); AutoScaleRun eval = boundPool.EvaluateAutoScale(poolASFormula2); Assert.Contains(poolASFormula2, eval.Results); // DisableAutoScale boundPool.DisableAutoScale(); boundPool.Refresh(); // autoscale should be disabled now Assert.True(boundPool.AutoScaleEnabled.HasValue); Assert.False(boundPool.AutoScaleEnabled.Value); // EnableAutoScale TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(5)).Wait(); boundPool.EnableAutoScale(poolASFormula2); boundPool.Refresh(); // confirm is enabled and formula has correct value Assert.True(boundPool.AutoScaleEnabled.HasValue); Assert.True(boundPool.AutoScaleEnabled.Value); Assert.Equal(poolASFormula2, boundPool.AutoScaleFormula); } finally { TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void Bug1432819UpdateImplOnCloudPool() { static void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = "Bug1432819-" + TestUtilities.GetMyName(); try { CloudPool unboundPool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: 0); unboundPool.Commit(); CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId); IList<MetadataItem> changedMDI = new List<MetadataItem> { new MetadataItem("name", "value") }; boundPool.Metadata = changedMDI; boundPool.Commit(); CloudPool boundPool2 = batchCli.PoolOperations.GetPool(poolId); Assert.NotNull(boundPool2.Metadata); // confirm the pool was updated foreach (MetadataItem curMDI in boundPool2.Metadata) { Assert.Equal("name", curMDI.Name); Assert.Equal("value", curMDI.Value); } } finally { // cleanup TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void TestListPoolUsageMetrics() { static void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); // test via faking data DateTime endTime = DateTime.UtcNow.AddYears(-1); DateTime startTime = DateTime.UtcNow; const int totalCoreHours = 1; const string virtualMachineSize = "really really big"; List<Protocol.Models.PoolUsageMetrics> pums = new List<Protocol.Models.PoolUsageMetrics>(); // create some data to return for (int i = 0; i < 4; i++) { string id = "my fancy pool id " + i.ToString(); Protocol.Models.PoolUsageMetrics newPum = new Protocol.Models.PoolUsageMetrics() { PoolId = id, EndTime = endTime, StartTime = startTime, TotalCoreHours = totalCoreHours, VmSize = virtualMachineSize }; pums.Add(newPum); } // our injector of fake data TestListPoolUsageMetricsFakesYieldInjector injectsTheFakeData = new TestListPoolUsageMetricsFakesYieldInjector(pums); // trigger the call and get our own data back to be tested List<PoolUsageMetrics> clList = batchCli.PoolOperations.ListPoolUsageMetrics(additionalBehaviors: new[] { injectsTheFakeData }).ToList(); // test that our data are honored for (int j = 0; j < 4; j++) { string id = "my fancy pool id " + j.ToString(); Assert.Equal(id, clList[j].PoolId); Assert.Equal(endTime, clList[j].EndTime); Assert.Equal(startTime, clList[j].StartTime); Assert.Equal(totalCoreHours, clList[j].TotalCoreHours); Assert.Equal(virtualMachineSize, clList[j].VirtualMachineSize); } List<PoolUsageMetrics> list = batchCli.PoolOperations.ListPoolUsageMetrics(DateTime.Now - TimeSpan.FromDays(1)).ToList(); } SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void TestPoolObjectResizeStopResize() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = "TestPoolObjectResizeStopResize" + TestUtilities.GetMyName(); const int targetDedicated = 0; const int newTargetDedicated = 1; try { //Create a pool CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: targetDedicated); pool.Commit(); TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromSeconds(20)).Wait(); testOutputHelper.WriteLine($"Created pool {poolId}"); CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId); //Resize the pool boundPool.Resize(newTargetDedicated, 0); boundPool.Refresh(); Assert.Equal(AllocationState.Resizing, boundPool.AllocationState); boundPool.StopResize(); boundPool.Refresh(); //The pool could be in stopping or steady state testOutputHelper.WriteLine($"Pool allocation state: {boundPool.AllocationState}"); Assert.True(boundPool.AllocationState == AllocationState.Steady || boundPool.AllocationState == AllocationState.Stopping); } finally { //Delete the pool TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongDuration)] public void TestPoolAutoscaleVerbs() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = TestUtilities.GenerateResourceId(); const int targetDedicated = 0; const string autoscaleFormula1 = "$TargetDedicatedNodes=0;$TargetLowPriorityNodes=0;$NodeDeallocationOption=requeue"; const string autoscaleFormula2 = "$TargetDedicatedNodes=0;$TargetLowPriorityNodes=0;$NodeDeallocationOption=terminate"; const string evaluateAutoscaleFormula = "myActiveSamples=$ActiveTasks.GetSample(5);"; TimeSpan enableAutoScaleMinimumDelay = TimeSpan.FromSeconds(30); // compiler says can't be const try { //Create a pool CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicated); pool.Commit(); TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromSeconds(20)).Wait(); CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId); //Enable autoscale (via instance) boundPool.EnableAutoScale(autoscaleFormula1); DateTime utcEarliestCanCallEnableASAgain = DateTime.UtcNow + enableAutoScaleMinimumDelay; boundPool.Refresh(); Assert.True(boundPool.AutoScaleEnabled); Assert.Equal(autoscaleFormula1, boundPool.AutoScaleFormula); testOutputHelper.WriteLine($"Got the pool"); Assert.NotNull(boundPool.AutoScaleRun); Assert.NotNull(boundPool.AutoScaleRun.Results); Assert.Contains(autoscaleFormula1, boundPool.AutoScaleRun.Results); //Evaluate a different formula AutoScaleRun evaluation = boundPool.EvaluateAutoScale(evaluateAutoscaleFormula); testOutputHelper.WriteLine("Autoscale evaluate results: {0}", evaluation.Results); Assert.NotNull(evaluation.Results); Assert.Contains("myActiveSamples", evaluation.Results); //Disable autoscale (via instance) boundPool.DisableAutoScale(); boundPool.Refresh(); Assert.False(boundPool.AutoScaleEnabled); //Wait for the pool to go to steady state TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(2)).Wait(); // about to call EnableAutoScale again, must delay to avoid throttle exception if (DateTime.UtcNow < utcEarliestCanCallEnableASAgain) { TimeSpan delayBeforeNextEnableASCall = utcEarliestCanCallEnableASAgain - DateTime.UtcNow; Thread.Sleep(delayBeforeNextEnableASCall); } //Enable autoscale (via operations) batchCli.PoolOperations.EnableAutoScale(poolId, autoscaleFormula2); boundPool.Refresh(); Assert.True(boundPool.AutoScaleEnabled); Assert.Equal(autoscaleFormula2, boundPool.AutoScaleFormula); Assert.NotNull(boundPool.AutoScaleRun); Assert.NotNull(boundPool.AutoScaleRun.Results); Assert.Contains(autoscaleFormula2, boundPool.AutoScaleRun.Results); evaluation = batchCli.PoolOperations.EvaluateAutoScale(poolId, evaluateAutoscaleFormula); testOutputHelper.WriteLine("Autoscale evaluate results: {0}", evaluation.Results); Assert.NotNull(evaluation); Assert.Contains("myActiveSamples", evaluation.Results); batchCli.PoolOperations.DisableAutoScale(poolId); boundPool.Refresh(); Assert.False(boundPool.AutoScaleEnabled); } finally { //Delete the pool TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public async Task TestServerRejectsNonExistantVNetWithCorrectError() { async Task test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = "TestPoolVNet" + TestUtilities.GetMyName(); const int targetDedicated = 0; string dummySubnetId = string.Format("/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.ClassicNetwork/virtualNetworks/vnet1/subnets/subnet1", TestCommon.Configuration.BatchSubscription, TestCommon.Configuration.BatchAccountResourceGroup); try { CloudPool pool = batchCli.PoolOperations.CreatePool( poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicated); pool.NetworkConfiguration = new NetworkConfiguration() { SubnetId = dummySubnetId }; BatchException exception = await TestUtilities.AssertThrowsAsync<BatchException>(async () => await pool.CommitAsync().ConfigureAwait(false)).ConfigureAwait(false); Assert.Equal(BatchErrorCodeStrings.InvalidPropertyValue, exception.RequestInformation.BatchError.Code); Assert.Equal("Either the specified VNet does not exist, or the Batch service does not have access to it", exception.RequestInformation.BatchError.Values.Single(value => value.Key == "Reason").Value); } finally { //Delete the pool TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } await SynchronizationContextHelper.RunTestAsync(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void TestPoolCreatedWithUserAccountsSucceeds() { static void test() { using BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result; string poolId = "TestPoolCreatedWithUserAccounts" + TestUtilities.GetMyName(); const int targetDedicated = 0; try { var nodeUserPassword = TestUtilities.GenerateRandomPassword(); //Create a pool CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicated); pool.UserAccounts = new List<UserAccount>() { new UserAccount("test1", nodeUserPassword), new UserAccount("test2", nodeUserPassword, ElevationLevel.NonAdmin), new UserAccount("test3", nodeUserPassword, ElevationLevel.Admin), new UserAccount("test4", nodeUserPassword, linuxUserConfiguration: new LinuxUserConfiguration(sshPrivateKey: "AAAA==")), }; pool.Commit(); CloudPool boundPool = batchCli.PoolOperations.GetPool(poolId); Assert.Equal(pool.UserAccounts.Count, boundPool.UserAccounts.Count); var results = pool.UserAccounts.Zip(boundPool.UserAccounts, (expected, actual) => new { Submitted = expected, Returned = actual }); foreach (var result in results) { Assert.Equal(result.Submitted.Name, result.Returned.Name); Assert.Null(result.Returned.Password); Assert.Equal(result.Submitted.ElevationLevel ?? ElevationLevel.NonAdmin, result.Returned.ElevationLevel); Assert.Null(result.Returned.LinuxUserConfiguration?.SshPrivateKey); } } finally { //Delete the pool TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void TestPoolCreatedOSDiskSucceeds() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result; string poolId = nameof(TestPoolCreatedOSDiskSucceeds) + TestUtilities.GetMyName(); const int targetDedicated = 0; try { var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(batchCli); //Create a pool CloudPool pool = batchCli.PoolOperations.CreatePool( poolId, PoolFixture.VMSize, new VirtualMachineConfiguration( imageDetails.ImageReference, imageDetails.NodeAgentSkuId) { LicenseType = "Windows_Server" }, targetDedicated); pool.Commit(); pool.Refresh(); Assert.Equal("Windows_Server", pool.VirtualMachineConfiguration.LicenseType); } finally { //Delete the pool TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void TestPoolCreatedDataDiskSucceeds() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result; string poolId = nameof(TestPoolCreatedDataDiskSucceeds) + TestUtilities.GetMyName(); const int targetDedicated = 0; try { var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(batchCli); const int lun = 50; const int diskSizeGB = 50; //Create a pool CloudPool pool = batchCli.PoolOperations.CreatePool( poolId, PoolFixture.VMSize, new VirtualMachineConfiguration( imageDetails.ImageReference, imageDetails.NodeAgentSkuId) { DataDisks = new List<DataDisk> { new DataDisk(lun, diskSizeGB) } }, targetDedicated); pool.Commit(); pool.Refresh(); Assert.Equal(lun, pool.VirtualMachineConfiguration.DataDisks.Single().Lun); Assert.Equal(diskSizeGB, pool.VirtualMachineConfiguration.DataDisks.Single().DiskSizeGB); } finally { //Delete the pool TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void TestPoolCreatedCustomImageExpectedError() { void test() { static Task<string> tokenProvider() => IntegrationTestCommon.GetAuthenticationTokenAsync("https://batch.core.windows.net/"); using var client = BatchClient.Open(new BatchTokenCredentials(TestCommon.Configuration.BatchAccountUrl, tokenProvider)); string poolId = "TestPoolCreatedWithCustomImage" + TestUtilities.GetMyName(); const int targetDedicated = 0; try { var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(client); //Create a pool CloudPool pool = client.PoolOperations.CreatePool( poolId, PoolFixture.VMSize, new VirtualMachineConfiguration( new ImageReference( $"/subscriptions/{TestCommon.Configuration.BatchSubscription}/resourceGroups/{TestCommon.Configuration.BatchAccountResourceGroup}/providers/Microsoft.Compute/galleries/FakeGallery/images/FakeImage/versions/FakeImageVersion"), imageDetails.NodeAgentSkuId), targetDedicated); var exception = Assert.Throws<BatchException>(() => pool.Commit()); Assert.Equal("InsufficientPermissions", exception.RequestInformation.BatchError.Code); Assert.Contains( "The user identity used for this operation does not have the required privelege Microsoft.Compute/galleries/images/versions/read on the specified resource", exception.RequestInformation.BatchError.Values.Single().Value); } finally { //Delete the pool TestUtilities.DeletePoolIfExistsAsync(client, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } [Theory] [LiveTest] [InlineData(1, 0)] [InlineData(0, 1)] [InlineData(1, null)] [InlineData(null, 1)] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public async Task ResizePool_AcceptedByServer(int? targetDedicated, int? targetLowPriority) { async Task test() { using BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false); string poolId = TestUtilities.GenerateResourceId(); try { CloudPool pool = batchCli.PoolOperations.CreatePool( poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily)); await pool.CommitAsync().ConfigureAwait(false); await pool.RefreshAsync().ConfigureAwait(false); await TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(1)); await pool.ResizeAsync( targetDedicatedComputeNodes: targetDedicated, targetLowPriorityComputeNodes: targetLowPriority, resizeTimeout: TimeSpan.FromMinutes(10)).ConfigureAwait(false); await pool.RefreshAsync().ConfigureAwait(false); Assert.Equal(targetDedicated ?? 0, pool.TargetDedicatedComputeNodes); Assert.Equal(targetLowPriority ?? 0, pool.TargetLowPriorityComputeNodes); Assert.Equal(AllocationState.Resizing, pool.AllocationState); } finally { await TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).ConfigureAwait(false); } } await SynchronizationContextHelper.RunTestAsync(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void PoolStateCount_IsReturnedFromServer() { static void test() { using BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result; var nodeCounts = batchCli.PoolOperations.ListPoolNodeCounts(); Assert.NotEmpty(nodeCounts); var poolId = nodeCounts.First().PoolId; foreach (var poolNodeCount in nodeCounts) { Assert.NotEmpty(poolNodeCount.PoolId); Assert.NotNull(poolNodeCount.Dedicated); Assert.NotNull(poolNodeCount.LowPriority); // Check a few properties at random Assert.Equal(0, poolNodeCount.LowPriority.Unusable); Assert.Equal(0, poolNodeCount.LowPriority.Offline); } var filteredNodeCounts = batchCli.PoolOperations.ListPoolNodeCounts(new ODATADetailLevel(filterClause: $"poolId eq '{poolId}'")).ToList(); Assert.Single(filteredNodeCounts); } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void ListSupportedImages() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); var supportedImages = batchCli.PoolOperations.ListSupportedImages().ToList(); Assert.True(supportedImages.Count > 0); foreach (ImageInformation imageInfo in supportedImages) { testOutputHelper.WriteLine("ImageInformation:"); testOutputHelper.WriteLine(" skuid: " + imageInfo.NodeAgentSkuId); testOutputHelper.WriteLine(" OSType: " + imageInfo.OSType); testOutputHelper.WriteLine(" publisher: " + imageInfo.ImageReference.Publisher); testOutputHelper.WriteLine(" offer: " + imageInfo.ImageReference.Offer); testOutputHelper.WriteLine(" sku: " + imageInfo.ImageReference.Sku); testOutputHelper.WriteLine(" version: " + imageInfo.ImageReference.Version); } } SynchronizationContextHelper.RunTest(test, timeout: TimeSpan.FromSeconds(60)); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public async Task CreatePool_WithBlobFuseMountConfiguration() { static async Task test() { using BatchClient batchCli = await TestUtilities.OpenBatchClientFromEnvironmentAsync().ConfigureAwait(false); string poolId = TestUtilities.GenerateResourceId(); const string containerName = "blobfusecontainer"; StagingStorageAccount storageAccount = TestUtilities.GetStorageCredentialsFromEnvironment(); BlobContainerClient containerClient = BlobUtilities.GetBlobContainerClient(containerName, storageAccount); containerClient.CreateIfNotExists(); try { var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(batchCli); CloudPool pool = batchCli.PoolOperations.CreatePool( poolId, PoolFixture.VMSize, new VirtualMachineConfiguration( imageDetails.ImageReference, imageDetails.NodeAgentSkuId)); pool.MountConfiguration = new List<MountConfiguration> { new MountConfiguration( new AzureBlobFileSystemConfiguration( storageAccount.StorageAccount, containerName, "foo", AzureStorageAuthenticationKey.FromAccountKey(storageAccount.StorageAccountKey))) }; await pool.CommitAsync().ConfigureAwait(false); await pool.RefreshAsync().ConfigureAwait(false); Assert.NotNull(pool.MountConfiguration); Assert.NotEmpty(pool.MountConfiguration); Assert.Equal(storageAccount.StorageAccount, pool.MountConfiguration.Single().AzureBlobFileSystemConfiguration.AccountName); Assert.Equal(containerName, pool.MountConfiguration.Single().AzureBlobFileSystemConfiguration.ContainerName); } finally { await TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).ConfigureAwait(false); } } await SynchronizationContextHelper.RunTestAsync(test, TestTimeout); } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.ShortDuration)] public void TestCreatePoolEncryptionEnabled() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClientFromEnvironmentAsync().Result; string poolId = nameof(TestCreatePoolEncryptionEnabled) + TestUtilities.GetMyName(); const int targetDedicated = 0; try { var imageDetails = IaasLinuxPoolFixture.GetUbuntuImageDetails(batchCli); //Create a pool CloudPool pool = batchCli.PoolOperations.CreatePool( poolId, PoolFixture.VMSize, new VirtualMachineConfiguration( imageDetails.ImageReference, imageDetails.NodeAgentSkuId) { DiskEncryptionConfiguration = new DiskEncryptionConfiguration(new List<DiskEncryptionTarget> { DiskEncryptionTarget.TemporaryDisk }) }, targetDedicated); pool.Commit(); pool.Refresh(); Assert.Single(pool.VirtualMachineConfiguration.DiskEncryptionConfiguration.Targets, DiskEncryptionTarget.TemporaryDisk); } finally { //Delete the pool TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } #region Test helpers /// <summary> /// injects a fake response /// </summary> internal class TestListPoolUsageMetricsFakesYieldInjector : Protocol.RequestInterceptor { // the fake data to be returned internal IList<Protocol.Models.PoolUsageMetrics> _poolUsageMetricsList; // returns our response... the fake private Task<AzureOperationResponse<IPage<Protocol.Models.PoolUsageMetrics>, Protocol.Models.PoolListUsageMetricsHeaders>> NewFunc(CancellationToken token) { var response = new AzureOperationResponse<IPage<Protocol.Models.PoolUsageMetrics>, Protocol.Models.PoolListUsageMetricsHeaders>() { Body = new FakePage<Protocol.Models.PoolUsageMetrics>(_poolUsageMetricsList) }; return System.Threading.Tasks.Task.FromResult(response); } // replaces the func with our own func private void RequestInterceptor(Protocol.IBatchRequest requestBase) { // mung the func ((PoolListPoolUsageMetricsBatchRequest)requestBase).ServiceRequestFunc = NewFunc; } private TestListPoolUsageMetricsFakesYieldInjector() { } internal TestListPoolUsageMetricsFakesYieldInjector(IList<Protocol.Models.PoolUsageMetrics> poolUsageMetricsList) { // here is our interceptor base.ModificationInterceptHandler = RequestInterceptor; // remember our fake data _poolUsageMetricsList = poolUsageMetricsList; } } private static void AddEnviornmentSettingsToStartTask(StartTask start, string envSettingName, string envSettingValue) { List<EnvironmentSetting> settings = new List<EnvironmentSetting>(); EnvironmentSetting newES = new EnvironmentSetting(envSettingName, envSettingValue); settings.Add(newES); start.EnvironmentSettings = settings; foreach (EnvironmentSetting curES in start.EnvironmentSettings) { Assert.Equal(envSettingName, curES.Name); Assert.Equal(envSettingValue, curES.Value); } } private static void CheckEnvironmentSettingsOnStartTask(StartTask start, string envSettingName, string envSettingValue) { foreach (EnvironmentSetting curES in start.EnvironmentSettings) { Assert.Equal(envSettingName, curES.Name); Assert.Equal(envSettingValue, curES.Value); } } private static void MakeResourceFiles(StartTask start, string resourceFileSas, string resourceFileValue) { List<ResourceFile> files = new List<ResourceFile>(); ResourceFile newRR = ResourceFile.FromUrl(resourceFileSas, resourceFileValue); files.Add(newRR); start.ResourceFiles = files; CheckResourceFiles(start, resourceFileSas, resourceFileValue); } /// <summary> /// Asserts that the resource files in the StartTask exactly match /// those created in MakeResourceFiles(). /// </summary> /// <param name="st"></param> private static void CheckResourceFiles(StartTask st, string resourceFileSas, string resourceFileValue) { foreach (ResourceFile curRF in st.ResourceFiles) { Assert.Equal(curRF.HttpUrl, resourceFileSas); Assert.Equal(curRF.FilePath, resourceFileValue); } } #endregion } /// <summary> /// This class exists because XUnit doesn't run tests in a single class in parallel. To reduce test runtime, /// the longest running pool tests have been split out into multiple classes. /// </summary> public class IntegrationCloudPoolLongRunningTests01 { private readonly ITestOutputHelper testOutputHelper; private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(20); public IntegrationCloudPoolLongRunningTests01(ITestOutputHelper testOutputHelper) { this.testOutputHelper = testOutputHelper; //Note -- this class does not and should not need a pool fixture } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongLongDuration)] public void LongRunning_RemovePoolComputeNodesResizeTimeout_ResizeErrorsPopulated() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = "Bug2251050_TestRemoveComputeNodesResizeTimeout_LR" + TestUtilities.GetMyName(); string jobId = "Bug2251050Job-" + TestUtilities.GetMyName(); const int targetDedicated = 2; try { //Create a pool with 2 compute nodes CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: targetDedicated); pool.Commit(); testOutputHelper.WriteLine("Created pool {0}", poolId); CloudPool refreshablePool = batchCli.PoolOperations.GetPool(poolId); //Wait for compute node allocation TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(5)).Wait(); refreshablePool.Refresh(); Assert.Equal(targetDedicated, refreshablePool.CurrentDedicatedComputeNodes); IEnumerable<ComputeNode> computeNodes = refreshablePool.ListComputeNodes(); Assert.Equal(targetDedicated, computeNodes.Count()); // //Create a job on this pool with targetDedicated tasks which run for 10m each // CloudJob workflowJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation() { PoolId = poolId }); workflowJob.Commit(); const int taskDurationSeconds = 600; string taskCmdLine = string.Format("ping 127.0.0.1 -n {0}", taskDurationSeconds); for (int i = 0; i < targetDedicated; i++) { string taskId = string.Format("T_{0}", i); batchCli.JobOperations.AddTask(jobId, new CloudTask(taskId, taskCmdLine)); } // // Wait for tasks to both go to running // Utilities utilities = batchCli.Utilities; TaskStateMonitor taskStateMonitor = utilities.CreateTaskStateMonitor(); taskStateMonitor.WaitAll( batchCli.JobOperations.ListTasks(jobId), Microsoft.Azure.Batch.Common.TaskState.Running, TimeSpan.FromMinutes(20)); // // Remove pool compute nodes // TimeSpan resizeTimeout = TimeSpan.FromMinutes(5); batchCli.PoolOperations.RemoveFromPool(poolId, computeNodes, ComputeNodeDeallocationOption.TaskCompletion, resizeTimeout); // // Wait for the resize to timeout // TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(6)).Wait(); refreshablePool.Refresh(); Assert.NotNull(refreshablePool.ResizeErrors); Assert.Equal(1, refreshablePool.ResizeErrors.Count); var resizeError = refreshablePool.ResizeErrors.Single(); Assert.Equal(PoolResizeErrorCodes.AllocationTimedOut, resizeError.Code); testOutputHelper.WriteLine("Resize error: {0}", resizeError.Message); } finally { //Delete the pool TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).Wait(); //Delete the job schedule TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait(); } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } } /// <summary> /// This class exists because XUnit doesn't run tests in a single class in parallel. To reduce test runtime, /// the longest running pool tests have been split out into multiple classes. /// </summary> public class IntegrationCloudPoolLongRunningTests02 { private readonly ITestOutputHelper testOutputHelper; private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(20); public IntegrationCloudPoolLongRunningTests02(ITestOutputHelper testOutputHelper) { this.testOutputHelper = testOutputHelper; //Note -- this class does not and should not need a pool fixture } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongLongDuration)] public void LongRunning_TestRemovePoolComputeNodes() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = "TestRemovePoolComputeNodes_LongRunning" + TestUtilities.GetMyName(); const int targetDedicated = 3; try { //Create a pool CloudPool pool = batchCli.PoolOperations.CreatePool(poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetDedicatedComputeNodes: targetDedicated); pool.Commit(); testOutputHelper.WriteLine("Created pool {0}", poolId); CloudPool refreshablePool = batchCli.PoolOperations.GetPool(poolId); //Wait for compute node allocation TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).Wait(); refreshablePool.Refresh(); Assert.Equal(targetDedicated, refreshablePool.CurrentDedicatedComputeNodes); IEnumerable<ComputeNode> computeNodes = refreshablePool.ListComputeNodes(); Assert.Equal(targetDedicated, computeNodes.Count()); // //Remove first compute node from the pool // ComputeNode computeNodeToRemove = computeNodes.First(); //For Bug234298 ensure start task property doesn't throw Assert.Null(computeNodeToRemove.StartTask); testOutputHelper.WriteLine("Will remove compute node: {0}", computeNodeToRemove.Id); //Remove the compute node from the pool by instance refreshablePool.RemoveFromPool(computeNodeToRemove); //Wait for pool to got to steady state again TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).Wait(); refreshablePool.Refresh(); //Ensure that the other ComputeNodes were not impacted and we now have 1 less ComputeNode List<ComputeNode> computeNodesAfterRemove = refreshablePool.ListComputeNodes().ToList(); Assert.Equal(targetDedicated - 1, computeNodesAfterRemove.Count); List<string> remainingComputeNodeIds = computeNodesAfterRemove.Select(computeNode => computeNode.Id).ToList(); foreach (ComputeNode originalComputeNode in computeNodes) { Assert.Contains(originalComputeNode.Id, remainingComputeNodeIds); } testOutputHelper.WriteLine("Verified that the compute node was removed correctly"); // //Remove a second compute node from the pool // ComputeNode secondComputeNodeToRemove = computeNodesAfterRemove.First(); string secondComputeNodeToRemoveId = secondComputeNodeToRemove.Id; //Remove the IComputeNode from the pool by id refreshablePool.RemoveFromPool(secondComputeNodeToRemoveId); //Wait for pool to got to steady state again TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).Wait(); refreshablePool.Refresh(); //Ensure that the other ComputeNodes were not impacted and we now have 1 less ComputeNode computeNodesAfterRemove = refreshablePool.ListComputeNodes().ToList(); Assert.Single(computeNodesAfterRemove); testOutputHelper.WriteLine("Verified that the compute node was removed correctly"); // //Remove a 3rd compute node from pool // ComputeNode thirdComputeNodeToRemove = computeNodesAfterRemove.First(); string thirdComputeNodeToRemoveId = thirdComputeNodeToRemove.Id; testOutputHelper.WriteLine("Will remove compute node: {0}", thirdComputeNodeToRemoveId); //Remove the IComputeNode from the pool using the ComputeNode object thirdComputeNodeToRemove.RemoveFromPool(); //Wait for pool to got to steady state again TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).Wait(); //Ensure that the other ComputeNodes were not impacted and we now have 1 less ComputeNode computeNodesAfterRemove = refreshablePool.ListComputeNodes().ToList(); Assert.Empty(computeNodesAfterRemove); testOutputHelper.WriteLine("Verified that the ComputeNode was removed correctly"); } finally { //Delete the pool batchCli.PoolOperations.DeletePool(poolId); } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } } /// <summary> /// This class exists because XUnit doesn't run tests in a single class in parallel. To reduce test runtime, /// the longest running pool tests have been split out into multiple classes. /// </summary> public class IntegrationCloudPoolLongRunningTests03 { private readonly ITestOutputHelper testOutputHelper; private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(20); public IntegrationCloudPoolLongRunningTests03(ITestOutputHelper testOutputHelper) { this.testOutputHelper = testOutputHelper; //Note -- this class does not and should not need a pool fixture } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongLongDuration)] public async Task LongRunning_LowPriorityComputeNodeAllocated_IsDedicatedFalse() { async Task test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string poolId = "TestLowPri_LongRunning" + TestUtilities.GetMyName(); const int targetLowPriority = 1; try { //Create a pool CloudPool pool = batchCli.PoolOperations.CreatePool( poolId, PoolFixture.VMSize, new CloudServiceConfiguration(PoolFixture.OSFamily), targetLowPriorityComputeNodes: targetLowPriority); await pool.CommitAsync().ConfigureAwait(false); testOutputHelper.WriteLine("Created pool {0}", poolId); await pool.RefreshAsync().ConfigureAwait(false); //Wait for compute node allocation await TestUtilities.WaitForPoolToReachStateAsync(batchCli, poolId, AllocationState.Steady, TimeSpan.FromMinutes(10)).ConfigureAwait(false); //Refresh pool to get latest from server await pool.RefreshAsync().ConfigureAwait(false); Assert.Equal(targetLowPriority, pool.CurrentLowPriorityComputeNodes); IEnumerable<ComputeNode> computeNodes = pool.ListComputeNodes(); Assert.Single(computeNodes); ComputeNode node = computeNodes.Single(); Assert.False(node.IsDedicated); } finally { //Delete the pool await TestUtilities.DeletePoolIfExistsAsync(batchCli, poolId).ConfigureAwait(false); } } await SynchronizationContextHelper.RunTestAsync(test, LongTestTimeout); } } [Collection("SharedPoolCollection")] public class IntegrationCloudPoolTestsWithSharedPool { private readonly PoolFixture poolFixture; private static readonly TimeSpan LongTestTimeout = TimeSpan.FromMinutes(20); public IntegrationCloudPoolTestsWithSharedPool(PaasWindowsPoolFixture poolFixture) { this.poolFixture = poolFixture; } [Fact] [LiveTest] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.LongLongDuration)] public void LongRunning_Bug1771277_1771278_RebootReimageComputeNode() { void test() { using BatchClient batchCli = TestUtilities.OpenBatchClient(TestUtilities.GetCredentialsFromEnvironment()); string jobId = "LongRunning_Bug1771277_1771278_RebootReimageComputeNode" + TestUtilities.GetMyName(); try { // // Get the pool and check its targets // CloudPool pool = batchCli.PoolOperations.GetPool(poolFixture.PoolId); // //Create a job on this pool with targetDedicated tasks which run for 2m each // const int taskDurationSeconds = 600; CloudJob workflowJob = batchCli.JobOperations.CreateJob(jobId, new PoolInformation() { PoolId = poolFixture.PoolId }); workflowJob.Commit(); CloudJob boundWorkflowJob = batchCli.JobOperations.GetJob(jobId); string taskCmdLine = string.Format("ping 127.0.0.1 -n {0}", taskDurationSeconds); for (int i = 0; i < pool.CurrentDedicatedComputeNodes; i++) { string taskId = string.Format("T_{0}", i); boundWorkflowJob.AddTask(new CloudTask(taskId, taskCmdLine)); } // // Wait for tasks to go to running // TaskStateMonitor taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor(); taskStateMonitor.WaitAll( batchCli.JobOperations.ListTasks(jobId), Microsoft.Azure.Batch.Common.TaskState.Running, TimeSpan.FromMinutes(2)); // // Reboot the compute nodes from the pool with requeue option and ensure tasks goes to Active again and compute node state goes to rebooting // IEnumerable<ComputeNode> computeNodes = pool.ListComputeNodes(); foreach (ComputeNode computeNode in computeNodes) { computeNode.Reboot(ComputeNodeRebootOption.Requeue); } //Ensure task goes to active state taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor(); taskStateMonitor.WaitAll( batchCli.JobOperations.ListTasks(jobId), Microsoft.Azure.Batch.Common.TaskState.Active, TimeSpan.FromMinutes(1)); //Ensure each compute node goes to rebooting state IEnumerable<ComputeNode> rebootingComputeNodes = batchCli.PoolOperations.ListComputeNodes(poolFixture.PoolId); foreach (ComputeNode computeNode in rebootingComputeNodes) { Assert.Equal(ComputeNodeState.Rebooting, computeNode.State); } //Wait for tasks to start to run again taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor(); taskStateMonitor.WaitAll( batchCli.JobOperations.ListTasks(jobId), Microsoft.Azure.Batch.Common.TaskState.Running, TimeSpan.FromMinutes(10)); // // Reimage a compute node from the pool with terminate option and ensure task goes to completed and compute node state goes to reimaging // computeNodes = pool.ListComputeNodes(); foreach (ComputeNode computeNode in computeNodes) { computeNode.Reimage(ComputeNodeReimageOption.Terminate); } //Ensure task goes to completed state taskStateMonitor = batchCli.Utilities.CreateTaskStateMonitor(); taskStateMonitor.WaitAll( batchCli.JobOperations.ListTasks(jobId), Microsoft.Azure.Batch.Common.TaskState.Completed, TimeSpan.FromMinutes(1)); //Ensure each compute node goes to reimaging state IEnumerable<ComputeNode> reimagingComputeNodes = batchCli.PoolOperations.ListComputeNodes(poolFixture.PoolId); foreach (ComputeNode computeNode in reimagingComputeNodes) { Assert.Equal(ComputeNodeState.Reimaging, computeNode.State); } } finally { //Delete the job TestUtilities.DeleteJobIfExistsAsync(batchCli, jobId).Wait(); //Wait until the compute nodes are idle again //TODO: Use a Utilities waiter TimeSpan computeNodeSteadyTimeout = TimeSpan.FromMinutes(15); DateTime allocationWaitStartTime = DateTime.UtcNow; DateTime timeoutAfterThisTimeUtc = allocationWaitStartTime.Add(computeNodeSteadyTimeout); IEnumerable<ComputeNode> computeNodes = batchCli.PoolOperations.ListComputeNodes(poolFixture.PoolId); while (computeNodes.Any(computeNode => computeNode.State != ComputeNodeState.Idle)) { Thread.Sleep(TimeSpan.FromSeconds(10)); computeNodes = batchCli.PoolOperations.ListComputeNodes(poolFixture.PoolId).ToList(); Assert.False(DateTime.UtcNow > timeoutAfterThisTimeUtc, "Timed out waiting for compute nodes in pool to reach idle state"); } } } SynchronizationContextHelper.RunTest(test, LongTestTimeout); } } }
using Lucene.Net.Codecs.Lucene40; using Lucene.Net.Support; using System; using System.Diagnostics; using System.Reflection; namespace Lucene.Net.Codecs.Compressing { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using ArrayUtil = Lucene.Net.Util.ArrayUtil; using BufferedChecksumIndexInput = Lucene.Net.Store.BufferedChecksumIndexInput; using ByteArrayDataInput = Lucene.Net.Store.ByteArrayDataInput; using BytesRef = Lucene.Net.Util.BytesRef; using ChecksumIndexInput = Lucene.Net.Store.ChecksumIndexInput; using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using DataInput = Lucene.Net.Store.DataInput; using DataOutput = Lucene.Net.Store.DataOutput; using Directory = Lucene.Net.Store.Directory; using FieldInfo = Lucene.Net.Index.FieldInfo; using FieldInfos = Lucene.Net.Index.FieldInfos; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexInput = Lucene.Net.Store.IndexInput; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; using SegmentInfo = Lucene.Net.Index.SegmentInfo; using StoredFieldVisitor = Lucene.Net.Index.StoredFieldVisitor; /// <summary> /// <see cref="StoredFieldsReader"/> impl for <see cref="CompressingStoredFieldsFormat"/>. /// <para/> /// @lucene.experimental /// </summary> public sealed class CompressingStoredFieldsReader : StoredFieldsReader { // Do not reuse the decompression buffer when there is more than 32kb to decompress private static readonly int BUFFER_REUSE_THRESHOLD = 1 << 15; private readonly int version; private readonly FieldInfos fieldInfos; private readonly CompressingStoredFieldsIndexReader indexReader; private readonly long maxPointer; private readonly IndexInput fieldsStream; private readonly int chunkSize; private readonly int packedIntsVersion; private readonly CompressionMode compressionMode; private readonly Decompressor decompressor; private readonly BytesRef bytes; private readonly int numDocs; private bool closed; // used by clone private CompressingStoredFieldsReader(CompressingStoredFieldsReader reader) { this.version = reader.version; this.fieldInfos = reader.fieldInfos; this.fieldsStream = (IndexInput)reader.fieldsStream.Clone(); this.indexReader = (CompressingStoredFieldsIndexReader)reader.indexReader.Clone(); this.maxPointer = reader.maxPointer; this.chunkSize = reader.chunkSize; this.packedIntsVersion = reader.packedIntsVersion; this.compressionMode = reader.compressionMode; this.decompressor = (Decompressor)reader.decompressor.Clone(); this.numDocs = reader.numDocs; this.bytes = new BytesRef(reader.bytes.Bytes.Length); this.closed = false; } /// <summary> /// Sole constructor. </summary> public CompressingStoredFieldsReader(Directory d, SegmentInfo si, string segmentSuffix, FieldInfos fn, IOContext context, string formatName, CompressionMode compressionMode) { this.compressionMode = compressionMode; string segment = si.Name; bool success = false; fieldInfos = fn; numDocs = si.DocCount; ChecksumIndexInput indexStream = null; try { string indexStreamFN = IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_INDEX_EXTENSION); string fieldsStreamFN = IndexFileNames.SegmentFileName(segment, segmentSuffix, Lucene40StoredFieldsWriter.FIELDS_EXTENSION); // Load the index into memory indexStream = d.OpenChecksumInput(indexStreamFN, context); string codecNameIdx = formatName + CompressingStoredFieldsWriter.CODEC_SFX_IDX; version = CodecUtil.CheckHeader(indexStream, codecNameIdx, CompressingStoredFieldsWriter.VERSION_START, CompressingStoredFieldsWriter.VERSION_CURRENT); Debug.Assert(CodecUtil.HeaderLength(codecNameIdx) == indexStream.GetFilePointer()); indexReader = new CompressingStoredFieldsIndexReader(indexStream, si); long maxPointer = -1; if (version >= CompressingStoredFieldsWriter.VERSION_CHECKSUM) { maxPointer = indexStream.ReadVInt64(); CodecUtil.CheckFooter(indexStream); } else { #pragma warning disable 612, 618 CodecUtil.CheckEOF(indexStream); #pragma warning restore 612, 618 } indexStream.Dispose(); indexStream = null; // Open the data file and read metadata fieldsStream = d.OpenInput(fieldsStreamFN, context); if (version >= CompressingStoredFieldsWriter.VERSION_CHECKSUM) { if (maxPointer + CodecUtil.FooterLength() != fieldsStream.Length) { throw new CorruptIndexException("Invalid fieldsStream maxPointer (file truncated?): maxPointer=" + maxPointer + ", length=" + fieldsStream.Length); } } else { maxPointer = fieldsStream.Length; } this.maxPointer = maxPointer; string codecNameDat = formatName + CompressingStoredFieldsWriter.CODEC_SFX_DAT; int fieldsVersion = CodecUtil.CheckHeader(fieldsStream, codecNameDat, CompressingStoredFieldsWriter.VERSION_START, CompressingStoredFieldsWriter.VERSION_CURRENT); if (version != fieldsVersion) { throw new CorruptIndexException("Version mismatch between stored fields index and data: " + version + " != " + fieldsVersion); } Debug.Assert(CodecUtil.HeaderLength(codecNameDat) == fieldsStream.GetFilePointer()); if (version >= CompressingStoredFieldsWriter.VERSION_BIG_CHUNKS) { chunkSize = fieldsStream.ReadVInt32(); } else { chunkSize = -1; } packedIntsVersion = fieldsStream.ReadVInt32(); decompressor = compressionMode.NewDecompressor(); this.bytes = new BytesRef(); success = true; } finally { if (!success) { IOUtils.DisposeWhileHandlingException(this, indexStream); } } } /// <exception cref="ObjectDisposedException"> If this FieldsReader is disposed. </exception> private void EnsureOpen() { if (closed) { throw new ObjectDisposedException(this.GetType().FullName, "this FieldsReader is closed"); } } /// <summary> /// Dispose the underlying <see cref="IndexInput"/>s. /// </summary> protected override void Dispose(bool disposing) { if (!closed) { IOUtils.Dispose(fieldsStream); closed = true; } } private static void ReadField(DataInput @in, StoredFieldVisitor visitor, FieldInfo info, int bits) { switch (bits & CompressingStoredFieldsWriter.TYPE_MASK) { case CompressingStoredFieldsWriter.BYTE_ARR: int length = @in.ReadVInt32(); var data = new byte[length]; @in.ReadBytes(data, 0, length); visitor.BinaryField(info, data); break; case CompressingStoredFieldsWriter.STRING: length = @in.ReadVInt32(); data = new byte[length]; @in.ReadBytes(data, 0, length); #pragma warning disable 612, 618 visitor.StringField(info, IOUtils.CHARSET_UTF_8.GetString(data)); #pragma warning restore 612, 618 break; case CompressingStoredFieldsWriter.NUMERIC_INT32: visitor.Int32Field(info, @in.ReadInt32()); break; case CompressingStoredFieldsWriter.NUMERIC_SINGLE: visitor.SingleField(info, J2N.BitConversion.Int32BitsToSingle(@in.ReadInt32())); break; case CompressingStoredFieldsWriter.NUMERIC_INT64: visitor.Int64Field(info, @in.ReadInt64()); break; case CompressingStoredFieldsWriter.NUMERIC_DOUBLE: visitor.DoubleField(info, J2N.BitConversion.Int64BitsToDouble(@in.ReadInt64())); break; default: throw new InvalidOperationException("Unknown type flag: " + bits.ToString("x")); } } private static void SkipField(DataInput @in, int bits) { switch (bits & CompressingStoredFieldsWriter.TYPE_MASK) { case CompressingStoredFieldsWriter.BYTE_ARR: case CompressingStoredFieldsWriter.STRING: int length = @in.ReadVInt32(); @in.SkipBytes(length); break; case CompressingStoredFieldsWriter.NUMERIC_INT32: case CompressingStoredFieldsWriter.NUMERIC_SINGLE: @in.ReadInt32(); break; case CompressingStoredFieldsWriter.NUMERIC_INT64: case CompressingStoredFieldsWriter.NUMERIC_DOUBLE: @in.ReadInt64(); break; default: throw new InvalidOperationException("Unknown type flag: " + bits.ToString("x")); } } public override void VisitDocument(int docID, StoredFieldVisitor visitor) { fieldsStream.Seek(indexReader.GetStartPointer(docID)); int docBase = fieldsStream.ReadVInt32(); int chunkDocs = fieldsStream.ReadVInt32(); if (docID < docBase || docID >= docBase + chunkDocs || docBase + chunkDocs > numDocs) { throw new CorruptIndexException("Corrupted: docID=" + docID + ", docBase=" + docBase + ", chunkDocs=" + chunkDocs + ", numDocs=" + numDocs + " (resource=" + fieldsStream + ")"); } int numStoredFields, offset, length, totalLength; if (chunkDocs == 1) { numStoredFields = fieldsStream.ReadVInt32(); offset = 0; length = fieldsStream.ReadVInt32(); totalLength = length; } else { int bitsPerStoredFields = fieldsStream.ReadVInt32(); if (bitsPerStoredFields == 0) { numStoredFields = fieldsStream.ReadVInt32(); } else if (bitsPerStoredFields > 31) { throw new CorruptIndexException("bitsPerStoredFields=" + bitsPerStoredFields + " (resource=" + fieldsStream + ")"); } else { long filePointer = fieldsStream.GetFilePointer(); PackedInt32s.Reader reader = PackedInt32s.GetDirectReaderNoHeader(fieldsStream, PackedInt32s.Format.PACKED, packedIntsVersion, chunkDocs, bitsPerStoredFields); numStoredFields = (int)(reader.Get(docID - docBase)); fieldsStream.Seek(filePointer + PackedInt32s.Format.PACKED.ByteCount(packedIntsVersion, chunkDocs, bitsPerStoredFields)); } int bitsPerLength = fieldsStream.ReadVInt32(); if (bitsPerLength == 0) { length = fieldsStream.ReadVInt32(); offset = (docID - docBase) * length; totalLength = chunkDocs * length; } else if (bitsPerStoredFields > 31) { throw new CorruptIndexException("bitsPerLength=" + bitsPerLength + " (resource=" + fieldsStream + ")"); } else { PackedInt32s.IReaderIterator it = PackedInt32s.GetReaderIteratorNoHeader(fieldsStream, PackedInt32s.Format.PACKED, packedIntsVersion, chunkDocs, bitsPerLength, 1); int off = 0; for (int i = 0; i < docID - docBase; ++i) { off += (int)it.Next(); } offset = off; length = (int)it.Next(); off += length; for (int i = docID - docBase + 1; i < chunkDocs; ++i) { off += (int)it.Next(); } totalLength = off; } } if ((length == 0) != (numStoredFields == 0)) { throw new CorruptIndexException("length=" + length + ", numStoredFields=" + numStoredFields + " (resource=" + fieldsStream + ")"); } if (numStoredFields == 0) { // nothing to do return; } DataInput documentInput; if (version >= CompressingStoredFieldsWriter.VERSION_BIG_CHUNKS && totalLength >= 2 * chunkSize) { Debug.Assert(chunkSize > 0); Debug.Assert(offset < chunkSize); decompressor.Decompress(fieldsStream, chunkSize, offset, Math.Min(length, chunkSize - offset), bytes); documentInput = new DataInputAnonymousInnerClassHelper(this, offset, length); } else { BytesRef bytes = totalLength <= BUFFER_REUSE_THRESHOLD ? this.bytes : new BytesRef(); decompressor.Decompress(fieldsStream, totalLength, offset, length, bytes); Debug.Assert(bytes.Length == length); documentInput = new ByteArrayDataInput(bytes.Bytes, bytes.Offset, bytes.Length); } for (int fieldIDX = 0; fieldIDX < numStoredFields; fieldIDX++) { long infoAndBits = documentInput.ReadVInt64(); int fieldNumber = (int)((long)((ulong)infoAndBits >> CompressingStoredFieldsWriter.TYPE_BITS)); FieldInfo fieldInfo = fieldInfos.FieldInfo(fieldNumber); int bits = (int)(infoAndBits & CompressingStoredFieldsWriter.TYPE_MASK); Debug.Assert(bits <= CompressingStoredFieldsWriter.NUMERIC_DOUBLE, "bits=" + bits.ToString("x")); switch (visitor.NeedsField(fieldInfo)) { case StoredFieldVisitor.Status.YES: ReadField(documentInput, visitor, fieldInfo, bits); break; case StoredFieldVisitor.Status.NO: SkipField(documentInput, bits); break; case StoredFieldVisitor.Status.STOP: return; } } } private class DataInputAnonymousInnerClassHelper : DataInput { private readonly CompressingStoredFieldsReader outerInstance; private int offset; private int length; public DataInputAnonymousInnerClassHelper(CompressingStoredFieldsReader outerInstance, int offset, int length) { this.outerInstance = outerInstance; this.offset = offset; this.length = length; decompressed = outerInstance.bytes.Length; } internal int decompressed; internal virtual void FillBuffer() { Debug.Assert(decompressed <= length); if (decompressed == length) { throw new Exception(); } int toDecompress = Math.Min(length - decompressed, outerInstance.chunkSize); outerInstance.decompressor.Decompress(outerInstance.fieldsStream, toDecompress, 0, toDecompress, outerInstance.bytes); decompressed += toDecompress; } public override byte ReadByte() { if (outerInstance.bytes.Length == 0) { FillBuffer(); } --outerInstance.bytes.Length; return (byte)outerInstance.bytes.Bytes[outerInstance.bytes.Offset++]; } public override void ReadBytes(byte[] b, int offset, int len) { while (len > outerInstance.bytes.Length) { Array.Copy(outerInstance.bytes.Bytes, outerInstance.bytes.Offset, b, offset, outerInstance.bytes.Length); len -= outerInstance.bytes.Length; offset += outerInstance.bytes.Length; FillBuffer(); } Array.Copy(outerInstance.bytes.Bytes, outerInstance.bytes.Offset, b, offset, len); outerInstance.bytes.Offset += len; outerInstance.bytes.Length -= len; } } public override object Clone() { EnsureOpen(); return new CompressingStoredFieldsReader(this); } internal int Version => version; internal CompressionMode CompressionMode => compressionMode; internal int ChunkSize => chunkSize; internal ChunkIterator GetChunkIterator(int startDocID) { EnsureOpen(); return new ChunkIterator(this, startDocID); } internal sealed class ChunkIterator { private readonly CompressingStoredFieldsReader outerInstance; internal readonly ChecksumIndexInput fieldsStream; internal readonly BytesRef spare; internal readonly BytesRef bytes; internal int docBase; internal int chunkDocs; internal int[] numStoredFields; internal int[] lengths; internal ChunkIterator(CompressingStoredFieldsReader outerInstance, int startDocId) { this.outerInstance = outerInstance; this.docBase = -1; bytes = new BytesRef(); spare = new BytesRef(); numStoredFields = new int[1]; lengths = new int[1]; IndexInput @in = outerInstance.fieldsStream; @in.Seek(0); fieldsStream = new BufferedChecksumIndexInput(@in); fieldsStream.Seek(outerInstance.indexReader.GetStartPointer(startDocId)); } /// <summary> /// Return the decompressed size of the chunk /// </summary> internal int ChunkSize() { int sum = 0; for (int i = 0; i < chunkDocs; ++i) { sum += lengths[i]; } return sum; } /// <summary> /// Go to the chunk containing the provided <paramref name="doc"/> ID. /// </summary> internal void Next(int doc) { Debug.Assert(doc >= this.docBase + this.chunkDocs, doc + " " + this.docBase + " " + this.chunkDocs); fieldsStream.Seek(outerInstance.indexReader.GetStartPointer(doc)); int docBase = fieldsStream.ReadVInt32(); int chunkDocs = fieldsStream.ReadVInt32(); if (docBase < this.docBase + this.chunkDocs || docBase + chunkDocs > outerInstance.numDocs) { throw new CorruptIndexException("Corrupted: current docBase=" + this.docBase + ", current numDocs=" + this.chunkDocs + ", new docBase=" + docBase + ", new numDocs=" + chunkDocs + " (resource=" + fieldsStream + ")"); } this.docBase = docBase; this.chunkDocs = chunkDocs; if (chunkDocs > numStoredFields.Length) { int newLength = ArrayUtil.Oversize(chunkDocs, 4); numStoredFields = new int[newLength]; lengths = new int[newLength]; } if (chunkDocs == 1) { numStoredFields[0] = fieldsStream.ReadVInt32(); lengths[0] = fieldsStream.ReadVInt32(); } else { int bitsPerStoredFields = fieldsStream.ReadVInt32(); if (bitsPerStoredFields == 0) { Arrays.Fill(numStoredFields, 0, chunkDocs, fieldsStream.ReadVInt32()); } else if (bitsPerStoredFields > 31) { throw new CorruptIndexException("bitsPerStoredFields=" + bitsPerStoredFields + " (resource=" + fieldsStream + ")"); } else { PackedInt32s.IReaderIterator it = PackedInt32s.GetReaderIteratorNoHeader(fieldsStream, PackedInt32s.Format.PACKED, outerInstance.packedIntsVersion, chunkDocs, bitsPerStoredFields, 1); for (int i = 0; i < chunkDocs; ++i) { numStoredFields[i] = (int)it.Next(); } } int bitsPerLength = fieldsStream.ReadVInt32(); if (bitsPerLength == 0) { Arrays.Fill(lengths, 0, chunkDocs, fieldsStream.ReadVInt32()); } else if (bitsPerLength > 31) { throw new CorruptIndexException("bitsPerLength=" + bitsPerLength); } else { PackedInt32s.IReaderIterator it = PackedInt32s.GetReaderIteratorNoHeader(fieldsStream, PackedInt32s.Format.PACKED, outerInstance.packedIntsVersion, chunkDocs, bitsPerLength, 1); for (int i = 0; i < chunkDocs; ++i) { lengths[i] = (int)it.Next(); } } } } /// <summary> /// Decompress the chunk. /// </summary> internal void Decompress() { // decompress data int chunkSize = ChunkSize(); if (outerInstance.version >= CompressingStoredFieldsWriter.VERSION_BIG_CHUNKS && chunkSize >= 2 * outerInstance.chunkSize) { bytes.Offset = bytes.Length = 0; for (int decompressed = 0; decompressed < chunkSize; ) { int toDecompress = Math.Min(chunkSize - decompressed, outerInstance.chunkSize); outerInstance.decompressor.Decompress(fieldsStream, toDecompress, 0, toDecompress, spare); bytes.Bytes = ArrayUtil.Grow(bytes.Bytes, bytes.Length + spare.Length); Array.Copy(spare.Bytes, spare.Offset, bytes.Bytes, bytes.Length, spare.Length); bytes.Length += spare.Length; decompressed += toDecompress; } } else { outerInstance.decompressor.Decompress(fieldsStream, chunkSize, 0, chunkSize, bytes); } if (bytes.Length != chunkSize) { throw new CorruptIndexException("Corrupted: expected chunk size = " + ChunkSize() + ", got " + bytes.Length + " (resource=" + fieldsStream + ")"); } } /// <summary> /// Copy compressed data. /// </summary> internal void CopyCompressedData(DataOutput @out) { Debug.Assert(outerInstance.Version == CompressingStoredFieldsWriter.VERSION_CURRENT); long chunkEnd = docBase + chunkDocs == outerInstance.numDocs ? outerInstance.maxPointer : outerInstance.indexReader.GetStartPointer(docBase + chunkDocs); @out.CopyBytes(fieldsStream, chunkEnd - fieldsStream.GetFilePointer()); } /// <summary> /// Check integrity of the data. The iterator is not usable after this method has been called. /// </summary> internal void CheckIntegrity() { if (outerInstance.version >= CompressingStoredFieldsWriter.VERSION_CHECKSUM) { fieldsStream.Seek(fieldsStream.Length - CodecUtil.FooterLength()); CodecUtil.CheckFooter(fieldsStream); } } } public override long RamBytesUsed() { return indexReader.RamBytesUsed(); } public override void CheckIntegrity() { if (version >= CompressingStoredFieldsWriter.VERSION_CHECKSUM) { CodecUtil.ChecksumEntireFile(fieldsStream); } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using DotVVM.Framework.Parser; using DotVVM.Framework.Parser.Dothtml.Tokenizer; namespace DotVVM.Framework.Tests.Parser.Dothtml { [TestClass] public class DothtmlTokenizerHtmlSpecialElementsTests : DothtmlTokenizerTestsBase { [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid() { var input = @"test <!DOCTYPE html> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid_Begin() { var input = @"<!DOCTYPE html> test"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid_End() { var input = @"test <!DOCTYPE html>"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid_Empty() { var input = @"<!DOCTYPE>"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual("", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Invalid_Incomplete_WithValue() { var input = @"<!DOCTYPE html"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Invalid_Incomplete_NoValue() { var input = @"<!DOCTYPE"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_XmlProcessingInstructionParsing_Valid() { var input = @"test <?xml version=""1.0"" encoding=""utf-8"" ?> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<?", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenXmlProcessingInstruction, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"xml version=""1.0"" encoding=""utf-8"" ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.XmlProcessingInstructionBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("?>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseXmlProcessingInstruction, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CDataParsing_Valid() { var input = @"test <![CDATA[ this is a text < > "" ' ]]> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<![CDATA[", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenCData, tokenizer.Tokens[i++].Type); Assert.AreEqual(@" this is a text < > "" ' ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CDataBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("]]>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseCData, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CommentParsing_Valid() { var input = @"test <!-- this is a text < > "" ' --> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(new StringReader(input)); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!--", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(@" this is a text < > "" ' ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("-->", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } } }
#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.Specialized; using System.Globalization; using System.Security.Cryptography; using System.Text; using System.Web; using MbUnit.Framework; using Moq; using Subtext.Framework; using Subtext.Framework.Configuration; using Subtext.Framework.Security; using Subtext.Framework.Web.HttpModules; namespace UnitTests.Subtext.Framework.SecurityHandling { /// <summary> /// Summary description for SecurityTests. /// </summary> [TestFixture] public class SecurityTests { /// <summary> /// Makes sure that the UpdatePassword method hashes the password. /// </summary> [Test] [RollBack] public void UpdatePasswordHashesPassword() { string hostName = UnitTestHelper.GenerateUniqueString(); UnitTestHelper.SetHttpContextWithBlogRequest(hostName, "MyBlog"); Config.Settings.UseHashedPasswords = true; Config.CreateBlog("", "username", "thePassword", hostName, "MyBlog"); BlogRequest.Current.Blog = Config.GetBlog(hostName, "MyBlog"); string password = SecurityHelper.HashPassword("newPass"); SecurityHelper.UpdatePassword("newPass"); Blog info = Config.GetBlog(hostName, "MyBlog"); Assert.AreEqual(password, info.Password); } [Test] public void IsValidPassword_WithBlogHavingHashedPasswordMatchingGivenClearTextPassword_ReturnsTrue() { // arrange const string password = "myPassword"; const string hashedPassword = "Bc5M0y93wXmtXNxwW6IJVA=="; Assert.AreEqual(hashedPassword, SecurityHelper.HashPassword(password)); var blog = new Blog {UserName = "username", Password = hashedPassword, IsPasswordHashed = true}; // act bool isValidPassword = SecurityHelper.IsValidPassword(blog, password); // assert Assert.IsTrue(isValidPassword); } [Test] public void IsValidPassword_WithPasswordHashingEnabledAndGivenTheHashedPassword_ReturnsFalse() { // arrange const string password = "myPassword"; const string hashedPassword = "Bc5M0y93wXmtXNxwW6IJVA=="; Assert.AreEqual(hashedPassword, SecurityHelper.HashPassword(password)); var blog = new Blog {UserName = "username", Password = hashedPassword, IsPasswordHashed = true}; // act bool isValidPassword = SecurityHelper.IsValidPassword(blog, hashedPassword); // assert Assert.IsFalse(isValidPassword); } [Test] public void IsValidPassword_WithClearTextPasswordMatchingBlogPassword_ReturnsTrue() { // arrange const string password = "myPassword"; var blog = new Blog {UserName = "username", Password = password, IsPasswordHashed = false}; // act bool isValidPassword = SecurityHelper.IsValidPassword(blog, password); // assert Assert.IsTrue(isValidPassword); } /// <summary> /// Ensures HashesPassword is case sensitive. /// </summary> [Test] public void HashPasswordIsCaseSensitive() { const string lowercase = "password"; const string uppercase = "Password"; UnitTestHelper.AssertAreNotEqual(SecurityHelper.HashPassword(lowercase), SecurityHelper.HashPassword(uppercase), "A lower cased and upper cased password should not be equivalent."); UnitTestHelper.AssertAreNotEqual(SecurityHelper.HashPassword(lowercase), SecurityHelper.HashPassword(uppercase.ToUpper(CultureInfo.InvariantCulture)), "A lower cased and a completely upper cased password should not be equivalent."); } /// <summary> /// Want to make sure that we still understand the old /// bitconverter created password. /// </summary> [Test] public void IsValidPassword_GivenValidPasswordHashedUsingOldBitConverterStyleHash_ReturnsTrue() { // arrange const string password = "myPassword"; Byte[] clearBytes = new UnicodeEncoding().GetBytes(password); Byte[] hashedBytes = new MD5CryptoServiceProvider().ComputeHash(clearBytes); string bitConvertedPassword = BitConverter.ToString(hashedBytes); var blog = new Blog {UserName = "username", Password = bitConvertedPassword, IsPasswordHashed = true}; // act bool isValid = SecurityHelper.IsValidPassword(blog, password); // assert Assert.IsTrue(isValid); } [Test] public void SelectAuthenticationCookie_WithCookieNameMatchingBlog_ReturnsThatCookie() { // arrange var cookies = new HttpCookieCollection { new HttpCookie("This Is Not The Cookie You're Looking For"), new HttpCookie(".ASPXAUTH.42") {Path = "/Subtext.Web"}, new HttpCookie("Awful Cookie") }; var request = new Mock<HttpRequestBase>(); request.Setup(r => r.QueryString).Returns(new NameValueCollection()); request.Setup(r => r.Cookies).Returns(cookies); // act HttpCookie cookie = request.Object.SelectAuthenticationCookie(new Blog {Id = 42}); // assert Assert.IsNotNull(cookie); Assert.AreEqual(".ASPXAUTH.42", cookie.Name); Assert.AreEqual("/Subtext.Web", cookie.Path); } [Test] public void GetFullCookieName_WithBlog_ReturnsCookieNameWithBlogId() { // arrange var request = new Mock<HttpRequestBase>(); request.Setup(r => r.QueryString).Returns(new NameValueCollection()); var blog = new Blog {Id = 42}; // act string cookieName = request.Object.GetFullCookieName(blog); // assert Assert.AreEqual(".ASPXAUTH.42", cookieName); } [Test] public void GetFullCookieName_WithNullBlog_ReturnsCookieNameWithHostAdminMarker() { // arrange var request = new Mock<HttpRequestBase>(); request.Setup(r => r.QueryString).Returns(new NameValueCollection()); // act string cookieName = request.Object.GetFullCookieName(null); // assert Assert.AreEqual(".ASPXAUTH.HA.null", cookieName); } [Test] public void GetFullCookieName_WithAggregateBlog_ReturnsCookieNameWithHostAdminMarker() { // arrange var request = new Mock<HttpRequestBase>(); request.Setup(r => r.QueryString).Returns(new NameValueCollection()); // act string cookieName = request.Object.GetFullCookieName(new Blog(true /*isAggregateBlog*/)); // assert Assert.AreEqual(".ASPXAUTH.HA.null", cookieName); } [Test] public void GetFullCookieName_WithReturnUrlPointingToHostAdmin_ReturnsCookieNameWithBlogIdAndHostAdminInitials() { // arrange var request = new Mock<HttpRequestBase>(); var queryStringParams = new NameValueCollection {{"ReturnUrl", "/HostAdmin"}}; request.Setup(r => r.QueryString).Returns(queryStringParams); var blog = new Blog {Id = 42}; // act string cookieName = request.Object.GetFullCookieName(blog, false); // assert Assert.AreEqual(".ASPXAUTH.HA.42", cookieName); } [Test] public void GetFullCookieName_WithForceHostAdminTrueAndNullBlog_ReturnsCookieNameWithHostAdminInitials() { // arrange var request = new Mock<HttpRequestBase>(); request.Setup(r => r.QueryString).Returns(new NameValueCollection()); // act string cookieName = request.Object.GetFullCookieName(null, true); // assert Assert.AreEqual(".ASPXAUTH.HA.null", cookieName); } [Test] public void CanAuthenticateAdmin() { // arrange var cookies = new HttpCookieCollection(); var request = new Mock<HttpRequestBase>(); request.Setup(r => r.Path).Returns("/whatever"); request.Setup(r => r.Cookies).Returns(cookies); request.Setup(r => r.QueryString).Returns(new NameValueCollection()); var httpContext = new Mock<HttpContextBase>(); httpContext.Setup(c => c.Request).Returns(request.Object); httpContext.Setup(c => c.Response.Cookies).Returns(cookies); var blog = new Blog {UserName = "the-username", Password = "thePassword", IsPasswordHashed = false}; // act bool authenticated = httpContext.Object.Authenticate(blog, "the-username", "thePassword", true); // assert Assert.IsTrue(authenticated); HttpCookie cookie = request.Object.SelectAuthenticationCookie(blog); Assert.IsNotNull(cookie); } [Test] public void CanGenerateSymmetricEncryptionKey() { byte[] key = SecurityHelper.GenerateSymmetricKey(); Assert.IsTrue(key.Length > 0, "Expected a non-zero key."); } [Test] public void CanSymmetricallyEncryptAndDecryptText() { const string clearText = "Hello world!"; byte[] key = SecurityHelper.GenerateSymmetricKey(); byte[] iv = SecurityHelper.GenerateInitializationVector(); string encrypted = SecurityHelper.EncryptString(clearText, Encoding.UTF8, key, iv); Assert.IsTrue(encrypted != clearText, "Encrypted text should not equal the clear text."); string unencrypted = SecurityHelper.DecryptString(encrypted, Encoding.UTF8, key, iv); Assert.AreEqual(clearText, unencrypted, "Round trip encrypt/decrypt failed to produce original string."); } /// <summary> /// Sets the up test fixture. This is called once for /// this test fixture before all the tests run. /// </summary> [TestFixtureSetUp] public void SetUpTestFixture() { //Confirm app settings UnitTestHelper.AssertAppSettings(); } } }
using System; using System.Collections; using System.Data; using System.IO; using System.Reflection; using System.Configuration; using IBatisNet.DataMapper.Configuration; using log4net; using NUnit.Framework; using IBatisNet.Common; // DataSource definition using IBatisNet.Common.Utilities; // ScriptRunner definition using IBatisNet.DataMapper; // SqlMap API using IBatisNet.DataMapper.Test.Domain; [assembly : log4net.Config.XmlConfigurator(Watch=true)] namespace IBatisNet.DataMapper.Test.NUnit.SqlMapTests { public delegate string KeyConvert(string key); /// <summary> /// Summary description for BaseTest. /// </summary> public abstract class BaseTest { /// <summary> /// The sqlMap /// </summary> protected static SqlMapper sqlMap = null; private static readonly ILog _logger = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType ); protected static string ScriptDirectory = null; protected static KeyConvert ConvertKey = null; /// <summary> /// Constructor /// </summary> static BaseTest() { ScriptDirectory = Path.Combine(Path.Combine(Path.Combine(Path.Combine(Resources.ApplicationBase, ".."), ".."), "Scripts"), ConfigurationSettings.AppSettings["database"]) + Path.DirectorySeparatorChar; } /// <summary> /// Initialize an sqlMap /// </summary> [TestFixtureSetUp] protected void InitSqlMap() { //DateTime start = DateTime.Now; DomSqlMapBuilder builder = new DomSqlMapBuilder(); string fileName = "sqlmap" + "_" + ConfigurationSettings.AppSettings["database"] + "_" + ConfigurationSettings.AppSettings["providerType"] + ".config"; sqlMap = builder.Configure(fileName); if ( sqlMap.DataSource.Provider.Name.IndexOf("PostgreSql")>=0) { BaseTest.ConvertKey = new KeyConvert(Lower); } else if ( sqlMap.DataSource.Provider.Name.IndexOf("oracle")>=0) { BaseTest.ConvertKey = new KeyConvert(Upper); } else { BaseTest.ConvertKey = new KeyConvert(Normal); } // string loadTime = DateTime.Now.Subtract(start).ToString(); // Console.WriteLine("Loading configuration time :"+loadTime); } /// <summary> /// Dispose the SqlMap /// </summary> [TestFixtureTearDown] protected void DisposeSqlMap() { sqlMap = null; } protected static string Normal(string key) { return key; } protected static string Upper(string key) { return key.ToUpper(); } protected static string Lower(string key) { return key.ToLower(); } /// <summary> /// Configure the SqlMap /// </summary> /// <remarks> /// Must verify ConfigureHandler signature. /// </remarks> /// <param name="obj"> /// The reconfigured sqlMap. /// </param> protected static void Configure(object obj) { sqlMap = null;//(SqlMapper) obj; } /// <summary> /// Run a sql batch for the datasource. /// </summary> /// <param name="datasource">The datasource.</param> /// <param name="script">The sql batch</param> protected static void InitScript(DataSource datasource, string script) { InitScript(datasource, script, true); } /// <summary> /// Run a sql batch for the datasource. /// </summary> /// <param name="datasource">The datasource.</param> /// <param name="script">The sql batch</param> /// <param name="doParse">parse out the statements in the sql script file.</param> protected static void InitScript(DataSource datasource, string script, bool doParse) { ScriptRunner runner = new ScriptRunner(); runner.RunScript(datasource, script, doParse); } /// <summary> /// Create a new account with id = 6 /// </summary> /// <returns>An account</returns> protected Account NewAccount6() { Account account = new Account(); account.Id = 6; account.FirstName = "Calamity"; account.LastName = "Jane"; account.EmailAddress = "no_email@provided.com"; return account; } /// <summary> /// Verify that the input account is equal to the account(id=1). /// </summary> /// <param name="account">An account object</param> protected void AssertAccount1(Account account) { Assert.AreEqual(1, account.Id, "account.Id"); Assert.AreEqual("Joe", account.FirstName, "account.FirstName"); Assert.AreEqual("Dalton", account.LastName, "account.LastName"); Assert.AreEqual("Joe.Dalton@somewhere.com", account.EmailAddress, "account.EmailAddress"); } /// <summary> /// Verify that the input account is equal to the account(id=1). /// </summary> /// <param name="account">An account as hashtable</param> protected void AssertAccount1AsHashtable(Hashtable account) { Assert.AreEqual(1, (int) account["Id"], "account.Id"); Assert.AreEqual("Joe", (string) account["FirstName"], "account.FirstName"); Assert.AreEqual("Dalton", (string) account["LastName"], "account.LastName"); Assert.AreEqual("Joe.Dalton@somewhere.com", (string) account["EmailAddress"], "account.EmailAddress"); } /// <summary> /// Verify that the input account is equal to the account(id=1). /// </summary> /// <param name="account">An account as hashtable</param> protected void AssertAccount1AsHashtableForResultClass(Hashtable account) { Assert.AreEqual(1, (int) account[BaseTest.ConvertKey("Id")], "account.Id"); Assert.AreEqual("Joe", (string) account[BaseTest.ConvertKey("FirstName")], "account.FirstName"); Assert.AreEqual("Dalton", (string) account[BaseTest.ConvertKey("LastName")], "account.LastName"); Assert.AreEqual("Joe.Dalton@somewhere.com", (string) account[BaseTest.ConvertKey("EmailAddress")], "account.EmailAddress"); } /// <summary> /// Verify that the input account is equal to the account(id=6). /// </summary> /// <param name="account">An account object</param> protected void AssertAccount6(Account account) { Assert.AreEqual(6, account.Id, "account.Id"); Assert.AreEqual("Calamity", account.FirstName, "account.FirstName"); Assert.AreEqual("Jane", account.LastName, "account.LastName"); Assert.IsNull(account.EmailAddress, "account.EmailAddress"); } /// <summary> /// Verify that the input order is equal to the order(id=1). /// </summary> /// <param name="order">An order object.</param> protected void AssertOrder1(Order order) { DateTime date = new DateTime(2003, 2, 15, 8, 15, 00); Assert.AreEqual(1, order.Id, "order.Id"); Assert.AreEqual(date.ToString(), order.Date.ToString(), "order.Date"); Assert.AreEqual("VISA", order.CardType, "order.CardType"); Assert.AreEqual("999999999999", order.CardNumber, "order.CardNumber"); Assert.AreEqual("05/03", order.CardExpiry, "order.CardExpiry"); Assert.AreEqual("11 This Street", order.Street, "order.Street"); Assert.AreEqual("Victoria", order.City, "order.City"); Assert.AreEqual("BC", order.Province, "order.Id"); Assert.AreEqual("C4B 4F4", order.PostalCode, "order.PostalCode"); } /// <summary> /// Verify that the input order is equal to the order(id=1). /// </summary> /// <param name="order">An order as hashtable.</param> protected void AssertOrder1AsHashtable(Hashtable order) { DateTime date = new DateTime(2003, 2, 15, 8, 15, 00); Assert.AreEqual(1, (int) order["Id"], "order.Id"); Assert.AreEqual(date.ToString(), ((DateTime) order["Date"]).ToString(), "order.Date"); Assert.AreEqual("VISA", (string) order["CardType"], "order.CardType"); Assert.AreEqual("999999999999", (string) order["CardNumber"], "order.CardNumber"); Assert.AreEqual("05/03", (string) order["CardExpiry"], "order.CardExpiry"); Assert.AreEqual("11 This Street", (string) order["Street"], "order.Street"); Assert.AreEqual("Victoria", (string) order["City"], "order.City"); Assert.AreEqual("BC", (string) order["Province"], "order.Id"); Assert.AreEqual("C4B 4F4", (string) order["PostalCode"], "order.PostalCode"); } } }
// **************************************************************** // 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.Collections; using NUnit.Framework.Constraints; namespace NUnit.Framework.Tests { /// <summary> /// This test fixture attempts to exercise all the syntactic /// variations of Assert without getting into failures, errors /// or corner cases. Thus, some of the tests may be duplicated /// in other fixtures. /// /// Each test performs the same operations using the classic /// syntax (if available) and the new syntax in both the /// helper-based and inherited forms. /// /// This Fixture will eventually be duplicated in other /// supported languages. /// </summary> [TestFixture] public class AssertSyntaxTests : AssertionHelper { #region Simple Constraint Tests [Test] public void IsNull() { object nada = null; // Classic syntax Assert.IsNull(nada); // Constraint Syntax Assert.That(nada, Is.Null); // Inherited syntax Expect(nada, Null); } [Test] public void IsNotNull() { // Classic syntax Assert.IsNotNull(42); // Constraint Syntax Assert.That(42, Is.Not.Null); // Inherited syntax Expect( 42, Not.Null ); } [Test] public void IsTrue() { // Classic syntax Assert.IsTrue(2+2==4); // Constraint Syntax Assert.That(2+2==4, Is.True); Assert.That(2+2==4); // Inherited syntax Expect(2+2==4, True); Expect(2+2==4); } [Test] public void IsFalse() { // Classic syntax Assert.IsFalse(2+2==5); // Constraint Syntax Assert.That(2+2== 5, Is.False); // Inherited syntax Expect(2+2==5, False); } [Test] public void IsNaN() { double d = double.NaN; float f = float.NaN; // Classic syntax Assert.IsNaN(d); Assert.IsNaN(f); // Constraint Syntax Assert.That(d, Is.NaN); Assert.That(f, Is.NaN); // Inherited syntax Expect(d, NaN); Expect(f, NaN); } [Test] public void EmptyStringTests() { // Classic syntax Assert.IsEmpty(""); Assert.IsNotEmpty("Hello!"); // Constraint Syntax Assert.That("", Is.Empty); Assert.That("Hello!", Is.Not.Empty); // Inherited syntax Expect("", Empty); Expect("Hello!", Not.Empty); } [Test] public void EmptyCollectionTests() { // Classic syntax Assert.IsEmpty(new bool[0]); Assert.IsNotEmpty(new int[] { 1, 2, 3 }); // Constraint Syntax Assert.That(new bool[0], Is.Empty); Assert.That(new int[] { 1, 2, 3 }, Is.Not.Empty); // Inherited syntax Expect(new bool[0], Empty); Expect(new int[] { 1, 2, 3 }, Not.Empty); } #endregion #region TypeConstraint Tests [Test] public void ExactTypeTests() { // Classic syntax workarounds Assert.AreEqual(typeof(string), "Hello".GetType()); Assert.AreEqual("System.String", "Hello".GetType().FullName); Assert.AreNotEqual(typeof(int), "Hello".GetType()); Assert.AreNotEqual("System.Int32", "Hello".GetType().FullName); // Constraint Syntax Assert.That("Hello", Is.TypeOf(typeof(string))); Assert.That("Hello", Is.Not.TypeOf(typeof(int))); // Inherited syntax Expect( "Hello", TypeOf(typeof(string))); Expect( "Hello", Not.TypeOf(typeof(int))); } [Test] public void InstanceOfTests() { // Classic syntax Assert.IsInstanceOf(typeof(string), "Hello"); Assert.IsNotInstanceOf(typeof(string), 5); // Constraint Syntax Assert.That("Hello", Is.InstanceOf(typeof(string))); Assert.That(5, Is.Not.InstanceOf(typeof(string))); // Inherited syntax Expect("Hello", InstanceOf(typeof(string))); Expect(5, Not.InstanceOf(typeof(string))); } [Test] public void AssignableFromTypeTests() { // Classic syntax Assert.IsAssignableFrom(typeof(string), "Hello"); Assert.IsNotAssignableFrom(typeof(string), 5); // Constraint Syntax Assert.That( "Hello", Is.AssignableFrom(typeof(string))); Assert.That( 5, Is.Not.AssignableFrom(typeof(string))); // Inherited syntax Expect( "Hello", AssignableFrom(typeof(string))); Expect( 5, Not.AssignableFrom(typeof(string))); } #endregion #region StringConstraint Tests [Test] public void SubstringTests() { string phrase = "Hello World!"; string[] array = new string[] { "abc", "bad", "dba" }; // Classic Syntax StringAssert.Contains("World", phrase); // Constraint Syntax Assert.That(phrase, Is.StringContaining("World")); // Only available using new syntax Assert.That(phrase, Is.Not.StringContaining("goodbye")); Assert.That(phrase, Is.StringContaining("WORLD").IgnoreCase); Assert.That(phrase, Is.Not.StringContaining("BYE").IgnoreCase); Assert.That(array, Is.All.StringContaining( "b" ) ); // Inherited syntax Expect(phrase, Contains("World")); // Only available using new syntax Expect(phrase, Not.Contains("goodbye")); Expect(phrase, Contains("WORLD").IgnoreCase); Expect(phrase, Not.Contains("BYE").IgnoreCase); Expect(array, All.Contains("b")); } [Test] public void StartsWithTests() { string phrase = "Hello World!"; string[] greetings = new string[] { "Hello!", "Hi!", "Hola!" }; // Classic syntax StringAssert.StartsWith("Hello", phrase); // Constraint Syntax Assert.That(phrase, Is.StringStarting("Hello")); // Only available using new syntax Assert.That(phrase, Is.Not.StringStarting("Hi!")); Assert.That(phrase, Is.StringStarting("HeLLo").IgnoreCase); Assert.That(phrase, Is.Not.StringStarting("HI").IgnoreCase); Assert.That(greetings, Is.All.StringStarting("h").IgnoreCase); // Inherited syntax Expect(phrase, StartsWith("Hello")); // Only available using new syntax Expect(phrase, Not.StartsWith("Hi!")); Expect(phrase, StartsWith("HeLLo").IgnoreCase); Expect(phrase, Not.StartsWith("HI").IgnoreCase); Expect(greetings, All.StartsWith("h").IgnoreCase); } [Test] public void EndsWithTests() { string phrase = "Hello World!"; string[] greetings = new string[] { "Hello!", "Hi!", "Hola!" }; // Classic Syntax StringAssert.EndsWith("!", phrase); // Constraint Syntax Assert.That(phrase, Is.StringEnding("!")); // Only available using new syntax Assert.That(phrase, Is.Not.StringEnding("?")); Assert.That(phrase, Is.StringEnding("WORLD!").IgnoreCase); Assert.That(greetings, Is.All.StringEnding("!")); // Inherited syntax Expect(phrase, EndsWith("!")); // Only available using new syntax Expect(phrase, Not.EndsWith("?")); Expect(phrase, EndsWith("WORLD!").IgnoreCase); Expect(greetings, All.EndsWith("!") ); } [Test] public void EqualIgnoringCaseTests() { string phrase = "Hello World!"; // Classic syntax StringAssert.AreEqualIgnoringCase("hello world!",phrase); // Constraint Syntax Assert.That(phrase, Is.EqualTo("hello world!").IgnoreCase); //Only available using new syntax Assert.That(phrase, Is.Not.EqualTo("goodbye world!").IgnoreCase); Assert.That(new string[] { "Hello", "World" }, Is.EqualTo(new object[] { "HELLO", "WORLD" }).IgnoreCase); Assert.That(new string[] {"HELLO", "Hello", "hello" }, Is.All.EqualTo( "hello" ).IgnoreCase); // Inherited syntax Expect(phrase, EqualTo("hello world!").IgnoreCase); //Only available using new syntax Expect(phrase, Not.EqualTo("goodbye world!").IgnoreCase); Expect(new string[] { "Hello", "World" }, EqualTo(new object[] { "HELLO", "WORLD" }).IgnoreCase); Expect(new string[] {"HELLO", "Hello", "hello" }, All.EqualTo( "hello" ).IgnoreCase); } [Test] public void RegularExpressionTests() { string phrase = "Now is the time for all good men to come to the aid of their country."; string[] quotes = new string[] { "Never say never", "It's never too late", "Nevermore!" }; // Classic syntax StringAssert.IsMatch( "all good men", phrase ); StringAssert.IsMatch( "Now.*come", phrase ); // Constraint Syntax Assert.That( phrase, Is.StringMatching( "all good men" ) ); Assert.That( phrase, Is.StringMatching( "Now.*come" ) ); // Only available using new syntax Assert.That(phrase, Is.Not.StringMatching("all.*men.*good")); Assert.That(phrase, Is.StringMatching("ALL").IgnoreCase); Assert.That(quotes, Is.All.StringMatching("never").IgnoreCase); // Inherited syntax Expect( phrase, Matches( "all good men" ) ); Expect( phrase, Matches( "Now.*come" ) ); // Only available using new syntax Expect(phrase, Not.Matches("all.*men.*good")); Expect(phrase, Matches("ALL").IgnoreCase); Expect(quotes, All.Matches("never").IgnoreCase); } #endregion #region Equality Tests [Test] public void EqualityTests() { int[] i3 = new int[] { 1, 2, 3 }; double[] d3 = new double[] { 1.0, 2.0, 3.0 }; int[] iunequal = new int[] { 1, 3, 2 }; // Classic Syntax Assert.AreEqual(4, 2 + 2); Assert.AreEqual(i3, d3); Assert.AreNotEqual(5, 2 + 2); Assert.AreNotEqual(i3, iunequal); // Constraint Syntax Assert.That(2 + 2, Is.EqualTo(4)); Assert.That(2 + 2 == 4); Assert.That(i3, Is.EqualTo(d3)); Assert.That(2 + 2, Is.Not.EqualTo(5)); Assert.That(i3, Is.Not.EqualTo(iunequal)); // Inherited syntax Expect(2 + 2, EqualTo(4)); Expect(2 + 2 == 4); Expect(i3, EqualTo(d3)); Expect(2 + 2, Not.EqualTo(5)); Expect(i3, Not.EqualTo(iunequal)); } [Test] public void EqualityTestsWithTolerance() { // CLassic syntax Assert.AreEqual(5.0d, 4.99d, 0.05d); Assert.AreEqual(5.0f, 4.99f, 0.05f); // Constraint Syntax Assert.That(4.99d, Is.EqualTo(5.0d).Within(0.05d)); Assert.That(4.0d, Is.Not.EqualTo(5.0d).Within(0.5d)); Assert.That(4.99f, Is.EqualTo(5.0f).Within(0.05f)); Assert.That(4.99m, Is.EqualTo(5.0m).Within(0.05m)); Assert.That(3999999999u, Is.EqualTo(4000000000u).Within(5u)); Assert.That(499, Is.EqualTo(500).Within(5)); Assert.That(4999999999L, Is.EqualTo(5000000000L).Within(5L)); Assert.That(5999999999ul, Is.EqualTo(6000000000ul).Within(5ul)); // Inherited syntax Expect(4.99d, EqualTo(5.0d).Within(0.05d)); Expect(4.0d, Not.EqualTo(5.0d).Within(0.5d)); Expect(4.99f, EqualTo(5.0f).Within(0.05f)); Expect(4.99m, EqualTo(5.0m).Within(0.05m)); Expect(499u, EqualTo(500u).Within(5u)); Expect(499, EqualTo(500).Within(5)); Expect(4999999999L, EqualTo(5000000000L).Within(5L)); Expect(5999999999ul, EqualTo(6000000000ul).Within(5ul)); } [Test] public void EqualityTestsWithTolerance_MixedFloatAndDouble() { // Bug Fix 1743844 Assert.That(2.20492d, Is.EqualTo(2.2d).Within(0.01f), "Double actual, Double expected, Single tolerance"); Assert.That(2.20492d, Is.EqualTo(2.2f).Within(0.01d), "Double actual, Single expected, Double tolerance" ); Assert.That(2.20492d, Is.EqualTo(2.2f).Within(0.01f), "Double actual, Single expected, Single tolerance" ); Assert.That(2.20492f, Is.EqualTo(2.2f).Within(0.01d), "Single actual, Single expected, Double tolerance"); Assert.That(2.20492f, Is.EqualTo(2.2d).Within(0.01d), "Single actual, Double expected, Double tolerance"); Assert.That(2.20492f, Is.EqualTo(2.2d).Within(0.01f), "Single actual, Double expected, Single tolerance"); } [Test] public void EqualityTestsWithTolerance_MixingTypesGenerally() { // Extending tolerance to all numeric types Assert.That(202d, Is.EqualTo(200d).Within(2), "Double actual, Double expected, int tolerance"); Assert.That( 4.87m, Is.EqualTo(5).Within(.25), "Decimal actual, int expected, Double tolerance" ); Assert.That( 4.87m, Is.EqualTo(5ul).Within(1), "Decimal actual, ulong expected, int tolerance" ); Assert.That( 487, Is.EqualTo(500).Within(25), "int actual, int expected, int tolerance" ); Assert.That( 487u, Is.EqualTo(500).Within(25), "uint actual, int expected, int tolerance" ); Assert.That( 487L, Is.EqualTo(500).Within(25), "long actual, int expected, int tolerance" ); Assert.That( 487ul, Is.EqualTo(500).Within(25), "ulong actual, int expected, int tolerance" ); } #endregion #region Comparison Tests [Test] public void ComparisonTests() { // Classic Syntax Assert.Greater(7, 3); Assert.GreaterOrEqual(7, 3); Assert.GreaterOrEqual(7, 7); // Constraint Syntax Assert.That(7, Is.GreaterThan(3)); Assert.That(7, Is.GreaterThanOrEqualTo(3)); Assert.That(7, Is.AtLeast(3)); Assert.That(7, Is.GreaterThanOrEqualTo(7)); Assert.That(7, Is.AtLeast(7)); // Inherited syntax Expect(7, GreaterThan(3)); Expect(7, GreaterThanOrEqualTo(3)); Expect(7, AtLeast(3)); Expect(7, GreaterThanOrEqualTo(7)); Expect(7, AtLeast(7)); // Classic syntax Assert.Less(3, 7); Assert.LessOrEqual(3, 7); Assert.LessOrEqual(3, 3); // Constraint Syntax Assert.That(3, Is.LessThan(7)); Assert.That(3, Is.LessThanOrEqualTo(7)); Assert.That(3, Is.AtMost(7)); Assert.That(3, Is.LessThanOrEqualTo(3)); Assert.That(3, Is.AtMost(3)); // Inherited syntax Expect(3, LessThan(7)); Expect(3, LessThanOrEqualTo(7)); Expect(3, AtMost(7)); Expect(3, LessThanOrEqualTo(3)); Expect(3, AtMost(3)); } #endregion #region Collection Tests [Test] public void AllItemsTests() { object[] ints = new object[] { 1, 2, 3, 4 }; object[] doubles = new object[] { 0.99, 2.1, 3.0, 4.05 }; object[] strings = new object[] { "abc", "bad", "cab", "bad", "dad" }; // Classic syntax CollectionAssert.AllItemsAreNotNull(ints); CollectionAssert.AllItemsAreInstancesOfType(ints, typeof(int)); CollectionAssert.AllItemsAreInstancesOfType(strings, typeof(string)); CollectionAssert.AllItemsAreUnique(ints); // Constraint Syntax Assert.That(ints, Is.All.Not.Null); Assert.That(ints, Has.None.Null); Assert.That(ints, Is.All.InstanceOf(typeof(int))); Assert.That(ints, Has.All.InstanceOf(typeof(int))); Assert.That(strings, Is.All.InstanceOf(typeof(string))); Assert.That(strings, Has.All.InstanceOf(typeof(string))); Assert.That(ints, Is.Unique); // Only available using new syntax Assert.That(strings, Is.Not.Unique); Assert.That(ints, Is.All.GreaterThan(0)); Assert.That(ints, Has.All.GreaterThan(0)); Assert.That(ints, Has.None.LessThanOrEqualTo(0)); Assert.That(strings, Is.All.StringContaining( "a" ) ); Assert.That(strings, Has.All.Contains( "a" ) ); Assert.That(strings, Has.Some.StartsWith( "ba" ) ); Assert.That( strings, Has.Some.Property( "Length" ).EqualTo( 3 ) ); Assert.That( strings, Has.Some.StartsWith( "BA" ).IgnoreCase ); Assert.That( doubles, Has.Some.EqualTo( 1.0 ).Within( .05 ) ); // Inherited syntax Expect(ints, All.Not.Null); Expect(ints, None.Null); Expect(ints, All.InstanceOf(typeof(int))); Expect(strings, All.InstanceOf(typeof(string))); Expect(ints, Unique); // Only available using new syntax Expect(strings, Not.Unique); Expect(ints, All.GreaterThan(0)); Expect(ints, None.LessThanOrEqualTo(0)); Expect(strings, All.Contains( "a" ) ); Expect(strings, Some.StartsWith( "ba" ) ); Expect(strings, Some.StartsWith( "BA" ).IgnoreCase ); Expect(doubles, Some.EqualTo( 1.0 ).Within( .05 ) ); } [Test] public void SomeItemTests() { object[] mixed = new object[] { 1, 2, "3", null, "four", 100 }; object[] strings = new object[] { "abc", "bad", "cab", "bad", "dad" }; // Not available using the classic syntax // Constraint Syntax Assert.That(mixed, Has.Some.Null); Assert.That(mixed, Has.Some.InstanceOf(typeof(int))); Assert.That(mixed, Has.Some.InstanceOf(typeof(string))); Assert.That(strings, Has.Some.StartsWith( "ba" ) ); Assert.That(strings, Has.Some.Not.StartsWith( "ba" ) ); // Inherited syntax Expect(mixed, Some.Null); Expect(mixed, Some.InstanceOf(typeof(int))); Expect(mixed, Some.InstanceOf(typeof(string))); Expect(strings, Some.StartsWith( "ba" ) ); Expect(strings, Some.Not.StartsWith( "ba" ) ); } [Test] public void NoItemTests() { object[] ints = new object[] { 1, 2, 3, 4, 5 }; object[] strings = new object[] { "abc", "bad", "cab", "bad", "dad" }; // Not available using the classic syntax // Constraint Syntax Assert.That(ints, Has.None.Null); Assert.That(ints, Has.None.InstanceOf(typeof(string))); Assert.That(ints, Has.None.GreaterThan(99)); Assert.That(strings, Has.None.StartsWith( "qu" ) ); // Inherited syntax Expect(ints, None.Null); Expect(ints, None.InstanceOf(typeof(string))); Expect(ints, None.GreaterThan(99)); Expect(strings, None.StartsWith( "qu" ) ); } [Test] public void CollectionContainsTests() { int[] iarray = new int[] { 1, 2, 3 }; string[] sarray = new string[] { "a", "b", "c" }; // Classic syntax Assert.Contains(3, iarray); Assert.Contains("b", sarray); CollectionAssert.Contains(iarray, 3); CollectionAssert.Contains(sarray, "b"); CollectionAssert.DoesNotContain(sarray, "x"); // Showing that Contains uses NUnit equality CollectionAssert.Contains( iarray, 1.0d ); // Constraint Syntax Assert.That(iarray, Has.Member(3)); Assert.That(sarray, Has.Member("b")); Assert.That(sarray, Has.No.Member("x")); // Showing that Contains uses NUnit equality Assert.That(iarray, Has.Member( 1.0d )); // Only available using the new syntax // Note that EqualTo and SameAs do NOT give // identical results to Contains because // Contains uses Object.Equals() Assert.That(iarray, Has.Some.EqualTo(3)); Assert.That(iarray, Has.Member(3)); Assert.That(sarray, Has.Some.EqualTo("b")); Assert.That(sarray, Has.None.EqualTo("x")); Assert.That(iarray, Has.None.SameAs( 1.0d )); Assert.That(iarray, Has.All.LessThan(10)); Assert.That(sarray, Has.All.Length.EqualTo(1)); Assert.That(sarray, Has.None.Property("Length").GreaterThan(3)); // Inherited syntax Expect(iarray, Contains(3)); Expect(sarray, Contains("b")); Expect(sarray, Not.Contains("x")); // Only available using new syntax // Note that EqualTo and SameAs do NOT give // identical results to Contains because // Contains uses Object.Equals() Expect(iarray, Some.EqualTo(3)); Expect(sarray, Some.EqualTo("b")); Expect(sarray, None.EqualTo("x")); Expect(iarray, All.LessThan(10)); Expect(sarray, All.Length.EqualTo(1)); Expect(sarray, None.Property("Length").GreaterThan(3)); } [Test] public void CollectionEquivalenceTests() { int[] ints1to5 = new int[] { 1, 2, 3, 4, 5 }; int[] twothrees = new int[] { 1, 2, 3, 3, 4, 5 }; int[] twofours = new int[] { 1, 2, 3, 4, 4, 5 }; // Classic syntax CollectionAssert.AreEquivalent(new int[] { 2, 1, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(new int[] { 2, 2, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(new int[] { 2, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(new int[] { 2, 2, 1, 1, 4, 3, 5 }, ints1to5); CollectionAssert.AreNotEquivalent(twothrees, twofours); // Constraint Syntax Assert.That(new int[] { 2, 1, 4, 3, 5 }, Is.EquivalentTo(ints1to5)); Assert.That(new int[] { 2, 2, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); Assert.That(new int[] { 2, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); Assert.That(new int[] { 2, 2, 1, 1, 4, 3, 5 }, Is.Not.EquivalentTo(ints1to5)); // Inherited syntax Expect(new int[] { 2, 1, 4, 3, 5 }, EquivalentTo(ints1to5)); Expect(new int[] { 2, 2, 4, 3, 5 }, Not.EquivalentTo(ints1to5)); Expect(new int[] { 2, 4, 3, 5 }, Not.EquivalentTo(ints1to5)); Expect(new int[] { 2, 2, 1, 1, 4, 3, 5 }, Not.EquivalentTo(ints1to5)); } [Test] public void SubsetTests() { int[] ints1to5 = new int[] { 1, 2, 3, 4, 5 }; // Classic syntax CollectionAssert.IsSubsetOf(new int[] { 1, 3, 5 }, ints1to5); CollectionAssert.IsSubsetOf(new int[] { 1, 2, 3, 4, 5 }, ints1to5); CollectionAssert.IsNotSubsetOf(new int[] { 2, 4, 6 }, ints1to5); CollectionAssert.IsNotSubsetOf(new int[] { 1, 2, 2, 2, 5 }, ints1to5); // Constraint Syntax Assert.That(new int[] { 1, 3, 5 }, Is.SubsetOf(ints1to5)); Assert.That(new int[] { 1, 2, 3, 4, 5 }, Is.SubsetOf(ints1to5)); Assert.That(new int[] { 2, 4, 6 }, Is.Not.SubsetOf(ints1to5)); // Inherited syntax Expect(new int[] { 1, 3, 5 }, SubsetOf(ints1to5)); Expect(new int[] { 1, 2, 3, 4, 5 }, SubsetOf(ints1to5)); Expect(new int[] { 2, 4, 6 }, Not.SubsetOf(ints1to5)); } #endregion #region Property Tests [Test] public void PropertyTests() { string[] array = { "abc", "bca", "xyz", "qrs" }; string[] array2 = { "a", "ab", "abc" }; ArrayList list = new ArrayList( array ); // Not available using the classic syntax // Constraint Syntax Assert.That( list, Has.Property( "Count" ) ); Assert.That( list, Has.No.Property( "Length" ) ); Assert.That( "Hello", Has.Length.EqualTo( 5 ) ); Assert.That( "Hello", Has.Length.LessThan( 10 ) ); Assert.That( "Hello", Has.Property("Length").EqualTo(5) ); Assert.That( "Hello", Has.Property("Length").GreaterThan(3) ); Assert.That( array, Has.Property( "Length" ).EqualTo( 4 ) ); Assert.That( array, Has.Length.EqualTo( 4 ) ); Assert.That( array, Has.Property( "Length" ).LessThan( 10 ) ); Assert.That( array, Has.All.Property("Length").EqualTo(3) ); Assert.That( array, Has.All.Length.EqualTo( 3 ) ); Assert.That( array, Is.All.Length.EqualTo( 3 ) ); Assert.That( array, Has.All.Property("Length").EqualTo(3) ); Assert.That( array, Is.All.Property("Length").EqualTo(3) ); Assert.That( array2, Has.Some.Property("Length").EqualTo(2) ); Assert.That( array2, Has.Some.Length.EqualTo(2) ); Assert.That( array2, Has.Some.Property("Length").GreaterThan(2) ); Assert.That( array2, Is.Not.Property("Length").EqualTo(4) ); Assert.That( array2, Is.Not.Length.EqualTo( 4 ) ); Assert.That( array2, Has.No.Property("Length").GreaterThan(3) ); Assert.That( List.Map( array2 ).Property("Length"), Is.EqualTo( new int[] { 1, 2, 3 } ) ); Assert.That( List.Map( array2 ).Property("Length"), Is.EquivalentTo( new int[] { 3, 2, 1 } ) ); Assert.That( List.Map( array2 ).Property("Length"), Is.SubsetOf( new int[] { 1, 2, 3, 4, 5 } ) ); Assert.That( List.Map( array2 ).Property("Length"), Is.Unique ); Assert.That( list, Has.Count.EqualTo( 4 ) ); // Inherited syntax Expect( list, Property( "Count" ) ); Expect( list, Not.Property( "Nada" ) ); Expect( "Hello", Length.EqualTo( 5 ) ); Expect( "Hello", Property("Length").EqualTo(5) ); Expect( "Hello", Property("Length").GreaterThan(0) ); Expect( array, Property("Length").EqualTo(4) ); Expect( array, Length.EqualTo(4) ); Expect( array, Property("Length").LessThan(10)); Expect( array, All.Length.EqualTo( 3 ) ); Expect( array, All.Property("Length").EqualTo(3)); Expect( array2, Some.Property("Length").EqualTo(2) ); Expect( array2, Some.Length.EqualTo( 2 ) ); Expect( array2, Some.Property("Length").GreaterThan(2)); Expect( array2, None.Property("Length").EqualTo(4) ); Expect( array2, None.Length.EqualTo( 4 ) ); Expect( array2, None.Property("Length").GreaterThan(3)); Expect( Map( array2 ).Property("Length"), EqualTo( new int[] { 1, 2, 3 } ) ); Expect( Map( array2 ).Property("Length"), EquivalentTo( new int[] { 3, 2, 1 } ) ); Expect( Map( array2 ).Property("Length"), SubsetOf( new int[] { 1, 2, 3, 4, 5 } ) ); Expect( Map( array2 ).Property("Length"), Unique ); Expect( list, Count.EqualTo( 4 ) ); } #endregion #region Not Tests [Test] public void NotTests() { // Not available using the classic syntax // Constraint Syntax Assert.That(42, Is.Not.Null); Assert.That(42, Is.Not.True); Assert.That(42, Is.Not.False); Assert.That(2.5, Is.Not.NaN); Assert.That(2 + 2, Is.Not.EqualTo(3)); Assert.That(2 + 2, Is.Not.Not.EqualTo(4)); Assert.That(2 + 2, Is.Not.Not.Not.EqualTo(5)); // Inherited syntax Expect(42, Not.Null); Expect(42, Not.True); Expect(42, Not.False); Expect(2.5, Not.NaN); Expect(2 + 2, Not.EqualTo(3)); Expect(2 + 2, Not.Not.EqualTo(4)); Expect(2 + 2, Not.Not.Not.EqualTo(5)); } #endregion #region Operator Tests [Test] public void NotOperator() { // The ! operator is only available in the new syntax Assert.That(42, !Is.Null); // Inherited syntax Expect( 42, !Null ); } [Test] public void AndOperator() { // The & operator is only available in the new syntax Assert.That(7, Is.GreaterThan(5) & Is.LessThan(10)); // Inherited syntax Expect( 7, GreaterThan(5) & LessThan(10)); } [Test] public void OrOperator() { // The | operator is only available in the new syntax Assert.That(3, Is.LessThan(5) | Is.GreaterThan(10)); Expect( 3, LessThan(5) | GreaterThan(10)); } [Test] public void ComplexTests() { Assert.That(7, Is.Not.Null & Is.Not.LessThan(5) & Is.Not.GreaterThan(10)); Expect(7, Not.Null & Not.LessThan(5) & Not.GreaterThan(10)); Assert.That(7, !Is.Null & !Is.LessThan(5) & !Is.GreaterThan(10)); Expect(7, !Null & !LessThan(5) & !GreaterThan(10)); // TODO: Remove #if when mono compiler can handle null #if MONO Constraint x = null; Assert.That(7, !x & !Is.LessThan(5) & !Is.GreaterThan(10)); Expect(7, !x & !LessThan(5) & !GreaterThan(10)); #else Assert.That(7, !(Constraint)null & !Is.LessThan(5) & !Is.GreaterThan(10)); Expect(7, !(Constraint)null & !LessThan(5) & !GreaterThan(10)); #endif } #endregion #region Invalid Code Tests // This method contains assertions that should not compile // You can check by uncommenting it. //public void WillNotCompile() //{ // Assert.That(42, Is.Not); // Assert.That(42, Is.All); // Assert.That(42, Is.Null.Not); // Assert.That(42, Is.Not.Null.GreaterThan(10)); // Assert.That(42, Is.GreaterThan(10).LessThan(99)); // object[] c = new object[0]; // Assert.That(c, Is.Null.All); // Assert.That(c, Is.Not.All); // Assert.That(c, Is.All.Not); //} #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddSubtractDouble() { var test = new SimpleBinaryOpTest__AddSubtractDouble(); 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__AddSubtractDouble { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[ElementCount]; private static Double[] _data2 = new Double[ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double> _dataTable; static SimpleBinaryOpTest__AddSubtractDouble() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__AddSubtractDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.AddSubtract( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx.AddSubtract( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx.AddSubtract( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx).GetMethod(nameof(Avx.AddSubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx).GetMethod(nameof(Avx.AddSubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx).GetMethod(nameof(Avx.AddSubtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx.AddSubtract( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.AddSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.AddSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.AddSubtract(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AddSubtractDouble(); var result = Avx.AddSubtract(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx.AddSubtract(_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(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, 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 = "") { Double[] inArray1 = new Double[ElementCount]; Double[] inArray2 = new Double[ElementCount]; Double[] outArray = new Double[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(left[0] - right[0]) != BitConverter.DoubleToInt64Bits(result[0])) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if (((i % 2 != 0) && (BitConverter.DoubleToInt64Bits(left[i] + right[i]) != BitConverter.DoubleToInt64Bits(result[i]))) || ((i % 2 == 0) && (BitConverter.DoubleToInt64Bits(left[i] - right[i]) != BitConverter.DoubleToInt64Bits(result[i])))) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.AddSubtract)}<Double>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Collections; using sys = System; namespace Comzept.Library.Drawing.ImageInfo { ///<summary>This Class retrives Image Properties using Image.GetPropertyItem() method /// and gives access to some of them trough its public properties. Or to all of them /// trough its public property PropertyItems. ///</summary> public class Info { ///<summary>Wenn using this constructor the Image property must be set before accessing properties.</summary> public Info() { } ///<summary>Creates Info Class to read properties of an Image given from a file.</summary> /// <param name="imageFileName">A string specifiing image file name on a file system.</param> public Info(string imageFileName) { _image = sys.Drawing.Image.FromFile(imageFileName); } ///<summary>Creates Info Class to read properties of a given Image object.</summary> /// <param name="anImage">An Image object to analise.</param> public Info(sys.Drawing.Image anImage) { _image = anImage; } sys.Drawing.Image _image; ///<summary>Sets or returns the current Image object.</summary> public sys.Drawing.Image Image { set{_image = value;} get{return _image;} } ///<summary> /// Type is PropertyTagTypeShort or PropertyTagTypeLong ///Information specific to compressed data. When a compressed file is recorded, the valid width of the meaningful image must be recorded in this tag, whether or not there is padding data or a restart marker. This tag should not exist in an uncompressed file. /// </summary> public uint PixXDim { get { object tmpValue = PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifPixXDim)); if (tmpValue.GetType().ToString().Equals("System.UInt16")) return (uint)(ushort)tmpValue; return (uint)tmpValue; } } ///<summary> /// Type is PropertyTagTypeShort or PropertyTagTypeLong /// Information specific to compressed data. When a compressed file is recorded, the valid height of the meaningful image must be recorded in this tag whether or not there is padding data or a restart marker. This tag should not exist in an uncompressed file. Because data padding is unnecessary in the vertical direction, the number of lines recorded in this valid image height tag will be the same as that recorded in the SOF. /// </summary> public uint PixYDim { get { object tmpValue = PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifPixYDim)); if (tmpValue.GetType().ToString().Equals("System.UInt16")) return (uint)(ushort)tmpValue; return (uint)tmpValue; } } ///<summary> ///Number of pixels per unit in the image width (x) direction. The unit is specified by PropertyTagResolutionUnit ///</summary> public Fraction XResolution { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.XResolution)); } } ///<summary> ///Number of pixels per unit in the image height (y) direction. The unit is specified by PropertyTagResolutionUnit. ///</summary> public Fraction YResolution { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.YResolution )); } } ///<summary> ///Unit of measure for the horizontal resolution and the vertical resolution. ///2 - inch 3 - centimeter ///</summary> public ResolutionUnit ResolutionUnit { get { return (ResolutionUnit) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ResolutionUnit )); } } ///<summary> ///Brightness value. The unit is the APEX value. Ordinarily it is given in the range of -99.99 to 99.99. ///</summary> public Fraction Brightness { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifBrightness)); } } ///<summary> /// The manufacturer of the equipment used to record the image. ///</summary> public string EquipMake { get { return (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.EquipMake)); } } ///<summary> /// The model name or model number of the equipment used to record the image. /// </summary> public string EquipModel { get { return (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.EquipModel)); } } ///<summary> ///Copyright information. ///</summary> public string Copyright { get { return (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.Copyright)); } } ///<summary> ///Date and time the image was created. ///</summary> public string DateTime { get { return (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.DateTime)); } } //The format is YYYY:MM:DD HH:MM:SS with time shown in 24-hour format and the date and time separated by one blank character (0x2000). The character string length is 20 bytes including the NULL terminator. When the field is empty, it is treated as unknown. private static DateTime ExifDTToDateTime(string exifDT) { exifDT = exifDT.Replace(' ', ':'); string[] ymdhms = exifDT.Split(':'); int years = int.Parse(ymdhms[0]); int months = int.Parse(ymdhms[1]); int days = int.Parse(ymdhms[2]); int hours = int.Parse(ymdhms[3]); int minutes = int.Parse(ymdhms[4]); int seconds = int.Parse(ymdhms[5]); return new DateTime(years, months, days, hours, minutes, seconds); } ///<summary> ///Date and time when the original image data was generated. For a DSC, the date and time when the picture was taken. ///</summary> public DateTime DTOrig { get { string tmpStr = (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifDTOrig)); return ExifDTToDateTime(tmpStr); } } ///<summary> ///Date and time when the image was stored as digital data. If, for example, an image was captured by DSC and at the same time the file was recorded, then DateTimeOriginal and DateTimeDigitized will have the same contents. ///</summary> public DateTime DTDigitized { get { string tmpStr = (string) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifDTDigitized)); return ExifDTToDateTime(tmpStr); } } ///<summary> ///ISO speed and ISO latitude of the camera or input device as specified in ISO 12232. ///</summary> public ushort ISOSpeed { get { return (ushort) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifISOSpeed)); } } ///<summary> ///Image orientation viewed in terms of rows and columns. ///</summary> public Orientation Orientation { get { return (Orientation) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.Orientation)); } } ///<summary> ///Actual focal length, in millimeters, of the lens. Conversion is not made to the focal length of a 35 millimeter film camera. ///</summary> public Fraction FocalLength { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifFocalLength)); } } ///<summary> ///F number. ///</summary> public Fraction FNumber { get { return (Fraction) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifFNumber)); } } ///<summary> ///Class of the program used by the camera to set exposure when the picture is taken. ///</summary> public ExposureProg ExposureProg { get { return (ExposureProg) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifExposureProg)); } } ///<summary> ///Metering mode. ///</summary> public MeteringMode MeteringMode { get { return (MeteringMode) PropertyTag.getValue(_image.GetPropertyItem((int)PropertyTagId.ExifMeteringMode)); } } private Hashtable _propertyItems; ///<summary> /// Returns a Hashtable of all available Properties of a gieven Image. Keys of this Hashtable are /// Display names of the Property Tags and values are transformed (typed) data. ///</summary> /// <example> /// <code> /// if (openFileDialog.ShowDialog()==DialogResult.OK) /// { /// Info inf=new Info(Image.FromFile(openFileDialog.FileName)); /// listView.Items.Clear(); /// foreach (string propertyname in inf.PropertyItems.Keys) /// { /// ListViewItem item1 = new ListViewItem(propertyname,0); /// item1.SubItems.Add((inf.PropertyItems[propertyname]).ToString()); /// listView.Items.Add(item1); /// } /// } /// </code> ///</example> public Hashtable PropertyItems { get { if (_propertyItems==null) { _propertyItems= new Hashtable(); foreach(int id in _image.PropertyIdList) _propertyItems[((PropertyTagId)id).ToString()]=PropertyTag.getValue(_image.GetPropertyItem(id)); } return _propertyItems; } } } }
using EIDSS.Reports.Parameterized.Human.GG.DataSet; using EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthDataSetTableAdapters; using EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewDataSetTableAdapters; using EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewHeaderDataSetTableAdapters; namespace EIDSS.Reports.Parameterized.Human.GG.Report { partial class InfectiousDiseasesMonthNew { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InfectiousDiseasesMonthNew)); DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary(); this.tableCustomHeader = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell84 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell(); this.EnTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell75 = new DevExpress.XtraReports.UI.XRTableCell(); this.InfectiousDiseaseHeaderDataSet = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewHeaderDataSet(); this.xrTableCell85 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell86 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell87 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell80 = new DevExpress.XtraReports.UI.XRTableCell(); this.EnTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell81 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell82 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell83 = new DevExpress.XtraReports.UI.XRTableCell(); this.GgTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell88 = new DevExpress.XtraReports.UI.XRTableCell(); this.GgTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell89 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell92 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell93 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell95 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell97 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell90 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell91 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow23 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell70 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow21 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellNameOfrespondent = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellActualAddress = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellTelephone = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow(); this.cellReportedPeriod = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell(); this.InfectiousDiseaseDataSet = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewDataSet(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.tableCustomFooter = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow18 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell(); this.DayFooterCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell(); this.MonthFooterCell = new DevExpress.XtraReports.UI.XRTableCell(); this.YearFooterCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell(); this.ChiefFooterCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow25 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell79 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell(); this.tableBody = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow19 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell71 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell66 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell67 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow20 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell72 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell54 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell55 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell56 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell57 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell59 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell61 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell68 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell62 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell69 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell63 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell64 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell65 = new DevExpress.XtraReports.UI.XRTableCell(); this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.CustomDetail = new DevExpress.XtraReports.UI.DetailBand(); this.PageBreakAtLine36 = new DevExpress.XtraReports.UI.XRPageBreak(); this.formattingRule2 = new DevExpress.XtraReports.UI.FormattingRule(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.formattingRule3 = new DevExpress.XtraReports.UI.FormattingRule(); this.xrTableRow22 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell73 = new DevExpress.XtraReports.UI.XRTableCell(); this.strDiseaseName = new DevExpress.XtraReports.UI.XRTableCell(); this.cellICD10 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellAge_0_1 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellAge_1_4 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellAge_5_14 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellAge_15_19 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellAge_20_29 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellAge_30_59 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellAge_60_more = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell94 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellTotal = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell96 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellLabTested = new DevExpress.XtraReports.UI.XRTableCell(); this.cellLabConfirmed = new DevExpress.XtraReports.UI.XRTableCell(); this.cellTotalConfirmed = new DevExpress.XtraReports.UI.XRTableCell(); this.CustomReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.SpRepHumMonthlyInfectiousDiseaseNewTableAdapter = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewDataSetTableAdapters.spRepHumMonthlyInfectiousDiseaseNewTableAdapter(); this.SpRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter = new EIDSS.Reports.Parameterized.Human.GG.DataSet.InfectiousDiseaseMonthNewHeaderDataSetTableAdapters.spRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter(); this.cellLocation = new DevExpress.XtraReports.UI.XRLabel(); this.formattingRule1 = new DevExpress.XtraReports.UI.FormattingRule(); ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableCustomHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.InfectiousDiseaseHeaderDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.InfectiousDiseaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableCustomFooter)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBody)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // tableInterval // resources.ApplyResources(this.tableInterval, "tableInterval"); this.tableInterval.StylePriority.UseBorders = false; this.tableInterval.StylePriority.UseFont = false; this.tableInterval.StylePriority.UsePadding = false; // // cellLanguage // resources.ApplyResources(this.cellLanguage, "cellLanguage"); this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.Multiline = true; this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // resources.ApplyResources(this.Detail, "Detail"); this.Detail.Expanded = false; this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; this.Detail.StylePriority.UseTextAlignment = false; // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; this.PageHeader.StylePriority.UseTextAlignment = false; // // PageFooter // resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.tableCustomHeader}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.ReportHeader.StylePriority.UseFont = false; this.ReportHeader.StylePriority.UsePadding = false; this.ReportHeader.Controls.SetChildIndex(this.tableCustomHeader, 0); this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // this.cellReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.cellLocation}); resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; this.cellReportHeader.Weight = 1.553228412422955D; this.cellReportHeader.Controls.SetChildIndex(this.tableInterval, 0); this.cellReportHeader.Controls.SetChildIndex(this.lblReportName, 0); this.cellReportHeader.Controls.SetChildIndex(this.cellLocation, 0); // // cellBaseSite // resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; this.cellBaseSite.Weight = 1.553228412422955D; // // cellBaseCountry // resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry"); this.cellBaseCountry.StylePriority.UseFont = false; // // cellBaseLeftHeader // resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // tableCustomHeader // resources.ApplyResources(this.tableCustomHeader, "tableCustomHeader"); this.tableCustomHeader.Name = "tableCustomHeader"; this.tableCustomHeader.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1, this.xrTableRow2, this.xrTableRow3, this.xrTableRow4, this.EnTableRow1, this.EnTableRow2, this.GgTableRow1, this.GgTableRow2, this.xrTableRow23, this.xrTableRow21, this.xrTableRow8, this.xrTableRow9, this.xrTableRow11, this.xrTableRow12, this.xrTableRow13, this.xrTableRow14, this.xrTableRow15}); this.tableCustomHeader.StylePriority.UseFont = false; this.tableCustomHeader.StylePriority.UseTextAlignment = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1}); resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Weight = 0.750000381469843D; // // xrTableCell1 // resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.StylePriority.UseFont = false; this.xrTableCell1.StylePriority.UseTextAlignment = false; this.xrTableCell1.Weight = 3D; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell2}); resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); this.xrTableRow2.Name = "xrTableRow2"; this.xrTableRow2.Weight = 1.1199996614642658D; // // xrTableCell2 // resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); this.xrTableCell2.Multiline = true; this.xrTableCell2.Name = "xrTableCell2"; this.xrTableCell2.StylePriority.UseFont = false; this.xrTableCell2.StylePriority.UseTextAlignment = false; this.xrTableCell2.Weight = 3D; // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell5, this.xrTableCell6, this.xrTableCell84}); resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); this.xrTableRow3.Name = "xrTableRow3"; this.xrTableRow3.StylePriority.UseFont = false; this.xrTableRow3.StylePriority.UseTextAlignment = false; this.xrTableRow3.Weight = 0.799999715166168D; // // xrTableCell5 // resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); this.xrTableCell5.Multiline = true; this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.Padding = new DevExpress.XtraPrinting.PaddingInfo(44, 2, 2, 2, 100F); this.xrTableCell5.StylePriority.UseFont = false; this.xrTableCell5.StylePriority.UsePadding = false; this.xrTableCell5.StylePriority.UseTextAlignment = false; this.xrTableCell5.Weight = 1.4873598055652759D; // // xrTableCell6 // resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.Weight = 1.2640449033664152D; // // xrTableCell84 // resources.ApplyResources(this.xrTableCell84, "xrTableCell84"); this.xrTableCell84.Name = "xrTableCell84"; this.xrTableCell84.StylePriority.UseFont = false; this.xrTableCell84.StylePriority.UseTextAlignment = false; this.xrTableCell84.Weight = 0.24859529106830902D; // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell9, this.xrTableCell14, this.xrTableCell29}); resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); this.xrTableRow4.Name = "xrTableRow4"; this.xrTableRow4.StylePriority.UseFont = false; this.xrTableRow4.StylePriority.UseTextAlignment = false; this.xrTableRow4.Weight = 0.79999975252393962D; // // xrTableCell9 // resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.Weight = 1.4873598055652759D; // // xrTableCell14 // resources.ApplyResources(this.xrTableCell14, "xrTableCell14"); this.xrTableCell14.Name = "xrTableCell14"; this.xrTableCell14.StylePriority.UseFont = false; this.xrTableCell14.StylePriority.UseTextAlignment = false; this.xrTableCell14.Weight = 1.2640451605370615D; // // xrTableCell29 // resources.ApplyResources(this.xrTableCell29, "xrTableCell29"); this.xrTableCell29.Name = "xrTableCell29"; this.xrTableCell29.Weight = 0.24859503389766274D; // // EnTableRow1 // this.EnTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell38, this.xrTableCell3, this.xrTableCell75, this.xrTableCell85, this.xrTableCell86, this.xrTableCell87, this.xrTableCell80}); resources.ApplyResources(this.EnTableRow1, "EnTableRow1"); this.EnTableRow1.Name = "EnTableRow1"; this.EnTableRow1.StylePriority.UseFont = false; this.EnTableRow1.StylePriority.UsePadding = false; this.EnTableRow1.StylePriority.UseTextAlignment = false; this.EnTableRow1.Weight = 0.59999989211962645D; // // xrTableCell38 // resources.ApplyResources(this.xrTableCell38, "xrTableCell38"); this.xrTableCell38.Name = "xrTableCell38"; this.xrTableCell38.Weight = 1.4873598055652759D; // // xrTableCell3 // resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.Weight = 0.41713477439190716D; // // xrTableCell75 // this.xrTableCell75.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell75.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strOrderNumber")}); resources.ApplyResources(this.xrTableCell75, "xrTableCell75"); this.xrTableCell75.Name = "xrTableCell75"; this.xrTableCell75.StylePriority.UseBorders = false; this.xrTableCell75.StylePriority.UseFont = false; this.xrTableCell75.StylePriority.UseTextAlignment = false; this.xrTableCell75.Weight = 0.16853935473827475D; // // InfectiousDiseaseHeaderDataSet // this.InfectiousDiseaseHeaderDataSet.DataSetName = "InfectiousDiseaseMonthNewHeaderDataSet"; this.InfectiousDiseaseHeaderDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // xrTableCell85 // resources.ApplyResources(this.xrTableCell85, "xrTableCell85"); this.xrTableCell85.Name = "xrTableCell85"; this.xrTableCell85.Weight = 0.10533709671142175D; // // xrTableCell86 // this.xrTableCell86.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell86.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strOrderDate")}); resources.ApplyResources(this.xrTableCell86, "xrTableCell86"); this.xrTableCell86.Name = "xrTableCell86"; this.xrTableCell86.StylePriority.UseBorders = false; this.xrTableCell86.StylePriority.UseTextAlignment = false; this.xrTableCell86.Weight = 0.21067419342284349D; // // xrTableCell87 // resources.ApplyResources(this.xrTableCell87, "xrTableCell87"); this.xrTableCell87.Name = "xrTableCell87"; this.xrTableCell87.Weight = 0.36235948410196772D; // // xrTableCell80 // resources.ApplyResources(this.xrTableCell80, "xrTableCell80"); this.xrTableCell80.Name = "xrTableCell80"; this.xrTableCell80.Weight = 0.2485952910683091D; // // EnTableRow2 // this.EnTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell81, this.xrTableCell82, this.xrTableCell83}); resources.ApplyResources(this.EnTableRow2, "EnTableRow2"); this.EnTableRow2.Name = "EnTableRow2"; this.EnTableRow2.StylePriority.UseFont = false; this.EnTableRow2.StylePriority.UsePadding = false; this.EnTableRow2.StylePriority.UseTextAlignment = false; this.EnTableRow2.Weight = 0.59999977767874335D; // // xrTableCell81 // resources.ApplyResources(this.xrTableCell81, "xrTableCell81"); this.xrTableCell81.Name = "xrTableCell81"; this.xrTableCell81.Weight = 1.4873598055652759D; // // xrTableCell82 // resources.ApplyResources(this.xrTableCell82, "xrTableCell82"); this.xrTableCell82.Name = "xrTableCell82"; this.xrTableCell82.StylePriority.UseFont = false; this.xrTableCell82.Weight = 1.2640451605370615D; // // xrTableCell83 // resources.ApplyResources(this.xrTableCell83, "xrTableCell83"); this.xrTableCell83.Name = "xrTableCell83"; this.xrTableCell83.Weight = 0.24859503389766274D; // // GgTableRow1 // this.GgTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell7, this.xrTableCell8, this.xrTableCell88}); resources.ApplyResources(this.GgTableRow1, "GgTableRow1"); this.GgTableRow1.Name = "GgTableRow1"; this.GgTableRow1.StylePriority.UseFont = false; this.GgTableRow1.StylePriority.UsePadding = false; this.GgTableRow1.StylePriority.UseTextAlignment = false; this.GgTableRow1.Weight = 0.59999977767874346D; // // xrTableCell7 // resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.Weight = 1.4873598055652759D; // // xrTableCell8 // resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); this.xrTableCell8.Name = "xrTableCell8"; this.xrTableCell8.StylePriority.UseFont = false; this.xrTableCell8.Tag = "UnchangedFont"; this.xrTableCell8.Weight = 1.2640451605370615D; // // xrTableCell88 // resources.ApplyResources(this.xrTableCell88, "xrTableCell88"); this.xrTableCell88.Name = "xrTableCell88"; this.xrTableCell88.Weight = 0.24859503389766274D; // // GgTableRow2 // this.GgTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell89, this.xrTableCell92, this.xrTableCell93, this.xrTableCell95, this.xrTableCell97, this.xrTableCell90, this.xrTableCell91}); resources.ApplyResources(this.GgTableRow2, "GgTableRow2"); this.GgTableRow2.Name = "GgTableRow2"; this.GgTableRow2.StylePriority.UseFont = false; this.GgTableRow2.StylePriority.UsePadding = false; this.GgTableRow2.StylePriority.UseTextAlignment = false; this.GgTableRow2.Weight = 0.59999977767874335D; // // xrTableCell89 // resources.ApplyResources(this.xrTableCell89, "xrTableCell89"); this.xrTableCell89.Name = "xrTableCell89"; this.xrTableCell89.Weight = 1.4873598055652759D; // // xrTableCell92 // resources.ApplyResources(this.xrTableCell92, "xrTableCell92"); this.xrTableCell92.Name = "xrTableCell92"; this.xrTableCell92.StylePriority.UseFont = false; this.xrTableCell92.Tag = "UnchangedFont"; this.xrTableCell92.Weight = 0.54775290289939327D; // // xrTableCell93 // this.xrTableCell93.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell93.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strOrderDate")}); resources.ApplyResources(this.xrTableCell93, "xrTableCell93"); this.xrTableCell93.Name = "xrTableCell93"; this.xrTableCell93.StylePriority.UseBorders = false; this.xrTableCell93.StylePriority.UseFont = false; this.xrTableCell93.StylePriority.UseTextAlignment = false; this.xrTableCell93.Tag = "UnchangedFont"; this.xrTableCell93.Weight = 0.18960677408055929D; // // xrTableCell95 // resources.ApplyResources(this.xrTableCell95, "xrTableCell95"); this.xrTableCell95.Name = "xrTableCell95"; this.xrTableCell95.StylePriority.UseFont = false; this.xrTableCell95.Tag = "UnchangedFont"; this.xrTableCell95.Weight = 0.14747193539599057D; // // xrTableCell97 // this.xrTableCell97.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell97.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strOrderNumber")}); resources.ApplyResources(this.xrTableCell97, "xrTableCell97"); this.xrTableCell97.Name = "xrTableCell97"; this.xrTableCell97.StylePriority.UseBorders = false; this.xrTableCell97.StylePriority.UseFont = false; this.xrTableCell97.StylePriority.UseTextAlignment = false; this.xrTableCell97.Tag = "UnchangedFont"; this.xrTableCell97.Weight = 0.14747193539599043D; // // xrTableCell90 // resources.ApplyResources(this.xrTableCell90, "xrTableCell90"); this.xrTableCell90.Name = "xrTableCell90"; this.xrTableCell90.StylePriority.UseFont = false; this.xrTableCell90.Tag = "UnchangedFont"; this.xrTableCell90.Weight = 0.23174161276512789D; // // xrTableCell91 // resources.ApplyResources(this.xrTableCell91, "xrTableCell91"); this.xrTableCell91.Name = "xrTableCell91"; this.xrTableCell91.Weight = 0.24859503389766274D; // // xrTableRow23 // this.xrTableRow23.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell70}); resources.ApplyResources(this.xrTableRow23, "xrTableRow23"); this.xrTableRow23.Name = "xrTableRow23"; this.xrTableRow23.StylePriority.UseTextAlignment = false; this.xrTableRow23.Weight = 1.5999994678745826D; // // xrTableCell70 // resources.ApplyResources(this.xrTableCell70, "xrTableCell70"); this.xrTableCell70.Multiline = true; this.xrTableCell70.Name = "xrTableCell70"; this.xrTableCell70.StylePriority.UseFont = false; this.xrTableCell70.StylePriority.UseTextAlignment = false; this.xrTableCell70.Weight = 3D; // // xrTableRow21 // this.xrTableRow21.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell16, this.xrTableCell27, this.xrTableCell15}); resources.ApplyResources(this.xrTableRow21, "xrTableRow21"); this.xrTableRow21.Name = "xrTableRow21"; this.xrTableRow21.Weight = 1.5999995070409951D; // // xrTableCell16 // resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); this.xrTableCell16.Name = "xrTableCell16"; this.xrTableCell16.Weight = 1.4873598055652757D; // // xrTableCell27 // resources.ApplyResources(this.xrTableCell27, "xrTableCell27"); this.xrTableCell27.Multiline = true; this.xrTableCell27.Name = "xrTableCell27"; this.xrTableCell27.StylePriority.UseFont = false; this.xrTableCell27.Weight = 1.2640449033664152D; // // xrTableCell15 // resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); this.xrTableCell15.Name = "xrTableCell15"; this.xrTableCell15.Weight = 0.24859529106830913D; // // xrTableRow8 // this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell10, this.cellNameOfrespondent, this.xrTableCell11}); resources.ApplyResources(this.xrTableRow8, "xrTableRow8"); this.xrTableRow8.Name = "xrTableRow8"; this.xrTableRow8.Weight = 0.47999982954698456D; // // xrTableCell10 // resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseFont = false; this.xrTableCell10.Weight = 1.3230339346954576D; // // cellNameOfrespondent // resources.ApplyResources(this.cellNameOfrespondent, "cellNameOfrespondent"); this.cellNameOfrespondent.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.cellNameOfrespondent.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strNameOfRespondent")}); this.cellNameOfrespondent.Name = "cellNameOfrespondent"; this.cellNameOfrespondent.StylePriority.UseBackColor = false; this.cellNameOfrespondent.StylePriority.UseBorders = false; this.cellNameOfrespondent.StylePriority.UseFont = false; this.cellNameOfrespondent.Weight = 1.4325845152753365D; // // xrTableCell11 // resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); this.xrTableCell11.Name = "xrTableCell11"; this.xrTableCell11.StylePriority.UseFont = false; this.xrTableCell11.StylePriority.UseTextAlignment = false; this.xrTableCell11.Weight = 0.24438155002920606D; // // xrTableRow9 // this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell12, this.cellActualAddress, this.xrTableCell13}); resources.ApplyResources(this.xrTableRow9, "xrTableRow9"); this.xrTableRow9.Name = "xrTableRow9"; this.xrTableRow9.Weight = 0.47999982954698439D; // // xrTableCell12 // resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.StylePriority.UseFont = false; this.xrTableCell12.Weight = 1.3230339346954576D; // // cellActualAddress // resources.ApplyResources(this.cellActualAddress, "cellActualAddress"); this.cellActualAddress.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.cellActualAddress.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strActualAddress")}); this.cellActualAddress.Name = "cellActualAddress"; this.cellActualAddress.StylePriority.UseBackColor = false; this.cellActualAddress.StylePriority.UseBorders = false; this.cellActualAddress.StylePriority.UseFont = false; this.cellActualAddress.Weight = 1.4325845152753363D; // // xrTableCell13 // resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.StylePriority.UseFont = false; this.xrTableCell13.StylePriority.UseTextAlignment = false; this.xrTableCell13.Weight = 0.24438155002920595D; // // xrTableRow11 // this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell17, this.xrTableCell18, this.xrTableCell19}); resources.ApplyResources(this.xrTableRow11, "xrTableRow11"); this.xrTableRow11.Name = "xrTableRow11"; this.xrTableRow11.Weight = 0.47999982954698428D; // // xrTableCell17 // resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); this.xrTableCell17.Name = "xrTableCell17"; this.xrTableCell17.StylePriority.UseFont = false; this.xrTableCell17.Weight = 1.3230339346954576D; // // xrTableCell18 // resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); this.xrTableCell18.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.xrTableCell18.Name = "xrTableCell18"; this.xrTableCell18.StylePriority.UseBackColor = false; this.xrTableCell18.StylePriority.UseBorders = false; this.xrTableCell18.StylePriority.UseFont = false; this.xrTableCell18.Weight = 1.4325845152753363D; // // xrTableCell19 // resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); this.xrTableCell19.Name = "xrTableCell19"; this.xrTableCell19.StylePriority.UseFont = false; this.xrTableCell19.StylePriority.UseTextAlignment = false; this.xrTableCell19.Weight = 0.24438155002920595D; // // xrTableRow12 // this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell20, this.xrTableCell21, this.xrTableCell22}); resources.ApplyResources(this.xrTableRow12, "xrTableRow12"); this.xrTableRow12.Name = "xrTableRow12"; this.xrTableRow12.Weight = 0.4799998295469845D; // // xrTableCell20 // resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); this.xrTableCell20.Name = "xrTableCell20"; this.xrTableCell20.StylePriority.UseFont = false; this.xrTableCell20.Weight = 1.3230339346954576D; // // xrTableCell21 // resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); this.xrTableCell21.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.xrTableCell21.Name = "xrTableCell21"; this.xrTableCell21.StylePriority.UseBackColor = false; this.xrTableCell21.StylePriority.UseBorders = false; this.xrTableCell21.StylePriority.UseFont = false; this.xrTableCell21.Weight = 1.43258425810469D; // // xrTableCell22 // resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); this.xrTableCell22.Name = "xrTableCell22"; this.xrTableCell22.StylePriority.UseFont = false; this.xrTableCell22.StylePriority.UseTextAlignment = false; this.xrTableCell22.Weight = 0.24438180719985223D; // // xrTableRow13 // this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell23, this.xrTableCell24, this.xrTableCell25}); resources.ApplyResources(this.xrTableRow13, "xrTableRow13"); this.xrTableRow13.Name = "xrTableRow13"; this.xrTableRow13.Weight = 0.47999982954698445D; // // xrTableCell23 // resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); this.xrTableCell23.Name = "xrTableCell23"; this.xrTableCell23.StylePriority.UseFont = false; this.xrTableCell23.Weight = 1.3230339346954576D; // // xrTableCell24 // resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); this.xrTableCell24.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); this.xrTableCell24.Name = "xrTableCell24"; this.xrTableCell24.StylePriority.UseBackColor = false; this.xrTableCell24.StylePriority.UseBorders = false; this.xrTableCell24.StylePriority.UseFont = false; this.xrTableCell24.Weight = 1.4325845152753363D; // // xrTableCell25 // resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); this.xrTableCell25.Name = "xrTableCell25"; this.xrTableCell25.StylePriority.UseFont = false; this.xrTableCell25.StylePriority.UseTextAlignment = false; this.xrTableCell25.Weight = 0.24438155002920595D; // // xrTableRow14 // this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell26, this.cellTelephone, this.xrTableCell28}); resources.ApplyResources(this.xrTableRow14, "xrTableRow14"); this.xrTableRow14.Name = "xrTableRow14"; this.xrTableRow14.Weight = 0.47999982954698428D; // // xrTableCell26 // resources.ApplyResources(this.xrTableCell26, "xrTableCell26"); this.xrTableCell26.Name = "xrTableCell26"; this.xrTableCell26.StylePriority.UseFont = false; this.xrTableCell26.Weight = 1.3230339346954576D; // // cellTelephone // resources.ApplyResources(this.cellTelephone, "cellTelephone"); this.cellTelephone.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.cellTelephone.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strTelephone")}); this.cellTelephone.Name = "cellTelephone"; this.cellTelephone.StylePriority.UseBackColor = false; this.cellTelephone.StylePriority.UseBorders = false; this.cellTelephone.StylePriority.UseFont = false; this.cellTelephone.Weight = 1.4325845152753363D; // // xrTableCell28 // resources.ApplyResources(this.xrTableCell28, "xrTableCell28"); this.xrTableCell28.Name = "xrTableCell28"; this.xrTableCell28.StylePriority.UseFont = false; this.xrTableCell28.Weight = 0.24438155002920595D; // // xrTableRow15 // this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.cellReportedPeriod, this.xrTableCell30, this.xrTableCell31}); resources.ApplyResources(this.xrTableRow15, "xrTableRow15"); this.xrTableRow15.Name = "xrTableRow15"; this.xrTableRow15.Weight = 0.4799998295469845D; // // cellReportedPeriod // resources.ApplyResources(this.cellReportedPeriod, "cellReportedPeriod"); this.cellReportedPeriod.Name = "cellReportedPeriod"; this.cellReportedPeriod.StylePriority.UseFont = false; this.cellReportedPeriod.Weight = 1.3230339346954576D; // // xrTableCell30 // resources.ApplyResources(this.xrTableCell30, "xrTableCell30"); this.xrTableCell30.Name = "xrTableCell30"; this.xrTableCell30.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 2, 2, 2, 100F); this.xrTableCell30.StylePriority.UseFont = false; this.xrTableCell30.StylePriority.UsePadding = false; this.xrTableCell30.Weight = 1.4283710314068794D; // // xrTableCell31 // resources.ApplyResources(this.xrTableCell31, "xrTableCell31"); this.xrTableCell31.Name = "xrTableCell31"; this.xrTableCell31.Weight = 0.24859503389766283D; // // InfectiousDiseaseDataSet // this.InfectiousDiseaseDataSet.DataSetName = "InfectiousDiseaseMonthNewDataSet"; this.InfectiousDiseaseDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // ReportFooter // this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.tableCustomFooter}); resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; this.ReportFooter.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.ReportFooter.StylePriority.UseFont = false; this.ReportFooter.StylePriority.UsePadding = false; this.ReportFooter.StylePriority.UseTextAlignment = false; // // tableCustomFooter // resources.ApplyResources(this.tableCustomFooter, "tableCustomFooter"); this.tableCustomFooter.Name = "tableCustomFooter"; this.tableCustomFooter.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow18, this.xrTableRow25, this.xrTableRow5}); this.tableCustomFooter.StylePriority.UseFont = false; // // xrTableRow18 // this.xrTableRow18.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell35, this.DayFooterCell, this.xrTableCell34, this.MonthFooterCell, this.YearFooterCell, this.xrTableCell32, this.ChiefFooterCell, this.xrTableCell4}); resources.ApplyResources(this.xrTableRow18, "xrTableRow18"); this.xrTableRow18.Name = "xrTableRow18"; this.xrTableRow18.Weight = 1D; // // xrTableCell35 // resources.ApplyResources(this.xrTableCell35, "xrTableCell35"); this.xrTableCell35.Name = "xrTableCell35"; this.xrTableCell35.Weight = 0.042253524694000635D; // // DayFooterCell // this.DayFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.DayFooterCell, "DayFooterCell"); this.DayFooterCell.Name = "DayFooterCell"; this.DayFooterCell.StylePriority.UseBorders = false; this.DayFooterCell.StylePriority.UseTextAlignment = false; this.DayFooterCell.Weight = 0.16901409897125619D; // // xrTableCell34 // resources.ApplyResources(this.xrTableCell34, "xrTableCell34"); this.xrTableCell34.Name = "xrTableCell34"; this.xrTableCell34.Weight = 0.042253521038213115D; // // MonthFooterCell // this.MonthFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.MonthFooterCell, "MonthFooterCell"); this.MonthFooterCell.Name = "MonthFooterCell"; this.MonthFooterCell.StylePriority.UseBorders = false; this.MonthFooterCell.StylePriority.UseTextAlignment = false; this.MonthFooterCell.Weight = 0.50704226900465355D; // // YearFooterCell // this.YearFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.YearFooterCell, "YearFooterCell"); this.YearFooterCell.Name = "YearFooterCell"; this.YearFooterCell.StylePriority.UseBorders = false; this.YearFooterCell.Weight = 0.19859169425273882D; // // xrTableCell32 // resources.ApplyResources(this.xrTableCell32, "xrTableCell32"); this.xrTableCell32.Name = "xrTableCell32"; this.xrTableCell32.Weight = 0.40985909319214486D; // // ChiefFooterCell // this.ChiefFooterCell.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.ChiefFooterCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", this.InfectiousDiseaseHeaderDataSet, "spRepHumMonthlyInfectiousDiseaseNewHeader.strChief")}); resources.ApplyResources(this.ChiefFooterCell, "ChiefFooterCell"); this.ChiefFooterCell.Name = "ChiefFooterCell"; this.ChiefFooterCell.StylePriority.UseBorders = false; this.ChiefFooterCell.Weight = 1.2929581144817024D; // // xrTableCell4 // resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UseFont = false; this.xrTableCell4.Weight = 0.33802768436529051D; // // xrTableRow25 // this.xrTableRow25.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell79}); resources.ApplyResources(this.xrTableRow25, "xrTableRow25"); this.xrTableRow25.Name = "xrTableRow25"; this.xrTableRow25.Weight = 1.5D; // // xrTableCell79 // this.xrTableCell79.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; resources.ApplyResources(this.xrTableCell79, "xrTableCell79"); this.xrTableCell79.Name = "xrTableCell79"; this.xrTableCell79.StylePriority.UseBorders = false; this.xrTableCell79.Weight = 3D; // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell33}); resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); this.xrTableRow5.Name = "xrTableRow5"; this.xrTableRow5.Weight = 1D; // // xrTableCell33 // resources.ApplyResources(this.xrTableCell33, "xrTableCell33"); this.xrTableCell33.Name = "xrTableCell33"; this.xrTableCell33.StylePriority.UseTextAlignment = false; this.xrTableCell33.Weight = 3D; // // tableBody // this.tableBody.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.tableBody, "tableBody"); this.tableBody.Name = "tableBody"; this.tableBody.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow19, this.xrTableRow20}); this.tableBody.StylePriority.UseBorders = false; // // xrTableRow19 // this.xrTableRow19.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell71, this.xrTableCell43, this.xrTableCell47, this.xrTableCell40, this.xrTableCell46, this.xrTableCell44, this.xrTableCell48, this.xrTableCell41, this.xrTableCell49, this.xrTableCell52, this.xrTableCell66, this.xrTableCell45, this.xrTableCell67, this.xrTableCell51, this.xrTableCell50, this.xrTableCell42}); resources.ApplyResources(this.xrTableRow19, "xrTableRow19"); this.xrTableRow19.Name = "xrTableRow19"; this.xrTableRow19.Weight = 3.4510522092487617D; // // xrTableCell71 // resources.ApplyResources(this.xrTableCell71, "xrTableCell71"); this.xrTableCell71.Name = "xrTableCell71"; this.xrTableCell71.StylePriority.UseFont = false; this.xrTableCell71.Weight = 0.12676056191221669D; // // xrTableCell43 // resources.ApplyResources(this.xrTableCell43, "xrTableCell43"); this.xrTableCell43.Name = "xrTableCell43"; this.xrTableCell43.StylePriority.UseFont = false; this.xrTableCell43.Weight = 0.83239434956416392D; // // xrTableCell47 // resources.ApplyResources(this.xrTableCell47, "xrTableCell47"); this.xrTableCell47.Name = "xrTableCell47"; this.xrTableCell47.StylePriority.UseFont = false; this.xrTableCell47.Weight = 0.25352105573348971D; // // xrTableCell40 // resources.ApplyResources(this.xrTableCell40, "xrTableCell40"); this.xrTableCell40.Name = "xrTableCell40"; this.xrTableCell40.StylePriority.UseFont = false; this.xrTableCell40.Weight = 0.15633802370428213D; // // xrTableCell46 // resources.ApplyResources(this.xrTableCell46, "xrTableCell46"); this.xrTableCell46.Name = "xrTableCell46"; this.xrTableCell46.StylePriority.UseFont = false; this.xrTableCell46.Weight = 0.15633802370428229D; // // xrTableCell44 // resources.ApplyResources(this.xrTableCell44, "xrTableCell44"); this.xrTableCell44.Name = "xrTableCell44"; this.xrTableCell44.StylePriority.UseFont = false; this.xrTableCell44.Weight = 0.15633802370428232D; // // xrTableCell48 // resources.ApplyResources(this.xrTableCell48, "xrTableCell48"); this.xrTableCell48.Name = "xrTableCell48"; this.xrTableCell48.StylePriority.UseFont = false; this.xrTableCell48.Weight = 0.15633802370428221D; // // xrTableCell41 // resources.ApplyResources(this.xrTableCell41, "xrTableCell41"); this.xrTableCell41.Name = "xrTableCell41"; this.xrTableCell41.StylePriority.UseFont = false; this.xrTableCell41.Weight = 0.156338039822721D; // // xrTableCell49 // resources.ApplyResources(this.xrTableCell49, "xrTableCell49"); this.xrTableCell49.Name = "xrTableCell49"; this.xrTableCell49.StylePriority.UseFont = false; this.xrTableCell49.Weight = 0.15633802370428207D; // // xrTableCell52 // resources.ApplyResources(this.xrTableCell52, "xrTableCell52"); this.xrTableCell52.Name = "xrTableCell52"; this.xrTableCell52.StylePriority.UseFont = false; this.xrTableCell52.Weight = 0.15633810698288259D; // // xrTableCell66 // resources.ApplyResources(this.xrTableCell66, "xrTableCell66"); this.xrTableCell66.Name = "xrTableCell66"; this.xrTableCell66.Weight = 0.0084503816749598171D; // // xrTableCell45 // resources.ApplyResources(this.xrTableCell45, "xrTableCell45"); this.xrTableCell45.Name = "xrTableCell45"; this.xrTableCell45.StylePriority.UseFont = false; this.xrTableCell45.Weight = 0.16901434035131324D; // // xrTableCell67 // resources.ApplyResources(this.xrTableCell67, "xrTableCell67"); this.xrTableCell67.Name = "xrTableCell67"; this.xrTableCell67.Weight = 0.008450962729544D; // // xrTableCell51 // this.xrTableCell51.Angle = 90F; resources.ApplyResources(this.xrTableCell51, "xrTableCell51"); this.xrTableCell51.Name = "xrTableCell51"; this.xrTableCell51.StylePriority.UseFont = false; this.xrTableCell51.Weight = 0.1690138237704843D; // // xrTableCell50 // this.xrTableCell50.Angle = 90F; resources.ApplyResources(this.xrTableCell50, "xrTableCell50"); this.xrTableCell50.Name = "xrTableCell50"; this.xrTableCell50.StylePriority.UseFont = false; this.xrTableCell50.Weight = 0.16901408245629254D; // // xrTableCell42 // this.xrTableCell42.Angle = 90F; resources.ApplyResources(this.xrTableCell42, "xrTableCell42"); this.xrTableCell42.Name = "xrTableCell42"; this.xrTableCell42.StylePriority.UseFont = false; this.xrTableCell42.Weight = 0.16901411200676422D; // // xrTableRow20 // this.xrTableRow20.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell72, this.xrTableCell53, this.xrTableCell54, this.xrTableCell55, this.xrTableCell56, this.xrTableCell57, this.xrTableCell58, this.xrTableCell59, this.xrTableCell60, this.xrTableCell61, this.xrTableCell68, this.xrTableCell62, this.xrTableCell69, this.xrTableCell63, this.xrTableCell64, this.xrTableCell65}); resources.ApplyResources(this.xrTableRow20, "xrTableRow20"); this.xrTableRow20.Name = "xrTableRow20"; this.xrTableRow20.StylePriority.UseBorders = false; this.xrTableRow20.StylePriority.UsePadding = false; this.xrTableRow20.Weight = 0.34510517859058065D; // // xrTableCell72 // resources.ApplyResources(this.xrTableCell72, "xrTableCell72"); this.xrTableCell72.Name = "xrTableCell72"; this.xrTableCell72.Weight = 0.1267605457937778D; // // xrTableCell53 // resources.ApplyResources(this.xrTableCell53, "xrTableCell53"); this.xrTableCell53.Name = "xrTableCell53"; this.xrTableCell53.StylePriority.UseFont = false; this.xrTableCell53.Weight = 0.83239436568260272D; // // xrTableCell54 // resources.ApplyResources(this.xrTableCell54, "xrTableCell54"); this.xrTableCell54.Name = "xrTableCell54"; this.xrTableCell54.StylePriority.UseFont = false; this.xrTableCell54.Weight = 0.25352118468100016D; // // xrTableCell55 // resources.ApplyResources(this.xrTableCell55, "xrTableCell55"); this.xrTableCell55.Name = "xrTableCell55"; this.xrTableCell55.StylePriority.UseFont = false; this.xrTableCell55.Weight = 0.15633776580926131D; // // xrTableCell56 // resources.ApplyResources(this.xrTableCell56, "xrTableCell56"); this.xrTableCell56.Name = "xrTableCell56"; this.xrTableCell56.StylePriority.UseFont = false; this.xrTableCell56.Weight = 0.15633828159930321D; // // xrTableCell57 // resources.ApplyResources(this.xrTableCell57, "xrTableCell57"); this.xrTableCell57.Name = "xrTableCell57"; this.xrTableCell57.StylePriority.UseFont = false; this.xrTableCell57.Weight = 0.1563378947567719D; // // xrTableCell58 // resources.ApplyResources(this.xrTableCell58, "xrTableCell58"); this.xrTableCell58.Name = "xrTableCell58"; this.xrTableCell58.StylePriority.UseFont = false; this.xrTableCell58.Weight = 0.15633802370428229D; // // xrTableCell59 // resources.ApplyResources(this.xrTableCell59, "xrTableCell59"); this.xrTableCell59.Name = "xrTableCell59"; this.xrTableCell59.StylePriority.UseFont = false; this.xrTableCell59.Weight = 0.15633802370428224D; // // xrTableCell60 // resources.ApplyResources(this.xrTableCell60, "xrTableCell60"); this.xrTableCell60.Name = "xrTableCell60"; this.xrTableCell60.StylePriority.UseFont = false; this.xrTableCell60.Weight = 0.15633802370428213D; // // xrTableCell61 // resources.ApplyResources(this.xrTableCell61, "xrTableCell61"); this.xrTableCell61.Name = "xrTableCell61"; this.xrTableCell61.StylePriority.UseFont = false; this.xrTableCell61.Weight = 0.15633802639068856D; // // xrTableCell68 // resources.ApplyResources(this.xrTableCell68, "xrTableCell68"); this.xrTableCell68.Name = "xrTableCell68"; this.xrTableCell68.Weight = 0.0084507209529619265D; // // xrTableCell62 // resources.ApplyResources(this.xrTableCell62, "xrTableCell62"); this.xrTableCell62.Name = "xrTableCell62"; this.xrTableCell62.StylePriority.UseFont = false; this.xrTableCell62.Weight = 0.16901409778394394D; // // xrTableCell69 // resources.ApplyResources(this.xrTableCell69, "xrTableCell69"); this.xrTableCell69.Name = "xrTableCell69"; this.xrTableCell69.Weight = 0.0084514777287984927D; // // xrTableCell63 // resources.ApplyResources(this.xrTableCell63, "xrTableCell63"); this.xrTableCell63.Name = "xrTableCell63"; this.xrTableCell63.StylePriority.UseFont = false; this.xrTableCell63.Weight = 0.16901356666625073D; // // xrTableCell64 // resources.ApplyResources(this.xrTableCell64, "xrTableCell64"); this.xrTableCell64.Name = "xrTableCell64"; this.xrTableCell64.StylePriority.UseFont = false; this.xrTableCell64.Weight = 0.1690140824562926D; // // xrTableCell65 // resources.ApplyResources(this.xrTableCell65, "xrTableCell65"); this.xrTableCell65.Name = "xrTableCell65"; this.xrTableCell65.StylePriority.UseFont = false; this.xrTableCell65.Weight = 0.16901385411174336D; // // DetailReport // this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.CustomDetail, this.CustomReportHeader}); this.DetailReport.DataAdapter = this.SpRepHumMonthlyInfectiousDiseaseNewTableAdapter; this.DetailReport.DataMember = "spRepHumMonthlyInfectiousDiseaseNew"; this.DetailReport.DataSource = this.InfectiousDiseaseDataSet; resources.ApplyResources(this.DetailReport, "DetailReport"); this.DetailReport.Level = 0; this.DetailReport.Name = "DetailReport"; this.DetailReport.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); // // CustomDetail // this.CustomDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.PageBreakAtLine36, this.xrTable1}); resources.ApplyResources(this.CustomDetail, "CustomDetail"); this.CustomDetail.Name = "CustomDetail"; this.CustomDetail.StylePriority.UseFont = false; this.CustomDetail.StylePriority.UseTextAlignment = false; // // PageBreakAtLine36 // resources.ApplyResources(this.PageBreakAtLine36, "PageBreakAtLine36"); this.PageBreakAtLine36.FormattingRules.Add(this.formattingRule2); this.PageBreakAtLine36.Name = "PageBreakAtLine36"; // // formattingRule2 // this.formattingRule2.Condition = "[DataSource.CurrentRowIndex] ==36"; this.formattingRule2.DataMember = "spRepHumMonthlyInfectiousDiseaseNew"; this.formattingRule2.DataSource = this.InfectiousDiseaseDataSet; // // // this.formattingRule2.Formatting.Visible = DevExpress.Utils.DefaultBoolean.True; this.formattingRule2.Name = "formattingRule2"; // // xrTable1 // this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.FormattingRules.Add(this.formattingRule3); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow22}); this.xrTable1.StylePriority.UseBorders = false; this.xrTable1.StylePriority.UseFont = false; this.xrTable1.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // formattingRule3 // this.formattingRule3.Condition = "[DataSource.CurrentRowIndex] ==36"; // // // this.formattingRule3.Formatting.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.formattingRule3.Name = "formattingRule3"; // // xrTableRow22 // this.xrTableRow22.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell73, this.strDiseaseName, this.cellICD10, this.cellAge_0_1, this.cellAge_1_4, this.cellAge_5_14, this.cellAge_15_19, this.cellAge_20_29, this.cellAge_30_59, this.cellAge_60_more, this.xrTableCell94, this.cellTotal, this.xrTableCell96, this.cellLabTested, this.cellLabConfirmed, this.cellTotalConfirmed}); resources.ApplyResources(this.xrTableRow22, "xrTableRow22"); this.xrTableRow22.Name = "xrTableRow22"; this.xrTableRow22.StylePriority.UseBorders = false; this.xrTableRow22.Weight = 0.34510518943249707D; // // xrTableCell73 // resources.ApplyResources(this.xrTableCell73, "xrTableCell73"); this.xrTableCell73.Name = "xrTableCell73"; this.xrTableCell73.StylePriority.UseFont = false; resources.ApplyResources(xrSummary1, "xrSummary1"); xrSummary1.Func = DevExpress.XtraReports.UI.SummaryFunc.RecordNumber; xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Report; this.xrTableCell73.Summary = xrSummary1; this.xrTableCell73.Weight = 0.12676056191221657D; this.xrTableCell73.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.NumberingCellBeforePrint); // // strDiseaseName // this.strDiseaseName.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.strDiseaseName")}); resources.ApplyResources(this.strDiseaseName, "strDiseaseName"); this.strDiseaseName.Name = "strDiseaseName"; this.strDiseaseName.StylePriority.UseFont = false; this.strDiseaseName.StylePriority.UseTextAlignment = false; this.strDiseaseName.Weight = 0.83239434956416425D; this.strDiseaseName.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // cellICD10 // this.cellICD10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.strICD10")}); resources.ApplyResources(this.cellICD10, "cellICD10"); this.cellICD10.Name = "cellICD10"; this.cellICD10.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.cellICD10.StylePriority.UseFont = false; this.cellICD10.StylePriority.UsePadding = false; this.cellICD10.Weight = 0.25352112020724493D; this.cellICD10.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // cellAge_0_1 // this.cellAge_0_1.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_0_1")}); resources.ApplyResources(this.cellAge_0_1, "cellAge_0_1"); this.cellAge_0_1.Name = "cellAge_0_1"; this.cellAge_0_1.StylePriority.UseFont = false; this.cellAge_0_1.Weight = 0.15633802370428218D; this.cellAge_0_1.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // cellAge_1_4 // this.cellAge_1_4.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_1_4")}); resources.ApplyResources(this.cellAge_1_4, "cellAge_1_4"); this.cellAge_1_4.Name = "cellAge_1_4"; this.cellAge_1_4.StylePriority.UseFont = false; this.cellAge_1_4.Weight = 0.15633815265179279D; this.cellAge_1_4.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // cellAge_5_14 // this.cellAge_5_14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_5_14")}); resources.ApplyResources(this.cellAge_5_14, "cellAge_5_14"); this.cellAge_5_14.Name = "cellAge_5_14"; this.cellAge_5_14.StylePriority.UseFont = false; this.cellAge_5_14.Weight = 0.15633776580926137D; this.cellAge_5_14.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // cellAge_15_19 // this.cellAge_15_19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_15_19")}); resources.ApplyResources(this.cellAge_15_19, "cellAge_15_19"); this.cellAge_15_19.Name = "cellAge_15_19"; this.cellAge_15_19.StylePriority.UseFont = false; this.cellAge_15_19.Weight = 0.15633802370428224D; this.cellAge_15_19.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // cellAge_20_29 // this.cellAge_20_29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_20_29")}); resources.ApplyResources(this.cellAge_20_29, "cellAge_20_29"); this.cellAge_20_29.Name = "cellAge_20_29"; this.cellAge_20_29.StylePriority.UseFont = false; this.cellAge_20_29.Weight = 0.15633802370428221D; this.cellAge_20_29.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // cellAge_30_59 // this.cellAge_30_59.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_30_59")}); resources.ApplyResources(this.cellAge_30_59, "cellAge_30_59"); this.cellAge_30_59.Name = "cellAge_30_59"; this.cellAge_30_59.StylePriority.UseFont = false; this.cellAge_30_59.Weight = 0.156338281599303D; this.cellAge_30_59.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // cellAge_60_more // this.cellAge_60_more.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intAge_60_more")}); resources.ApplyResources(this.cellAge_60_more, "cellAge_60_more"); this.cellAge_60_more.Name = "cellAge_60_more"; this.cellAge_60_more.StylePriority.UseFont = false; this.cellAge_60_more.Weight = 0.15633812310132142D; this.cellAge_60_more.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellBeforePrint); // // xrTableCell94 // resources.ApplyResources(this.xrTableCell94, "xrTableCell94"); this.xrTableCell94.Name = "xrTableCell94"; this.xrTableCell94.Weight = 0.0084501890444813876D; // // cellTotal // this.cellTotal.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intTotal")}); resources.ApplyResources(this.cellTotal, "cellTotal"); this.cellTotal.Name = "cellTotal"; this.cellTotal.StylePriority.UseFont = false; this.cellTotal.Weight = 0.16901382377048424D; this.cellTotal.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellTotalBeforePrint); // // xrTableCell96 // resources.ApplyResources(this.xrTableCell96, "xrTableCell96"); this.xrTableCell96.Name = "xrTableCell96"; this.xrTableCell96.Weight = 0.008451219833777654D; // // cellLabTested // this.cellLabTested.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intLabTested")}); resources.ApplyResources(this.cellLabTested, "cellLabTested"); this.cellLabTested.Name = "cellLabTested"; this.cellLabTested.StylePriority.UseFont = false; this.cellLabTested.Weight = 0.16901382456127156D; this.cellLabTested.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellLabBeforePrint); // // cellLabConfirmed // this.cellLabConfirmed.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intLabConfirmed")}); resources.ApplyResources(this.cellLabConfirmed, "cellLabConfirmed"); this.cellLabConfirmed.Name = "cellLabConfirmed"; this.cellLabConfirmed.StylePriority.UseFont = false; this.cellLabConfirmed.Weight = 0.16901408245629257D; this.cellLabConfirmed.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellLabBeforePrint); // // cellTotalConfirmed // this.cellTotalConfirmed.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumMonthlyInfectiousDisease.intTotalConfirmed")}); resources.ApplyResources(this.cellTotalConfirmed, "cellTotalConfirmed"); this.cellTotalConfirmed.Name = "cellTotalConfirmed"; this.cellTotalConfirmed.StylePriority.UseFont = false; this.cellTotalConfirmed.Weight = 0.16901436990178509D; this.cellTotalConfirmed.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CellLabBeforePrint); // // CustomReportHeader // this.CustomReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.tableBody}); resources.ApplyResources(this.CustomReportHeader, "CustomReportHeader"); this.CustomReportHeader.Name = "CustomReportHeader"; this.CustomReportHeader.StylePriority.UseTextAlignment = false; // // SpRepHumMonthlyInfectiousDiseaseNewTableAdapter // this.SpRepHumMonthlyInfectiousDiseaseNewTableAdapter.ClearBeforeFill = true; // // SpRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter // this.SpRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter.ClearBeforeFill = true; // // cellLocation // this.cellLocation.Borders = DevExpress.XtraPrinting.BorderSide.None; this.cellLocation.BorderWidth = 0; resources.ApplyResources(this.cellLocation, "cellLocation"); this.cellLocation.Name = "cellLocation"; this.cellLocation.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.cellLocation.StylePriority.UseBorders = false; this.cellLocation.StylePriority.UseBorderWidth = false; this.cellLocation.StylePriority.UseFont = false; this.cellLocation.StylePriority.UseTextAlignment = false; // // formattingRule1 // this.formattingRule1.Name = "formattingRule1"; // // InfectiousDiseasesMonthNew // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.ReportHeader, this.ReportFooter, this.DetailReport}); this.CanWorkWithArchive = true; resources.ApplyResources(this, "$this"); this.FormattingRuleSheet.AddRange(new DevExpress.XtraReports.UI.FormattingRule[] { this.formattingRule1, this.formattingRule2, this.formattingRule3}); this.Landscape = false; this.PageHeight = 1169; this.PageWidth = 827; this.Version = "11.1"; this.Controls.SetChildIndex(this.DetailReport, 0); this.Controls.SetChildIndex(this.ReportFooter, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.baseDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableCustomHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.InfectiousDiseaseHeaderDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.InfectiousDiseaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableCustomFooter)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBody)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.XRTable tableCustomHeader; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableRow xrTableRow8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTableRow xrTableRow9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTableCell cellNameOfrespondent; private DevExpress.XtraReports.UI.XRTableCell cellActualAddress; private DevExpress.XtraReports.UI.XRTableRow xrTableRow11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableRow xrTableRow12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableRow xrTableRow13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableRow xrTableRow14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell26; private DevExpress.XtraReports.UI.XRTableCell cellTelephone; private DevExpress.XtraReports.UI.XRTableCell xrTableCell28; private DevExpress.XtraReports.UI.XRTableRow xrTableRow15; private DevExpress.XtraReports.UI.XRTableCell cellReportedPeriod; private DevExpress.XtraReports.UI.XRTableCell xrTableCell30; private DevExpress.XtraReports.UI.XRTableCell xrTableCell31; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private DevExpress.XtraReports.UI.XRTable tableCustomFooter; private DevExpress.XtraReports.UI.XRTableRow xrTableRow18; private DevExpress.XtraReports.UI.XRTable tableBody; private DevExpress.XtraReports.UI.XRTableRow xrTableRow19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell40; private DevExpress.XtraReports.UI.XRTableCell xrTableCell41; private DevExpress.XtraReports.UI.XRTableCell xrTableCell42; private DevExpress.XtraReports.UI.XRTableCell xrTableCell43; private DevExpress.XtraReports.UI.XRTableCell xrTableCell47; private DevExpress.XtraReports.UI.XRTableCell xrTableCell46; private DevExpress.XtraReports.UI.XRTableCell xrTableCell44; private DevExpress.XtraReports.UI.XRTableCell xrTableCell48; private DevExpress.XtraReports.UI.XRTableCell xrTableCell49; private DevExpress.XtraReports.UI.XRTableCell xrTableCell52; private DevExpress.XtraReports.UI.XRTableCell xrTableCell45; private DevExpress.XtraReports.UI.XRTableCell xrTableCell51; private DevExpress.XtraReports.UI.XRTableCell xrTableCell50; private DevExpress.XtraReports.UI.XRTableRow xrTableRow20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell53; private DevExpress.XtraReports.UI.XRTableCell xrTableCell54; private DevExpress.XtraReports.UI.XRTableCell xrTableCell55; private DevExpress.XtraReports.UI.XRTableCell xrTableCell56; private DevExpress.XtraReports.UI.XRTableCell xrTableCell57; private DevExpress.XtraReports.UI.XRTableCell xrTableCell58; private DevExpress.XtraReports.UI.XRTableCell xrTableCell59; private DevExpress.XtraReports.UI.XRTableCell xrTableCell60; private DevExpress.XtraReports.UI.XRTableCell xrTableCell61; private DevExpress.XtraReports.UI.XRTableCell xrTableCell62; private DevExpress.XtraReports.UI.XRTableCell xrTableCell63; private DevExpress.XtraReports.UI.XRTableCell xrTableCell64; private DevExpress.XtraReports.UI.XRTableCell xrTableCell65; private DevExpress.XtraReports.UI.XRTableCell xrTableCell66; private DevExpress.XtraReports.UI.XRTableCell xrTableCell67; private DevExpress.XtraReports.UI.XRTableCell xrTableCell68; private DevExpress.XtraReports.UI.XRTableCell xrTableCell69; private DevExpress.XtraReports.UI.DetailReportBand DetailReport; private DevExpress.XtraReports.UI.DetailBand CustomDetail; private DevExpress.XtraReports.UI.ReportHeaderBand CustomReportHeader; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow22; private DevExpress.XtraReports.UI.XRTableCell strDiseaseName; private DevExpress.XtraReports.UI.XRTableCell cellICD10; private DevExpress.XtraReports.UI.XRTableCell cellAge_0_1; private DevExpress.XtraReports.UI.XRTableCell cellAge_1_4; private DevExpress.XtraReports.UI.XRTableCell cellAge_5_14; private DevExpress.XtraReports.UI.XRTableCell cellAge_15_19; private DevExpress.XtraReports.UI.XRTableCell cellAge_20_29; private DevExpress.XtraReports.UI.XRTableCell cellAge_30_59; private DevExpress.XtraReports.UI.XRTableCell cellAge_60_more; private DevExpress.XtraReports.UI.XRTableCell xrTableCell94; private DevExpress.XtraReports.UI.XRTableCell cellTotal; private DevExpress.XtraReports.UI.XRTableCell xrTableCell96; private DevExpress.XtraReports.UI.XRTableCell cellLabTested; private DevExpress.XtraReports.UI.XRTableCell cellLabConfirmed; private DevExpress.XtraReports.UI.XRTableCell cellTotalConfirmed; private InfectiousDiseaseMonthNewDataSet InfectiousDiseaseDataSet; private InfectiousDiseaseMonthNewHeaderDataSet InfectiousDiseaseHeaderDataSet; private DevExpress.XtraReports.UI.XRTableRow xrTableRow23; private DevExpress.XtraReports.UI.XRTableCell xrTableCell70; private DevExpress.XtraReports.UI.XRTableRow xrTableRow21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell27; private DevExpress.XtraReports.UI.XRTableCell ChiefFooterCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableRow xrTableRow25; private DevExpress.XtraReports.UI.XRTableCell xrTableCell79; private spRepHumMonthlyInfectiousDiseaseNewTableAdapter SpRepHumMonthlyInfectiousDiseaseNewTableAdapter; private spRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter SpRepHumMonthlyInfectiousDiseaseNewHeaderTableAdapter; private DevExpress.XtraReports.UI.XRLabel cellLocation; private DevExpress.XtraReports.UI.XRTableCell xrTableCell84; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell29; private DevExpress.XtraReports.UI.XRTableRow EnTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell38; private DevExpress.XtraReports.UI.XRTableCell xrTableCell75; private DevExpress.XtraReports.UI.XRTableCell xrTableCell80; private DevExpress.XtraReports.UI.XRTableCell xrTableCell81; private DevExpress.XtraReports.UI.XRTableCell xrTableCell82; private DevExpress.XtraReports.UI.XRTableCell xrTableCell83; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell85; private DevExpress.XtraReports.UI.XRTableCell xrTableCell86; private DevExpress.XtraReports.UI.XRTableCell xrTableCell87; private DevExpress.XtraReports.UI.XRTableRow EnTableRow2; private DevExpress.XtraReports.UI.XRTableRow GgTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell88; private DevExpress.XtraReports.UI.XRTableRow GgTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell89; private DevExpress.XtraReports.UI.XRTableCell xrTableCell92; private DevExpress.XtraReports.UI.XRTableCell xrTableCell93; private DevExpress.XtraReports.UI.XRTableCell xrTableCell95; private DevExpress.XtraReports.UI.XRTableCell xrTableCell97; private DevExpress.XtraReports.UI.XRTableCell xrTableCell90; private DevExpress.XtraReports.UI.XRTableCell xrTableCell91; private DevExpress.XtraReports.UI.XRTableCell xrTableCell71; private DevExpress.XtraReports.UI.XRTableCell xrTableCell72; private DevExpress.XtraReports.UI.XRTableCell xrTableCell73; private DevExpress.XtraReports.UI.XRTableCell MonthFooterCell; private DevExpress.XtraReports.UI.XRTableCell YearFooterCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell32; private DevExpress.XtraReports.UI.XRTableCell xrTableCell34; private DevExpress.XtraReports.UI.XRTableCell xrTableCell35; private DevExpress.XtraReports.UI.XRTableCell DayFooterCell; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell33; private DevExpress.XtraReports.UI.FormattingRule formattingRule1; private DevExpress.XtraReports.UI.XRPageBreak PageBreakAtLine36; private DevExpress.XtraReports.UI.FormattingRule formattingRule2; private DevExpress.XtraReports.UI.FormattingRule formattingRule3; } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.Data; using System.Collections; namespace fyiReporting.Data { /// <summary> /// FileDirCommand allows specifying the command for the web log. /// </summary> public class FileDirCommand : IDbCommand { FileDirConnection _fdc; // connection we're running under string _cmd; // command to execute // parsed constituents of the command string _Directory; // Directory string _FilePattern; // SearchPattern when doing the file lookup string _DirectoryPattern; // SearchPattern when doing the directory lookup string _TrimEmpty="yes"; // Directory with no files will be omitted from result set DataParameterCollection _Parameters = new DataParameterCollection(); public FileDirCommand(FileDirConnection conn) { _fdc = conn; } internal string Directory { get { // Check to see if "Directory" or "@Directory" is a parameter IDbDataParameter dp= _Parameters["Directory"] as IDbDataParameter; if (dp == null) dp= _Parameters["@Directory"] as IDbDataParameter; // Then check to see if the Directory value is a parameter? if (dp == null) dp = _Parameters[_Directory] as IDbDataParameter; if (dp != null) return dp.Value != null? dp.Value.ToString(): _Directory; // don't pass null; pass existing value return _Directory == null? _fdc.Directory: _Directory; } set {_Directory = value;} } internal string FilePattern { get { // Check to see if "FilePattern" or "@FilePattern" is a parameter IDbDataParameter dp= _Parameters["FilePattern"] as IDbDataParameter; if (dp == null) dp= _Parameters["@FilePattern"] as IDbDataParameter; // Then check to see if the FilePattern value is a parameter? if (dp == null) dp = _Parameters[_FilePattern] as IDbDataParameter; if (dp != null) return dp.Value as string; return _FilePattern; } set {_FilePattern = value;} } internal string DirectoryPattern { get { // Check to see if "DirectoryPattern" or "@DirectoryPattern" is a parameter IDbDataParameter dp= _Parameters["DirectoryPattern"] as IDbDataParameter; if (dp == null) dp= _Parameters["@DirectoryPattern"] as IDbDataParameter; // Then check to see if the DirectoryPattern value is a parameter? if (dp == null) dp = _Parameters[_DirectoryPattern] as IDbDataParameter; if (dp != null) return dp.Value as string; return _DirectoryPattern; } set {_DirectoryPattern = value;} } internal bool TrimEmpty { get { // Check to see if "TrimEmpty" or "@TrimEmpty" is a parameter IDbDataParameter dp= _Parameters["TrimEmpty"] as IDbDataParameter; if (dp == null) dp= _Parameters["@TrimEmpty"] as IDbDataParameter; // Then check to see if the TrimEmpty value is a parameter? if (dp == null) dp = _Parameters[_TrimEmpty] as IDbDataParameter; if (dp != null) { string tf = dp.Value as string; if (tf == null) return false; tf = tf.ToLower(); return (tf == "true" || tf == "yes"); } return _TrimEmpty=="yes"? true: false; // the value must be a constant } set {_TrimEmpty = value? "yes": "no";} } #region IDbCommand Members public void Cancel() { throw new NotImplementedException("Cancel not implemented"); } public void Prepare() { return; // Prepare is a noop } public System.Data.CommandType CommandType { get { throw new NotImplementedException("CommandType not implemented"); } set { throw new NotImplementedException("CommandType not implemented"); } } public IDataReader ExecuteReader(System.Data.CommandBehavior behavior) { if (!(behavior == CommandBehavior.SingleResult || behavior == CommandBehavior.SchemaOnly)) throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only."); return new FileDirDataReader(behavior, _fdc, this); } IDataReader System.Data.IDbCommand.ExecuteReader() { return ExecuteReader(System.Data.CommandBehavior.SingleResult); } public object ExecuteScalar() { throw new NotImplementedException("ExecuteScalar not implemented"); } public int ExecuteNonQuery() { throw new NotImplementedException("ExecuteNonQuery not implemented"); } public int CommandTimeout { get { return 0; } set { throw new NotImplementedException("CommandTimeout not implemented"); } } public IDbDataParameter CreateParameter() { return new FileDirDataParameter(); } public IDbConnection Connection { get { return this._fdc; } set { throw new NotImplementedException("Setting Connection not implemented"); } } public System.Data.UpdateRowSource UpdatedRowSource { get { throw new NotImplementedException("UpdatedRowSource not implemented"); } set { throw new NotImplementedException("UpdatedRowSource not implemented"); } } public string CommandText { get { return this._cmd; } set { // Parse the command string for keyword value pairs separated by ';' _FilePattern = null; _DirectoryPattern = null; _Directory = null; string[] args = value.Split(';'); foreach(string arg in args) { string[] param = arg.Trim().Split('='); if (param == null || param.Length != 2) continue; string key = param[0].Trim().ToLower(); string val = param[1]; switch (key) { case "directory": _Directory = val; break; case "filepattern": _FilePattern = val; break; case "directorypattern": _DirectoryPattern = val; break; default: throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0])); } } // User must specify both the url and the RowsXPath if (_Directory == null && this._fdc.Directory == null) { if (_Directory == null) throw new ArgumentException("CommandText requires a 'Directory=' parameter."); } _cmd = value; } } public IDataParameterCollection Parameters { get { return _Parameters; } } public IDbTransaction Transaction { get { throw new NotImplementedException("Transaction not implemented"); } set { throw new NotImplementedException("Transaction not implemented"); } } #endregion #region IDisposable Members public void Dispose() { // nothing to dispose of } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (c) 2004 Mainsoft Co. // // 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 Xunit; using System.Collections; using System.ComponentModel; namespace System.Data.Tests { public class DataTableCollectionTest2 { private int _counter = 0; [Fact] public void Add() { // Adding computed column to a data set var ds = new DataSet(); ds.Tables.Add(new DataTable("Table")); ds.Tables[0].Columns.Add(new DataColumn("EmployeeNo", typeof(string))); ds.Tables[0].Rows.Add(new object[] { "Maciek" }); ds.Tables[0].Columns.Add("ComputedColumn", typeof(object), "EmployeeNo"); Assert.Equal("EmployeeNo", ds.Tables[0].Columns["ComputedColumn"].Expression); } [Fact] public void AddTwoTables() { var ds = new DataSet(); ds.Tables.Add(); Assert.Equal("Table1", ds.Tables[0].TableName); //Assert.Equal(ds.Tables[0].TableName,"Table1"); ds.Tables.Add(); Assert.Equal("Table2", ds.Tables[1].TableName); //Assert.Equal(ds.Tables[1].TableName,"Table2"); } [Fact] public void AddRange() { var ds = new DataSet(); DataTable[] arr = new DataTable[2]; arr[0] = new DataTable("NewTable1"); arr[1] = new DataTable("NewTable2"); ds.Tables.AddRange(arr); Assert.Equal("NewTable1", ds.Tables[0].TableName); Assert.Equal("NewTable2", ds.Tables[1].TableName); } [Fact] public void AddRange_NullValue() { var ds = new DataSet(); ds.Tables.AddRange(null); } [Fact] public void AddRange_ArrayWithNull() { var ds = new DataSet(); DataTable[] arr = new DataTable[2]; arr[0] = new DataTable("NewTable1"); arr[1] = null; ds.Tables.AddRange(arr); Assert.Equal("NewTable1", ds.Tables[0].TableName); Assert.Equal(1, ds.Tables.Count); } [Fact] public void CanRemove() { var ds = new DataSet(); ds.Tables.Add(); Assert.Equal(true, ds.Tables.CanRemove(ds.Tables[0])); } [Fact] public void CanRemove_NullValue() { var ds = new DataSet(); Assert.Equal(false, ds.Tables.CanRemove(null)); } [Fact] public void CanRemove_TableDoesntBelong() { var ds = new DataSet(); DataSet ds1 = new DataSet(); ds1.Tables.Add(); Assert.Equal(false, ds.Tables.CanRemove(ds1.Tables[0])); } [Fact] public void CanRemove_PartOfRelation() { var ds = new DataSet(); ds.Tables.Add(DataProvider.CreateParentDataTable()); ds.Tables.Add(DataProvider.CreateChildDataTable()); ds.Relations.Add("rel", ds.Tables[0].Columns["ParentId"], ds.Tables[1].Columns["ParentId"], false); Assert.Equal(false, ds.Tables.CanRemove(ds.Tables[0])); Assert.Equal(false, ds.Tables.CanRemove(ds.Tables[1])); } [Fact] public void CanRemove_PartOfConstraint() { DataSet ds = DataProvider.CreateForigenConstraint(); Assert.Equal(false, ds.Tables.CanRemove(ds.Tables[0])); Assert.Equal(false, ds.Tables.CanRemove(ds.Tables[1])); } [Fact] public void CollectionChanged() { _counter = 0; var ds = new DataSet(); ds.Tables.CollectionChanged += new CollectionChangeEventHandler(Tables_CollectionChanged); ds.Tables.Add(); ds.Tables.Add(); Assert.Equal(2, _counter); ds.Tables.Remove(ds.Tables[0]); ds.Tables.Remove(ds.Tables[0]); Assert.Equal(4, _counter); } private void Tables_CollectionChanged(object sender, CollectionChangeEventArgs e) { _counter++; } [Fact] public void CollectionChanging() { _counter = 0; var ds = new DataSet(); ds.Tables.CollectionChanging += new CollectionChangeEventHandler(Tables_CollectionChanging); ds.Tables.Add(); ds.Tables.Add(); Assert.Equal(2, _counter); ds.Tables.Remove(ds.Tables[0]); ds.Tables.Remove(ds.Tables[0]); Assert.Equal(4, _counter); } private void Tables_CollectionChanging(object sender, CollectionChangeEventArgs e) { _counter++; } [Fact] public void Contains() { var ds = new DataSet(); ds.Tables.Add("NewTable1"); ds.Tables.Add("NewTable2"); Assert.Equal(true, ds.Tables.Contains("NewTable1")); Assert.Equal(true, ds.Tables.Contains("NewTable2")); Assert.Equal(false, ds.Tables.Contains("NewTable3")); ds.Tables["NewTable1"].TableName = "Tbl1"; Assert.Equal(false, ds.Tables.Contains("NewTable1")); Assert.Equal(true, ds.Tables.Contains("Tbl1")); } [Fact] public void CopyTo() { var ds = new DataSet(); ds.Tables.Add(); ds.Tables.Add(); DataTable[] arr = new DataTable[2]; ds.Tables.CopyTo(arr, 0); Assert.Equal("Table1", arr[0].TableName); Assert.Equal("Table2", arr[1].TableName); } [Fact] public void Count() { var ds = new DataSet(); Assert.Equal(0, ds.Tables.Count); ds.Tables.Add(); Assert.Equal(1, ds.Tables.Count); ds.Tables.Add(); Assert.Equal(2, ds.Tables.Count); ds.Tables.Remove("Table1"); Assert.Equal(1, ds.Tables.Count); ds.Tables.Remove("Table2"); Assert.Equal(0, ds.Tables.Count); } [Fact] public void GetEnumerator() { var ds = new DataSet(); ds.Tables.Add(); ds.Tables.Add(); int count = 0; IEnumerator myEnumerator = ds.Tables.GetEnumerator(); while (myEnumerator.MoveNext()) { Assert.Equal("Table", ((DataTable)myEnumerator.Current).TableName.Substring(0, 5)); count++; } Assert.Equal(2, count); } public void IndexOf_ByDataTable() { var ds = new DataSet(); DataTable dt = new DataTable("NewTable1"); DataTable dt1 = new DataTable("NewTable2"); ds.Tables.AddRange(new DataTable[] { dt, dt1 }); Assert.Equal(0, ds.Tables.IndexOf(dt)); Assert.Equal(1, ds.Tables.IndexOf(dt1)); ds.Tables.IndexOf((DataTable)null); DataTable dt2 = new DataTable("NewTable2"); Assert.Equal(-1, ds.Tables.IndexOf(dt2)); } public void IndexOf_ByName() { var ds = new DataSet(); DataTable dt = new DataTable("NewTable1"); DataTable dt1 = new DataTable("NewTable2"); ds.Tables.AddRange(new DataTable[] { dt, dt1 }); Assert.Equal(0, ds.Tables.IndexOf("NewTable1")); Assert.Equal(1, ds.Tables.IndexOf("NewTable2")); ds.Tables.IndexOf((string)null); Assert.Equal(-1, ds.Tables.IndexOf("NewTable3")); } [Fact] public void Item() { var ds = new DataSet(); DataTable dt = new DataTable("NewTable1"); DataTable dt1 = new DataTable("NewTable2"); ds.Tables.AddRange(new DataTable[] { dt, dt1 }); Assert.Equal(dt, ds.Tables[0]); Assert.Equal(dt1, ds.Tables[1]); Assert.Equal(dt, ds.Tables["NewTable1"]); Assert.Equal(dt1, ds.Tables["NewTable2"]); } [Fact] public void DataTableCollection_Add_D1() { var ds = new DataSet(); DataTable dt = new DataTable("NewTable1"); ds.Tables.Add(dt); Assert.Equal("NewTable1", ds.Tables[0].TableName); } [Fact] public void DataTableCollection_Add_D2() { var ds = new DataSet(); Assert.Throws<ArgumentNullException>(() => { ds.Tables.Add((DataTable)null); }); } [Fact] public void DataTableCollection_Add_D3() { var ds = new DataSet(); DataSet ds1 = new DataSet(); ds1.Tables.Add(); Assert.Throws<ArgumentException>(() => ds.Tables.Add(ds1.Tables[0])); } [Fact] public void DataTableCollection_Add_D4() { var ds = new DataSet(); ds.Tables.Add(); DataTable dt = new DataTable("Table1"); Assert.Throws<DuplicateNameException>(() => ds.Tables.Add(dt)); } [Fact] public void DataTableCollection_Add_S1() { var ds = new DataSet(); ds.Tables.Add("NewTable1"); Assert.Equal("NewTable1", ds.Tables[0].TableName); ds.Tables.Add("NewTable2"); Assert.Equal("NewTable2", ds.Tables[1].TableName); } [Fact] public void DataTableCollection_Add_S2() { var ds = new DataSet(); ds.Tables.Add("NewTable1"); Assert.Throws<DuplicateNameException>(() => ds.Tables.Add("NewTable1")); } [Fact] public void DataTableCollection_Clear1() { var ds = new DataSet(); ds.Tables.Add(); ds.Tables.Add(); ds.Tables.Clear(); Assert.Equal(0, ds.Tables.Count); } [Fact] public void DataTableCollection_Clear2() { var ds = new DataSet(); ds.Tables.Add(); ds.Tables.Add(); ds.Tables.Clear(); Assert.Throws<IndexOutOfRangeException>(() => ds.Tables[0].TableName = "Error"); } [Fact] public void DataTableCollection_Remove_D1() { var ds = new DataSet(); DataTable dt = new DataTable("NewTable1"); DataTable dt1 = new DataTable("NewTable2"); ds.Tables.AddRange(new DataTable[] { dt, dt1 }); ds.Tables.Remove(dt); Assert.Equal(1, ds.Tables.Count); Assert.Equal(dt1, ds.Tables[0]); ds.Tables.Remove(dt1); Assert.Equal(0, ds.Tables.Count); } [Fact] public void DataTableCollection_Remove_D2() { var ds = new DataSet(); DataTable dt = new DataTable("NewTable1"); Assert.Throws<ArgumentException>(() => ds.Tables.Remove(dt)); } [Fact] public void DataTableCollection_Remove_D3() { var ds = new DataSet(); Assert.Throws<ArgumentNullException>(() => ds.Tables.Remove((DataTable)null)); } [Fact] public void DataTableCollection_Remove_S1() { var ds = new DataSet(); DataTable dt = new DataTable("NewTable1"); DataTable dt1 = new DataTable("NewTable2"); ds.Tables.AddRange(new DataTable[] { dt, dt1 }); ds.Tables.Remove("NewTable1"); Assert.Equal(1, ds.Tables.Count); Assert.Equal(dt1, ds.Tables[0]); ds.Tables.Remove("NewTable2"); Assert.Equal(0, ds.Tables.Count); } [Fact] public void DataTableCollection_Remove_S2() { var ds = new DataSet(); Assert.Throws<ArgumentException>(() => ds.Tables.Remove("NewTable2")); } [Fact] public void DataTableCollection_Remove_S3() { var ds = new DataSet(); Assert.Throws<ArgumentException>(() => ds.Tables.Remove((string)null)); } [Fact] public void DataTableCollection_RemoveAt_I1() { var ds = new DataSet(); DataTable dt = new DataTable("NewTable1"); DataTable dt1 = new DataTable("NewTable2"); ds.Tables.AddRange(new DataTable[] { dt, dt1 }); ds.Tables.RemoveAt(1); Assert.Equal(dt, ds.Tables[0]); ds.Tables.RemoveAt(0); Assert.Equal(0, ds.Tables.Count); } [Fact] public void DataTableCollection_RemoveAt_I2() { var ds = new DataSet(); Assert.Throws<IndexOutOfRangeException>(() => ds.Tables.RemoveAt(-1)); } [Fact] public void DataTableCollection_RemoveAt_I3() { DataSet ds = DataProvider.CreateForigenConstraint(); Assert.Throws<ArgumentException>(() => ds.Tables.RemoveAt(0)); //Parent table } [Fact] public void AddTable_DiffNamespaceTest() { var ds = new DataSet(); ds.Tables.Add("table", "namespace1"); ds.Tables.Add("table", "namespace2"); Assert.Equal(2, ds.Tables.Count); try { ds.Tables.Add("table", "namespace1"); Assert.False(true); } catch (DuplicateNameException e) { } ds.Tables.Add("table"); try { ds.Tables.Add("table", null); Assert.False(true); } catch (DuplicateNameException e) { } } [Fact] public void Contains_DiffNamespaceTest() { var ds = new DataSet(); ds.Tables.Add("table"); Assert.True(ds.Tables.Contains("table")); ds.Tables.Add("table", "namespace1"); ds.Tables.Add("table", "namespace2"); // Should fail if it cannot be resolved to a single table Assert.False(ds.Tables.Contains("table")); try { ds.Tables.Contains("table", null); Assert.False(true); } catch (ArgumentNullException e) { } Assert.True(ds.Tables.Contains("table", "namespace1")); Assert.False(ds.Tables.Contains("table", "namespace3")); } [Fact] public void IndexOf_DiffNamespaceTest() { var ds = new DataSet(); ds.Tables.Add("table"); Assert.Equal(0, ds.Tables.IndexOf("table")); ds.Tables.Add("table", "namespace1"); ds.Tables.Add("table", "namespace2"); Assert.Equal(-1, ds.Tables.IndexOf("table")); Assert.Equal(2, ds.Tables.IndexOf("table", "namespace2")); Assert.Equal(1, ds.Tables.IndexOf("table", "namespace1")); } [Fact] public void Remove_DiffNamespaceTest() { var ds = new DataSet(); ds.Tables.Add("table"); ds.Tables.Add("table", "namespace1"); ds.Tables.Add("table", "namespace2"); try { ds.Tables.Remove("table"); Assert.False(true); } catch (ArgumentException e) { } ds.Tables.Remove("table", "namespace2"); Assert.Equal(2, ds.Tables.Count); Assert.Equal("namespace1", ds.Tables[1].Namespace); try { ds.Tables.Remove("table", "namespace2"); Assert.False(true); } catch (ArgumentException e) { } } } }
using System; namespace InsurgenceData { public static class MoveHelper { public static string GetMoveName(string id) { var i = int.Parse(id); if (Enum.IsDefined(typeof(MovesList), i)) { return ((MovesList) i).ToString(); } return i.ToString(); } public static string GetMoveName(int id) { return ((MovesList) id).ToString(); } public enum MovesList { Megahorn = 1, AttackOrder = 2, BugBuzz = 3, XScissor = 4, SignalBeam = 5, Uturn = 6, Steamroller = 7, BugBite = 8, SilverWind = 9, StruggleBug = 10, Twineedle = 11, FuryCutter = 12, LeechLife = 13, PinMissile = 14, DefendOrder = 15, HealOrder = 16, QuiverDance = 17, RagePowder = 18, SpiderWeb = 19, StringShot = 20, TailGlow = 21, FoulPlay = 22, NightDaze = 23, Crunch = 24, DarkPulse = 25, SuckerPunch = 26, NightSlash = 27, Bite = 28, FeintAttack = 29, Snarl = 30, Assurance = 31, Payback = 32, Pursuit = 33, Thief = 34, KnockOff = 35, BeatUp = 36, Fling = 37, Punishment = 38, DarkVoid = 39, Embargo = 40, FakeTears = 41, Flatter = 42, HoneClaws = 43, Memento = 44, NastyPlot = 45, Quash = 46, Snatch = 47, Switcheroo = 48, Taunt = 49, Torment = 50, RoarofTime = 51, DracoMeteor = 52, Outrage = 53, DragonRush = 54, SpacialRend = 55, DragonPulse = 56, DragonClaw = 57, DragonTail = 58, DragonBreath = 59, DualChop = 60, Twister = 61, DragonRage = 62, DragonDance = 63, BoltStrike = 64, Thunder = 65, VoltTackle = 66, ZapCannon = 67, FusionBolt = 68, Thunderbolt = 69, WildCharge = 70, Discharge = 71, ThunderPunch = 72, VoltSwitch = 73, Spark = 74, ThunderFang = 75, ShockWave = 76, Electroweb = 77, ChargeBeam = 78, ThunderShock = 79, ElectroBall = 80, Charge = 81, MagnetRise = 82, ThunderWave = 83, FocusPunch = 84, HighJumpKick = 85, CloseCombat = 86, FocusBlast = 87, Superpower = 88, CrossChop = 89, DynamicPunch = 90, HammerArm = 91, JumpKick = 92, AuraSphere = 93, SacredSword = 94, SecretSword = 95, SkyUppercut = 96, Submission = 97, BrickBreak = 98, DrainPunch = 99, VitalThrow = 100, CircleThrow = 101, ForcePalm = 102, LowSweep = 103, Revenge = 104, RollingKick = 105, WakeUpSlap = 106, KarateChop = 107, MachPunch = 108, RockSmash = 109, StormThrow = 110, VacuumWave = 111, DoubleKick = 112, ArmThrust = 113, TripleKick = 114, Counter = 115, FinalGambit = 116, LowKick = 117, Reversal = 118, SeismicToss = 119, BulkUp = 120, Detect = 121, QuickGuard = 122, Vcreate = 123, BlastBurn = 124, Eruption = 125, Overheat = 126, BlueFlare = 127, FireBlast = 128, FlareBlitz = 129, MagmaStorm = 130, FusionFlare = 131, HeatWave = 132, Inferno = 133, SacredFire = 134, SearingShot = 135, Flamethrower = 136, BlazeKick = 137, FieryDance = 138, LavaPlume = 139, FirePunch = 140, FlameBurst = 141, FireFang = 142, FlameWheel = 143, FirePledge = 144, FlameCharge = 145, Ember = 146, FireSpin = 147, Incinerate = 148, HeatCrash = 149, SunnyDay = 150, WillOWisp = 151, SkyAttack = 152, BraveBird = 153, Hurricane = 154, Aeroblast = 155, Fly = 156, Bounce = 157, DrillPeck = 158, AirSlash = 159, AerialAce = 160, Chatter = 161, Pluck = 162, SkyDrop = 163, WingAttack = 164, Acrobatics = 165, AirCutter = 166, Gust = 167, Peck = 168, Defog = 169, FeatherDance = 170, MirrorMove = 171, Roost = 172, Tailwind = 173, ShadowForce = 174, ShadowBall = 175, ShadowClaw = 176, OminousWind = 177, ShadowPunch = 178, Hex = 179, ShadowSneak = 180, Astonish = 181, Lick = 182, NightShade = 183, ConfuseRay = 184, Curse = 185, DestinyBond = 186, Grudge = 187, Nightmare = 188, Spite = 189, FrenzyPlant = 190, LeafStorm = 191, PetalDance = 192, PowerWhip = 193, SeedFlare = 194, SolarBeam = 195, WoodHammer = 196, LeafBlade = 197, EnergyBall = 198, SeedBomb = 199, GigaDrain = 200, HornLeech = 201, LeafTornado = 202, MagicalLeaf = 203, NeedleArm = 204, RazorLeaf = 205, GrassPledge = 206, MegaDrain = 207, VineWhip = 208, BulletSeed = 209, Absorb = 210, GrassKnot = 211, Aromatherapy = 212, CottonGuard = 213, CottonSpore = 214, GrassWhistle = 215, Ingrain = 216, LeechSeed = 217, SleepPowder = 218, Spore = 219, StunSpore = 220, Synthesis = 221, WorrySeed = 222, Earthquake = 223, EarthPower = 224, Dig = 225, DrillRun = 226, BoneClub = 227, MudBomb = 228, Bulldoze = 229, MudShot = 230, Bonemerang = 231, SandTomb = 232, BoneRush = 233, MudSlap = 234, Fissure = 235, Magnitude = 236, MudSport = 237, SandAttack = 238, Spikes = 239, FreezeShock = 240, IceBurn = 241, Blizzard = 242, IceBeam = 243, IcicleCrash = 244, IcePunch = 245, AuroraBeam = 246, Glaciate = 247, IceFang = 248, Avalanche = 249, IcyWind = 250, FrostBreath = 251, IceShard = 252, PowderSnow = 253, IceBall = 254, IcicleSpear = 255, SheerCold = 256, Hail = 257, Haze = 258, Mist = 259, Explosion = 260, SelfDestruct = 261, GigaImpact = 262, HyperBeam = 263, LastResort = 264, DoubleEdge = 265, HeadCharge = 266, MegaKick = 267, Thrash = 268, EggBomb = 269, Judgment = 270, SkullBash = 271, HyperVoice = 272, RockClimb = 273, TakeDown = 274, Uproar = 275, BodySlam = 276, TechnoBlast = 277, ExtremeSpeed = 278, HyperFang = 279, MegaPunch = 280, RazorWind = 281, Slam = 282, Strength = 283, TriAttack = 284, CrushClaw = 285, RelicSong = 286, ChipAway = 287, DizzyPunch = 288, Facade = 289, Headbutt = 290, Retaliate = 291, SecretPower = 292, Slash = 293, HornAttack = 294, Stomp = 295, Covet = 296, Round = 297, SmellingSalts = 298, Swift = 299, ViceGrip = 300, Cut = 301, Struggle = 302, Tackle = 303, WeatherBall = 304, EchoedVoice = 305, FakeOut = 306, FalseSwipe = 307, PayDay = 308, Pound = 309, QuickAttack = 310, Scratch = 311, Snore = 312, DoubleHit = 313, Feint = 314, TailSlap = 315, Rage = 316, RapidSpin = 317, SpikeCannon = 318, CometPunch = 319, FurySwipes = 320, Barrage = 321, Bind = 322, DoubleSlap = 323, FuryAttack = 324, Wrap = 325, Constrict = 326, Bide = 327, CrushGrip = 328, Endeavor = 329, Flail = 330, Frustration = 331, Guillotine = 332, HiddenPower = 333, HornDrill = 334, NaturalGift = 335, Present = 336, Return = 337, SonicBoom = 338, SpitUp = 339, SuperFang = 340, TrumpCard = 341, WringOut = 342, Acupressure = 343, AfterYou = 344, Assist = 345, Attract = 346, BatonPass = 347, BellyDrum = 348, Bestow = 349, Block = 350, Camouflage = 351, Captivate = 352, Charm = 353, Conversion = 354, Conversion2 = 355, Copycat = 356, DefenseCurl = 357, Disable = 358, DoubleTeam = 359, Encore = 360, Endure = 361, Entrainment = 362, Flash = 363, FocusEnergy = 364, FollowMe = 365, Foresight = 366, Glare = 367, Growl = 368, Growth = 369, Harden = 370, HealBell = 371, HelpingHand = 372, Howl = 373, Leer = 374, LockOn = 375, LovelyKiss = 376, LuckyChant = 377, MeFirst = 378, MeanLook = 379, Metronome = 380, MilkDrink = 381, Mimic = 382, MindReader = 383, Minimize = 384, Moonlight = 385, MorningSun = 386, NaturePower = 387, OdorSleuth = 388, PainSplit = 389, PerishSong = 390, Protect = 391, PsychUp = 392, Recover = 393, Recycle = 394, ReflectType = 395, Refresh = 396, Roar = 397, Safeguard = 398, ScaryFace = 399, Screech = 400, Sharpen = 401, ShellSmash = 402, SimpleBeam = 403, Sing = 404, Sketch = 405, SlackOff = 406, SleepTalk = 407, Smokescreen = 408, SoftBoiled = 409, Splash = 410, Stockpile = 411, Substitute = 412, Supersonic = 413, Swagger = 414, Swallow = 415, SweetKiss = 416, SweetScent = 417, SwordsDance = 418, TailWhip = 419, TeeterDance = 420, Tickle = 421, Transform = 422, Whirlwind = 423, Wish = 424, WorkUp = 425, Yawn = 426, GunkShot = 427, SludgeWave = 428, SludgeBomb = 429, PoisonJab = 430, CrossPoison = 431, Sludge = 432, Venoshock = 433, ClearSmog = 434, PoisonFang = 435, PoisonTail = 436, Acid = 437, AcidSpray = 438, Smog = 439, PoisonSting = 440, AcidArmor = 441, Coil = 442, GastroAcid = 443, PoisonGas = 444, PoisonPowder = 445, Toxic = 446, ToxicSpikes = 447, PsychoBoost = 448, DreamEater = 449, FutureSight = 450, Psystrike = 451, Psychic = 452, Extrasensory = 453, Psyshock = 454, ZenHeadbutt = 455, LusterPurge = 456, MistBall = 457, PsychoCut = 458, Synchronoise = 459, Psybeam = 460, HeartStamp = 461, Confusion = 462, MirrorCoat = 463, Psywave = 464, StoredPower = 465, Agility = 466, AllySwitch = 467, Amnesia = 468, Barrier = 469, CalmMind = 470, CosmicPower = 471, Gravity = 472, GuardSplit = 473, GuardSwap = 474, HealBlock = 475, HealPulse = 476, HealingWish = 477, HeartSwap = 478, Hypnosis = 479, Imprison = 480, Kinesis = 481, LightScreen = 482, LunarDance = 483, MagicCoat = 484, MagicRoom = 485, Meditate = 486, MiracleEye = 487, PowerSplit = 488, PowerSwap = 489, PowerTrick = 490, PsychoShift = 491, Reflect = 492, Rest = 493, RolePlay = 494, SkillSwap = 495, Telekinesis = 496, Teleport = 497, Trick = 498, TrickRoom = 499, WonderRoom = 500, HeadSmash = 501, RockWrecker = 502, StoneEdge = 503, RockSlide = 504, PowerGem = 505, AncientPower = 506, RockThrow = 507, RockTomb = 508, SmackDown = 509, Rollout = 510, RockBlast = 511, RockPolish = 512, Sandstorm = 513, StealthRock = 514, WideGuard = 515, DoomDesire = 516, IronTail = 517, MeteorMash = 518, FlashCannon = 519, IronHead = 520, SteelWing = 521, MirrorShot = 522, MagnetBomb = 523, GearGrind = 524, MetalClaw = 525, BulletPunch = 526, GyroBall = 527, HeavySlam = 528, MetalBurst = 529, Autotomize = 530, IronDefense = 531, MetalSound = 532, ShiftGear = 533, HydroCannon = 534, WaterSpout = 535, HydroPump = 536, MuddyWater = 537, Surf = 538, AquaTail = 539, Crabhammer = 540, Dive = 541, Scald = 542, Waterfall = 543, RazorShell = 544, Brine = 545, BubbleBeam = 546, Octazooka = 547, WaterPulse = 548, WaterPledge = 549, AquaJet = 550, WaterGun = 551, Clamp = 552, Whirlpool = 553, Bubble = 554, AquaRing = 555, RainDance = 556, Soak = 557, WaterSport = 558, Withdraw = 559, OblivionWing = 560, Geomancy = 561, ZombieStrike = 578, CustomMove = 579, Livewire = 580, LunarCannon = 582, DracoJet = 583, Permafrost = 604, MedusaRay = 605, DarkMatter = 606, Dragonify = 612, Wildfire = 614, Moonblast = 627, Boomburst = 634, KingsShield = 635, CrystalRush = 638, Wormhole = 640, PlayRough = 641, DrainingKiss = 642, WaterShuriken = 643, SpikyShield = 644, MysticalFire = 645, FreezeDry = 646, FlyingPress = 647, DiamondStorm = 648, SteamEruption = 649, HyperspaceHole = 650, ParabolicCharge = 652, HiddenPower2 = 653, DazzlingGleam = 654, HiddenPower3 = 655, HiddenPower4 = 656, HiddenPower5 = 657, HiddenPower6 = 658, HiddenPower7 = 659, HiddenPower8 = 660, HiddenPower9 = 661, HiddenPower10 = 662, HiddenPower11 = 663, HiddenPower12 = 664, HiddenPower13 = 665, HiddenPower14 = 666, HiddenPower15 = 667, HiddenPower16 = 668, HiddenPower17 = 668, HiddenPower18 = 669, HiddenPower19 = 670, HiddenPower20 = 671, Powder = 676, NobleRoar = 677, FairyWind = 678, GrassyTerrain = 679, MistyTerrain = 680, ElectricTerrain = 681, PetalBlizzard = 682, DisarmingVoice = 683, FlowerShield = 684, BabyDollEyes = 685, AromaticMist = 686, PlayNice = 687, Nuzzle = 688, EerieImpulse = 689, ForestsCurse = 690, TrickorTreat = 691, PhantomForce = 692, VenomDrench = 693, Rototiller = 694, FellStinger = 695, Belch = 696, Confide = 697, FairyLock = 698, Infestation = 699, LandsWrath = 700, MatBlock = 701, ThousandArrows = 702, ThousandWaves = 703, StickyWeb = 704, TopsyTurvy = 705, PowerUpPunch = 706, NewMoon = 707, JetStream = 708, AchillesHeel = 709, Corrode = 710, DrakonVoice = 711, AncientRoar = 712, DragonAscent = 713, OriginPulse = 714, PrecipiceBlades = 715, CoreEnforcer = 716, PartingShot = 723, Morph = 724, Retrograde = 725, Nanorepair = 726, HyperspaceFury = 727, CraftyShield = 728, SpiritAway = 729, Celebrate = 730, HappyHour = 731, HoldHands = 732, Electrify = 733, HoldBack = 734, LightofRuin = 735, MagneticFlux = 736, IonDeluge = 737, FairyTempest = 738, DynamicFury = 739, AuraBlast = 740, DarkNova = 741, } } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Cassandra.Mapping; using Cassandra.Metrics.Internal; using Cassandra.Tasks; using Cassandra.Tests.Mapping.Pocos; using Cassandra.Tests.Mapping.TestData; using Moq; using NUnit.Framework; namespace Cassandra.Tests.Mapping { public class FetchTests : MappingTestBase { [Test] public void FetchAsync_Pocos_WithCql_Empty() { var rowset = new RowSet(); var mappingClient = GetMappingClient(rowset); var userTask = mappingClient.FetchAsync<PlainUser>("SELECT * FROM users"); var users = userTask.Result; Assert.NotNull(users); Assert.AreEqual(0, users.Count()); } [Test] public void FetchAsync_Pocos_WithCql_Single_Column_Maps() { //just the userid var usersExpected = TestDataHelper.GetUserList().Select(u => new PlainUser { UserId = u.UserId} ).ToList(); var rowset = TestDataHelper.GetUsersRowSet(usersExpected); var mappingClient = GetMappingClient(rowset); var userTask = mappingClient.FetchAsync<PlainUser>("SELECT * FROM users"); var users = userTask.Result; Assert.NotNull(users); CollectionAssert.AreEqual(usersExpected, users, new TestHelper.PropertyComparer()); } [Test] public void FetchAsync_Pocos_Prepares_Just_Once() { const int times = 100; var users = TestDataHelper.GetUserList(); var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Returns(() => TaskHelper.ToTask(TestDataHelper.GetUsersRowSet(users))) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns(TaskHelper.ToTask(GetPrepared())) .Verifiable(); var mappingClient = GetMappingClient(sessionMock); var taskList = new List<Task<IEnumerable<PlainUser>>>(); for (var i = 0; i < times; i++) { var t = mappingClient.FetchAsync<PlainUser>("SELECT * FROM users"); taskList.Add(t); } Task.WaitAll(taskList.Select(t => (Task)t).ToArray(), 5000); Assert.True(taskList.All(t => t.Result.Count() == 10)); sessionMock.Verify(); //Prepare should be called just once sessionMock .Verify(s => s.PrepareAsync(It.IsAny<string>()), Times.Once()); //ExecuteAsync should be called the exact number of times sessionMock .Verify(s => s.ExecuteAsync(It.IsAny<BoundStatement>()), Times.Exactly(times)); sessionMock.Verify(); } [Test] public void Fetch_Throws_ExecuteAsync_Exception() { var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Returns(() => TaskHelper.FromException<RowSet>(new InvalidQueryException("Mocked Exception"))) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns(TaskHelper.ToTask(GetPrepared())) .Verifiable(); var mappingClient = GetMappingClient(sessionMock); var ex = Assert.Throws<InvalidQueryException>(() => mappingClient.Fetch<PlainUser>("SELECT WILL FAIL FOR INVALID")); Assert.AreEqual(ex.Message, "Mocked Exception"); sessionMock.Verify(); } [Test] public void Fetch_Throws_PrepareAsync_Exception() { var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns(() => TaskHelper.FromException<PreparedStatement>(new SyntaxError("Mocked Exception 2"))) .Verifiable(); var mappingClient = GetMappingClient(sessionMock); var ex = Assert.Throws<SyntaxError>(() => mappingClient.Fetch<PlainUser>("SELECT WILL FAIL FOR SYNTAX")); Assert.AreEqual(ex.Message, "Mocked Exception 2"); sessionMock.Verify(); } [Test] public void FetchAsync_Pocos_WithCqlAndOptions() { var usersExpected = TestDataHelper.GetUserList(); var rowset = TestDataHelper.GetUsersRowSet(usersExpected); var mappingClient = GetMappingClient(rowset); var users = mappingClient.FetchAsync<PlainUser>(Cql.New("SELECT * FROM users").WithOptions(opt => opt.SetConsistencyLevel(ConsistencyLevel.Quorum))).Result; CollectionAssert.AreEqual(users, usersExpected, new TestHelper.PropertyComparer()); } [Test] public void Fetch_Fluent_Mapping() { var usersOriginal = TestDataHelper.GetUserList(); var rowset = TestDataHelper.GetUsersRowSet(usersOriginal); var mappingClient = GetMappingClient(rowset); var users = mappingClient.Fetch<FluentUser>("SELECT * FROM users").ToList(); Assert.AreEqual(usersOriginal.Count, users.Count); for (var i = 0; i < users.Count; i++) { var expected = usersOriginal[i]; var user = users[i]; Assert.AreEqual(expected.UserId, user.Id); Assert.AreEqual(expected.Age, user.Age); Assert.AreEqual(expected.ChildrenAges.ToDictionary(t => t.Key, t => t.Value), user.ChildrenAges.ToDictionary(t => t.Key, t => t.Value)); Assert.AreEqual(expected.HairColor, user.HairColor); } } [Test] public void Fetch_Invalid_Type_Conversion_Throws() { var usersOriginal = TestDataHelper.GetUserList(); var rowset = TestDataHelper.GetUsersRowSet(usersOriginal); var mappingClient = GetMappingClient(rowset); var ex = Assert.Throws<InvalidTypeException>(() => mappingClient.Fetch<UserDifferentPropTypes>("SELECT * FROM users")); //Message contains column name StringAssert.Contains("age", ex.Message.ToLower()); //Source type StringAssert.Contains("int", ex.Message.ToLower()); //Target type StringAssert.Contains("Dictionary", ex.Message); } [Test] public void Fetch_Invalid_Constructor_Throws() { var usersOriginal = TestDataHelper.GetUserList(); var rowset = TestDataHelper.GetUsersRowSet(usersOriginal); var mappingClient = GetMappingClient(rowset); var ex = Assert.Throws<ArgumentException>(() => mappingClient.Fetch<SomeClassWithNoDefaultConstructor>("SELECT * FROM users")); StringAssert.Contains("constructor", ex.Message); } private class SomeClassWithNoDefaultConstructor { // ReSharper disable once UnusedParameter.Local public SomeClassWithNoDefaultConstructor(string w) { } } [Test] public void Fetch_Lazily_Pages() { const int pageSize = 10; const int totalPages = 4; var rs = TestDataHelper.CreateMultipleValuesRowSet(new[] {"title", "artist"}, new[] {"Once in a Livetime", "Dream Theater"}, pageSize); rs.PagingState = new byte[] {1}; SetFetchNextMethod(rs, state => { var pageNumber = state[0]; pageNumber++; var nextRs = TestDataHelper.CreateMultipleValuesRowSet(new[] {"title", "artist"}, new[] {"Once in a Livetime " + pageNumber, "Dream Theater"}, pageSize); if (pageNumber < totalPages) { nextRs.PagingState = new[] { pageNumber }; } return nextRs; }); var mappingClient = GetMappingClient(rs); var songs = mappingClient.Fetch<Song>("SELECT * FROM songs"); //Page to all the values var allSongs = songs.ToList(); Assert.AreEqual(pageSize * totalPages, allSongs.Count); } [Test] public void FetchPageAsync_Pocos_Uses_Defaults() { var rs = TestDataHelper.GetUsersRowSet(TestDataHelper.GetUserList()); rs.AutoPage = false; rs.PagingState = new byte[] { 1, 2, 3 }; BoundStatement stmt = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Callback<IStatement>(s => stmt = (BoundStatement)s) .Returns(() => TestHelper.DelayedTask(rs)) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns(TaskHelper.ToTask(GetPrepared())) .Verifiable(); var mappingClient = GetMappingClient(sessionMock); IPage<PlainUser> page = mappingClient.FetchPageAsync<PlainUser>(Cql.New("SELECT * FROM users")).Result; Assert.Null(page.CurrentPagingState); Assert.NotNull(page.PagingState); Assert.AreEqual(rs.PagingState, page.PagingState); sessionMock.Verify(); Assert.False(stmt.AutoPage); Assert.AreEqual(0, stmt.PageSize); } [Test] public void FetchPageAsync_Pocos_WithCqlAndOptions() { const int pageSize = 10; var usersExpected = TestDataHelper.GetUserList(pageSize); var rs = TestDataHelper.GetUsersRowSet(usersExpected); rs.AutoPage = false; rs.PagingState = new byte[] {1, 2, 3}; BoundStatement stmt = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Callback<IStatement>(s => stmt = (BoundStatement)s) .Returns(() => TestHelper.DelayedTask(rs, 50)) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns(TaskHelper.ToTask(GetPrepared())) .Verifiable(); var mappingClient = GetMappingClient(sessionMock); IPage<PlainUser> page = mappingClient.FetchPageAsync<PlainUser>(Cql.New("SELECT * FROM users").WithOptions(opt => opt.SetPageSize(pageSize))).Result; Assert.Null(page.CurrentPagingState); Assert.NotNull(page.PagingState); Assert.AreEqual(rs.PagingState, page.PagingState); CollectionAssert.AreEqual(page, usersExpected, new TestHelper.PropertyComparer()); sessionMock.Verify(); Assert.False(stmt.AutoPage); Assert.AreEqual(pageSize, stmt.PageSize); } [Test] public void Fetch_Nullable_Bool_Does_Not_Throw() { var rowMock = new Mock<Row>(MockBehavior.Strict); rowMock.Setup(r => r.GetValue<bool>(It.IsIn(0))).Throws<NullReferenceException>(); rowMock.Setup(r => r.IsNull(It.IsIn(0))).Returns(true).Verifiable(); var rs = new RowSet { Columns = new[] { new CqlColumn { Name = "bool_sample", TypeCode = ColumnTypeCode.Boolean, Type = typeof(bool), Index = 0 } } }; rs.AddRow(rowMock.Object); var map = new Map<AllTypesEntity>().Column(p => p.BooleanValue, c => c.WithName("bool_sample")); var mapper = GetMappingClient(rs, new MappingConfiguration().Define(map)); // ReSharper disable once ReturnValueOfPureMethodIsNotUsed Assert.DoesNotThrow(() => mapper.Fetch<AllTypesEntity>().ToArray()); rowMock.Verify(); } [Test] public void Fetch_Sets_Consistency() { ConsistencyLevel? consistency = null; ConsistencyLevel? serialConsistency = null; var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Callback<IStatement>(b => { consistency = b.ConsistencyLevel; serialConsistency = b.SerialConsistencyLevel; }) .Returns(() => TaskHelper.ToTask(TestDataHelper.GetUsersRowSet(TestDataHelper.GetUserList()))) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns(TaskHelper.ToTask(GetPrepared())) .Verifiable(); var mapper = GetMappingClient(sessionMock); mapper.Fetch<PlainUser>(new Cql("SELECT").WithOptions(o => o.SetConsistencyLevel(ConsistencyLevel.EachQuorum).SetSerialConsistencyLevel(ConsistencyLevel.Serial))); Assert.AreEqual(ConsistencyLevel.EachQuorum, consistency); Assert.AreEqual(ConsistencyLevel.Serial, serialConsistency); } [Test] public void Fetch_Maps_NullableDateTime_Test() { var rs = new RowSet { Columns = new[] { new CqlColumn {Name = "id", TypeCode = ColumnTypeCode.Uuid, Type = typeof (Guid), Index = 0}, new CqlColumn {Name = "title", TypeCode = ColumnTypeCode.Text, Type = typeof (string), Index = 1}, new CqlColumn {Name = "releasedate", TypeCode = ColumnTypeCode.Timestamp, Type = typeof (DateTimeOffset), Index = 2} } }; var values = new object[] { Guid.NewGuid(), "Come Away with Me", DateTimeOffset.Parse("2002-01-01 +0")}; var row = new Row(values, rs.Columns, rs.Columns.ToDictionary(c => c.Name, c => c.Index)); rs.AddRow(row); var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Returns(TestHelper.DelayedTask(rs, 100)) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns(TaskHelper.ToTask(GetPrepared())) .Verifiable(); var mapper = GetMappingClient(sessionMock); var song = mapper.Fetch<Song2>(new Cql("SELECT * FROM songs")).First(); Assert.AreEqual("Come Away with Me", song.Title); Assert.AreEqual(DateTimeOffset.Parse("2002-01-01 +0").DateTime, song.ReleaseDate); } [Test] public void Fetch_Anonymous_Type_With_Nullable_Column() { var songs = FetchAnonymous(x => new { x.Title, x.ReleaseDate }); Assert.AreEqual("Come Away with Me", songs[0].Title); Assert.AreEqual(DateTimeOffset.Parse("2002-01-01 +0").DateTime, songs[0].ReleaseDate); Assert.AreEqual(false, songs[1].ReleaseDate.HasValue); } // ReSharper disable once UnusedParameter.Local T[] FetchAnonymous<T>(Func<Song2, T> justHereToCreateAnonymousType) { var rs = new RowSet { Columns = new[] { new CqlColumn {Name = "title", TypeCode = ColumnTypeCode.Text, Type = typeof (string), Index = 0}, new CqlColumn {Name = "releasedate", TypeCode = ColumnTypeCode.Timestamp, Type = typeof (DateTimeOffset), Index = 1} } }; var values = new object[] {"Come Away with Me", DateTimeOffset.Parse("2002-01-01 +0")}; var row = new Row(values, rs.Columns, rs.Columns.ToDictionary(c => c.Name, c => c.Index)); rs.AddRow(row); values = new object[] { "Come Away with Me", null }; row = new Row(values, rs.Columns, rs.Columns.ToDictionary(c => c.Name, c => c.Index)); rs.AddRow(row); var sessionMock = new Mock<ISession>(MockBehavior.Strict); sessionMock.Setup(s => s.Keyspace).Returns<string>(null); sessionMock .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>())) .Returns(TestHelper.DelayedTask(rs, 100)) .Verifiable(); sessionMock .Setup(s => s.PrepareAsync(It.IsAny<string>())) .Returns(TaskHelper.ToTask(GetPrepared())) .Verifiable(); var mapper = GetMappingClient(sessionMock); return mapper.Fetch<T>(new Cql("SELECT title,releasedate FROM songs")).ToArray(); } [Test] public void Fetch_Poco_With_Enum() { var columns = new [] { new CqlColumn { Name = "id", Index = 0, Type = typeof(long), TypeCode = ColumnTypeCode.Bigint }, new CqlColumn { Name = "enum1", Index = 1, Type = typeof(int), TypeCode = ColumnTypeCode.Int } }; var rs = new RowSet { Columns = columns }; rs.AddRow( new Row(new object[] {1L, 3}, columns, columns.ToDictionary(c => c.Name, c => c.Index))); var config = new MappingConfiguration().Define(new Map<PocoWithEnumCollections>() .ExplicitColumns() .Column(x => x.Id, cm => cm.WithName("id")) .Column(x => x.Enum1, cm => cm.WithName("enum1")) ); var mapper = GetMappingClient(rs, config); var result = mapper.Fetch<PocoWithEnumCollections>("SELECT * FROM tbl1 WHERE id = ?", 1).First(); Assert.NotNull(result); Assert.AreEqual(1L, result.Id); Assert.AreEqual(HairColor.Gray, result.Enum1); } [Test] public void Fetch_Poco_With_Enum_Collections() { var columns = PocoWithEnumCollections.DefaultColumns; var rs = new RowSet { Columns = columns }; var expectedCollection = new[]{ HairColor.Blonde, HairColor.Gray }; var expectedMap = new SortedDictionary<HairColor, TimeUuid> { { HairColor.Brown, TimeUuid.NewId() }, { HairColor.Red, TimeUuid.NewId() } }; var collectionValues = expectedCollection.Select(x => (int)x).ToArray(); var mapValues = new SortedDictionary<int, Guid>(expectedMap.ToDictionary(kv => (int) kv.Key, kv => (Guid) kv.Value)); rs.AddRow( new Row( new object[] { 1L, collectionValues, collectionValues, collectionValues, collectionValues, collectionValues, collectionValues, mapValues, mapValues, mapValues }, columns, columns.ToDictionary(c => c.Name, c => c.Index))); var config = new MappingConfiguration().Define(PocoWithEnumCollections.DefaultMapping); var mapper = GetMappingClient(rs, config); var result = mapper.Fetch<PocoWithEnumCollections>("SELECT * FROM tbl1 WHERE id = ?", 1).First(); Assert.NotNull(result); Assert.AreEqual(1L, result.Id); Assert.AreEqual(expectedCollection, result.List1); Assert.AreEqual(expectedCollection, result.List2); Assert.AreEqual(expectedCollection, result.Array1); Assert.AreEqual(expectedCollection, result.Set1); Assert.AreEqual(expectedCollection, result.Set2); Assert.AreEqual(expectedCollection, result.Set3); Assert.AreEqual(expectedMap, result.Dictionary1); Assert.AreEqual(expectedMap, result.Dictionary2); Assert.AreEqual(expectedMap, result.Dictionary3); } private static void SetFetchNextMethod(RowSet rs, Func<byte[], RowSet> handler) { rs.SetFetchNextPageHandler(pagingState => Task.FromResult(handler(pagingState)), 10000, Mock.Of<IMetricsManager>()); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Django.Project; using Microsoft.PythonTools.Django.TemplateParsing; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Text; namespace DjangoTests { [TestClass] public class DjangoTemplateParserTests { #region Filter parser tests [TestMethod, Priority(1)] public void FilterRegexTests() { var testCases = new[] { new { Got = ("100"), Expected = DjangoVariable.Number("100", 0) }, new { Got = ("100.0"), Expected = DjangoVariable.Number("100.0", 0) }, new { Got = ("+100"), Expected = DjangoVariable.Number("+100", 0) }, new { Got = ("-100"), Expected = DjangoVariable.Number("-100", 0) }, new { Got = ("'fob'"), Expected = DjangoVariable.Constant("'fob'", 0) }, new { Got = ("\"fob\""), Expected = DjangoVariable.Constant("\"fob\"", 0) }, new { Got = ("fob"), Expected = DjangoVariable.Variable("fob", 0) }, new { Got = ("fob.oar"), Expected = DjangoVariable.Variable("fob.oar", 0) }, new { Got = ("fob|oar"), Expected = DjangoVariable.Variable("fob", 0, new DjangoFilter("oar", 4)) }, new { Got = ("fob|oar|baz"), Expected = DjangoVariable.Variable("fob", 0, new DjangoFilter("oar", 4), new DjangoFilter("baz", 8)) }, new { Got = ("fob|oar:'fob'"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Constant("oar", 4, "'fob'", 8)) }, new { Got = ("fob|oar:42"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "42", 8)) }, new { Got = ("fob|oar:\"fob\""), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Constant("oar", 4, "\"fob\"", 8)) }, new { Got = ("fob|oar:100"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "100", 8)) }, new { Got = ("fob|oar:100.0"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "100.0", 8)) }, new { Got = ("fob|oar:+100.0"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "+100.0", 8)) }, new { Got = ("fob|oar:-100.0"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Number("oar", 4, "-100.0", 8)) }, new { Got = ("fob|oar:baz.quox"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Variable("oar", 4, "baz.quox", 8)) }, new { Got = ("fob|oar:baz"), Expected = DjangoVariable.Variable("fob", 0, DjangoFilter.Variable("oar", 4, "baz", 8)) }, new { Got = ("{{ 100 }}"), Expected = DjangoVariable.Number("100", 3) }, new { Got = ("{{ 100.0 }}"), Expected = DjangoVariable.Number("100.0", 3) }, new { Got = ("{{ +100 }}"), Expected = DjangoVariable.Number("+100", 3) }, new { Got = ("{{ -100 }}"), Expected = DjangoVariable.Number("-100", 3) }, new { Got = ("{{ 'fob' }}"), Expected = DjangoVariable.Constant("'fob'", 3) }, new { Got = ("{{ \"fob\" }}"), Expected = DjangoVariable.Constant("\"fob\"", 3) }, new { Got = ("{{ fob }}"), Expected = DjangoVariable.Variable("fob", 3) }, new { Got = ("{{ fob.oar }}"), Expected = DjangoVariable.Variable("fob.oar", 3) }, new { Got = ("{{ fob|oar }}"), Expected = DjangoVariable.Variable("fob", 3, new DjangoFilter("oar", 7)) }, new { Got = ("{{ fob|oar|baz }}"), Expected = DjangoVariable.Variable("fob", 3, new DjangoFilter("oar", 7), new DjangoFilter("baz", 11)) }, new { Got = ("{{ fob|oar:'fob' }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Constant("oar", 7, "'fob'", 11)) }, new { Got = ("{{ fob|oar:42 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "42", 11)) }, new { Got = ("{{ fob|oar:\"fob\" }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Constant("oar", 7, "\"fob\"", 11)) }, new { Got = ("{{ fob|oar:100 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "100", 11)) }, new { Got = ("{{ fob|oar:100.0 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "100.0", 11)) }, new { Got = ("{{ fob|oar:+100.0 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "+100.0", 11)) }, new { Got = ("{{ fob|oar:-100.0 }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Number("oar", 7, "-100.0", 11)) }, new { Got = ("{{ fob|oar:baz.quox }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Variable("oar", 7, "baz.quox", 11)) }, new { Got = ("{{ fob|oar:baz }}"), Expected = DjangoVariable.Variable("fob", 3, DjangoFilter.Variable("oar", 7, "baz", 11)) }, }; foreach (var testCase in testCases) { Console.WriteLine(testCase.Got); var got = DjangoVariable.Parse(testCase.Got); ValidateFilter(testCase.Expected, got); } } internal void ValidateFilter(DjangoVariable got, DjangoVariable expected) { Assert.AreEqual(expected.Expression.Value, got.Expression.Value); Assert.AreEqual(expected.Expression.Kind, got.Expression.Kind); Assert.AreEqual(expected.ExpressionStart, got.ExpressionStart); Assert.AreEqual(expected.Filters.Length, got.Filters.Length); for (int i = 0; i < expected.Filters.Length; i++) { if (expected.Filters[i].Arg == null) { Assert.AreEqual(null, got.Filters[i].Arg); } else { Assert.AreEqual(expected.Filters[i].Arg.Value, got.Filters[i].Arg.Value); Assert.AreEqual(expected.Filters[i].Arg.Kind, got.Filters[i].Arg.Kind); Assert.AreEqual(expected.Filters[i].ArgStart, got.Filters[i].ArgStart); } Assert.AreEqual(expected.Filters[i].Filter, got.Filters[i].Filter); } } #endregion #region Block parser tests [TestMethod, Priority(1)] public void BlockParserTests() { var testCases = new[] { new { Got = ("for x in "), Expected = (DjangoBlock)new DjangoForBlock(new BlockParseInfo("for", "x in ", 0), 6, null, 9, -1, new[] { new Tuple<string, int>("x", 4) }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 9, Expected = new[] { "fob", "oar" } }, new { Position = 4, Expected = new string[0] } } }, new { Got = ("for x in oar"), Expected = (DjangoBlock)new DjangoForBlock(new BlockParseInfo("for", "x in oar", 0), 6, DjangoVariable.Variable("oar", 9), 12, -1, new[] { new Tuple<string, int>("x", 4) }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 9, Expected = new[] { "fob", "oar" } }, new { Position = 4, Expected = new string[0] } } }, new { Got = ("for x in b"), Expected = (DjangoBlock)new DjangoForBlock(new BlockParseInfo("for", "x in b", 0), 6, DjangoVariable.Variable("b", 9), 10, -1, new[] { new Tuple<string, int>("x", 4) }), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new [] { "fob", "oar" } }, new { Position = 4, Expected = new string[0] } } }, new { Got = ("autoescape"), Expected = (DjangoBlock)new DjangoAutoEscapeBlock(new BlockParseInfo("autoescape", "", 0), -1, -1), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new[] { "on", "off" } } } }, new { Got = ("autoescape on"), Expected = (DjangoBlock)new DjangoAutoEscapeBlock(new BlockParseInfo("autoescape", " on", 0), 11, 2), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new string[0] } } }, new { Got = ("comment"), Expected = (DjangoBlock)new DjangoArgumentlessBlock(new BlockParseInfo("comment", "", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 0, Expected = new string[0] } } }, new { Got = ("spaceless"), Expected = (DjangoBlock)new DjangoSpacelessBlock(new BlockParseInfo("spaceless", "", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 0, Expected = new string[0] } } }, new { Got = ("filter "), Expected = (DjangoBlock)new DjangoFilterBlock(new BlockParseInfo("filter", " ", 0), DjangoVariable.Variable("", 7)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 7, Expected = new [] { "cut", "lower" } } } }, new { Got = ("ifequal "), Expected = (DjangoBlock)new DjangoIfOrIfNotEqualBlock(new BlockParseInfo("ifequal", " ", 0), DjangoVariable.Variable("", 8)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 8, Expected = new [] { "fob", "oar" } } } }, new { Got = ("ifequal fob "), Expected = (DjangoBlock)new DjangoIfOrIfNotEqualBlock(new BlockParseInfo("ifequal", " fob ", 0), DjangoVariable.Variable("fob", 8)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 12, Expected = new [] { "fob", "oar" } } } }, new { Got = ("if "), Expected = (DjangoBlock)new DjangoIfBlock(new BlockParseInfo("if", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 3, Expected = new [] { "fob", "oar", "not" } } } }, new { Got = ("if fob "), Expected = (DjangoBlock)new DjangoIfBlock(new BlockParseInfo("if", " fob ", 0), new BlockClassification(new Span(3, 3), Classification.Identifier)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 7, Expected = new [] { "and", "or" } } } }, new { Got = ("if fob and "), Expected = (DjangoBlock)new DjangoIfBlock(new BlockParseInfo("if", " fob and ", 0), new BlockClassification(new Span(3, 3), Classification.Identifier), new BlockClassification(new Span(7, 3), Classification.Keyword)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 11, Expected = new [] { "fob", "oar", "not" } } } }, new { Got = ("firstof "), Expected = (DjangoBlock)new DjangoMultiVariableArgumentBlock(new BlockParseInfo("firstof", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 8, Expected = new [] { "fob", "oar" } } } }, new { Got = ("firstof fob|"), Expected = (DjangoBlock)new DjangoMultiVariableArgumentBlock(new BlockParseInfo("firstof", " fob|", 0), DjangoVariable.Variable("fob", 8)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 12, Expected = new [] { "cut", "lower" } } } }, new { Got = ("spaceless "), Expected = (DjangoBlock)new DjangoSpacelessBlock(new BlockParseInfo("spaceless", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 10, Expected = new string[0] } } }, new { Got = ("widthratio "), Expected = (DjangoBlock)new DjangoWidthRatioBlock(new BlockParseInfo("widthratio", " ", 0)), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 11, Expected = new [] { "fob", "oar" } } } }, new { Got = ("templatetag "), Expected = (DjangoBlock)new DjangoTemplateTagBlock(new BlockParseInfo("templatetag", " ", 0), 11, null), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 11, Expected = new [] { "openblock", "closeblock", "openvariable", "closevariable", "openbrace", "closebrace", "opencomment", "closecomment" } } } }, new { Got = ("templatetag open"), Expected = (DjangoBlock)new DjangoTemplateTagBlock(new BlockParseInfo("templatetag", " open", 0), 11, null), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 15, Expected = new [] { "openblock", "openvariable", "openbrace", "opencomment" } } } }, new { Got = ("templatetag openblock "), Expected = (DjangoBlock)new DjangoTemplateTagBlock(new BlockParseInfo("templatetag", " openblock ", 0), 11, "openblock"), Context = TestCompletionContext.Simple, Completions = new[] { new { Position = 22, Expected = new string[0] } } }, }; foreach (var testCase in testCases) { Console.WriteLine(testCase.Got); var got = DjangoBlock.Parse(testCase.Got); ValidateBlock(testCase.Expected, got); foreach (var completionCase in testCase.Completions) { var completions = new HashSet<string>(got.GetCompletions(testCase.Context, completionCase.Position).Select(x => x.DisplayText)); Assert.AreEqual(completionCase.Expected.Length, completions.Count); var expected = new HashSet<string>(completionCase.Expected); foreach (var value in completions) { Assert.IsTrue(expected.Contains(value)); } } } } private static Dictionary<Type, Action<DjangoBlock, DjangoBlock>> _blockValidators = MakeBlockValidators(); private static Dictionary<Type, Action<DjangoBlock, DjangoBlock>> MakeBlockValidators() { return new Dictionary<Type, Action<DjangoBlock, DjangoBlock>>() { { typeof(DjangoForBlock), ValidateForBlock }, { typeof(DjangoAutoEscapeBlock), ValidateAutoEscape }, { typeof(DjangoArgumentlessBlock), ValidateArgumentless }, { typeof(DjangoFilterBlock), ValidateFilter }, { typeof(DjangoIfOrIfNotEqualBlock), ValidateIfOrIfNotEqualBlock}, { typeof(DjangoIfBlock), ValidateIfBlock}, { typeof(DjangoMultiVariableArgumentBlock), ValidateMultiArgumentBlock}, { typeof(DjangoSpacelessBlock), ValidateSpacelessBlock}, { typeof(DjangoTemplateTagBlock), ValidateTemplateTagBlock }, { typeof(DjangoWidthRatioBlock), ValidateWidthRatioBlock } }; } private static void ValidateWidthRatioBlock(DjangoBlock expected, DjangoBlock got) { var withExpected = (DjangoWidthRatioBlock)expected; var withGot = (DjangoWidthRatioBlock)got; Assert.AreEqual(withExpected.ParseInfo.Start, withGot.ParseInfo.Start); Assert.AreEqual(withExpected.ParseInfo.Command, withGot.ParseInfo.Command); Assert.AreEqual(withExpected.ParseInfo.Args, withGot.ParseInfo.Args); } private static void ValidateTemplateTagBlock(DjangoBlock expected, DjangoBlock got) { var tempTagExpected = (DjangoTemplateTagBlock)expected; var tempTagGot = (DjangoTemplateTagBlock)got; Assert.AreEqual(tempTagExpected.ParseInfo.Start, tempTagGot.ParseInfo.Start); Assert.AreEqual(tempTagExpected.ParseInfo.Command, tempTagGot.ParseInfo.Command); Assert.AreEqual(tempTagExpected.ParseInfo.Args, tempTagGot.ParseInfo.Args); } private static void ValidateSpacelessBlock(DjangoBlock expected, DjangoBlock got) { var spacelessExpected = (DjangoSpacelessBlock)expected; var spacelessGot = (DjangoSpacelessBlock)got; Assert.AreEqual(spacelessExpected.ParseInfo.Start, spacelessGot.ParseInfo.Start); Assert.AreEqual(spacelessExpected.ParseInfo.Command, spacelessGot.ParseInfo.Command); Assert.AreEqual(spacelessExpected.ParseInfo.Args, spacelessGot.ParseInfo.Args); } private static void ValidateMultiArgumentBlock(DjangoBlock expected, DjangoBlock got) { var maExpected = (DjangoMultiVariableArgumentBlock)expected; var maGot = (DjangoMultiVariableArgumentBlock)got; Assert.AreEqual(maExpected.ParseInfo.Start, maGot.ParseInfo.Start); Assert.AreEqual(maExpected.ParseInfo.Command, maGot.ParseInfo.Command); Assert.AreEqual(maExpected.ParseInfo.Args, maGot.ParseInfo.Args); } private static void ValidateIfBlock(DjangoBlock expected, DjangoBlock got) { var ifExpected = (DjangoIfBlock)expected; var ifGot = (DjangoIfBlock)got; Assert.AreEqual(ifExpected.ParseInfo.Start, ifGot.ParseInfo.Start); Assert.AreEqual(ifExpected.ParseInfo.Command, ifGot.ParseInfo.Command); Assert.AreEqual(ifExpected.ParseInfo.Args, ifGot.ParseInfo.Args); Assert.AreEqual(ifExpected.Args.Length, ifGot.Args.Length); for (int i = 0; i < ifExpected.Args.Length; i++) { Assert.AreEqual(ifExpected.Args[i], ifGot.Args[i]); } } private static void ValidateIfOrIfNotEqualBlock(DjangoBlock expected, DjangoBlock got) { var ifExpected = (DjangoIfOrIfNotEqualBlock)expected; var ifGot = (DjangoIfOrIfNotEqualBlock)got; Assert.AreEqual(ifExpected.ParseInfo.Start, ifGot.ParseInfo.Start); Assert.AreEqual(ifExpected.ParseInfo.Command, ifGot.ParseInfo.Command); Assert.AreEqual(ifExpected.ParseInfo.Args, ifGot.ParseInfo.Args); } private static void ValidateFilter(DjangoBlock expected, DjangoBlock got) { var filterExpected = (DjangoFilterBlock)expected; var filterGot = (DjangoFilterBlock)got; Assert.AreEqual(filterExpected.ParseInfo.Start, filterGot.ParseInfo.Start); Assert.AreEqual(filterExpected.ParseInfo.Command, filterGot.ParseInfo.Command); Assert.AreEqual(filterExpected.ParseInfo.Args, filterGot.ParseInfo.Args); } private static void ValidateForBlock(DjangoBlock expected, DjangoBlock got) { var forExpected = (DjangoForBlock)expected; var forGot = (DjangoForBlock)got; Assert.AreEqual(forExpected.ParseInfo.Start, forGot.ParseInfo.Start); Assert.AreEqual(forExpected.InStart, forGot.InStart); } private static void ValidateAutoEscape(DjangoBlock expected, DjangoBlock got) { var aeExpected = (DjangoAutoEscapeBlock)expected; var aeGot = (DjangoAutoEscapeBlock)got; Assert.AreEqual(aeExpected.ParseInfo.Start, aeGot.ParseInfo.Start); Assert.AreEqual(aeExpected.ParseInfo.Command, aeGot.ParseInfo.Command); Assert.AreEqual(aeExpected.ParseInfo.Args, aeGot.ParseInfo.Args); } private static void ValidateArgumentless(DjangoBlock expected, DjangoBlock got) { var aeExpected = (DjangoArgumentlessBlock)expected; var aeGot = (DjangoArgumentlessBlock)got; Assert.AreEqual(aeExpected.ParseInfo.Start, aeGot.ParseInfo.Start); Assert.AreEqual(aeExpected.ParseInfo.Command, aeGot.ParseInfo.Command); Assert.AreEqual(aeExpected.ParseInfo.Args, aeGot.ParseInfo.Args); } private void ValidateBlock(DjangoBlock expected, DjangoBlock got) { Assert.AreEqual(expected.GetType(), got.GetType()); _blockValidators[expected.GetType()](expected, got); } #endregion #region Template tokenizer tests [TestMethod, Priority(1)] public void TestSimpleVariable() { var code = @"<html> <head><title></title></head> <body> {{ content }} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Variable, 50, 62), new TemplateToken(TemplateTokenKind.Text, 63, 82) ); } [TestMethod, Priority(1)] public void TestEmbeddedWrongClose() { var code = @"<html> <head><title></title></head> <body> {{ content %} }} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Variable, 50, 65), new TemplateToken(TemplateTokenKind.Text, 66, 85) ); } [TestMethod, Priority(1)] public void SingleTrailingChar() { foreach (var code in new[] { "{{fob}}\n", "{{fob}}a" }) { TokenizerTest(code, new TemplateToken(TemplateTokenKind.Variable, 0, 6), new TemplateToken(TemplateTokenKind.Text, 7, 7) ); } } // struct TemplateTokenResult { public readonly TemplateToken Token; public readonly char? Start, End; public TemplateTokenResult(TemplateToken token, char? start = null, char? end = null) { Token = token; Start = start; End = end; } public static implicit operator TemplateTokenResult(TemplateToken token) { return new TemplateTokenResult(token); } } [TestMethod, Priority(1)] public void TestSimpleBlock() { var code = @"<html> <head><title></title></head> <body> {% block %} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Block, 50, 60), new TemplateToken(TemplateTokenKind.Text, 61, code.Length - 1)); } [TestMethod, Priority(1)] public void TestSimpleComment() { var code = @"<html> <head><title></title></head> <body> {# comment #} </body> </html>"; TokenizerTest(code, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Comment, 50, 62), new TemplateToken(TemplateTokenKind.Text, 63, code.Length - 1)); } [TestMethod, Priority(1)] public void TestUnclosedVariable() { var code = @"<html> <head><title></title></head> <body> {{ content </body> </html>"; TokenizerTest(code, /*unclosed*/true, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Variable, 50, 80, isClosed: false) ); } [TestMethod, Priority(1)] public void TestTextStartAndEnd() { var code = @"<html> <head><title></title></head> <body> <p>{{ content }}</p> </body> </html>"; TokenizerTest(code, new TemplateTokenResult( new TemplateToken(TemplateTokenKind.Text, 0, code.IndexOf("<p>") + 2), '<', '>' ), new TemplateToken(TemplateTokenKind.Variable, code.IndexOf("<p>") + 3, code.IndexOf("</p>") - 1), new TemplateTokenResult( new TemplateToken(TemplateTokenKind.Text, code.IndexOf("</p>"), code.Length - 1), '<', '>' ) ); } [TestMethod, Priority(1)] public void TestUnclosedComment() { var code = @"<html> <head><title></title></head> <body> {# content </body> </html>"; TokenizerTest(code, /*unclosed*/true, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Comment, 50, 80, isClosed: false) ); } [TestMethod, Priority(1)] public void TestUnclosedBlock() { var code = @"<html> <head><title></title></head> <body> {% content </body> </html>"; TokenizerTest(code, /*unclosed*/true, new TemplateToken(TemplateTokenKind.Text, 0, 49), new TemplateToken(TemplateTokenKind.Block, 50, 80, isClosed: false) ); } private void TokenizerTest(string text, params TemplateTokenResult[] expected) { TokenizerTest(text, false, expected); } private void TokenizerTest(string text, bool unclosed, params TemplateTokenResult[] expected) { var tokenizer = new TemplateTokenizer(new StringReader(text)); var tokens = tokenizer.GetTokens().ToArray(); bool passed = false; try { Assert.AreEqual(expected.Length, tokens.Length); Assert.AreEqual(0, tokens[0].Start); Assert.AreEqual(text.Length - 1, tokens[tokens.Length - 1].End); for (int i = 0; i < expected.Length; i++) { var expectedToken = expected[i].Token; Assert.AreEqual(expectedToken.Kind, tokens[i].Kind); Assert.AreEqual(expectedToken.Start, tokens[i].Start); Assert.AreEqual(expectedToken.End, tokens[i].End); switch (expectedToken.Kind) { case TemplateTokenKind.Block: case TemplateTokenKind.Comment: case TemplateTokenKind.Variable: Assert.AreEqual('{', text[expectedToken.Start]); if (!unclosed) { Assert.AreEqual('}', text[expectedToken.End]); } break; } if (expected[i].Start != null) { Assert.AreEqual(expected[i].Start, text[expectedToken.Start]); } if (expected[i].End != null) { Assert.AreEqual(expected[i].End, text[expectedToken.End]); } } passed = true; } finally { if (!passed) { List<string> res = new List<string>(); for (int i = 0; i < tokens.Length; i++) { res.Add( String.Format("new TemplateToken(TemplateTokenKind.{0}, {1}, {2})", tokens[i].Kind, tokens[i].Start, tokens[i].End ) ); } Console.WriteLine(String.Join(",\r\n", res)); } } } #endregion } class TestCompletionContext : IDjangoCompletionContext { private readonly Dictionary<string, HashSet<AnalysisValue>> _variables; private readonly Dictionary<string, TagInfo> _filters; internal static TestCompletionContext Simple = new TestCompletionContext(new[] { "fob", "oar" }, new[] { "cut", "lower" }); public TestCompletionContext(string[] variables, string[] filters) { _variables = new Dictionary<string, HashSet<AnalysisValue>>(); _filters = new Dictionary<string, TagInfo>(); foreach (var variable in variables) { _variables[variable] = new HashSet<AnalysisValue>(); } foreach (var filter in filters) { _filters[filter] = new TagInfo("", null); } } #region IDjangoCompletionContext Members public Dictionary<string, HashSet<AnalysisValue>> Variables { get { return _variables; } } public Dictionary<string, TagInfo> Filters { get { return _filters; } } public IModuleContext ModuleContext { get { return null; } } #endregion } }
using NUnit.Framework; [TestFixture] [Category("Extensions")] public class StringExtensions_Tests { #region DelimitedFormat(string tag, char delimiter, params object[] parameters) [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Test_Normal_Usage() { string expected = "TAG A B C D"; string actual = StringExtension.DelimitedFormat("TAG", ' ', "A", "B", "C", "D"); Assert.AreEqual(expected, actual); } [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Test_Null_Tag_Null_Params_Array() { string actual = StringExtension.DelimitedFormat(null, ' ', null); string expected = string.Empty; Assert.AreEqual(expected, actual); } [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Test_Nonnull_Tag_Null_Params_Array() { string actual = StringExtension.DelimitedFormat("TAG", ' ', null); string expected = "TAG"; Assert.AreEqual(expected, actual); } [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Test_Null_Params() { string actual = StringExtension.DelimitedFormat("TAG", ' ', null, null, null); string expected = "TAG"; Assert.AreEqual(expected, actual); } [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Test_Leading_Null_Param_Nonnull_Param() { string actual = StringExtension.DelimitedFormat("TAG", ' ', null, null, "S"); string expected = "TAG S"; Assert.AreEqual(expected, actual); } [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Test_Mixed_Null_Param_Nonnull_Param() { string actual = StringExtension.DelimitedFormat("TAG", ' ', null, "S", null, "X"); string expected = "TAG S X"; Assert.AreEqual(expected, actual); } #endregion #region DelimitedFormat(char delimiter, params object[] parameters) [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Override_Char_Params_Test_Normal_Usage() { string expected = "A B C D"; string actual = StringExtension.DelimitedFormat(' ', "A", "B", "C", "D"); Assert.AreEqual(expected, actual); } [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Override_Char_Params_Test_Null_Params_Array() { string actual = StringExtension.DelimitedFormat(' ', null); string expected = string.Empty; Assert.AreEqual(expected, actual); } [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Override_Char_Params_Test_Null_Params() { string actual = StringExtension.DelimitedFormat(' ', null, null, null); string expected = string.Empty; Assert.AreEqual(expected, actual); } [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Override_Char_Params_Test_Leading_Null_Param_Nonnull_Param() { string actual = StringExtension.DelimitedFormat(' ', null, null, "S"); string expected = "S"; Assert.AreEqual(expected, actual); } [Test] [Category("DelimitedFormat")] public void DelimetedFormat_Override_Char_Params_Test_Mixed_Null_Param_Nonnull_Param() { string actual = StringExtension.DelimitedFormat(' ', null, "S", null, "X"); string expected = "S X"; Assert.AreEqual(expected, actual); } #endregion #region CSVFormat(string tag, params object[] parameters) [Test] [Category("CSVFormat")] public void CSVFormat_String_Params_Test_Normal_Usage() { string expected = "TAG A,B,C,D"; string actual = StringExtension.CSVFormat("TAG", "A", "B", "C", "D"); Assert.AreEqual(expected, actual); } [Test] [Category("CSVFormat")] public void CSVFormat_String_Params_Test_Null_Params_Array() { string actual = StringExtension.CSVFormat(null, null); string expected = string.Empty; Assert.AreEqual(expected, actual); } [Test] [Category("CSVFormat")] public void CSVFormat_String_Params_Test_Null_Params() { string actual = StringExtension.CSVFormat("TAG", null, null, null); string expected = "TAG"; Assert.AreEqual(expected, actual); } [Test] [Category("CSVFormat")] public void CSVFormat_String_Params_Test_Leading_Null_Param_Nonnull_Param() { string actual = StringExtension.CSVFormat("TAG", null, null, "S"); string expected = "TAG S"; Assert.AreEqual(expected, actual); } [Test] [Category("CSVFormat")] public void CSVFormat_String_Params_Test_Mixed_Null_Param_Nonnull_Param() { string actual = StringExtension.CSVFormat("TAG", null, "S", null, "X"); string expected = "TAG S,X"; Assert.AreEqual(expected, actual); } [Test] [Category("CSVFormat")] public void CSVFormat_String_Params_Test_Normal_Usage_Null_Tag() { string actual = StringExtension.CSVFormat(null, "A", "B", "C", "D"); string expected = "A,B,C,D"; Assert.AreEqual(expected, actual); } #endregion #region Truncate(this string value, int maxLength) [Test] [Category("Truncate")] public void Truncate_Test_Normal_Usage() { string actual = "ABCDE".Truncate(4); string expected = "ABCD"; Assert.AreEqual(expected, actual); } [Test] [Category("Truncate")] public void Truncate_Test_Empty() { string actual = string.Empty.Truncate(4); string expected = string.Empty; Assert.AreEqual(expected, actual); } [Test] [Category("Truncate")] public void Truncate_Test_ZeroLength() { string actual = "ABCDE".Truncate(0); string expected = string.Empty; Assert.AreEqual(expected, actual); } [Test] [Category("Truncate")] public void Truncate_Test_NegativeLength() { string actual = "ABCDE".Truncate(-1); string expected = string.Empty; Assert.AreEqual(expected, actual); } [Test] [Category("Truncate")] public void Truncate_Test_MaxLength() { string actual = "ABCDE".Truncate(int.MaxValue); string expected = "ABCDE"; Assert.AreEqual(expected, actual); } #endregion }
using System; using Akka.Actor; using Akka.Configuration; using Akka.Event; using FluentAssertions; using Serilog; using Serilog.Events; using Xunit; using Xunit.Abstractions; namespace Akka.Logger.Serilog.Tests { public class LogMessageSpecs : TestKit.Xunit2.TestKit { public static readonly Config Config = @"akka.loglevel = DEBUG akka.loggers=[""Akka.Logger.Serilog.SerilogLogger, Akka.Logger.Serilog""]"; private readonly ILoggingAdapter _loggingAdapter; private readonly TestSink _sink = new TestSink(); public LogMessageSpecs(ITestOutputHelper helper) : base(Config, output: helper) { global::Serilog.Log.Logger = new LoggerConfiguration() .WriteTo.Sink(_sink) .MinimumLevel.Debug() .CreateLogger(); _loggingAdapter = Sys.Log; } [Fact] public void ShouldLogDebugLevelMessage() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); context.Debug("hi"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Debug); logEvent.RenderMessage().Should().Contain("hi"); } [Fact] public void ShouldLogDebugLevelMessageWithArgs() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); context.Debug("hi {0}", "test"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Debug); logEvent.RenderMessage().Should().Contain("hi \"test\""); } [Fact] public void ShouldLogDebugLevelMessageWithException() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); var exception = new Exception("BOOM!!!"); context.Debug(exception, "hi"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Debug); logEvent.Exception.Should().Be(exception); } [Fact] public void ShouldLogDebugLevelMessageWithArgsAndException() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); var exception = new Exception("BOOM!!!"); context.Debug(exception, "hi {0}", "test"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Debug); logEvent.Exception.Should().Be(exception); } [Fact] public void ShouldLogInfoLevelMessage() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); context.Info("hi"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Information); logEvent.RenderMessage().Should().Contain("hi"); } [Fact] public void ShouldLogInfoLevelMessageWithArgs() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); context.Info("hi {0}", "test"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Information); logEvent.RenderMessage().Should().Contain("hi \"test\""); } [Fact] public void ShouldLogInfoLevelMessageWithException() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); var exception = new Exception("BOOM!!!"); context.Info(exception, "hi"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Information); logEvent.Exception.Should().Be(exception); } [Fact] public void ShouldLogInfoLevelMessageWithArgsAndException() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); var exception = new Exception("BOOM!!!"); context.Info(exception, "hi {0}", "test"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Information); logEvent.Exception.Should().Be(exception); } [Fact] public void ShouldLogWarningLevelMessage() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); context.Warning("hi"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Warning); logEvent.RenderMessage().Should().Contain("hi"); } [Fact] public void ShouldLogWarningLevelMessageWithArgs() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); context.Warning("hi {0}", "test"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Warning); logEvent.RenderMessage().Should().Contain("hi \"test\""); } [Fact] public void ShouldLogWarningLevelMessageWithException() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); var exception = new Exception("BOOM!!!"); context.Warning(exception, "hi"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Warning); logEvent.Exception.Should().Be(exception); } [Fact] public void ShouldLogWarningLevelMessageWithArgsAndException() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); var exception = new Exception("BOOM!!!"); context.Warning(exception, "hi {0}", "test"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Warning); logEvent.Exception.Should().Be(exception); } [Fact] public void ShouldLogErrorLevelMessage() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); context.Error("hi"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Error); logEvent.RenderMessage().Should().Contain("hi"); } [Fact] public void ShouldLogErrorLevelMessageWithArgs() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); context.Error("hi {0}", "test"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Error); logEvent.RenderMessage().Should().Contain("hi \"test\""); } [Fact] public void ShouldLogErrorLevelMessageWithException() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); var exception = new Exception("BOOM!!!"); context.Error(exception, "hi"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Error); logEvent.Exception.Should().Be(exception); } [Fact] public void ShouldLogErrorLevelMessageWithArgsAndException() { var context = _loggingAdapter; _sink.Clear(); AwaitCondition(() => _sink.Writes.Count == 0); var exception = new Exception("BOOM!!!"); context.Error(exception, "hi {0}", "test"); AwaitCondition(() => _sink.Writes.Count == 1); _sink.Writes.TryDequeue(out var logEvent).Should().BeTrue(); logEvent.Level.Should().Be(LogEventLevel.Error); logEvent.Exception.Should().Be(exception); } } }
using Avalonia; using Avalonia.Controls; using Avalonia.Dialogs; using Avalonia.ReactiveUI; using Splat; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using WalletWasabi.Fluent.CrashReport; using WalletWasabi.Fluent.Helpers; using WalletWasabi.Fluent.ViewModels; using WalletWasabi.Gui; using WalletWasabi.Helpers; using WalletWasabi.Logging; using WalletWasabi.Services; using WalletWasabi.Services.Terminate; using WalletWasabi.Wallets; using LogLevel = WalletWasabi.Logging.LogLevel; namespace WalletWasabi.Fluent.Desktop { public class Program { private static Global? Global; private static readonly TerminateService TerminateService = new TerminateService(TerminateApplicationAsync); // Initialization code. Don't use any Avalonia, third-party APIs or any // SynchronizationContext-reliant code before AppMain is called: things aren't initialized // yet and stuff might break. public static int Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException; bool runGui = true; try { if (CrashReporter.TryGetExceptionFromCliArgs(args, out var exceptionToShow)) { // Show the exception. Console.WriteLine($"TODO Implement crash reporting. {exceptionToShow}"); runGui = false; } } catch (Exception ex) { // Anything happens here just log it and do not run the Gui. Logger.LogCritical(ex); runGui = false; } Exception? exceptionToReport = null; SingleInstanceChecker? singleInstanceChecker = null; if (runGui) { try { string dataDir = EnvironmentHelpers.GetDataDir(Path.Combine("WalletWasabi", "Client")); SetupLogger(dataDir, args); var (uiConfig, config) = LoadOrCreateConfigs(dataDir); singleInstanceChecker = new SingleInstanceChecker(config.Network); singleInstanceChecker.EnsureSingleOrThrowAsync().GetAwaiter().GetResult(); Global = CreateGlobal(dataDir, uiConfig, config); // TODO only required due to statusbar vm... to be removed. Locator.CurrentMutable.RegisterConstant(Global); Logger.LogSoftwareStarted("Wasabi GUI"); BuildAvaloniaApp() .AfterSetup(_ => ThemeHelper.ApplyTheme(Global.UiConfig.DarkModeEnabled)) .StartWithClassicDesktopLifetime(args); } catch (OperationCanceledException ex) { Logger.LogDebug(ex); } catch (Exception ex) { exceptionToReport = ex; Logger.LogCritical(ex); } } // Start termination/disposal of the application. TerminateService.Terminate(); if (singleInstanceChecker is { } single) { Task.Run(async () => await single.DisposeAsync()).Wait(); } if (exceptionToReport is { }) { // Trigger the CrashReport process if required. CrashReporter.Invoke(exceptionToReport); } AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException; TaskScheduler.UnobservedTaskException -= TaskScheduler_UnobservedTaskException; Logger.LogSoftwareStopped("Wasabi"); return exceptionToReport is { } ? 1 : 0; } /// <summary> /// Initializes Wasabi Logger. Sets user-defined log-level, if provided. /// </summary> /// <example>Start Wasabi Wallet with <c>./wassabee --LogLevel=trace</c> to set <see cref="LogLevel.Trace"/>.</example> private static void SetupLogger(string dataDir, string[] args) { LogLevel? logLevel = null; foreach (string arg in args) { if (arg.StartsWith("--LogLevel=")) { string value = arg.Split('=', count: 2)[1]; if (Enum.TryParse(value, ignoreCase: true, out LogLevel parsedLevel)) { logLevel = parsedLevel; break; } } } Logger.InitializeDefaults(Path.Combine(dataDir, "Logs.txt"), logLevel); } private static (UiConfig uiConfig, Config config) LoadOrCreateConfigs(string dataDir) { Directory.CreateDirectory(dataDir); UiConfig uiConfig = new(Path.Combine(dataDir, "UiConfig.json")); uiConfig.LoadOrCreateDefaultFile(); Config config = new(Path.Combine(dataDir, "Config.json")); config.LoadOrCreateDefaultFile(); config.CorrectMixUntilAnonymitySet(); return (uiConfig, config); } private static Global CreateGlobal(string dataDir, UiConfig uiConfig, Config config) { string torLogsFile = Path.Combine(dataDir, "TorLogs.txt"); var walletManager = new WalletManager(config.Network, dataDir, new WalletDirectories(config.Network, dataDir)); return new Global(dataDir, torLogsFile, config, uiConfig, walletManager); } /// <summary> /// Do not call this method it should only be called by TerminateService. /// </summary> private static async Task TerminateApplicationAsync() { if (MainViewModel.Instance is { } mainViewModel) { mainViewModel.ClearStacks(); Logger.LogSoftwareStopped("Wasabi GUI"); } if (Global is { } global) { await global.DisposeAsync().ConfigureAwait(false); } } private static void TaskScheduler_UnobservedTaskException(object? sender, UnobservedTaskExceptionEventArgs? e) { if (e?.Exception is Exception ex) { Logger.LogWarning(ex); } } private static void CurrentDomain_UnhandledException(object? sender, UnhandledExceptionEventArgs? e) { if (e?.ExceptionObject is Exception ex) { Logger.LogWarning(ex); } } // Avalonia configuration, don't remove; also used by visual designer. private static AppBuilder BuildAvaloniaApp() { bool useGpuLinux = true; var result = AppBuilder.Configure(() => new App(Program.Global, async () => await Program.Global.InitializeNoWalletAsync(TerminateService))) .UseReactiveUI(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { result .UseWin32() .UseSkia(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { result.UsePlatformDetect() .UseManagedSystemDialogs<AppBuilder, Window>(); } else { result.UsePlatformDetect(); } return result .With(new Win32PlatformOptions { AllowEglInitialization = true, UseDeferredRendering = true, UseWindowsUIComposition = true }) .With(new X11PlatformOptions { UseGpu = useGpuLinux, WmClass = "Wasabi Wallet" }) .With(new AvaloniaNativePlatformOptions { UseDeferredRendering = true, UseGpu = true }) .With(new MacOSPlatformOptions { ShowInDock = true }); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using NodaTime; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Securities; namespace QuantConnect.Algorithm { public partial class QCAlgorithm { /// <summary> /// Gets or sets the history provider for the algorithm /// </summary> IHistoryProvider IAlgorithm.HistoryProvider { get; set; } /// <summary> /// Gets whether or not this algorithm is still warming up /// </summary> public bool IsWarmingUp { get; private set; } /// <summary> /// Sets the warm up period to the specified value /// </summary> /// <param name="timeSpan">The amount of time to warm up, this does not take into account market hours/weekends</param> public void SetWarmup(TimeSpan timeSpan) { _warmupBarCount = null; _warmupTimeSpan = timeSpan; } /// <summary> /// Sets the warm up period by resolving a start date that would send that amount of data into /// the algorithm. The highest (smallest) resolution in the securities collection will be used. /// For example, if an algorithm has minute and daily data and 200 bars are requested, that would /// use 200 minute bars. /// </summary> /// <param name="barCount">The number of data points requested for warm up</param> public void SetWarmup(int barCount) { _warmupTimeSpan = null; _warmupBarCount = barCount; } /// <summary> /// Sets <see cref="IAlgorithm.IsWarmingUp"/> to false to indicate this algorithm has finished its warm up /// </summary> public void SetFinishedWarmingUp() { IsWarmingUp = false; } /// <summary> /// Gets the history requests required for provide warm up data for the algorithm /// </summary> /// <returns></returns> public IEnumerable<HistoryRequest> GetWarmupHistoryRequests() { if (_warmupBarCount.HasValue) { return CreateBarCountHistoryRequests(Securities.Keys, _warmupBarCount.Value); } if (_warmupTimeSpan.HasValue) { var end = UtcTime.ConvertFromUtc(TimeZone); return CreateDateRangeHistoryRequests(Securities.Keys, end - _warmupTimeSpan.Value, end); } // if not warmup requested return nothing return Enumerable.Empty<HistoryRequest>(); } /// <summary> /// Get the history for all configured securities over the requested span. /// This will use the resolution and other subscription settings for each security. /// The symbols must exist in the Securities collection. /// </summary> /// <param name="span">The span over which to request data. This is a calendar span, so take into consideration weekends and such</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns> public IEnumerable<Slice> History(TimeSpan span, Resolution? resolution = null) { return History(Securities.Keys, Time - span, Time, resolution); } /// <summary> /// Get the history for all configured securities over the requested span. /// This will use the resolution and other subscription settings for each security. /// The symbols must exist in the Securities collection. /// </summary> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing data over the most recent span for all configured securities</returns> public IEnumerable<Slice> History(int periods, Resolution? resolution = null) { return History(Securities.Keys, periods, resolution); } /// <summary> /// Gets the historical data for all symbols of the requested type over the requested span. /// The symbol's configured values for resolution and fill forward behavior will be used /// The symbols must exist in the Securities collection. /// </summary> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<DataDictionary<T>> History<T>(TimeSpan span, Resolution? resolution = null) where T : BaseData { return History<T>(Securities.Keys, span, resolution); } /// <summary> /// Gets the historical data for the specified symbols over the requested span. /// The symbols must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbols</typeparam> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null) where T : BaseData { return History<T>(symbols, Time - span, Time, resolution); } /// <summary> /// Gets the historical data for the specified symbols. The exact number of bars will be returned for /// each symbol. This may result in some data start earlier/later than others due to when various /// exchanges are open. The symbols must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbols</typeparam> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null) where T : BaseData { var requests = symbols.Select(x => { var security = Securities[x]; // don't make requests for symbols of the wrong type if (!typeof(T).IsAssignableFrom(security.SubscriptionDataConfig.Type)) return null; Resolution? res = resolution ?? security.Resolution; var start = GetStartTimeAlgoTz(x, periods, resolution).ConvertToUtc(TimeZone); return CreateHistoryRequest(security, start, UtcTime.RoundDown(res.Value.ToTimeSpan()), resolution); }); return History(requests.Where(x => x != null)).Get<T>(); } /// <summary> /// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbols</typeparam> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<DataDictionary<T>> History<T>(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null) where T : BaseData { var requests = symbols.Select(x => { var security = Securities[x]; // don't make requests for symbols of the wrong type if (!typeof (T).IsAssignableFrom(security.SubscriptionDataConfig.Type)) return null; return CreateHistoryRequest(security, start, end, resolution); }); return History(requests.Where(x => x != null)).Get<T>(); } /// <summary> /// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbol</typeparam> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<T> History<T>(Symbol symbol, TimeSpan span, Resolution? resolution = null) where T : BaseData { return History<T>(symbol, Time - span, Time, resolution); } /// <summary> /// Gets the historical data for the specified symbol. The exact number of bars will be returned. /// The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<TradeBar> History(Symbol symbol, int periods, Resolution? resolution = null) { var security = Securities[symbol]; var start = GetStartTimeAlgoTz(symbol, periods, resolution); return History(new[] {symbol}, start, Time.RoundDown((resolution ?? security.Resolution).ToTimeSpan()), resolution).Get(symbol); } /// <summary> /// Gets the historical data for the specified symbol. The exact number of bars will be returned. /// The symbol must exist in the Securities collection. /// </summary> /// <typeparam name="T">The data type of the symbol</typeparam> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<T> History<T>(Symbol symbol, int periods, Resolution? resolution = null) where T : BaseData { if (resolution == Resolution.Tick) throw new ArgumentException("History functions that accept a 'periods' parameter can not be used with Resolution.Tick"); var security = Securities[symbol]; // verify the types match var actualType = security.SubscriptionDataConfig.Type; var requestedType = typeof(T); if (!requestedType.IsAssignableFrom(actualType)) { throw new ArgumentException("The specified security is not of the requested type. Symbol: " + symbol + " Requested Type: " + requestedType.Name + " Actual Type: " + actualType); } var start = GetStartTimeAlgoTz(symbol, periods, resolution); return History<T>(symbol, start, Time.RoundDown((resolution ?? security.Resolution).ToTimeSpan()), resolution); } /// <summary> /// Gets the historical data for the specified symbol between the specified dates. The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<T> History<T>(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null) where T : BaseData { var security = Securities[symbol]; // verify the types match var actualType = security.SubscriptionDataConfig.Type; var requestedType = typeof(T); if (!requestedType.IsAssignableFrom(actualType)) { throw new ArgumentException("The specified security is not of the requested type. Symbol: " + symbol + " Requested Type: " + requestedType.Name + " Actual Type: " + actualType); } var request = CreateHistoryRequest(security, start, end, resolution); return History(request).Get<T>(symbol); } /// <summary> /// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<TradeBar> History(Symbol symbol, TimeSpan span, Resolution? resolution = null) { return History(new[] {symbol}, span, resolution).Get(symbol); } /// <summary> /// Gets the historical data for the specified symbol over the request span. The symbol must exist in the Securities collection. /// </summary> /// <param name="symbol">The symbol to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<TradeBar> History(Symbol symbol, DateTime start, DateTime end, Resolution? resolution = null) { return History(new[] {symbol}, start, end, resolution).Get(symbol); } /// <summary> /// Gets the historical data for the specified symbols over the requested span. /// The symbol's configured values for resolution and fill forward behavior will be used /// The symbols must exist in the Securities collection. /// </summary> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="span">The span over which to retrieve recent historical data</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, TimeSpan span, Resolution? resolution = null) { return History(symbols, Time - span, Time, resolution); } /// <summary> /// Gets the historical data for the specified symbols. The exact number of bars will be returned for /// each symbol. This may result in some data start earlier/later than others due to when various /// exchanges are open. The symbols must exist in the Securities collection. /// </summary> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="periods">The number of bars to request</param> /// <param name="resolution">The resolution to request</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null) { if (resolution == Resolution.Tick) throw new ArgumentException("History functions that accept a 'periods' parameter can not be used with Resolution.Tick"); return History(CreateBarCountHistoryRequests(symbols, periods, resolution)); } /// <summary> /// Gets the historical data for the specified symbols between the specified dates. The symbols must exist in the Securities collection. /// </summary> /// <param name="symbols">The symbols to retrieve historical data for</param> /// <param name="start">The start time in the algorithm's time zone</param> /// <param name="end">The end time in the algorithm's time zone</param> /// <param name="resolution">The resolution to request</param> /// <param name="fillForward">True to fill forward missing data, false otherwise</param> /// <param name="extendedMarket">True to include extended market hours data, false otherwise</param> /// <returns>An enumerable of slice containing the requested historical data</returns> public IEnumerable<Slice> History(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarket = null) { return History(CreateDateRangeHistoryRequests(symbols, start, end, resolution, fillForward, extendedMarket)); } /// <summary> /// Gets the start time required for the specified bar count in terms of the algorithm's time zone /// </summary> private DateTime GetStartTimeAlgoTz(Symbol symbol, int periods, Resolution? resolution = null) { var security = Securities[symbol]; var timeSpan = (resolution ?? security.Resolution).ToTimeSpan(); // make this a minimum of one second timeSpan = timeSpan < QuantConnect.Time.OneSecond ? QuantConnect.Time.OneSecond : timeSpan; var localStartTime = QuantConnect.Time.GetStartTimeForTradeBars(security.Exchange.Hours, UtcTime.ConvertFromUtc(security.Exchange.TimeZone), timeSpan, periods, security.IsExtendedMarketHours); return localStartTime.ConvertTo(security.Exchange.TimeZone, TimeZone); } /// <summary> /// Executes the specified history request /// </summary> /// <param name="request">the history request to execute</param> /// <returns>An enumerable of slice satisfying the specified history request</returns> public IEnumerable<Slice> History(HistoryRequest request) { return History(new[] {request}); } /// <summary> /// Executes the specified history requests /// </summary> /// <param name="requests">the history requests to execute</param> /// <returns>An enumerable of slice satisfying the specified history request</returns> public IEnumerable<Slice> History(IEnumerable<HistoryRequest> requests) { return History(requests, TimeZone); } private IEnumerable<Slice> History(IEnumerable<HistoryRequest> requests, DateTimeZone timeZone) { var sentMessage = false; var reqs = requests.ToList(); foreach (var request in reqs) { // prevent future requests if (request.EndTimeUtc > UtcTime) { request.EndTimeUtc = UtcTime; if (request.StartTimeUtc > request.EndTimeUtc) { request.StartTimeUtc = request.EndTimeUtc; } if (!sentMessage) { sentMessage = true; Debug("Request for future history modified to end now."); } } } // filter out future data to prevent look ahead bias return ((IAlgorithm) this).HistoryProvider.GetHistory(reqs, timeZone); } /// <summary> /// Helper method to create history requests from a date range /// </summary> private IEnumerable<HistoryRequest> CreateDateRangeHistoryRequests(IEnumerable<Symbol> symbols, DateTime start, DateTime end, Resolution? resolution = null, bool? fillForward = null, bool? extendedMarket = null) { return symbols.Select(x => { var security = Securities[x]; var request = CreateHistoryRequest(security, start, end, resolution); // apply overrides Resolution? res = resolution ?? security.Resolution; if (fillForward.HasValue) request.FillForwardResolution = fillForward.Value ? res : null; if (extendedMarket.HasValue) request.IncludeExtendedMarketHours = extendedMarket.Value; return request; }); } /// <summary> /// Helper methods to create a history request for the specified symbols and bar count /// </summary> private IEnumerable<HistoryRequest> CreateBarCountHistoryRequests(IEnumerable<Symbol> symbols, int periods, Resolution? resolution = null) { return symbols.Select(x => { var security = Securities[x]; Resolution? res = resolution ?? security.Resolution; var start = GetStartTimeAlgoTz(x, periods, res).ConvertToUtc(security.Exchange.TimeZone); return CreateHistoryRequest(security, start, UtcTime.RoundDown(res.Value.ToTimeSpan()), resolution); }); } private HistoryRequest CreateHistoryRequest(Security security, DateTime start, DateTime end, Resolution? resolution) { resolution = resolution ?? security.Resolution; var request = new HistoryRequest(security, start.ConvertToUtc(TimeZone), end.ConvertToUtc(TimeZone)) { Resolution = resolution.Value, FillForwardResolution = security.IsFillDataForward ? resolution : null }; return request; } } }
using System; using System.Collections.Generic; using System.Data; using System.Web.UI.WebControls; using SRP_DAL; using SRPApp.Classes; using GRA.SRP.ControlRooms; using GRA.SRP.Core.Utilities; using GRA.SRP.Utilities; namespace GRA.SRP.ControlRoom.Modules.Security { public partial class GroupsAddEdit : BaseControlRoomPage { protected void Page_Load(object sender, EventArgs e) { MasterPage.IsSecure = true; MasterPage.PageTitle = "SRP - Add / Edit User Groups"; ControlRoomAccessPermission.CheckControlRoomAccessPermission(1000); // User Security; if (!IsPostBack) { List<RibbonPanel> moduleRibbonPanels = StandardModuleRibbons.SecurityRibbon(); foreach (var moduleRibbonPanel in moduleRibbonPanels) { MasterPage.PageRibbon.Add(moduleRibbonPanel); } MasterPage.PageRibbon.DataBind(); } if (!IsPostBack ) { lblGID.Text = Session["GID"] == null ? "" : Session["GID"].ToString(); //Session["GID"]= string.Empty; //lblGID.Text = Request["PK"]; dv.ChangeMode(lblGID.Text.Length == 0 ? DetailsViewMode.Insert : DetailsViewMode.Edit); } } protected void DvItemCommand(object sender, DetailsViewCommandEventArgs e) { string returnURL = "~/ControlRoom/Modules/Security/GroupsList.aspx"; if (e.CommandName.ToLower() == "back") { Response.Redirect(returnURL); } if (e.CommandName.ToLower() == "refresh") { try { odsSRPGroups.DataBind(); dv.DataBind(); dv.ChangeMode(DetailsViewMode.Edit); MasterPage.PageMessage = SRPResources.RefreshOK; } catch (Exception ex) { MasterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message); } } if (e.CommandName.ToLower() == "add" || e.CommandName.ToLower() == "addandback") { try { SRPGroup obj = new SRPGroup(); //obj.GID = int.Parse( ((Label)((DetailsView)sender).FindControl(".GID")).Text ); obj.GroupName = ((TextBox)((DetailsView)sender).FindControl("GroupName")).Text; obj.GroupDescription = ((TextBox)((DetailsView)sender).FindControl("GroupDescription")).Text; obj.AddedDate = DateTime.Now; obj.AddedUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username; //"N/A"; // Get from session obj.LastModDate = obj.AddedDate; obj.LastModUser = obj.AddedUser; obj.TenID = (int)CRTenantID; if (obj.IsValid(BusinessRulesValidationMode.INSERT)) { obj.Insert(); if (e.CommandName.ToLower() == "addandback") { Response.Redirect(returnURL); } lblGID.Text = obj.GID.ToString(); odsSRPGroups.DataBind(); dv.DataBind(); dv.ChangeMode(DetailsViewMode.Edit); MasterPage.PageMessage = SRPResources.AddedOK; } else { string message = String.Format(SRPResources.ApplicationError1, "<ul>"); foreach (BusinessRulesValidationMessage m in obj.ErrorCodes) { message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage); } message = string.Format("{0}</ul>", message); MasterPage.PageError = message; } } catch(Exception ex) { MasterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message); } } if (e.CommandName.ToLower() == "save" || e.CommandName.ToLower() == "saveandback") { try { SRPGroup obj = new SRPGroup(); int pk = int.Parse(((DetailsView)sender).Rows[0].Cells[1].Text); obj = SRPGroup.Fetch(pk); obj.GroupName = ((TextBox)((DetailsView)sender).FindControl("GroupName")).Text; obj.GroupDescription = ((TextBox)((DetailsView)sender).FindControl("GroupDescription")).Text; obj.LastModDate = DateTime.Now; obj.LastModUser = ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username; //"N/A"; // Get from session if (obj.IsValid(BusinessRulesValidationMode.UPDATE)) { obj.Update(); SaveUsers((DetailsView)sender, obj); SavePermissions((DetailsView)sender, obj); if (e.CommandName.ToLower() == "saveandback") { Response.Redirect(returnURL); } odsSRPGroups.DataBind(); dv.DataBind(); dv.ChangeMode(DetailsViewMode.Edit); MasterPage.PageMessage = SRPResources.SaveOK; MasterPage.PageMessage = SRPResources.AddedOK; } else { string message = String.Format(SRPResources.ApplicationError1, "<ul>"); foreach (BusinessRulesValidationMessage m in obj.ErrorCodes) { message = string.Format(String.Format("{0}<li>{{0}}</li>", message), m.ErrorMessage); } message = string.Format("{0}</ul>", message); MasterPage.PageError = message; } } catch(Exception ex) { MasterPage.PageError = String.Format(SRPResources.ApplicationError1, ex.Message); } } } protected void SaveUsers(DetailsView dv, SRPGroup obj) { GridView gv = (GridView)dv.FindControl("gvGroupUsers"); string memberUsers= string.Empty; foreach (GridViewRow row in gv.Rows) { if (((CheckBox)row.FindControl("isMember")).Checked) { memberUsers = string.Format("{0},{1}", memberUsers, ((Label)row.FindControl("UID")).Text); } } if (memberUsers.Length > 0) memberUsers = memberUsers.Substring(1, memberUsers.Length - 1); SRPGroup.UpdateMemberUsers(obj.GID, memberUsers, ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username); } protected void SavePermissions(DetailsView dv, SRPGroup obj) { GridView gv = (GridView)dv.FindControl("gvGroupPermissions"); string groupPermissions= string.Empty; foreach (GridViewRow row in gv.Rows) { if (((CheckBox)row.FindControl("isChecked")).Checked) { groupPermissions = string.Format("{0},{1}", groupPermissions, ((Label)row.FindControl("PermissionID")).Text); } } if (groupPermissions.Length > 0) groupPermissions = groupPermissions.Substring(1, groupPermissions.Length - 1); SRPGroup.UpdatePermissions(obj.GID, groupPermissions, ((SRPUser)Session[SessionData.UserProfile.ToString()]).Username); } } }
#region License // // Copyright (c) 2007-2018, Sean Chambers <schambers80@gmail.com> // Copyright (c) 2010, Nathan Brown // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics; using System.IO; using System.Linq; using FluentMigrator.Expressions; using FluentMigrator.Infrastructure.Extensions; using FluentMigrator.Runner.BatchParser; using FluentMigrator.Runner.BatchParser.Sources; using FluentMigrator.Runner.BatchParser.SpecialTokenSearchers; using FluentMigrator.Runner.Helpers; using FluentMigrator.Runner.Initialization; using FluentMigrator.SqlAnywhere; using JetBrains.Annotations; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace FluentMigrator.Runner.Processors.SqlAnywhere { public class SqlAnywhereProcessor : GenericProcessorBase { [CanBeNull] private readonly IServiceProvider _serviceProvider; //select 1 from sys.syscolumn as c inner join sys.systable as t on t.table_id = c.table_id where t.table_name = '{0}' and c.column_name = '{1}' private const string SCHEMA_EXISTS = "SELECT 1 WHERE EXISTS (SELECT * FROM sys.sysuserperm WHERE user_name = '{0}') "; private const string TABLE_EXISTS = "SELECT 1 WHERE EXISTS (SELECT t.* FROM sys.systable AS t INNER JOIN sys.sysuserperm AS up ON up.user_id = t.creator WHERE up.user_name = '{0}' AND t.table_name = '{1}')"; private const string COLUMN_EXISTS = "SELECT 1 WHERE EXISTS (SELECT c.* FROM sys.syscolumn AS c INNER JOIN sys.systable AS t ON t.table_id = c.table_id INNER JOIN sys.sysuserperm AS up ON up.user_id = t.creator WHERE up.user_name = '{0}' AND t.table_name = '{1}' AND c.column_name = '{2}')"; private const string CONSTRAINT_EXISTS = "SELECT 1 WHERE EXISTS (SELECT c.* FROM sys.sysconstraint AS c INNER JOIN sys.systable AS t ON t.object_id = c.table_object_id INNER JOIN sys.sysuserperm AS up ON up.user_id = t.creator WHERE up.user_name = '{0}' AND t.table_name = '{1}' AND c.constraint_name = '{2}')"; private const string INDEX_EXISTS = "SELECT 1 WHERE EXISTS (SELECT i.* FROM sys.sysindex AS i INNER JOIN sys.systable AS t ON t.table_id = i.table_id INNER JOIN sys.sysuserperm AS up ON up.user_id = t.creator WHERE i.index_name = '{0}' AND up.user_name = '{1}' AND t.table_name = '{2}')"; private const string SEQUENCES_EXISTS = "SELECT 1 WHERE EXISTS (SELECT s.* FROM sys.syssequence AS s INNER JOIN sys.sysuserperm AS up ON up.user_id = s.owner WHERE up.user_name = '{0}' AND s.sequence_name = '{1}' )"; private const string DEFAULTVALUE_EXISTS = "SELECT 1 WHERE EXISTS (SELECT c.* FROM sys.syscolumn AS c INNER JOIN sys.systable AS t ON t.table_id = c.table_id INNER JOIN sys.sysuserperm AS up ON up.user_id = t.creator WHERE up.user_name = '{0}' AND t.table_name = '{1}' AND c.column_name = '{2}' AND c.default LIKE '{3}')"; public override string DatabaseType { get; } public override IList<string> DatabaseTypeAliases { get; } = new List<string> { "SqlAnywhere" }; [Obsolete] public SqlAnywhereProcessor(string databaseType, IDbConnection connection, IMigrationGenerator generator, IAnnouncer announcer, IMigrationProcessorOptions options, IDbFactory factory) : base(connection, factory, generator, announcer, options) { DatabaseType = databaseType; } protected SqlAnywhereProcessor( [NotNull] string databaseType, [NotNull] Func<DbProviderFactory> factoryAccessor, [NotNull] IMigrationGenerator generator, [NotNull] ILogger logger, [NotNull] IOptionsSnapshot<ProcessorOptions> options, [NotNull] IConnectionStringAccessor connectionStringAccessor, [NotNull] IServiceProvider serviceProvider) : base(factoryAccessor, generator, logger, options.Value, connectionStringAccessor) { _serviceProvider = serviceProvider; DatabaseType = databaseType; } private static string SafeSchemaName(string schemaName) { return string.IsNullOrEmpty(schemaName) ? "dbo" : FormatHelper.FormatSqlEscape(schemaName); } public override bool SchemaExists(string schemaName) { return Exists(SCHEMA_EXISTS, SafeSchemaName(schemaName)); } public override bool TableExists(string schemaName, string tableName) { try { return Exists(TABLE_EXISTS, SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName)); } catch (Exception e) { Console.WriteLine(e); } return false; } public override bool ColumnExists(string schemaName, string tableName, string columnName) { return Exists(COLUMN_EXISTS, SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(columnName)); } public override bool ConstraintExists(string schemaName, string tableName, string constraintName) { return Exists(CONSTRAINT_EXISTS, SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(constraintName)); } public override bool IndexExists(string schemaName, string tableName, string indexName) { return Exists(INDEX_EXISTS, FormatHelper.FormatSqlEscape(indexName), SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName)); } public override bool SequenceExists(string schemaName, string sequenceName) { return Exists(SEQUENCES_EXISTS, SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(sequenceName)); } public override bool DefaultValueExists(string schemaName, string tableName, string columnName, object defaultValue) { string defaultValueAsString = $"%{FormatHelper.FormatSqlEscape(defaultValue.ToString())}%"; return Exists(DEFAULTVALUE_EXISTS, SafeSchemaName(schemaName), FormatHelper.FormatSqlEscape(tableName), FormatHelper.FormatSqlEscape(columnName), defaultValueAsString); } public override void Process(CreateSchemaExpression expression) { var password = expression.GetAdditionalFeature(SqlAnywhereExtensions.SchemaPassword, string.Empty); if (string.IsNullOrEmpty(password)) throw new Exception("Create schema requires connection for the schema user. No password specified in CreateSchemaExpression."); if (!Exists("SELECT count(*) FROM \"dbo\".\"syslogins\" WHERE \"name\"='{0}'", FormatHelper.FormatSqlEscape(expression.SchemaName))) { // Try to automatically generate the user Logger.LogSay($"Creating user {expression.SchemaName}."); Execute("CREATE USER \"{0}\" IDENTIFIED BY \"{1}\"", expression.SchemaName, password); } var sql = Generator.Generate(expression); string connectionString = ReplaceUserIdAndPasswordInConnectionString(expression.SchemaName, password); Logger.LogSay($"Creating connection for user {expression.SchemaName} to create schema."); IDbConnection connection; if (DbProviderFactory == null) { #pragma warning disable 612 connection = Factory.CreateConnection(connectionString); #pragma warning restore 612 } else { connection = DbProviderFactory.CreateConnection(); Debug.Assert(connection != null, nameof(connection) + " != null"); connection.ConnectionString = connectionString; } EnsureConnectionIsOpen(connection); Logger.LogSay("Beginning out of scope transaction to create schema."); var transaction = connection.BeginTransaction(); try { ExecuteNonQuery(connection, transaction, sql); transaction.Commit(); Logger.LogSay("Out of scope transaction to create schema committed."); } catch { transaction.Rollback(); Logger.LogSay("Out of scope transaction to create schema rolled back."); throw; } finally { transaction?.Dispose(); connection.Dispose(); } } private string ReplaceUserIdAndPasswordInConnectionString(string userId, string password) { #pragma warning disable 618, 612 var csb = new DbConnectionStringBuilder { ConnectionString = ConnectionString }; #pragma warning restore 618, 612 var uidKey = new[] { "uid", "userid" }.FirstOrDefault(x => csb.ContainsKey(x)) ?? "uid"; var pwdKey = new[] { "pwd", "password" }.FirstOrDefault(x => csb.ContainsKey(x)) ?? "pwd"; csb[uidKey] = userId; csb[pwdKey] = password; return csb.ConnectionString; } public override void Execute(string template, params object[] args) { Process(string.Format(template, args)); } public override bool Exists(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = CreateCommand(string.Format(template, args))) { var result = command.ExecuteScalar(); return DBNull.Value != result && Convert.ToInt32(result) != 0; } } public override DataSet ReadTableData(string schemaName, string tableName) { return Read("SELECT * FROM [{0}].[{1}]", SafeSchemaName(schemaName), tableName); } public override DataSet Read(string template, params object[] args) { EnsureConnectionIsOpen(); using (var command = CreateCommand(string.Format(template, args))) using (var reader = command.ExecuteReader()) { return reader.ReadDataSet(); } } protected override void Process(string sql) { Logger.LogSql(sql); if (Options.PreviewOnly || string.IsNullOrEmpty(sql)) return; EnsureConnectionIsOpen(); if (ContainsGo(sql)) { ExecuteBatchNonQuery(sql); } else { ExecuteNonQuery(Connection, Transaction, sql); } } private bool ContainsGo(string sql) { var containsGo = false; var parser = _serviceProvider?.GetService<SqlAnywhereBatchParser>() ?? new SqlAnywhereBatchParser(); parser.SpecialToken += (sender, args) => containsGo = true; using (var source = new TextReaderSource(new StringReader(sql), true)) { parser.Process(source); } return containsGo; } private void EnsureConnectionIsOpen(IDbConnection connection) { if (connection.State != ConnectionState.Open) connection.Open(); } private void ExecuteNonQuery(IDbConnection connection, IDbTransaction transaction, string sql) { using (var command = CreateCommand(sql, connection, transaction)) { try { command.ExecuteNonQuery(); } catch (Exception ex) { using (var message = new StringWriter()) { message.WriteLine("An error occured executing the following sql:"); message.WriteLine(sql); message.WriteLine("The error was {0}", ex.Message); throw new Exception(message.ToString(), ex); } } } } private void ExecuteBatchNonQuery(string sql) { var sqlBatch = string.Empty; try { var parser = _serviceProvider?.GetService<SqlAnywhereBatchParser>() ?? new SqlAnywhereBatchParser(); parser.SqlText += (sender, args) => { sqlBatch = args.SqlText.Trim(); }; parser.SpecialToken += (sender, args) => { if (string.IsNullOrEmpty(sqlBatch)) return; if (args.Opaque is GoSearcher.GoSearcherParameters goParams) { using (var command = CreateCommand(sqlBatch)) { for (var i = 0; i != goParams.Count; ++i) { command.ExecuteNonQuery(); } } } sqlBatch = null; }; using (var source = new TextReaderSource(new StringReader(sql), true)) { parser.Process(source, stripComments: Options.StripComments); } if (!string.IsNullOrEmpty(sqlBatch)) { using (var command = CreateCommand(sqlBatch)) { command.ExecuteNonQuery(); } } } catch (Exception ex) { using (var message = new StringWriter()) { message.WriteLine("An error occured executing the following sql:"); message.WriteLine(string.IsNullOrEmpty(sqlBatch) ? sql : sqlBatch); message.WriteLine("The error was {0}", ex.Message); throw new Exception(message.ToString(), ex); } } } public override void Process(PerformDBOperationExpression expression) { Logger.LogSay("Performing DB Operation"); if (Options.PreviewOnly) return; EnsureConnectionIsOpen(); expression.Operation?.Invoke(Connection, Transaction); } } }
//------------------------------------------------------------------------------ // Copyright (c) 2014-2016 the original author or authors. All Rights Reserved. // // NOTICE: You are permitted to use, modify, and distribute this file // in accordance with the terms of the license agreement accompanying it. //------------------------------------------------------------------------------ using System; using Robotlegs.Bender.Framework.Impl; namespace Robotlegs.Bender.Framework.API { public interface IContext : IPinEvent, ILifecycleEvent { /// <summary> /// The injection binder this context relies on. Use this to bind and unbind anything you require /// </summary> /// <value>The injection binder.</value> IInjector injector { get; } /// <summary> /// Gets or sets the current log level /// </summary> /// <value>The log level</value> LogLevel LogLevel {get;set;} /// <summary> /// Is this context uninitialized? /// </summary> bool Uninitialized { get; } /// <summary> /// Is this context initialized? /// </summary> bool Initialized { get; } /// <summary> /// Is this context active? /// </summary> bool Active { get; } /// <summary> /// Is this context suspended? /// </summary> bool Suspended { get; } /// <summary> /// Has this context been destroyed? /// </summary> bool Destroyed { get; } /// <summary> /// Will initialized the context. Doing so will /// - Fire the pre initilize callbacks /// - Process all the configs that have been added /// - Fire the post initilize callbacks /// </summary> /// <param name="callback">Initialization callback</param> IContext Initialize(Action callback = null); /// <summary> /// Suspends this context /// </summary> /// <param name="callback">Suspension callback.</param> IContext Suspend (Action callback = null); /// <summary> /// Suspends this context (if active). /// </summary> /// <param name="callback">Resume callback.</param> IContext Resume (Action callback = null); /// <summary> /// Destroys this context (if alive) /// </summary> /// <param name="callback">Destruction callback.</param> IContext Destroy (Action callback = null); /// <summary> /// Installs custom extensions or bundles into the context /// </summary> /// <typeparam name="T">IExtension class</typeparam> IContext Install<T>() where T : IExtension; /// <summary> /// Installs custom extensions or bundles into the context /// </summary> /// <param name="type">Type with an 'Extend(IContext context)' method signature</param> IContext Install (Type type); /// <summary> /// Installs custom extensions or bundles into the context /// </summary> /// <param name="extension">IExtension instance</param> IContext Install (IExtension extension); /// <summary> /// Configures the context with custom configurations /// </summary> /// <typeparam name="T">Configuration class</typeparam> IContext Configure<T>() where T : class; /// <summary> /// Configures the context with custom configurations /// </summary> /// <param name="objects">Configuration objects</param> IContext Configure(params object[] objects); /// <summary> /// A handler to run before the context is initialized. This is before the configs have been processed /// </summary> /// <returns>This</returns> /// <param name="callback">Callback to fire</param> IContext BeforeInitializing (Action callback); /// <summary> /// A handler to run before the context is initialized. This is before the configs have been processed /// </summary> /// <returns>This</returns> /// <param name="handler">Handler to fire</param> IContext BeforeInitializing (HandlerMessageDelegate handler); /// <summary> /// A asynchronous handler to run before the context is initialized. This is before the configs have been processed /// </summary> /// <returns>This</returns> /// <param name="handler">Handler to fire, you must fire the callback given to the hander to continue initialization</param> IContext BeforeInitializing (HandlerMessageCallbackDelegate handler); /// <summary> /// A handler to run during initialization /// </summary> /// <returns>The initializing.</returns> /// <param name="callback">Initialization callback</param> IContext WhenInitializing (Action callback); /// <summary> /// A handler to run after initialization /// </summary> /// <returns>The initializing.</returns> /// <param name="callback">Post-initialize callback</param> IContext AfterInitializing (Action callback); /// <summary> /// A handler to run before the target object is suspended /// </summary> /// <returns>This</returns> /// <param name="callback">Callback to fire</param> IContext BeforeSuspending (Action callback); /// <summary> /// A handler to run before the target object is suspended /// </summary> /// <returns>This</returns> /// <param name="handler">Handler to fire</param> IContext BeforeSuspending (HandlerMessageDelegate handler); /// <summary> /// A asynchronous handler to run before the target object is suspended /// </summary> /// <returns>This</returns> /// <param name="handler">Handler to fire, you must fire the callback given to the hander to continue suspension</param> IContext BeforeSuspending (HandlerMessageCallbackDelegate handler); /// <summary> /// A handler to run during suspension /// </summary> /// <returns>This</returns> /// <param name="callback">Suspension callback</param> IContext WhenSuspending (Action callback); /// <summary> /// A handler to run after suspension /// </summary> /// <returns>This</returns> /// <param name="callback">Post suspend callback</param> IContext AfterSuspending (Action callback); /// <summary> /// A handler to run before the context is resumed /// </summary> /// <returns>This</returns> /// <param name="callback">Pre-resume callback</param> IContext BeforeResuming (Action callback); /// <summary> /// A handler to run before the context is resumed /// </summary> /// <returns>Pre-resume handler</returns> IContext BeforeResuming (HandlerMessageDelegate handler); /// <summary> /// A asynchronous handler to run before the context is resumed /// </summary> /// <param name="handler">Handler to fire, you must fire the callback given to the hander to continue resumption</param> IContext BeforeResuming (HandlerMessageCallbackDelegate handler); /// <summary> /// A handler to run before the context is resumed /// </summary> /// <returns>This</returns> /// <param name="callback">Resumption callback</param> IContext WhenResuming (Action callback); /// <summary> /// A handler to run before the context is resumed /// </summary> /// <returns>This</returns> /// <param name="callback">Post resume callback.</param> IContext AfterResuming (Action callback); /// <summary> /// A handler to run before the context is destroyed /// </summary> /// <returns>The destroying.</returns> /// <param name="callback">Pre-destroy callback.</param> IContext BeforeDestroying (Action callback); /// <summary> /// A handler to run before the context is destroyed /// </summary> /// <returns>The destroying.</returns> /// <param name="handler">Handler to fire, you must fire the callback given to the hander to continue destruction</param> IContext BeforeDestroying (HandlerMessageDelegate handler); /// <summary> /// A handler to run before the context is destroyed /// </summary> /// <returns>The destroying.</returns> /// <param name="handler">Pre-destroy handler.</param> IContext BeforeDestroying (HandlerMessageCallbackDelegate handler); /// <summary> /// A handler to run during destruction /// </summary> /// <returns>The destroying.</returns> /// <param name="callback">Destruction callback.</param> IContext WhenDestroying (Action callback); /// <summary> /// A handler to run after destruction /// </summary> /// <returns>The destroying.</returns> /// <param name="callback">Post destroy callback.</param> IContext AfterDestroying(Action callback); /// <summary> /// Adds a config match and handler for processing configs. /// Generally you would call this from an extension to add more functionality to your configs if needed /// </summary> /// <returns>The config handler.</returns> /// <param name="matcher">The matching conditions run on all configs</param> /// <param name="handler">The process match function to run when the match has succeded on a config</param> IContext AddConfigHandler(IMatcher matcher, Action<object> handler); /// <summary> /// Retrieves a logger for a given source /// </summary> /// <returns>this</returns> /// <param name="source">Logging source</param> ILogging GetLogger(Object source); /// <summary> /// Adds a custom log target /// </summary> /// <returns>this</returns> /// <param name="target">Log Target</param> IContext AddLogTarget(ILogTarget target); /// <summary> /// Pins instances in memory /// </summary> /// <param name="instances">Instances to pin</param> IContext Detain (params object[] instances); /// <summary> /// Unpins instances from memory /// </summary> /// <param name="instances">Instances to unpin</param> IContext Release (params object[] instances); /// <summary> /// Adds an uninitialized context as a child. /// <para>This setups up an injection chain.</para> /// </summary> /// <returns>This</returns> /// <param name="child">The context to add as a child</param> IContext AddChild(IContext child); /// <summary> /// Removes a child context from this context /// </summary> /// <returns>This</returns> /// <param name="child">The child context to remove</param> IContext RemoveChild(IContext child); } }
// // ListView_DragAndDrop.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; namespace Hyena.Data.Gui { public static class ListViewDragDropTarget { public enum TargetType { ModelSelection } public static readonly TargetEntry ModelSelection = new TargetEntry ("application/x-hyena-data-model-selection", TargetFlags.App, (uint)TargetType.ModelSelection); } public partial class ListView<T> : ListViewBase { private static TargetEntry [] drag_drop_dest_entries = new TargetEntry [] { ListViewDragDropTarget.ModelSelection }; protected virtual TargetEntry [] DragDropDestEntries { get { return drag_drop_dest_entries; } } protected virtual TargetEntry [] DragDropSourceEntries { get { return drag_drop_dest_entries; } } private bool is_reorderable = false; public bool IsReorderable { get { return is_reorderable && IsEverReorderable; } set { is_reorderable = value; OnDragSourceSet (); OnDragDestSet (); } } private bool is_ever_reorderable = false; public bool IsEverReorderable { get { return is_ever_reorderable; } set { is_ever_reorderable = value; OnDragSourceSet (); OnDragDestSet (); } } private bool force_drag_source_set = false; protected bool ForceDragSourceSet { get { return force_drag_source_set; } set { force_drag_source_set = true; OnDragSourceSet (); } } private bool force_drag_dest_set = false; protected bool ForceDragDestSet { get { return force_drag_dest_set; } set { force_drag_dest_set = true; OnDragDestSet (); } } protected virtual void OnDragDestSet () { if (ForceDragDestSet || IsReorderable) { Gtk.Drag.DestSet (this, DestDefaults.All, DragDropDestEntries, Gdk.DragAction.Move); } else { Gtk.Drag.DestUnset (this); } } protected virtual void OnDragSourceSet () { if (ForceDragSourceSet || IsReorderable) { Gtk.Drag.SourceSet (this, Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask, DragDropSourceEntries, Gdk.DragAction.Copy | Gdk.DragAction.Move); } else { Gtk.Drag.SourceUnset (this); } } private uint drag_scroll_timeout_id; private uint drag_scroll_timeout_duration = 50; private double drag_scroll_velocity; private double drag_scroll_velocity_max = 100.0; private int drag_reorder_row_index = -1; private int drag_reorder_motion_y = -1; private void StopDragScroll () { drag_scroll_velocity = 0.0; if (drag_scroll_timeout_id > 0) { GLib.Source.Remove (drag_scroll_timeout_id); drag_scroll_timeout_id = 0; } } private void OnDragScroll (GLib.TimeoutHandler handler, double threshold, int total, int position) { if (position < threshold) { drag_scroll_velocity = -1.0 + (position / threshold); } else if (position > total - threshold) { drag_scroll_velocity = 1.0 - ((total - position) / threshold); } else { StopDragScroll (); return; } if (drag_scroll_timeout_id == 0) { drag_scroll_timeout_id = GLib.Timeout.Add (drag_scroll_timeout_duration, handler); } } protected override bool OnDragMotion (Gdk.DragContext context, int x, int y, uint time) { if (!IsReorderable) { StopDragScroll (); drag_reorder_row_index = -1; drag_reorder_motion_y = -1; InvalidateList (); return false; } drag_reorder_motion_y = y; DragReorderUpdateRow (); OnDragScroll (OnDragVScrollTimeout, Allocation.Height * 0.3, Allocation.Height, y); return true; } protected override void OnDragLeave (Gdk.DragContext context, uint time) { StopDragScroll (); } protected override void OnDragEnd (Gdk.DragContext context) { StopDragScroll (); drag_reorder_row_index = -1; drag_reorder_motion_y = -1; InvalidateList (); } private bool OnDragVScrollTimeout () { ScrollToY (VadjustmentValue + (drag_scroll_velocity * drag_scroll_velocity_max)); DragReorderUpdateRow (); return true; } private void DragReorderUpdateRow () { int row = GetDragRow (drag_reorder_motion_y); if (row != drag_reorder_row_index) { drag_reorder_row_index = row; InvalidateList (); } } protected int GetDragRow (int y) { y = TranslateToListY (y); int row = GetModelRowAt (0, y); if (row == -1) { return -1; } if (row != GetModelRowAt (0, y + ChildSize.Height / 2)) { row++; } return row; } } }
// 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.Text; using System.Xml; using System.Reflection; using System.Collections; using System.IO; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>; namespace System.Runtime.Serialization.Json { #if NET_NATIVE public class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex #else internal class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex #endif { private DataContractJsonSerializer _jsonSerializer; private EmitTypeInformation _emitXsiType; private bool _perCallXsiTypeAlreadyEmitted; private bool _useSimpleDictionaryFormat; public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) : base(null, int.MaxValue, new StreamingContext(), true) { _jsonSerializer = serializer; this.rootTypeDataContract = rootTypeDataContract; this.serializerKnownTypeList = serializer.knownTypeList; } internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) { return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract); } internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract) { return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract); } internal XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract) : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false) { _emitXsiType = serializer.EmitTypeInformation; this.rootTypeDataContract = rootTypeDataContract; this.serializerKnownTypeList = serializer.knownTypeList; this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes; _useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat; } internal IList<Type> SerializerKnownTypeList { get { return this.serializerKnownTypeList; } } public bool UseSimpleDictionaryFormat { get { return _useSimpleDictionaryFormat; } } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, string clrTypeName, string clrAssemblyName) { return false; } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { //Noop } protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) { if (_emitXsiType != EmitTypeInformation.Never) { if (string.IsNullOrEmpty(dataContractNamespace)) { WriteTypeInfo(writer, dataContractName); } else { WriteTypeInfo(writer, string.Concat(dataContractName, JsonGlobals.NameValueSeparatorString, TruncateDefaultDataContractNamespace(dataContractNamespace))); } } } internal static string TruncateDefaultDataContractNamespace(string dataContractNamespace) { if (!string.IsNullOrEmpty(dataContractNamespace)) { if (dataContractNamespace[0] == '#') { return string.Concat("\\", dataContractNamespace); } else if (dataContractNamespace[0] == '\\') { return string.Concat("\\", dataContractNamespace); } else if (dataContractNamespace.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal)) { return string.Concat("#", dataContractNamespace.Substring(JsonGlobals.DataContractXsdBaseNamespaceLength)); } } return dataContractNamespace; } protected override bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract) { if (!((object.ReferenceEquals(contract.Name, declaredContract.Name) && object.ReferenceEquals(contract.Namespace, declaredContract.Namespace)) || (contract.Name.Value == declaredContract.Name.Value && contract.Namespace.Value == declaredContract.Namespace.Value)) && (contract.UnderlyingType != Globals.TypeOfObjectArray) && (_emitXsiType != EmitTypeInformation.Never)) { // We always deserialize collections assigned to System.Object as object[] // Because of its common and JSON-specific nature, // we don't want to validate known type information for object[] // Don't validate known type information when emitXsiType == Never because // known types are not used without type information in the JSON if (RequiresJsonTypeInfo(contract)) { _perCallXsiTypeAlreadyEmitted = true; WriteTypeInfo(writer, contract.Name.Value, contract.Namespace.Value); } else { // check if the declared type is System.Enum and throw because // __type information cannot be written for enums since it results in invalid JSON. // Without __type, the resulting JSON cannot be deserialized since a number cannot be directly assigned to System.Enum. if (declaredContract.UnderlyingType == typeof(Enum)) { throw new SerializationException(SR.Format(SR.EnumTypeNotSupportedByDataContractJsonSerializer, declaredContract.UnderlyingType)); } } // Return true regardless of whether we actually wrote __type information // E.g. We don't write __type information for enums, but we still want verifyKnownType // to be true for them. return true; } return false; } private static bool RequiresJsonTypeInfo(DataContract contract) { return (contract is ClassDataContract); } private void WriteTypeInfo(XmlWriterDelegator writer, string typeInformation) { writer.WriteAttributeString(null, JsonGlobals.serverTypeString, null, typeInformation); } protected override void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { JsonDataContract jsonDataContract = JsonDataContract.GetJsonDataContract(dataContract); if (_emitXsiType == EmitTypeInformation.Always && !_perCallXsiTypeAlreadyEmitted && RequiresJsonTypeInfo(dataContract)) { WriteTypeInfo(xmlWriter, jsonDataContract.TypeName); } _perCallXsiTypeAlreadyEmitted = false; DataContractJsonSerializerImpl.WriteJsonValue(jsonDataContract, xmlWriter, obj, this, declaredTypeHandle); } protected override void WriteNull(XmlWriterDelegator xmlWriter) { DataContractJsonSerializerImpl.WriteJsonNull(xmlWriter); } internal XmlDictionaryString CollectionItemName { get { return JsonGlobals.itemDictionaryString; } } protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { DataContract dataContract; bool verifyKnownType = false; bool isDeclaredTypeInterface = declaredType.IsInterface; if (isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { dataContract = GetDataContract(declaredTypeHandle, declaredType); } else if (declaredType.IsArray) // If declared type is array do not write __serverType. Instead write__serverType for each item { dataContract = GetDataContract(declaredTypeHandle, declaredType); } else { dataContract = GetDataContract(objectTypeHandle, objectType); DataContract declaredTypeContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, declaredType); verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract); HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType); } if (isDeclaredTypeInterface) { VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType); } private void HandleCollectionAssignedToObject(Type declaredType, ref DataContract dataContract, ref object obj, ref bool verifyKnownType) { if ((declaredType != dataContract.UnderlyingType) && (dataContract is CollectionDataContract)) { if (verifyKnownType) { VerifyType(dataContract, declaredType); verifyKnownType = false; } if (((CollectionDataContract)dataContract).Kind == CollectionKind.Dictionary) { // Convert non-generic dictionary to generic dictionary IDictionary dictionaryObj = obj as IDictionary; Dictionary<object, object> genericDictionaryObj = new Dictionary<object, object>(dictionaryObj.Count); // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = dictionaryObj.GetEnumerator(); try { while (e.MoveNext()) { DictionaryEntry entry = e.Entry; genericDictionaryObj.Add(entry.Key, entry.Value); } } finally { (e as IDisposable)?.Dispose(); } obj = genericDictionaryObj; } dataContract = GetDataContract(Globals.TypeOfIEnumerable); } } internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) { bool verifyKnownType = false; Type declaredType = rootTypeDataContract.UnderlyingType; bool isDeclaredTypeInterface = declaredType.IsInterface; if (!(isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType)) && !declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract); HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType); } if (isDeclaredTypeInterface) { VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType); } private void VerifyType(DataContract dataContract, Type declaredType) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (!IsKnownType(dataContract, declaredType)) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)); } if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } } internal static void WriteJsonNameWithMapping(XmlWriterDelegator xmlWriter, XmlDictionaryString[] memberNames, int index) { xmlWriter.WriteStartElement("a", JsonGlobals.itemString, JsonGlobals.itemString); xmlWriter.WriteAttributeString(null, JsonGlobals.itemString, null, memberNames[index].Value); } internal override void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, IDataNode dataNode) { Type dataType = dataNode.DataType; if (dataType == Globals.TypeOfClassDataNode || dataType == Globals.TypeOfISerializableDataNode) { xmlWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString); base.WriteExtensionDataTypeInfo(xmlWriter, dataNode); } else if (dataType == Globals.TypeOfCollectionDataNode) { xmlWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.arrayString); // Don't write __type for collections } else if (dataType == Globals.TypeOfXmlDataNode) { // Don't write type or __type for XML types because we serialize them to strings } else if ((dataType == Globals.TypeOfObject) && (dataNode.Value != null)) { DataContract dc = GetDataContract(dataNode.Value.GetType()); if (RequiresJsonTypeInfo(dc)) { base.WriteExtensionDataTypeInfo(xmlWriter, dataNode); } } } internal static void VerifyObjectCompatibilityWithInterface(DataContract contract, object graph, Type declaredType) { Type contractType = contract.GetType(); if ((contractType == typeof(XmlDataContract)) && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(declaredType)) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlObjectAssignedToIncompatibleInterface, graph.GetType(), declaredType))); } if ((contractType == typeof(CollectionDataContract)) && !CollectionDataContract.IsCollectionInterface(declaredType)) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CollectionAssignedToIncompatibleInterface, graph.GetType(), declaredType))); } } internal void CheckIfTypeNeedsVerifcation(DataContract declaredContract, DataContract runtimeContract) { if (WriteTypeInfo(null, runtimeContract, declaredContract)) { VerifyType(runtimeContract); } } internal void VerifyType(DataContract dataContract) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/); if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } } internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable obj) { Type objType = obj.GetType(); var serInfo = new SerializationInfo(objType, XmlObjectSerializer.FormatterConverter); GetObjectData(obj, serInfo, GetStreamingContext()); if (DataContract.GetClrTypeFullName(objType) != serInfo.FullTypeName) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ChangingFullTypeNameNotSupported, serInfo.FullTypeName, DataContract.GetClrTypeFullName(objType)))); } else { base.WriteSerializationInfo(xmlWriter, objType, serInfo); } } internal static DataContract GetRevisedItemContract(DataContract oldItemContract) { if ((oldItemContract != null) && oldItemContract.UnderlyingType.IsGenericType && (oldItemContract.UnderlyingType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue)) { return DataContract.GetDataContract(oldItemContract.UnderlyingType); } return oldItemContract; } internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = base.GetDataContract(typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { DataContract dataContract = base.GetDataContract(id, typeHandle); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } } }
// // NodeListTests.cs // // Author: // Ventsislav Mladenov <vmladenov.mladenov@gmail.com> // // Copyright (c) 2013 Ventsislav Mladenov // // 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 Microsoft.TeamFoundation.WorkItemTracking.Client.Query; using Xunit; namespace MonoDevelop.VersionControl.TFS.Tests { public class NodeListTests { [Fact] public void RemoveUnUsedBrackets1() { string val = "where (([a] = 2))"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); Console.WriteLine(nodes); Assert.Equal("[a] = 2", nodes.ToString()); } [Fact] public void RemoveUnUsedBrackets2() { string val = "where (([a] = 2) and [b] = @p)"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); Console.WriteLine(nodes); Assert.Equal("( [a] = 2 ) And [b] = @p", nodes.ToString()); } [Fact] public void RemoveUnUsedBrackets3() { string val = "where ([a] = 2) and ([b] = @p)"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); Console.WriteLine(nodes); Assert.Equal("( [a] = 2 ) And ( [b] = @p )", nodes.ToString()); } [Fact] public void RemoveUnUsedBrackets4() { string val = "where (([a] = 2) and (([b] = @p)))"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); Console.WriteLine(nodes); Assert.Equal("( [a] = 2 ) And ( ( [b] = @p ) )", nodes.ToString()); } [Fact] public void GetSubList1() { string val = "where ([a] = 2) and ([b] = @p)"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); var list = nodes.GetSubList(0); Console.WriteLine(list); Assert.Equal("[a] = 2", list.ToString()); } [Fact] public void GetSubList2() { string val = "where (([a] = 2) and [b] = @p)"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); var list = nodes.GetSubList(0); Console.WriteLine(list); Assert.Equal("( [a] = 2 ) And [b] = @p", list.ToString()); } // [Test] // public void CreateHelperGroups1() // { // string val = "where [a] = 2 and [b] = 3 and [c] = 4 or [d] = 5"; // var parser = new LexalParser(val); // var nodes = parser.Process(); // nodes.Optimize(); // nodes.CreateHelperGroups(); // Console.WriteLine(nodes); // Assert.AreEqual("( [a] = 2 And [b] = 3 And [c] = 4 ) Or [d] = 5", nodes.ToString()); // } // // [Test] // public void CreateHelperGroups2() // { // string val = "where [f] = 2 and [a] = 2 or [s] = 1 or [b] = 3 or [x] = 1 and [c] = 4 or [d] = 5"; // var parser = new LexalParser(val); // var nodes = parser.Process(); // nodes.Optimize(); // nodes.CreateHelperGroups(); // Console.WriteLine(nodes); // Assert.AreEqual("( [f] = 2 And [a] = 2 ) Or ( [s] = 1 Or [b] = 3 Or [x] = 1 ) And ( [c] = 4 Or [d] = 5 )", nodes.ToString()); // } // // [Test] // public void CreateHelperGroups3() // { // string val = "where ([f] = 2 and [a] = 2 or [s] = 1) and [b] = 3"; // var parser = new LexalParser(val); // var nodes = parser.Process(); // nodes.Optimize(); // nodes.CreateHelperGroups(); // Console.WriteLine(nodes); // Assert.AreEqual("( ( [f] = 2 And [a] = 2 ) Or [s] = 1 ) And [b] = 3", nodes.ToString()); // } // // [Test] // public void CreateHelperGroups4() // { // string val = "where ([f] = 2 and [a] = 2 or [s] = 1) and ([b] = 3 or [x] = 1)"; // var parser = new LexalParser(val); // var nodes = parser.Process(); // nodes.Optimize(); // nodes.CreateHelperGroups(); // Console.WriteLine(nodes); // Assert.AreEqual("( ( [f] = 2 And [a] = 2 ) Or [s] = 1 ) And ( [b] = 3 Or [x] = 1 )", nodes.ToString()); // } // // [Test] // public void CreateHelperGroups5() // { // string val = "where ([f] = 2 and [a] = 2 or [s] = 1) and ([b] = 3 or [x] = 1 and [s] = 3)"; // var parser = new LexalParser(val); // var nodes = parser.Process(); // nodes.Optimize(); // nodes.CreateHelperGroups(); // Console.WriteLine(nodes); // Assert.AreEqual("( ( [f] = 2 And [a] = 2 ) Or [s] = 1 ) And ( ( [b] = 3 Or [x] = 1 ) And [s] = 3 )", nodes.ToString()); // } [Fact] public void ExtractOperatorForward1() { string val = "where [a] = 2 and [b] = 3 and [c] = 4 or [d] = 5"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); nodes.ExtractOperatorForward(); Console.WriteLine(nodes); Assert.Equal("Or ( And [a] = 2 [b] = 3 [c] = 4 ) [d] = 5", nodes.ToString()); } [Fact] public void ExtractOperatorForward2() { string val = "where ([f] = 2 and [a] = 2 or [s] = 1) and [b] = 3"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); nodes.ExtractOperatorForward(); Console.WriteLine(nodes); Assert.Equal("And ( Or ( And [f] = 2 [a] = 2 ) [s] = 1 ) [b] = 3", nodes.ToString()); } [Fact] public void ExtractOperatorForward3() { string val = "where ([f] = 2 and [a] = 2 or [s] = 1) and ([b] = 3 or [x] = 1 and [s] = 3)"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); nodes.ExtractOperatorForward(); Console.WriteLine(nodes); Assert.Equal("And ( Or ( And [f] = 2 [a] = 2 ) [s] = 1 ) ( And ( Or [b] = 3 [x] = 1 ) [s] = 3 )", nodes.ToString()); } [Fact] public void ExtractOperatorForward4() { string val = "where (([f] = 2 and [a] = 2) or [s] = 1) and ([b] = 3 or ([x] = 1 and [s] = 3))"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); nodes.ExtractOperatorForward(); Console.WriteLine(nodes); Assert.Equal("And ( Or ( And [f] = 2 [a] = 2 ) [s] = 1 ) ( Or [b] = 3 ( And [x] = 1 [s] = 3 ) )", nodes.ToString()); } [Fact] public void ExtractOperatorForward5() { string val = "where ([f] = 2 and [a] = 2) or ([b] = 3 and [x] = 1)"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); nodes.ExtractOperatorForward(); Console.WriteLine(nodes); Assert.Equal("Or ( And [f] = 2 [a] = 2 ) ( And [b] = 3 [x] = 1 )", nodes.ToString()); } [Fact] public void ExtractOperatorForward6() { string val = "where [f] = 2"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); nodes.ExtractOperatorForward(); Console.WriteLine(nodes); Assert.Equal("[f] = 2", nodes.ToString()); } [Fact] public void NodesToXml1() { string val = "where [f] = 2"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); nodes.ExtractOperatorForward(); var xmlTransformer = new NodesToXml(nodes); var output = xmlTransformer.WriteXml(); Console.WriteLine(output); Assert.Equal("<Expression Column=\"f\" FieldType=\"0\" Operator=\"equals\">\r\n <Number>2</Number>\r\n</Expression>", output); } [Fact] public void NodesToXml2() { string val = "where ([f] = 2 and [a] = 2) or ([b] = 3 and [x] = 1)"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); nodes.ExtractOperatorForward(); var xmlTransformer = new NodesToXml(nodes); var output = xmlTransformer.WriteXml(); Console.WriteLine(output); Assert.Equal("<Group GroupOperator=\"Or\">\r\n <Group GroupOperator=\"And\">\r\n <Expression Column=\"f\" FieldType=\"0\" Operator=\"equals\">\r\n <Number>2</Number>\r\n </Expression>\r\n <Expression Column=\"a\" FieldType=\"0\" Operator=\"equals\">\r\n <Number>2</Number>\r\n </Expression>\r\n </Group>\r\n <Group GroupOperator=\"And\">\r\n <Expression Column=\"b\" FieldType=\"0\" Operator=\"equals\">\r\n <Number>3</Number>\r\n </Expression>\r\n <Expression Column=\"x\" FieldType=\"0\" Operator=\"equals\">\r\n <Number>1</Number>\r\n </Expression>\r\n </Group>\r\n</Group>", output); } [Fact] public void NodesToXml3() { string val = "where (([f] = 2 and [a] = 2) or [s] = 1) and ([b] = 3 or ([x] = 1 and [s] = 3))"; var parser = new LexalParser(val); var nodes = parser.ProcessWherePart(); nodes.Optimize(); nodes.ExtractOperatorForward(); var xmlTransformer = new NodesToXml(nodes); var output = xmlTransformer.WriteXml(); Console.WriteLine(output); } } }
// 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.Web.UI.WebControls.TextBox.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.Web.UI.WebControls { public partial class TextBox : WebControl, System.Web.UI.IPostBackDataHandler, System.Web.UI.IEditableTextControl, System.Web.UI.ITextControl { #region Methods and constructors protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer) { } protected override void AddParsedSubObject(Object obj) { } protected virtual new bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { return default(bool); } protected internal override void OnPreRender(EventArgs e) { } protected virtual new void OnTextChanged(EventArgs e) { } protected virtual new void RaisePostDataChangedEvent() { } protected internal override void Render(System.Web.UI.HtmlTextWriter writer) { } protected override Object SaveViewState() { return default(Object); } bool System.Web.UI.IPostBackDataHandler.LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection) { return default(bool); } void System.Web.UI.IPostBackDataHandler.RaisePostDataChangedEvent() { } public TextBox() { } #endregion #region Properties and indexers public virtual new AutoCompleteType AutoCompleteType { get { return default(AutoCompleteType); } set { } } public virtual new bool AutoPostBack { get { return default(bool); } set { } } public virtual new bool CausesValidation { get { return default(bool); } set { } } public virtual new int Columns { get { return default(int); } set { } } public virtual new int MaxLength { get { return default(int); } set { } } public virtual new bool ReadOnly { get { return default(bool); } set { } } public virtual new int Rows { get { return default(int); } set { } } protected override System.Web.UI.HtmlTextWriterTag TagKey { get { return default(System.Web.UI.HtmlTextWriterTag); } } public virtual new string Text { get { return default(string); } set { } } public virtual new TextBoxMode TextMode { get { return default(TextBoxMode); } set { } } public virtual new string ValidationGroup { get { return default(string); } set { } } public virtual new bool Wrap { get { return default(bool); } set { } } #endregion #region Events public event EventHandler TextChanged { add { } remove { } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal struct AidContainer { internal static readonly AidContainer NullAidContainer = default(AidContainer); private enum Kind { None = 0, File, ExternAlias } private object _value; public AidContainer(FileRecord file) { _value = file; } } internal class BSYMMGR { internal HashSet<KAID> bsetGlobalAssemblies; // Assemblies in the global alias. // Special nullable members. public PropertySymbol propNubValue; public MethodSymbol methNubCtor; private SymFactory _symFactory; private MiscSymFactory _miscSymFactory; private NamespaceSymbol _rootNS; // The "root" (unnamed) namespace. // Map from aids to INFILESYMs and EXTERNALIASSYMs protected List<AidContainer> ssetAssembly; // Map from aids to MODULESYMs and OUTFILESYMs protected NameManager m_nameTable; protected SYMTBL tableGlobal; // The hash table for type arrays. protected Dictionary<TypeArrayKey, TypeArray> tableTypeArrays; private InputFile _infileUnres; private const int LOG2_SYMTBL_INITIAL_BUCKET_CNT = 13; // Initial local size: 8192 buckets. private static readonly TypeArray s_taEmpty = new TypeArray(Array.Empty<CType>()); public BSYMMGR(NameManager nameMgr, TypeManager typeManager) { this.m_nameTable = nameMgr; this.tableGlobal = new SYMTBL(); _symFactory = new SymFactory(this.tableGlobal, this.m_nameTable); _miscSymFactory = new MiscSymFactory(this.tableGlobal); this.ssetAssembly = new List<AidContainer>(); _infileUnres = new InputFile(); _infileUnres.isSource = false; _infileUnres.SetAssemblyID(KAID.kaidUnresolved); this.ssetAssembly.Add(new AidContainer(_infileUnres)); this.bsetGlobalAssemblies = new HashSet<KAID>(); this.bsetGlobalAssemblies.Add(KAID.kaidThisAssembly); this.tableTypeArrays = new Dictionary<TypeArrayKey, TypeArray>(); _rootNS = _symFactory.CreateNamespace(m_nameTable.Add(""), null); GetNsAid(_rootNS, KAID.kaidGlobal); } public void Init() { /* tableTypeArrays.Init(&this->GetPageHeap(), this->getAlloc()); tableNameToSym.Init(this); nsToExtensionMethods.Init(this); // Some root symbols. Name* emptyName = m_nameTable->AddString(L""); rootNS = symFactory.CreateNamespace(emptyName, NULL); // Root namespace nsaGlobal = GetNsAid(rootNS, kaidGlobal); m_infileUnres.name = emptyName; m_infileUnres.isSource = false; m_infileUnres.idLocalAssembly = mdTokenNil; m_infileUnres.SetAssemblyID(kaidUnresolved, allocGlobal); size_t isym; isym = ssetAssembly.Add(&m_infileUnres); ASSERT(isym == 0); */ InitPreLoad(); } public NameManager GetNameManager() { return m_nameTable; } public SYMTBL GetSymbolTable() { return tableGlobal; } public static TypeArray EmptyTypeArray() { return s_taEmpty; } public AssemblyQualifiedNamespaceSymbol GetRootNsAid(KAID aid) { return GetNsAid(_rootNS, aid); } public NamespaceSymbol GetRootNS() { return _rootNS; } public KAID AidAlloc(InputFile sym) { ssetAssembly.Add(new AidContainer(sym)); return (KAID)(ssetAssembly.Count - 1 + KAID.kaidUnresolved); } public BetterType CompareTypes(TypeArray ta1, TypeArray ta2) { if (ta1 == ta2) { return BetterType.Same; } if (ta1.Size != ta2.Size) { // The one with more parameters is more specific. return ta1.Size > ta2.Size ? BetterType.Left : BetterType.Right; } BetterType nTot = BetterType.Neither; for (int i = 0; i < ta1.Size; i++) { CType type1 = ta1.Item(i); CType type2 = ta2.Item(i); BetterType nParam = BetterType.Neither; LAgain: if (type1.GetTypeKind() != type2.GetTypeKind()) { if (type1.IsTypeParameterType()) { nParam = BetterType.Right; } else if (type2.IsTypeParameterType()) { nParam = BetterType.Left; } } else { switch (type1.GetTypeKind()) { default: Debug.Assert(false, "Bad kind in CompareTypes"); break; case TypeKind.TK_TypeParameterType: case TypeKind.TK_ErrorType: break; case TypeKind.TK_PointerType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_ArrayType: case TypeKind.TK_NullableType: type1 = type1.GetBaseOrParameterOrElementType(); type2 = type2.GetBaseOrParameterOrElementType(); goto LAgain; case TypeKind.TK_AggregateType: nParam = CompareTypes(type1.AsAggregateType().GetTypeArgsAll(), type2.AsAggregateType().GetTypeArgsAll()); break; } } if (nParam == BetterType.Right || nParam == BetterType.Left) { if (nTot == BetterType.Same || nTot == BetterType.Neither) { nTot = nParam; } else if (nParam != nTot) { return BetterType.Neither; } } } return nTot; } public SymFactory GetSymFactory() { return _symFactory; } public MiscSymFactory GetMiscSymFactory() { return _miscSymFactory; } //////////////////////////////////////////////////////////////////////////////// // Build the data structures needed to make FPreLoad fast. Make sure the // namespaces are created. Compute and sort hashes of the NamespaceSymbol * value and type // name (sans arity indicator). private void InitPreLoad() { for (int i = 0; i < (int)PredefinedType.PT_COUNT; ++i) { NamespaceSymbol ns = GetRootNS(); string name = PredefinedTypeFacts.GetName((PredefinedType)i); int start = 0; while (start < name.Length) { int iDot = name.IndexOf('.', start); if (iDot == -1) break; string sub = (iDot > start) ? name.Substring(start, iDot - start) : name.Substring(start); Name nm = this.GetNameManager().Add(sub); NamespaceSymbol sym = this.LookupGlobalSymCore(nm, ns, symbmask_t.MASK_NamespaceSymbol).AsNamespaceSymbol(); if (sym == null) { ns = _symFactory.CreateNamespace(nm, ns); } else { ns = sym; } start += sub.Length + 1; } } } public Symbol LookupGlobalSymCore(Name name, ParentSymbol parent, symbmask_t kindmask) { return tableGlobal.LookupSym(name, parent, kindmask); } public Symbol LookupAggMember(Name name, AggregateSymbol agg, symbmask_t mask) { return tableGlobal.LookupSym(name, agg, mask); } public static Symbol LookupNextSym(Symbol sym, ParentSymbol parent, symbmask_t kindmask) { Debug.Assert(sym.parent == parent); sym = sym.nextSameName; Debug.Assert(sym == null || sym.parent == parent); // Keep traversing the list of symbols with same name and parent. while (sym != null) { if ((kindmask & sym.mask()) > 0) return sym; sym = sym.nextSameName; Debug.Assert(sym == null || sym.parent == parent); } return null; } public Name GetNameFromPtrs(object u1, object u2) { // Note: this won't produce the same names as the native logic if (u2 != null) { return this.m_nameTable.Add(string.Format(CultureInfo.InvariantCulture, "{0:X}-{1:X}", u1.GetHashCode(), u2.GetHashCode())); } else { return this.m_nameTable.Add(string.Format(CultureInfo.InvariantCulture, "{0:X}", u1.GetHashCode())); } } public AssemblyQualifiedNamespaceSymbol GetNsAid(NamespaceSymbol ns, KAID aid) { Name name = GetNameFromPtrs(aid, 0); Debug.Assert(name != null); AssemblyQualifiedNamespaceSymbol nsa = LookupGlobalSymCore(name, ns, symbmask_t.MASK_AssemblyQualifiedNamespaceSymbol).AsAssemblyQualifiedNamespaceSymbol(); if (nsa == null) { // Create a new one. nsa = _symFactory.CreateNamespaceAid(name, ns, aid); } Debug.Assert(nsa.GetNS() == ns); return nsa; } //////////////////////////////////////////////////////////////////////////////// // Allocate a type array; used to represent a parameter list. // We use a hash table to make sure that allocating the same type array twice // returns the same value. This does two things: // // 1) Save a lot of memory. // 2) Make it so parameter lists can be compared by a simple pointer comparison // 3) Allow us to associate a token with each signature for faster metadata emit protected struct TypeArrayKey : IEquatable<TypeArrayKey> { private CType[] _types; private int _hashCode; public TypeArrayKey(CType[] types) { _types = types; _hashCode = 0; for (int i = 0, n = types.Length; i < n; i++) { _hashCode ^= types[i].GetHashCode(); } } public bool Equals(TypeArrayKey other) { if (other._types == _types) return true; if (other._types.Length != _types.Length) return false; if (other._hashCode != _hashCode) return false; for (int i = 0, n = _types.Length; i < n; i++) { if (!_types[i].Equals(other._types[i])) return false; } return true; } public override bool Equals(object obj) { if (obj is TypeArrayKey) { return this.Equals((TypeArrayKey)obj); } return false; } public override int GetHashCode() { return _hashCode; } } public TypeArray AllocParams(int ctype, CType[] prgtype) { if (ctype == 0) { return s_taEmpty; } Debug.Assert(ctype == prgtype.Length); return AllocParams(prgtype); } public TypeArray AllocParams(int ctype, TypeArray array, int offset) { CType[] types = array.ToArray(); CType[] newTypes = new CType[ctype]; Array.ConstrainedCopy(types, offset, newTypes, 0, ctype); return AllocParams(newTypes); } public TypeArray AllocParams(params CType[] types) { if (types == null || types.Length == 0) { return s_taEmpty; } TypeArrayKey key = new TypeArrayKey(types); TypeArray result; if (!tableTypeArrays.TryGetValue(key, out result)) { result = new TypeArray(types); tableTypeArrays.Add(key, result); } return result; } public TypeArray ConcatParams(CType[] prgtype1, CType[] prgtype2) { CType[] combined = new CType[prgtype1.Length + prgtype2.Length]; Array.Copy(prgtype1, combined, prgtype1.Length); Array.Copy(prgtype2, 0, combined, prgtype1.Length, prgtype2.Length); return AllocParams(combined); } public TypeArray ConcatParams(TypeArray pta1, TypeArray pta2) { return ConcatParams(pta1.ToArray(), pta2.ToArray()); } } }
using System; using System.IO; using System.Text; using System.Collections.Generic; using System.Globalization; namespace SilentOrbit.ProtocolBuffers { static class ProtoParser { /// <summary> /// Parse a single .proto file. /// Return true if successful/no errors. /// </summary> public static void Parse(string path, ProtoCollection p) { //Preparation for parsing //Real parsing is done in ParseMessages lastComment.Clear(); //Read entire file and pass it into a TokenReader string t = ""; using (TextReader reader = new StreamReader(path, Encoding.UTF8)) { while (true) { string line = reader.ReadLine(); if (line == null) break; t += line + "\n"; } } TokenReader tr = new TokenReader(t, path); try { ParseMessages(tr, p); } catch (EndOfStreamException) { return; } } static readonly List<string> lastComment = new List<string>(); /// <summary> /// Return true if token was a comment /// </summary> static bool ParseComment(string token) { if (token.StartsWith("//")) { lastComment.Add(token.TrimStart('/')); return true; } if (token.StartsWith("/*")) { lastComment.Add(token.Substring(2)); return true; } return false; } static void ParseMessages(TokenReader tr, ProtoCollection p) { string package = "Example"; while (true) { string token = tr.ReadNextComment(); if (ParseComment(token)) continue; try { switch (token) { case ";": break; case "message": ParseMessage(tr, p, package); break; case "enum": ParseEnum(tr, p, package); break; case "option": //Save options ParseOption(tr, p); break; case "import": ParseImport(tr, p); break; case "package": package = tr.ReadNext(); tr.ReadNextOrThrow(";"); break; case "syntax": //This is not a supported protobuf keyword, used in Google internally tr.ReadNextOrThrow("="); tr.ReadNext(); tr.ReadNextOrThrow(";"); break; case "extend": ParseExtend(tr, p, package); break; default: throw new ProtoFormatException("Unexpected/not implemented: " + token, tr); } lastComment.Clear(); } catch (EndOfStreamException) { throw new ProtoFormatException("Unexpected EOF", tr); } } } static void ParseMessage(TokenReader tr, ProtoMessage parent, string package) { var msg = new ProtoMessage(parent, package); LocalParser.ParseComments(msg, lastComment, tr); msg.ProtoName = tr.ReadNext(); tr.ReadNextOrThrow("{"); try { while (ParseField(tr, msg)) continue; } catch (Exception e) { throw new ProtoFormatException(e.Message, e, tr); } parent.Messages.Add(msg.ProtoName, msg); } static void ParseExtend(TokenReader tr, ProtoMessage parent, string package) { var msg = new ProtoMessage(parent, package); LocalParser.ParseComments(msg, lastComment, tr); msg.ProtoName = tr.ReadNext(); tr.ReadNextOrThrow("{"); try { while (ParseField(tr, msg)) continue; } catch (Exception e) { throw new ProtoFormatException(e.Message, e, tr); } //Not implemented //parent.Messages.Add(msg.ProtoName, msg); } static bool ParseField(TokenReader tr, ProtoMessage m) { string rule = tr.ReadNextComment(); while (true) { if (ParseComment(rule) == false) break; rule = tr.ReadNextComment(); } Field f = new Field(tr); //Rule switch (rule) { case ";": lastComment.Clear(); return true; case "}": lastComment.Clear(); return false; case "required": f.Rule = FieldRule.Required; break; case "optional": f.Rule = FieldRule.Optional; break; case "repeated": f.Rule = FieldRule.Repeated; break; case "option": //Save options ParseOption(tr, m); return true; case "message": ParseMessage(tr, m, m.Package + "." + m.ProtoName); return true; case "enum": ParseEnum(tr, m, m.Package + "." + m.ProtoName); return true; case "extensions": ParseExtensions(tr, m); return true; default: throw new ProtoFormatException("unknown rule: " + rule, tr); } //Field comments LocalParser.ParseComments(f, lastComment, tr); //Type f.ProtoTypeName = tr.ReadNext(); //Name f.ProtoName = tr.ReadNext(); //ID tr.ReadNextOrThrow("="); f.ID = ParseInt(tr); if (19000 <= f.ID && f.ID <= 19999) throw new ProtoFormatException("Can't use reserved field ID 19000-19999", tr); if (f.ID > (1 << 29) - 1) throw new ProtoFormatException("Maximum field id is 2^29 - 1", tr); //Add Field to message m.Fields.Add(f.ID, f); //Determine if extra options string extra = tr.ReadNext(); if (extra == ";") return true; //Field options if (extra != "[") throw new ProtoFormatException("Expected: [ got " + extra, tr); ParseFieldOptions(tr, f); return true; } static void ParseFieldOptions(TokenReader tr, Field f) { while (true) { string key = tr.ReadNext(); tr.ReadNextOrThrow("="); string val = tr.ReadNext(); ParseFieldOption(key, val, f); string optionSep = tr.ReadNext(); if (optionSep == "]") break; if (optionSep == ",") continue; throw new ProtoFormatException(@"Expected "","" or ""]"" got " + tr.NextCharacter, tr); } tr.ReadNextOrThrow(";"); } static void ParseFieldOption(string key, string val, Field f) { switch (key) { case "default": f.OptionDefault = val; break; case "packed": f.OptionPacked = Boolean.Parse(val); break; case "deprecated": f.OptionDeprecated = Boolean.Parse(val); break; default: Console.WriteLine("Warning: Unknown field option: " + key); break; } } /// <summary> /// File or Message options /// </summary> static void ParseOption(TokenReader tr, ProtoMessage m) { //Read name string key = tr.ReadNext(); if (tr.ReadNext() != "=") throw new ProtoFormatException("Expected: = got " + tr.NextCharacter, tr); //Read value string value = tr.ReadNext(); if (tr.ReadNext() != ";") throw new ProtoFormatException("Expected: ; got " + tr.NextCharacter, tr); //null = ignore option if (m == null) return; switch (key) { //None at the moment //case "namespace": // m.OptionNamespace = value; // break; default: Console.WriteLine("Warning: Unknown option: " + key + " = " + value); break; } } static void ParseEnum(TokenReader tr, ProtoMessage parent, string package) { ProtoEnum me = new ProtoEnum(parent, package); LocalParser.ParseComments(me, lastComment, tr); me.ProtoName = tr.ReadNext(); parent.Enums.Add(me.ProtoName, me); //must be after .ProtoName is read if (tr.ReadNext() != "{") throw new ProtoFormatException("Expected: {", tr); while (true) { string name = tr.ReadNextComment(); if (ParseComment(name)) continue; if (name == "}") return; //Ignore options if (name == "option") { ParseOption(tr, null); lastComment.Clear(); continue; } ParseEnumValue(tr, me, name); } } static void ParseEnumValue(TokenReader tr, ProtoEnum parent, string name) { if (tr.ReadNext() != "=") throw new ProtoFormatException("Expected: =", tr); int id = ParseInt(tr); var value = new ProtoEnumValue(name, id, lastComment); parent.Enums.Add(value); string extra = tr.ReadNext(); if (extra == ";") return; if (extra != "[") throw new ProtoFormatException("Expected: ; or [", tr); ParseEnumValueOptions(tr, value); } static void ParseEnumValueOptions(TokenReader tr, ProtoEnumValue evalue) { while (true) { string key = tr.ReadNext(); tr.ReadNextOrThrow("="); string val = tr.ReadNext(); ParseEnumValueOptions(key, val, evalue); string optionSep = tr.ReadNext(); if (optionSep == "]") break; if (optionSep == ",") continue; throw new ProtoFormatException(@"Expected "","" or ""]"" got " + tr.NextCharacter, tr); } tr.ReadNextOrThrow(";"); } static void ParseEnumValueOptions(string key, string val, ProtoEnumValue f) { //TODO } static void ParseExtensions(TokenReader tr, ProtoMessage m) { //extensions 100 to max; tr.ReadNext(); //100 tr.ReadNextOrThrow("to"); tr.ReadNext(); //number or max tr.ReadNextOrThrow(";"); } static void ParseImport(TokenReader tr, ProtoCollection collection) { string path = tr.ReadNext(); bool publicImport = path == "public"; if (publicImport) path = tr.ReadNext(); tr.ReadNextOrThrow(";"); if (publicImport) collection.ImportPublic.Add(path); else collection.Import.Add(path); } static int ParseInt(TokenReader tr) { string text = tr.ReadNext(); int val; //Decimal if (int.TryParse(text, out val)) return val; //Hex if (text.StartsWith("0x", StringComparison.CurrentCultureIgnoreCase)) { var hex = text.Substring(2); if (int.TryParse(hex, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out val)) return val; } throw new ProtoFormatException("Unknown integer format: " + text, tr); } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace Elasticsearch.Net.Integration.Yaml.IndicesGetWarmer1 { public partial class IndicesGetWarmer1YamlTests { public class IndicesGetWarmer110BasicYamlBase : YamlTestsBase { public IndicesGetWarmer110BasicYamlBase() : base() { //do indices.create _body = new { warmers= new { warmer_1= new { source= new { query= new { match_all= new {} } } }, warmer_2= new { source= new { query= new { match_all= new {} } } } } }; this.Do(()=> _client.IndicesCreate("test_1", _body)); //do indices.create _body = new { warmers= new { warmer_2= new { source= new { query= new { match_all= new {} } } }, warmer_3= new { source= new { query= new { match_all= new {} } } } } }; this.Do(()=> _client.IndicesCreate("test_2", _body)); //do cluster.health this.Do(()=> _client.ClusterHealth(nv=>nv .AddQueryString("wait_for_status", @"yellow") )); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetWarmer2Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetWarmer2Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmerForAll()); //match _response.test_1.warmers.warmer_1.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_1.source.query.match_all, new {}); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //match _response.test_2.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_2.warmers.warmer_2.source.query.match_all, new {}); //match _response.test_2.warmers.warmer_3.source.query.match_all: this.IsMatch(_response.test_2.warmers.warmer_3.source.query.match_all, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexWarmer3Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetIndexWarmer3Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("test_1")); //match _response.test_1.warmers.warmer_1.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_1.source.query.match_all, new {}); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexWarmerAll4Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetIndexWarmerAll4Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("test_1", "_all")); //match _response.test_1.warmers.warmer_1.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_1.source.query.match_all, new {}); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexWarmer5Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetIndexWarmer5Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("test_1", "*")); //match _response.test_1.warmers.warmer_1.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_1.source.query.match_all, new {}); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexWarmerName6Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetIndexWarmerName6Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("test_1", "warmer_1")); //match _response.test_1.warmers.warmer_1.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_1.source.query.match_all, new {}); //is_false _response.test_1.warmers.warmer_2; this.IsFalse(_response.test_1.warmers.warmer_2); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexWarmerNameName7Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetIndexWarmerNameName7Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("test_1", "warmer_1,warmer_2")); //match _response.test_1.warmers.warmer_1.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_1.source.query.match_all, new {}); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexWarmerName8Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetIndexWarmerName8Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("test_1", "*2")); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_1.warmers.warmer_1; this.IsFalse(_response.test_1.warmers.warmer_1); //is_false _response.test_2; this.IsFalse(_response.test_2); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetWarmerName9Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetWarmerName9Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmerForAll("warmer_2")); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //match _response.test_2.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_2.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_1.warmers.warmer_1; this.IsFalse(_response.test_1.warmers.warmer_1); //is_false _response.test_2.warmers.warmer_3; this.IsFalse(_response.test_2.warmers.warmer_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetAllWarmerName10Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetAllWarmerName10Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("_all", "warmer_2")); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //match _response.test_2.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_2.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_1.warmers.warmer_1; this.IsFalse(_response.test_1.warmers.warmer_1); //is_false _response.test_2.warmers.warmer_3; this.IsFalse(_response.test_2.warmers.warmer_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetWarmerName11Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetWarmerName11Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("*", "warmer_2")); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //match _response.test_2.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_2.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_1.warmers.warmer_1; this.IsFalse(_response.test_1.warmers.warmer_1); //is_false _response.test_2.warmers.warmer_3; this.IsFalse(_response.test_2.warmers.warmer_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexIndexWarmerName12Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetIndexIndexWarmerName12Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("test_1,test_2", "warmer_2")); //match _response.test_1.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_1.warmers.warmer_2.source.query.match_all, new {}); //match _response.test_2.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_2.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_2.warmers.warmer_3; this.IsFalse(_response.test_2.warmers.warmer_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetIndexWarmerName13Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetIndexWarmerName13Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("*2", "warmer_2")); //match _response.test_2.warmers.warmer_2.source.query.match_all: this.IsMatch(_response.test_2.warmers.warmer_2.source.query.match_all, new {}); //is_false _response.test_1; this.IsFalse(_response.test_1); //is_false _response.test_2.warmers.warmer_3; this.IsFalse(_response.test_2.warmers.warmer_3); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class EmptyResponseWhenNoMatchingWarmer14Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void EmptyResponseWhenNoMatchingWarmer14Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("*", "non_existent")); //match this._status: this.IsMatch(this._status, new {}); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class Throw404OnMissingIndex15Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void Throw404OnMissingIndex15Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmer("non_existent", "*"), shouldCatch: @"missing"); } } [NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")] public class GetWarmerWithLocalFlag16Tests : IndicesGetWarmer110BasicYamlBase { [Test] public void GetWarmerWithLocalFlag16Test() { //do indices.get_warmer this.Do(()=> _client.IndicesGetWarmerForAll(nv=>nv .AddQueryString("local", @"true") )); //is_true _response.test_1; this.IsTrue(_response.test_1); //is_true _response.test_2; this.IsTrue(_response.test_2); } } } }
// // DatabaseTrackListModel.cs // // Author: // Aaron Bockover <abockover@novell.com> // Gabriel Burt <gburt@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.Text; using System.Collections.Generic; using System.Linq; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Data.Sqlite; using Hyena.Query; using Banshee.Base; using Banshee.Query; using Banshee.Database; using Banshee.PlaybackController; namespace Banshee.Collection.Database { public class DatabaseTrackListModel : TrackListModel, IExportableModel, ICacheableDatabaseModel, IFilterable, ISortable, ICareAboutView, ISearchable { private readonly BansheeDbConnection connection; private IDatabaseTrackModelProvider provider; protected IDatabaseTrackModelCache cache; private Banshee.Sources.DatabaseSource source; private long count; private long filtered_count; private TimeSpan filtered_duration, duration; private long filtered_filesize, filesize; private ISortableColumn sort_column; private string sort_query; private bool forced_sort_query; private string reload_fragment; private string join_table, join_fragment, join_primary_key, join_column, condition, condition_from; private string query_fragment; private string user_query; private int rows_in_view; public DatabaseTrackListModel (BansheeDbConnection connection, IDatabaseTrackModelProvider provider, Banshee.Sources.DatabaseSource source) { this.connection = connection; this.provider = provider; this.source = source; SelectAggregates = "SUM(CoreTracks.Duration), SUM(CoreTracks.FileSize)"; Selection.Changed += delegate { if (SelectionAggregatesHandler != null) { cache.UpdateSelectionAggregates (SelectionAggregatesHandler); } }; } protected Action<IDataReader> SelectionAggregatesHandler { get; set; } protected HyenaSqliteConnection Connection { get { return connection; } } private bool initialized = false; public void Initialize (IDatabaseTrackModelCache cache) { if (initialized) return; initialized = true; this.cache = cache; cache.AggregatesUpdated += HandleCacheAggregatesUpdated; GenerateSortQueryPart (); } private bool have_new_user_query = true; private void GenerateUserQueryFragment () { if (!have_new_user_query) return; if (String.IsNullOrEmpty (UserQuery)) { query_fragment = null; query_tree = null; } else { query_tree = UserQueryParser.Parse (UserQuery, BansheeQuery.FieldSet); query_fragment = (query_tree == null) ? null : query_tree.ToSql (BansheeQuery.FieldSet); if (query_fragment != null && query_fragment.Length == 0) { query_fragment = null; query_tree = null; } } have_new_user_query = false; } private QueryNode query_tree; public QueryNode Query { get { return query_tree; } } protected string SortQuery { get { return sort_query; } set { sort_query = value; } } protected virtual void GenerateSortQueryPart () { SortQuery = (SortColumn == null || SortColumn.SortType == SortType.None) ? (SortColumn != null && source is Banshee.Playlist.PlaylistSource) ? "CorePlaylistEntries.ViewOrder ASC, CorePlaylistEntries.EntryID ASC" : BansheeQuery.GetSort ("Artist", true) : BansheeQuery.GetSort (SortColumn.SortKey, SortColumn.SortType == SortType.Ascending); } private SortType last_sort_type = SortType.None; public bool Sort (ISortableColumn column) { lock (this) { if (forced_sort_query) { return false; } // Don't sort by the same column and the same sort-type more than once if (sort_column != null && sort_column == column && column.SortType == last_sort_type) { return false; } last_sort_type = column.SortType; sort_column = column; GenerateSortQueryPart (); cache.Clear (); } return true; } public void Resort () { var column = sort_column; sort_column = null; Sort (column); } private void HandleCacheAggregatesUpdated (IDataReader reader) { filtered_duration = TimeSpan.FromMilliseconds (reader[1] == null ? 0 : Convert.ToInt64 (reader[1])); filtered_filesize = reader[2] == null ? 0 : Convert.ToInt64 (reader[2]); } public override void Clear () { cache.Clear (); count = 0; filesize = 0; duration = TimeSpan.Zero; filtered_count = 0; OnCleared (); } public void InvalidateCache (bool notify) { if (cache == null) { Log.ErrorFormat ("Called invalidate cache for {0}'s track model, but cache is null", source); } else { cache.Clear (); if (notify) { OnReloaded (); } } } private string unfiltered_query; public virtual string UnfilteredQuery { get { return unfiltered_query ?? (unfiltered_query = String.Format ( "FROM {0} WHERE {1} {2}", FromFragment, String.IsNullOrEmpty (provider.Where) ? "1=1" : provider.Where, ConditionFragment )); } } private string from; protected string From { get { if (from == null) { from = provider.From; int i = from.IndexOf (','); if (i > 0) { // Force the join order to fix bgo#581103 and bgo#603661 // See section 5.2 in http://www.sqlite.org/optoverview.html from = from.Substring (0, i) + " CROSS JOIN " + from.Substring (i + 1); } } return from; } set { from = value; } } private string from_fragment; public string FromFragment { get { return from_fragment ?? (from_fragment = String.Format ("{0}{1}", From, JoinFragment)); } } public virtual void UpdateUnfilteredAggregates () { HyenaSqliteCommand count_command = new HyenaSqliteCommand (String.Format ( "SELECT COUNT(*), SUM(CoreTracks.FileSize), SUM(CoreTracks.Duration) {0}", UnfilteredQuery )); using (HyenaDataReader reader = new HyenaDataReader (connection.Query (count_command))) { count = reader.Get<long> (0); filesize = reader.Get<long> (1); duration = reader.Get<TimeSpan> (2); } } public override void Reload () { Reload (null); } public void Reload (IListModel reloadTrigger) { if (cache == null) { Log.WarningFormat ("Called Reload on {0} for source {1} but cache is null; Did you forget to call AfterInitialized () in your DatabaseSource ctor?", this, source == null ? "null source!" : source.Name); return; } lock (this) { GenerateUserQueryFragment (); UpdateUnfilteredAggregates (); cache.SaveSelection (); List<IFilterListModel> reload_models = new List<IFilterListModel> (); bool found = (reloadTrigger == null); foreach (IFilterListModel filter in source.CurrentFilters) { if (found) { reload_models.Add (filter); } else if (filter == reloadTrigger) { found = true; } } if (reload_models.Count == 0) { ReloadWithFilters (true); } else { ReloadWithoutFilters (); foreach (IFilterListModel model in reload_models) { model.Reload (false); } bool have_filters = false; foreach (IFilterListModel filter in source.CurrentFilters) { have_filters |= !filter.Selection.AllSelected; } // Unless both artist/album selections are "all" (eg unfiltered), reload // the track model again with the artist/album filters now in place. if (have_filters) { ReloadWithFilters (true); } } cache.UpdateAggregates (); cache.RestoreSelection (); if (SelectionAggregatesHandler != null) { cache.UpdateSelectionAggregates (SelectionAggregatesHandler); } filtered_count = cache.Count; OnReloaded (); // Trigger these after the track list, b/c visually it's more important for it to update first foreach (IFilterListModel model in reload_models) { model.RaiseReloaded (); } } } private void ReloadWithoutFilters () { ReloadWithFilters (false); } private void ReloadWithFilters (bool with_filters) { StringBuilder qb = new StringBuilder (); qb.Append (UnfilteredQuery); if (with_filters) { foreach (IFilterListModel filter in source.CurrentFilters) { string filter_sql = filter.GetSqlFilter (); if (filter_sql != null) { qb.Append (" AND "); qb.Append (filter_sql); } } } if (query_fragment != null) { qb.Append (" AND "); qb.Append (query_fragment); } if (sort_query != null) { qb.Append (" ORDER BY "); qb.Append (sort_query); } reload_fragment = qb.ToString (); cache.Reload (); } private QueryFieldSet query_fields = BansheeQuery.FieldSet; public QueryFieldSet QueryFields { get { return query_fields; } protected set { query_fields = value; } } public int IndexOf (QueryNode query, long offset) { lock (this) { if (query == null) { return -1; } return (int) cache.IndexOf (query.ToSql (QueryFields), offset); } } public override int IndexOf (TrackInfo track) { lock (this) { if (track is DatabaseTrackInfo) { return (int) cache.IndexOf (track as DatabaseTrackInfo); } else if (track is Banshee.Streaming.RadioTrackInfo) { return (int) cache.IndexOf ((track as Banshee.Streaming.RadioTrackInfo).ParentTrack as DatabaseTrackInfo); } return -1; } } public int IndexOfFirst (TrackInfo track) { lock (this) { return IndexOf (cache.GetSingleWhere ("AND MetadataHash = ? ORDER BY OrderID", track.MetadataHash)); } } public override TrackInfo GetRandom (DateTime notPlayedSince) { return GetRandom (notPlayedSince, "song", true, false, Shuffler.Playback); } public TrackInfo GetRandom (DateTime notPlayedSince, string shuffle_mode, bool repeat, bool resetSinceTime, Shuffler shuffler) { lock (this) { shuffler.SetModelAndCache (this, cache); return shuffler.GetRandom (notPlayedSince, shuffle_mode, repeat, resetSinceTime); } } public override TrackInfo this[int index] { get { lock (this) { return cache.GetValue (index); } } } public override int Count { get { return (int) filtered_count; } } public virtual TimeSpan Duration { get { return filtered_duration; } } public virtual long FileSize { get { return filtered_filesize; } } public long UnfilteredFileSize { get { return filesize; } } public TimeSpan UnfilteredDuration { get { return duration; } } public int UnfilteredCount { get { return (int) count; } set { count = value; } } public string UserQuery { get { return user_query; } set { lock (this) { user_query = value; have_new_user_query = true; } } } public string ForcedSortQuery { get { return forced_sort_query ? sort_query : null; } set { forced_sort_query = value != null; sort_query = value; if (cache != null) { cache.Clear (); } } } public string JoinTable { get { return join_table; } set { join_table = value; join_fragment = String.Format (", {0}", join_table); } } public string JoinFragment { get { return join_fragment; } } public string JoinPrimaryKey { get { return join_primary_key; } set { join_primary_key = value; } } public string JoinColumn { get { return join_column; } set { join_column = value; } } public void AddCondition (string part) { AddCondition (null, part); } public void AddCondition (string tables, string part) { if (!String.IsNullOrEmpty (part)) { condition = condition == null ? part : String.Format ("{0} AND {1}", condition, part); if (!String.IsNullOrEmpty (tables)) { condition_from = condition_from == null ? tables : String.Format ("{0}, {1}", condition_from, tables); } } } public string Condition { get { return condition; } } private string condition_from_fragment; public string ConditionFromFragment { get { if (condition_from_fragment == null) { if (JoinFragment == null) { condition_from_fragment = condition_from; } else { if (condition_from == null) { condition_from = "CoreTracks"; } condition_from_fragment = String.Format ("{0}{1}", condition_from, JoinFragment); } } return condition_from_fragment; } } public string ConditionFragment { get { return PrefixCondition ("AND"); } } private string PrefixCondition (string prefix) { string condition = Condition; return String.IsNullOrEmpty (condition) ? String.Empty : String.Format (" {0} {1} ", prefix, condition); } public int CacheId { get { return (int) cache.CacheId; } } public ISortableColumn SortColumn { get { return sort_column; } } public virtual int RowsInView { protected get { return rows_in_view; } set { rows_in_view = value; } } int IExportableModel.GetLength () { return Count; } IDictionary<string, object> IExportableModel.GetMetadata (int index) { return this[index].GenerateExportable (); } private string track_ids_sql; public string TrackIdsSql { get { if (track_ids_sql == null) { if (!CachesJoinTableEntries) { track_ids_sql = "ItemID FROM CoreCache WHERE ModelID = ? LIMIT ?, ?"; } else { track_ids_sql = String.Format ( "{0} FROM {1} WHERE {2} IN (SELECT ItemID FROM CoreCache WHERE ModelID = ? LIMIT ?, ?)", JoinColumn, JoinTable, JoinPrimaryKey ); } } return track_ids_sql; } } private bool caches_join_table_entries = false; public bool CachesJoinTableEntries { get { return caches_join_table_entries; } set { caches_join_table_entries = value; } } // Implement ICacheableModel public int FetchCount { get { return RowsInView > 0 ? RowsInView * 5 : 100; } } public string SelectAggregates { get; protected set; } // Implement IDatabaseModel public string ReloadFragment { get { return reload_fragment; } } public bool CachesValues { get { return false; } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Notes; using Adxstudio.Xrm.Resources; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Diagnostics; using Microsoft.Xrm.Portal; using Microsoft.Xrm.Sdk; namespace Adxstudio.Xrm.Web.Handlers.ElFinder { /// <summary> /// Handler for elFinder "upload" command. /// </summary> /// <remarks> /// File upload (http://elrte.org/redmine/projects/elfinder/wiki/Client-Server_Protocol_EN#upload). /// /// Arguments (send using POST): /// /// - cmd : upload /// - current : hash of directory where to upload files /// - upload : array of files to upload (upload[]) /// /// Response: /// /// 1. If no files where uploaded return: /// /// { /// "error" : "Unable to upload files" /// } /// /// 2. If at least one file was uploaded response with open and select. If some files failed to upload append error and errorData: /// /// { /// // open /// "select" : [ "8d331825ebfbe1ddae14d314bf81a712" ], // (Array) array of hashes of files that were uploaded /// "error" : "Some files was not uploaded", // (String) return if not all files where uploaded /// "errorData" : { // (Object) warnings which files were not uploaded /// "some-file.exe" : "Not allowed file type" // (String) "file name": "error" /// } /// } /// </remarks> public class UploadCommand : ICommand { public CommandResponse GetResponse(ICommandContext commandContext) { var fileSystem = commandContext.CreateFileSystem(); var hash = commandContext.Parameters["current"]; DirectoryContentHash cwd; if (!DirectoryContentHash.TryParse(hash, out cwd)) { return new ErrorCommandResponse { error = ResourceManager.GetString("Unable_To_Retrieve_Current_Directory_For_Upload_Error") }; } DirectoryUploadInfo cwdInfo; try { cwdInfo = fileSystem.Using(cwd, fs => new DirectoryUploadInfo(fs.Current)); } catch (InvalidOperationException) { return new ErrorCommandResponse { error = ResourceManager.GetString("Unable_To_Retrieve_Current_Directory_For_Upload_Error") }; } if (!(cwdInfo.SupportsUpload && cwdInfo.CanWrite)) { return new ErrorCommandResponse { error = ResourceManager.GetString("Upload_Permission_Denied_For_Current_Directory_Error") }; } var files = GetUploadedFiles(commandContext.Files); if (!files.Any()) { return new ErrorCommandResponse { error = "No valid files were uploaded" }; } var portal = commandContext.CreatePortalContext(); var publishingState = GetPublishingState(portal, cwdInfo.Entity); if (publishingState == null) { return new ErrorCommandResponse { error = ResourceManager.GetString("Unable_To_Retrieve_Current_Directory_For_Upload_Error") }; } List<string> @select; List<Tuple<string, string>> errors; CreateFiles(commandContext, cwdInfo, files, publishingState, out @select, out errors); try { return fileSystem.Using(cwd, fs => GetResponse(commandContext, fs, @select, errors)); } catch (InvalidOperationException) { return new ErrorCommandResponse { error = ResourceManager.GetString("Unable_To_Retrieve_Current_Directory_For_Upload_Error") }; } } private CommandResponse GetResponse(ICommandContext commandContext, IFileSystemContext fileSystemContext, List<string> @select, List<Tuple<string, string>> errors) { var response = new OpenCommand().GetResponse(commandContext, fileSystemContext); response.select = select.ToArray(); if (errors.Any()) { var errorMessages = errors.Select(e => "[{0}: {1}]".FormatWith(e.Item1, e.Item2)); response.error = ResourceManager.GetString("Uploading_Files_Error").FormatWith(string.Join(",", errorMessages)); } return response; } private static void CreateFiles(ICommandContext commandContext, DirectoryUploadInfo uploadInfo, IEnumerable<HttpPostedFile> files, EntityReference publishingState, out List<string> @select, out List<Tuple<string, string>> errors) { @select = new List<string>(); errors = new List<Tuple<string, string>>(); var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(); var annotationDataAdapter = new AnnotationDataAdapter(dataAdapterDependencies); var website = HttpContext.Current.GetWebsite(); var location = website.Settings.Get<string>("WebFiles/StorageLocation"); StorageLocation storageLocation; if (!Enum.TryParse(location, true, out storageLocation)) { storageLocation = StorageLocation.CrmDocument; } var maxFileSizeErrorMessage = website.Settings.Get<string>("WebFiles/MaxFileSizeErrorMessage"); var annotationSettings = new AnnotationSettings(dataAdapterDependencies.GetServiceContext(), storageLocation: storageLocation, maxFileSizeErrorMessage: maxFileSizeErrorMessage); foreach (var file in files) { var serviceContext = commandContext.CreateServiceContext(); try { var webFile = new Entity("adx_webfile"); var fileName = Path.GetFileName(file.FileName); webFile.Attributes["adx_name"] = fileName; webFile.Attributes["adx_partialurl"] = GetPartialUrlFromFileName(fileName); webFile.Attributes["adx_websiteid"] = website.Entity.ToEntityReference(); webFile.Attributes["adx_publishingstateid"] = publishingState; webFile.Attributes["adx_hiddenfromsitemap"] = true; webFile.Attributes[uploadInfo.WebFileForeignKeyAttribute] = uploadInfo.EntityReference; serviceContext.AddObject(webFile); serviceContext.SaveChanges(); annotationDataAdapter.CreateAnnotation(new Annotation { Regarding = webFile.ToEntityReference(), FileAttachment = AnnotationDataAdapter.CreateFileAttachment(new HttpPostedFileWrapper(file), annotationSettings.StorageLocation) }, annotationSettings); @select.Add(new DirectoryContentHash(webFile.ToEntityReference()).ToString()); } catch (Exception e) { ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Exception uploading file: {0}", e.ToString())); errors.Add(new Tuple<string, string>(file.FileName, e.Message)); } } } private static string GetPartialUrlFromFileName(string fileName) { if (fileName == null) { throw new ArgumentNullException("fileName"); } return HttpUtility.UrlPathEncode(fileName); } private static EntityReference GetPublishingState(IPortalContext portal, Entity directory) { // Load all publishing states in website. var publishingStates = portal.ServiceContext.CreateQuery("adx_publishingstate") .Where(e => e.GetAttributeValue<EntityReference>("adx_websiteid") == portal.Website.ToEntityReference()) .ToList(); // Favour a publishing state that is both visible and the default. var visibleAndDefaultState = publishingStates.FirstOrDefault(e => e.GetAttributeValue<bool?>("adx_isvisible").GetValueOrDefault() && e.GetAttributeValue<bool?>("adx_isdefault").GetValueOrDefault()); if (visibleAndDefaultState != null) { return visibleAndDefaultState.ToEntityReference(); } // Next best, try to use the publishing state of the parent directory. if (directory.Attributes.Contains("adx_publishingstateid")) { var directoryPublishingState = directory.GetAttributeValue<EntityReference>("adx_publishingstateid"); if (directoryPublishingState != null) { return directoryPublishingState; } } // Next, just try for the default. var defaultState = publishingStates.FirstOrDefault(e => e.GetAttributeValue<bool?>("adx_isdefault").GetValueOrDefault()); if (defaultState != null) { return defaultState.ToEntityReference(); } // Failing that, try for visible. var visibleState = publishingStates.FirstOrDefault(e => e.GetAttributeValue<bool?>("adx_isvisible").GetValueOrDefault()); if (visibleState != null) { return visibleState.ToEntityReference(); } // Failing that, settle for any state. var firstState = publishingStates.FirstOrDefault(); if (firstState != null) { return firstState.ToEntityReference(); } return null; } private static HttpPostedFile[] GetUploadedFiles(HttpFileCollection files) { var validFiles = new List<HttpPostedFile>(); for (var i = 0; i < files.Count; i++) { var key = files.GetKey(i); if (key != "upload[]") { continue; } var file = files[i]; if (string.IsNullOrWhiteSpace(file.FileName)) { continue; } validFiles.Add(file); } return validFiles.ToArray(); } private class DirectoryUploadInfo { public DirectoryUploadInfo(IDirectory directory) { CanWrite = directory.CanWrite; Entity = directory.Entity; EntityReference = directory.EntityReference; SupportsUpload = directory.SupportsUpload; WebFileForeignKeyAttribute = directory.WebFileForeignKeyAttribute; } public bool CanWrite { get; private set; } public Entity Entity { get; private set; } public EntityReference EntityReference { get; private set; } public bool SupportsUpload { get; private set; } public string WebFileForeignKeyAttribute { get; private set; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Redis; namespace Microsoft.Azure.Management.Redis { /// <summary> /// .Net client wrapper for the REST API for Azure Redis Cache Management /// Service /// </summary> public partial class RedisManagementClient : ServiceClient<RedisManagementClient>, IRedisManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IRedisOperations _redis; /// <summary> /// Operations for managing the redis cache. /// </summary> public virtual IRedisOperations Redis { get { return this._redis; } } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> public RedisManagementClient() : base() { this._redis = new RedisOperations(this); this._apiVersion = "2014-04-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public RedisManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public RedisManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public RedisManagementClient(HttpClient httpClient) : base(httpClient) { this._redis = new RedisOperations(this); this._apiVersion = "2014-04-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public RedisManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the RedisManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public RedisManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// RedisManagementClient instance /// </summary> /// <param name='client'> /// Instance of RedisManagementClient to clone to /// </param> protected override void Clone(ServiceClient<RedisManagementClient> client) { base.Clone(client); if (client is RedisManagementClient) { RedisManagementClient clonedClient = ((RedisManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
#region Usings using System; #endregion namespace Stomp.Net.Stomp.Commands { /// <summary> /// Summary description for Destination. /// </summary> public abstract class Destination : BaseDataStructure, IDestination { #region Properties /// <summary> /// Indicates if the Destination was created by this client or was provided /// by the broker, most commonly the Destinations provided by the broker /// are those that appear in the ReplyTo field of a Message. /// </summary> private Boolean RemoteDestination { get; set; } #endregion #region Ctor /// <summary> /// Initializes a new instance of the <see cref="Destination" /> class with the given physical name. /// </summary> /// <param name="name">The physical name of the destination.</param> /// <param name="skipDesinationNameFormatting"> /// A value indicating whether the destination name formatting will be skipped /// or not. /// </param> protected Destination( String name, Boolean skipDesinationNameFormatting ) { PhysicalName = name; SkipDesinationNameFormatting = skipDesinationNameFormatting; } #endregion public abstract DestinationType DestinationType { get; } public Boolean IsQueue { get { var destinationType = GetDestinationType(); return StompQueue == destinationType || StompTemporaryQueue == destinationType; } } public Boolean IsTemporary { get { var destinationType = GetDestinationType(); return StompTemporaryQueue == destinationType || StompTemporaryTopic == destinationType; } } public Boolean IsTopic { get { var destinationType = GetDestinationType(); return StompTopic == destinationType || StompTemporaryTopic == destinationType; } } public String PhysicalName { get; } /// <summary> /// Gets or sets a value indicating whether the destination name formatting should be skipped or not. /// If set to true the physical name property will be used as stomp destination string without adding prefixes such as /// queue or topic. This to support JMS brokers listening for queue/topic names in a different format. /// </summary> public Boolean SkipDesinationNameFormatting { get; } public override Object Clone() { // Since we are a derived class use the base's Clone() // to perform the shallow copy. Since it is shallow it // will include our derived class. Since we are derived, // this method is an override. var o = (Destination) base.Clone(); // Now do the deep work required // If any new variables are added then this routine will // likely need updating return o; } /// <summary> /// </summary> /// <param name="text">The name of the destination</param> /// <param name="skipDesinationNameFormatting"> /// A value indicating whether the destination name formatting will be skipped /// or not. /// </param> /// <returns></returns> public static Destination ConvertToDestination( String text, Boolean skipDesinationNameFormatting ) { if ( text == null ) return null; var type = StompQueue; var lowertext = text.ToLower(); var remote = false; if ( lowertext.StartsWith( "/queue/", StringComparison.Ordinal ) ) text = text.Substring( "/queue/".Length ); else if ( lowertext.StartsWith( "/topic/", StringComparison.Ordinal ) ) { text = text.Substring( "/topic/".Length ); type = StompTopic; } else if ( lowertext.StartsWith( "/temp-topic/", StringComparison.Ordinal ) ) { text = text.Substring( "/temp-topic/".Length ); type = StompTemporaryTopic; } else if ( lowertext.StartsWith( "/temp-queue/", StringComparison.Ordinal ) ) { text = text.Substring( "/temp-queue/".Length ); type = StompTemporaryQueue; } else if ( lowertext.StartsWith( "/remote-temp-topic/", StringComparison.Ordinal ) ) { text = text.Substring( "/remote-temp-topic/".Length ); type = StompTemporaryTopic; remote = true; } else if ( lowertext.StartsWith( "/remote-temp-queue/", StringComparison.Ordinal ) ) { text = text.Substring( "/remote-temp-queue/".Length ); type = StompTemporaryQueue; remote = true; } return CreateDestination( type, text, remote, skipDesinationNameFormatting ); } public String ConvertToStompString() { if ( SkipDesinationNameFormatting ) return PhysicalName; var result = DestinationType switch { DestinationType.Topic => "/topic/" + PhysicalName, DestinationType.TemporaryTopic => ( RemoteDestination ? "/remote-temp-topic/" : "/temp-topic/" ) + PhysicalName, DestinationType.TemporaryQueue => ( RemoteDestination ? "/remote-temp-queue/" : "/temp-queue/" ) + PhysicalName, _ => "/queue/" + PhysicalName }; return result; } /// <summary> /// If the object passed in is equivalent, return true /// </summary> /// <param name="obj">the object to compare</param> /// <returns>true if this instance and obj are equivalent</returns> public override Boolean Equals( Object obj ) { var result = this == obj; if ( result || obj is not Destination other ) return result; result = GetDestinationType() == other.GetDestinationType() && PhysicalName.Equals( other.PhysicalName ); return result; } /// <summary> /// </summary> /// <returns>hashCode for this instance</returns> public override Int32 GetHashCode() { var answer = 37; if ( PhysicalName != null ) answer = PhysicalName.GetHashCode(); if ( IsTopic ) answer ^= 0xfabfab; return answer; } /// <summary> /// </summary> /// <returns>string representation of this instance</returns> public override String ToString() { return DestinationType switch { DestinationType.Topic => "topic://" + PhysicalName, DestinationType.TemporaryTopic => "temp-topic://" + PhysicalName, DestinationType.TemporaryQueue => "temp-queue://" + PhysicalName, _ => "queue://" + PhysicalName }; } public static Destination Transform( IDestination destination ) => destination switch { Destination dest => dest, ITemporaryQueue tempQueue => new TempQueue( tempQueue.QueueName, tempQueue.SkipDesinationNameFormatting ), ITemporaryTopic tempTopic => new TempTopic( tempTopic.TopicName, tempTopic.SkipDesinationNameFormatting ), IQueue queue => new Queue( queue.QueueName, queue.SkipDesinationNameFormatting ), _ => destination is ITopic topic ? new Topic( topic.TopicName, topic.SkipDesinationNameFormatting ) : null }; /// <summary> /// </summary> /// <returns>Returns the Destination type</returns> protected abstract Int32 GetDestinationType(); /// <summary> /// Create a Destination using the name given, the type is determined by the /// value of the type parameter. /// </summary> /// <param name="type"></param> /// <param name="pyhsicalName"></param> /// <param name="remote"></param> /// <param name="skipDesinationNameFormatting"> /// A value indicating whether the destination name formatting will be skipped /// or not. /// </param> /// <returns></returns> private static Destination CreateDestination( Int32 type, String pyhsicalName, Boolean remote, Boolean skipDesinationNameFormatting ) { if ( pyhsicalName == null ) return null; Destination result = type switch { StompTopic => new Topic( pyhsicalName, skipDesinationNameFormatting ), StompTemporaryTopic => new TempTopic( pyhsicalName, skipDesinationNameFormatting ), StompQueue => new Queue( pyhsicalName, skipDesinationNameFormatting ), _ => new TempQueue( pyhsicalName, skipDesinationNameFormatting ) }; result.RemoteDestination = remote; return result; } #region Constants /// <summary> /// Queue Destination object /// </summary> protected const Int32 StompQueue = 3; /// <summary> /// Temporary Queue Destination object /// </summary> protected const Int32 StompTemporaryQueue = 4; /// <summary> /// Temporary Topic Destination object /// </summary> protected const Int32 StompTemporaryTopic = 2; /// <summary> /// Topic Destination object /// </summary> protected const Int32 StompTopic = 1; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Collections.Generic; using System.Diagnostics; namespace System.Net.Mime { #region RFC2822 date time string format description // Format of Date Time string as described by RFC 2822 section 4.3 which obsoletes // some field formats that were allowed under RFC 822 // date-time = [ day-of-week "," ] date FWS time [CFWS] // day-of-week = ([FWS] day-name) / obs-day-of-week // day-name = "Mon" / "Tue" / "Wed" / "Thu" / "Fri" / "Sat" / "Sun" // date = day month year // year = 4*DIGIT / obs-year // month = (FWS month-name FWS) / obs-month // month-name = "Jan" / "Feb" / "Mar" / "Apr" / "May" / "Jun" / "Jul" / "Aug" / // "Sep" / "Oct" / "Nov" / "Dec" // day = ([FWS] 1*2DIGIT) / obs-day // time = time-of-day FWS zone // time-of-day = hour ":" minute [ ":" second ] // hour = 2DIGIT / obs-hour // minute = 2DIGIT / obs-minute // second = 2DIGIT / obs-second // zone = (( "+" / "-" ) 4DIGIT) / obs-zone #endregion // stores a Date and a Time Zone. These are parsed and formatted according to the // rules in RFC 2822 section 3.3. // This class is immutable internal class SmtpDateTime { #region constants // use this when a time zone is unknown or is not supplied internal const string UnknownTimeZoneDefaultOffset = "-0000"; internal const string UtcDefaultTimeZoneOffset = "+0000"; internal const int OffsetLength = 5; // range for absolute value of minutes. it is not necessary to include a max value for hours since // the two-digit value that is parsed can't exceed the max value of hours, which is 99 internal const int MaxMinuteValue = 59; // possible valid values for a date string // these do NOT include the timezone internal const string DateFormatWithDayOfWeek = "ddd, dd MMM yyyy HH:mm:ss"; internal const string DateFormatWithoutDayOfWeek = "dd MMM yyyy HH:mm:ss"; internal const string DateFormatWithDayOfWeekAndNoSeconds = "ddd, dd MMM yyyy HH:mm"; internal const string DateFormatWithoutDayOfWeekAndNoSeconds = "dd MMM yyyy HH:mm"; #endregion #region static fields // array of all possible date time values // if a string matches any one of these it will be parsed correctly internal static readonly string[] s_validDateTimeFormats = new string[] { DateFormatWithDayOfWeek, DateFormatWithoutDayOfWeek, DateFormatWithDayOfWeekAndNoSeconds, DateFormatWithoutDayOfWeekAndNoSeconds }; internal static readonly char[] s_allowedWhiteSpaceChars = new char[] { ' ', '\t' }; internal static readonly Dictionary<string, TimeSpan> s_timeZoneOffsetLookup = InitializeShortHandLookups(); // a TimeSpan must be between these two values in order for it to be within the range allowed // by RFC 2822 internal const long TimeSpanMaxTicks = TimeSpan.TicksPerHour * 99 + TimeSpan.TicksPerMinute * 59; // allowed max values for each digit. min value is always 0 internal const int OffsetMaxValue = 9959; #endregion #region static initializers internal static Dictionary<string, TimeSpan> InitializeShortHandLookups() { var tempTimeZoneOffsetLookup = new Dictionary<string, TimeSpan>(); // all well-known short hand time zone values and their semantic equivalents tempTimeZoneOffsetLookup.Add("UT", TimeSpan.Zero); // +0000 tempTimeZoneOffsetLookup.Add("GMT", TimeSpan.Zero); // +0000 tempTimeZoneOffsetLookup.Add("EDT", new TimeSpan(-4, 0, 0)); // -0400 tempTimeZoneOffsetLookup.Add("EST", new TimeSpan(-5, 0, 0)); // -0500 tempTimeZoneOffsetLookup.Add("CDT", new TimeSpan(-5, 0, 0)); // -0500 tempTimeZoneOffsetLookup.Add("CST", new TimeSpan(-6, 0, 0)); // -0600 tempTimeZoneOffsetLookup.Add("MDT", new TimeSpan(-6, 0, 0)); // -0600 tempTimeZoneOffsetLookup.Add("MST", new TimeSpan(-7, 0, 0)); // -0700 tempTimeZoneOffsetLookup.Add("PDT", new TimeSpan(-7, 0, 0)); // -0700 tempTimeZoneOffsetLookup.Add("PST", new TimeSpan(-8, 0, 0)); // -0800 return tempTimeZoneOffsetLookup; } #endregion #region private fields private readonly DateTime _date; private readonly TimeSpan _timeZone; // true if the time zone is unspecified i.e. -0000 // the time zone will usually be specified private readonly bool _unknownTimeZone = false; #endregion #region constructors internal SmtpDateTime(DateTime value) { _date = value; switch (value.Kind) { case DateTimeKind.Local: // GetUtcOffset takes local time zone information into account e.g. daylight savings time TimeSpan localTimeZone = TimeZoneInfo.Local.GetUtcOffset(value); _timeZone = ValidateAndGetSanitizedTimeSpan(localTimeZone); break; case DateTimeKind.Unspecified: _unknownTimeZone = true; break; case DateTimeKind.Utc: _timeZone = TimeSpan.Zero; break; } } internal SmtpDateTime(string value) { string timeZoneOffset; _date = ParseValue(value, out timeZoneOffset); if (!TryParseTimeZoneString(timeZoneOffset, out _timeZone)) { // time zone is unknown _unknownTimeZone = true; } } #endregion #region internal properties internal DateTime Date { get { if (_unknownTimeZone) { return DateTime.SpecifyKind(_date, DateTimeKind.Unspecified); } else { // DateTimeOffset will convert the value of this.date to the time as // specified in this.timeZone DateTimeOffset offset = new DateTimeOffset(_date, _timeZone); return offset.LocalDateTime; } } } #if DEBUG // this method is only called by test code internal string TimeZone => _unknownTimeZone ? UnknownTimeZoneDefaultOffset : TimeSpanToOffset(_timeZone); #endif #endregion #region internals // outputs the RFC 2822 formatted date string including time zone public override string ToString() => string.Format("{0} {1}", FormatDate(_date), _unknownTimeZone ? UnknownTimeZoneDefaultOffset : TimeSpanToOffset(_timeZone)); // returns true if the offset is of the form [+|-]dddd and // within the range 0000 to 9959 internal void ValidateAndGetTimeZoneOffsetValues(string offset, out bool positive, out int hours, out int minutes) { Debug.Assert(!string.IsNullOrEmpty(offset), "violation of precondition: offset must not be null or empty"); Debug.Assert(offset != UnknownTimeZoneDefaultOffset, "Violation of precondition: do not pass an unknown offset"); Debug.Assert(offset.StartsWith("-") || offset.StartsWith("+"), "offset initial character was not a + or -"); if (offset.Length != OffsetLength) { throw new FormatException(SR.MailDateInvalidFormat); } positive = offset.StartsWith("+", StringComparison.Ordinal); // TryParse will parse in base 10 by default. do not allow any styles of input beyond the default // which is numeric values only if (!int.TryParse(offset.Substring(1, 2), NumberStyles.None, CultureInfo.InvariantCulture, out hours)) { throw new FormatException(SR.MailDateInvalidFormat); } if (!int.TryParse(offset.Substring(3, 2), NumberStyles.None, CultureInfo.InvariantCulture, out minutes)) { throw new FormatException(SR.MailDateInvalidFormat); } // we only explicitly validate the minutes. they must be below 59 // the hours are implicitly validated as a number formed from a string of length // 2 can only be <= 99 if (minutes > MaxMinuteValue) { throw new FormatException(SR.MailDateInvalidFormat); } } // returns true if the time zone short hand is all alphabetical characters internal void ValidateTimeZoneShortHandValue(string value) { // time zones can't be empty Debug.Assert(!string.IsNullOrEmpty(value), "violation of precondition: offset must not be null or empty"); // time zones must all be alphabetical characters for (int i = 0; i < value.Length; i++) { if (!Char.IsLetter(value, i)) { throw new FormatException(SR.MailHeaderFieldInvalidCharacter); } } } // formats a date only. Does not include time zone internal string FormatDate(DateTime value) => value.ToString("ddd, dd MMM yyyy HH:mm:ss", CultureInfo.InvariantCulture); // parses the date and time zone // postconditions: // return value is valid DateTime representation of the Date portion of data // timeZone is the portion of data which should contain the time zone data // timeZone is NOT evaluated by ParseValue internal DateTime ParseValue(string data, out string timeZone) { // check that there is something to parse if (string.IsNullOrEmpty(data)) { throw new FormatException(SR.MailDateInvalidFormat); } // find the first occurrence of ':' // this tells us where the separator between hour and minute are int indexOfHourSeparator = data.IndexOf(':'); // no ':' means invalid value if (indexOfHourSeparator == -1) { throw new FormatException(SR.MailHeaderFieldInvalidCharacter); } // now we know where hours and minutes are separated. The first whitespace after // that MUST be the separator between the time portion and the timezone portion // timezone may have additional spaces, characters, or comments after it but // this is ok since we'll parse that whole section later int indexOfTimeZoneSeparator = data.IndexOfAny(s_allowedWhiteSpaceChars, indexOfHourSeparator); if (indexOfTimeZoneSeparator == -1) { throw new FormatException(SR.MailHeaderFieldInvalidCharacter); } // extract the time portion and remove all leading and trailing whitespace string date = data.Substring(0, indexOfTimeZoneSeparator).Trim(); // attempt to parse the DateTime component. DateTime dateValue; if (!DateTime.TryParseExact(date, s_validDateTimeFormats, CultureInfo.InvariantCulture, DateTimeStyles.AllowWhiteSpaces, out dateValue)) { throw new FormatException(SR.MailDateInvalidFormat); } // kind property will be Unspecified since no timezone info was in the date string Debug.Assert(dateValue.Kind == DateTimeKind.Unspecified); // extract the second half of the string. This will start with at least one whitespace character. // Trim the string to remove these characters. string timeZoneString = data.Substring(indexOfTimeZoneSeparator).Trim(); // find, if any, the first whitespace character after the timezone. // These will be CFWS and must be ignored. Remove them. int endOfTimeZoneOffset = timeZoneString.IndexOfAny(s_allowedWhiteSpaceChars); if (endOfTimeZoneOffset != -1) { timeZoneString = timeZoneString.Substring(0, endOfTimeZoneOffset); } if (string.IsNullOrEmpty(timeZoneString)) { throw new FormatException(SR.MailDateInvalidFormat); } timeZone = timeZoneString; return dateValue; } // if this returns true, timeZone is the correct TimeSpan representation of the input // if it returns false then the time zone is unknown and so timeZone must be ignored internal bool TryParseTimeZoneString(string timeZoneString, out TimeSpan timeZone) { // see if the zone is the special unspecified case, a numeric offset, or a shorthand string if (timeZoneString == UnknownTimeZoneDefaultOffset) { // The inputed time zone is the special value "unknown", -0000 timeZone = TimeSpan.Zero; return false; } else if ((timeZoneString[0] == '+' || timeZoneString[0] == '-')) { bool positive; int hours; int minutes; ValidateAndGetTimeZoneOffsetValues(timeZoneString, out positive, out hours, out minutes); // Apply the negative sign, if applicable, to whichever of hours or minutes is NOT 0. if (!positive) { if (hours != 0) { hours *= -1; } else if (minutes != 0) { minutes *= -1; } } timeZone = new TimeSpan(hours, minutes, 0); return true; } else { // not an offset so ensure that it contains no invalid characters ValidateTimeZoneShortHandValue(timeZoneString); // check if the shorthand value has a semantically equivalent offset return s_timeZoneOffsetLookup.TryGetValue(timeZoneString, out timeZone); } } internal TimeSpan ValidateAndGetSanitizedTimeSpan(TimeSpan span) { // sanitize the time span by removing the seconds and milliseconds. Days are not handled here TimeSpan sanitizedTimeSpan = new TimeSpan(span.Days, span.Hours, span.Minutes, 0, 0); // validate range of time span if (Math.Abs(sanitizedTimeSpan.Ticks) > TimeSpanMaxTicks) { throw new FormatException(SR.MailDateInvalidFormat); } return sanitizedTimeSpan; } // precondition: span must be sanitized and within a valid range internal string TimeSpanToOffset(TimeSpan span) { Debug.Assert(span.Seconds == 0, "Span had seconds value"); Debug.Assert(span.Milliseconds == 0, "Span had milliseconds value"); if (span.Ticks == 0) { return UtcDefaultTimeZoneOffset; } else { // get the total number of hours since TimeSpan.Hours won't go beyond 24 // ensure that it's a whole number since the fractional part represents minutes uint hours = (uint)Math.Abs(Math.Floor(span.TotalHours)); uint minutes = (uint)Math.Abs(span.Minutes); Debug.Assert((hours != 0) || (minutes != 0), "Input validation ensures hours or minutes isn't zero"); string output = span.Ticks > 0 ? "+" : "-"; // hours and minutes must be two digits if (hours < 10) { output += "0"; } output += hours.ToString(); if (minutes < 10) { output += "0"; } output += minutes.ToString(); return output; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Wealthperk.Web.ViewModels; using Wealthperk.ViewModel; using Wealthperk.Model; using Wealthperk.Web.Auth; using Microsoft.AspNetCore.Http; using Wealthperl.Model; using Microsoft.AspNetCore.Identity; using Wealthperk.Model.Accounts; using System.IO; using Wealthperk.Web.Formatting; using Wealthperk.ViewModel.Account; using Microsoft.AspNetCore.Authorization; using Wealthperk.Calculation; using Wealthperk.Model.Profile; namespace WelthPeck.Controllers { [Authorize] public class AccountController : Controller { private IUserAccountsRepository _accountRepo; private IUserAccountTimeseriesRepository _timeseriesRepo; private UserManager<UserInfo> _userManager; private IUserSettingsRepository _settingsRepo; private IUserProfileRepository _profileRepo; private IRiskStrategyConfiguration _risksConfig; private ICalculationService _calculation; private ICalculationConfiguration _calcConfig; public AccountController( IUserAccountsRepository accountRepo, UserManager<UserInfo> userManager, IUserAccountTimeseriesRepository timeseriesRepo, IUserSettingsRepository settingsRepo, IRiskStrategyConfiguration risksConfig, ICalculationConfiguration calcConfig, IUserProfileRepository profileRepo, ICalculationService calculation) { _accountRepo = accountRepo; _userManager = userManager; _timeseriesRepo = timeseriesRepo; _settingsRepo = settingsRepo; _risksConfig = risksConfig; _profileRepo = profileRepo; _calculation = calculation; _calcConfig = calcConfig; } [Produces("application/json")] [HttpGet] public async Task<IActionResult> Values() { var userName = HttpUserIdentity.CurrentUserName(User); var res = await _accountRepo.GetUserAccountsByUserNameAsync(userName); if (!res.Any()){ return BadRequest(new { message = "You have no accounts configured"}); } return Json(await GetAccountsWithValues(res)); } [HttpGet("~/account/values/{id}")] [Produces("application/json")] public async Task<IActionResult> Values(string id) { var userName = HttpUserIdentity.CurrentUserName(User); var res = await _accountRepo.GetUserAccountsByUserNameAsync(userName); if (!res.Any()){ return BadRequest(new { message = "You have no accounts configured"}); } var account = res.FirstOrDefault(x => x.AccountId == id); if (account == null){ return NotFound(new { message = "Account not found"}); } return Json(await GetAccountWithValues(account)); } [Produces("application/json")] [HttpGet] public async Task<IActionResult> Settings() { var userName = HttpUserIdentity.CurrentUserName(User); var settings = await _settingsRepo.GetUserSettingsByUserNameAsync(userName); var contribution = settings != null && settings.ContributionStrategy != null ? new ContributionSettings { contribution = settings.ContributionStrategy.AmountPerFrequency().FormatCurrency(),//"$250.10", frequency = settings.ContributionStrategy.ContributionFrequency?.ToString() ?? "N/A",//"Biweekly" description = string.Format("<p>{0} of your pay</p><p>{1} employer match</p>", settings.ContributionStrategy.SalaryPercent?.ToString("P0") ?? "N/A", settings.ContributionStrategy.CompanyMatch?.ToString("P0") ?? "N/A") } : ContributionSettings.Undefined(); var risks = settings != null && settings.RiskStrategy != null && _risksConfig.RiskStrategies.ContainsKey(settings.RiskStrategy) ? new RiskSettings { profileName = _risksConfig.RiskStrategies[settings.RiskStrategy].Name,//"Aggressive Growth", description = _risksConfig.RiskStrategies[settings.RiskStrategy].Description,//"<p>100% Growth Assets (Stocks)</p><p>0% Defensive Assets (Bonds)</p>", fee = string.Format("{0:0.00}%", _risksConfig.RiskStrategies[settings.RiskStrategy].Fee) //"0.20%" } : RiskSettings.Undefined(); return Json(new AccountSettings() { contribution = contribution, riskProfile = risks }); } [Produces("application/json")] [HttpGet] public async Task<IActionResult> Forecast() { var userName = HttpUserIdentity.CurrentUserName(User); var age = (await _profileRepo.GetUserProfileByUserNameAsync(userName) ?? UserProfile.Default()).Age(); var accounts = (await _accountRepo.GetUserAccountsByUserNameAsync(userName)); var currentBalance = (await Task.WhenAll(accounts.Select(acc=> _timeseriesRepo.GetLatestMarketValueForAccountAsync(acc.AccountId)))).Sum(); var startBalance = (await Task.WhenAll(accounts.Select(acc=> _timeseriesRepo.GetStartMarketValueForAccountAsync(acc.AccountId)))).Sum(); //var halfWay = startBalance + (currentBalance - startBalance)/2; var annualContribution = (await _settingsRepo.GetUserSettingsByUserNameAsync(userName))?.ContributionStrategy?.AnnualContribution() ?? 0; var byAmount = currentBalance.HasValue ? _calculation.PredictionForYears( startBalance: currentBalance.Value, annualContribution: annualContribution, annualGrowth: _calcConfig.DefaultGrowth, years: age.HasValue ? (_calcConfig.YearsAtRetirement - age.Value) : _calcConfig.YearsForPrediction) : default(double?); return Json(new Forecast{ byAmount = byAmount.FormatCurrency(),// "$1,019,101", byAge = age.HasValue ? $"{_calcConfig.YearsAtRetirement}" : $"{_calcConfig.YearsForPrediction}",//"65" currentAge = age.HasValue ? age.Value.ToString() : $"", //"52" currentAmount = currentBalance.FormatCurrency(),// "$51,823.33", forecast = new [] { new ChartPointReal { x = 1, label = "Joined Wealthperk", y = startBalance, z = startBalance }, //new ChartPointReal { x = 2, label = "", y = halfWay, z = halfWay }; new ChartPointReal { x = 2, label = age.HasValue ? $"{age} years old" : "current age", y = currentBalance, z = currentBalance }, //x = 3 new ChartPoint { x = 3, label = age.HasValue ? $"{_calcConfig.YearsAtRetirement} years old" : $" after {_calcConfig.YearsForPrediction} years", z = byAmount} //x = 4 } ,/*new [] { new ChartPointReal { x = 1, label = "Today", y = 180, z = 180 }, new ChartPointReal { x = 2, label = "", y = 240, z = 240 }, new ChartPointReal { x = 3, label = "48 years old", y = 360, z = 360 }, new ChartPoint { x = 4, label = "65 years old", z = 1000 } }*/ forRetirement = age.HasValue }); } private async Task<AccountBalance> GetAccountWithValues(AccountInfo account) { var values = await Task.WhenAll( _timeseriesRepo.GetLatestMarketValueForAccountAsync(account.AccountId), _timeseriesRepo.GetStartMarketValueForAccountAsync(account.AccountId), _timeseriesRepo.GetTotalCashFlowForAccountAsync(account.AccountId) ); double? mv = values[0]; double? earn = mv - values[1] - (values[2] ?? 0); return new AccountBalance { id = account.AccountId, name = account.DisplayName, balance = mv.FormatCurrency(), earnings = earn.FormatCurrencyWithNoSign(), feeSavings = "N/A", autodeposit = false, earningsSign = Math.Sign(earn ?? 0) }; } private async Task<PortfolioValue> GetAccountsWithValues(IEnumerable<AccountInfo> accounts) { double? retirementSavings = null; double? totalEarnings = null; var accountBalances = new List<AccountBalance>(); foreach (var account in accounts) { var values = await Task.WhenAll( _timeseriesRepo.GetLatestMarketValueForAccountAsync(account.AccountId), _timeseriesRepo.GetStartMarketValueForAccountAsync(account.AccountId), _timeseriesRepo.GetTotalCashFlowForAccountAsync(account.AccountId) ); double? mv = values[0];//await _timeseriesRepo.GetLatestMarketValueForAccountAsync(account.AccountId); double? earn = mv - values[1] - (values[2] ?? 0); retirementSavings = (mv.HasValue ? (retirementSavings.HasValue ? retirementSavings + mv.Value : mv) : retirementSavings); totalEarnings = (earn.HasValue ? (totalEarnings.HasValue ? totalEarnings + earn.Value : earn) : totalEarnings); accountBalances.Add(new AccountBalance { id = account.AccountId, name = account.DisplayName, balance = mv.FormatCurrency(), earnings = earn.FormatCurrencyWithNoSign(),//"$1,203.51" autodeposit = false, earningsSign = Math.Sign(earn ?? 0) }); } return new PortfolioValue() { total = new TotalValue { retirementSavings = retirementSavings.FormatCurrency(), returns = (totalEarnings/(retirementSavings - totalEarnings)).FormatPercentageWithSign(),//"+14.1%", totalEarnings = totalEarnings.FormatCurrencyWithSign(),//"+ $5,912.12", feeSavings = "N/A",//"$509", freeTrades = "N/A",//"629", dividents = "N/A"//"$643" }, accounts = accountBalances.ToArray() }; } } }
/* Copyright (c) 2005-2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Text; using PHP.Core; #if SILVERLIGHT using MathEx = PHP.CoreCLR.MathEx; #else using MathEx = System.Math; using System.Diagnostics; #endif namespace PHP.Library { /// <summary> /// Provides methods for strings UU-encoding and UU-decoding. /// </summary> /// <remarks> /// <para> /// Uuencode repeatedly takes in a group of three bytes, adding trailing zeros if there are fewer /// than three bytes left. These 24 bits are split into four groups of six which are treated as /// numbers between 0 and 63. Decimal 32 is added to each number and they are output as ASCII /// characters which will lie in the range 32 (space) to 32+63 = 95 (underscore). ASCII characters /// greater than 95 may also be used; however, only the six right-most bits are relevant. /// </para> /// <para> /// Each group of sixty output characters (corresponding to 45 input bytes) is output as a separate /// line preceded by an encoded character giving the number of encoded bytes on that line. /// For all lines except the last, this will be the character 'M' (ASCII code 77 = 32+45). /// If the input is not evenly divisible by 45, the last line will contain the remaining N /// output characters, preceded by the character whose code is 32+N. Finally, a line containing just /// a single space (or grave character) is output, followed by one line containing the string "end". /// </para> /// <para> /// Sometimes each data line has extra dummy characters (often the grave accent) added to avoid /// problems with mailers that strip trailing spaces. These characters are ignored by uudecode. /// The grave accent ('`') is used in place of a space character. /// When stripped of their high bits they both decode to 100000. /// </para> /// </remarks> public static class UUEncoder { private const char UUEncodeZero = '`'; /// <summary> /// Encodes an array of bytes using UU-encode algorithm. /// </summary> /// <param name="input">Array of bytes to be encoded.</param> /// <param name="output">Encoded output writer.</param> public static void Encode(byte[]/*!*/ input, TextWriter/*!*/ output) { if (input == null) throw new ArgumentNullException("input"); if (output == null) throw new ArgumentNullException("output"); if (input.Length == 0) return; const int max_bytes_per_line = 45; int remains; int full_lines = MathEx.DivRem(input.Length, max_bytes_per_line, out remains); int input_offset = 0; // encode full lines: for (int i = 0; i < full_lines; i++) { output.Write(EncodeByte(max_bytes_per_line)); for (int j = 0; j < max_bytes_per_line / 3; j++) { EncodeWriteTriplet(output, input[input_offset], input[input_offset + 1], input[input_offset + 2]); input_offset += 3; } output.Write('\n'); } // encode remaining bytes (if any): if (remains > 0) { output.Write(EncodeByte(remains)); // ceil(remains/3)*4 int full_triplets = MathEx.DivRem(remains, 3, out remains); // full triplets: for (int i = 0; i < full_triplets; i++) { EncodeWriteTriplet(output, input[input_offset], input[input_offset + 1], input[input_offset + 2]); input_offset += 3; } // remaining bytes: if (remains == 1) { EncodeWriteTriplet(output, input[input_offset], 0, 0); } else if (remains == 2) { EncodeWriteTriplet(output, input[input_offset], input[input_offset + 1], 0); } output.Write('\n'); } output.Write('`'); output.Write('\n'); } private static char EncodeByte(int b) { Debug.Assert(b <= 0x3f); return (b == 0) ? '`' : (char)(0x20 + b); } private static byte DecodeChar(int c) { return (byte)((c - 0x20) & 0x3f); } private static void EncodeWriteTriplet(TextWriter/*!*/ output, int a, int b, int c) { output.Write(EncodeByte(a >> 2)); output.Write(EncodeByte(((a << 4) | (b >> 4)) & 0x3f)); output.Write(EncodeByte(((b << 2) | (c >> 6)) & 0x3f)); output.Write(EncodeByte(c & 0x3f)); } /// <summary> /// Decodes textual data using UU-encode algorithm. /// </summary> /// <param name="input">Textual data reader.</param> /// <param name="output">Binary output writer.</param> /// <remarks>Whether input data has correct format.</remarks> public static bool Decode(TextReader/*!*/ input, MemoryStream/*!*/ output) { if (input == null) throw new ArgumentNullException("input"); if (output == null) throw new ArgumentNullException("output"); // empty input: if (input.Peek() == -1) return true; for (; ; ) { int line_length = input.Read(); if (line_length == -1) return false; line_length = DecodeChar((char)line_length); // stopped by '`' on the last line: if (line_length == 0) return input.Read() == (int)'\n'; int remains; int full_triplets = MathEx.DivRem(line_length, 3, out remains); for (int i = 0; i < full_triplets; i++) { int a = DecodeChar(input.Read()); int b = DecodeChar(input.Read()); int c = DecodeChar(input.Read()); int d = input.Read(); if (d == -1) return false; d = DecodeChar(d); output.WriteByte((byte)((a << 2 | b >> 4) & 0xff)); output.WriteByte((byte)((b << 4 | c >> 2) & 0xff)); output.WriteByte((byte)((c << 6 | d) & 0xff)); } if (remains > 0) { int a = DecodeChar(input.Read()); int b = DecodeChar(input.Read()); int c = DecodeChar(input.Read()); int d = input.Read(); if (d == -1) return false; d = DecodeChar(d); output.WriteByte((byte)(a << 2 | b >> 4)); if (remains == 2) output.WriteByte((byte)(b << 4 | c >> 2)); } if (input.Read() != (int)'\n') return false; } } /// <summary> /// Encodes a string using UU-encode algorithm. /// </summary> /// <param name="bytes">String of bytes to be encoded.</param> /// <returns>The encoded string.</returns> [ImplementsFunction("convert_uuencode")] public static string Encode(PhpBytes bytes) { byte[] data = (bytes != null) ? bytes.ReadonlyData : ArrayUtils.EmptyBytes; StringBuilder result = new StringBuilder((int)(data.Length * 1.38 + data.Length + 1)); Encode(data, new StringWriter(result)); return result.ToString(); } /// <summary> /// Decodes a uu-encoded string. /// </summary> /// <param name="data">Data to be decoded.</param> /// <returns>Decoded bytes.</returns> [ImplementsFunction("convert_uudecode")] public static PhpBytes Decode(string data) { if (data == null) data = ""; MemoryStream result = new MemoryStream((int)(data.Length * 0.75) + 2); if (!Decode(new StringReader(data), result)) PhpException.Throw(PhpError.Warning, LibResources.GetString("invalid_uuencoded_string")); return new PhpBytes(result.ToArray()); } } }
using Discord.Rest; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Model = Discord.API.Channel; namespace Discord.WebSocket { /// <summary> /// Represents a WebSocket-based guild channel. /// </summary> [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class SocketGuildChannel : SocketChannel, IGuildChannel { private ImmutableArray<Overwrite> _overwrites; /// <summary> /// Gets the guild associated with this channel. /// </summary> /// <returns> /// A guild object that this channel belongs to. /// </returns> public SocketGuild Guild { get; } /// <inheritdoc /> public string Name { get; private set; } /// <inheritdoc /> public int Position { get; private set; } /// <inheritdoc /> public virtual IReadOnlyCollection<Overwrite> PermissionOverwrites => _overwrites; /// <summary> /// Gets a collection of users that are able to view the channel. /// </summary> /// <returns> /// A read-only collection of users that can access the channel (i.e. the users seen in the user list). /// </returns> public new virtual IReadOnlyCollection<SocketGuildUser> Users => ImmutableArray.Create<SocketGuildUser>(); internal SocketGuildChannel(DiscordSocketClient discord, ulong id, SocketGuild guild) : base(discord, id) { Guild = guild; } internal static SocketGuildChannel Create(SocketGuild guild, ClientState state, Model model) { switch (model.Type) { case ChannelType.News: return SocketNewsChannel.Create(guild, state, model); case ChannelType.Text: return SocketTextChannel.Create(guild, state, model); case ChannelType.Voice: return SocketVoiceChannel.Create(guild, state, model); case ChannelType.Category: return SocketCategoryChannel.Create(guild, state, model); default: return new SocketGuildChannel(guild.Discord, model.Id, guild); } } /// <inheritdoc /> internal override void Update(ClientState state, Model model) { Name = model.Name.Value; Position = model.Position.Value; var overwrites = model.PermissionOverwrites.Value; var newOverwrites = ImmutableArray.CreateBuilder<Overwrite>(overwrites.Length); for (int i = 0; i < overwrites.Length; i++) newOverwrites.Add(overwrites[i].ToEntity()); _overwrites = newOverwrites.ToImmutable(); } /// <inheritdoc /> public Task ModifyAsync(Action<GuildChannelProperties> func, RequestOptions options = null) => ChannelHelper.ModifyAsync(this, Discord, func, options); /// <inheritdoc /> public Task DeleteAsync(RequestOptions options = null) => ChannelHelper.DeleteAsync(this, Discord, options); /// <summary> /// Gets the permission overwrite for a specific user. /// </summary> /// <param name="user">The user to get the overwrite from.</param> /// <returns> /// An overwrite object for the targeted user; <c>null</c> if none is set. /// </returns> public virtual OverwritePermissions? GetPermissionOverwrite(IUser user) { for (int i = 0; i < _overwrites.Length; i++) { if (_overwrites[i].TargetId == user.Id) return _overwrites[i].Permissions; } return null; } /// <summary> /// Gets the permission overwrite for a specific role. /// </summary> /// <param name="role">The role to get the overwrite from.</param> /// <returns> /// An overwrite object for the targeted role; <c>null</c> if none is set. /// </returns> public virtual OverwritePermissions? GetPermissionOverwrite(IRole role) { for (int i = 0; i < _overwrites.Length; i++) { if (_overwrites[i].TargetId == role.Id) return _overwrites[i].Permissions; } return null; } /// <summary> /// Adds or updates the permission overwrite for the given user. /// </summary> /// <param name="user">The user to add the overwrite to.</param> /// <param name="permissions">The overwrite to add to the user.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task representing the asynchronous permission operation for adding the specified permissions to the channel. /// </returns> public virtual async Task AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options = null) { await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, user, permissions, options).ConfigureAwait(false); } /// <summary> /// Adds or updates the permission overwrite for the given role. /// </summary> /// <param name="role">The role to add the overwrite to.</param> /// <param name="permissions">The overwrite to add to the role.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task representing the asynchronous permission operation for adding the specified permissions to the channel. /// </returns> public virtual async Task AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options = null) { await ChannelHelper.AddPermissionOverwriteAsync(this, Discord, role, permissions, options).ConfigureAwait(false); } /// <summary> /// Removes the permission overwrite for the given user, if one exists. /// </summary> /// <param name="user">The user to remove the overwrite from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task representing the asynchronous operation for removing the specified permissions from the channel. /// </returns> public virtual async Task RemovePermissionOverwriteAsync(IUser user, RequestOptions options = null) { await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, user, options).ConfigureAwait(false); } /// <summary> /// Removes the permission overwrite for the given role, if one exists. /// </summary> /// <param name="role">The role to remove the overwrite from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task representing the asynchronous operation for removing the specified permissions from the channel. /// </returns> public virtual async Task RemovePermissionOverwriteAsync(IRole role, RequestOptions options = null) { await ChannelHelper.RemovePermissionOverwriteAsync(this, Discord, role, options).ConfigureAwait(false); } public new virtual SocketGuildUser GetUser(ulong id) => null; /// <summary> /// Gets the name of the channel. /// </summary> /// <returns> /// A string that resolves to <see cref="SocketGuildChannel.Name"/>. /// </returns> public override string ToString() => Name; private string DebuggerDisplay => $"{Name} ({Id}, Guild)"; internal new SocketGuildChannel Clone() => MemberwiseClone() as SocketGuildChannel; //SocketChannel /// <inheritdoc /> internal override IReadOnlyCollection<SocketUser> GetUsersInternal() => Users; /// <inheritdoc /> internal override SocketUser GetUserInternal(ulong id) => GetUser(id); //IGuildChannel /// <inheritdoc /> IGuild IGuildChannel.Guild => Guild; /// <inheritdoc /> ulong IGuildChannel.GuildId => Guild.Id; /// <inheritdoc /> OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IRole role) => GetPermissionOverwrite(role); /// <inheritdoc /> OverwritePermissions? IGuildChannel.GetPermissionOverwrite(IUser user) => GetPermissionOverwrite(user); /// <inheritdoc /> async Task IGuildChannel.AddPermissionOverwriteAsync(IRole role, OverwritePermissions permissions, RequestOptions options) => await AddPermissionOverwriteAsync(role, permissions, options).ConfigureAwait(false); /// <inheritdoc /> async Task IGuildChannel.AddPermissionOverwriteAsync(IUser user, OverwritePermissions permissions, RequestOptions options) => await AddPermissionOverwriteAsync(user, permissions, options).ConfigureAwait(false); /// <inheritdoc /> async Task IGuildChannel.RemovePermissionOverwriteAsync(IRole role, RequestOptions options) => await RemovePermissionOverwriteAsync(role, options).ConfigureAwait(false); /// <inheritdoc /> async Task IGuildChannel.RemovePermissionOverwriteAsync(IUser user, RequestOptions options) => await RemovePermissionOverwriteAsync(user, options).ConfigureAwait(false); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create<IReadOnlyCollection<IGuildUser>>(Users).ToAsyncEnumerable(); /// <inheritdoc /> Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult<IGuildUser>(GetUser(id)); //IChannel /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable(); //Overridden in Text/Voice /// <inheritdoc /> Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult<IUser>(GetUser(id)); //Overridden in Text/Voice } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** * A class that provides CAST6 key encryption operations, * such as encoding data and generating keys. * * All the algorithms herein are from the Internet RFC * * RFC2612 - CAST6 (128bit block, 128-256bit key) * * and implement a simplified cryptography interface. */ public sealed class Cast6Engine : Cast5Engine { //==================================== // Useful constants //==================================== private const int ROUNDS = 12; private const int BLOCK_SIZE = 16; // bytes = 128 bits /* * Put the round and mask keys into an array. * Kr0[i] => _Kr[i*4 + 0] */ private int []_Kr = new int[ROUNDS*4]; // the rotating round key(s) private uint []_Km = new uint[ROUNDS*4]; // the masking round key(s) /* * Key setup */ private int []_Tr = new int[24 * 8]; private uint []_Tm = new uint[24 * 8]; private uint[] _workingKey = new uint[8]; public Cast6Engine() { } public override string AlgorithmName { get { return "CAST6"; } } public override void Reset() { } public override int GetBlockSize() { return BLOCK_SIZE; } //================================== // Private Implementation //================================== /* * Creates the subkeys using the same nomenclature * as described in RFC2612. * * See section 2.4 */ internal override void SetKey( byte[] key) { uint Cm = 0x5a827999; uint Mm = 0x6ed9eba1; int Cr = 19; int Mr = 17; /* * Determine the key size here, if required * * if keysize < 256 bytes, pad with 0 * * Typical key sizes => 128, 160, 192, 224, 256 */ for (int i=0; i< 24; i++) { for (int j=0; j< 8; j++) { _Tm[i*8 + j] = Cm; Cm += Mm; //mod 2^32; _Tr[i*8 + j] = Cr; Cr = (Cr + Mr) & 0x1f; // mod 32 } } byte[] tmpKey = new byte[64]; key.CopyTo(tmpKey, 0); // now create ABCDEFGH for (int i = 0; i < 8; i++) { _workingKey[i] = Pack.BE_To_UInt32(tmpKey, i*4); } // Generate the key schedule for (int i = 0; i < 12; i++) { // KAPPA <- W2i(KAPPA) int i2 = i*2 *8; _workingKey[6] ^= F1(_workingKey[7], _Tm[i2], _Tr[i2]); _workingKey[5] ^= F2(_workingKey[6], _Tm[i2+1], _Tr[i2+1]); _workingKey[4] ^= F3(_workingKey[5], _Tm[i2+2], _Tr[i2+2]); _workingKey[3] ^= F1(_workingKey[4], _Tm[i2+3], _Tr[i2+3]); _workingKey[2] ^= F2(_workingKey[3], _Tm[i2+4], _Tr[i2+4]); _workingKey[1] ^= F3(_workingKey[2], _Tm[i2+5], _Tr[i2+5]); _workingKey[0] ^= F1(_workingKey[1], _Tm[i2+6], _Tr[i2+6]); _workingKey[7] ^= F2(_workingKey[0], _Tm[i2+7], _Tr[i2+7]); // KAPPA <- W2i+1(KAPPA) i2 = (i*2 + 1)*8; _workingKey[6] ^= F1(_workingKey[7], _Tm[i2], _Tr[i2]); _workingKey[5] ^= F2(_workingKey[6], _Tm[i2+1], _Tr[i2+1]); _workingKey[4] ^= F3(_workingKey[5], _Tm[i2+2], _Tr[i2+2]); _workingKey[3] ^= F1(_workingKey[4], _Tm[i2+3], _Tr[i2+3]); _workingKey[2] ^= F2(_workingKey[3], _Tm[i2+4], _Tr[i2+4]); _workingKey[1] ^= F3(_workingKey[2], _Tm[i2+5], _Tr[i2+5]); _workingKey[0] ^= F1(_workingKey[1], _Tm[i2+6], _Tr[i2+6]); _workingKey[7] ^= F2(_workingKey[0], _Tm[i2+7], _Tr[i2+7]); // Kr_(i) <- KAPPA _Kr[i*4] = (int)(_workingKey[0] & 0x1f); _Kr[i*4 + 1] = (int)(_workingKey[2] & 0x1f); _Kr[i*4 + 2] = (int)(_workingKey[4] & 0x1f); _Kr[i*4 + 3] = (int)(_workingKey[6] & 0x1f); // Km_(i) <- KAPPA _Km[i*4] = _workingKey[7]; _Km[i*4 + 1] = _workingKey[5]; _Km[i*4 + 2] = _workingKey[3]; _Km[i*4 + 3] = _workingKey[1]; } } /** * Encrypt the given input starting at the given offset and place * the result in the provided buffer starting at the given offset. * * @param src The plaintext buffer * @param srcIndex An offset into src * @param dst The ciphertext buffer * @param dstIndex An offset into dst */ internal override int EncryptBlock( byte[] src, int srcIndex, byte[] dst, int dstIndex) { // process the input block // batch the units up into 4x32 bit chunks and go for it uint A = Pack.BE_To_UInt32(src, srcIndex); uint B = Pack.BE_To_UInt32(src, srcIndex + 4); uint C = Pack.BE_To_UInt32(src, srcIndex + 8); uint D = Pack.BE_To_UInt32(src, srcIndex + 12); uint[] result = new uint[4]; CAST_Encipher(A, B, C, D, result); // now stuff them into the destination block Pack.UInt32_To_BE(result[0], dst, dstIndex); Pack.UInt32_To_BE(result[1], dst, dstIndex + 4); Pack.UInt32_To_BE(result[2], dst, dstIndex + 8); Pack.UInt32_To_BE(result[3], dst, dstIndex + 12); return BLOCK_SIZE; } /** * Decrypt the given input starting at the given offset and place * the result in the provided buffer starting at the given offset. * * @param src The plaintext buffer * @param srcIndex An offset into src * @param dst The ciphertext buffer * @param dstIndex An offset into dst */ internal override int DecryptBlock( byte[] src, int srcIndex, byte[] dst, int dstIndex) { // process the input block // batch the units up into 4x32 bit chunks and go for it uint A = Pack.BE_To_UInt32(src, srcIndex); uint B = Pack.BE_To_UInt32(src, srcIndex + 4); uint C = Pack.BE_To_UInt32(src, srcIndex + 8); uint D = Pack.BE_To_UInt32(src, srcIndex + 12); uint[] result = new uint[4]; CAST_Decipher(A, B, C, D, result); // now stuff them into the destination block Pack.UInt32_To_BE(result[0], dst, dstIndex); Pack.UInt32_To_BE(result[1], dst, dstIndex + 4); Pack.UInt32_To_BE(result[2], dst, dstIndex + 8); Pack.UInt32_To_BE(result[3], dst, dstIndex + 12); return BLOCK_SIZE; } /** * Does the 12 quad rounds rounds to encrypt the block. * * @param A the 00-31 bits of the plaintext block * @param B the 32-63 bits of the plaintext block * @param C the 64-95 bits of the plaintext block * @param D the 96-127 bits of the plaintext block * @param result the resulting ciphertext */ private void CAST_Encipher( uint A, uint B, uint C, uint D, uint[] result) { for (int i = 0; i < 6; i++) { int x = i*4; // BETA <- Qi(BETA) C ^= F1(D, _Km[x], _Kr[x]); B ^= F2(C, _Km[x + 1], _Kr[x + 1]); A ^= F3(B, _Km[x + 2], _Kr[x + 2]); D ^= F1(A, _Km[x + 3], _Kr[x + 3]); } for (int i = 6; i < 12; i++) { int x = i*4; // BETA <- QBARi(BETA) D ^= F1(A, _Km[x + 3], _Kr[x + 3]); A ^= F3(B, _Km[x + 2], _Kr[x + 2]); B ^= F2(C, _Km[x + 1], _Kr[x + 1]); C ^= F1(D, _Km[x], _Kr[x]); } result[0] = A; result[1] = B; result[2] = C; result[3] = D; } /** * Does the 12 quad rounds rounds to decrypt the block. * * @param A the 00-31 bits of the ciphertext block * @param B the 32-63 bits of the ciphertext block * @param C the 64-95 bits of the ciphertext block * @param D the 96-127 bits of the ciphertext block * @param result the resulting plaintext */ private void CAST_Decipher( uint A, uint B, uint C, uint D, uint[] result) { for (int i = 0; i < 6; i++) { int x = (11-i)*4; // BETA <- Qi(BETA) C ^= F1(D, _Km[x], _Kr[x]); B ^= F2(C, _Km[x + 1], _Kr[x + 1]); A ^= F3(B, _Km[x + 2], _Kr[x + 2]); D ^= F1(A, _Km[x + 3], _Kr[x + 3]); } for (int i=6; i<12; i++) { int x = (11-i)*4; // BETA <- QBARi(BETA) D ^= F1(A, _Km[x + 3], _Kr[x + 3]); A ^= F3(B, _Km[x + 2], _Kr[x + 2]); B ^= F2(C, _Km[x + 1], _Kr[x + 1]); C ^= F1(D, _Km[x], _Kr[x]); } result[0] = A; result[1] = B; result[2] = C; result[3] = D; } } } #endif
namespace android.view { [global::MonoJavaBridge.JavaClass()] public sealed partial class ViewTreeObserver : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal ViewTreeObserver(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_))] public partial interface OnGlobalFocusChangeListener : global::MonoJavaBridge.IJavaObject { void onGlobalFocusChanged(android.view.View arg0, android.view.View arg1); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener))] internal sealed partial class OnGlobalFocusChangeListener_ : java.lang.Object, OnGlobalFocusChangeListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnGlobalFocusChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.view.ViewTreeObserver.OnGlobalFocusChangeListener.onGlobalFocusChanged(android.view.View arg0, android.view.View arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_.staticClass, "onGlobalFocusChanged", "(Landroid/view/View;Landroid/view/View;)V", ref global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } static OnGlobalFocusChangeListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnGlobalFocusChangeListener")); } } public delegate void OnGlobalFocusChangeListenerDelegate(android.view.View arg0, android.view.View arg1); internal partial class OnGlobalFocusChangeListenerDelegateWrapper : java.lang.Object, OnGlobalFocusChangeListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnGlobalFocusChangeListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnGlobalFocusChangeListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper.staticClass, global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper._m0); Init(@__env, handle); } static OnGlobalFocusChangeListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver_OnGlobalFocusChangeListenerDelegateWrapper")); } } internal partial class OnGlobalFocusChangeListenerDelegateWrapper { private OnGlobalFocusChangeListenerDelegate myDelegate; public void onGlobalFocusChanged(android.view.View arg0, android.view.View arg1) { myDelegate(arg0, arg1); } public static implicit operator OnGlobalFocusChangeListenerDelegateWrapper(OnGlobalFocusChangeListenerDelegate d) { global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper ret = new global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnGlobalLayoutListener_))] public partial interface OnGlobalLayoutListener : global::MonoJavaBridge.IJavaObject { void onGlobalLayout(); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnGlobalLayoutListener))] internal sealed partial class OnGlobalLayoutListener_ : java.lang.Object, OnGlobalLayoutListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnGlobalLayoutListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.view.ViewTreeObserver.OnGlobalLayoutListener.onGlobalLayout() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.OnGlobalLayoutListener_.staticClass, "onGlobalLayout", "()V", ref global::android.view.ViewTreeObserver.OnGlobalLayoutListener_._m0); } static OnGlobalLayoutListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnGlobalLayoutListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnGlobalLayoutListener")); } } public delegate void OnGlobalLayoutListenerDelegate(); internal partial class OnGlobalLayoutListenerDelegateWrapper : java.lang.Object, OnGlobalLayoutListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnGlobalLayoutListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnGlobalLayoutListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper.staticClass, global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper._m0); Init(@__env, handle); } static OnGlobalLayoutListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver_OnGlobalLayoutListenerDelegateWrapper")); } } internal partial class OnGlobalLayoutListenerDelegateWrapper { private OnGlobalLayoutListenerDelegate myDelegate; public void onGlobalLayout() { myDelegate(); } public static implicit operator OnGlobalLayoutListenerDelegateWrapper(OnGlobalLayoutListenerDelegate d) { global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper ret = new global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnPreDrawListener_))] public partial interface OnPreDrawListener : global::MonoJavaBridge.IJavaObject { bool onPreDraw(); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnPreDrawListener))] internal sealed partial class OnPreDrawListener_ : java.lang.Object, OnPreDrawListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnPreDrawListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; bool android.view.ViewTreeObserver.OnPreDrawListener.onPreDraw() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.ViewTreeObserver.OnPreDrawListener_.staticClass, "onPreDraw", "()Z", ref global::android.view.ViewTreeObserver.OnPreDrawListener_._m0); } static OnPreDrawListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnPreDrawListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnPreDrawListener")); } } public delegate bool OnPreDrawListenerDelegate(); internal partial class OnPreDrawListenerDelegateWrapper : java.lang.Object, OnPreDrawListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnPreDrawListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnPreDrawListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper.staticClass, global::android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper._m0); Init(@__env, handle); } static OnPreDrawListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver_OnPreDrawListenerDelegateWrapper")); } } internal partial class OnPreDrawListenerDelegateWrapper { private OnPreDrawListenerDelegate myDelegate; public bool onPreDraw() { return myDelegate(); } public static implicit operator OnPreDrawListenerDelegateWrapper(OnPreDrawListenerDelegate d) { global::android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper ret = new global::android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnScrollChangedListener_))] public partial interface OnScrollChangedListener : global::MonoJavaBridge.IJavaObject { void onScrollChanged(); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnScrollChangedListener))] internal sealed partial class OnScrollChangedListener_ : java.lang.Object, OnScrollChangedListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnScrollChangedListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.view.ViewTreeObserver.OnScrollChangedListener.onScrollChanged() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.OnScrollChangedListener_.staticClass, "onScrollChanged", "()V", ref global::android.view.ViewTreeObserver.OnScrollChangedListener_._m0); } static OnScrollChangedListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnScrollChangedListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnScrollChangedListener")); } } public delegate void OnScrollChangedListenerDelegate(); internal partial class OnScrollChangedListenerDelegateWrapper : java.lang.Object, OnScrollChangedListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnScrollChangedListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnScrollChangedListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper.staticClass, global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper._m0); Init(@__env, handle); } static OnScrollChangedListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver_OnScrollChangedListenerDelegateWrapper")); } } internal partial class OnScrollChangedListenerDelegateWrapper { private OnScrollChangedListenerDelegate myDelegate; public void onScrollChanged() { myDelegate(); } public static implicit operator OnScrollChangedListenerDelegateWrapper(OnScrollChangedListenerDelegate d) { global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper ret = new global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } [global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnTouchModeChangeListener_))] public partial interface OnTouchModeChangeListener : global::MonoJavaBridge.IJavaObject { void onTouchModeChanged(bool arg0); } [global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnTouchModeChangeListener))] internal sealed partial class OnTouchModeChangeListener_ : java.lang.Object, OnTouchModeChangeListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal OnTouchModeChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void android.view.ViewTreeObserver.OnTouchModeChangeListener.onTouchModeChanged(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.OnTouchModeChangeListener_.staticClass, "onTouchModeChanged", "(Z)V", ref global::android.view.ViewTreeObserver.OnTouchModeChangeListener_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } static OnTouchModeChangeListener_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnTouchModeChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnTouchModeChangeListener")); } } public delegate void OnTouchModeChangeListenerDelegate(bool arg0); internal partial class OnTouchModeChangeListenerDelegateWrapper : java.lang.Object, OnTouchModeChangeListener { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected OnTouchModeChangeListenerDelegateWrapper(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public OnTouchModeChangeListenerDelegateWrapper() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper._m0.native == global::System.IntPtr.Zero) global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper._m0 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper.staticClass, global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper._m0); Init(@__env, handle); } static OnTouchModeChangeListenerDelegateWrapper() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver_OnTouchModeChangeListenerDelegateWrapper")); } } internal partial class OnTouchModeChangeListenerDelegateWrapper { private OnTouchModeChangeListenerDelegate myDelegate; public void onTouchModeChanged(bool arg0) { myDelegate(arg0); } public static implicit operator OnTouchModeChangeListenerDelegateWrapper(OnTouchModeChangeListenerDelegate d) { global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper ret = new global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper(); ret.myDelegate = d; global::MonoJavaBridge.JavaBridge.SetGCHandle(global::MonoJavaBridge.JNIEnv.ThreadEnv, ret); return ret; } } private static global::MonoJavaBridge.MethodId _m0; public bool isAlive() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.ViewTreeObserver.staticClass, "isAlive", "()Z", ref global::android.view.ViewTreeObserver._m0); } private static global::MonoJavaBridge.MethodId _m1; public void addOnGlobalFocusChangeListener(android.view.ViewTreeObserver.OnGlobalFocusChangeListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "addOnGlobalFocusChangeListener", "(Landroid/view/ViewTreeObserver$OnGlobalFocusChangeListener;)V", ref global::android.view.ViewTreeObserver._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void addOnGlobalFocusChangeListener(global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegate arg0) { addOnGlobalFocusChangeListener((global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m2; public void removeOnGlobalFocusChangeListener(android.view.ViewTreeObserver.OnGlobalFocusChangeListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "removeOnGlobalFocusChangeListener", "(Landroid/view/ViewTreeObserver$OnGlobalFocusChangeListener;)V", ref global::android.view.ViewTreeObserver._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void removeOnGlobalFocusChangeListener(global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegate arg0) { removeOnGlobalFocusChangeListener((global::android.view.ViewTreeObserver.OnGlobalFocusChangeListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m3; public void addOnGlobalLayoutListener(android.view.ViewTreeObserver.OnGlobalLayoutListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "addOnGlobalLayoutListener", "(Landroid/view/ViewTreeObserver$OnGlobalLayoutListener;)V", ref global::android.view.ViewTreeObserver._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void addOnGlobalLayoutListener(global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegate arg0) { addOnGlobalLayoutListener((global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m4; public void removeGlobalOnLayoutListener(android.view.ViewTreeObserver.OnGlobalLayoutListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "removeGlobalOnLayoutListener", "(Landroid/view/ViewTreeObserver$OnGlobalLayoutListener;)V", ref global::android.view.ViewTreeObserver._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void removeGlobalOnLayoutListener(global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegate arg0) { removeGlobalOnLayoutListener((global::android.view.ViewTreeObserver.OnGlobalLayoutListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m5; public void addOnPreDrawListener(android.view.ViewTreeObserver.OnPreDrawListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "addOnPreDrawListener", "(Landroid/view/ViewTreeObserver$OnPreDrawListener;)V", ref global::android.view.ViewTreeObserver._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void addOnPreDrawListener(global::android.view.ViewTreeObserver.OnPreDrawListenerDelegate arg0) { addOnPreDrawListener((global::android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m6; public void removeOnPreDrawListener(android.view.ViewTreeObserver.OnPreDrawListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "removeOnPreDrawListener", "(Landroid/view/ViewTreeObserver$OnPreDrawListener;)V", ref global::android.view.ViewTreeObserver._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void removeOnPreDrawListener(global::android.view.ViewTreeObserver.OnPreDrawListenerDelegate arg0) { removeOnPreDrawListener((global::android.view.ViewTreeObserver.OnPreDrawListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m7; public void addOnScrollChangedListener(android.view.ViewTreeObserver.OnScrollChangedListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "addOnScrollChangedListener", "(Landroid/view/ViewTreeObserver$OnScrollChangedListener;)V", ref global::android.view.ViewTreeObserver._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void addOnScrollChangedListener(global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegate arg0) { addOnScrollChangedListener((global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m8; public void removeOnScrollChangedListener(android.view.ViewTreeObserver.OnScrollChangedListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "removeOnScrollChangedListener", "(Landroid/view/ViewTreeObserver$OnScrollChangedListener;)V", ref global::android.view.ViewTreeObserver._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void removeOnScrollChangedListener(global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegate arg0) { removeOnScrollChangedListener((global::android.view.ViewTreeObserver.OnScrollChangedListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m9; public void addOnTouchModeChangeListener(android.view.ViewTreeObserver.OnTouchModeChangeListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "addOnTouchModeChangeListener", "(Landroid/view/ViewTreeObserver$OnTouchModeChangeListener;)V", ref global::android.view.ViewTreeObserver._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void addOnTouchModeChangeListener(global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegate arg0) { addOnTouchModeChangeListener((global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m10; public void removeOnTouchModeChangeListener(android.view.ViewTreeObserver.OnTouchModeChangeListener arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "removeOnTouchModeChangeListener", "(Landroid/view/ViewTreeObserver$OnTouchModeChangeListener;)V", ref global::android.view.ViewTreeObserver._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public void removeOnTouchModeChangeListener(global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegate arg0) { removeOnTouchModeChangeListener((global::android.view.ViewTreeObserver.OnTouchModeChangeListenerDelegateWrapper)arg0); } private static global::MonoJavaBridge.MethodId _m11; public void dispatchOnGlobalLayout() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.ViewTreeObserver.staticClass, "dispatchOnGlobalLayout", "()V", ref global::android.view.ViewTreeObserver._m11); } private static global::MonoJavaBridge.MethodId _m12; public bool dispatchOnPreDraw() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.ViewTreeObserver.staticClass, "dispatchOnPreDraw", "()Z", ref global::android.view.ViewTreeObserver._m12); } static ViewTreeObserver() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.ViewTreeObserver.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver")); } } }
/******************************************************************************* INTEL CORPORATION PROPRIETARY INFORMATION This software is supplied under the terms of a license agreement or nondisclosure agreement with Intel Corporation and may not be copied or disclosed except in accordance with the terms of that agreement Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved. *******************************************************************************/ using UnityEngine; using System.Collections; using UnityEditor; using System.Linq; using System.Collections.Generic; using RSUnityToolkit; /// <summary> /// Action base custom editor. This class is reponsible to draw the custom controls in order to edit the action, triggers and rules. /// </summary> [CanEditMultipleObjects] [CustomEditor(typeof(BaseAction), true)] public class BaseActionEditor: Editor { #region Private Fields private SerializedProperty _supportedTriggers; private GUIStyle _descBoxStyle = null; private GUIStyle _bigBoxStyle = null; private GUIStyle _popupStyle = null; private static Dictionary<string, string> _friendlyNames = new Dictionary<string, string>(); private BaseRule _ruleToReset = null; private BaseRule _ruleToRemove = null; private System.Type _ruleToAdd = null; private Trigger _triggerToAddRuleTo = null; private Trigger _triggerToReset = null; private Trigger _triggerToRemove = null; private System.Type _triggerToAdd = null; private List<string> _showFirstProp = new List<string>(); #endregion #region Unity's override methods public void OnEnable() { _descBoxStyle = null; _supportedTriggers = serializedObject.FindProperty ("SupportedTriggers"); ((BaseAction)target).InitializeSupportedTriggers(); } // This function is called every editor gui update. In here we are diong our magic to show all to the user in a nice way. public override void OnInspectorGUI() { //Setting styles if ( _descBoxStyle == null) { _descBoxStyle = new GUIStyle(GUI.skin.FindStyle("Box")); _descBoxStyle.alignment = TextAnchor.UpperLeft; _descBoxStyle.normal.textColor = Color.white; _descBoxStyle.stretchWidth = true; _bigBoxStyle = new GUIStyle(GUI.skin.FindStyle("Box")); _bigBoxStyle.alignment = TextAnchor.UpperLeft; _bigBoxStyle.normal.textColor = Color.white; _bigBoxStyle.stretchHeight = true; _bigBoxStyle.normal.background = (Texture2D) Resources.Load("SourceBack"); _popupStyle = new GUIStyle(GUI.skin.FindStyle("Popup")); _popupStyle.fontStyle = (FontStyle.Normal); _popupStyle.stretchHeight = true; } EditorGUIUtility.LookLikeInspector(); serializedObject.Update(); // update the serialized object since the last time this method was called. BaseAction myTarget = (BaseAction)target; myTarget.UpdateInspector(); SerializedProperty script = serializedObject.FindProperty("m_Script"); EditorGUILayout.PropertyField(script, new GUIContent("Script",myTarget.GetActionDescription())); //Show first public visible fields with the Attribute "ShowAtfirst" SerializedProperty prop = serializedObject.GetIterator(); prop.NextVisible(true ); do { if (ShouldShowFirst(prop)) { EditorGUILayout.PropertyField(prop,true); } } while (prop.NextVisible(false )); //then show Triggers Rect rect = EditorGUILayout.BeginVertical(); GUI.Box (rect,"",_bigBoxStyle); if (myTarget.IsSupportCustomTriggers()) { GUILayout.Space(5); // Add Trigger row - Combo-box + Add Button Rect addTriggerRect = EditorGUILayout.BeginHorizontal(); { if (_triggerToAdd != null) { // If user pressed on "Add" button - add the selected trigger to the action's supported triggers _supportedTriggers.InsertArrayElementAtIndex(0); _supportedTriggers.GetArrayElementAtIndex(0).objectReferenceValue = myTarget.AddHiddenComponent(_triggerToAdd); ((Trigger)_supportedTriggers.GetArrayElementAtIndex(0).objectReferenceValue).CleanRules(); _triggerToAdd = null; } GUILayout.Box("Add Triger", _popupStyle ); var evt = Event.current; if (evt.type == EventType.mouseDown) { //Getting all Triggers List<System.Type> possibleTriggers = myTarget.GetSupprtedTriggers(); var mousePos = evt.mousePosition; if (addTriggerRect.Contains (mousePos)) { // Now create the menu, add items and show it var menu = new GenericMenu (); for (int i = 0; i < possibleTriggers.Count; i++) { string triggerFriendlyName = ""; if (!_friendlyNames.ContainsKey(possibleTriggers[i].FullName)) { GameObject g = new GameObject("temp"); Trigger triggerTemp = (Trigger) g.AddComponent(possibleTriggers[i]); _friendlyNames.Add(possibleTriggers[i].FullName, triggerTemp.FriendlyName); DestroyImmediate(g); } triggerFriendlyName = _friendlyNames[possibleTriggers[i].FullName]; menu.AddItem(new GUIContent(triggerFriendlyName), false, AddTrigger, possibleTriggers[i]); } menu.ShowAsContext (); evt.Use(); } } } EditorGUILayout.EndHorizontal(); } // go over all the Action's supported triggers and add them to the inspector. for (int i =0; i < _supportedTriggers.arraySize; i++) { //Get Trigger and update rules Trigger trigger = (Trigger)_supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue; if (trigger == null) { ((BaseAction)target).InitializeSupportedTriggers(); EditorGUILayout.EndVertical(); return; } // Trigger Row - Foldout + Reset trigger button + Delete trigger Rect triggerRect = EditorGUILayout.BeginHorizontal(); { trigger.FoldoutOpen = GUIUtils.Foldout(trigger.FoldoutOpen, trigger.FriendlyName); if (trigger.FoldoutOpen) { List<System.Type> supprtedRules1 = trigger.GetSupportedRules(); Rect rectRuleAddButton = EditorGUILayout.BeginHorizontal(); GUILayout.Box("Add", _popupStyle, GUILayout.Width(50) ); EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); var evt = Event.current; if (evt.type == EventType.mouseDown) { var mousePos = evt.mousePosition; if (rectRuleAddButton.Contains (mousePos)) { // Now create the menu, add items and show it var menu1 = new GenericMenu (); for (int ri = 0; ri < supprtedRules1.Count(); ri++) { string ruleFriendlyName = ""; if (!_friendlyNames.ContainsKey(supprtedRules1[ri].FullName)) { GameObject g = new GameObject("temp"); BaseRule ruleTemp = (BaseRule)g.AddComponent(supprtedRules1[ri]); _friendlyNames.Add(supprtedRules1[ri].FullName, ruleTemp.FriendlyName); DestroyImmediate(g); } ruleFriendlyName = _friendlyNames[supprtedRules1[ri].FullName]; menu1.AddItem (new GUIContent (ruleFriendlyName), false, AddRule, supprtedRules1[ri]); } menu1.ShowAsContext (); evt.Use(); _triggerToAddRuleTo = trigger; } } } } EditorGUILayout.EndHorizontal(); SetTriggersContextMenu(triggerRect, myTarget, trigger); // show trigger's rules if opened if (trigger.FoldoutOpen) { SerializedObject obj = new SerializedObject(_supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue); SerializedProperty rules = obj.FindProperty("Rules"); if (true) { // Add Trigger row - Combo-box + Add Button EditorGUILayout.BeginHorizontal(); { //Adding combo-box control to the inspector with the list of triggers. if ( _triggerToAddRuleTo == trigger && _ruleToAdd != null) { // If user pressed on "Add" button - add the selected trigger to the action's supported triggers rules.InsertArrayElementAtIndex(0); rules.GetArrayElementAtIndex(0).objectReferenceValue = myTarget.AddHiddenComponent(_ruleToAdd); // initialize rules _ruleToAdd = null; _triggerToAddRuleTo = null; } } EditorGUILayout.EndHorizontal(); GUILayout.Space(5); } for (int j = 0; j < rules.arraySize; j++) { BaseRule rule = (BaseRule)rules.GetArrayElementAtIndex(j).objectReferenceValue; DrawRuleInspector(rule); //Reset Rule if (_ruleToReset != null && _ruleToReset == rule) { rule.ActionOwner = null; rules.GetArrayElementAtIndex(j).objectReferenceValue = myTarget.AddHiddenComponent(_ruleToReset.GetType()); // Save folded state ((BaseRule)rules.GetArrayElementAtIndex(j).objectReferenceValue).FoldoutOpen = rule.FoldoutOpen; _ruleToReset = null; } //Remove Rule if (_ruleToRemove != null && _ruleToRemove == rule) { // delete the trigger and reorganize the array var r = rules.GetArrayElementAtIndex(j).objectReferenceValue; rules.DeleteArrayElementAtIndex(j); ((BaseRule)r).ActionOwner = null; for (int k = j; k < rules.arraySize - 1; k++) { rules.MoveArrayElement(k+1, k); } rules.arraySize--; _ruleToRemove = null; } } //Save changes to the rule obj.ApplyModifiedProperties(); } // Reset Trigger if (_triggerToReset != null && _triggerToReset == trigger) { trigger.ActionOwner = null; foreach (BaseRule r in trigger.Rules) { r.ActionOwner = null; } _supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue = myTarget.AddHiddenComponent(trigger.GetType()); Trigger oldTrigger = trigger; trigger = (Trigger)_supportedTriggers.GetArrayElementAtIndex(i).objectReferenceValue; trigger.CleanRules(); //trigger.SetDefaults(myTarget); myTarget.SetDefaultTriggerValues(i, trigger); // Save folded state trigger.FoldoutOpen = oldTrigger.FoldoutOpen; _triggerToReset = null; break; } // Remove Trigger if (_triggerToRemove != null && _triggerToRemove == trigger) { // delete the trigger and reorganize the array _supportedTriggers.DeleteArrayElementAtIndex(i); trigger.ActionOwner = null; if (trigger.Rules != null) { foreach (BaseRule r in trigger.Rules) { if (r != null) { r.ActionOwner = null; } } } for (int j = i; j < _supportedTriggers.arraySize - 1; j++) { _supportedTriggers.MoveArrayElement(j+1, j); } _supportedTriggers.arraySize--; break; } } EditorGUILayout.Space(); EditorGUILayout.EndVertical(); // Draw the rest of the control except several predefined fields or the fields which are marked as show first prop = serializedObject.GetIterator(); prop.NextVisible(true ); do { if (prop.name != "m_Script" && !ShouldShowFirst(prop)) { EditorGUILayout.PropertyField(prop,true); } } while (prop.NextVisible(false )); //Save changes to the Action Script serializedObject.ApplyModifiedProperties (); } #endregion #region Private methods /// <summary> /// Returns true or false if to show the this property before the Triggers or not. /// </summary> /// <param name='prop'> /// property in question. /// </param> private bool ShouldShowFirst(SerializedProperty prop) { if (_showFirstProp.Contains(prop.name)) { return true; } BaseAction myTarget = (BaseAction)target; var o = myTarget.GetType().GetFields( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance ).FirstOrDefault(i => i.Name == prop.name); if (o != null) { var attributes = o.GetCustomAttributes(typeof(BaseAction.ShowAtFirst), false); if (attributes.Length > 0) { _showFirstProp.Add(prop.name); return true; } } return false; } /// <summary> /// Sets the rules context menu (add, remove, etc.) /// </summary> /// <param name='contextRect'> /// Context active rectangle for mouse click /// </param> /// <param name='rule'> /// Rule in question /// </param> private void SetRulesContextMenu(Rect contextRect, BaseRule rule) { var evt = Event.current; if (evt.type == EventType.ContextClick) { var mousePos = evt.mousePosition; if (contextRect.Contains (mousePos)) { // Now create the menu, add items and show it var menu = new GenericMenu (); menu.AddItem (new GUIContent ("Reset"), false, ResetRule, rule); menu.AddItem (new GUIContent ("Remove"), false, RemoveRule, rule); menu.ShowAsContext (); evt.Use(); } } } /// <summary> /// Sets the triggers context menu. /// </summary> /// <param name='contextRect'> /// Context active rectangle for mouse click /// </param> /// <param name='action'> /// Action that the trigger is linked to /// </param> /// <param name='trigger'> /// the Trigger in question /// </param> private void SetTriggersContextMenu(Rect contextRect, BaseAction action, Trigger trigger) { var evt = Event.current; if (evt.type == EventType.ContextClick) { var mousePos = evt.mousePosition; if (contextRect.Contains (mousePos)) { // Now create the menu, add items and show it var menu = new GenericMenu (); menu.AddItem (new GUIContent ("Reset"), false, ResetTrigger, trigger); if( action.IsSupportCustomTriggers() ) { menu.AddItem (new GUIContent ("Remove"), false, RemoveTrigger, trigger); } menu.ShowAsContext (); evt.Use(); } } } /// <summary> /// Set a rule to be added. /// </summary> /// <param name='obj'> /// Object - rule to add. Must derive from BaseRule /// </param> private void AddRule(object obj) { System.Type ruleType = (System.Type)obj; _ruleToAdd = ruleType; } /// <summary> /// Set a trigger to be added /// </summary> /// <param name='obj'> /// Object - trigger to add. Must derive from Trigger class. /// </param> private void AddTrigger(object obj) { // If user pressed on "Add" button - add the selected trigger to the action's supported triggers System.Type triggerType = (System.Type)obj; _triggerToAdd = triggerType; } /// <summary> /// Set the Rule to reset. /// </summary> /// <param name='obj'> /// Object - rule to reset. Must derive from BaseRule. /// </param> private void ResetRule(object obj) { _ruleToReset = (BaseRule)obj; } /// <summary> /// Set the rule to remove /// </summary> /// <param name='obj'> /// Object - rule to remove. Must derive from BaseRule. /// </param> private void RemoveRule(object obj) { _ruleToRemove = (BaseRule)obj; } /// <summary> /// Set the trigger to reset /// </summary> /// <param name='obj'> /// Object - trigger to reset. Must derive from Trigger class. /// </param> private void ResetTrigger(object obj) { _triggerToReset = (Trigger)obj; } /// <summary> /// Set the trigger to remove /// </summary> /// <param name='obj'> /// Object - trigger to remove. Must derive from Trigger class. /// </param> private void RemoveTrigger(object obj) { _triggerToRemove = (Trigger)obj; } /// <summary> /// Draws the rule inspector. /// </summary> /// <param name='obj'> /// Object - the serialized object /// </param> private void DrawRuleInspector(Object obj) { SerializedObject serObj = new SerializedObject(obj); //rule row - enable/disable rule foldout + reset button Rect ruleTopRect = EditorGUILayout.BeginHorizontal(); { Rect imageRect = new Rect(ruleTopRect); imageRect.width = 20; imageRect.x=35; Texture2D icon = (Texture2D) Resources.Load(((BaseRule)obj).GetIconPath()); if (icon != null) { EditorGUI.DrawPreviewTexture(imageRect,(Texture2D) Resources.Load(((BaseRule)obj).GetIconPath())); } ((BaseRule)obj).IsEnabled = EditorGUILayout.Toggle(((BaseRule)obj).Enabled ,GUILayout.Width(30)); GUIContent placeHolderContent = new GUIContent("", ((BaseRule)obj).GetRuleDescription()); string[] ver = UnityEditorInternal.InternalEditorUtility.GetFullUnityVersion().Substring(0,5).Replace('.',' ').Split(' '); if (int.Parse(ver[0]) == 4 && int.Parse(ver[1]) <=2) { EditorGUILayout.LabelField(placeHolderContent, GUILayout.Width(25)); } else { EditorGUILayout.LabelField(placeHolderContent, GUILayout.Width(0)); } ((BaseRule)obj).FoldoutOpen = GUIUtils.Foldout(((BaseRule)obj).FoldoutOpen, new GUIContent(((BaseRule)obj).FriendlyName, ((BaseRule)obj).GetRuleDescription())); } EditorGUILayout.EndHorizontal(); SetRulesContextMenu(ruleTopRect,(BaseRule)obj); if ( ((BaseRule)obj).FoldoutOpen ) { EditorGUI.indentLevel++; EditorGUI.indentLevel++; EditorGUI.indentLevel++; if(serObj != null) { SerializedProperty prop = serObj.GetIterator(); prop.NextVisible(true ); do { if(prop.name != "m_Script" && prop.name != "Enabled") { EditorGUILayout.PropertyField(prop,true); } } while (prop.NextVisible(false )); prop.Reset(); } else { EditorGUILayout.PrefixLabel("Rule Null "); } EditorGUI.indentLevel--; EditorGUI.indentLevel--; EditorGUI.indentLevel--; } if (GUI.changed) { EditorUtility.SetDirty(serObj.targetObject); } //save changes to serialized object serObj.ApplyModifiedProperties(); } #endregion }
// dnlib: See LICENSE.txt for more info using System.Collections.Generic; using dnlib.DotNet.Pdb; using dnlib.PE; namespace dnlib.DotNet.Emit { /// <summary> /// Method body base class /// </summary> public abstract class MethodBody { } /// <summary> /// A native method body /// </summary> public sealed class NativeMethodBody : MethodBody { RVA rva; /// <summary> /// Gets/sets the RVA of the native method body /// </summary> public RVA RVA { get => rva; set => rva = value; } /// <summary> /// Default constructor /// </summary> public NativeMethodBody() { } /// <summary> /// Constructor /// </summary> /// <param name="rva">RVA of method body</param> public NativeMethodBody(RVA rva) => this.rva = rva; } /// <summary> /// CIL (managed code) body /// </summary> public sealed class CilBody : MethodBody { bool keepOldMaxStack; bool initLocals; byte headerSize; ushort maxStack; uint localVarSigTok; readonly IList<Instruction> instructions; readonly IList<ExceptionHandler> exceptionHandlers; readonly LocalList localList; /// <summary> /// Size of a small header /// </summary> public const byte SMALL_HEADER_SIZE = 1; /// <summary> /// Gets/sets a flag indicating whether the original max stack value should be used. /// </summary> public bool KeepOldMaxStack { get => keepOldMaxStack; set => keepOldMaxStack = value; } /// <summary> /// Gets/sets the init locals flag. This is only valid if the method has any locals. /// </summary> public bool InitLocals { get => initLocals; set => initLocals = value; } /// <summary> /// Gets/sets the size in bytes of the method body header. The instructions immediately follow /// the header. /// </summary> public byte HeaderSize { get => headerSize; set => headerSize = value; } /// <summary> /// <c>true</c> if it was a small body header (<see cref="HeaderSize"/> is <c>1</c>) /// </summary> public bool IsSmallHeader => headerSize == SMALL_HEADER_SIZE; /// <summary> /// <c>true</c> if it was a big body header /// </summary> public bool IsBigHeader => headerSize != SMALL_HEADER_SIZE; /// <summary> /// Gets/sets max stack value from the fat method header. /// </summary> public ushort MaxStack { get => maxStack; set => maxStack = value; } /// <summary> /// Gets/sets the locals metadata token /// </summary> public uint LocalVarSigTok { get => localVarSigTok; set => localVarSigTok = value; } /// <summary> /// <c>true</c> if <see cref="Instructions"/> is not empty /// </summary> public bool HasInstructions => instructions.Count > 0; /// <summary> /// Gets the instructions /// </summary> public IList<Instruction> Instructions => instructions; /// <summary> /// <c>true</c> if <see cref="ExceptionHandlers"/> is not empty /// </summary> public bool HasExceptionHandlers => exceptionHandlers.Count > 0; /// <summary> /// Gets the exception handlers /// </summary> public IList<ExceptionHandler> ExceptionHandlers => exceptionHandlers; /// <summary> /// <c>true</c> if <see cref="Variables"/> is not empty /// </summary> public bool HasVariables => localList.Count > 0; /// <summary> /// Gets the locals /// </summary> public LocalList Variables => localList; /// <summary> /// Gets/sets the PDB method. This is <c>null</c> if no PDB has been loaded or if there's /// no PDB info for this method. /// </summary> public PdbMethod PdbMethod { get => pdbMethod; set => pdbMethod = value; } PdbMethod pdbMethod; /// <summary> /// <c>true</c> if <see cref="PdbMethod"/> is not <c>null</c> /// </summary> public bool HasPdbMethod => PdbMethod is not null; /// <summary> /// Gets the total size of the body in the PE file, including header, IL bytes, and exception handlers. /// This property returns 0 if the size is unknown. /// </summary> internal uint MetadataBodySize { get; set; } /// <summary> /// Default constructor /// </summary> public CilBody() { initLocals = true; instructions = new List<Instruction>(); exceptionHandlers = new List<ExceptionHandler>(); localList = new LocalList(); } /// <summary> /// Constructor /// </summary> /// <param name="initLocals">Init locals flag</param> /// <param name="instructions">All instructions. This instance will own the list.</param> /// <param name="exceptionHandlers">All exception handlers. This instance will own the list.</param> /// <param name="locals">All locals. This instance will own the locals in the list.</param> public CilBody(bool initLocals, IList<Instruction> instructions, IList<ExceptionHandler> exceptionHandlers, IList<Local> locals) { this.initLocals = initLocals; this.instructions = instructions; this.exceptionHandlers = exceptionHandlers; localList = new LocalList(locals); } /// <summary> /// Shorter instructions are converted to the longer form, eg. <c>Ldc_I4_1</c> is /// converted to <c>Ldc_I4</c> with a <c>1</c> as the operand. /// </summary> /// <param name="parameters">All method parameters, including the hidden 'this' parameter /// if it's an instance method. Use <see cref="MethodDef.Parameters"/>.</param> public void SimplifyMacros(IList<Parameter> parameters) => instructions.SimplifyMacros(localList, parameters); /// <summary> /// Optimizes instructions by using the shorter form if possible. Eg. <c>Ldc_I4</c> <c>1</c> /// will be replaced with <c>Ldc_I4_1</c>. /// </summary> public void OptimizeMacros() => instructions.OptimizeMacros(); /// <summary> /// Short branch instructions are converted to the long form, eg. <c>Beq_S</c> is /// converted to <c>Beq</c>. /// </summary> public void SimplifyBranches() => instructions.SimplifyBranches(); /// <summary> /// Optimizes branches by using the smallest possible branch /// </summary> public void OptimizeBranches() => instructions.OptimizeBranches(); /// <summary> /// Updates each instruction's offset /// </summary> /// <returns>Total size in bytes of all instructions</returns> public uint UpdateInstructionOffsets() => instructions.UpdateInstructionOffsets(); } }
namespace ContosoUniversity.Migrations { using ContosoUniversity.Models; using ContosoUniversity.DAL; using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<SchoolContext> { public Configuration() { AutomaticMigrationsEnabled = false; ContextKey = "ContosoUniversity.DAL.SchoolContext"; } protected override void Seed(SchoolContext context) { var students = new List<Student> { new Student { FirstMidName = "Carson", LastName = "Alexander", EnrollmentDate = DateTime.Parse("2010-09-01") }, new Student { FirstMidName = "Meredith", LastName = "Alonso", EnrollmentDate = DateTime.Parse("2012-09-01") }, new Student { FirstMidName = "Arturo", LastName = "Anand", EnrollmentDate = DateTime.Parse("2013-09-01") }, new Student { FirstMidName = "Gytis", LastName = "Barzdukas", EnrollmentDate = DateTime.Parse("2012-09-01") }, new Student { FirstMidName = "Yan", LastName = "Li", EnrollmentDate = DateTime.Parse("2012-09-01") }, new Student { FirstMidName = "Peggy", LastName = "Justice", EnrollmentDate = DateTime.Parse("2011-09-01") }, new Student { FirstMidName = "Laura", LastName = "Norman", EnrollmentDate = DateTime.Parse("2013-09-01") }, new Student { FirstMidName = "Nino", LastName = "Olivetto", EnrollmentDate = DateTime.Parse("2005-09-01") } }; students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s)); context.SaveChanges(); var instructors = new List<Instructor> { new Instructor { FirstMidName = "Kim", LastName = "Abercrombie", HireDate = DateTime.Parse("1995-03-11") }, new Instructor { FirstMidName = "Fadi", LastName = "Fakhouri", HireDate = DateTime.Parse("2002-07-06") }, new Instructor { FirstMidName = "Roger", LastName = "Harui", HireDate = DateTime.Parse("1998-07-01") }, new Instructor { FirstMidName = "Candace", LastName = "Kapoor", HireDate = DateTime.Parse("2001-01-15") }, new Instructor { FirstMidName = "Roger", LastName = "Zheng", HireDate = DateTime.Parse("2004-02-12") } }; instructors.ForEach(s => context.Instructors.AddOrUpdate(p => p.LastName, s)); context.SaveChanges(); var departments = new List<Department> { new Department { Name = "English", Budget = 350000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single( i => i.LastName == "Abercrombie").ID }, new Department { Name = "Mathematics", Budget = 100000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID }, new Department { Name = "Engineering", Budget = 350000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single( i => i.LastName == "Harui").ID }, new Department { Name = "Economics", Budget = 100000, StartDate = DateTime.Parse("2007-09-01"), InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID } }; departments.ForEach(s => context.Departments.AddOrUpdate(p => p.Name, s)); context.SaveChanges(); var courses = new List<Course> { new Course {CourseID = 1050, Title = "Chemistry", Credits = 3, DepartmentID = departments.Single( s => s.Name == "Engineering").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3, DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3, DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 1045, Title = "Calculus", Credits = 4, DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 3141, Title = "Trigonometry", Credits = 4, DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 2021, Title = "Composition", Credits = 3, DepartmentID = departments.Single( s => s.Name == "English").DepartmentID, Instructors = new List<Instructor>() }, new Course {CourseID = 2042, Title = "Literature", Credits = 4, DepartmentID = departments.Single( s => s.Name == "English").DepartmentID, Instructors = new List<Instructor>() }, }; courses.ForEach(s => context.Courses.AddOrUpdate(p => p.CourseID, s)); context.SaveChanges(); var officeAssignments = new List<OfficeAssignment> { new OfficeAssignment { InstructorID = instructors.Single( i => i.LastName == "Fakhouri").ID, Location = "Smith 17" }, new OfficeAssignment { InstructorID = instructors.Single( i => i.LastName == "Harui").ID, Location = "Gowan 27" }, new OfficeAssignment { InstructorID = instructors.Single( i => i.LastName == "Kapoor").ID, Location = "Thompson 304" }, }; officeAssignments.ForEach(s => context.OfficeAssignments.AddOrUpdate(p => p.InstructorID, s)); context.SaveChanges(); AddOrUpdateInstructor(context, "Chemistry", "Kapoor"); AddOrUpdateInstructor(context, "Chemistry", "Harui"); AddOrUpdateInstructor(context, "Microeconomics", "Zheng"); AddOrUpdateInstructor(context, "Macroeconomics", "Zheng"); AddOrUpdateInstructor(context, "Calculus", "Fakhouri"); AddOrUpdateInstructor(context, "Trigonometry", "Harui"); AddOrUpdateInstructor(context, "Composition", "Abercrombie"); AddOrUpdateInstructor(context, "Literature", "Abercrombie"); context.SaveChanges(); var enrollments = new List<Enrollment> { new Enrollment { StudentID = students.Single(s => s.LastName == "Alexander").ID, CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID, Grade = Grade.A }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alexander").ID, CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID, Grade = Grade.C }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alexander").ID, CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alonso").ID, CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alonso").ID, CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Alonso").ID, CourseID = courses.Single(c => c.Title == "Composition" ).CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Anand").ID, CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID }, new Enrollment { StudentID = students.Single(s => s.LastName == "Anand").ID, CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Barzdukas").ID, CourseID = courses.Single(c => c.Title == "Chemistry").CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Li").ID, CourseID = courses.Single(c => c.Title == "Composition").CourseID, Grade = Grade.B }, new Enrollment { StudentID = students.Single(s => s.LastName == "Justice").ID, CourseID = courses.Single(c => c.Title == "Literature").CourseID, Grade = Grade.B } }; foreach (Enrollment e in enrollments) { var enrollmentInDataBase = context.Enrollments.Where( s => s.Student.ID == e.StudentID && s.Course.CourseID == e.CourseID).SingleOrDefault(); if (enrollmentInDataBase == null) { context.Enrollments.Add(e); } } context.SaveChanges(); } void AddOrUpdateInstructor(SchoolContext context, string courseTitle, string instructorName) { var crs = context.Courses.SingleOrDefault(c => c.Title == courseTitle); var inst = crs.Instructors.SingleOrDefault(i => i.LastName == instructorName); if (inst == null) crs.Instructors.Add(context.Instructors.Single(i => i.LastName == instructorName)); } } }
#if OS_WINDOWS using Microsoft.VisualStudio.Services.Agent.Listener.Configuration; using Microsoft.VisualStudio.Services.Agent.Listener; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.Win32; using Moq; using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Microsoft.VisualStudio.Services.Agent.Tests.Listener { public sealed class AgentAutoLogonTestL0 { private Mock<INativeWindowsServiceHelper> _windowsServiceHelper; private Mock<IPromptManager> _promptManager; private Mock<IProcessInvoker> _processInvoker; private Mock<IConfigurationStore> _store; private MockRegistryManager _mockRegManager; private AutoLogonSettings _autoLogonSettings; private CommandSettings _command; private string _sid = "001"; private string _sidForDifferentUser = "007"; private string _userName = "ironMan"; private string _domainName = "avengers"; private bool _powerCfgCalledForACOption = false; private bool _powerCfgCalledForDCOption = false; [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestAutoLogonConfiguration() { using (var hc = new TestHostContext(this)) { _domainName = "avengers"; SetupTestEnv(hc, _sid); var iConfigManager = new AutoLogonManager(); iConfigManager.Initialize(hc); await iConfigManager.ConfigureAsync(_command); VerifyRegistryChanges(_sid); Assert.True(_powerCfgCalledForACOption); Assert.True(_powerCfgCalledForDCOption); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestAutoLogonConfigurationForDotAsDomainName() { using (var hc = new TestHostContext(this)) { // Set the domain name to '.' _domainName = "."; SetupTestEnv(hc, _sid); var iConfigManager = new AutoLogonManager(); iConfigManager.Initialize(hc); await iConfigManager.ConfigureAsync(_command); // Domain should have been set to Environment.Machine name in case the value passsed was '.' _domainName = Environment.MachineName; VerifyRegistryChanges(_sid); Assert.True(_powerCfgCalledForACOption); Assert.True(_powerCfgCalledForDCOption); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestAutoLogonConfigurationForDifferentUser() { using (var hc = new TestHostContext(this)) { _domainName = "avengers"; SetupTestEnv(hc, _sidForDifferentUser); var iConfigManager = new AutoLogonManager(); iConfigManager.Initialize(hc); await iConfigManager.ConfigureAsync(_command); VerifyRegistryChanges(_sidForDifferentUser); Assert.True(_powerCfgCalledForACOption); Assert.True(_powerCfgCalledForDCOption); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestAutoLogonUnConfigure() { //strategy- //1. fill some existing values in the registry //2. run configure //3. unconfigure //4. make sure the autologon settings are reset using (var hc = new TestHostContext(this)) { _domainName = "avengers"; SetupTestEnv(hc, _sid); SetupRegistrySettings(_sid); var iConfigManager = new AutoLogonManager(); iConfigManager.Initialize(hc); await iConfigManager.ConfigureAsync(_command); // Debugger.Launch(); iConfigManager.Unconfigure(); //original values were reverted RegistryVerificationForUnConfigure(_sid); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void TestAutoLogonUnConfigureForDifferentUser() { //strategy- //1. fill some existing values in the registry //2. run configure //3. make sure the old values are there in the backup //4. unconfigure //5. make sure original values are reverted back using (var hc = new TestHostContext(this)) { _domainName = "avengers"; SetupTestEnv(hc, _sidForDifferentUser); SetupRegistrySettings(_sidForDifferentUser); var iConfigManager = new AutoLogonManager(); iConfigManager.Initialize(hc); await iConfigManager.ConfigureAsync(_command); iConfigManager.Unconfigure(); //original values were reverted RegistryVerificationForUnConfigure(_sidForDifferentUser); } } private void RegistryVerificationForUnConfigure(string securityId) { //screen saver (user specific) ValidateRegistryValue(RegistryHive.Users, $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}", RegistryConstants.UserSettings.ValueNames.ScreenSaver, "1"); //when done with reverting back the original settings we need to make sure we dont leave behind any extra setting //user specific ValidateRegistryValue(RegistryHive.Users, $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.StartupProcess}", RegistryConstants.UserSettings.ValueNames.StartupProcess, null); } private void SetupRegistrySettings(string securityId) { //screen saver (user specific) _mockRegManager.SetValue(RegistryHive.Users, $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}", RegistryConstants.UserSettings.ValueNames.ScreenSaver, "1"); } private void SetupTestEnv(TestHostContext hc, string securityId) { _powerCfgCalledForACOption = _powerCfgCalledForDCOption = false; _autoLogonSettings = null; _windowsServiceHelper = new Mock<INativeWindowsServiceHelper>(); hc.SetSingleton<INativeWindowsServiceHelper>(_windowsServiceHelper.Object); _promptManager = new Mock<IPromptManager>(); hc.SetSingleton<IPromptManager>(_promptManager.Object); _promptManager .Setup(x => x.ReadValue( Constants.Agent.CommandLine.Args.WindowsLogonAccount, // argName It.IsAny<string>(), // description It.IsAny<bool>(), // secret It.IsAny<string>(), // defaultValue Validators.NTAccountValidator, // validator It.IsAny<bool>())) // unattended .Returns(string.Format(@"{0}\{1}", _domainName, _userName)); _windowsServiceHelper.Setup(x => x.IsValidAutoLogonCredential(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(true); _windowsServiceHelper.Setup(x => x.SetAutoLogonPassword(It.IsAny<string>())); _windowsServiceHelper.Setup(x => x.GetSecurityId(It.IsAny<string>(), It.IsAny<string>())).Returns(() => securityId); _windowsServiceHelper.Setup(x => x.IsRunningInElevatedMode()).Returns(true); _processInvoker = new Mock<IProcessInvoker>(); hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object); hc.EnqueueInstance<IProcessInvoker>(_processInvoker.Object); _processInvoker.Setup(x => x.ExecuteAsync( It.IsAny<String>(), "powercfg.exe", "/Change monitor-timeout-ac 0", null, It.IsAny<CancellationToken>())).Returns(Task.FromResult<int>(SetPowerCfgFlags(true))); _processInvoker.Setup(x => x.ExecuteAsync( It.IsAny<String>(), "powercfg.exe", "/Change monitor-timeout-dc 0", null, It.IsAny<CancellationToken>())).Returns(Task.FromResult<int>(SetPowerCfgFlags(false))); _mockRegManager = new MockRegistryManager(); hc.SetSingleton<IWindowsRegistryManager>(_mockRegManager); _command = new CommandSettings( hc, new[] { "--windowslogonaccount", "wont be honored", "--windowslogonpassword", "sssh", "--norestart" }); _store = new Mock<IConfigurationStore>(); _store.Setup(x => x.SaveAutoLogonSettings(It.IsAny<AutoLogonSettings>())) .Callback((AutoLogonSettings settings) => { _autoLogonSettings = settings; }); _store.Setup(x => x.IsAutoLogonConfigured()).Returns(() => _autoLogonSettings != null); _store.Setup(x => x.GetAutoLogonSettings()).Returns(() => _autoLogonSettings); hc.SetSingleton<IConfigurationStore>(_store.Object); hc.SetSingleton<IAutoLogonRegistryManager>(new AutoLogonRegistryManager()); } private int SetPowerCfgFlags(bool isForACOption) { if (isForACOption) { _powerCfgCalledForACOption = true; } else { _powerCfgCalledForDCOption = true; } return 0; } public void VerifyRegistryChanges(string securityId) { ValidateRegistryValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogon, "1"); ValidateRegistryValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonUserName, _userName); ValidateRegistryValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonDomainName, _domainName); ValidateRegistryValue(RegistryHive.LocalMachine, RegistryConstants.MachineSettings.SubKeys.AutoLogon, RegistryConstants.MachineSettings.ValueNames.AutoLogonPassword, null); ValidateRegistryValue(RegistryHive.Users, $"{securityId}\\{RegistryConstants.UserSettings.SubKeys.ScreenSaver}", RegistryConstants.UserSettings.ValueNames.ScreenSaver, "0"); } public void ValidateRegistryValue(RegistryHive hive, string subKeyName, string name, string expectedValue) { var actualValue = _mockRegManager.GetValue(hive, subKeyName, name); var validationPassed = string.Equals(expectedValue, actualValue, StringComparison.OrdinalIgnoreCase); Assert.True(validationPassed, $"Validation failed for '{subKeyName}\\{name}'. Expected - {expectedValue} Actual - {actualValue}"); } } public class MockRegistryManager : AgentService, IWindowsRegistryManager { private Dictionary<string, string> _regStore; public MockRegistryManager() { _regStore = new Dictionary<string, string>(); } public string GetValue(RegistryHive hive, string subKeyName, string name) { var key = string.Concat(hive.ToString(), subKeyName, name); return _regStore.ContainsKey(key) ? _regStore[key] : null; } public void SetValue(RegistryHive hive, string subKeyName, string name, string value) { var key = string.Concat(hive.ToString(), subKeyName, name); if (_regStore.ContainsKey(key)) { _regStore[key] = value; } else { _regStore.Add(key, value); } } public void DeleteValue(RegistryHive hive, string subKeyName, string name) { var key = string.Concat(hive.ToString(), subKeyName, name); _regStore.Remove(key); } public bool SubKeyExists(RegistryHive hive, string subKeyName) { return true; } } } #endif
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using GitVersion; using GitVersion.Configuration; using GitVersion.Extensions; using GitVersion.Logging; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using GitVersionCore.Tests.Helpers; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NUnit.Framework; using Shouldly; using YamlDotNet.Serialization; using Environment = System.Environment; namespace GitVersionCore.Tests { [TestFixture] public class ConfigProviderTests : TestBase { private const string DefaultRepoPath = @"c:\MyGitRepo"; private string repoPath; private IConfigProvider configProvider; private IFileSystem fileSystem; [SetUp] public void Setup() { repoPath = DefaultRepoPath; var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); var sp = ConfigureServices(services => { services.AddSingleton(options); }); configProvider = sp.GetService<IConfigProvider>(); fileSystem = sp.GetService<IFileSystem>(); ShouldlyConfiguration.ShouldMatchApprovedDefaults.LocateTestMethodUsingAttribute<TestAttribute>(); } [Test] public void OverwritesDefaultsWithProvidedConfig() { var defaultConfig = configProvider.Provide(repoPath); const string text = @" next-version: 2.0.0 branches: develop: mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.0.0"); config.Branches["develop"].Increment.ShouldBe(defaultConfig.Branches["develop"].Increment); config.Branches["develop"].VersioningMode.ShouldBe(defaultConfig.Branches["develop"].VersioningMode); config.Branches["develop"].Tag.ShouldBe("dev"); } [Test] public void AllBranchesModeWhenUsingMainline() { const string text = @"mode: Mainline"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); var branches = config.Branches.Select(x => x.Value); branches.All(branch => branch.VersioningMode == VersioningMode.Mainline).ShouldBe(true); } [Test] public void CanRemoveTag() { const string text = @" next-version: 2.0.0 branches: release: tag: """""; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.0.0"); config.Branches["release"].Tag.ShouldBe(string.Empty); } [Test] public void RegexIsRequired() { const string text = @" next-version: 2.0.0 branches: bug: tag: bugfix"; SetupConfigFileContent(text); var ex = Should.Throw<ConfigurationException>(() => configProvider.Provide(repoPath)); ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'regex'{Environment.NewLine}" + "See https://gitversion.net/docs/configuration/ for more info"); } [Test] public void SourceBranchIsRequired() { const string text = @" next-version: 2.0.0 branches: bug: regex: 'bug[/-]' tag: bugfix"; SetupConfigFileContent(text); var ex = Should.Throw<ConfigurationException>(() => configProvider.Provide(repoPath)); ex.Message.ShouldBe($"Branch configuration 'bug' is missing required configuration 'source-branches'{Environment.NewLine}" + "See https://gitversion.net/docs/configuration/ for more info"); } [Test] public void CanProvideConfigForNewBranch() { const string text = @" next-version: 2.0.0 branches: bug: regex: 'bug[/-]' tag: bugfix source-branches: []"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["bug"].Regex.ShouldBe("bug[/-]"); config.Branches["bug"].Tag.ShouldBe("bugfix"); } [Test] public void NextVersionCanBeInteger() { const string text = "next-version: 2"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.0"); } [Test] public void NextVersionCanHaveEnormousMinorVersion() { const string text = "next-version: 2.118998723"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.118998723"); } [Test] public void NextVersionCanHavePatch() { const string text = "next-version: 2.12.654651698"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.NextVersion.ShouldBe("2.12.654651698"); } [Test] [MethodImpl(MethodImplOptions.NoInlining)] [Category("NoMono")] [Description("Won't run on Mono due to source information not being available for ShouldMatchApproved.")] public void CanWriteOutEffectiveConfiguration() { var config = configProvider.Provide(repoPath); config.ToString().ShouldMatchApproved(); } [Test] public void CanUpdateAssemblyInformationalVersioningScheme() { const string text = @" assembly-versioning-scheme: MajorMinor assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{NugetVersion}'"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{NugetVersion}"); } [Test] public void CanUpdateAssemblyInformationalVersioningSchemeWithMultipleVariables() { const string text = @" assembly-versioning-scheme: MajorMinor assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{Major}.{Minor}.{Patch}'"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinor); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{Major}.{Minor}.{Patch}"); } [Test] public void CanUpdateAssemblyInformationalVersioningSchemeWithFullSemVer() { const string text = @"assembly-versioning-scheme: MajorMinorPatch assembly-file-versioning-scheme: MajorMinorPatch assembly-informational-format: '{FullSemVer}' mode: ContinuousDelivery next-version: 5.3.0 branches: {}"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe("{FullSemVer}"); } [Test] public void CanReadDefaultDocument() { const string text = ""; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.AssemblyVersioningScheme.ShouldBe(AssemblyVersioningScheme.MajorMinorPatch); config.AssemblyFileVersioningScheme.ShouldBe(AssemblyFileVersioningScheme.MajorMinorPatch); config.AssemblyInformationalFormat.ShouldBe(null); config.Branches["develop"].Tag.ShouldBe("alpha"); config.Branches["release"].Tag.ShouldBe("beta"); config.TagPrefix.ShouldBe(Config.DefaultTagPrefix); config.NextVersion.ShouldBe(null); } [Test] public void VerifyAliases() { var config = typeof(Config); var propertiesMissingAlias = config.GetProperties() .Where(p => p.GetCustomAttribute<ObsoleteAttribute>() == null) .Where(p => p.GetCustomAttribute(typeof(YamlMemberAttribute)) == null) .Select(p => p.Name); propertiesMissingAlias.ShouldBeEmpty(); } [Test] public void NoWarnOnGitVersionYmlFile() { SetupConfigFileContent(string.Empty); var stringLogger = string.Empty; void Action(string info) => stringLogger = info; var logAppender = new TestLogAppender(Action); var log = new Log(logAppender); var options = Options.Create(new GitVersionOptions { WorkingDirectory = repoPath }); var sp = ConfigureServices(services => { services.AddSingleton(options); services.AddSingleton<ILog>(log); }); configProvider = sp.GetService<IConfigProvider>(); configProvider.Provide(repoPath); stringLogger.Length.ShouldBe(0); } private string SetupConfigFileContent(string text, string fileName = DefaultConfigFileLocator.DefaultFileName) { return SetupConfigFileContent(text, fileName, repoPath); } private string SetupConfigFileContent(string text, string fileName, string path) { var fullPath = Path.Combine(path, fileName); fileSystem.WriteAllText(fullPath, text); return fullPath; } [Test] public void ShouldUseSpecifiedSourceBranchesForDevelop() { const string text = @" next-version: 2.0.0 branches: develop: mode: ContinuousDeployment source-branches: ['develop'] tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["develop"].SourceBranches.ShouldBe(new List<string> { "develop" }); } [Test] public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForDevelop() { const string text = @" next-version: 2.0.0 branches: develop: mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["develop"].SourceBranches.ShouldBe(new List<string>()); } [Test] public void ShouldUseSpecifiedSourceBranchesForFeature() { const string text = @" next-version: 2.0.0 branches: feature: mode: ContinuousDeployment source-branches: ['develop', 'release'] tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["feature"].SourceBranches.ShouldBe(new List<string> { "develop", "release" }); } [Test] public void ShouldUseDefaultSourceBranchesWhenNotSpecifiedForFeature() { const string text = @" next-version: 2.0.0 branches: feature: mode: ContinuousDeployment tag: dev"; SetupConfigFileContent(text); var config = configProvider.Provide(repoPath); config.Branches["feature"].SourceBranches.ShouldBe( new List<string> { "develop", "master", "release", "feature", "support", "hotfix" }); } } }
//----------------------------------------------------------------------- // <copyright file="SerializationContext.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace Stratus.OdinSerializer { using System; using System.Collections.Generic; using System.Runtime.Serialization; using Utilities; /// <summary> /// The context of a given serialization session. This class maintains all internal and external references during serialization. /// </summary> /// <seealso cref="ICacheNotificationReceiver" /> public sealed class SerializationContext : ICacheNotificationReceiver { private SerializationConfig config; private Dictionary<object, int> internalReferenceIdMap = new Dictionary<object, int>(128, ReferenceEqualityComparer<object>.Default); private StreamingContext streamingContext; private IFormatterConverter formatterConverter; private TwoWaySerializationBinder binder; /// <summary> /// Initializes a new instance of the <see cref="SerializationContext"/> class. /// </summary> public SerializationContext() : this(new StreamingContext(), new FormatterConverter()) { } /// <summary> /// Initializes a new instance of the <see cref="SerializationContext"/> class. /// </summary> /// <param name="context">The streaming context to use.</param> public SerializationContext(StreamingContext context) : this(context, new FormatterConverter()) { } /// <summary> /// Initializes a new instance of the <see cref="SerializationContext"/> class. /// </summary> /// <param name="formatterConverter">The formatter converter to use.</param> public SerializationContext(FormatterConverter formatterConverter) : this(new StreamingContext(), formatterConverter) { } /// <summary> /// Initializes a new instance of the <see cref="SerializationContext"/> class. /// </summary> /// <param name="context">The streaming context to use.</param> /// <param name="formatterConverter">The formatter converter to use.</param> /// <exception cref="System.ArgumentNullException">The formatterConverter parameter is null.</exception> public SerializationContext(StreamingContext context, FormatterConverter formatterConverter) { if (formatterConverter == null) { throw new ArgumentNullException("formatterConverter"); } this.streamingContext = context; this.formatterConverter = formatterConverter; this.ResetToDefault(); } /// <summary> /// Gets or sets the context's type binder. /// </summary> /// <value> /// The context's serialization binder. /// </value> public TwoWaySerializationBinder Binder { get { if (this.binder == null) { this.binder = DefaultSerializationBinder.Default; } return this.binder; } set { this.binder = value; } } /// <summary> /// Gets the streaming context. /// </summary> /// <value> /// The streaming context. /// </value> public StreamingContext StreamingContext { get { return this.streamingContext; } } /// <summary> /// Gets the formatter converter. /// </summary> /// <value> /// The formatter converter. /// </value> public IFormatterConverter FormatterConverter { get { return this.formatterConverter; } } /// <summary> /// Gets or sets the index reference resolver. /// </summary> /// <value> /// The index reference resolver. /// </value> public IExternalIndexReferenceResolver IndexReferenceResolver { get; set; } /// <summary> /// Gets or sets the string reference resolver. /// </summary> /// <value> /// The string reference resolver. /// </value> public IExternalStringReferenceResolver StringReferenceResolver { get; set; } /// <summary> /// Gets or sets the Guid reference resolver. /// </summary> /// <value> /// The Guid reference resolver. /// </value> public IExternalGuidReferenceResolver GuidReferenceResolver { get; set; } /// <summary> /// Gets or sets the serialization configuration. /// </summary> /// <value> /// The serialization configuration. /// </value> public SerializationConfig Config { get { if (this.config == null) { this.config = new SerializationConfig(); } return this.config; } set { this.config = value; } } /// <summary> /// Tries to get the id of an internally referenced object. /// </summary> /// <param name="reference">The reference to get the id of.</param> /// <param name="id">The id that was found, or -1 if no id was found.</param> /// <returns><c>true</c> if a reference was found, otherwise <c>false</c>.</returns> public bool TryGetInternalReferenceId(object reference, out int id) { return this.internalReferenceIdMap.TryGetValue(reference, out id); } /// <summary> /// Tries to register an internal reference. Returns <c>true</c> if the reference was registered, otherwise, <c>false</c> when the reference has already been registered. /// </summary> /// <param name="reference">The reference to register.</param> /// <param name="id">The id of the registered reference.</param> /// <returns><c>true</c> if the reference was registered, otherwise, <c>false</c> when the reference has already been registered.</returns> public bool TryRegisterInternalReference(object reference, out int id) { if (this.internalReferenceIdMap.TryGetValue(reference, out id) == false) { id = this.internalReferenceIdMap.Count; this.internalReferenceIdMap.Add(reference, id); return true; } return false; } /// <summary> /// Tries to register an external index reference. /// </summary> /// <param name="obj">The object to reference.</param> /// <param name="index">The index of the referenced object.</param> /// <returns><c>true</c> if the object could be referenced by index; otherwise, <c>false</c>.</returns> public bool TryRegisterExternalReference(object obj, out int index) { if (this.IndexReferenceResolver == null) { index = -1; return false; } if (this.IndexReferenceResolver.CanReference(obj, out index)) { return true; } index = -1; return false; } /// <summary> /// Tries to register an external guid reference. /// </summary> /// <param name="obj">The object to reference.</param> /// <param name="guid">The guid of the referenced object.</param> /// <returns><c>true</c> if the object could be referenced by guid; otherwise, <c>false</c>.</returns> public bool TryRegisterExternalReference(object obj, out Guid guid) { if (this.GuidReferenceResolver == null) { guid = Guid.Empty; return false; } var resolver = this.GuidReferenceResolver; while (resolver != null) { if (resolver.CanReference(obj, out guid)) { return true; } resolver = resolver.NextResolver; } guid = Guid.Empty; return false; } /// <summary> /// Tries to register an external string reference. /// </summary> /// <param name="obj">The object to reference.</param> /// <param name="id">The id string of the referenced object.</param> /// <returns><c>true</c> if the object could be referenced by string; otherwise, <c>false</c>.</returns> public bool TryRegisterExternalReference(object obj, out string id) { if (this.StringReferenceResolver == null) { id = null; return false; } var resolver = this.StringReferenceResolver; while (resolver != null) { if (resolver.CanReference(obj, out id)) { return true; } resolver = resolver.NextResolver; } id = null; return false; } /// <summary> /// Resets the context's internal reference map. /// </summary> public void ResetInternalReferences() { this.internalReferenceIdMap.Clear(); } /// <summary> /// Resets the serialization context completely to baseline status, as if its constructor has just been called. /// This allows complete reuse of a serialization context, with all of its internal reference buffers. /// </summary> public void ResetToDefault() { if (!object.ReferenceEquals(this.config, null)) { this.config.ResetToDefault(); } this.internalReferenceIdMap.Clear(); this.IndexReferenceResolver = null; this.GuidReferenceResolver = null; this.StringReferenceResolver = null; this.binder = null; } void ICacheNotificationReceiver.OnFreed() { this.ResetToDefault(); } void ICacheNotificationReceiver.OnClaimed() { } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadSoftDelete.DataAccess; using SelfLoadSoftDelete.DataAccess.ERLevel; namespace SelfLoadSoftDelete.Business.ERLevel { /// <summary> /// G03_Continent_Child (editable child object).<br/> /// This is a generated base class of <see cref="G03_Continent_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="G02_Continent"/> collection. /// </remarks> [Serializable] public partial class G03_Continent_Child : BusinessBase<G03_Continent_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_Child_NameProperty = RegisterProperty<string>(p => p.Continent_Child_Name, "SubContinents Child Name"); /// <summary> /// Gets or sets the SubContinents Child Name. /// </summary> /// <value>The SubContinents Child Name.</value> public string Continent_Child_Name { get { return GetProperty(Continent_Child_NameProperty); } set { SetProperty(Continent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="G03_Continent_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="G03_Continent_Child"/> object.</returns> internal static G03_Continent_Child NewG03_Continent_Child() { return DataPortal.CreateChild<G03_Continent_Child>(); } /// <summary> /// Factory method. Loads a <see cref="G03_Continent_Child"/> object, based on given parameters. /// </summary> /// <param name="continent_ID1">The Continent_ID1 parameter of the G03_Continent_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="G03_Continent_Child"/> object.</returns> internal static G03_Continent_Child GetG03_Continent_Child(int continent_ID1) { return DataPortal.FetchChild<G03_Continent_Child>(continent_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="G03_Continent_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public G03_Continent_Child() { // 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="G03_Continent_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="G03_Continent_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="continent_ID1">The Continent ID1.</param> protected void Child_Fetch(int continent_ID1) { var args = new DataPortalHookArgs(continent_ID1); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var dal = dalManager.GetProvider<IG03_Continent_ChildDal>(); var data = dal.Fetch(continent_ID1); Fetch(data); } OnFetchPost(args); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="G03_Continent_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_Child_NameProperty, dr.GetString("Continent_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="G03_Continent_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(G02_Continent parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IG03_Continent_ChildDal>(); using (BypassPropertyChecks) { dal.Insert( parent.Continent_ID, Continent_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="G03_Continent_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(G02_Continent parent) { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IG03_Continent_ChildDal>(); using (BypassPropertyChecks) { dal.Update( parent.Continent_ID, Continent_Child_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="G03_Continent_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(G02_Continent parent) { using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IG03_Continent_ChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.Continent_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 2004-2009 Castle Project - http://www.castleproject.org/ // // 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 ASTViewer { using System; using System.IO; using System.Windows.Forms; using Castle.Rook.Compiler; using Castle.Rook.Compiler.AST; using Castle.Rook.Compiler.Services; /// <summary> /// Summary description for Form1. /// </summary> public class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.RichTextBox sourceCode; private System.Windows.Forms.TreeView rawAST; private System.Windows.Forms.ListView listView1; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader4; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private UICompilerContainer container = new UICompilerContainer(); private System.Windows.Forms.TreeView resultingAST; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.CheckBox checkBox1; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button1; private System.Windows.Forms.PropertyGrid propertyGrid1; private UIErrorReport errorReport; public Form1() { InitializeComponent(); errorReport = container[ typeof(IErrorReport) ] as UIErrorReport; FileInfo info = new FileInfo( "source.rook.txt" ); if (!info.Exists) return; using(StreamReader reader = new StreamReader(info.FullName)) { sourceCode.Text = reader.ReadToEnd(); } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.sourceCode = new System.Windows.Forms.RichTextBox(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.rawAST = new System.Windows.Forms.TreeView(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.resultingAST = new System.Windows.Forms.TreeView(); this.listView1 = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.columnHeader3 = new System.Windows.Forms.ColumnHeader(); this.columnHeader4 = new System.Windows.Forms.ColumnHeader(); this.panel1 = new System.Windows.Forms.Panel(); this.propertyGrid1 = new System.Windows.Forms.PropertyGrid(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.button2 = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage3.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.tabControl1.Location = new System.Drawing.Point(0, 0); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(880, 574); this.tabControl1.TabIndex = 0; // // tabPage1 // this.tabPage1.Controls.Add(this.sourceCode); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Size = new System.Drawing.Size(872, 548); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Source"; // // sourceCode // this.sourceCode.Dock = System.Windows.Forms.DockStyle.Fill; this.sourceCode.Font = new System.Drawing.Font("Lucida Console", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.sourceCode.Location = new System.Drawing.Point(0, 0); this.sourceCode.Name = "sourceCode"; this.sourceCode.Size = new System.Drawing.Size(872, 548); this.sourceCode.TabIndex = 0; this.sourceCode.Text = ""; // // tabPage2 // this.tabPage2.Controls.Add(this.rawAST); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Size = new System.Drawing.Size(872, 548); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Raw AST"; // // rawAST // this.rawAST.Dock = System.Windows.Forms.DockStyle.Fill; this.rawAST.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.rawAST.ImageIndex = -1; this.rawAST.Location = new System.Drawing.Point(0, 0); this.rawAST.Name = "rawAST"; this.rawAST.SelectedImageIndex = -1; this.rawAST.Size = new System.Drawing.Size(872, 548); this.rawAST.TabIndex = 0; this.rawAST.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.rawAST_AfterSelect); // // tabPage3 // this.tabPage3.Controls.Add(this.resultingAST); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size(872, 548); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "After passes"; // // resultingAST // this.resultingAST.Dock = System.Windows.Forms.DockStyle.Fill; this.resultingAST.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.resultingAST.ImageIndex = -1; this.resultingAST.Location = new System.Drawing.Point(0, 0); this.resultingAST.Name = "resultingAST"; this.resultingAST.SelectedImageIndex = -1; this.resultingAST.Size = new System.Drawing.Size(872, 548); this.resultingAST.TabIndex = 1; this.resultingAST.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.resultingAST_AfterSelect); // // listView1 // this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3, this.columnHeader4}); this.listView1.Dock = System.Windows.Forms.DockStyle.Bottom; this.listView1.GridLines = true; this.listView1.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.listView1.Location = new System.Drawing.Point(0, 486); this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(880, 88); this.listView1.TabIndex = 4; this.listView1.View = System.Windows.Forms.View.Details; // // columnHeader1 // this.columnHeader1.Text = "file"; // // columnHeader2 // this.columnHeader2.Text = "position"; // // columnHeader3 // this.columnHeader3.Text = "cat"; // // columnHeader4 // this.columnHeader4.Text = "Message"; this.columnHeader4.Width = 400; // // panel1 // this.panel1.Controls.Add(this.propertyGrid1); this.panel1.Controls.Add(this.checkBox1); this.panel1.Controls.Add(this.button2); this.panel1.Controls.Add(this.button1); this.panel1.Dock = System.Windows.Forms.DockStyle.Right; this.panel1.Location = new System.Drawing.Point(640, 0); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(240, 486); this.panel1.TabIndex = 12; // // propertyGrid1 // this.propertyGrid1.CommandsVisibleIfAvailable = true; this.propertyGrid1.Dock = System.Windows.Forms.DockStyle.Bottom; this.propertyGrid1.LargeButtons = false; this.propertyGrid1.LineColor = System.Drawing.SystemColors.ScrollBar; this.propertyGrid1.Location = new System.Drawing.Point(0, 142); this.propertyGrid1.Name = "propertyGrid1"; this.propertyGrid1.Size = new System.Drawing.Size(240, 344); this.propertyGrid1.TabIndex = 15; this.propertyGrid1.Text = "propertyGrid1"; this.propertyGrid1.ViewBackColor = System.Drawing.SystemColors.Window; this.propertyGrid1.ViewForeColor = System.Drawing.SystemColors.WindowText; // // checkBox1 // this.checkBox1.Checked = true; this.checkBox1.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox1.Location = new System.Drawing.Point(12, 16); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(112, 24); this.checkBox1.TabIndex = 14; this.checkBox1.Text = "Declaration Pass"; // // button2 // this.button2.Location = new System.Drawing.Point(28, 88); this.button2.Name = "button2"; this.button2.TabIndex = 13; this.button2.Text = "Reset"; // // button1 // this.button1.Location = new System.Drawing.Point(28, 56); this.button1.Name = "button1"; this.button1.TabIndex = 12; this.button1.Text = "&Compile"; this.button1.Click += new System.EventHandler(this.button1_Click_1); // // Form1 // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(880, 574); this.Controls.Add(this.panel1); this.Controls.Add(this.listView1); this.Controls.Add(this.tabControl1); this.Name = "Form1"; this.Text = "Form1"; this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.Run(new Form1()); } private void button1_Click_1(object sender, System.EventArgs e) { listView1.Items.Clear(); SaveSource(); Compiler comp = new Compiler( container ); comp.PrePassExecution += new PassInfoHandler(PrePassExecution); comp.PostPassExecution += new PassInfoHandler(PostPassExecution); comp.Compile( sourceCode.Text ); ShowErrors(); } private void SaveSource() { FileInfo info = new FileInfo( "source.rook.txt" ); if (info.Exists) { info.Delete(); } using( StreamWriter writer = new StreamWriter(info.FullName) ) { writer.Write( sourceCode.Text ); writer.Flush(); } } private void PrePassExecution(object sender, ICompilerPass pass, CompilationUnit unit, IErrorReport errorService) { CreateAst(unit, rawAST.Nodes); } private void PostPassExecution(object sender, ICompilerPass pass, CompilationUnit unit, IErrorReport errorService) { CreateAst(unit, resultingAST.Nodes); } private void ShowErrors() { listView1.Items.Clear(); foreach(ErrorEntry entry in errorReport.List) { ListViewItem item = listView1.Items.Add( entry.Filename ); // item.SubItems.Add( entry.Pos ); item.SubItems.Add( "" ); item.SubItems.Add( entry.IsError ? "error" : "warning" ); item.SubItems.Add( entry.Contents ); } } private void CreateAst(CompilationUnit unit, TreeNodeCollection nodes) { nodes.Clear(); new TreeWalker(unit, nodes); } private void rawAST_AfterSelect(object sender, TreeViewEventArgs e) { propertyGrid1.SelectedObject = e.Node.Tag; } private void resultingAST_AfterSelect(object sender, TreeViewEventArgs e) { propertyGrid1.SelectedObject = e.Node.Tag; } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; #if !NETCF using System.Runtime.Serialization; using System.Xml; #endif namespace Ctrip.Log4.Util { /// <summary> /// String keyed object map. /// </summary> /// <remarks> /// <para> /// While this collection is serializable only member /// objects that are serializable will /// be serialized along with this collection. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> #if NETCF public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, IDictionary #else [Serializable] public sealed class PropertiesDictionary : ReadOnlyPropertiesDictionary, ISerializable, IDictionary #endif { #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="PropertiesDictionary" /> class. /// </para> /// </remarks> public PropertiesDictionary() { } /// <summary> /// Constructor /// </summary> /// <param name="propertiesDictionary">properties to copy</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="PropertiesDictionary" /> class. /// </para> /// </remarks> public PropertiesDictionary(ReadOnlyPropertiesDictionary propertiesDictionary) : base(propertiesDictionary) { } #endregion Public Instance Constructors #region Private Instance Constructors #if !NETCF /// <summary> /// Initializes a new instance of the <see cref="PropertiesDictionary" /> class /// with serialized data. /// </summary> /// <param name="info">The <see cref="SerializationInfo" /> that holds the serialized object data.</param> /// <param name="context">The <see cref="StreamingContext" /> that contains contextual information about the source or destination.</param> /// <remarks> /// <para> /// Because this class is sealed the serialization constructor is private. /// </para> /// </remarks> private PropertiesDictionary(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif #endregion Protected Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the value of the property with the specified key. /// </summary> /// <value> /// The value of the property with the specified key. /// </value> /// <param name="key">The key of the property to get or set.</param> /// <remarks> /// <para> /// The property value will only be serialized if it is serializable. /// If it cannot be serialized it will be silently ignored if /// a serialization operation is performed. /// </para> /// </remarks> override public object this[string key] { get { return InnerHashtable[key]; } set { InnerHashtable[key] = value; } } #endregion Public Instance Properties #region Public Instance Methods /// <summary> /// Remove the entry with the specified key from this dictionary /// </summary> /// <param name="key">the key for the entry to remove</param> /// <remarks> /// <para> /// Remove the entry with the specified key from this dictionary /// </para> /// </remarks> public void Remove(string key) { InnerHashtable.Remove(key); } #endregion Public Instance Methods #region Implementation of IDictionary /// <summary> /// See <see cref="IDictionary.GetEnumerator"/> /// </summary> /// <returns>an enumerator</returns> /// <remarks> /// <para> /// Returns a <see cref="IDictionaryEnumerator"/> over the contest of this collection. /// </para> /// </remarks> IDictionaryEnumerator IDictionary.GetEnumerator() { return InnerHashtable.GetEnumerator(); } /// <summary> /// See <see cref="IDictionary.Remove"/> /// </summary> /// <param name="key">the key to remove</param> /// <remarks> /// <para> /// Remove the entry with the specified key from this dictionary /// </para> /// </remarks> void IDictionary.Remove(object key) { InnerHashtable.Remove(key); } /// <summary> /// See <see cref="IDictionary.Contains"/> /// </summary> /// <param name="key">the key to lookup in the collection</param> /// <returns><c>true</c> if the collection contains the specified key</returns> /// <remarks> /// <para> /// Test if this collection contains a specified key. /// </para> /// </remarks> bool IDictionary.Contains(object key) { return InnerHashtable.Contains(key); } /// <summary> /// Remove all properties from the properties collection /// </summary> /// <remarks> /// <para> /// Remove all properties from the properties collection /// </para> /// </remarks> public override void Clear() { InnerHashtable.Clear(); } /// <summary> /// See <see cref="IDictionary.Add"/> /// </summary> /// <param name="key">the key</param> /// <param name="value">the value to store for the key</param> /// <remarks> /// <para> /// Store a value for the specified <see cref="String"/> <paramref name="key"/>. /// </para> /// </remarks> /// <exception cref="ArgumentException">Thrown if the <paramref name="key"/> is not a string</exception> void IDictionary.Add(object key, object value) { if (!(key is string)) { throw new ArgumentException("key must be a string", "key"); } InnerHashtable.Add(key, value); } /// <summary> /// See <see cref="IDictionary.IsReadOnly"/> /// </summary> /// <value> /// <c>false</c> /// </value> /// <remarks> /// <para> /// This collection is modifiable. This property always /// returns <c>false</c>. /// </para> /// </remarks> bool IDictionary.IsReadOnly { get { return false; } } /// <summary> /// See <see cref="IDictionary.this"/> /// </summary> /// <value> /// The value for the key specified. /// </value> /// <remarks> /// <para> /// Get or set a value for the specified <see cref="String"/> <paramref name="key"/>. /// </para> /// </remarks> /// <exception cref="ArgumentException">Thrown if the <paramref name="key"/> is not a string</exception> object IDictionary.this[object key] { get { if (!(key is string)) { throw new ArgumentException("key must be a string", "key"); } return InnerHashtable[key]; } set { if (!(key is string)) { throw new ArgumentException("key must be a string", "key"); } InnerHashtable[key] = value; } } /// <summary> /// See <see cref="IDictionary.Values"/> /// </summary> ICollection IDictionary.Values { get { return InnerHashtable.Values; } } /// <summary> /// See <see cref="IDictionary.Keys"/> /// </summary> ICollection IDictionary.Keys { get { return InnerHashtable.Keys; } } /// <summary> /// See <see cref="IDictionary.IsFixedSize"/> /// </summary> bool IDictionary.IsFixedSize { get { return false; } } #endregion #region Implementation of ICollection /// <summary> /// See <see cref="ICollection.CopyTo"/> /// </summary> /// <param name="array"></param> /// <param name="index"></param> void ICollection.CopyTo(Array array, int index) { InnerHashtable.CopyTo(array, index); } /// <summary> /// See <see cref="ICollection.IsSynchronized"/> /// </summary> bool ICollection.IsSynchronized { get { return InnerHashtable.IsSynchronized; } } /// <summary> /// See <see cref="ICollection.SyncRoot"/> /// </summary> object ICollection.SyncRoot { get { return InnerHashtable.SyncRoot; } } #endregion #region Implementation of IEnumerable /// <summary> /// See <see cref="IEnumerable.GetEnumerator"/> /// </summary> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)InnerHashtable).GetEnumerator(); } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// NetworkResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Supersim.V1 { public class NetworkResource : Resource { private static Request BuildFetchRequest(FetchNetworkOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Supersim, "/v1/Networks/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch a Network resource. /// </summary> /// <param name="options"> Fetch Network parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Network </returns> public static NetworkResource Fetch(FetchNetworkOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch a Network resource. /// </summary> /// <param name="options"> Fetch Network parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Network </returns> public static async System.Threading.Tasks.Task<NetworkResource> FetchAsync(FetchNetworkOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch a Network resource. /// </summary> /// <param name="pathSid"> The SID of the Network resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Network </returns> public static NetworkResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchNetworkOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch a Network resource. /// </summary> /// <param name="pathSid"> The SID of the Network resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Network </returns> public static async System.Threading.Tasks.Task<NetworkResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchNetworkOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadNetworkOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Supersim, "/v1/Networks", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of Network resources. /// </summary> /// <param name="options"> Read Network parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Network </returns> public static ResourceSet<NetworkResource> Read(ReadNetworkOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<NetworkResource>.FromJson("networks", response.Content); return new ResourceSet<NetworkResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of Network resources. /// </summary> /// <param name="options"> Read Network parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Network </returns> public static async System.Threading.Tasks.Task<ResourceSet<NetworkResource>> ReadAsync(ReadNetworkOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<NetworkResource>.FromJson("networks", response.Content); return new ResourceSet<NetworkResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of Network resources. /// </summary> /// <param name="isoCountry"> The ISO country code of the Network resources to read </param> /// <param name="mcc"> The MCC of Network resource identifiers to be read </param> /// <param name="mnc"> The MNC of Network resource identifiers to be read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Network </returns> public static ResourceSet<NetworkResource> Read(string isoCountry = null, string mcc = null, string mnc = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadNetworkOptions(){IsoCountry = isoCountry, Mcc = mcc, Mnc = mnc, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of Network resources. /// </summary> /// <param name="isoCountry"> The ISO country code of the Network resources to read </param> /// <param name="mcc"> The MCC of Network resource identifiers to be read </param> /// <param name="mnc"> The MNC of Network resource identifiers to be read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Network </returns> public static async System.Threading.Tasks.Task<ResourceSet<NetworkResource>> ReadAsync(string isoCountry = null, string mcc = null, string mnc = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadNetworkOptions(){IsoCountry = isoCountry, Mcc = mcc, Mnc = mnc, PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<NetworkResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<NetworkResource>.FromJson("networks", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<NetworkResource> NextPage(Page<NetworkResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Supersim) ); var response = client.Request(request); return Page<NetworkResource>.FromJson("networks", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<NetworkResource> PreviousPage(Page<NetworkResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Supersim) ); var response = client.Request(request); return Page<NetworkResource>.FromJson("networks", response.Content); } /// <summary> /// Converts a JSON string into a NetworkResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> NetworkResource object represented by the provided JSON </returns> public static NetworkResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<NetworkResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// A human readable identifier of this resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The absolute URL of the Network resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The ISO country code of the Network resource /// </summary> [JsonProperty("iso_country")] public string IsoCountry { get; private set; } /// <summary> /// The MCC/MNCs included in the Network resource /// </summary> [JsonProperty("identifiers")] public List<object> Identifiers { get; private set; } private NetworkResource() { } } }
#region License, Terms and Conditions // // BillingManagementInfo.cs // // Authors: Kori Francis <twitter.com/djbyter>, David Ball // Copyright (C) 2010 Clinical Support Systems, Inc. All rights reserved. // // 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. // #endregion namespace ChargifyNET { #region Imports using System; using System.Xml; using Json; #endregion /// <summary> /// From http://docs.chargify.com/api-billing-portal /// </summary> public class BillingManagementInfo : ChargifyBase, IBillingManagementInfo, IComparable<BillingManagementInfo> { #region Field Keys private const string CreatedAtKey = "created_at"; private const string UrlKey = "url"; private const string FetchCountKey = "fetch_count"; private const string NewLinkAvailableAtKey = "new_link_available_at"; private const string ExpiresAtKey = "expires_at"; #endregion #region Constructors /// <summary> /// Constructor /// </summary> private BillingManagementInfo() { } /// <summary> /// Constructor /// </summary> /// <param name="billingManagementInfoXml">An XML string containing a billingManagementInfo node</param> public BillingManagementInfo(string billingManagementInfoXml) { // get the XML into an XML document XmlDocument doc = new XmlDocument(); doc.LoadXml(billingManagementInfoXml); if (doc.ChildNodes.Count == 0) throw new ArgumentException("XML not valid", nameof(billingManagementInfoXml)); // loop through the child nodes of this node foreach (XmlNode elementNode in doc.ChildNodes) { if (elementNode.Name == "management_link") { LoadFromNode(elementNode); return; } } // if we get here, then no info was found throw new ArgumentException("XML does not contain billing management information", nameof(billingManagementInfoXml)); } /// <summary> /// Constructor /// </summary> /// <param name="billingManagementInfoNode">An xml node with component information</param> internal BillingManagementInfo(XmlNode billingManagementInfoNode) { if (billingManagementInfoNode == null) throw new ArgumentNullException(nameof(billingManagementInfoNode)); if (billingManagementInfoNode.Name != "management_link") throw new ArgumentException("Not a vaild billing management node", nameof(billingManagementInfoNode)); if (billingManagementInfoNode.ChildNodes.Count == 0) throw new ArgumentException("XML not valid", nameof(billingManagementInfoNode)); LoadFromNode(billingManagementInfoNode); } /// <summary> /// Constructor /// </summary> /// <param name="billingManagementInfoObject">An JsonObject with billing management information</param> public BillingManagementInfo(JsonObject billingManagementInfoObject) { if (billingManagementInfoObject == null) throw new ArgumentNullException(nameof(billingManagementInfoObject)); if (billingManagementInfoObject.Keys.Count <= 0) throw new ArgumentException("Not a vaild management object", nameof(billingManagementInfoObject)); LoadFromJson(billingManagementInfoObject); } private void LoadFromJson(JsonObject obj) { // loop through the keys of this JsonObject to get component info, and parse it out foreach (string key in obj.Keys) { switch (key) { case CreatedAtKey: _createdAt = obj.GetJSONContentAsDateTime(key); break; case UrlKey: _url = obj.GetJSONContentAsString(key); break; case NewLinkAvailableAtKey: _newLinkAvailableAt = obj.GetJSONContentAsDateTime(key); break; case FetchCountKey: _fetchCount = obj.GetJSONContentAsInt(key); break; case ExpiresAtKey: _expiresAt = obj.GetJSONContentAsDateTime(key); break; } } } private void LoadFromNode(XmlNode obj) { // loop through the nodes to get component info foreach (XmlNode dataNode in obj.ChildNodes) { switch (dataNode.Name) { case CreatedAtKey: _createdAt = dataNode.GetNodeContentAsDateTime(); break; case UrlKey: _url = dataNode.GetNodeContentAsString(); break; case FetchCountKey: _fetchCount = dataNode.GetNodeContentAsInt(); break; case ExpiresAtKey: _expiresAt = dataNode.GetNodeContentAsDateTime(); break; case NewLinkAvailableAtKey: _newLinkAvailableAt = dataNode.GetNodeContentAsDateTime(); break; } } } #endregion #region IBillingManagementInfo Members /// <summary> /// The customer's management URL /// </summary> public string URL { get { return _url; } } private string _url = string.Empty; /// <summary> /// Number of times this link has been retrieved (at 15 you will be blocked) /// </summary> public int FetchCount { get { return _fetchCount; } } private int _fetchCount = int.MinValue; /// <summary> /// When this link was created /// </summary> public DateTime CreatedAt { get { return _createdAt; } } private DateTime _createdAt = DateTime.MinValue; /// <summary> /// When a new link will be available and fetch_count is reset (15 days from when it was created) /// </summary> public DateTime NewLinkAvailableAt { get { return _newLinkAvailableAt; } } private DateTime _newLinkAvailableAt = DateTime.MinValue; /// <summary> /// When this link expires (65 days from when it was created) /// </summary> public DateTime ExpiresAt { get { return _expiresAt; } } private DateTime _expiresAt = DateTime.MinValue; #endregion #region ICompare Members /// <summary> /// Compare /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(BillingManagementInfo other) { // compare return string.Compare(URL, other.URL, StringComparison.InvariantCultureIgnoreCase); } /// <summary> /// Compare /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(IBillingManagementInfo other) { return string.Compare(URL, other.URL, StringComparison.CurrentCultureIgnoreCase); } #endregion } }
using System; using System.Collections.Generic; using System.Messaging; using System.Runtime.Serialization; using System.Transactions; using log4net; using Rhino.ServiceBus.Exceptions; using Rhino.ServiceBus.Impl; using Rhino.ServiceBus.Internal; using Rhino.ServiceBus.Msmq.TransportActions; using Rhino.ServiceBus.Transport; using MessageType=Rhino.ServiceBus.Transport.MessageType; namespace Rhino.ServiceBus.Msmq { public class MsmqTransport : AbstractMsmqListener, IMsmqTransport { [ThreadStatic] private static MsmqCurrentMessageInformation currentMessageInformation; public static MsmqCurrentMessageInformation MsmqCurrentMessageInformation { get { return currentMessageInformation; } } public CurrentMessageInformation CurrentMessageInformation { get { return currentMessageInformation; } } private readonly ILog logger = LogManager.GetLogger(typeof(MsmqTransport)); private readonly IMsmqTransportAction[] transportActions; private readonly IsolationLevel queueIsolationLevel; private readonly bool consumeInTransaction; public MsmqTransport(IMessageSerializer serializer, IQueueStrategy queueStrategy, Uri endpoint, int threadCount, IMsmqTransportAction[] transportActions, IEndpointRouter endpointRouter, IsolationLevel queueIsolationLevel, TransactionalOptions transactional, bool consumeInTransaction) : base(queueStrategy, endpoint, threadCount, serializer, endpointRouter, transactional) { this.transportActions = transportActions; this.queueIsolationLevel = queueIsolationLevel; this.consumeInTransaction = consumeInTransaction; } #region ITransport Members protected override void BeforeStart(OpenedQueue queue) { foreach (var messageAction in transportActions) { messageAction.Init(this, queue); } } public void Reply(params object[] messages) { if (currentMessageInformation == null) throw new TransactionException("There is no message to reply to, sorry."); logger.DebugFormat("Replying to {0}", currentMessageInformation.Source); Send(endpointRouter.GetRoutedEndpoint(currentMessageInformation.Source), messages); } public event Action<CurrentMessageInformation> MessageSent; public event Func<CurrentMessageInformation, bool> AdministrativeMessageArrived; public event Func<CurrentMessageInformation, bool> MessageArrived; public event Action<CurrentMessageInformation, Exception> MessageProcessingFailure; public event Action<CurrentMessageInformation, Exception> MessageProcessingCompleted; public event Action<CurrentMessageInformation> BeforeMessageTransactionCommit; public event Action<CurrentMessageInformation, Exception> AdministrativeMessageProcessingCompleted; public void Discard(object msg) { var message = GenerateMsmqMessageFromMessageBatch(new[] { msg }); SendMessageToQueue(message.SetSubQueueToSendTo(SubQueue.Discarded), Endpoint); } public bool RaiseAdministrativeMessageArrived(CurrentMessageInformation information) { var copy = AdministrativeMessageArrived; if (copy != null) return copy(information); return false; } public void RaiseAdministrativeMessageProcessingCompleted(CurrentMessageInformation information, Exception ex) { var copy = AdministrativeMessageProcessingCompleted; if (copy != null) copy(information, ex); } public void Send(Endpoint endpoint, DateTime processAgainAt, object[] msgs) { if (HaveStarted == false) throw new InvalidOperationException("Cannot send a message before transport is started"); var message = GenerateMsmqMessageFromMessageBatch(msgs); var bytes = new List<byte>(message.Extension); bytes.AddRange(BitConverter.GetBytes(processAgainAt.ToBinary())); message.Extension = bytes.ToArray(); message.AppSpecific = (int)MessageType.TimeoutMessageMarker; SendMessageToQueue(message, endpoint); } public void Send(Endpoint destination, object[] msgs) { if(HaveStarted==false) throw new InvalidOperationException("Cannot send a message before transport is started"); var message = GenerateMsmqMessageFromMessageBatch(msgs); SendMessageToQueue(message, destination); var copy = MessageSent; if (copy == null) return; copy(new CurrentMessageInformation { AllMessages = msgs, Source = Endpoint.Uri, Destination = destination.Uri, MessageId = message.GetMessageId(), }); } public event Action<CurrentMessageInformation, Exception> MessageSerializationException; #endregion public void ReceiveMessageInTransaction(OpenedQueue queue, string messageId, Func<CurrentMessageInformation, bool> messageArrived, Action<CurrentMessageInformation, Exception> messageProcessingCompleted, Action<CurrentMessageInformation> beforeMessageTransactionCommit) { var transactionOptions = new TransactionOptions { IsolationLevel = queueIsolationLevel, Timeout = TransportUtil.GetTransactionTimeout(), }; using (var tx = new TransactionScope(TransactionScopeOption.Required, transactionOptions)) { var message = queue.TryGetMessageFromQueue(messageId); if (message == null) return;// someone else got our message, better luck next time ProcessMessage(message, queue, tx, messageArrived, beforeMessageTransactionCommit, messageProcessingCompleted); } } private void ReceiveMessage(OpenedQueue queue, string messageId, Func<CurrentMessageInformation, bool> messageArrived, Action<CurrentMessageInformation, Exception> messageProcessingCompleted) { var message = queue.TryGetMessageFromQueue(messageId); if (message == null) return; ProcessMessage(message, queue, null, messageArrived, null, messageProcessingCompleted); } public void RaiseMessageSerializationException(OpenedQueue queue, Message msg, string errorMessage) { var copy = MessageSerializationException; if (copy == null) return; var messageInformation = new MsmqCurrentMessageInformation { MsmqMessage = msg, Queue = queue, Message = null, Source = queue.RootUri, MessageId = Guid.Empty }; copy(messageInformation, new SerializationException(errorMessage)); } public OpenedQueue CreateQueue() { return Endpoint.InitalizeQueue(); } private void ProcessMessage( Message message, OpenedQueue messageQueue, TransactionScope tx, Func<CurrentMessageInformation, bool> messageRecieved, Action<CurrentMessageInformation> beforeMessageTransactionCommit, Action<CurrentMessageInformation, Exception> messageCompleted) { Exception ex = null; currentMessageInformation = CreateMessageInformation(messageQueue, message, null, null); try { //deserialization errors do not count for module events object[] messages = DeserializeMessages(messageQueue, message, MessageSerializationException); try { foreach (object msg in messages) { currentMessageInformation = CreateMessageInformation(messageQueue, message, messages, msg); if (TransportUtil.ProcessSingleMessage(currentMessageInformation, messageRecieved) == false) Discard(currentMessageInformation.Message); } } catch (Exception e) { ex = e; logger.Error("Failed to process message", e); } } catch (Exception e) { ex = e; logger.Error("Failed to deserialize message", e); } finally { Action sendMessageBackToQueue = null; if (message != null && (messageQueue.IsTransactional == false|| consumeInTransaction==false)) sendMessageBackToQueue = () => messageQueue.Send(message); var messageHandlingCompletion = new MessageHandlingCompletion(tx, sendMessageBackToQueue, ex, messageCompleted, beforeMessageTransactionCommit, logger, MessageProcessingFailure, currentMessageInformation); messageHandlingCompletion.HandleMessageCompletion(); currentMessageInformation = null; } } private MsmqCurrentMessageInformation CreateMessageInformation(OpenedQueue queue,Message message, object[] messages, object msg) { return new MsmqCurrentMessageInformation { MessageId = message.GetMessageId(), AllMessages = messages, Message = msg, Queue = queue, TransportMessageId = message.Id, Destination = Endpoint.Uri, Source = MsmqUtil.GetQueueUri(message.ResponseQueue), MsmqMessage = message, TransactionType = queue.GetTransactionType() }; } private void SendMessageToQueue(Message message, Endpoint endpoint) { if (HaveStarted == false) throw new TransportException("Cannot send message before transport is started"); try { using (var sendQueue = MsmqUtil.GetQueuePath(endpoint).Open(QueueAccessMode.Send)) { sendQueue.Send(message); logger.DebugFormat("Send message {0} to {1}", message.Label, endpoint); } } catch (Exception e) { throw new TransactionException("Failed to send message to " + endpoint, e); } } protected override void HandlePeekedMessage(OpenedQueue queue,Message message) { foreach (var action in transportActions) { if(action.CanHandlePeekedMessage(message)==false) continue; try { if (action.HandlePeekedMessage(this, queue, message)) return; } catch (Exception e) { logger.Error("Error when trying to execute action " + action + " on message " + message.Id + ". Message has been removed without handling!", e); queue.ConsumeMessage(message.Id); } } if (consumeInTransaction) ReceiveMessageInTransaction(queue, message.Id, MessageArrived, MessageProcessingCompleted, BeforeMessageTransactionCommit); else ReceiveMessage(queue, message.Id, MessageArrived, MessageProcessingCompleted); } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Dialogflow.V2.Snippets { using Google.Api.Gax; using Google.Api.Gax.Grpc; using apis = Google.Cloud.Dialogflow.V2; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; /// <summary>Generated snippets</summary> public class GeneratedContextsClientSnippets { /// <summary>Snippet for ListContextsAsync</summary> public async Task ListContextsAsync() { // Snippet: ListContextsAsync(SessionName,string,int?,CallSettings) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) SessionName parent = new SessionName("[PROJECT]", "[SESSION]"); // Make the request PagedAsyncEnumerable<ListContextsResponse, Context> response = contextsClient.ListContextsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Context item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListContextsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContexts</summary> public void ListContexts() { // Snippet: ListContexts(SessionName,string,int?,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) SessionName parent = new SessionName("[PROJECT]", "[SESSION]"); // Make the request PagedEnumerable<ListContextsResponse, Context> response = contextsClient.ListContexts(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Context item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListContextsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContextsAsync</summary> public async Task ListContextsAsync_RequestObject() { // Snippet: ListContextsAsync(ListContextsRequest,CallSettings) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) ListContextsRequest request = new ListContextsRequest { ParentAsSessionName = new SessionName("[PROJECT]", "[SESSION]"), }; // Make the request PagedAsyncEnumerable<ListContextsResponse, Context> response = contextsClient.ListContextsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Context item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListContextsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListContexts</summary> public void ListContexts_RequestObject() { // Snippet: ListContexts(ListContextsRequest,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) ListContextsRequest request = new ListContextsRequest { ParentAsSessionName = new SessionName("[PROJECT]", "[SESSION]"), }; // Make the request PagedEnumerable<ListContextsResponse, Context> response = contextsClient.ListContexts(request); // Iterate over all response items, lazily performing RPCs as required foreach (Context item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListContextsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Context item in page) { Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Context> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Context item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetContextAsync</summary> public async Task GetContextAsync() { // Snippet: GetContextAsync(ContextName,CallSettings) // Additional: GetContextAsync(ContextName,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) ContextName name = new ContextName("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request Context response = await contextsClient.GetContextAsync(name); // End snippet } /// <summary>Snippet for GetContext</summary> public void GetContext() { // Snippet: GetContext(ContextName,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) ContextName name = new ContextName("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request Context response = contextsClient.GetContext(name); // End snippet } /// <summary>Snippet for GetContextAsync</summary> public async Task GetContextAsync_RequestObject() { // Snippet: GetContextAsync(GetContextRequest,CallSettings) // Additional: GetContextAsync(GetContextRequest,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) GetContextRequest request = new GetContextRequest { ContextName = new ContextName("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request Context response = await contextsClient.GetContextAsync(request); // End snippet } /// <summary>Snippet for GetContext</summary> public void GetContext_RequestObject() { // Snippet: GetContext(GetContextRequest,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) GetContextRequest request = new GetContextRequest { ContextName = new ContextName("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request Context response = contextsClient.GetContext(request); // End snippet } /// <summary>Snippet for CreateContextAsync</summary> public async Task CreateContextAsync() { // Snippet: CreateContextAsync(SessionName,Context,CallSettings) // Additional: CreateContextAsync(SessionName,Context,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) SessionName parent = new SessionName("[PROJECT]", "[SESSION]"); Context context = new Context(); // Make the request Context response = await contextsClient.CreateContextAsync(parent, context); // End snippet } /// <summary>Snippet for CreateContext</summary> public void CreateContext() { // Snippet: CreateContext(SessionName,Context,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) SessionName parent = new SessionName("[PROJECT]", "[SESSION]"); Context context = new Context(); // Make the request Context response = contextsClient.CreateContext(parent, context); // End snippet } /// <summary>Snippet for CreateContextAsync</summary> public async Task CreateContextAsync_RequestObject() { // Snippet: CreateContextAsync(CreateContextRequest,CallSettings) // Additional: CreateContextAsync(CreateContextRequest,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = new SessionName("[PROJECT]", "[SESSION]"), Context = new Context(), }; // Make the request Context response = await contextsClient.CreateContextAsync(request); // End snippet } /// <summary>Snippet for CreateContext</summary> public void CreateContext_RequestObject() { // Snippet: CreateContext(CreateContextRequest,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) CreateContextRequest request = new CreateContextRequest { ParentAsSessionName = new SessionName("[PROJECT]", "[SESSION]"), Context = new Context(), }; // Make the request Context response = contextsClient.CreateContext(request); // End snippet } /// <summary>Snippet for UpdateContextAsync</summary> public async Task UpdateContextAsync() { // Snippet: UpdateContextAsync(Context,CallSettings) // Additional: UpdateContextAsync(Context,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) Context context = new Context(); // Make the request Context response = await contextsClient.UpdateContextAsync(context); // End snippet } /// <summary>Snippet for UpdateContext</summary> public void UpdateContext() { // Snippet: UpdateContext(Context,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) Context context = new Context(); // Make the request Context response = contextsClient.UpdateContext(context); // End snippet } /// <summary>Snippet for UpdateContextAsync</summary> public async Task UpdateContextAsync_RequestObject() { // Snippet: UpdateContextAsync(UpdateContextRequest,CallSettings) // Additional: UpdateContextAsync(UpdateContextRequest,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), }; // Make the request Context response = await contextsClient.UpdateContextAsync(request); // End snippet } /// <summary>Snippet for UpdateContext</summary> public void UpdateContext_RequestObject() { // Snippet: UpdateContext(UpdateContextRequest,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) UpdateContextRequest request = new UpdateContextRequest { Context = new Context(), }; // Make the request Context response = contextsClient.UpdateContext(request); // End snippet } /// <summary>Snippet for DeleteContextAsync</summary> public async Task DeleteContextAsync() { // Snippet: DeleteContextAsync(ContextName,CallSettings) // Additional: DeleteContextAsync(ContextName,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) ContextName name = new ContextName("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request await contextsClient.DeleteContextAsync(name); // End snippet } /// <summary>Snippet for DeleteContext</summary> public void DeleteContext() { // Snippet: DeleteContext(ContextName,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) ContextName name = new ContextName("[PROJECT]", "[SESSION]", "[CONTEXT]"); // Make the request contextsClient.DeleteContext(name); // End snippet } /// <summary>Snippet for DeleteContextAsync</summary> public async Task DeleteContextAsync_RequestObject() { // Snippet: DeleteContextAsync(DeleteContextRequest,CallSettings) // Additional: DeleteContextAsync(DeleteContextRequest,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) DeleteContextRequest request = new DeleteContextRequest { ContextName = new ContextName("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request await contextsClient.DeleteContextAsync(request); // End snippet } /// <summary>Snippet for DeleteContext</summary> public void DeleteContext_RequestObject() { // Snippet: DeleteContext(DeleteContextRequest,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) DeleteContextRequest request = new DeleteContextRequest { ContextName = new ContextName("[PROJECT]", "[SESSION]", "[CONTEXT]"), }; // Make the request contextsClient.DeleteContext(request); // End snippet } /// <summary>Snippet for DeleteAllContextsAsync</summary> public async Task DeleteAllContextsAsync() { // Snippet: DeleteAllContextsAsync(SessionName,CallSettings) // Additional: DeleteAllContextsAsync(SessionName,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) SessionName parent = new SessionName("[PROJECT]", "[SESSION]"); // Make the request await contextsClient.DeleteAllContextsAsync(parent); // End snippet } /// <summary>Snippet for DeleteAllContexts</summary> public void DeleteAllContexts() { // Snippet: DeleteAllContexts(SessionName,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) SessionName parent = new SessionName("[PROJECT]", "[SESSION]"); // Make the request contextsClient.DeleteAllContexts(parent); // End snippet } /// <summary>Snippet for DeleteAllContextsAsync</summary> public async Task DeleteAllContextsAsync_RequestObject() { // Snippet: DeleteAllContextsAsync(DeleteAllContextsRequest,CallSettings) // Additional: DeleteAllContextsAsync(DeleteAllContextsRequest,CancellationToken) // Create client ContextsClient contextsClient = await ContextsClient.CreateAsync(); // Initialize request argument(s) DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = new SessionName("[PROJECT]", "[SESSION]"), }; // Make the request await contextsClient.DeleteAllContextsAsync(request); // End snippet } /// <summary>Snippet for DeleteAllContexts</summary> public void DeleteAllContexts_RequestObject() { // Snippet: DeleteAllContexts(DeleteAllContextsRequest,CallSettings) // Create client ContextsClient contextsClient = ContextsClient.Create(); // Initialize request argument(s) DeleteAllContextsRequest request = new DeleteAllContextsRequest { ParentAsSessionName = new SessionName("[PROJECT]", "[SESSION]"), }; // Make the request contextsClient.DeleteAllContexts(request); // End snippet } } }
using System; using Raksha.Crypto.Parameters; using Raksha.Crypto.Utilities; namespace Raksha.Crypto.Engines { /** * HC-128 is a software-efficient stream cipher created by Hongjun Wu. It * generates keystream from a 128-bit secret key and a 128-bit initialization * vector. * <p> * http://www.ecrypt.eu.org/stream/p3ciphers/hc/hc128_p3.pdf * </p><p> * It is a third phase candidate in the eStream contest, and is patent-free. * No attacks are known as of today (April 2007). See * * http://www.ecrypt.eu.org/stream/hcp3.html * </p> */ public class HC128Engine : IStreamCipher { private uint[] p = new uint[512]; private uint[] q = new uint[512]; private uint cnt = 0; private static uint F1(uint x) { return RotateRight(x, 7) ^ RotateRight(x, 18) ^ (x >> 3); } private static uint F2(uint x) { return RotateRight(x, 17) ^ RotateRight(x, 19) ^ (x >> 10); } private uint G1(uint x, uint y, uint z) { return (RotateRight(x, 10) ^ RotateRight(z, 23)) + RotateRight(y, 8); } private uint G2(uint x, uint y, uint z) { return (RotateLeft(x, 10) ^ RotateLeft(z, 23)) + RotateLeft(y, 8); } private static uint RotateLeft(uint x, int bits) { return (x << bits) | (x >> -bits); } private static uint RotateRight(uint x, int bits) { return (x >> bits) | (x << -bits); } private uint H1(uint x) { return q[x & 0xFF] + q[((x >> 16) & 0xFF) + 256]; } private uint H2(uint x) { return p[x & 0xFF] + p[((x >> 16) & 0xFF) + 256]; } private static uint Mod1024(uint x) { return x & 0x3FF; } private static uint Mod512(uint x) { return x & 0x1FF; } private static uint Dim(uint x, uint y) { return Mod512(x - y); } private uint Step() { uint j = Mod512(cnt); uint ret; if (cnt < 512) { p[j] += G1(p[Dim(j, 3)], p[Dim(j, 10)], p[Dim(j, 511)]); ret = H1(p[Dim(j, 12)]) ^ p[j]; } else { q[j] += G2(q[Dim(j, 3)], q[Dim(j, 10)], q[Dim(j, 511)]); ret = H2(q[Dim(j, 12)]) ^ q[j]; } cnt = Mod1024(cnt + 1); return ret; } private byte[] key, iv; private bool initialised; private void Init() { if (key.Length != 16) throw new ArgumentException("The key must be 128 bits long"); cnt = 0; uint[] w = new uint[1280]; for (int i = 0; i < 16; i++) { w[i >> 2] |= ((uint)key[i] << (8 * (i & 0x3))); } Array.Copy(w, 0, w, 4, 4); for (int i = 0; i < iv.Length && i < 16; i++) { w[(i >> 2) + 8] |= ((uint)iv[i] << (8 * (i & 0x3))); } Array.Copy(w, 8, w, 12, 4); for (uint i = 16; i < 1280; i++) { w[i] = F2(w[i - 2]) + w[i - 7] + F1(w[i - 15]) + w[i - 16] + i; } Array.Copy(w, 256, p, 0, 512); Array.Copy(w, 768, q, 0, 512); for (int i = 0; i < 512; i++) { p[i] = Step(); } for (int i = 0; i < 512; i++) { q[i] = Step(); } cnt = 0; } public string AlgorithmName { get { return "HC-128"; } } /** * Initialise a HC-128 cipher. * * @param forEncryption whether or not we are for encryption. Irrelevant, as * encryption and decryption are the same. * @param params the parameters required to set up the cipher. * @throws ArgumentException if the params argument is * inappropriate (ie. the key is not 128 bit long). */ public void Init( bool forEncryption, ICipherParameters parameters) { ICipherParameters keyParam = parameters; if (parameters is ParametersWithIV) { iv = ((ParametersWithIV)parameters).GetIV(); keyParam = ((ParametersWithIV)parameters).Parameters; } else { iv = new byte[0]; } if (keyParam is KeyParameter) { key = ((KeyParameter)keyParam).GetKey(); Init(); } else { throw new ArgumentException( "Invalid parameter passed to HC128 init - " + parameters.GetType().Name, "parameters"); } initialised = true; } private byte[] buf = new byte[4]; private int idx = 0; private byte GetByte() { if (idx == 0) { Pack.UInt32_To_LE(Step(), buf); } byte ret = buf[idx]; idx = idx + 1 & 0x3; return ret; } public void ProcessBytes( byte[] input, int inOff, int len, byte[] output, int outOff) { if (!initialised) throw new InvalidOperationException(AlgorithmName + " not initialised"); if ((inOff + len) > input.Length) throw new DataLengthException("input buffer too short"); if ((outOff + len) > output.Length) throw new DataLengthException("output buffer too short"); for (int i = 0; i < len; i++) { output[outOff + i] = (byte)(input[inOff + i] ^ GetByte()); } } public void Reset() { idx = 0; Init(); } public byte ReturnByte(byte input) { return (byte)(input ^ GetByte()); } } }
using System; using Assets.Sources.Scripts.EventEngine.Utils; using Assets.Sources.Scripts.UI.Common; using FF9; using Memoria; using System.Collections.Generic; using System.IO; using Memoria.Data; using UnityEngine; using static EventEngine; using Debug = UnityEngine.Debug; using Object = UnityEngine.Object; // ReSharper disable NotAccessedField.Global // ReSharper disable UnassignedField.Global // ReSharper disable ClassNeverInstantiated.Global // ReSharper disable SuspiciousTypeConversion.Global // ReSharper disable UnusedMethodReturnValue.Local // ReSharper disable UnusedParameter.Global // ReSharper disable UnusedVariable // ReSharper disable FieldCanBeMadeReadOnly.Global // ReSharper disable RedundantArgumentDefaultValue // ReSharper disable RedundantExplicitArraySize // ReSharper disable UnusedParameter.Local // ReSharper disable InconsistentNaming // ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Local // ReSharper disable RedundantCast // ReSharper disable ArrangeThisQualifier // ReSharper disable ArrangeStaticMemberQualifier public partial class EventEngine : PersistenSingleton<EventEngine> { public Int32 nil; public Single nilFloat; public FieldMap fieldmap; public FieldSPSSystem fieldSps; public Single POS_COMMAND_DEFAULTY; public Obj gExec; public EventContext sEventContext0; public EventContext sEventContext1; public ObjList gStopObj; public ObjTable[] sObjTable; public Int32 sSourceObjN; #region Memoria Background free-view mode public Boolean sExternalFieldMode = false; public List<Int16> sExternalFieldList = new List<Int16>(); public Int32 sExternalFieldNum; public Int16 sExternalFieldFade; public Int32 sExternalFieldChangeCamera; public Int32 sExternalFieldChangeField; public List<GameObject> sOriginalFieldGameObjects = new List<GameObject>(); public String sOriginalFieldName; #endregion public Int16 sOriginalFieldNo; public Int32 gMode; public Obj gCur; public Int32 gArgFlag; public Int32 gArgUsed; public CalcStack gCP; public Int32 gAnimCount; public Int32 sSysX; public Int32 sSysY; public Int32 sMapJumpX; public Int32 sMapJumpZ; public Int32 sSEPos; public Int32 sSEVol; public Obj gMemberTarget; public Int64 sLockTimer; public Int64 sLockFree; public EBin eBin; public ETb eTb; public Byte[][] allObjsEBData; public List<Int32> toBeAddedObjUIDList; public Boolean requiredAddActor; public Boolean addedChar; private EventContext _context; private String _defaultMapName; private Int32 _lastIP; private EncountData _enCountData; private Int32 _encountBase; private Single _encountTimer; private Int32 _lastScene; private Int32 _collTimer; private Boolean _moveKey; // ProcessEvents private Obj[] _objPtrList; private Int32 _opLStart; private UInt16[] _sysList; private Boolean _encountReserved; private PosObj _eyeObj; private PosObj _aimObj; private FF9FIELD_DISC _ff9fieldDisc; private Byte[] _currentEBAsset; private Boolean _posUsed; private Boolean _noEvents; private FF9StateGlobal _ff9; private FF9StateSystem _ff9Sys; private GeoTexAnim _geoTexAnim; // DoEventCode private readonly Dictionary<Int32, Int32> _mesIdES_FR; // DoEventCode; for field 1060 (Cleyra/Cathedral) only private readonly Dictionary<Int32, Int32> _mesIdGR; // DoEventCode; for field 1060 (Cleyra/Cathedral) only private readonly Dictionary<Int32, Int32> _mesIdIT; // DoEventCode; for field 1060 (Cleyra/Cathedral) only private PosObj _fixThornPosObj; // DoEventCode private Int32 _fixThornPosA; // DoEventCode private Int32 _fixThornPosB; // DoEventCode private Int32 _fixThornPosC; // DoEventCode private CMD_DATA[,] _requestCommandTrigger; public Int32 SCollTimer { get { return this._collTimer; } set { this._collTimer = value; } } public Int32 ServiceEvents() { Int32 num = 0; if (!this._noEvents) { this.eTb.ProcessKeyEvents(); this.CheckSleep(); num = this.ProcessEvents(); EIcon.ProcessFIcon(); EIcon.ProcessAIcon(); } return num; } public Int32 GetFldMapNoAfterChangeDisc() { return this._ff9fieldDisc.FieldMapNo; } public void addObjPtrList(Obj obj) { this._objPtrList[this._opLStart++] = obj; } public ObjList GetFreeObjList() { if (this._context.freeObj == null) return this._context.AddObjList(); return this._context.freeObj; } public void SetFreeObjList(ObjList objList) { this._context.freeObj = objList; } public ObjList GetActiveObjTailList() { return this._context.activeObjTail; } public void SetActiveObjTailList(ObjList objList) { this._context.activeObjTail = objList; } public Byte[] GetMapVar() { return this._context.mapvar; } public Int16 GetTwistA() { return this._context.twist_a; } public Int16 GetTwistD() { return this._context.twist_d; } public PosObj GetEventEye() { return this._eyeObj; } public PosObj GetEventAim() { return this._aimObj; } public Byte GetControlUID() { return this._context.controlUID; } private Int32 SelectScene() { EncountData encountData = this.gMode != 1 ? ff9.w_worldGetBattleScenePtr() : this._enCountData; Int32 num = Comn.random8(); Int32 index = encountData.pattern & 3; if (num < d[index, 0]) return encountData.scene[0]; if (num < d[index, 1]) return encountData.scene[1]; if (num < d[index, 2]) return encountData.scene[2]; return encountData.scene[3]; } public Int32 OperatorPick() { Int32 num1 = 0; Int32 valueAtOffset = this.gCP.getValueAtOffset(-2); Int32 num2; if ((valueAtOffset >> 26 & 7) == 5) { num2 = this.GetSysList(valueAtOffset); } else { this.gCP.retreatTopOfStack(); num2 = this.eBin.getv(); this.gCP.advanceTopOfStack(); this.gCP.advanceTopOfStack(); } Int32 index = 0; while (index < 8 && (num2 & 1) == 0) { ++index; num2 >>= 1; } if (index < 8) { this.gMemberTarget = this._objPtrList[index]; num1 = this.eBin.getv(); } else this.gCP.retreatTopOfStack(); this.gCP.retreatTopOfStack(); return num1; } public Int32 OperatorCount() { Int32 num1 = 0; Int32 num2 = this.eBin.getv(); Int16 num3 = 1; while (num3 != 0) { num1 += (num2 & num3) == 0 ? 0 : 1; num3 <<= 1; } return num1; } public Int32 OperatorSelect() { Byte[] numArray = new Byte[8]; Int32 num1 = this.eBin.getv(); Int32 num2 = 0; Int32 num3 = 0; while (num3 < 8) { if ((num1 & 1) != 0) numArray[num2++] = (Byte)num3; ++num3; num1 >>= 1; } if (num2 == 0) return 0; Int32 index = num2 * Comn.random8() >> 8; return 1 << numArray[index]; } public Boolean RequestAction(BattleCommandId cmd, Int32 target, Int32 prm1, Int32 commandAndScript, CMD_DATA triggeringCmd = null) { Int32 index; for (index = 0; index < 8 && (target & 1) == 0; ++index) target >>= 1; if (index >= 8) return false; Obj p = this._objPtrList[index]; if (cmd == BattleCommandId.EnemyAtk) { if (p.level > 3) { p.btlchk = 2; return true; } return false; } Int32 level = 2; Int32 tagNumber = 7; switch (cmd) { case BattleCommandId.EnemyCounter: tagNumber = 6; this.SetSysList(0, prm1); level = 1; break; case BattleCommandId.EnemyDying: tagNumber = 9; this.SetSysList(0, prm1); level = 0; break; } _btlCmdPrm = commandAndScript; _requestCommandTrigger[index, level] = triggeringCmd; return this.Request(p, level, tagNumber, false); } private Obj Collision(EventEngine eventEngine, PosObj po, Int32 mode, ref Single distance) { return EventCollision.Collision(this, po, mode, ref distance); } private void CollisionRequest(PosObj po) { EventCollision.CollisionRequest(po); } public Boolean Request(Obj p, Int32 level, Int32 tagNumber, Boolean ew) { Int32 ip = this.nil; if (p != null && level < p.level) { ip = this.GetIP(p.sid, tagNumber, p.ebData); if (ip != this.nil) this.Call(p, ip, level, ew, null); } return ip != this.nil; } public Boolean IsActuallyTalkable(Obj p) { if (p == null) return false; Int32 ip = this.GetIP(p.sid, 3, p.ebData); return ip != this.nil && ((EBin.event_code_binary)p.getByteFromCurrentByte(ip + 7) != EBin.event_code_binary.rsv04 || (EBin.event_code_binary)p.getByteFromCurrentByte(ip + 8) != EBin.event_code_binary.rsv04); } private void Call(Obj obj, Int32 ip, Int32 level, Boolean ew, Byte[] additionCommand = null) { Int32 startID = this.getspw(obj, obj.sx); obj.setIntToBuffer(startID, obj.ip); Int32 num = obj.wait & Byte.MaxValue | (obj.level & Byte.MaxValue) << 8 | (!ew ? Byte.MaxValue : this.gExec.level & Byte.MaxValue) << 16 | (this.gExec.uid & Byte.MaxValue) << 24; obj.setIntToBuffer(startID + 4, num); if (ew) this.gExec.wait = Byte.MaxValue; obj.sx += 2; obj.ip = ip; obj.level = (Byte)level; obj.wait = 0; if (additionCommand == null) return; obj.CallAdditionCommand(additionCommand); } private Int32 getspw(Obj obj, Int32 id) { return obj.sofs * 4 + 4 * id; } private Obj getSender(Obj obj) { Int32 startID = this.getspw(obj, obj.sx - 1); return this.FindObjByUID(obj.getIntFromBuffer(startID) >> 24 & Byte.MaxValue); } public ObjList GetActiveObjList() { return this._context?.activeObj; } public void SetActiveObjList(ObjList objList) { this._context.activeObj = objList; } public Actor getActiveActorByUID(Int32 uid) { if (this._context.activeObj == null) return null; for (ObjList objList = this._context.activeObj; objList != null; objList = objList.next) { if (objList.obj.cid == 4 && objList.obj.uid == uid) return (Actor)objList.obj; } return null; } public Actor getActiveActor(Int32 sid) { if (this._context.activeObj == null) return null; for (ObjList objList = this._context.activeObj; objList != null; objList = objList.next) { if (objList.obj.cid == 4) { Actor actor = (Actor)objList.obj; if (actor != null && actor.sid == sid) return actor; } } return null; } public PosObj GetControlChar() { Obj obj = this._context == null ? null : this.FindObjByUID(this._context.controlUID); if (obj != null && obj.cid == 4) return (PosObj)obj; return null; } public PosObj GetControlCharOrTheFirstActor() { PosObj posObj = this.GetControlChar(); if (posObj == null) { for (ObjList objList = this._context.activeObj; objList != null; objList = objList.next) { Obj obj = objList.obj; if (obj.cid == 4) { posObj = (PosObj)obj; break; } } } return posObj; } private void printEObj() { //if (this._context.activeObj.next == null) // Debug.Log("E.activeObj.next == null"); //else // Debug.Log("E.activeObj.next.obj.uid = " + (object)this._context.activeObj.next.obj.uid); // //Debug.Log(this._context.freeObj == null ? "E.freeObj == null" : "E.freeObj is NOT null"); } public void stay() { this.gExec.ip = this._lastIP; this.gArgUsed = 1; } public void clrdist(Actor actor) { actor.lastdist = kInitialDist; actor.actf &= (UInt16)~(actMove | actLockDir); actor.rot0 = 0.0f; } private void SetupCodeParam(BinaryReader br) { br.BaseStream.Seek(3L, SeekOrigin.Begin); this.sSourceObjN = br.ReadByte(); br.BaseStream.Seek(128L, SeekOrigin.Begin); this.sObjTable = new ObjTable[this.sSourceObjN]; for (Int32 index = 0; index < this.sObjTable.Length; ++index) { this.sObjTable[index] = new ObjTable(); this.sObjTable[index].ReadData(br); } } public void ResetIdleTimer(Int32 x) { if (this._context.idletimer < 0) return; this._context.idletimer = (Int16)(200 + Comn.random8() << 1 + (x != 0 ? 0 : 1)); } private void CheckSleep() { if (this._context == null || this._context.usercontrol == 0) return; this._context.idletimer -= this._context.idletimer <= 0 ? (Int16)0 : (Int16)1; Obj objByUid = this.FindObjByUID(this._context.controlUID); if (this._context.idletimer != 0 || objByUid == null || objByUid.cid != 4) return; Actor p = (Actor)objByUid; if (p.animFrame != p.frameN - 1) return; this.ResetIdleTimer(1); if (p.sleep == 0 || (p.animFlag & (afExec | afFreeze)) != 0) return; p.inFrame = 0; p.outFrame = Byte.MaxValue; this.ExecAnim(p, p.sleep); p.animFlag |= (Byte)afLower; } public Boolean isPosObj(Obj obj) { return obj.cid == 4; } public void StartEventsByEBFileName(String ebFileName) { String[] ebInfo; this._currentEBAsset = AssetManager.LoadBytes(ebFileName, out ebInfo); this.StartEvents(this._currentEBAsset); } public Boolean IsEventContextValid() { return this._context != null; } public void StartEvents(Byte[] ebFileData) { resyncBGMSignal = 0; //Debug.Log("Reset resyncBGMSignal = " + (object)EventEngine.resyncBGMSignal); this._ff9 = FF9StateSystem.Common.FF9; this._ff9.charArray.Clear(); this._ff9Sys = PersistenSingleton<FF9StateSystem>.Instance; BinaryReader br = new BinaryReader(new MemoryStream(ebFileData)); this.SetupCodeParam(br); this._ff9.mapNameStr = FF9TextTool.LocationName(this._ff9.fldMapNo); this._defaultMapName = this._ff9.mapNameStr; switch (this._ff9Sys.mode) { case 1: // Field this.gMode = 1; break; case 2: // Battle this.gMode = 2; break; case 3: // World this.gMode = 3; UIManager.World.EnableMapButton = true; break; case 8: // Battle this.gMode = 4; break; } EventInput.IsProcessingInput = this.gMode != 2 && this.gMode != 4; EMinigame.GetTheAirShipAchievement(); EMinigame.GetHelpAllVictimsInCleyraTown(); TimerUI.SetEnable(this._ff9.timerDisplay); TimerUI.SetDisplay(this._ff9.timerDisplay); TimerUI.SetPlay(this._ff9.timerControl); this.allObjsEBData = new Byte[this.sSourceObjN][]; this.toBeAddedObjUIDList.Clear(); for (Int32 btlindex = 0; btlindex < 8; btlindex++) for (Int32 lvlindex = 0; lvlindex < 8; lvlindex++) this._requestCommandTrigger[btlindex, lvlindex] = null; for (Int32 index = 0; index < this.sSourceObjN; ++index) { br.BaseStream.Seek(128L, SeekOrigin.Begin); Int32 num = (Int32)this.sObjTable[index].ofs; Int32 count = (Int32)this.sObjTable[index].size; br.BaseStream.Seek((Int64)num, SeekOrigin.Current); this.allObjsEBData[index] = br.ReadBytes(count); //if (count < 4) //; } if ((this.sEventContext0.inited == 1 || this.sEventContext0.inited == 3) && this.gMode == 2) this.sEventContext1.copy(this.sEventContext0); this._context = this.sEventContext0; this.InitMP(); this.InitObj(); EventInput.IsProcessingInput = true; EIcon.InitFIcon(); EIcon.SetAIcon(0); for (Int32 index = 0; index < 80; ++index) this._context.mapvar[index] = 0; this._context.usercontrol = 0; this._context.controlUID = 0; this._context.idletimer = 0; EIcon.SetHereIcon(0); this.gStopObj = null; this._context.dashinh = 0; this._context.twist_a = 0; this._context.twist_d = 0; this.eTb.gMesCount = this.gAnimCount = 10; this._noEvents = false; this.InitEncount(); NewThread(0, 0); this._context.activeObj.obj.state = stateInit; this.SetupPartyUID(); for (Int32 index = 0; index < 8; ++index) this._objPtrList[index] = null; this._opLStart = 0; // Battle if (this.gMode == 2) { for (Int32 index = 0; index < 4; ++index) { Int32 partyMember = this.eTb.GetPartyMember(index); if (partyMember >= 0) new Actor(this.sSourceObjN - 9 + partyMember, 0, sizeOfActor); } this._context.partyObjTail = this._context.activeObjTail; } else { this._ff9.btl_rain = 0; this.SetSysList(1, 0); } this._opLStart = 4; if (this.gMode == 1 && this.sEventContext1.inited == 1 && this.sEventContext1.lastmap == this._ff9.fldMapNo || this.gMode == 3 && this.sEventContext1.inited == 3 && this.sEventContext1.lastmap == this._ff9.wldMapNo || this._ff9Sys.prevMode == 9 && this.sEventContext1.inited != 0) { this.sEventContext0.copy(this.sEventContext1); this.Request(this.FindObjByUID(0), 0, 10, false); this.EnterBattleEnd(); } else { if (this.gMode != 2 && this.gMode != 4) { Int32 scCounterSvr = this.eBin.getVarManually(EBin.SC_COUNTER_SVR); Int32 mapIndexSvr = this.eBin.getVarManually(EBin.MAP_INDEX_SVR); Boolean flag1 = this._ff9.fldMapNo == 70; Boolean flag2 = this._ff9.fldMapNo == 2200 && scCounterSvr == 9450 && mapIndexSvr == 9999; Boolean flag3 = this._ff9.fldMapNo == 150 && scCounterSvr == 1155 && mapIndexSvr == 325; Boolean flag4 = this._ff9.fldMapNo == 1251 && scCounterSvr == 5400; Boolean flag5 = this._ff9.fldMapNo == 1602 && scCounterSvr == 6645 && mapIndexSvr == 16; Boolean flag6 = this._ff9.fldMapNo == 1757 && scCounterSvr == 6740; Boolean flag7 = this._ff9.fldMapNo == 2752 && scCounterSvr == 11100 && mapIndexSvr == 9999; Boolean flag8 = this._ff9.fldMapNo == 3001 && scCounterSvr == 12000 && mapIndexSvr == 0; Boolean flag9 = this._ff9.fldMapNo == 2161 && scCounterSvr == 10000 && mapIndexSvr == 32; if (!flag1 && !flag4 && (!flag5 && !flag6) && (!flag3 && !flag2 && (!flag7 && !flag8)) && !flag9) { FF9StateSystem.Settings.UpdateTickTime(); ISharedDataSerializer serializer = FF9StateSystem.Serializer; serializer.Autosave(null, (e, s) => { }); } } this.ProcessEvents(); } this._context.inited = (Byte)this.gMode; this._context.lastmap = this.gMode != 1 ? (this.gMode != 3 ? (UInt16)0 : (UInt16)this._ff9.wldMapNo) : (UInt16)this._ff9.fldMapNo; br.Close(); SpawnCustomChatacters(); PersistenSingleton<CheatingManager>.Instance.ApplyDataWhenEventStart(); } private void SpawnCustomChatacters() { CharacterBuilder builer = new CharacterBuilder(this); if (_ff9.fldMapNo == 102 && false) { builer.Spawn(new MyCharacter()); } } private void EnterBattleEnd() { for (ObjList objList = this._context.activeObj; objList != null; objList = objList.next) { Obj obj = objList.obj; if (obj.uid != 0) { obj.state0 = obj.state; obj.state = stateSuspend; } } } private void SetupPartyUID() { Byte[] numArray1 = new Byte[9] {0, 6, 3, 1, 4, 5, 7, 2, 8}; Byte[] numArray2 = new Byte[9] {0, 3, 7, 2, 4, 5, 1, 6, 8}; Int32 num = 0; for (Int32 index = 0; index < 4; ++index) this._context.partyUID[index] = Byte.MaxValue; for (Int32 index = 0; index < 4; ++index) { Int32 partyMember = this.eTb.GetPartyMember(index); if (partyMember >= 0) { // https://github.com/Albeoris/Memoria/issues/3 // Tirlititi: If Beatrix is in the team and she has no script, we make it so the engine thinks it's another member instead if (partyMember == 8) // The index-th team character is Beatrix { Byte BeatrixSID = (Byte)((UInt32)(this.sSourceObjN - 9) + numArray1[partyMember]); if (this.GetIP(BeatrixSID, 0, this.allObjsEBData[BeatrixSID]) == this.nil) // The Main function of the Beatrix entry doesn't exist { if (!partychk(1)) partyMember = 1; else if (!partychk(2)) partyMember = 2; else if (!partychk(3)) partyMember = 3; else partyMember = 0; } } // Note that, as for all the 9 characters, the Beatrix entry is not dependant on the model used by the entry but rather on the fact that it is at the end of the entry list // (Even in battle scripts, in which character entries are never used nor tied to the team's battle datas, 9 entry slots are reserved at the end of the entry list) // ********************* num |= 1 << numArray2[partyMember]; } } Int32 index1 = 0; Int32 index2 = 0; while (num != 0) { if ((num & 1) != 0) { this._context.partyUID[index1] = (Byte)((UInt32)(this.sSourceObjN - 9) + numArray1[index2]); ++index1; } ++index2; num >>= 1; } } public Int32 GetPartyPlayer(Int32 ix) { Int32 num = this._context.partyUID[ix] - (this.sSourceObjN - 9); if (num >= 0 && num < 9) return num; return 0; } public Boolean partychk(Int32 x) { Int32 num = this.chr2slot(x); Int32 index; for (index = 0; index < 4; ++index) { PLAYER player = FF9StateSystem.Common.FF9.party.member[index]; if (player != null && player.info.slot_no == num && !(player.info.serial_no >= 14 ^ x >= 8)) break; } return index < 4; } public Boolean partyadd(Int64 a) { Int64 num = 0; if (!this.partychk((Int32)a)) { a = this.chr2slot((Int32)a); if (a >= 0L && a < 9L) { Int64 index = 0; while (index < 4L && this._ff9.party.member[index] != null) ++index; num = index < 4L ? 0L : 1L; if (num == 0L) { ff9play.FF9Play_SetParty((Int32)index, (Int32)a); BattleAchievement.UpdateParty(); this.SetupPartyUID(); } } else num = 1L; } return num != 0L; } private Int32 chr2slot(Int32 x) { if (x < 9) return x; return x - 4; } public Int32 GetNumberNPC() { Int32 num = 0; if (this._context != null) { for (ObjList objList = this._context.activeObj; objList != null; objList = objList.next) { Obj obj = objList.obj; if (obj.sid < this.sSourceObjN - 9 && obj.cid == 4) ++num; } } return num; } public Obj GetObjIP(Int32 ip) { ObjList objList = this._context.activeObj; while (objList != null && objList.obj.ip != ip) objList = objList.next; return objList?.obj; } public Obj GetObjUID(Int32 uid) { if (uid == Byte.MaxValue) return this.gCur; if (uid == 250) uid = this._context.controlUID; else if (uid >= 251 && uid < Byte.MaxValue) uid = this._context.partyUID[uid - 251]; ObjList objList = this._context.activeObj; while (objList != null && objList.obj.uid != uid) objList = objList.next; return objList?.obj; } public Int32 GetSysList(Int32 num) { num &= 7; switch (num) { case 2: this._sysList[2] = btl_scrp.GetBattleID(0U); break; case 3: this._sysList[3] = btl_scrp.GetBattleID(1U); break; case 4: this._sysList[4] = btl_scrp.GetBattleID(2U); break; case 6: // Usage in battle scripts: // set SV_5 = Spell stat ID of the currently used spell to access (see btl_scrp.GetCurrentCommandData for the list) // set spellstat = SV_6 this._sysList[6] = btl_scrp.GetCurrentCommandData(this._sysList[5]); break; } return this._sysList[num]; } public void ProcessCodeExt(Obj obj) { Int32 index = 0; while (index < 8 && this._objPtrList[index] != obj) ++index; if (index >= 8) this.SetSysList(1, 0); else this.SetSysList(1, 1 << index); } public void SetSysList(Int32 num, Int32 value) { this._sysList[num & 7] = (UInt16)value; // Usage in battle scripts: // set SV_5 = Spell stat ID of the currently used spell to modify (see btl_scrp.GetCurrentCommandData for the list) // set SV_6 = newvalue if (num == 6) btl_scrp.SetCurrentCommandData(this._sysList[5], value); } private void InitMP() { } private void InitObj() { Int32 index; for (index = 0; index < this._context.objlist.Count - 1; ++index) { ObjList objList = this._context.objlist[index]; objList.next = this._context.objlist[index + 1]; objList.obj = null; } ObjList objList1 = this._context.objlist[index]; objList1.next = null; objList1.obj = null; this._context.freeObj = this._context.objlist[0]; this._context.activeObj = this._context.activeObjTail = null; } private static Obj NewThread(Int32 sid, Int32 uid) { return new Obj(sid, uid, sizeOfObj, 16) {cid = 2}; } public Int32 GetBattleCharData(Obj obj, Int32 kind) { Int32 num = 0; Int32 index = 0; while (index < 8 && this._objPtrList[index] != obj) ++index; if (index < 8) { BattleUnit btlDataPtr = btl_scrp.FindBattleUnit((UInt16)(1 << index)); if (btlDataPtr != null) num = (Int32)btl_scrp.GetCharacterData(btlDataPtr.Data, (UInt32)kind); } return num; } private void SetBattleCharData(Obj obj, Int32 kind, Int32 value) { Int32 index = 0; while (index < 8 && this._objPtrList[index] != obj) ++index; if (index >= 8) return; BattleUnit btl = kind != 32 ? btl_scrp.FindBattleUnit((UInt16)(1 << index)) : btl_scrp.FindBattleUnitUnlimited((UInt16)(1 << index)); if (btl == null) return; btl_scrp.SetCharacterData(btl.Data, (UInt32)kind, (Int32)value); } public CMD_DATA GetTriggeringCommand(BTL_DATA btl) { if (btl.bi.line_no < 8 && this._objPtrList[btl.bi.line_no] != null && this._objPtrList[btl.bi.line_no].level < 8) return this._requestCommandTrigger[btl.bi.line_no, this._objPtrList[btl.bi.line_no].level]; return null; } private Int32 getNumOfObjsInObjList(ObjList list) { Int32 num = 0; for (; list != null; list = list.next) ++num; return num; } public void printObjsInObjList(ObjList list) { //int num = 0; //while (list != null) //{ // if (list.obj != null) // ; // list = list.next; // ++num; //} } private void printActorsInObjList(ObjList list) { //int num = 0; //while (list != null) //{ // if ((int)list.obj.cid != 4 || (Actor)list.obj != null) // ; // list = list.next; // ++num; //} } public Int32 GetIP(Int32 objID, Int32 tagID, Byte[] eventData) { if (eventData.Length == 0) return this.nil; using (MemoryStream memoryStream = new MemoryStream(eventData)) { using (BinaryReader binaryReader = new BinaryReader(memoryStream)) { binaryReader.ReadByte(); Byte count = binaryReader.ReadByte(); UInt16 num2 = 0; Int32 num3; for (num3 = count; num3 > 0; --num3) { UInt16 id = (UInt16)binaryReader.ReadInt16(); num2 = (UInt16)binaryReader.ReadInt16(); if (id == tagID) break; } if (num3 == 0) return this.nil; return 2 + num2; } } } public ObjList DisposeObj(Obj obj) { ObjList objList1 = null; ObjList objList2 = null; ObjList objList3; for (objList3 = this._context.activeObj; objList3 != null && objList3.obj != obj; objList3 = objList3.next) objList2 = objList3; if (obj.cid == 4) { FieldMapActorController mapActorController = ((Actor)obj).fieldMapActorController; mapActorController?.UnregisterHonoBehavior(true); FieldMapActor fieldMapActor = ((Actor)obj).fieldMapActor; if (fieldMapActor != null) { fieldMapActor.DestroySelfShadow(); fieldMapActor.UnregisterHonoBehavior(true); } } if (objList3 != null) { objList1 = objList3.next; if (objList2 != null) objList2.next = objList1; if (this._context.activeObjTail == objList3) this._context.activeObjTail = objList2; objList3.next = this._context.freeObj; this._context.freeObj = objList3; DeallocObj(obj); if (this._context.controlUID == objList3.obj.uid) this._context.controlUID = 0; } return objList1; } private static void DeallocObj(Obj obj) { } public Obj FindObjByUID(Int32 uid) { ObjList objList = this._context.activeObj; while (objList != null && objList.obj.uid != uid) objList = objList.next; return objList?.obj; } public Boolean objIsVisible(Obj obj) { if (obj.state == stateRunning) return (obj.flags & 1) != 0; return false; } public void putvobj(Obj obj, Int32 type, Int32 v) { if (obj == null) return; if (type == 2) { Int16 fixedPointAngle = (Int16)(v << 4); ((PosObj)obj).rotAngle[1] = EventEngineUtils.ConvertFixedPointAngleToDegree(fixedPointAngle); } else this.SetBattleCharData(obj, type, v); } public Int32 BGI_systemSetAttributeMask(Byte mask) { this.fieldmap.bgi.attributeMask = mask; return 1; } private Single dist64(Single deltaX, Single deltaY, Single deltaZ) { return (Single)(deltaX * (Double)deltaX + deltaY * (Double)deltaY + deltaZ * (Double)deltaZ); } private Single disdif64(Single deltaX, Single deltaZ, Single deltaR) { return (Single)(deltaX * (Double)deltaX + deltaZ * (Double)deltaZ + deltaR * (Double)deltaR); } private Single distance(Single deltaX, Single deltaY, Single deltaZ) { return Mathf.Sqrt((Single)(deltaX * (Double)deltaX + deltaY * (Double)deltaY + deltaZ * (Double)deltaZ)); } private void ExitBattleEnd() { for (ObjList objList = this._context.activeObj; objList != null; objList = objList.next) { Obj obj = objList.obj; if (obj.uid != 0) obj.state = obj.state0; } } public void Return(Obj obj) { if (obj.sx > 1) { Int32 btlIndex = 0; while (btlIndex < 8 && this._objPtrList[btlIndex] != obj) ++btlIndex; if (btlIndex < 8 && obj.level < 8) _requestCommandTrigger[btlIndex, obj.level] = null; Int32 startID1 = this.getspw(obj, obj.sx) - 4; Int32 intFromBuffer = obj.getIntFromBuffer(startID1); if (obj.uid == 0 && obj.level == 0) this.ExitBattleEnd(); Int32 startID2 = startID1 - 4; obj.ip = obj.getIntFromBuffer(startID2); obj.sx -= 2; obj.wait = (Byte)(intFromBuffer & Byte.MaxValue); obj.level = (Byte)(intFromBuffer >> 8 & Byte.MaxValue); if ((intFromBuffer >> 16 & Byte.MaxValue) != Byte.MaxValue) { Obj objByUid = this.FindObjByUID(intFromBuffer >> 24 & Byte.MaxValue); if (objByUid != null) { if (objByUid.wait == Byte.MaxValue) { objByUid.wait = 0; } else { Int32 num1 = this.getspw(objByUid, 0); Int32 startID3 = this.getspw(objByUid, objByUid.sx - 1); while (startID3 > num1 && (objByUid.getByteFromBuffer(startID3) & Byte.MaxValue) != Byte.MaxValue) startID3 -= 8; if (startID3 > num1) { Byte num2 = (Byte)(objByUid.getByteFromBuffer(startID3) & 4294967040U); objByUid.setByteToBuffer(startID3, num2); } } } } } else if (obj.state == stateInit) { obj.state = stateRunning; obj.ip = this.GetIP(obj.sid, 1, obj.ebData); obj.level = (Byte)(cEventLevelN - 1); } else obj.ip = this.nil; if (!obj.isAdditionCommand) return; obj.RetunCall(); } public void SetFollow(Obj obj, Int32 winnum, Int32 flags) { if ((flags & 160) != 128 || !this.isPosObj(obj)) return; for (ObjList objList = this._context.activeObj; objList != null; objList = objList.next) { Obj obj1 = objList.obj; if (this.isPosObj(obj1) && ((PosObj)obj1).follow == winnum) ((PosObj)obj1).follow = Byte.MaxValue; } ((PosObj)obj).follow = (Byte)winnum; sLastTalker = (PosObj)obj; sTalkTimer = 0; } public void SetNextMap(Int32 MapNo) { this.FF9ChangeMap(MapNo); } private void SetBattleScene(Int32 SceneNo) { this.FF9ChangeMap(SceneNo); } private void FF9ChangeMap(Int32 MapNo) { FF9StateFieldSystem stateFieldSystem = FF9StateSystem.Field.FF9Field; FF9StateBattleSystem stateBattleSystem = FF9StateSystem.Battle.FF9Battle; FF9StateWorldSystem stateWorldSystem = FF9StateSystem.World.FF9World; switch (this._ff9Sys.mode) { case 1: stateFieldSystem.loc.map.nextMapNo = (Int16)MapNo; break; case 2: stateBattleSystem.map.nextMapNo = (Int16)MapNo; break; case 3: stateWorldSystem.map.nextMapNo = (Int16)MapNo; break; } } private Int32 geti() { Int32 num = this.gExec.getByteIP(); ++this.gExec.ip; return num; } private Int32 getv1() { Int32 num; if ((this.gArgFlag & 1) != 0) { this.eBin.CalcExpr(); num = this.eBin.getv(); } else num = this.geti(); this.gArgFlag >>= 1; this.gArgUsed = 1; return num; } private Int32 getv2() { Int32 num; if ((this.gArgFlag & 1) != 0) { this.eBin.CalcExpr(); num = this.eBin.getv(); } else num = (this.geti() | this.geti() << 8) << 16 >> 16; this.gArgFlag >>= 1; this.gArgUsed = 1; return num; } private Int32 getv3() { Int32 num; if ((this.gArgFlag & 1) != 0) { this.eBin.CalcExpr(); num = this.eBin.getv(); } else num = this.geti() | this.geti() << 8 | this.geti() << 16; this.gArgFlag >>= 1; this.gArgUsed = 1; return num; } private void ExecAnim(Actor p, Int32 anim) { if ((p.animFlag & afExec) != 0 && (p.flags & 128) != 0) this.FinishTurn(p); p.anim = (UInt16)anim; p.animFrame = p.inFrame; Byte num1 = (Byte)~(afDir | afLower | afFreeze); p.animFlag &= num1; Byte num2 = p.inFrame <= p.outFrame ? (Byte)afExec : (Byte)(afExec | afDir); p.animFlag |= num2; p.frameDif = 0; p.frameN = (Byte)EventEngineUtils.GetCharAnimFrame(p.go, anim); p.aspeed = p.aspeed0; if (p.uid != this._context.controlUID) return; ++this.gAnimCount; } public Boolean GetUserControl() { return this._context?.usercontrol == 1; } public void SetUserControl(Boolean isEnable) { if (this._context == null) return; this._context.usercontrol = !isEnable ? (Byte)0 : (Byte)1; } public void BackupPosObjData() { for (ObjList objList = this._context.activeObj; objList != null; objList = objList.next) { Obj obj = objList.obj; if (this.isPosObj(obj) && (Object)obj.go) { FieldMapActorController component = obj.go.GetComponent<FieldMapActorController>(); ((PosObj)obj).posField = component.curPos; ((PosObj)obj).rotField = obj.go.transform.localRotation; ((PosObj)obj).charFlags = (Int16)component.charFlags; ((PosObj)obj).activeTri = (Int16)component.activeTri; ((PosObj)obj).activeFloor = (Byte)component.activeFloor; ((PosObj)obj).bgiRad = (Byte)(component.radius / 4.0); this.fieldmap.isBattleBackupPos = true; } } } public Int32 GetDashInh() { if (this._context != null) return this._context.dashinh; return 0; } private enum wait_desc { waitMessage = 254, waitSpecial = 254, waitEndReq = 255, } private class FF9FIELD_DISC { public Int16 FieldMapNo; } }