context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Xunit; namespace Microsoft.Win32.RegistryTests { public class RegistryKey_SetValueKind_str_obj_valueKind : TestSubKey { private const string TestKey = "TEST_KEY"; public RegistryKey_SetValueKind_str_obj_valueKind() : base(TestKey) { } public static IEnumerable<object[]> TestObjects { get { return TestData.TestObjects; } } [Theory] [MemberData("TestObjects")] public void SetValueWithUnknownValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { string valueName = "Testing_" + testIndex.ToString(); _testRegistryKey.SetValue(valueName, testValue, RegistryValueKind.Unknown); Assert.Equal(testValue.ToString(), _testRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, _testRegistryKey.GetValueKind(valueName)); _testRegistryKey.DeleteValue(valueName); } [Theory] [MemberData("TestObjects")] public void SetValueWithStringValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.String; _testRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), _testRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, _testRegistryKey.GetValueKind(valueName)); _testRegistryKey.DeleteValue(valueName); } [Theory] [MemberData("TestObjects")] public void SetValueWithExpandStringValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.ExpandString; _testRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), _testRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, _testRegistryKey.GetValueKind(valueName)); _testRegistryKey.DeleteValue(valueName); } [Theory] [MemberData("TestObjects")] public void SetValueWithMultiStringValeKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.MultiString; _testRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), _testRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, _testRegistryKey.GetValueKind(valueName)); _testRegistryKey.DeleteValue(valueName); } catch (ArgumentException) { Assert.IsNotType<string[]>(testValue); } } [Theory] [MemberData("TestObjects")] public void SetValueWithBinaryValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.Binary; _testRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(testValue.ToString(), _testRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, _testRegistryKey.GetValueKind(valueName)); _testRegistryKey.DeleteValue(valueName); } catch (ArgumentException) { Assert.IsNotType<byte[]>(testValue); } } [Theory] [MemberData("TestObjects")] public void SetValueWithDWordValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.DWord; _testRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(Convert.ToInt32(testValue).ToString(), _testRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, _testRegistryKey.GetValueKind(valueName)); Assert.True(testIndex <= 15); _testRegistryKey.DeleteValue(valueName); } catch (ArgumentException ioe) { Assert.False(testIndex <= 15, ioe.ToString()); } } [Theory] [MemberData("TestObjects")] public void SetValueWithQWordValueKind(int testIndex, object testValue, RegistryValueKind expectedValueKind) { try { string valueName = "Testing_" + testIndex.ToString(); expectedValueKind = RegistryValueKind.QWord; _testRegistryKey.SetValue(valueName, testValue, expectedValueKind); Assert.Equal(Convert.ToInt64(testValue).ToString(), _testRegistryKey.GetValue(valueName).ToString()); Assert.Equal(expectedValueKind, _testRegistryKey.GetValueKind(valueName)); Assert.True(testIndex <= 25); _testRegistryKey.DeleteValue(valueName); } catch (ArgumentException ioe) { Assert.False(testIndex <= 25, ioe.ToString()); } } [Fact] public void SetValueForNonExistingKey() { const string valueName = "FooBar"; const int expectedValue1 = int.MaxValue; const long expectedValue2 = long.MinValue; const RegistryValueKind expectedValueKind1 = RegistryValueKind.DWord; const RegistryValueKind expectedValueKind2 = RegistryValueKind.QWord; Assert.True(_testRegistryKey.GetValue(valueName) == null, "Registry key already exists"); _testRegistryKey.SetValue(valueName, expectedValue1, expectedValueKind1); Assert.True(_testRegistryKey.GetValue(valueName) != null, "Registry key doesn't exists"); Assert.Equal(expectedValue1, (int)_testRegistryKey.GetValue(valueName)); Assert.Equal(expectedValueKind1, _testRegistryKey.GetValueKind(valueName)); _testRegistryKey.SetValue(valueName, expectedValue2, expectedValueKind2); Assert.Equal(expectedValue2, (long)_testRegistryKey.GetValue(valueName)); Assert.Equal(expectedValueKind2, _testRegistryKey.GetValueKind(valueName)); } public IEnumerable<object[]> TestValueNames { get { return TestData.TestValueNames; } } [Theory] [InlineData("TestValueNames")] public void SetValueWithNameTest(string valueName) { const long expectedValue = long.MaxValue; const RegistryValueKind expectedValueKind = RegistryValueKind.QWord; _testRegistryKey.SetValue(valueName, expectedValue, expectedValueKind); Assert.Equal(expectedValue, (long)_testRegistryKey.GetValue(valueName)); Assert.Equal(expectedValueKind, _testRegistryKey.GetValueKind(valueName)); } [Fact] public void NegativeTests() { // Should throw if key length above 255 characters but prior to V4 the limit is 16383 const int maxValueNameLength = 16383; string tooLongValueName = new string('a', maxValueNameLength + 1); Assert.Throws<ArgumentException>(() => _testRegistryKey.SetValue(tooLongValueName, ulong.MaxValue, RegistryValueKind.String)); const string valueName = "FooBar"; // Should throw if passed value is null Assert.Throws<ArgumentNullException>(() => _testRegistryKey.SetValue(valueName, null, RegistryValueKind.QWord)); // Should throw because valueKind is equal to -2 which is not an acceptable value Assert.Throws<ArgumentException>(() => _testRegistryKey.SetValue(valueName, int.MinValue, (RegistryValueKind)(-2))); // Should throw because passed array contains null string[] strArr = { "one", "two", null, "three" }; Assert.Throws<ArgumentException>(() => _testRegistryKey.SetValue(valueName, strArr, RegistryValueKind.MultiString)); // Should throw because passed array has wrong type Assert.Throws<ArgumentException>(() => _testRegistryKey.SetValue(valueName, new[] { new object() }, RegistryValueKind.MultiString)); // Should throw because passed array has wrong type object[] objTemp = { "my string", "your string", "Any once string" }; Assert.Throws<ArgumentException>(() => _testRegistryKey.SetValue(valueName, objTemp, RegistryValueKind.Unknown)); // Should throw because RegistryKey is readonly using (var rk = Registry.CurrentUser.OpenSubKey(TestKey, false)) { Assert.Throws<UnauthorizedAccessException>(() => rk.SetValue(valueName, int.MaxValue, RegistryValueKind.DWord)); } // Should throw if RegistryKey is closed Assert.Throws<ObjectDisposedException>(() => { _testRegistryKey.Dispose(); _testRegistryKey.SetValue(valueName, int.MinValue, RegistryValueKind.DWord); }); } } }
// This file was generated by CSLA Object Generator - CslaGenFork v4.5 // // Filename: DocContentInfo // ObjectType: DocContentInfo // CSLAType: ReadOnlyObject using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using DocStore.Business.Util; using UsingLibrary; namespace DocStore.Business { /// <summary> /// Content of this document (read only object).<br/> /// This is a generated <see cref="DocContentInfo"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="DocContentList"/> collection. /// </remarks> [Serializable] public partial class DocContentInfo : MyReadOnlyBase<DocContentInfo> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="DocContentID"/> property. /// </summary> public static readonly PropertyInfo<int> DocContentIDProperty = RegisterProperty<int>(p => p.DocContentID, "Doc Content ID", -1); /// <summary> /// Gets the Doc Content ID. /// </summary> /// <value>The Doc Content ID.</value> public int DocContentID { get { return GetProperty(DocContentIDProperty); } } /// <summary> /// Maintains metadata about <see cref="DocContentOrder"/> property. /// </summary> public static readonly PropertyInfo<byte> DocContentOrderProperty = RegisterProperty<byte>(p => p.DocContentOrder, "Content Number"); /// <summary> /// Get the document content order number. /// </summary> /// <value>The Content Number.</value> /// <remarks> /// 1 => own image / > 1 => attachements /// </remarks> public byte DocContentOrder { get { return GetProperty(DocContentOrderProperty); } } /// <summary> /// Maintains metadata about <see cref="Version"/> property. /// </summary> public static readonly PropertyInfo<short> VersionProperty = RegisterProperty<short>(p => p.Version, "Version"); /// <summary> /// Gets the Version. /// </summary> /// <value>The Version.</value> public short Version { get { return GetProperty(VersionProperty); } } /// <summary> /// Maintains metadata about <see cref="FileSize"/> property. /// </summary> public static readonly PropertyInfo<int> FileSizeProperty = RegisterProperty<int>(p => p.FileSize, "File Size"); /// <summary> /// Gets the File Size. /// </summary> /// <value>The File Size.</value> public int FileSize { get { return GetProperty(FileSizeProperty); } } /// <summary> /// Maintains metadata about <see cref="FileType"/> property. /// </summary> public static readonly PropertyInfo<string> FileTypeProperty = RegisterProperty<string>(p => p.FileType, "File Type"); /// <summary> /// Gets the File Type. /// </summary> /// <value>The File Type.</value> public string FileType { get { return GetProperty(FileTypeProperty); } } /// <summary> /// Maintains metadata about <see cref="CheckInDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> CheckInDateProperty = RegisterProperty<SmartDate>(p => p.CheckInDate, "Check In Date"); /// <summary> /// Gets the Check-in date. /// </summary> /// <value>The Check In Date.</value> public string CheckInDate { get { return GetPropertyConvert<SmartDate, string>(CheckInDateProperty); } } /// <summary> /// Maintains metadata about <see cref="CheckInUserID"/> property. /// </summary> public static readonly PropertyInfo<int> CheckInUserIDProperty = RegisterProperty<int>(p => p.CheckInUserID, "Check In User ID"); /// <summary> /// Gets the Check-in user ID. /// </summary> /// <value>The Check In User ID.</value> public int CheckInUserID { get { return GetProperty(CheckInUserIDProperty); } } /// <summary> /// Maintains metadata about <see cref="CheckInComment"/> property. /// </summary> public static readonly PropertyInfo<string> CheckInCommentProperty = RegisterProperty<string>(p => p.CheckInComment, "Check In Note"); /// <summary> /// Gets the Check-in comment. /// </summary> /// <value>The Check In Note.</value> public string CheckInComment { get { return GetProperty(CheckInCommentProperty); } } /// <summary> /// Maintains metadata about <see cref="CheckOutDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> CheckOutDateProperty = RegisterProperty<SmartDate>(p => p.CheckOutDate, "Check Out Date", null); /// <summary> /// Gets the Check-out date. /// </summary> /// <value>The Check Out Date.</value> public string CheckOutDate { get { return GetPropertyConvert<SmartDate, string>(CheckOutDateProperty); } } /// <summary> /// Maintains metadata about <see cref="CheckOutUserID"/> property. /// </summary> public static readonly PropertyInfo<int?> CheckOutUserIDProperty = RegisterProperty<int?>(p => p.CheckOutUserID, "Check Out User ID", null); /// <summary> /// Gets the Check-out user ID. /// </summary> /// <value>The Check Out User ID.</value> public int? CheckOutUserID { get { return GetProperty(CheckOutUserIDProperty); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="DocContentInfo"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="DocContentInfo"/> object.</returns> internal static DocContentInfo GetDocContentInfo(SafeDataReader dr) { DocContentInfo obj = new DocContentInfo(); obj.Fetch(dr); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DocContentInfo"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public DocContentInfo() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="DocContentInfo"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(DocContentIDProperty, dr.GetInt32("DocContentID")); LoadProperty(DocContentOrderProperty, dr.GetByte("DocContentOrder")); LoadProperty(VersionProperty, dr.GetInt16("Version")); LoadProperty(FileSizeProperty, dr.GetInt32("FileSize")); LoadProperty(FileTypeProperty, dr.GetString("FileType")); LoadProperty(CheckInDateProperty, dr.GetSmartDate("CheckInDate", true)); LoadProperty(CheckInUserIDProperty, dr.GetInt32("CheckInUserID")); LoadProperty(CheckInCommentProperty, dr.GetString("CheckInComment")); LoadProperty(CheckOutDateProperty, dr.IsDBNull("CheckOutDate") ? null : dr.GetSmartDate("CheckOutDate", true)); LoadProperty(CheckOutUserIDProperty, (int?)dr.GetValue("CheckOutUserID")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * 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. * * 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. ******************************************************************************/ /** * Created at 3:38:38 AM Jan 15, 2011 */ using SharpBox2D.Common; using SharpBox2D.Pooling; namespace SharpBox2D.Dynamics.Joints { //Point-to-point constraint //C = p2 - p1 //Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) //J = [-I -r1_skew I r2_skew ] //Identity used: //w k % (rx i + ry j) = w * (-ry i + rx j) //Angle constraint //C = angle2 - angle1 - referenceAngle //Cdot = w2 - w1 //J = [0 0 -1 0 0 1] //K = invI1 + invI2 /** * A weld joint essentially glues two bodies together. A weld joint may distort somewhat because the * island constraint solver is approximate. * * @author Daniel Murphy */ public class WeldJoint : Joint { private float m_frequencyHz; private float m_dampingRatio; private float m_bias; // Solver shared private Vec2 m_localAnchorA; private Vec2 m_localAnchorB; private float m_referenceAngle; private float m_gamma; private Vec3 m_impulse; // Solver temp private int m_indexA; private int m_indexB; private Vec2 m_rA = new Vec2(); private Vec2 m_rB = new Vec2(); private Vec2 m_localCenterA = new Vec2(); private Vec2 m_localCenterB = new Vec2(); private float m_invMassA; private float m_invMassB; private float m_invIA; private float m_invIB; private Mat33 m_mass = new Mat33(); internal WeldJoint(IWorldPool argWorld, WeldJointDef def) : base(argWorld, def) { m_localAnchorA = new Vec2(def.localAnchorA); m_localAnchorB = new Vec2(def.localAnchorB); m_referenceAngle = def.referenceAngle; m_frequencyHz = def.frequencyHz; m_dampingRatio = def.dampingRatio; m_impulse = new Vec3(); m_impulse.setZero(); } public float getReferenceAngle() { return m_referenceAngle; } public Vec2 getLocalAnchorA() { return m_localAnchorA; } public Vec2 getLocalAnchorB() { return m_localAnchorB; } public float getFrequency() { return m_frequencyHz; } public void setFrequency(float frequencyHz) { this.m_frequencyHz = frequencyHz; } public float getDampingRatio() { return m_dampingRatio; } public void setDampingRatio(float dampingRatio) { this.m_dampingRatio = dampingRatio; } public override void getAnchorA(ref Vec2 argOut) { m_bodyA.getWorldPointToOut(m_localAnchorA, ref argOut); } public override void getAnchorB(ref Vec2 argOut) { m_bodyB.getWorldPointToOut(m_localAnchorB, ref argOut); } public override void getReactionForce(float inv_dt, ref Vec2 argOut) { argOut.set(m_impulse.x, m_impulse.y); argOut.mulLocal(inv_dt); } public override float getReactionTorque(float inv_dt) { return inv_dt*m_impulse.z; } public override void initVelocityConstraints(SolverData data) { m_indexA = m_bodyA.m_islandIndex; m_indexB = m_bodyB.m_islandIndex; m_localCenterA.set(m_bodyA.m_sweep.localCenter); m_localCenterB.set(m_bodyB.m_sweep.localCenter); m_invMassA = m_bodyA.m_invMass; m_invMassB = m_bodyB.m_invMass; m_invIA = m_bodyA.m_invI; m_invIB = m_bodyB.m_invI; // Vec2 cA = data.positions[m_indexA].c; float aA = data.positions[m_indexA].a; Vec2 vA = data.velocities[m_indexA].v; float wA = data.velocities[m_indexA].w; // Vec2 cB = data.positions[m_indexB].c; float aB = data.positions[m_indexB].a; Vec2 vB = data.velocities[m_indexB].v; float wB = data.velocities[m_indexB].w; Rot qA = pool.popRot(); Rot qB = pool.popRot(); Vec2 temp = pool.popVec2(); qA.set(aA); qB.set(aB); // Compute the effective masses. temp.set(m_localAnchorA); temp.subLocal(m_localCenterA); Rot.mulToOutUnsafe(qA, temp, ref m_rA); temp.set(m_localAnchorB); temp.subLocal(m_localCenterB); Rot.mulToOutUnsafe(qB, temp, ref m_rB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float mA = m_invMassA, mB = m_invMassB; float iA = m_invIA, iB = m_invIB; Mat33 K = pool.popMat33(); K.ex.x = mA + mB + m_rA.y*m_rA.y*iA + m_rB.y*m_rB.y*iB; K.ey.x = -m_rA.y*m_rA.x*iA - m_rB.y*m_rB.x*iB; K.ez.x = -m_rA.y*iA - m_rB.y*iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + m_rA.x*m_rA.x*iA + m_rB.x*m_rB.x*iB; K.ez.y = m_rA.x*iA + m_rB.x*iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (m_frequencyHz > 0.0f) { K.getInverse22(m_mass); float invM = iA + iB; float m = invM > 0.0f ? 1.0f/invM : 0.0f; float C = aB - aA - m_referenceAngle; // Frequency float omega = 2.0f*MathUtils.PI*m_frequencyHz; // Damping coefficient float d = 2.0f*m*m_dampingRatio*omega; // Spring stiffness float k = m*omega*omega; // magic formulas float h = data.step.dt; m_gamma = h*(d + h*k); m_gamma = m_gamma != 0.0f ? 1.0f/m_gamma : 0.0f; m_bias = C*h*k*m_gamma; invM += m_gamma; m_mass.ez.z = invM != 0.0f ? 1.0f/invM : 0.0f; } else { K.getSymInverse33(m_mass); m_gamma = 0.0f; m_bias = 0.0f; } if (data.step.warmStarting) { Vec2 P = pool.popVec2(); // Scale impulses to support a variable time step. m_impulse.mulLocal(data.step.dtRatio); P.set(m_impulse.x, m_impulse.y); vA.x -= mA*P.x; vA.y -= mA*P.y; wA -= iA*(Vec2.cross(m_rA, P) + m_impulse.z); vB.x += mB*P.x; vB.y += mB*P.y; wB += iB*(Vec2.cross(m_rB, P) + m_impulse.z); pool.pushVec2(1); } else { m_impulse.setZero(); } // data.velocities[m_indexA].v.set(vA); data.velocities[m_indexA].w = wA; // data.velocities[m_indexB].v.set(vB); data.velocities[m_indexB].w = wB; pool.pushVec2(1); pool.pushRot(2); pool.pushMat33(1); } public override void solveVelocityConstraints(SolverData data) { Vec2 vA = data.velocities[m_indexA].v; float wA = data.velocities[m_indexA].w; Vec2 vB = data.velocities[m_indexB].v; float wB = data.velocities[m_indexB].w; float mA = m_invMassA, mB = m_invMassB; float iA = m_invIA, iB = m_invIB; Vec2 Cdot1 = pool.popVec2(); Vec2 P = pool.popVec2(); Vec2 temp = pool.popVec2(); if (m_frequencyHz > 0.0f) { float Cdot2 = wB - wA; float impulse2 = -m_mass.ez.z*(Cdot2 + m_bias + m_gamma*m_impulse.z); m_impulse.z += impulse2; wA -= iA*impulse2; wB += iB*impulse2; Vec2.crossToOutUnsafe(wB, m_rB, ref Cdot1); Vec2.crossToOutUnsafe(wA, m_rA, ref temp); Cdot1.addLocal(vB); Cdot1.subLocal(vA); Cdot1.subLocal(temp); Vec2 impulse1 = P; Mat33.mul22ToOutUnsafe(m_mass, Cdot1, ref impulse1); impulse1.negateLocal(); m_impulse.x += impulse1.x; m_impulse.y += impulse1.y; vA.x -= mA*P.x; vA.y -= mA*P.y; wA -= iA*Vec2.cross(m_rA, P); vB.x += mB*P.x; vB.y += mB*P.y; wB += iB*Vec2.cross(m_rB, P); } else { Vec2.crossToOutUnsafe(wA, m_rA, ref temp); Vec2.crossToOutUnsafe(wB, m_rB, ref Cdot1); Cdot1.addLocal(vB); Cdot1.subLocal(vA); Cdot1.subLocal(temp); float Cdot2 = wB - wA; Vec3 Cdot = pool.popVec3(); Cdot.set(Cdot1.x, Cdot1.y, Cdot2); Vec3 impulse = pool.popVec3(); Mat33.mulToOutUnsafe(m_mass, Cdot, ref impulse); impulse.negateLocal(); m_impulse.addLocal(impulse); P.set(impulse.x, impulse.y); vA.x -= mA*P.x; vA.y -= mA*P.y; wA -= iA*(Vec2.cross(m_rA, P) + impulse.z); vB.x += mB*P.x; vB.y += mB*P.y; wB += iB*(Vec2.cross(m_rB, P) + impulse.z); pool.pushVec3(2); } // data.velocities[m_indexA].v.set(vA); data.velocities[m_indexA].w = wA; // data.velocities[m_indexB].v.set(vB); data.velocities[m_indexB].w = wB; pool.pushVec2(3); } public override bool solvePositionConstraints(SolverData data) { Vec2 cA = data.positions[m_indexA].c; float aA = data.positions[m_indexA].a; Vec2 cB = data.positions[m_indexB].c; float aB = data.positions[m_indexB].a; Rot qA = pool.popRot(); Rot qB = pool.popRot(); Vec2 temp = pool.popVec2(); Vec2 rA = pool.popVec2(); Vec2 rB = pool.popVec2(); qA.set(aA); qB.set(aB); float mA = m_invMassA, mB = m_invMassB; float iA = m_invIA, iB = m_invIB; temp.set(m_localAnchorA); temp.subLocal(m_localCenterA); Rot.mulToOutUnsafe(qA, temp , ref rA); temp.subLocal(m_localCenterB); Rot.mulToOutUnsafe(qB, temp , ref rB); float positionError, angularError; Mat33 K = pool.popMat33(); Vec2 C1 = pool.popVec2(); Vec2 P = pool.popVec2(); K.ex.x = mA + mB + rA.y*rA.y*iA + rB.y*rB.y*iB; K.ey.x = -rA.y*rA.x*iA - rB.y*rB.x*iB; K.ez.x = -rA.y*iA - rB.y*iB; K.ex.y = K.ey.x; K.ey.y = mA + mB + rA.x*rA.x*iA + rB.x*rB.x*iB; K.ez.y = rA.x*iA + rB.x*iB; K.ex.z = K.ez.x; K.ey.z = K.ez.y; K.ez.z = iA + iB; if (m_frequencyHz > 0.0f) { C1.set(cB); C1.addLocal(rB); C1.subLocal(cA); C1.subLocal(rA); positionError = C1.length(); angularError = 0.0f; K.solve22ToOut(C1, ref P); P.negateLocal(); cA.x -= mA*P.x; cA.y -= mA*P.y; aA -= iA*Vec2.cross(rA, P); cB.x += mB*P.x; cB.y += mB*P.y; aB += iB*Vec2.cross(rB, P); } else { C1.set(cB); C1.addLocal(rB); C1.subLocal(cA); C1.subLocal(rA); float C2 = aB - aA - m_referenceAngle; positionError = C1.length(); angularError = MathUtils.abs(C2); Vec3 C = pool.popVec3(); Vec3 impulse = pool.popVec3(); C.set(C1.x, C1.y, C2); K.solve33ToOut(C, ref impulse); impulse.negateLocal(); P.set(impulse.x, impulse.y); cA.x -= mA*P.x; cA.y -= mA*P.y; aA -= iA*(Vec2.cross(rA, P) + impulse.z); cB.x += mB*P.x; cB.y += mB*P.y; aB += iB*(Vec2.cross(rB, P) + impulse.z); pool.pushVec3(2); } // data.positions[m_indexA].c.set(cA); data.positions[m_indexA].a = aA; // data.positions[m_indexB].c.set(cB); data.positions[m_indexB].a = aB; pool.pushVec2(5); pool.pushRot(2); pool.pushMat33(1); return positionError <= Settings.linearSlop && angularError <= Settings.angularSlop; } } }
using UnityEngine; using System.Collections.Generic; using Pathfinding; using Pathfinding.RVO; namespace Pathfinding.RVO.Sampled { public class Agent : IAgent { Vector3 smoothPos; public Vector3 Position { get; private set; } public Vector3 InterpolatedPosition { get { return smoothPos; } } public Vector3 DesiredVelocity { get; set; } public void Teleport (Vector3 pos) { Position = pos; smoothPos = pos; prevSmoothPos = pos; } public void SetYPosition (float yCoordinate) { Position = new Vector3(Position.x, yCoordinate, Position.z); smoothPos.y = yCoordinate; prevSmoothPos.y = yCoordinate; } //Current values for double buffer calculation public float radius, height, maxSpeed, neighbourDist, agentTimeHorizon, obstacleTimeHorizon, weight; public bool locked = false; RVOLayer layer, collidesWith; public int maxNeighbours; public Vector3 position, desiredVelocity, prevSmoothPos; public RVOLayer Layer { get; set; } public RVOLayer CollidesWith { get; set; } public bool Locked { get; set; } public float Radius { get; set; } public float Height { get; set; } public float MaxSpeed { get; set; } public float NeighbourDist { get; set; } public float AgentTimeHorizon { get; set; } public float ObstacleTimeHorizon { get; set; } public Vector3 Velocity { get; set; } public bool DebugDraw { get; set; } public int MaxNeighbours { get; set; } /** Used internally for a linked list */ internal Agent next; private Vector3 velocity; internal Vector3 newVelocity; /** Simulator which handles this agent. * Used by this script as a reference and to prevent * adding this agent to multiple simulations. */ public Simulator simulator; public List<Agent> neighbours = new List<Agent>(); public List<float> neighbourDists = new List<float>(); List<ObstacleVertex> obstaclesBuffered = new List<ObstacleVertex>(); List<ObstacleVertex> obstacles = new List<ObstacleVertex>(); List<float> obstacleDists = new List<float>(); public List<ObstacleVertex> NeighbourObstacles { get { return null; } } public Agent (Vector3 pos) { MaxSpeed = 2; NeighbourDist = 15; AgentTimeHorizon = 2; ObstacleTimeHorizon = 2; Height = 5; Radius = 5; MaxNeighbours = 10; Locked = false; position = pos; Position = position; prevSmoothPos = position; smoothPos = position; Layer = RVOLayer.DefaultAgent; CollidesWith = (RVOLayer)(-1); } public void BufferSwitch () { // <== radius = Radius; height = Height; maxSpeed = MaxSpeed; neighbourDist = NeighbourDist; agentTimeHorizon = AgentTimeHorizon; obstacleTimeHorizon = ObstacleTimeHorizon; maxNeighbours = MaxNeighbours; desiredVelocity = DesiredVelocity; locked = Locked; collidesWith = CollidesWith; layer = Layer; //position = Position; // ==> Velocity = velocity; List<ObstacleVertex> tmp = obstaclesBuffered; obstaclesBuffered = obstacles; obstacles = tmp; } // Update is called once per frame public void Update () { velocity = newVelocity; prevSmoothPos = smoothPos; //Note the case P/p //position = Position; position = prevSmoothPos; position = position + velocity * simulator.DeltaTime; Position = position; } public void Interpolate (float t) { smoothPos = prevSmoothPos + (Position-prevSmoothPos)*t; } public static System.Diagnostics.Stopwatch watch1 = new System.Diagnostics.Stopwatch(); public static System.Diagnostics.Stopwatch watch2 = new System.Diagnostics.Stopwatch(); public void CalculateNeighbours () { neighbours.Clear(); neighbourDists.Clear(); float rangeSq; if (locked) return; //watch1.Start (); if (MaxNeighbours > 0) { rangeSq = neighbourDist*neighbourDist; //simulator.KDTree.GetAgentNeighbours (this, rangeSq); simulator.Quadtree.Query(new Vector2(position.x, position.z), neighbourDist, this); } //watch1.Stop (); obstacles.Clear(); obstacleDists.Clear(); rangeSq = (obstacleTimeHorizon * maxSpeed + radius); rangeSq *= rangeSq; // Obstacles disabled at the moment //simulator.KDTree.GetObstacleNeighbours (this, rangeSq); } float Sqr (float x) { return x*x; } public float InsertAgentNeighbour (Agent agent, float rangeSq) { if (this == agent) return rangeSq; if ((agent.layer & collidesWith) == 0) return rangeSq; //2D Dist float dist = Sqr(agent.position.x-position.x) + Sqr(agent.position.z - position.z); if (dist < rangeSq) { if (neighbours.Count < maxNeighbours) { neighbours.Add(agent); neighbourDists.Add(dist); } int i = neighbours.Count-1; if (dist < neighbourDists[i]) { while (i != 0 && dist < neighbourDists[i-1]) { neighbours[i] = neighbours[i-1]; neighbourDists[i] = neighbourDists[i-1]; i--; } neighbours[i] = agent; neighbourDists[i] = dist; } if (neighbours.Count == maxNeighbours) { rangeSq = neighbourDists[neighbourDists.Count-1]; } } return rangeSq; } /*public void UpdateNeighbours () { * neighbours.Clear (); * float sqrDist = neighbourDistance*neighbourDistance; * for ( int i = 0; i < simulator.agents.Count; i++ ) { * float dist = (simulator.agents[i].position - position).sqrMagnitude; * if ( dist <= sqrDist ) { * neighbours.Add ( simulator.agents[i] ); * } * } * }*/ public void InsertObstacleNeighbour (ObstacleVertex ob1, float rangeSq) { ObstacleVertex ob2 = ob1.next; float dist = VectorMath.SqrDistancePointSegment(ob1.position, ob2.position, Position); if (dist < rangeSq) { obstacles.Add(ob1); obstacleDists.Add(dist); int i = obstacles.Count-1; while (i != 0 && dist < obstacleDists[i-1]) { obstacles[i] = obstacles[i-1]; obstacleDists[i] = obstacleDists[i-1]; i--; } obstacles[i] = ob1; obstacleDists[i] = dist; } } static Vector3 To3D (Vector2 p) { return new Vector3(p.x, 0, p.y); } static void DrawCircle (Vector2 _p, float radius, Color col) { DrawCircle(_p, radius, 0, 2*Mathf.PI, col); } static void DrawCircle (Vector2 _p, float radius, float a0, float a1, Color col) { Vector3 p = To3D(_p); while (a0 > a1) a0 -= 2*Mathf.PI; Vector3 prev = new Vector3(Mathf.Cos(a0)*radius, 0, Mathf.Sin(a0)*radius); const float steps = 40.0f; for (int i = 0; i <= steps; i++) { Vector3 c = new Vector3(Mathf.Cos(Mathf.Lerp(a0, a1, i/steps))*radius, 0, Mathf.Sin(Mathf.Lerp(a0, a1, i/steps))*radius); Debug.DrawLine(p+prev, p+c, col); prev = c; } } static void DrawVO (Vector2 circleCenter, float radius, Vector2 origin) { float alpha = Mathf.Atan2((origin - circleCenter).y, (origin - circleCenter).x); float gamma = radius/(origin-circleCenter).magnitude; float delta = gamma <= 1.0f ? Mathf.Abs(Mathf.Acos(gamma)) : 0; DrawCircle(circleCenter, radius, alpha-delta, alpha+delta, Color.black); Vector2 p1 = new Vector2(Mathf.Cos(alpha-delta), Mathf.Sin(alpha-delta)) * radius; Vector2 p2 = new Vector2(Mathf.Cos(alpha+delta), Mathf.Sin(alpha+delta)) * radius; Vector2 p1t = -new Vector2(-p1.y, p1.x); Vector2 p2t = new Vector2(-p2.y, p2.x); p1 += circleCenter; p2 += circleCenter; Debug.DrawRay(To3D(p1), To3D(p1t).normalized*100, Color.black); Debug.DrawRay(To3D(p2), To3D(p2t).normalized*100, Color.black); } static void DrawCross (Vector2 p, float size = 1) { DrawCross(p, Color.white, size); } static void DrawCross (Vector2 p, Color col, float size = 1) { size *= 0.5f; Debug.DrawLine(new Vector3(p.x, 0, p.y) - Vector3.right*size, new Vector3(p.x, 0, p.y) + Vector3.right*size, col); Debug.DrawLine(new Vector3(p.x, 0, p.y) - Vector3.forward*size, new Vector3(p.x, 0, p.y) + Vector3.forward*size, col); } public struct VO { public Vector2 origin, center; Vector2 line1, line2, dir1, dir2; Vector2 cutoffLine, cutoffDir; float sqrCutoffDistance; bool leftSide; bool colliding; float radius; float weightFactor; /** Creates a VO to avoid the half plane created by the point \a p0 and has a tangent in the direction of \a dir. * \param p0 A point on the half plane border * \param dir The normalized tangent to the half plane * \param weightFactor relative amount of influence this VO should have on the agent */ public VO (Vector2 offset, Vector2 p0, Vector2 dir, float weightFactor) { colliding = true; line1 = p0; dir1 = -dir; // Fully initialize the struct, compiler complains otherwise origin = Vector2.zero; center = Vector2.zero; line2 = Vector2.zero; dir2 = Vector2.zero; cutoffLine = Vector2.zero; cutoffDir = Vector2.zero; sqrCutoffDistance = 0; leftSide = false; radius = 0; // Adjusted so that a parameter weightFactor of 1 will be the default ("natural") weight factor this.weightFactor = weightFactor*0.5f; //Debug.DrawRay ( To3D(offset + line1), To3D(dir1)*10, Color.red); } /** Creates a VO to avoid the three half planes with {point, tangent}s of {p1, p2-p1}, {p1, tang1}, {p2, tang2}. * tang1 and tang2 should be normalized. */ public VO (Vector2 offset, Vector2 p1, Vector2 p2, Vector2 tang1, Vector2 tang2, float weightFactor) { // Adjusted so that a parameter weightFactor of 1 will be the default ("natural") weight factor this.weightFactor = weightFactor*0.5f; colliding = false; cutoffLine = p1; /** \todo Square root can theoretically be removed by passing another parameter */ cutoffDir = (p2-p1).normalized; line1 = p1; dir1 = tang1; line2 = p2; dir2 = tang2; //dir1 = -dir1; dir2 = -dir2; cutoffDir = -cutoffDir; // Fully initialize the struct, compiler complains otherwise origin = Vector2.zero; center = Vector2.zero; sqrCutoffDistance = 0; leftSide = false; radius = 0; weightFactor = 5; //Debug.DrawRay (To3D(cutoffLine+offset), To3D(cutoffDir)*10, Color.blue); //Debug.DrawRay (To3D(line1+offset), To3D(dir1)*10, Color.blue); //Debug.DrawRay (To3D(line2+offset), To3D(dir2)*10, Color.cyan); } /** Creates a VO for avoiding another agent */ public VO (Vector2 center, Vector2 offset, float radius, Vector2 sideChooser, float inverseDt, float weightFactor) { // Adjusted so that a parameter weightFactor of 1 will be the default ("natural") weight factor this.weightFactor = weightFactor*0.5f; //this.radius = radius; Vector2 globalCenter; this.origin = offset; weightFactor = 0.5f; // Collision? if (center.magnitude < radius) { colliding = true; leftSide = false; line1 = center.normalized * (center.magnitude - radius); dir1 = new Vector2(line1.y, -line1.x).normalized; line1 += offset; cutoffDir = Vector2.zero; cutoffLine = Vector2.zero; sqrCutoffDistance = 0; dir2 = Vector2.zero; line2 = Vector2.zero; this.center = Vector2.zero; this.radius = 0; } else { colliding = false; center *= inverseDt; radius *= inverseDt; globalCenter = center+offset; sqrCutoffDistance = center.magnitude - radius; this.center = center; cutoffLine = center.normalized * sqrCutoffDistance; cutoffDir = new Vector2(-cutoffLine.y, cutoffLine.x).normalized; cutoffLine += offset; sqrCutoffDistance *= sqrCutoffDistance; float alpha = Mathf.Atan2(-center.y, -center.x); float delta = Mathf.Abs(Mathf.Acos(radius/center.magnitude)); this.radius = radius; // Bounding Lines leftSide = VectorMath.RightOrColinear(Vector2.zero, center, sideChooser); // Point on circle line1 = new Vector2(Mathf.Cos(alpha+delta), Mathf.Sin(alpha+delta)) * radius; // Vector tangent to circle which is the correct line tangent dir1 = new Vector2(line1.y, -line1.x).normalized; // Point on circle line2 = new Vector2(Mathf.Cos(alpha-delta), Mathf.Sin(alpha-delta)) * radius; // Vector tangent to circle which is the correct line tangent dir2 = new Vector2(line2.y, -line2.x).normalized; line1 += globalCenter; line2 += globalCenter; //Debug.DrawRay ( To3D(line1), To3D(dir1), Color.cyan ); //Debug.DrawRay ( To3D(line2), To3D(dir2), Color.cyan ); } } /** Returns if \a p lies on the left side of a line which with one point in \a a and has a tangent in the direction of \a dir. * Also returns true if the points are colinear. */ public static bool Left (Vector2 a, Vector2 dir, Vector2 p) { return (dir.x) * (p.y - a.y) - (p.x - a.x) * (dir.y) <= 0; } /** Returns a negative number of if \a p lies on the left side of a line which with one point in \a a and has a tangent in the direction of \a dir. * The number can be seen as the double signed area of the triangle {a, a+dir, p} multiplied by the length of \a dir. * If length(dir)=1 this is also the distance from p to the line {a, a+dir}. */ public static float Det (Vector2 a, Vector2 dir, Vector2 p) { return (p.x - a.x) * (dir.y) - (dir.x) * (p.y - a.y); } public Vector2 Sample (Vector2 p, out float weight) { if (colliding) { // Calculate double signed area of the triangle consisting of the points // {line1, line1+dir1, p} float l1 = Det(line1, dir1, p); // Serves as a check for which side of the line the point p is if (l1 >= 0) { /*float dot1 = Vector2.Dot ( p - line1, dir1 ); * * Vector2 c1 = dot1 * dir1 + line1; * return (c1-p);*/ weight = l1*weightFactor; return new Vector2(-dir1.y, dir1.x)*weight*GlobalIncompressibility; // 10 is an arbitrary constant signifying incompressability // (the higher the value, the more the agents will avoid penetration) } else { weight = 0; return new Vector2(0, 0); } } float det3 = Det(cutoffLine, cutoffDir, p); if (det3 <= 0) { weight = 0; return Vector2.zero; } else { float det1 = Det(line1, dir1, p); float det2 = Det(line2, dir2, p); if (det1 >= 0 && det2 >= 0) { // We are inside both of the half planes // (all three if we count the cutoff line) // and thus inside the forbidden region in velocity space /*float magn = ( p - origin ).sqrMagnitude; * if ( magn < sqrCutoffDistance ) { * weight = 0; * return Vector2.zero; * }*/ if (leftSide) { if (det3 < radius) { weight = det3*weightFactor; return new Vector2(-cutoffDir.y, cutoffDir.x)*weight; /*Vector2 dir = (p - center); * float magn = dir.magnitude; * weight = radius-magn; * dir *= (1.0f/magn)*weight; * return dir;*/ } weight = det1; return new Vector2(-dir1.y, dir1.x)*weight; } else { if (det3 < radius) { weight = det3*weightFactor; return new Vector2(-cutoffDir.y, cutoffDir.x)*weight; /*Vector2 dir = (p - center); * float magn = dir.magnitude; * weight = radius-magn; * dir *= (1.0f/magn)*weight; * return dir;*/ } /*if ( det3 < det2 ) { * weight = det3*0.5f; * return new Vector2(-cutoffDir.y, cutoffDir.x)*weight; * }*/ weight = det2*weightFactor; return new Vector2(-dir2.y, dir2.x)*weight; } } } weight = 0; return new Vector2(0, 0); } public float ScalarSample (Vector2 p) { if (colliding) { // Calculate double signed area of the triangle consisting of the points // {line1, line1+dir1, p} float l1 = Det(line1, dir1, p); // Serves as a check for which side of the line the point p is if (l1 >= 0) { /*float dot1 = Vector2.Dot ( p - line1, dir1 ); * * Vector2 c1 = dot1 * dir1 + line1; * return (c1-p);*/ return l1*GlobalIncompressibility*weightFactor; } else { return 0; } } float det3 = Det(cutoffLine, cutoffDir, p); if (det3 <= 0) { return 0; } { float det1 = Det(line1, dir1, p); float det2 = Det(line2, dir2, p); if (det1 >= 0 && det2 >= 0) { /*float magn = ( p - origin ).sqrMagnitude; * if ( magn < sqrCutoffDistance ) { * weight = 0; * return Vector2.zero; * }*/ if (leftSide) { if (det3 < radius) { return det3*weightFactor; //return radius - (p-center).magnitude; /*Vector2 dir = (p - center); * float magn = dir.magnitude; * weight = radius-magn; * dir *= (1.0f/magn)*weight; * return dir;*/ } return det1*weightFactor; } else { if (det3 < radius) { return det3*weightFactor; //return radius - (p-center).magnitude; /*Vector2 dir = (p - center); * float magn = dir.magnitude; * weight = radius-magn; * dir *= (1.0f/magn)*weight; * return dir;*/ } return det2*weightFactor; } } } return 0; } } internal void CalculateVelocity (Pathfinding.RVO.Simulator.WorkerContext context) { if (locked) { newVelocity = Vector2.zero; return; } if (context.vos.Length < neighbours.Count+simulator.obstacles.Count) { context.vos = new VO[Mathf.Max(context.vos.Length*2, neighbours.Count+simulator.obstacles.Count)]; } Vector2 position2D = new Vector2(position.x, position.z); var vos = context.vos; var voCount = 0; Vector2 optimalVelocity = new Vector2(velocity.x, velocity.z); float inverseAgentTimeHorizon = 1.0f/agentTimeHorizon; float wallThickness = simulator.WallThickness; float wallWeight = simulator.algorithm == Simulator.SamplingAlgorithm.GradientDecent ? 1 : WallWeight; for (int i = 0; i < simulator.obstacles.Count; i++) { var obstacle = simulator.obstacles[i]; var vertex = obstacle; do { if (vertex.ignore || position.y > vertex.position.y + vertex.height || position.y+height < vertex.position.y || (vertex.layer & collidesWith) == 0) { vertex = vertex.next; continue; } float cross = VO.Det(new Vector2(vertex.position.x, vertex.position.z), vertex.dir, position2D);// vertex.dir.x * ( vertex.position.z - position.z ) - vertex.dir.y * ( vertex.position.x - position.x ); // Signed distance from the line (not segment), lines are infinite // Usually divided by vertex.dir.magnitude, but that is known to be 1 float signedDist = cross; float dotFactor = Vector2.Dot(vertex.dir, position2D - new Vector2(vertex.position.x, vertex.position.z)); // It is closest to the segment // if the dotFactor is <= 0 or >= length of the segment // WallThickness*0.1 is added as a margin to avoid false positives when moving along the edges of square obstacles bool closestIsEndpoints = dotFactor <= wallThickness*0.05f || dotFactor >= (new Vector2(vertex.position.x, vertex.position.z) - new Vector2(vertex.next.position.x, vertex.next.position.z)).magnitude - wallThickness*0.05f; if (Mathf.Abs(signedDist) < neighbourDist) { if (signedDist <= 0 && !closestIsEndpoints && signedDist > -wallThickness) { // Inside the wall on the "wrong" side vos[voCount] = new VO(position2D, new Vector2(vertex.position.x, vertex.position.z) - position2D, vertex.dir, wallWeight*2); voCount++; } else if (signedDist > 0) { //Debug.DrawLine (position, (vertex.position+vertex.next.position)*0.5f, Color.yellow); Vector2 p1 = new Vector2(vertex.position.x, vertex.position.z) - position2D; Vector2 p2 = new Vector2(vertex.next.position.x, vertex.next.position.z) - position2D; Vector2 tang1 = (p1).normalized; Vector2 tang2 = (p2).normalized; vos[voCount] = new VO(position2D, p1, p2, tang1, tang2, wallWeight); voCount++; } } vertex = vertex.next; } while (vertex != obstacle); } for (int o = 0; o < neighbours.Count; o++) { Agent other = neighbours[o]; if (other == this) continue; float maxY = System.Math.Min(position.y+height, other.position.y+other.height); float minY = System.Math.Max(position.y, other.position.y); //The agents cannot collide since they //are on different y-levels if (maxY - minY < 0) { continue; } Vector2 otherOptimalVelocity = new Vector2(other.Velocity.x, other.velocity.z); float totalRadius = radius + other.radius; // Describes a circle on the border of the VO //float boundingRadius = totalRadius * inverseAgentTimeHorizon; Vector2 voBoundingOrigin = new Vector2(other.position.x, other.position.z) - position2D; //float boundingDist = voBoundingOrigin.magnitude; Vector2 relativeVelocity = optimalVelocity - otherOptimalVelocity; { //voBoundingOrigin *= inverseAgentTimeHorizon; //boundingDist *= inverseAgentTimeHorizon; // Common case, no collision Vector2 voCenter; if (other.locked) { voCenter = otherOptimalVelocity; } else { voCenter = (optimalVelocity + otherOptimalVelocity)*0.5f; } vos[voCount] = new VO(voBoundingOrigin, voCenter, totalRadius, relativeVelocity, inverseAgentTimeHorizon, 1); voCount++; if (DebugDraw) DrawVO(position2D + voBoundingOrigin*inverseAgentTimeHorizon + voCenter, totalRadius*inverseAgentTimeHorizon, position2D + voCenter); } } Vector2 result = Vector2.zero; if (simulator.algorithm == Simulator.SamplingAlgorithm.GradientDecent) { if (DebugDraw) { const int PlotWidth = 40; const float WorldPlotWidth = 15; for (int x = 0; x < PlotWidth; x++) { for (int y = 0; y < PlotWidth; y++) { Vector2 p = new Vector2(x*WorldPlotWidth / PlotWidth, y*WorldPlotWidth / PlotWidth); Vector2 dir = Vector2.zero; float weight = 0; for (int i = 0; i < voCount; i++) { float w; dir += vos[i].Sample(p-position2D, out w); if (w > weight) weight = w; } Vector2 d2 = (new Vector2(desiredVelocity.x, desiredVelocity.z) - (p-position2D)); dir += d2*DesiredVelocityScale; if (d2.magnitude * DesiredVelocityWeight > weight) weight = d2.magnitude * DesiredVelocityWeight; if (weight > 0) dir /= weight; //Vector2 d3 = simulator.SampleDensity (p+position2D); Debug.DrawRay(To3D(p), To3D(d2*0.00f), Color.blue); //simulator.Plot (p, Rainbow(weight*simulator.colorScale)); float sc = 0; Vector2 p0 = p - Vector2.one*WorldPlotWidth*0.5f; Vector2 p1 = Trace(vos, voCount, p0, 0.01f, out sc); if ((p0 - p1).sqrMagnitude < Sqr(WorldPlotWidth / PlotWidth)*2.6f) { Debug.DrawRay(To3D(p1 + position2D), Vector3.up*1, Color.red); } } } } //if ( debug ) { float best = float.PositiveInfinity; float cutoff = new Vector2(velocity.x, velocity.z).magnitude*simulator.qualityCutoff; //for ( int i = 0; i < 10; i++ ) { { result = Trace(vos, voCount, new Vector2(desiredVelocity.x, desiredVelocity.z), cutoff, out best); if (DebugDraw) DrawCross(result+position2D, Color.yellow, 0.5f); } // Can be uncommented for higher quality local avoidance /*for ( int i = 0; i < 3; i++ ) { * Vector2 p = desiredVelocity + new Vector2(Mathf.Cos(Mathf.PI*2*(i/3.0f)), Mathf.Sin(Mathf.PI*2*(i/3.0f))); * float score; * Vector2 res = Trace ( vos, voCount, p, velocity.magnitude*simulator.qualityCutoff, out score ); * * if ( score < best ) { * //if ( score < best*0.9f ) Debug.Log ("Better " + score + " < " + best); * result = res; * best = score; * } * }*/ { Vector2 p = Velocity; float score; Vector2 res = Trace(vos, voCount, p, cutoff, out score); if (score < best) { //if ( score < best*0.9f ) Debug.Log ("Better " + score + " < " + best); result = res; best = score; } if (DebugDraw) DrawCross(res+position2D, Color.magenta, 0.5f); } } else { // Adaptive sampling Vector2[] samplePos = context.samplePos; float[] sampleSize = context.sampleSize; int samplePosCount = 0; Vector2 desired2D = new Vector2(desiredVelocity.x, desiredVelocity.z); float sampleScale = Mathf.Max(radius, Mathf.Max(desired2D.magnitude, Velocity.magnitude)); samplePos[samplePosCount] = desired2D; sampleSize[samplePosCount] = sampleScale*0.3f; samplePosCount++; const float GridScale = 0.3f; // Initial 9 samples samplePos[samplePosCount] = optimalVelocity; sampleSize[samplePosCount] = sampleScale*GridScale; samplePosCount++; { Vector2 fw = optimalVelocity * 0.5f; Vector2 rw = new Vector2(fw.y, -fw.x); const int Steps = 8; for (int i = 0; i < Steps; i++) { samplePos[samplePosCount] = rw * Mathf.Sin(i*Mathf.PI*2 / Steps) + fw * (1 + Mathf.Cos(i*Mathf.PI*2 / Steps)); sampleSize[samplePosCount] = (1.0f - (Mathf.Abs(i - Steps*0.5f)/Steps))*sampleScale*0.5f; samplePosCount++; } const float InnerScale = 0.6f; fw *= InnerScale; rw *= InnerScale; const int Steps2 = 6; for (int i = 0; i < Steps2; i++) { samplePos[samplePosCount] = rw * Mathf.Cos((i+0.5f)*Mathf.PI*2 / Steps2) + fw * ((1.0f/InnerScale) + Mathf.Sin((i+0.5f)*Mathf.PI*2 / Steps2)); sampleSize[samplePosCount] = sampleScale*0.3f; samplePosCount++; } const float TargetScale = 0.2f; const int Steps3 = 6; for (int i = 0; i < Steps3; i++) { samplePos[samplePosCount] = optimalVelocity + new Vector2(sampleScale * TargetScale * Mathf.Cos((i+0.5f)*Mathf.PI*2 / Steps3), sampleScale * TargetScale * Mathf.Sin((i+0.5f)*Mathf.PI*2 / Steps3)); sampleSize[samplePosCount] = sampleScale*TargetScale*2; samplePosCount++; } } samplePos[samplePosCount] = optimalVelocity*0.5f; sampleSize[samplePosCount] = sampleScale*0.4f; samplePosCount++; const int KeepCount = Simulator.WorkerContext.KeepCount; Vector2[] bestPos = context.bestPos; float[] bestSizes = context.bestSizes; float[] bestScores = context.bestScores; for (int i = 0; i < KeepCount; i++) { bestScores[i] = float.PositiveInfinity; } bestScores[KeepCount] = float.NegativeInfinity; Vector2 bestEver = optimalVelocity; float bestEverScore = float.PositiveInfinity; for (int sub = 0; sub < 3; sub++) { for (int i = 0; i < samplePosCount; i++) { float score = 0; for (int vo = 0; vo < voCount; vo++) { score = System.Math.Max(score, vos[vo].ScalarSample(samplePos[i])); } // Note that velocity is a vector and speed is a scalar, not the same thing float bonusForDesiredVelocity = (samplePos[i] - desired2D).magnitude; // This didn't work out as well as I though // Code left here because I might reenable it later //float bonusForDesiredSpeed = Mathf.Abs (samplePos[i].magnitude - desired2D.magnitude); float biasedScore = score + bonusForDesiredVelocity*DesiredVelocityWeight;// + bonusForDesiredSpeed*0; score += bonusForDesiredVelocity*0.001f; if (DebugDraw) { DrawCross(position2D + samplePos[i], Rainbow(Mathf.Log(score+1)*5), sampleSize[i]*0.5f); } if (biasedScore < bestScores[0]) { for (int j = 0; j < KeepCount; j++) { if (biasedScore >= bestScores[j+1]) { bestScores[j] = biasedScore; bestSizes[j] = sampleSize[i]; bestPos[j] = samplePos[i]; break; } } } if (score < bestEverScore) { bestEver = samplePos[i]; bestEverScore = score; if (score == 0) { sub = 100; break; } } } samplePosCount = 0; for (int i = 0; i < KeepCount; i++) { Vector2 p = bestPos[i]; float s = bestSizes[i]; bestScores[i] = float.PositiveInfinity; const float Half = 0.6f; float offset = s * Half * 0.5f; samplePos[samplePosCount+0] = (p + new Vector2(+offset, +offset)); samplePos[samplePosCount+1] = (p + new Vector2(-offset, +offset)); samplePos[samplePosCount+2] = (p + new Vector2(-offset, -offset)); samplePos[samplePosCount+3] = (p + new Vector2(+offset, -offset)); s *= s * Half; sampleSize[samplePosCount+0] = (s); sampleSize[samplePosCount+1] = (s); sampleSize[samplePosCount+2] = (s); sampleSize[samplePosCount+3] = (s); samplePosCount += 4; } } result = bestEver; } if (DebugDraw) DrawCross(result+position2D); newVelocity = To3D(Vector2.ClampMagnitude(result, maxSpeed)); } public static float DesiredVelocityWeight = 0.02f; public static float DesiredVelocityScale = 0.1f; //public static float DesiredSpeedScale = 0.0f; public static float GlobalIncompressibility = 30; /** Extra weight that walls will have */ const float WallWeight = 5; static Color Rainbow (float v) { Color c = new Color(v, 0, 0); if (c.r > 1) { c.g = c.r - 1; c.r = 1; } if (c.g > 1) { c.b = c.g - 1; c.g = 1; } return c; } /** Traces the vector field constructed out of the velocity obstacles. * Returns the position which gives the minimum score (approximately). */ Vector2 Trace (VO[] vos, int voCount, Vector2 p, float cutoff, out float score) { score = 0; float stepScale = simulator.stepScale; float bestScore = float.PositiveInfinity; Vector2 bestP = p; for (int s = 0; s < 50; s++) { float step = 1.0f - (s/50.0f); step *= stepScale; Vector2 dir = Vector2.zero; float mx = 0; for (int i = 0; i < voCount; i++) { float w; Vector2 d = vos[i].Sample(p, out w); dir += d; if (w > mx) mx = w; //mx = System.Math.Max (mx, d.sqrMagnitude); } // This didn't work out as well as I though // Code left here because I might reenable it later //Vector2 bonusForDesiredSpeed = p.normalized * new Vector2(desiredVelocity.x,desiredVelocity.z).magnitude - p; Vector2 bonusForDesiredVelocity = (new Vector2(desiredVelocity.x, desiredVelocity.z) - p); float weight = bonusForDesiredVelocity.magnitude*DesiredVelocityWeight;// + bonusForDesiredSpeed.magnitude*DesiredSpeedScale; dir += bonusForDesiredVelocity*DesiredVelocityScale;// + bonusForDesiredSpeed*DesiredSpeedScale; mx = System.Math.Max(mx, weight); score = mx; if (score < bestScore) { bestScore = score; } bestP = p; if (score <= cutoff && s > 10) break; float sq = dir.sqrMagnitude; if (sq > 0) dir *= mx/Mathf.Sqrt(sq); dir *= step; Vector2 prev = p; p += dir; if (DebugDraw) Debug.DrawLine(To3D(prev)+position, To3D(p)+position, Rainbow(0.1f/score) * new Color(1, 1, 1, 0.2f)); } score = bestScore; return bestP; } /** Returns the intersection factors for line 1 and line 2. The intersection factors is a distance along the line \a start - \a end where the other line intersects it.\n * \code intersectionPoint = start1 + factor1 * (end1-start1) \endcode * \code intersectionPoint2 = start2 + factor2 * (end2-start2) \endcode * Lines are treated as infinite.\n * false is returned if the lines are parallel and true if they are not. */ public static bool IntersectionFactor (Vector2 start1, Vector2 dir1, Vector2 start2, Vector2 dir2, out float factor) { float den = dir2.y*dir1.x - dir2.x * dir1.y; // Parallel if (den == 0) { factor = 0; return false; } float nom = dir2.x*(start1.y-start2.y)- dir2.y*(start1.x-start2.x); factor = nom/den; return true; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using iSukces.Code.AutoCode; using iSukces.Code.Interfaces; namespace iSukces.Code.FeatureImplementers { public partial class EqualityFeatureImplementer { public EqualityFeatureImplementer(CsClass @class, Type type) { _class = @class; _type = type; MyTypeName = _class.GetTypeName(type); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static string GetSuffix(int cnt) => cnt == 0 ? "" : (cnt + 1).ToCsString(); public void CreateCode() { if (ImplementFeatures.HasFlag(Features.Equality)) { WriteEqualsWithObject(); WriteEqualsWithMyType(); WriteEqualityOperators(); WriteGetHashCode(); } if (ImplementFeatures.HasFlag(Features.CompareTo)) { var methodName = WriteCompareTo(); if (ImplementFeatures.HasFlag(Features.CompareOperators) && !string.IsNullOrEmpty(methodName)) WriteCompareOperators(methodName); } } public EqualityFeatureImplementer WithCompareToExpressions(IEnumerable<CompareToExpressionData> expressions) { if (CompareToExpressions == null) CompareToExpressions = new List<CompareToExpressionData>(); else CompareToExpressions.Clear(); CompareToExpressions.AddRange(expressions); return this; } public EqualityFeatureImplementer WithEqualityExpressions(IEnumerable<EqualsExpressionData> expressions) { if (EqualityExpressions == null) EqualityExpressions = new List<EqualsExpressionData>(); else EqualityExpressions.Clear(); EqualityExpressions.AddRange(expressions); return this; } public EqualityFeatureImplementer WithGetHashCodeExpressions( IEnumerable<GetHashCodeExpressionDataWithMemberInfo> expressions) { if (GetHashCodeExpressions == null) GetHashCodeExpressions = new List<GetHashCodeExpressionDataWithMemberInfo>(); else GetHashCodeExpressions.Clear(); expressions = expressions.OrderBy(a => a); GetHashCodeExpressions.AddRange(expressions); return this; } private void AddNeverBrowsable(IAttributable field) { var tn1 = _class.GetTypeName(typeof(DebuggerBrowsableAttribute)); var tn2 = _class.GetTypeName(typeof(DebuggerBrowsableState)); field.Attributes.Add(new CsAttribute(tn1).WithArgument(new CsDirectCode(tn2 + ".Never"))); } private void AddOperatorMethod(string opertatorName, string body) { var m = _class.AddMethod(opertatorName, "bool").WithStatic().WithBody(body); m.Parameters.Add(new CsProperty("left", MyTypeName)); m.Parameters.Add(new CsProperty("right", MyTypeName)); } private void WriteCompareOperators(string methodName) { var hasEqualityGeneratorAttribute = ImplementFeatures.HasFlag(Features.Equality); if (methodName is null) { var tmp = GeneratorsHelper.DefaultComparerMethodName(_type, _class); methodName = tmp.GetCode(); foreach (var oper in CompareOperators) { var resultIfEqual = oper.Length == 2 ? "true" : "false"; var cs = new CsCodeWriter(); if (hasEqualityGeneratorAttribute) cs.WriteLine($"if (Equals(left, right)) return {resultIfEqual};"); else if (CanBeNull) cs.WriteLine($"if (ReferenceEquals(left, right)) return {resultIfEqual};"); cs.WriteLine($"return {methodName}(left, right) {oper} 0;"); AddOperatorMethod(oper, cs.Code); } } else { foreach (var oper in CompareOperators) { var resultIfEqual = oper.Length == 2 ? "true" : "false"; var cs = new CsCodeWriter(); if (hasEqualityGeneratorAttribute) cs.WriteLine($"if (Equals(left, right)) return {resultIfEqual};"); else if (CanBeNull) cs.WriteLine($"if (ReferenceEquals(left, right)) return {resultIfEqual};"); // ======= if (CanBeNull) { var result = oper.Contains("<") ? "true" : "false"; cs.WriteLine("if (left is null) // null.CompareTo(NOTNULL) = -1") .IncIndent() .WriteLine($"return {result};") .DecIndent(); } cs.WriteLine($"return left.CompareTo(right) {oper} 0;"); AddOperatorMethod(oper, cs.Code); } } } private string WriteCompareTo() { if (CompareToExpressions is null || CompareToExpressions.Count == 0) return null; var cs = new CsCodeWriter(); if (CanBeNull) cs.WriteLine("if (ReferenceEquals(this, other)) return 0;") .WriteLine("if (other is null) return 1;"); var comparers = new Dictionary<string, string>(); for (var index = 0; index < CompareToExpressions.Count; index++) { var c1 = CompareToExpressions[index]; var expr = c1.ExpressionTemplate; if (!string.IsNullOrEmpty(c1.Instance)) { if (!comparers.TryGetValue(c1.Instance, out var variableName)) { comparers[c1.Instance] = variableName = "comparer" + GetSuffix(comparers.Count); cs.WriteLine("var " + variableName + " = " + c1.Instance + ";"); } expr = expr.Format(variableName); } if (index + 1 == CompareToExpressions.Count) { cs.WriteLine($"return {expr};"); } else { // var compar = c1.FieldName.FirstLower() + "Comparison"; var compar = "comparisonResult"; // c1.FieldName.FirstLower() + "Comparison"; if (index == 0) cs.WriteLine($"var {compar} = {expr};"); else cs.WriteLine($"{compar} = {expr};"); cs.WriteLine($"if ({compar} != 0) return {compar};"); } } var m = _class.AddMethod(nameof(IComparable<int>.CompareTo), "int") .WithBody(cs); m.Parameters.Add(new CsProperty("other", _class.Name)); cs = new CsCodeWriter() .WriteLine("if (obj is null) return 1;"); if (CanBeNull) cs.WriteLine("if (ReferenceEquals(this, obj)) return 0;"); cs.WriteLine( $"return obj is {MyTypeName} other ? CompareTo(other) : throw new ArgumentException(\"Object must be of type {MyTypeName}\");"); m = _class.AddMethod(m.Name, "int") .WithBody(cs); m.Parameters.Add(new CsProperty("obj", "object")); return m.Name; } private void WriteEqualityOperators() { AddOperatorMethod("==", "return Equals(left, right);"); AddOperatorMethod("!=", "return !Equals(left, right);"); } private void WriteEqualsWithMyType() { var cw = new CsCodeWriter(); if (CanBeNull) { cw.WriteLine($"if ({OtherArgName} is null) return false;"); cw.WriteLine($"if (ReferenceEquals(this, {OtherArgName})) return true;"); } if (UseGetHashCodeInEqualityChecking) { var getHashCodeExpression = CachedGetHashCodeImplementation == GetHashCodeImplementationKind.Precomputed ? GetHashCodeFieldName : nameof(GetHashCode) + "()"; cw.WriteLine( $"if ({getHashCodeExpression} != {OtherArgName}.{getHashCodeExpression}) return false;"); } if (!string.IsNullOrEmpty(IsEmptyObjectPropertyName)) { cw.WriteLine( $"if ({IsEmptyObjectPropertyName}) return {OtherArgName}.{IsEmptyObjectPropertyName};"); cw.WriteLine($"if ({OtherArgName}.{IsEmptyObjectPropertyName}) return false;"); } for (var i = 0; i < EqualityExpressions.Count; i++) { var code = i == 0 ? EqualityExpressions[i].Code.GetCode(CsOperatorPrecendence.LogicalAnd, ExpressionAppend.Before) : EqualityExpressions[i].Code.GetCode(CsOperatorPrecendence.LogicalAnd, ExpressionAppend.After); var codeLine = (i == 0 ? "return " : " && ") + code; if (i + 1 == EqualityExpressions.Count) codeLine += ";"; cw.WriteLine(codeLine); // +" // cost "+code[i].co); } var m = _class.AddMethod("Equals", "bool") .WithBody(cw); m.AddParam(OtherArgName, MyTypeName); } private void WriteEqualsWithObject() { var gettype = nameof(GetType) + "()"; if (_type.GetTypeInfo().IsSealed) gettype = string.Format("typeof({0})", MyTypeName); var cw = new CsCodeWriter(); cw.WriteLine($"if ({OtherArgName} is null) return false;"); if (CanBeNull) { cw.WriteLine($"if (ReferenceEquals(this, {OtherArgName})) return true;"); cw.WriteLine( $"return {OtherArgName} is {MyTypeName} {OtherArgName}Casted && Equals({OtherArgName}Casted);"); } else { cw.WriteLine($"if ({OtherArgName}.GetType() != {gettype}) return false;"); cw.WriteLine($"return Equals(({MyTypeName}){OtherArgName});"); } var m = _class.AddMethod("Equals", "bool") .WithOverride() .WithBody(cw); m.AddParam(OtherArgName, "object"); } private void WriteGetHashCode() { if (CachedGetHashCodeImplementation == GetHashCodeImplementationKind.Custom) return; const string flagFieldName = "_isCachedHashCodeCalculated"; const string calculateHashCode = "CalculateHashCode"; var hasBoolField = CachedGetHashCodeImplementation == GetHashCodeImplementationKind.Cached; var hasIntField = hasBoolField || CachedGetHashCodeImplementation == GetHashCodeImplementationKind.Precomputed; if (hasBoolField) { var field = _class.AddField(flagFieldName, "bool"); AddNeverBrowsable(field); } if (hasIntField) { var field = _class.AddField(GetHashCodeFieldName, "int").WithVisibility(Visibilities.Private); AddNeverBrowsable(field); } switch (CachedGetHashCodeImplementation) { case GetHashCodeImplementationKind.Cached: var cw1 = new CsCodeWriter() .WriteLine($"if ({flagFieldName}) return {GetHashCodeFieldName};") .WriteLine($"{GetHashCodeFieldName} = {calculateHashCode}();") .WriteLine($"{flagFieldName} = true;") .WriteLine($"return {GetHashCodeFieldName};"); _class.AddMethod("GetHashCode", "int") .WithOverride() .WithBody(cw1); break; case GetHashCodeImplementationKind.Precomputed: _class.AddMethod("GetHashCode", "int") .WithOverride() .WithBody($"return {GetHashCodeFieldName};"); break; } var useCalcMetod = hasIntField; var m = WriteGetHashCode(useCalcMetod ? calculateHashCode : nameof(GetHashCode)); if (useCalcMetod) m.Visibility = Visibilities.Private; else m.Overriding = OverridingType.Override; } private CsMethod WriteGetHashCode(string methodName) { CsCodeWriter WriteGetHashCodeInternal() { var cw = new CsCodeWriter(); var expressions = GetHashCodeExpressions; if (expressions.Count == 0) { cw.WriteLine("return 0;"); return cw; } if (!string.IsNullOrEmpty(IsEmptyObjectPropertyName)) { if (expressions.Count == 1) { var q = expressions[0].Code.ExpressionWithOffset; cw.WriteLine($"return {IsEmptyObjectPropertyName} ? 0 : {q};"); return cw; } cw.WriteLine($"if ({IsEmptyObjectPropertyName}) return 0;"); } GetHashCodeEmiter.Write(expressions, cw); return cw; } var cw1 = WriteGetHashCodeInternal(); var m = _class.AddMethod(methodName, "int") .WithBody(cw1); return m; } public List<EqualsExpressionData> EqualityExpressions { get; set; } = new List<EqualsExpressionData>(); public List<CompareToExpressionData> CompareToExpressions { get; set; } = new List<CompareToExpressionData>(); public List<GetHashCodeExpressionDataWithMemberInfo> GetHashCodeExpressions { get; set; } = new List<GetHashCodeExpressionDataWithMemberInfo>(); public Features ImplementFeatures { get; set; } public string OtherArgName { get; set; } = "other"; public string MyTypeName { get; } /// <summary> /// Name of property that denotes if object is empty. If true then no other properties will be compared. /// </summary> public string IsEmptyObjectPropertyName { get; set; } public bool UseGetHashCodeInEqualityChecking { get; set; } public GetHashCodeImplementationKind CachedGetHashCodeImplementation { get; set; } public bool CanBeNull { get; set; } public static int DefaultGethashcodeMultiply = 397; public static IReadOnlyList<string> CompareOperators = "> < >= <=".Split(' '); private readonly CsClass _class; private readonly Type _type; [Flags] public enum Features { None = 0, Equality = 1, CompareTo = 2, CompareOperators = 4, All = Equality | CompareTo | CompareOperators } private const string GetHashCodeFieldName = "_cachedHashCode"; } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace System { /// <summary> /// Defines the kinds of <see cref="System.Uri"/>s for the /// <see cref="System.Uri.IsWellFormedUriString"/> method and several /// <see cref="System.Uri"/> methods. /// </summary> public enum UriKind { /// <summary> /// The kind of the Uri is indeterminate. /// </summary> RelativeOrAbsolute = 0, /// <summary> /// The Uri is an absolute Uri. /// </summary> Absolute = 1, /// <summary> /// The Uri is a relative Uri. /// </summary> Relative = 2, } /// <summary> /// Defines host name types for the http and https protocols. /// method. /// </summary> public enum UriHostNameType { /// <summary> /// The type of the host name is not supplied. /// </summary> Unknown = 0, /// <summary> /// The host is set, but the type cannot be determined. /// </summary> Basic = 1, /// <summary> /// The host name is a domain name system (DNS) style host name. /// </summary> Dns = 2, /// <summary> /// The host name is an Internet Protocol (IP) version 4 host address. /// </summary> IPv4 = 3, /// <summary> /// The host name is an Internet Protocol (IP) version 6 host address. /// </summary> IPv6 = 4, } /// <summary> /// Provides an object representation of a uniform resource identifier (URI) /// and easy access to the parts of the URI. /// </summary> public class Uri { private int DefaultPort(string scheme) { switch (scheme) { case "http": return 80; case "https": return 443; case "ftp": return 21; case "gopher": return 70; case "nntp": return 119; case "telnet": return 23; case "ldap": return 389; case "mailto": return 25; case "net.tcp": return 808; case "ws": return 80; default: return UnknownPort; } } /// <summary> /// Defines flags kept in m_Flags variable. /// </summary> protected enum Flags { /// <summary> /// Flag value for loopback host /// </summary> LoopbackHost = 0x00400000 } /// <summary> /// Default port for http protocol - 80 /// </summary> public const int HttpDefaultPort = 80; /// <summary> /// Default port for https protocol - 443 /// </summary> public const int HttpsDefaultPort = 443; /// <summary> /// Constant to indicate that port for this protocol is unknown /// </summary> protected const int UnknownPort = -1; /// <summary> /// Type of the host. /// </summary> protected UriHostNameType m_hostNameType; /// <summary> /// Member variable that keeps port used by this uri. /// </summary> protected int m_port = UnknownPort; /// <summary> /// Member variable that keeps internal flags/ /// </summary> protected int m_Flags = 0; /// <summary> /// Member varialbe that keeps absolute path. /// </summary> protected string m_AbsolutePath = null; /// <summary> /// Member varialbe that keeps original string passed to Uri constructor. /// </summary> protected string m_OriginalUriString = null; /// <summary> /// Member varialbe that keeps scheme of Uri. /// </summary> protected string m_scheme = null; /// <summary> /// Member varialbe that keeps host name ( http and https ). /// </summary> protected string m_host = ""; /// <summary> /// Member varialbe that keeps boolean if Uri is absolute. /// </summary> protected bool m_isAbsoluteUri = false; /// <summary> /// Member varialbe that tells if path is UNC ( Universal Naming Convention ) /// In this class it is always false, but can be changed in derived classes. /// </summary> protected bool m_isUnc = false; /// <summary> /// Member variable that keeps absolute uri (generated in method ParseUriString) /// </summary> protected string m_absoluteUri = null; /// <summary> /// Initializes a new instance of the <see cref="System.Uri"/> class /// with the specified URI. /// </summary> /// <remarks> /// This constructor parses the URI string, therefore it can be used to /// validate a URI. /// </remarks> /// <param name="uriString">A URI.</param> /// <exception cref="System.Exception"> /// The <paramref name="uriString"/> is null. /// </exception> /// <exception cref="System.ArgumentNullException"> /// <p>The <paramref name="uriString"/> is empty.</p> /// <p>-or-</p><p>The scheme specified in <paramref name="uriString"/> /// is not correctly formed. </p> /// <p>-or-</p><p><paramref name="uriString"/> contains too many /// slashes.</p> /// <p>-or-</p><p>The password specified in <paramref name="uriString"/> /// is not valid.</p> /// <p>-or-</p><p>The host name specified in /// <paramref name="uriString"/> is not valid.</p> /// <p>-or-</p><p>The file name specified in /// <paramref name="uriString"/> is not valid.</p> /// <p>-or-</p><p>The user name specified in /// <paramref name="uriString"/> is not valid.</p> /// <p>-or-</p><p>The host or authority name specified in /// <paramref name="uriString"/> cannot be terminated by backslashes. /// </p> /// <p>-or-</p><p>The port number specified in /// <paramref name="uriString"/> is not valid or cannot be parsed.</p> /// <p>-or-</p><p>The length of <paramref name="uriString"/> exceeds /// 65534 characters.</p> /// <p>-or-</p><p>The length of the scheme specified in /// <paramref name="uriString"/> exceeds 1023 characters.</p> /// <p>-or-</p><p>There is an invalid character sequence in /// <paramref name="uriString"/>.</p> /// <p>-or-</p><p>The MS-DOS path specified in /// <paramref name="uriString"/> must start with c:\\.</p> /// </exception> public Uri(string uriString) { ConstructAbsoluteUri(uriString); } /// <summary> /// Constructs an absolute Uri from a URI string. /// </summary> /// <param name="uriString">A URI.</param> /// <remarks> /// See <see cref="System.Uri(string)"/>. /// </remarks> protected void ConstructAbsoluteUri(string uriString) { // ParseUriString provides full validation including testing for // null. ParseUriString(uriString); m_OriginalUriString = uriString; } /// <summary> /// Constructs Uri from string and enumeration that tell what is the type of Uri. /// </summary> /// <param name="uriString">String to construct Uri from</param> /// <param name="kind">Type of Uri to construct</param> public Uri(string uriString, UriKind kind) { // ParseUriString provides full validation including testing for null. switch (kind) { case UriKind.Absolute: { ConstructAbsoluteUri(uriString); break; } // Do not support unknown type of Uri. User should decide what he wants. case UriKind.RelativeOrAbsolute: { throw new ArgumentException(); } // Relative Uri. Store in original string. case UriKind.Relative: { // Validates the relative Uri. ValidateUriPart(uriString, 0); m_OriginalUriString = uriString; break; } } m_OriginalUriString = uriString; } /// <summary> /// Validates that part of Uri after sheme is valid for unknown Uri scheme /// </summary> /// <param name="uriString">Uri string </param> /// <param name="startIndex">Index in the string where Uri part ( after scheme ) starts</param> protected void ValidateUriPart(string uriString, int startIndex) { // Check for valid alpha numeric characters int pathLength = uriString.Length - startIndex; // This is unknown scheme. We do validate following rules: // 1. All character values are less than 128. For characters it means they are more than zero. // 2. All charaters are >= 32. Lower values are control characters. // 3. If there is %, then there should be 2 hex digits which are 0-10 and A-F or a-f. for (int i = startIndex; i < pathLength; ++i) { //if (!(IsAlphaNumeric(uriString[i]) || uriString[i] == '+' || uriString[i] == '-' || uriString[i] == '.')) // If character is upper ( in signed more than 127, then value is negative ). char value = uriString[i]; if (value < 32) { throw new ArgumentException("Invalid char: " + value); } // If it is percent, then there should be 2 hex digits after. if (value == '%') { if (pathLength - i < 3) { throw new ArgumentException("No data after %"); } // There are at least 2 characters. Check their values for (int j = 1; j < 3; j++) { char nextVal = uriString[i + j]; if (!((nextVal >= '0' && nextVal <= '9') || (nextVal >= 'A' && nextVal <= 'F') || (nextVal >= 'a' && nextVal <= 'f') ) ) { throw new ArgumentException("Invalid char after %: " + value); } } // Moves i by 2 up to bypass verified characters. i += 2; } } } /// <summary> /// Internal method parses a URI string into Uri variables /// </summary> /// <param name="uriString">A Uri.</param> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="uriString"/> is null. /// </exception> /// <exception cref="System.Exception"> /// See constructor description. /// </exception> protected void ParseUriString(string uriString) { int startIndex = 0; int endIndex = 0; // Check for null or empty string. if (uriString == null || uriString.Length == 0) { throw new ArgumentNullException(); } uriString = uriString.Trim(); // Check for presence of ':'. Colon always should be present in URI. if (uriString.IndexOf(':') == -1) { throw new ArgumentException(); } string uriStringLower = uriString.ToLower(); // If this is a urn parse and return if(uriStringLower.IndexOf( "urn:", startIndex ) == 0) { ValidateUrn( uriString ); return; } // If the uri is a relative path parse and return if(uriString[0] == '/') { ValidateRelativePath(uriString); return; } // Validate Scheme endIndex = uriString.IndexOf(':'); m_scheme = uriString.Substring(0, endIndex); if (!IsAlpha(m_scheme[0])) { throw new ArgumentException(); } for (int i = 1; i < m_scheme.Length; ++i) { if (!(IsAlphaNumeric(m_scheme[i]) || m_scheme[i] == '+' || m_scheme[i] == '-' || m_scheme[i] == '.')) { throw new ArgumentException(); } } // Get past the colon startIndex = endIndex + 1; if (startIndex >= uriString.Length) { throw new ArgumentException(); } // Get host, port and absolute path bool bRooted = ParseSchemeSpecificPart(uriString, startIndex); if ((m_scheme == "file" || m_scheme == "mailto") && m_host.Length == 0) { m_hostNameType = UriHostNameType.Basic; } else if (m_host.Length == 0) { m_hostNameType = UriHostNameType.Unknown; } else if (m_host[0] == '[') { if (!IsIPv6(m_host)) { throw new ArgumentException(); } m_hostNameType = UriHostNameType.IPv6; } else if (IsIPv4(m_host)) { m_hostNameType = UriHostNameType.IPv4; } else { m_hostNameType = UriHostNameType.Dns; } if (m_host != null) { if (m_host == "localhost" || m_host == "loopback" || (m_scheme == "file" || m_scheme == "mailto") && m_host.Length == 0) { m_Flags |= m_Flags | (int)Flags.LoopbackHost; } } m_absoluteUri = m_scheme + ":" + (bRooted ? "//" : string.Empty) + m_host + ((DefaultPort(m_scheme) == m_port) ? string.Empty : ":" + m_port.ToString()) + (m_scheme == "file" && m_AbsolutePath.Length >= 2 && IsAlpha(m_AbsolutePath[0]) && m_AbsolutePath[1] == ':' ? "/" : string.Empty) + m_AbsolutePath; m_isAbsoluteUri = true; m_isUnc = m_scheme == "file" && m_host.Length > 0; } /// <summary> /// Parse Scheme-specific part of uri for host, port and absolute path /// Briefed syntax abstracted from .NET FX: /// Group 1 - http, https, ftp, file, gopher, nntp, telnet, ldap, net.tcp and net.pipe /// Must be rooted. The 1st segment is authority. Empty path should be replace as '/' /// /// Group 2 - file /// Reminder: Treat all '\' as '/' /// If it starts with only one '/', host should be empty /// Otherwise, all leading '/' should be ignored before searching for 1st segment. The 1st segment is host /// /// Group 3 - news and uuid /// Authority always be empty. Everything goes to path. /// /// Group 4 - mailto and all other shemes /// The 1st segment is authority iff it was not rooted. /// /// Group 5 - all other schemes /// The 1st segment is authority iff it was rooted. Empty path should be replace as '/' /// </summary> /// <param name="sInput">Scheme-specific part of uri</param> protected bool ParseSchemeSpecificPart(string sUri, int iStart) { bool bRooted = sUri.Length >= iStart + 2 && sUri.Substring(iStart, 2) == "//"; bool bAbsoluteUriRooted; string sAuthority; switch (m_scheme) { case "http": case "https": case "ftp": case "gopher": case "nntp": case "telnet": case "ldap": case "net.tcp": case "net.pipe": if (!bRooted) { throw new ArgumentException(); } bAbsoluteUriRooted = bRooted; Split(sUri, iStart + 2, out sAuthority, out m_AbsolutePath, true); break; case "file": if (!bRooted) { throw new ArgumentException(); } sUri = sUri.Substring(iStart + 2); if (sUri.Length > 0) { var array = sUri.ToCharArray(); for (int i = 0; i < array.Length; i++) { if (array[i] == '\\') { array[i] = '/'; } } sUri = new string(array); } string sTrimmed = sUri.TrimStart('/'); if (sTrimmed.Length >= 2 && IsAlpha(sTrimmed[0]) && sTrimmed[1] == ':') { //Windows style path if (sTrimmed.Length < 3 || sTrimmed[2] != '/') { throw new ArgumentException(); } sAuthority = string.Empty; m_AbsolutePath = sTrimmed; } else { //Unix style path if (sUri.Length - sTrimmed.Length == 1 || sTrimmed.Length == 0) { sAuthority = string.Empty; m_AbsolutePath = sUri.Length > 0 ? sUri : "/"; } else { Split(sTrimmed, 0, out sAuthority, out m_AbsolutePath, true); } } bAbsoluteUriRooted = bRooted; break; case "news": case "uuid": sAuthority = string.Empty; m_AbsolutePath = sUri.Substring(iStart); bAbsoluteUriRooted = false; break; case "mailto": if (bRooted) { sAuthority = string.Empty; m_AbsolutePath = sUri.Substring(iStart); } else { Split(sUri, iStart, out sAuthority, out m_AbsolutePath, false); } bAbsoluteUriRooted = false; break; default: if (bRooted) { Split(sUri, iStart + 2, out sAuthority, out m_AbsolutePath, true); } else { sAuthority = string.Empty; m_AbsolutePath = sUri.Substring(iStart); } bAbsoluteUriRooted = bRooted; break; } int iPortSplitter = sAuthority.LastIndexOf(':'); if (iPortSplitter < 0 || sAuthority.LastIndexOf(']') > iPortSplitter) { m_host = sAuthority; m_port = DefaultPort(m_scheme); } else { m_host = sAuthority.Substring(0, iPortSplitter); m_port = Convert.ToInt32(sAuthority.Substring(iPortSplitter + 1)); } return bAbsoluteUriRooted; } protected void Split(string sUri, int iStart, out string sAuthority, out string sPath, bool bReplaceEmptyPath) { int iSplitter = sUri.IndexOf('/', iStart); if (iSplitter < 0) { sAuthority = sUri.Substring(iStart); sPath = string.Empty; } else { sAuthority = sUri.Substring(iStart, iSplitter - iStart); sPath = sUri.Substring(iSplitter); } if (bReplaceEmptyPath && sPath.Length == 0) { sPath = "/"; } } /// <summary> /// Returns if host name is IP adress 4 bytes. Like 192.1.1.1 /// </summary> /// <param name="host">string with host name</param> /// <returns>True if name is string with IPv4 address</returns> protected bool IsIPv4(String host) { int dots = 0; int number = 0; bool haveNumber = false; int length = host.Length; for (int i = 0; i < length; i++) { char ch = host[i]; if (ch <= '9' && ch >= '0') { haveNumber = true; number = number * 10 + (host[i] - '0'); if (number > 255) { return false; } } else if (ch == '.') { if (!haveNumber) { return false; } ++dots; haveNumber = false; number = 0; } else { return false; } } return (dots == 3) && haveNumber; } protected bool IsIPv6(string host) { return host[0] == '[' && host[host.Length - 1] == ']'; } /// <summary> /// Parses urn string into Uri variables. /// Parsing is restricted to basic urn:NamespaceID, urn:uuid formats only. /// </summary> /// <param name="uri">A Uri.</param> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="uri"/> is null. /// </exception> /// <exception cref="System.Exception"> /// See the constructor description. /// </exception> protected void ValidateUrn(string uri) { bool invalidUrn = false; // If this is a urn:uuid validate the uuid if (uri.ToLower().IndexOf("urn:uuid:", 0) == 0) { char[] tempUUID = uri.Substring(9).ToLower().ToCharArray(); int length = tempUUID.Length; int uuidSegmentCount = 0; int[] delimiterIndexes = { 8, 13, 18, 23 }; for (int i = 0; i < length; ++i) { // Make sure these are valid hex numbers numbers if (!IsHex(tempUUID[i]) && tempUUID[i] != '-') { invalidUrn = true; break; } else { // Check each segment length if (tempUUID[i] == '-') { if (uuidSegmentCount > 3) { invalidUrn = true; break; } if (i != delimiterIndexes[uuidSegmentCount]) { invalidUrn = true; break; } ++uuidSegmentCount; } } } m_AbsolutePath = uri.Substring(4); } // Else validate against RFC2141 else { string lowerUrn = uri.Substring(4).ToLower(); char[] tempUrn = lowerUrn.ToCharArray(); // Validate the NamespaceID (NID) int index = lowerUrn.IndexOf(':'); if (index == -1) throw new ArgumentException(); int i = 0; for (i = 0; i < index; ++i) { // Make sure these are valid hex numbers numbers if (!IsAlphaNumeric(tempUrn[i]) && tempUrn[i] != '-') { invalidUrn = true; break; } } // Validate the Namespace String tempUrn = lowerUrn.Substring(index + 1).ToCharArray(); int urnLength = tempUrn.Length; if (!invalidUrn && urnLength != 0) { string otherChars = "()+,-.:=@;$_!*'"; for (i = 0; i < urnLength; ++i) { if (!IsAlphaNumeric(tempUrn[i]) && !IsHex(tempUrn[i]) && tempUrn[i] != '%' && otherChars.IndexOf(tempUrn[i]) == -1) { invalidUrn = true; break; } } m_AbsolutePath = uri.Substring(4); } } if (invalidUrn) throw new ArgumentNullException(); // Set Uri properties m_host = ""; m_isAbsoluteUri = true; m_isUnc = false; m_hostNameType = UriHostNameType.Unknown; m_port = UnknownPort; m_scheme = "urn"; m_absoluteUri = uri; return; } /// <summary> /// Parses relative Uri into variables. /// </summary> /// <param name="uri">A Uri.</param> /// <exception cref="System.ArgumentNullException"> /// The <paramref name="uri"/> is null. /// </exception> /// <exception cref="System.Exception"> /// See constructor description. /// </exception> protected void ValidateRelativePath(string uri) { // Check for null if (uri == null || uri.Length == 0) throw new ArgumentNullException(); // Check for "//" if (uri[1] == '/') throw new ArgumentException(); // Check for alphnumeric and special characters for (int i = 1; i < uri.Length; ++i) if (!IsAlphaNumeric(uri[i]) && ("()+,-.:=@;$_!*'").IndexOf(uri[i]) == -1) throw new ArgumentException(); m_AbsolutePath = uri.Substring(1); m_host = ""; m_isAbsoluteUri = false; m_isUnc = false; m_hostNameType = UriHostNameType.Unknown; m_port = UnknownPort; } public override int GetHashCode() { return base.GetHashCode(); } public override bool Equals(object o) { return this == (Uri)o; } public static bool operator ==(Uri lhs, Uri rhs) { object l = lhs, r = rhs; if (l == null) { return (r == null); } else if (r == null) { return false; } else { if (lhs.m_isAbsoluteUri && rhs.m_isAbsoluteUri) { return lhs.m_AbsolutePath.ToLower() == rhs.m_AbsolutePath.ToLower(); } else { return lhs.m_OriginalUriString.ToLower() == rhs.m_OriginalUriString.ToLower(); } } } public static bool operator !=(Uri lhs, Uri rhs) { object l = lhs, r = rhs; if (l == null) { return (r != null); } else if (r == null) { return true; } else { if (lhs.m_isAbsoluteUri && rhs.m_isAbsoluteUri) { return lhs.m_AbsolutePath.ToLower() != rhs.m_AbsolutePath.ToLower(); } else { return lhs.m_OriginalUriString.ToLower() != rhs.m_OriginalUriString.ToLower(); } } } /// <summary> /// Checks to see if the character value is an alpha character. /// </summary> /// <param name="testChar">The character to evaluate.</param> /// <returns><itemref>true</itemref> if the character is Alpha; /// otherwise, <itemref>false</itemref>.</returns> protected bool IsAlpha(char testChar) { return (testChar >= 'A' && testChar <= 'Z') || (testChar >= 'a' && testChar <= 'z'); } /// <summary> /// Checks to see if the character value is an alpha or numeric. /// </summary> /// <param name="testChar">The character to evaluate.</param> /// <returns><itemref>true</itemref> if the character is Alpha or /// numeric; otherwise, <itemref>false</itemref>.</returns> protected bool IsAlphaNumeric(char testChar) { return (testChar >= 'A' && testChar <= 'Z') || (testChar >= 'a' && testChar <= 'z') || (testChar >= '0' && testChar <= '9'); } /// <summary> /// Checks to see if the character value is Hex. /// </summary> /// <param name="testChar">The character to evaluate.</param> /// <returns><itemref>true</itemref> if the character is a valid Hex /// character; otherwise, <itemref>false</itemref>.</returns> protected bool IsHex(char testChar) { return (testChar >= 'A' && testChar <= 'F') || (testChar >= 'a' && testChar <= 'f') || (testChar >= '0' && testChar <= '9'); } /// <summary> /// Gets the type of the host name specified in the URI. /// </summary> /// <value>A member of the <see cref="System.UriHostNameType"/> /// enumeration.</value> public UriHostNameType HostNameType { get { return m_hostNameType; } } /// <summary> /// Gets the port number of this URI. /// </summary> /// <value>An <itemref>Int32</itemref> value containing the port number /// for this URI.</value> /// <exception cref="System.InvalidOperationException"> /// This instance represents a relative URI, and this property is valid /// only for absolute URIs. /// </exception> public int Port { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_port; } } /// <summary> /// Gets whether the <see cref="System.Uri"/> instance is absolute. /// </summary> /// <value><itemref>true</itemref> if the <itemref>Uri</itemref> /// instance is absolute; otherwise, <itemref>false</itemref>.</value> public bool IsAbsoluteUri { get { return m_isAbsoluteUri; } } /// <summary> /// Gets whether the specified <see cref="System.Uri"/> is a universal /// naming convention (UNC) path. /// </summary> /// <value><itemref>true</itemref> if the <see cref="System.Uri"/> is a /// UNC path; otherwise, <itemref>false</itemref>.</value> /// <exception cref="System.InvalidOperationException"> /// This instance represents a relative URI, and this property is valid /// only for absolute URIs. /// </exception> public bool IsUnc { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_isUnc; } } /// <summary> /// Gets a local operating-system representation of a file name. /// </summary> /// <value>A <itemref>String</itemref> containing the local /// operating-system representation of a file name.</value> /// <exception cref="System.InvalidOperationException"> /// This instance represents a relative URI, and this property is valid /// only for absolute URIs. /// </exception> public string AbsolutePath { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_AbsolutePath; } } /// <summary> /// Gets the original URI string that was passed to the Uri constructor. /// </summary> public string OriginalString { get { // The original string was saved in m_OriginalUriString. return m_OriginalUriString; } } /// <summary> /// Gets a string containing the absolute uri or entire uri of this instance. /// </summary> /// <value>A <itemref>String</itemref> containing the entire URI. /// </value> public string AbsoluteUri { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_absoluteUri; } } /// <summary> /// Gets the scheme name for this URI. /// </summary> /// <value>A <itemref>String</itemref> containing the scheme for this /// URI, converted to lowercase.</value> /// <exception cref="System.InvalidOperationException"> /// This instance represents a relative URI, and this property is valid only /// for absolute URIs. /// </exception> public string Scheme { get { if (m_isAbsoluteUri == false) throw new InvalidOperationException(); return m_scheme; } } /// <summary> /// Gets the host component of this instance. /// </summary> /// <value>A <itemref>String</itemref> containing the host name. This /// is usually the DNS host name or IP address of the server.</value> public string Host { get { return m_host; } } /// <summary> /// Gets whether the specified <see cref="System.Uri"/> refers to the /// local host. /// </summary> /// <value><itemref>true</itemref> if the host specified in the Uri is /// the local computer; otherwise, <itemref>false</itemref>.</value> public bool IsLoopback { get { return (m_Flags & (int)Flags.LoopbackHost) != 0; } } /// <summary> /// Indicates whether the string is well-formed by attempting to /// construct a URI with the string. /// </summary> /// <param name="uriString">A URI.</param> /// <param name="uriKind">The type of the URI in /// <paramref name="uriString"/>.</param> /// <returns> /// <itemref>true</itemref> if the string was well-formed in accordance /// with RFC 2396 and RFC 2732; otherwise <itemref>false</itemref>. /// </returns> public static bool IsWellFormedUriString(string uriString, UriKind uriKind) { try { // If absolute Uri was passed - create Uri object. switch (uriKind) { case UriKind.Absolute: { Uri testUri = new Uri(uriString); if (testUri.IsAbsoluteUri) { return true; } return false; } case UriKind.Relative: { Uri testUri = new Uri(uriString, UriKind.Relative); if (!testUri.IsAbsoluteUri) { return true; } return false; } default: return false; } } catch { return false; } } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoad.Business.ERLevel { /// <summary> /// C02_Continent (editable root object).<br/> /// This is a generated base class of <see cref="C02_Continent"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="C03_SubContinentObjects"/> of type <see cref="C03_SubContinentColl"/> (1:M relation to <see cref="C04_SubContinent"/>) /// </remarks> [Serializable] public partial class C02_Continent : BusinessBase<C02_Continent> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID"); /// <summary> /// Gets the Continents ID. /// </summary> /// <value>The Continents ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name"); /// <summary> /// Gets or sets the Continents Name. /// </summary> /// <value>The Continents Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } set { SetProperty(Continent_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<C03_Continent_Child> C03_Continent_SingleObjectProperty = RegisterProperty<C03_Continent_Child>(p => p.C03_Continent_SingleObject, "C03 Continent Single Object", RelationshipTypes.Child); /// <summary> /// Gets the C03 Continent Single Object ("self load" child property). /// </summary> /// <value>The C03 Continent Single Object.</value> public C03_Continent_Child C03_Continent_SingleObject { get { return GetProperty(C03_Continent_SingleObjectProperty); } private set { LoadProperty(C03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<C03_Continent_ReChild> C03_Continent_ASingleObjectProperty = RegisterProperty<C03_Continent_ReChild>(p => p.C03_Continent_ASingleObject, "C03 Continent ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the C03 Continent ASingle Object ("self load" child property). /// </summary> /// <value>The C03 Continent ASingle Object.</value> public C03_Continent_ReChild C03_Continent_ASingleObject { get { return GetProperty(C03_Continent_ASingleObjectProperty); } private set { LoadProperty(C03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<C03_SubContinentColl> C03_SubContinentObjectsProperty = RegisterProperty<C03_SubContinentColl>(p => p.C03_SubContinentObjects, "C03 SubContinent Objects", RelationshipTypes.Child); /// <summary> /// Gets the C03 Sub Continent Objects ("self load" child property). /// </summary> /// <value>The C03 Sub Continent Objects.</value> public C03_SubContinentColl C03_SubContinentObjects { get { return GetProperty(C03_SubContinentObjectsProperty); } private set { LoadProperty(C03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C02_Continent"/> object. /// </summary> /// <returns>A reference to the created <see cref="C02_Continent"/> object.</returns> public static C02_Continent NewC02_Continent() { return DataPortal.Create<C02_Continent>(); } /// <summary> /// Factory method. Loads a <see cref="C02_Continent"/> object, based on given parameters. /// </summary> /// <param name="continent_ID">The Continent_ID parameter of the C02_Continent to fetch.</param> /// <returns>A reference to the fetched <see cref="C02_Continent"/> object.</returns> public static C02_Continent GetC02_Continent(int continent_ID) { return DataPortal.Fetch<C02_Continent>(continent_ID); } /// <summary> /// Factory method. Deletes a <see cref="C02_Continent"/> object, based on given parameters. /// </summary> /// <param name="continent_ID">The Continent_ID of the C02_Continent to delete.</param> public static void DeleteC02_Continent(int continent_ID) { DataPortal.Delete<C02_Continent>(continent_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C02_Continent() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="C02_Continent"/> object properties. /// </summary> [Csla.RunLocal] protected override void DataPortal_Create() { LoadProperty(Continent_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(C03_Continent_SingleObjectProperty, DataPortal.CreateChild<C03_Continent_Child>()); LoadProperty(C03_Continent_ASingleObjectProperty, DataPortal.CreateChild<C03_Continent_ReChild>()); LoadProperty(C03_SubContinentObjectsProperty, DataPortal.CreateChild<C03_SubContinentColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="C02_Continent"/> object from the database, based on given criteria. /// </summary> /// <param name="continent_ID">The Continent ID.</param> protected void DataPortal_Fetch(int continent_ID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetC02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", continent_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, continent_ID); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } FetchChildren(); // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID")); LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> private void FetchChildren() { LoadProperty(C03_Continent_SingleObjectProperty, C03_Continent_Child.GetC03_Continent_Child(Continent_ID)); LoadProperty(C03_Continent_ASingleObjectProperty, C03_Continent_ReChild.GetC03_Continent_ReChild(Continent_ID)); LoadProperty(C03_SubContinentObjectsProperty, C03_SubContinentColl.GetC03_SubContinentColl(Continent_ID)); } /// <summary> /// Inserts a new <see cref="C02_Continent"/> object in the database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Insert() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddC02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(Continent_IDProperty, (int) cmd.Parameters["@Continent_ID"].Value); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="C02_Continent"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] protected override void DataPortal_Update() { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateC02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", ReadProperty(Continent_IDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Continent_Name", ReadProperty(Continent_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="C02_Continent"/> object. /// </summary> protected override void DataPortal_DeleteSelf() { DataPortal_Delete(Continent_ID); } /// <summary> /// Deletes the <see cref="C02_Continent"/> object from database. /// </summary> /// <param name="continent_ID">The delete criteria.</param> [Transactional(TransactionalTypes.TransactionScope)] protected void DataPortal_Delete(int continent_ID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { // flushes all pending data operations FieldManager.UpdateChildren(this); using (var cmd = new SqlCommand("DeleteC02_Continent", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Continent_ID", continent_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, continent_ID); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } // removes all previous references to children LoadProperty(C03_Continent_SingleObjectProperty, DataPortal.CreateChild<C03_Continent_Child>()); LoadProperty(C03_Continent_ASingleObjectProperty, DataPortal.CreateChild<C03_Continent_ReChild>()); LoadProperty(C03_SubContinentObjectsProperty, DataPortal.CreateChild<C03_SubContinentColl>()); } #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 } }
namespace Fixtures.Azure.SwaggerBatPaging { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Azure; using Models; public static partial class PagingOperationsExtensions { /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static ProductResult GetSinglePages(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetSinglePagesAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetSinglePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static ProductResult GetMultiplePages(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static ProductResult GetMultiplePagesRetryFirst(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesRetryFirstAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesRetryFirstWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static ProductResult GetMultiplePagesRetrySecond(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesRetrySecondAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesRetrySecondWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static ProductResult GetSinglePagesFailure(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetSinglePagesFailureAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetSinglePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static ProductResult GetMultiplePagesFailure(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesFailureAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static ProductResult GetMultiplePagesFailureUri(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesFailureUriAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesFailureUriWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> public static ProductResult GetSinglePagesNext(this IPagingOperations operations, string nextLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesNextAsync(nextLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetSinglePagesNextAsync( this IPagingOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetSinglePagesNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> public static ProductResult GetMultiplePagesNext(this IPagingOperations operations, string nextLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesNextAsync(nextLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesNextAsync( this IPagingOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> public static ProductResult GetMultiplePagesRetryFirstNext(this IPagingOperations operations, string nextLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstNextAsync(nextLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesRetryFirstNextAsync( this IPagingOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> public static ProductResult GetMultiplePagesRetrySecondNext(this IPagingOperations operations, string nextLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondNextAsync(nextLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesRetrySecondNextAsync( this IPagingOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> public static ProductResult GetSinglePagesFailureNext(this IPagingOperations operations, string nextLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureNextAsync(nextLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetSinglePagesFailureNextAsync( this IPagingOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetSinglePagesFailureNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> public static ProductResult GetMultiplePagesFailureNext(this IPagingOperations operations, string nextLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureNextAsync(nextLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesFailureNextAsync( this IPagingOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesFailureNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> public static ProductResult GetMultiplePagesFailureUriNext(this IPagingOperations operations, string nextLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriNextAsync(nextLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='nextLink'> /// NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<ProductResult> GetMultiplePagesFailureUriNextAsync( this IPagingOperations operations, string nextLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<ProductResult> result = await operations.GetMultiplePagesFailureUriNextWithHttpMessagesAsync(nextLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // QueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// This is the abstract base class for all query operators in the system. It /// implements the ParallelQuery{T} type so that it can be bound as the source /// of parallel queries and so that it can be returned as the result of parallel query /// operations. Not much is in here, although it does serve as the "entry point" for /// opening all query operators: it will lazily analyze and cache a plan the first /// time the tree is opened, and will open the tree upon calls to GetEnumerator. /// /// Notes: /// This class implements ParallelQuery so that any parallel query operator /// can bind to the parallel query provider overloads. This allows us to string /// together operators w/out the user always specifying AsParallel, e.g. /// Select(Where(..., ...), ...), and so forth. /// </summary> /// <typeparam name="TOutput"></typeparam> internal abstract class QueryOperator<TOutput> : ParallelQuery<TOutput> { protected bool _outputOrdered; internal QueryOperator(QuerySettings settings) : this(false, settings) { } internal QueryOperator(bool isOrdered, QuerySettings settings) : base(settings) { _outputOrdered = isOrdered; } //--------------------------------------------------------------------------------------- // Opening the query operator will do whatever is necessary to begin enumerating its // results. This includes in some cases actually introducing parallelism, enumerating // other query operators, and so on. This is abstract and left to the specific concrete // operator classes to implement. // // Arguments: // settings - various flags and settings to control query execution // preferStriping - flag representing whether the caller prefers striped partitioning // over range partitioning // // Return Values: // Either a single enumerator, or a partition (for partition parallelism). // internal abstract QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping); //--------------------------------------------------------------------------------------- // The GetEnumerator method is the standard IEnumerable mechanism for walking the // contents of a query. Note that GetEnumerator is only ever called on the root node: // we then proceed by calling Open on all of the subsequent query nodes. // // Arguments: // usePipelining - whether the returned enumerator will pipeline (i.e. return // control to the caller when the query is spawned) or not // (i.e. use the calling thread to execute the query). Note // that there are some conditions during which this hint will // be ignored -- currently, that happens only if a sort is // found anywhere in the query graph. // suppressOrderPreservation - whether to shut order preservation off, regardless // of the contents of the query // // Return Value: // An enumerator that retrieves elements from the query output. // // Notes: // The default mode of execution is to pipeline the query execution with respect // to the GetEnumerator caller (aka the consumer). An overload is available // that can be used to override the default with an explicit choice. // public override IEnumerator<TOutput> GetEnumerator() { // Buffering is unspecified and order preservation is not suppressed. return GetEnumerator(null, false); } public IEnumerator<TOutput> GetEnumerator(ParallelMergeOptions? mergeOptions) { // Pass through the value supplied for pipelining, and do not suppress // order preservation by default. return GetEnumerator(mergeOptions, false); } //--------------------------------------------------------------------------------------- // Is the output of this operator ordered? // internal bool OutputOrdered { get { return _outputOrdered; } } internal virtual IEnumerator<TOutput> GetEnumerator(ParallelMergeOptions? mergeOptions, bool suppressOrderPreservation) { // Return a dummy enumerator that will call back GetOpenedEnumerator() on 'this' QueryOperator // the first time the user calls MoveNext(). We do this to prevent executing the query if user // never calls MoveNext(). return new QueryOpeningEnumerator<TOutput>(this, mergeOptions, suppressOrderPreservation); } //--------------------------------------------------------------------------------------- // The GetOpenedEnumerator method return an enumerator that walks the contents of a query. // The enumerator will be "opened", which means that PLINQ will start executing the query // immediately, even before the user calls MoveNext() for the first time. // internal IEnumerator<TOutput>? GetOpenedEnumerator(ParallelMergeOptions? mergeOptions, bool suppressOrder, bool forEffect, QuerySettings querySettings) { Debug.Assert(querySettings.ExecutionMode != null); // If the top-level enumerator forces a premature merge, run the query sequentially. if (querySettings.ExecutionMode.Value == ParallelExecutionMode.Default && LimitsParallelism) { IEnumerable<TOutput> opSequential = AsSequentialQuery(querySettings.CancellationState.ExternalCancellationToken); return ExceptionAggregator.WrapEnumerable(opSequential, querySettings.CancellationState).GetEnumerator(); } QueryResults<TOutput> queryResults = GetQueryResults(querySettings); if (mergeOptions == null) { mergeOptions = querySettings.MergeOptions; } Debug.Assert(mergeOptions != null); // Top-level preemptive cancellation test. // This handles situations where cancellation has occurred before execution commences // The handling for in-execution occurs in QueryTaskGroupState.QueryEnd() if (querySettings.CancellationState.MergedCancellationToken.IsCancellationRequested) { if (querySettings.CancellationState.ExternalCancellationToken.IsCancellationRequested) throw new OperationCanceledException(querySettings.CancellationState.ExternalCancellationToken); else throw new OperationCanceledException(); } bool orderedMerge = OutputOrdered && !suppressOrder; Debug.Assert(querySettings.TaskScheduler != null); PartitionedStreamMerger<TOutput> merger = new PartitionedStreamMerger<TOutput>(forEffect, mergeOptions.GetValueOrDefault(), querySettings.TaskScheduler, orderedMerge, querySettings.CancellationState, querySettings.QueryId); queryResults.GivePartitionedStream(merger); // hook up the data flow between the operator-executors, starting from the merger. if (forEffect) { return null; } Debug.Assert(merger.MergeExecutor != null); return merger.MergeExecutor.GetEnumerator(); } // This method is called only once on the 'head operator' which is the last specified operator in the query // This method then recursively uses Open() to prepare itself and the other enumerators. private QueryResults<TOutput> GetQueryResults(QuerySettings querySettings) { TraceHelpers.TraceInfo("[timing]: {0}: starting execution - QueryOperator<>::GetQueryResults", DateTime.Now.Ticks); // All mandatory query settings must be specified Debug.Assert(querySettings.TaskScheduler != null); Debug.Assert(querySettings.DegreeOfParallelism.HasValue); Debug.Assert(querySettings.ExecutionMode.HasValue); // Now just open the query tree's root operator, supplying a specific DOP return Open(querySettings, false); } //--------------------------------------------------------------------------------------- // Executes the query and returns the results in an array. // internal TOutput[] ExecuteAndGetResultsAsArray() { QuerySettings querySettings = SpecifiedQuerySettings .WithPerExecutionSettings() .WithDefaults(); QueryLifecycle.LogicalQueryExecutionBegin(querySettings.QueryId); try { Debug.Assert(querySettings.ExecutionMode != null); if (querySettings.ExecutionMode.Value == ParallelExecutionMode.Default && LimitsParallelism) { IEnumerable<TOutput> opSequential = AsSequentialQuery(querySettings.CancellationState.ExternalCancellationToken); IEnumerable<TOutput> opSequentialWithCancelChecks = CancellableEnumerable.Wrap(opSequential, querySettings.CancellationState.ExternalCancellationToken); return ExceptionAggregator.WrapEnumerable(opSequentialWithCancelChecks, querySettings.CancellationState).ToArray(); } QueryResults<TOutput> results = GetQueryResults(querySettings); // Top-level preemptive cancellation test. // This handles situations where cancellation has occurred before execution commences // The handling for in-execution occurs in QueryTaskGroupState.QueryEnd() if (querySettings.CancellationState.MergedCancellationToken.IsCancellationRequested) { if (querySettings.CancellationState.ExternalCancellationToken.IsCancellationRequested) throw new OperationCanceledException(querySettings.CancellationState.ExternalCancellationToken); else throw new OperationCanceledException(); } if (results.IsIndexible && OutputOrdered) { // The special array-based merge performs better if the output is ordered, because // it does not have to pay for ordering. In the unordered case, we it appears that // the stop-and-go merge performs a little better. ArrayMergeHelper<TOutput> merger = new ArrayMergeHelper<TOutput>(SpecifiedQuerySettings, results); merger.Execute(); TOutput[] output = merger.GetResultsAsArray(); querySettings.CleanStateAtQueryEnd(); return output; } else { Debug.Assert(querySettings.TaskScheduler != null); PartitionedStreamMerger<TOutput> merger = new PartitionedStreamMerger<TOutput>(false, ParallelMergeOptions.FullyBuffered, querySettings.TaskScheduler, OutputOrdered, querySettings.CancellationState, querySettings.QueryId); results.GivePartitionedStream(merger); Debug.Assert(merger.MergeExecutor != null); TOutput[]? output = merger.MergeExecutor.GetResultsAsArray(); querySettings.CleanStateAtQueryEnd(); Debug.Assert(output != null); return output; } } finally { QueryLifecycle.LogicalQueryExecutionEnd(querySettings.QueryId); } } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // // Note that iterating the returned enumerable will not wrap exceptions AggregateException. // Before this enumerable is returned to the user, we must wrap it with an // ExceptionAggregator. // internal abstract IEnumerable<TOutput> AsSequentialQuery(CancellationToken token); //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge. // internal abstract bool LimitsParallelism { get; } //--------------------------------------------------------------------------------------- // The state of the order index of the results returned by this operator. // internal abstract OrdinalIndexState OrdinalIndexState { get; } //--------------------------------------------------------------------------------------- // A helper method that executes the query rooted at the openedChild operator, and returns // the results as ListQueryResults<TSource>. // internal static ListQueryResults<TOutput> ExecuteAndCollectResults<TKey>( PartitionedStream<TOutput, TKey> openedChild, int partitionCount, bool outputOrdered, bool useStriping, QuerySettings settings) { TaskScheduler? taskScheduler = settings.TaskScheduler; Debug.Assert(taskScheduler != null); MergeExecutor<TOutput> executor = MergeExecutor<TOutput>.Execute<TKey>( openedChild, false, ParallelMergeOptions.FullyBuffered, taskScheduler, outputOrdered, settings.CancellationState, settings.QueryId); return new ListQueryResults<TOutput>(executor.GetResultsAsArray()!, partitionCount, useStriping); } //--------------------------------------------------------------------------------------- // Returns a QueryOperator<T> for any IEnumerable<T> data source. This will just do a // cast and return a reference to the same data source if the source is another query // operator, but will lazily allocate a scan operation and return that otherwise. // // Arguments: // source - any enumerable data source to be wrapped // // Return Value: // A query operator. // internal static QueryOperator<TOutput> AsQueryOperator(IEnumerable<TOutput> source) { Debug.Assert(source != null); // Just try casting the data source to a query operator, in the case that // our child is just another query operator. QueryOperator<TOutput>? sourceAsOperator = source as QueryOperator<TOutput>; if (sourceAsOperator == null) { if (source is OrderedParallelQuery<TOutput> orderedQuery) { // We have to handle OrderedParallelQuery<T> specially. In all other cases, // ParallelQuery *is* the QueryOperator<T>. But, OrderedParallelQuery<T> // is not QueryOperator<T>, it only has a reference to one. Ideally, we // would want SortQueryOperator<T> to inherit from OrderedParallelQuery<T>, // but that conflicts with other constraints on our class hierarchy. sourceAsOperator = (QueryOperator<TOutput>)orderedQuery.SortOperator; } else { // If the cast failed, then the data source is a real piece of data. We // just construct a new scan operator on top of it. sourceAsOperator = new ScanQueryOperator<TOutput>(source); } } Debug.Assert(sourceAsOperator != null); return sourceAsOperator; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Hosting; using System.Linq; using System.Reflection; using Xunit; namespace System.ComponentModel.Composition.Registration.Tests { public class PartBuilderTests { private class MyDoNotIncludeAttribute : Attribute { } [MyDoNotIncludeAttribute] public class MyNotToBeIncludedClass { } public class MyToBeIncludedClass { } public class ImporterOfMyNotTobeIncludedClass { [Import(AllowDefault = true)] public MyNotToBeIncludedClass MyNotToBeIncludedClass; [Import(AllowDefault = true)] public MyToBeIncludedClass MyToBeIncludedClass; } public interface IFirst { } private interface IFoo { } private class FooImpl { public string P1 { get; set; } public string P2 { get; set; } public IEnumerable<IFoo> P3 { get; set; } } private class FooImplWithConstructors { public FooImplWithConstructors() { } public FooImplWithConstructors(IEnumerable<IFoo> ids) { } public FooImplWithConstructors(int id, string name) { } } private class FooImplWithConstructorsAmbiguous { public FooImplWithConstructorsAmbiguous(string name, int id) { } public FooImplWithConstructorsAmbiguous(int id, string name) { } } [Fact] public void NoOperations_ShouldGenerateNoAttributes() { var builder = new PartBuilder(t => true); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(0, typeAtts.Count()); Assert.Equal(0, configuredMembers.Count); } [Fact] public void ExportSelf_ShouldGenerateSingleExportAttribute() { var builder = new PartBuilder(t => true); builder.Export(); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(1, typeAtts.Count()); Assert.Equal(0, configuredMembers.Count); Assert.Same(typeof(ExportAttribute), typeAtts.ElementAt(0).GetType()); Assert.Null((typeAtts.ElementAt(0) as ExportAttribute).ContractType); Assert.Null((typeAtts.ElementAt(0) as ExportAttribute).ContractName); } [Fact] public void ExportOfT_ShouldGenerateSingleExportAttributeWithContractType() { var builder = new PartBuilder(t => true); builder.Export<IFoo>(); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(1, typeAtts.Count()); Assert.Equal(0, configuredMembers.Count); Assert.Same(typeof(ExportAttribute), typeAtts.ElementAt(0).GetType()); Assert.Equal(typeof(IFoo), (typeAtts.ElementAt(0) as ExportAttribute).ContractType); Assert.Null((typeAtts.ElementAt(0) as ExportAttribute).ContractName); } [Fact] public void AddMetadata_ShouldGeneratePartMetadataAttribute() { var builder = new PartBuilder(t => true); builder.Export<IFoo>().AddMetadata("name", "value"); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(2, typeAtts.Count()); Assert.Equal(0, configuredMembers.Count); Assert.Same(typeof(ExportAttribute), typeAtts.ElementAt(0).GetType()); Assert.True(typeAtts.ElementAt(0) is ExportAttribute); Assert.True(typeAtts.ElementAt(1) is PartMetadataAttribute); var metadataAtt = typeAtts.ElementAt(1) as PartMetadataAttribute; Assert.Equal("name", metadataAtt.Name); Assert.Equal("value", metadataAtt.Value); } [Fact] public void AddMetadataWithFunc_ShouldGeneratePartMetadataAttribute() { var builder = new PartBuilder(t => true); builder.Export<IFoo>().AddMetadata("name", t => t.Name); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(2, typeAtts.Count()); Assert.Equal(0, configuredMembers.Count); Assert.Same(typeof(ExportAttribute), typeAtts.ElementAt(0).GetType()); Assert.True(typeAtts.ElementAt(0) is ExportAttribute); Assert.True(typeAtts.ElementAt(1) is PartMetadataAttribute); var metadataAtt = typeAtts.ElementAt(1) as PartMetadataAttribute; Assert.Equal("name", metadataAtt.Name); Assert.Equal(typeof(FooImpl).Name, metadataAtt.Value); } [Fact] public void ExportProperty_ShouldGenerateExportForPropertySelected() { var builder = new PartBuilder(t => true); builder.Export<IFoo>(). ExportProperties(p => p.Name == "P1"); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(1, typeAtts.Count()); Assert.Equal(1, configuredMembers.Count); Tuple<object, List<Attribute>> tuple = configuredMembers[0]; Assert.Equal(typeof(FooImpl).GetProperty("P1"), tuple.Item1); List<Attribute> atts = tuple.Item2; Assert.Equal(1, atts.Count); var expAtt = atts[0] as ExportAttribute; Assert.Null(expAtt.ContractName); Assert.Null(expAtt.ContractType); } [Fact] public void ImportProperty_ShouldGenerateImportForPropertySelected() { var builder = new PartBuilder(t => true); builder.Export<IFoo>(). ImportProperties(p => p.Name == "P2"); // P3 is string IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(1, typeAtts.Count()); Assert.Equal(1, configuredMembers.Count); Tuple<object, List<Attribute>> tuple = configuredMembers[0]; Assert.Equal(typeof(FooImpl).GetProperty("P2"), tuple.Item1); List<Attribute> atts = tuple.Item2; Assert.Equal(1, atts.Count); var importAttribute = atts[0] as ImportAttribute; Assert.NotNull(importAttribute); Assert.Null(importAttribute.ContractName); Assert.Null(importAttribute.ContractType); } [Fact] public void ImportProperties_ShouldGenerateImportForPropertySelected_And_ApplyImportMany() { var builder = new PartBuilder(t => true); builder.Export<IFoo>(). ImportProperties(p => p.Name == "P3"); // P3 is IEnumerable<IFoo> IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(1, typeAtts.Count()); Assert.Equal(1, configuredMembers.Count); Tuple<object, List<Attribute>> tuple = configuredMembers[0]; Assert.Equal(typeof(FooImpl).GetProperty("P3"), tuple.Item1); List<Attribute> atts = tuple.Item2; Assert.Equal(1, atts.Count); var importManyAttribute = atts[0] as ImportManyAttribute; Assert.NotNull(importManyAttribute); Assert.Null(importManyAttribute.ContractName); Assert.Null(importManyAttribute.ContractType); } [Fact] public void ExportPropertyWithConfiguration_ShouldGenerateExportForPropertySelected() { var builder = new PartBuilder(t => true); builder.Export<IFoo>(). ExportProperties(p => p.Name == "P1", (p, c) => c.AsContractName("hey")); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(1, typeAtts.Count()); Assert.Equal(1, configuredMembers.Count); Tuple<object, List<Attribute>> tuple = configuredMembers[0]; Assert.Equal(typeof(FooImpl).GetProperty("P1"), tuple.Item1); List<Attribute> atts = tuple.Item2; Assert.Equal(1, atts.Count); var expAtt = atts[0] as ExportAttribute; Assert.Equal("hey", expAtt.ContractName); Assert.Null(expAtt.ContractType); } [Fact] public void ExportPropertyOfT_ShouldGenerateExportForPropertySelectedWithTAsContractType() { var builder = new PartBuilder(t => true); builder.Export<IFoo>(). ExportProperties<string>(p => p.Name == "P1"); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(1, typeAtts.Count()); Assert.Equal(1, configuredMembers.Count); Tuple<object, List<Attribute>> tuple = configuredMembers[0]; Assert.Equal(typeof(FooImpl).GetProperty("P1"), tuple.Item1); List<Attribute> atts = tuple.Item2; Assert.Equal(1, atts.Count); var expAtt = atts[0] as ExportAttribute; Assert.Null(expAtt.ContractName); Assert.Equal(typeof(string), expAtt.ContractType); } [Fact] public void SetCreationPolicy_ShouldGeneratePartCreationPolicyAttributeForType() { var builder = new PartBuilder(t => true); builder.Export<IFoo>().SetCreationPolicy(CreationPolicy.NonShared); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts); Assert.Equal(2, typeAtts.Count()); Assert.Equal(0, configuredMembers.Count); var partCPAtt = (PartCreationPolicyAttribute)typeAtts.ElementAt(1); Assert.Equal(CreationPolicy.NonShared, partCPAtt.CreationPolicy); } [Fact] public void ConventionSelectsConstructor_SelectsTheOneWithMostParameters() { var builder = new PartBuilder(t => true); builder.Export<IFoo>(); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts, typeof(FooImplWithConstructors)); Assert.Equal(1, typeAtts.Count()); Assert.Equal(3, configuredMembers.Count); Tuple<object, List<Attribute>> tuple = configuredMembers[0]; // Constructor ConstructorInfo ci = typeof(FooImplWithConstructors).GetConstructors()[2]; Assert.True(tuple.Item1 is ConstructorInfo); Assert.Same(ci, tuple.Item1); Assert.Equal(1, tuple.Item2.Count); Assert.True(tuple.Item2[0] is ImportingConstructorAttribute); tuple = configuredMembers[1]; // Parameter 1 Assert.True(tuple.Item1 is ParameterInfo); Assert.Same(ci.GetParameters()[0], tuple.Item1); Assert.Equal(1, tuple.Item2.Count); Assert.True(tuple.Item2[0] is ImportAttribute); tuple = configuredMembers[2]; // Parameter 2 Assert.True(tuple.Item1 is ParameterInfo); Assert.Same(ci.GetParameters()[1], tuple.Item1); Assert.Equal(1, tuple.Item2.Count); Assert.True(tuple.Item2[0] is ImportAttribute); } [Fact] public void ManuallySelectingConstructor_SelectsTheExplicitOne() { var builder = new PartBuilder(t => true); builder.Export<IFoo>().SelectConstructor((cis) => cis[1]); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts, typeof(FooImplWithConstructors)); Assert.Equal(1, typeAtts.Count()); Assert.Equal(2, configuredMembers.Count); Tuple<object, List<Attribute>> tuple = configuredMembers[0]; // Constructor ConstructorInfo ci = typeof(FooImplWithConstructors).GetConstructors()[1]; Assert.True(tuple.Item1 is ConstructorInfo); Assert.Same(ci, tuple.Item1); Assert.Equal(1, tuple.Item2.Count); Assert.True(tuple.Item2[0] is ImportingConstructorAttribute); tuple = configuredMembers[1]; // Parameter 1 Assert.True(tuple.Item1 is ParameterInfo); Assert.Same(ci.GetParameters()[0], tuple.Item1); Assert.Equal(1, tuple.Item2.Count); } [Fact] public void ManuallySelectingConstructor_SelectsTheExplicitOne_IEnumerableParameterBecomesImportMany() { var builder = new PartBuilder(t => true); builder.Export<IFoo>().SelectConstructor((cis) => cis[1]); IEnumerable<Attribute> typeAtts; List<Tuple<object, List<Attribute>>> configuredMembers; GetConfiguredMembers(builder, out configuredMembers, out typeAtts, typeof(FooImplWithConstructors)); Assert.Equal(1, typeAtts.Count()); Assert.Equal(2, configuredMembers.Count); ConstructorInfo ci = typeof(FooImplWithConstructors).GetConstructors()[1]; Tuple<object, List<Attribute>> tuple = configuredMembers[1]; // Parameter 1 Assert.True(tuple.Item1 is ParameterInfo); Assert.Same(ci.GetParameters()[0], tuple.Item1); Assert.Equal(1, tuple.Item2.Count); Assert.Equal(typeof(ImportManyAttribute), tuple.Item2[0].GetType()); } private static void GetConfiguredMembers(PartBuilder builder, out List<Tuple<object, List<Attribute>>> configuredMembers, out IEnumerable<Attribute> typeAtts, Type targetType = null) { if (targetType == null) { targetType = typeof(FooImpl); } configuredMembers = new List<Tuple<object, List<Attribute>>>(); typeAtts = builder.BuildTypeAttributes(targetType); if (!builder.BuildConstructorAttributes(targetType, ref configuredMembers)) { PartBuilder.BuildDefaultConstructorAttributes(targetType, ref configuredMembers); } builder.BuildPropertyAttributes(targetType, ref configuredMembers); } [Fact] public void ExportInterfaceSelectorNull_ShouldThrowArgumentNull() { //Same test as above only using default export builder var builder = new RegistrationBuilder(); Assert.Throws<ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null)); Assert.Throws<ArgumentNullException>("interfaceFilter", () => builder.ForTypesMatching((t) => true).ExportInterfaces(null, null)); } [Fact] public void ImportSelectorNull_ShouldThrowArgumentNull() { //Same test as above only using default export builder var builder = new RegistrationBuilder(); Assert.Throws<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ImportProperties(null)); Assert.Throws<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ImportProperties(null, null)); Assert.Throws<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ImportProperties<IFirst>(null)); Assert.Throws<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ImportProperties<IFirst>(null, null)); } [Fact] public void ExportSelectorNull_ShouldThrowArgumentNull() { //Same test as above only using default export builder var builder = new RegistrationBuilder(); Assert.Throws<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties(null)); Assert.Throws<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties(null, null)); Assert.Throws<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties<IFirst>(null)); Assert.Throws<ArgumentNullException>("propertyFilter", () => builder.ForTypesMatching((t) => true).ExportProperties<IFirst>(null, null)); } [Fact] public void InsideTheLambdaCallGetCustomAttributesShouldSucceed() { //Same test as above only using default export builder var builder = new RegistrationBuilder(); builder.ForTypesMatching((t) => !t.IsDefined(typeof(MyDoNotIncludeAttribute), false)).Export(); var types = new Type[] { typeof(MyNotToBeIncludedClass), typeof(MyToBeIncludedClass) }; var catalog = new TypeCatalog(types, builder); CompositionService cs = catalog.CreateCompositionService(); var importer = new ImporterOfMyNotTobeIncludedClass(); cs.SatisfyImportsOnce(importer); Assert.Null(importer.MyNotToBeIncludedClass); Assert.NotNull(importer.MyToBeIncludedClass); } } }
#region License /* * Copyright 2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using NUnit.Framework; #endregion namespace Spring.Util { /// <summary> /// Unit tests for the NumberUtils class. /// </summary> /// <author>Rick Evans</author> [TestFixture] public sealed class NumberUtilsTests { [Test] public void IsInteger() { Assert.IsTrue(NumberUtils.IsInteger(10)); Assert.IsTrue(NumberUtils.IsInteger(10L)); Assert.IsTrue(NumberUtils.IsInteger((short) 10)); Assert.IsFalse(NumberUtils.IsInteger('e')); Assert.IsFalse(NumberUtils.IsInteger(null)); Assert.IsFalse(NumberUtils.IsInteger(9.5D)); Assert.IsFalse(NumberUtils.IsInteger(9.5F)); Assert.IsFalse(NumberUtils.IsInteger(this)); Assert.IsFalse(NumberUtils.IsInteger(null)); Assert.IsFalse(NumberUtils.IsInteger(string.Empty)); } [Test] public void IsDecimal() { Assert.IsFalse(NumberUtils.IsDecimal(10)); Assert.IsFalse(NumberUtils.IsDecimal(10L)); Assert.IsFalse(NumberUtils.IsDecimal((short) 10)); Assert.IsFalse(NumberUtils.IsDecimal('e')); Assert.IsFalse(NumberUtils.IsDecimal(null)); Assert.IsTrue(NumberUtils.IsDecimal(9.5D)); Assert.IsTrue(NumberUtils.IsDecimal(9.5F)); Assert.IsFalse(NumberUtils.IsDecimal(this)); Assert.IsFalse(NumberUtils.IsDecimal(null)); Assert.IsFalse(NumberUtils.IsDecimal(string.Empty)); } [Test] public void IsNumber() { Assert.IsTrue(NumberUtils.IsNumber(10)); Assert.IsTrue(NumberUtils.IsNumber(10L)); Assert.IsTrue(NumberUtils.IsNumber((short)10)); Assert.IsFalse(NumberUtils.IsNumber('e')); Assert.IsFalse(NumberUtils.IsNumber(null)); Assert.IsTrue(NumberUtils.IsNumber(9.5D)); Assert.IsTrue(NumberUtils.IsNumber(9.5F)); Assert.IsFalse(NumberUtils.IsNumber(this)); Assert.IsFalse(NumberUtils.IsNumber(null)); Assert.IsFalse(NumberUtils.IsNumber(string.Empty)); } [Test] public void IsZero() { Assert.IsFalse(NumberUtils.IsZero((Int16)2)); Assert.IsTrue(NumberUtils.IsZero((Int16)0)); Assert.IsFalse(NumberUtils.IsZero((Int32)2)); Assert.IsTrue(NumberUtils.IsZero((Int32)0)); Assert.IsFalse(NumberUtils.IsZero((Int64)2)); Assert.IsTrue(NumberUtils.IsZero((Int64)0)); Assert.IsFalse(NumberUtils.IsZero((UInt16)2)); Assert.IsTrue(NumberUtils.IsZero((UInt16)0)); Assert.IsFalse(NumberUtils.IsZero((UInt32)2)); Assert.IsTrue(NumberUtils.IsZero((UInt32)0)); Assert.IsFalse(NumberUtils.IsZero((UInt64)2)); Assert.IsTrue(NumberUtils.IsZero((UInt64)0)); Assert.IsFalse(NumberUtils.IsZero((decimal)2)); Assert.IsTrue(NumberUtils.IsZero((decimal)0)); Assert.IsTrue(NumberUtils.IsZero((Byte?)0)); Assert.IsFalse(NumberUtils.IsZero((Byte)2)); Assert.IsTrue(NumberUtils.IsZero((SByte?)0)); Assert.IsFalse(NumberUtils.IsZero((SByte)2)); } [Test] [ExpectedException(typeof(ArgumentException))] public void NegateNull() { NumberUtils.Negate(null); } [Test] [ExpectedException(typeof(ArgumentException))] public void NegateString() { NumberUtils.Negate(string.Empty); } [Test] public void Negate() { Assert.AreEqual(-10, NumberUtils.Negate(10)); } [Test] public void CoercesTypes() { object x = (int)1; object y = (double)2; NumberUtils.CoerceTypes(ref x, ref y); Assert.AreEqual(typeof(double), x.GetType()); } [Test] public void Add() { Assert.AreEqual(5, NumberUtils.Add(2, 3)); try { NumberUtils.Add(2, "3"); Assert.Fail(); } catch(ArgumentException) {} } [Test] public void BitwiseNot() { Assert.AreEqual( ~((Byte)2), NumberUtils.BitwiseNot((Byte)2) ); Assert.AreEqual(~((SByte)2), NumberUtils.BitwiseNot((SByte)2)); Assert.AreEqual(~((Int16)2), NumberUtils.BitwiseNot((Int16)2)); Assert.AreEqual(~((UInt16)2), NumberUtils.BitwiseNot((UInt16)2)); Assert.AreEqual(~((Int32)2), NumberUtils.BitwiseNot((Int32)2)); Assert.AreEqual(~((UInt32)2), NumberUtils.BitwiseNot((UInt32)2)); Assert.AreEqual(~((Int64)2), NumberUtils.BitwiseNot((Int64)2)); Assert.AreEqual(~((UInt64)2), NumberUtils.BitwiseNot((UInt64)2)); Assert.AreEqual( false, NumberUtils.BitwiseNot(true) ); try { NumberUtils.BitwiseNot((double)2.0); Assert.Fail(); } catch(ArgumentException) {} } [Test] public void BitwiseAnd() { Assert.AreEqual( ((Byte)2)&((Byte)3), NumberUtils.BitwiseAnd((Byte)2, (Byte)3)); Assert.AreEqual(((SByte)2) & ((SByte)3), NumberUtils.BitwiseAnd((SByte)2, (SByte)3)); Assert.AreEqual(((Int16)2) & ((Int16)3), NumberUtils.BitwiseAnd((Int16)2, (Int16)3)); Assert.AreEqual(((UInt16)2) & ((UInt16)3), NumberUtils.BitwiseAnd((UInt16)2, (UInt16)3)); Assert.AreEqual(((Int32)2) & ((Int32)3), NumberUtils.BitwiseAnd((Int32)2, (Int32)3)); Assert.AreEqual(((UInt32)2) & ((UInt32)3), NumberUtils.BitwiseAnd((UInt32)2, (UInt32)3)); Assert.AreEqual(((Int64)2) & ((Int64)3), NumberUtils.BitwiseAnd((Int64)2, (Int64)3)); Assert.AreEqual(((UInt64)2) & ((UInt64)3), NumberUtils.BitwiseAnd((UInt64)2, (UInt64)3)); Assert.AreEqual(((UInt64)2) & ((Byte)3), NumberUtils.BitwiseAnd((UInt64)2, (Byte)3)); Assert.AreEqual(true, NumberUtils.BitwiseAnd(true, true)); Assert.AreEqual( false, NumberUtils.BitwiseAnd(false, true) ); try { NumberUtils.BitwiseAnd((double)2.0, 3); Assert.Fail(); } catch(ArgumentException) {} } [Test] public void BitwiseOr() { Assert.AreEqual( ((Byte)2) | ((Byte)3), NumberUtils.BitwiseOr((Byte)2, (Byte)3)); Assert.AreEqual(((SByte)2) | ((SByte)3), NumberUtils.BitwiseOr((SByte)2, (SByte)3)); Assert.AreEqual(((Int16)2) | ((Int16)3), NumberUtils.BitwiseOr((Int16)2, (Int16)3)); Assert.AreEqual(((UInt16)2) | ((UInt16)3), NumberUtils.BitwiseOr((UInt16)2, (UInt16)3)); Assert.AreEqual(((Int32)2) | ((Int32)3), NumberUtils.BitwiseOr((Int32)2, (Int32)3)); Assert.AreEqual(((UInt32)2) | ((UInt32)3), NumberUtils.BitwiseOr((UInt32)2, (UInt32)3)); Assert.AreEqual(((Int64)2) | ((Int64)3), NumberUtils.BitwiseOr((Int64)2, (Int64)3)); Assert.AreEqual(((UInt64)2) | ((UInt64)3), NumberUtils.BitwiseOr((UInt64)2, (UInt64)3)); Assert.AreEqual(((UInt64)2) | ((Byte)3), NumberUtils.BitwiseOr((UInt64)2, (Byte)3)); Assert.AreEqual(false, NumberUtils.BitwiseOr(false, false)); Assert.AreEqual(true, NumberUtils.BitwiseOr(false, true)); try { NumberUtils.BitwiseAnd((double)2.0, 3); Assert.Fail(); } catch(ArgumentException) {} } [Test] public void BitwiseXor() { Assert.AreEqual( ((Byte)2) ^ ((Byte)3), NumberUtils.BitwiseXor((Byte)2, (Byte)3)); Assert.AreEqual(((SByte)2) ^ ((SByte)3), NumberUtils.BitwiseXor((SByte)2, (SByte)3)); Assert.AreEqual(((Int16)2) ^ ((Int16)3), NumberUtils.BitwiseXor((Int16)2, (Int16)3)); Assert.AreEqual(((UInt16)2) ^ ((UInt16)3), NumberUtils.BitwiseXor((UInt16)2, (UInt16)3)); Assert.AreEqual(((Int32)2) ^ ((Int32)3), NumberUtils.BitwiseXor((Int32)2, (Int32)3)); Assert.AreEqual(((UInt32)2) ^ ((UInt32)3), NumberUtils.BitwiseXor((UInt32)2, (UInt32)3)); Assert.AreEqual(((Int64)2) ^ ((Int64)3), NumberUtils.BitwiseXor((Int64)2, (Int64)3)); Assert.AreEqual(((UInt64)2) ^ ((UInt64)3), NumberUtils.BitwiseXor((UInt64)2, (UInt64)3)); Assert.AreEqual(((UInt64)2) ^ ((Byte)3), NumberUtils.BitwiseXor((UInt64)2, (Byte)3)); Assert.AreEqual(false, NumberUtils.BitwiseXor(false, false)); Assert.AreEqual(false, NumberUtils.BitwiseXor(true, true)); Assert.AreEqual(true, NumberUtils.BitwiseXor(false, true)); Assert.AreEqual(true, NumberUtils.BitwiseXor(true, false)); try { NumberUtils.BitwiseAnd((double)2.0, 3); Assert.Fail(); } catch(ArgumentException) {} } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Input; using NUnit.Framework; namespace Xamarin.Forms.Core.UnitTests { [TestFixture] public class ListViewTests : BaseTestFixture { [TearDown] public override void TearDown() { base.TearDown (); Device.PlatformServices = null; Device.Info = null; } [SetUp] public override void Setup () { base.Setup (); Device.PlatformServices = new MockPlatformServices (); Device.Info = new TestDeviceInfo (); } [Test] public void TestConstructor () { var listView = new ListView (); Assert.Null (listView.ItemsSource); Assert.Null (listView.ItemTemplate); Assert.AreEqual (LayoutOptions.FillAndExpand, listView.HorizontalOptions); Assert.AreEqual (LayoutOptions.FillAndExpand, listView.VerticalOptions); } internal class ListItem { public string Name { get; set; } public string Description { get; set; } } [Test] public void TestTemplating () { var cellTemplate = new DataTemplate (typeof (TextCell)); cellTemplate.SetBinding (TextCell.TextProperty, new Binding ("Name")); cellTemplate.SetBinding (TextCell.DetailProperty, new Binding ("Description")); var listView = new ListView { ItemsSource = new[] { new ListItem {Name = "Foo", Description = "Bar"}, new ListItem {Name = "Baz", Description = "Raz"} }, ItemTemplate = cellTemplate }; var cell = (Cell)listView.ItemTemplate.CreateContent (); var textCell = (TextCell)cell; cell.BindingContext = listView.ItemsSource.OfType<ListItem> ().First (); Assert.AreEqual ("Foo", textCell.Text); Assert.AreEqual ("Bar", textCell.Detail); } [Test] public void TemplateNullObject() { var listView = new ListView { ItemsSource = new object[] { null } }; Cell cell = listView.TemplatedItems[0]; Assert.That (cell, Is.Not.Null); Assert.That (cell, Is.InstanceOf<TextCell>()); Assert.That (((TextCell) cell).Text, Is.Null); } [Test] [Description("Setting BindingContext should trickle down to Header and Footer.")] public void SettingBindingContextPassesToHeaderAndFooter() { var bc = new object(); var header = new BoxView(); var footer = new BoxView(); var listView = new ListView { Header = header, Footer = footer, BindingContext = bc, }; Assert.That(header.BindingContext, Is.SameAs(bc)); Assert.That(footer.BindingContext, Is.SameAs(bc)); } [Test] [Description("Setting Header and Footer should pass BindingContext.")] public void SettingHeaderFooterPassesBindingContext() { var bc = new object(); var listView = new ListView { BindingContext = bc, }; var header = new BoxView(); var footer = new BoxView(); listView.Footer = footer; listView.Header = header; Assert.That(header.BindingContext, Is.SameAs(bc)); Assert.That(footer.BindingContext, Is.SameAs(bc)); } [Test] [Description ("Setting GroupDisplayBinding or GroupHeaderTemplate when the other is set should set the other one to null.")] public void SettingGroupHeaderTemplateSetsDisplayBindingToNull() { var listView = new ListView { GroupDisplayBinding = new Binding ("Path") }; listView.GroupHeaderTemplate = new DataTemplate (typeof (TextCell)); Assert.That (listView.GroupDisplayBinding, Is.Null); } [Test] [Description ("Setting GroupDisplayBinding or GroupHeaderTemplate when the other is set should set the other one to null.")] public void SettingGroupDisplayBindingSetsHeaderTemplateToNull() { var listView = new ListView { GroupHeaderTemplate = new DataTemplate (typeof (TextCell)) }; listView.GroupDisplayBinding = new Binding ("Path"); Assert.That (listView.GroupHeaderTemplate, Is.Null); } [Test] [Description ("You should be able to set ItemsSource without having set the other properties first without issue")] public void SettingItemsSourceWithoutBindingsOrItemsSource() { var listView = new ListView { IsGroupingEnabled = true }; Assert.That (() => listView.ItemsSource = new[] { new[] { new object() } }, Throws.Nothing); } [Test] public void DefaultGroupHeaderTemplates() { var items = new[] { new[] { new object() } }; var listView = new ListView { IsGroupingEnabled = true, ItemsSource = items }; var til = (TemplatedItemsList<ItemsView<Cell>, Cell>)((IList)listView.TemplatedItems)[0]; Cell cell = til.HeaderContent; Assert.That (cell, Is.Not.Null); Assert.That (cell, Is.InstanceOf<TextCell>()); Assert.That (((TextCell) cell).Text, Is.EqualTo (items[0].ToString())); } [Test] [Description ("Tapping a different item (row) that is equal to the current item selection should still raise ItemSelected")] public void NotifyRowTappedDifferentIndex() { string item = "item"; var listView = new ListView { ItemsSource = new[] { item, item } }; listView.NotifyRowTapped (0); bool raised = false; listView.ItemSelected += (sender, arg) => raised = true; listView.NotifyRowTapped (1); Assert.That (raised, Is.True, "ItemSelected was not raised"); } [Test] public void DoesNotCrashWhenAddingToSource () { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var listView = new ListView { ItemsSource = items, ItemTemplate = new DataTemplate(typeof(TextCell)) }; Assert.DoesNotThrow (() => items.Add ("Blah")); } [Test] public void DoesNotThrowWhenMovingInSource () { var items = new ObservableCollection<string> { "Foo", "Bar", "Baz" }; var listView = new ListView { ItemsSource = items, ItemTemplate = new DataTemplate (typeof (TextCell)) }; Assert.DoesNotThrow (() => items.Move (0, 1)); } [Test] [Description ("A cell being tapped from the UI should raise both tapped events, but not change ItemSelected")] public void NotifyTappedSameItem() { int cellTapped = 0; int itemTapped = 0; int itemSelected = 0; var listView = new ListView { ItemsSource = new[] { "item" }, ItemTemplate = new DataTemplate (() => { var cell = new TextCell(); cell.Tapped += (s, e) => { cellTapped++; }; return cell; }) }; listView.ItemTapped += (sender, arg) => itemTapped++; listView.ItemSelected += (sender, arg) => itemSelected++; listView.NotifyRowTapped (0); Assert.That (cellTapped, Is.EqualTo (1), "Cell.Tapped was not raised"); Assert.That (itemTapped, Is.EqualTo (1), "ListView.ItemTapped was not raised"); Assert.That (itemSelected, Is.EqualTo (1), "ListView.ItemSelected was not raised"); listView.NotifyRowTapped (0); Assert.That (cellTapped, Is.EqualTo (2), "Cell.Tapped was not raised a second time"); Assert.That (itemTapped, Is.EqualTo (2), "ListView.ItemTapped was not raised a second time"); Assert.That (itemSelected, Is.EqualTo (1), "ListView.ItemSelected was raised a second time"); } [Test] public void ScrollTo() { var listView = new ListView { IsPlatformEnabled = true, Platform = new UnitPlatform() }; object item = new object(); bool requested = false; listView.ScrollToRequested += (sender, args) => { requested = true; Assert.That (args.Item, Is.SameAs (item)); Assert.That (args.Group, Is.Null); Assert.That (args.Position, Is.EqualTo (ScrollToPosition.Center)); Assert.That (args.ShouldAnimate, Is.EqualTo (true)); }; listView.ScrollTo (item, ScrollToPosition.Center, animated: true); Assert.That (requested, Is.True); } [Test] public void ScrollToDelayed() { var listView = new ListView(); object item = new object(); bool requested = false; listView.ScrollToRequested += (sender, args) => { requested = true; Assert.That (args.Item, Is.SameAs (item)); Assert.That (args.Group, Is.Null); Assert.That (args.Position, Is.EqualTo (ScrollToPosition.Center)); Assert.That (args.ShouldAnimate, Is.EqualTo (true)); }; listView.ScrollTo (item, ScrollToPosition.Center, animated: true); Assert.That (requested, Is.False); listView.IsPlatformEnabled = true; listView.Platform = new UnitPlatform(); Assert.That (requested, Is.True); } [Test] public void ScrollToGroup() { // Fake a renderer so we pass along messages right away var listView = new ListView { IsPlatformEnabled = true, Platform = new UnitPlatform(), IsGroupingEnabled = true }; object item = new object(); object group = new object(); bool requested = false; listView.ScrollToRequested += (sender, args) => { requested = true; Assert.That (args.Item, Is.SameAs (item)); Assert.That (args.Group, Is.SameAs (group)); Assert.That (args.Position, Is.EqualTo (ScrollToPosition.Center)); Assert.That (args.ShouldAnimate, Is.EqualTo (true)); }; listView.ScrollTo (item, group, ScrollToPosition.Center, animated: true); Assert.That (requested, Is.True); } [Test] public void ScrollToInvalid() { var listView = new ListView { IsPlatformEnabled = true, Platform = new UnitPlatform() }; Assert.That (() => listView.ScrollTo (new object(), (ScrollToPosition) 500, true), Throws.ArgumentException); Assert.That (() => listView.ScrollTo (new object(), new object(), ScrollToPosition.Start, true), Throws.InvalidOperationException); listView.IsGroupingEnabled = true; Assert.That (() => listView.ScrollTo (new object(), new object(), (ScrollToPosition) 500, true), Throws.ArgumentException); } [Test] public void GetSizeRequest () { var listView = new ListView { IsPlatformEnabled = true, Platform = new UnitPlatform (), HasUnevenRows = false, RowHeight = 50, ItemsSource = Enumerable.Range (0, 20).ToList () }; var sizeRequest = listView.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity); Assert.AreEqual (40, sizeRequest.Minimum.Width); Assert.AreEqual (40, sizeRequest.Minimum.Height); Assert.AreEqual (50, sizeRequest.Request.Width); Assert.AreEqual (50 * 20, sizeRequest.Request.Height); } [Test] public void GetSizeRequestUneven () { var listView = new ListView { IsPlatformEnabled = true, Platform = new UnitPlatform (), HasUnevenRows = true, RowHeight = 50, ItemsSource = Enumerable.Range (0, 20).ToList () }; var sizeRequest = listView.GetSizeRequest (double.PositiveInfinity, double.PositiveInfinity); Assert.AreEqual (40, sizeRequest.Minimum.Width); Assert.AreEqual (40, sizeRequest.Minimum.Height); Assert.AreEqual (50, sizeRequest.Request.Width); Assert.AreEqual (100, sizeRequest.Request.Height); } public class ListItemValue : IComparable<ListItemValue> { public string Name { get; private set; } public ListItemValue (string name) { Name = name; } int IComparable<ListItemValue>.CompareTo (ListItemValue value) { return Name.CompareTo (value.Name); } public string Label { get { return Name[0].ToString (); } } } public class ListItemCollection : ObservableCollection<ListItemValue> { public string Title { get; private set; } public ListItemCollection (string title) { Title = title; } public static List<ListItemValue> GetSortedData () { var items = ListItems; items.Sort (); return items; } // Data used to populate our list. static readonly List<ListItemValue> ListItems = new List<ListItemValue> () { new ListItemValue ("Babbage"), new ListItemValue ("Boole"), new ListItemValue ("Berners-Lee"), new ListItemValue ("Atanasoff"), new ListItemValue ("Allen"), new ListItemValue ("Cormack"), new ListItemValue ("Cray"), new ListItemValue ("Dijkstra"), new ListItemValue ("Dix"), new ListItemValue ("Dewey"), new ListItemValue ("Erdos"), }; } public class TestCell : TextCell { public static int NumberOfCells = 0; public TestCell () { Interlocked.Increment (ref NumberOfCells); } ~TestCell () { Interlocked.Decrement (ref NumberOfCells); } } ObservableCollection<ListItemCollection> SetupList () { var allListItemGroups = new ObservableCollection<ListItemCollection> (); foreach (var item in ListItemCollection.GetSortedData ()) { // Attempt to find any existing groups where theg group title matches the first char of our ListItem's name. var listItemGroup = allListItemGroups.FirstOrDefault (g => g.Title == item.Label); // If the list group does not exist, we create it. if (listItemGroup == null) { listItemGroup = new ListItemCollection (item.Label) { item }; allListItemGroups.Add (listItemGroup); } else { // If the group does exist, we simply add the demo to the existing group. listItemGroup.Add (item); } } return allListItemGroups; } [Test] public void UncollectableHeaderReferences () { var list = new ListView { Platform = new UnitPlatform (), IsPlatformEnabled = true, ItemTemplate = new DataTemplate (typeof (TextCell)) { Bindings = { {TextCell.TextProperty, new Binding ("Name")} } }, GroupHeaderTemplate = new DataTemplate (typeof (TestCell)) { Bindings = { {TextCell.TextProperty, new Binding ("Title")} } }, IsGroupingEnabled = true, ItemsSource = SetupList (), }; Assert.AreEqual (5, TestCell.NumberOfCells); var newList1 = SetupList (); var newList2 = SetupList (); for (var i = 0; i < 400; i++) { list.ItemsSource = i % 2 > 0 ? newList1 : newList2; // grab a header just so we can be sure its reailized var header = list.TemplatedItems.GetGroup (0).HeaderContent; } GC.Collect (); GC.WaitForPendingFinalizers (); // use less or equal because mono will keep the last header var alive no matter what Assert.True (TestCell.NumberOfCells <= 6); var keepAlive = list.ToString (); } [Test] public void CollectionChangedMultipleFires () { var source = new ObservableCollection<string> { "Foo", "Bar" }; var list = new ListView { Platform = new UnitPlatform (), IsPlatformEnabled = true, ItemsSource = source, ItemTemplate = new DataTemplate (typeof (TextCell)) }; int fireCount = 0; list.TemplatedItems.CollectionChanged += (sender, args) => { fireCount++; }; source.Add ("Baz"); Assert.AreEqual (1, fireCount); } [Test] public void GroupedCollectionChangedMultipleFires () { var source = new ObservableCollection<ObservableCollection <string>> { new ObservableCollection<string> {"Foo"}, new ObservableCollection<string> {"Bar"} }; var list = new ListView { Platform = new UnitPlatform (), IsPlatformEnabled = true, IsGroupingEnabled = true, ItemsSource = source, ItemTemplate = new DataTemplate (typeof (TextCell)) { Bindings = { {TextCell.TextProperty, new Binding (".") } } } }; int fireCount = 0; list.TemplatedItems.GroupedCollectionChanged += (sender, args) => { fireCount++; }; source[0].Add ("Baz"); Assert.AreEqual (1, fireCount); } [Test] public void HeaderAsView() { var label = new Label { Text = "header" }; var lv = new ListView { Header = label }; IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.SameAs (label)); } [Test] public void HeaderTemplated() { var lv = new ListView { Header = "header", HeaderTemplate = new DataTemplate(typeof(Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.Not.Null); Assert.That (controller.HeaderElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.HeaderElement).Text, Is.EqualTo (lv.Header)); } [Test] public void HeaderTemplateThrowsIfCell () { var lv = new ListView (); Assert.Throws<ArgumentException> (() => lv.HeaderTemplate = new DataTemplate (typeof (TextCell))); } [Test] public void FooterTemplateThrowsIfCell () { var lv = new ListView (); Assert.Throws<ArgumentException> (() => lv.FooterTemplate = new DataTemplate (typeof (TextCell))); } [Test] public void HeaderObjectTemplatedChanged() { var lv = new ListView { Header = "header", HeaderTemplate = new DataTemplate (typeof (Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "HeaderElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "HeaderElement") changed = true; }; lv.Header = "newheader"; Assert.That (changing, Is.False); Assert.That (changed, Is.False); IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.Not.Null); Assert.That (controller.HeaderElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.HeaderElement).Text, Is.EqualTo (lv.Header)); } [Test] public void HeaderViewChanged() { var lv = new ListView { Header = new Label { Text = "header" } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "HeaderElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "HeaderElement") changed = true; }; Label label = new Label { Text = "header" }; lv.Header = label; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.SameAs (label)); } [Test] public void HeaderTemplateChanged() { var lv = new ListView { Header = "header", HeaderTemplate = new DataTemplate(typeof(Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "HeaderElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "HeaderElement") changed = true; }; lv.HeaderTemplate = new DataTemplate (typeof (Entry)) { Bindings = { { Entry.TextProperty, new Binding (".") } } }; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.Not.Null); Assert.That (controller.HeaderElement, Is.InstanceOf<Entry>()); Assert.That (((Entry) controller.HeaderElement).Text, Is.EqualTo (lv.Header)); } [Test] public void HeaderTemplateChangedNoObject() { var lv = new ListView { HeaderTemplate = new DataTemplate(typeof(Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "HeaderElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "HeaderElement") changed = true; }; lv.HeaderTemplate = new DataTemplate (typeof (Entry)) { Bindings = { { Entry.TextProperty, new Binding (".") } } }; Assert.That (changing, Is.False); Assert.That (changed, Is.False); IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.Null); } [Test] public void HeaderNoTemplate() { var lv = new ListView { Header = "foo" }; IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.Not.Null); Assert.That (controller.HeaderElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.HeaderElement).Text, Is.EqualTo (lv.Header)); } [Test] public void HeaderChangedNoTemplate() { var lv = new ListView { Header = "foo" }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "HeaderElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "HeaderElement") changed = true; }; lv.Header = "bar"; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.Not.Null); Assert.That (controller.HeaderElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.HeaderElement).Text, Is.EqualTo (lv.Header)); } [Test] public void HeaderViewButTemplated() { var lv = new ListView { Header = new Entry { Text = "foo" }, HeaderTemplate = new DataTemplate (typeof(Label)) { Bindings = { { Label.TextProperty, new Binding ("Text") } } } }; IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.Not.Null); Assert.That (controller.HeaderElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.HeaderElement).Text, Is.EqualTo (((Entry)lv.Header).Text)); } [Test] public void HeaderTemplatedChangedToView() { var lv = new ListView { Header = new Entry { Text = "foo" }, HeaderTemplate = new DataTemplate (typeof(Label)) { Bindings = { { Label.TextProperty, new Binding ("Text") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "HeaderElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "HeaderElement") changed = true; }; lv.HeaderTemplate = null; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.Not.Null); Assert.That (controller.HeaderElement, Is.InstanceOf<Entry>()); Assert.That (((Entry) controller.HeaderElement).Text, Is.EqualTo (((Entry)lv.Header).Text)); } [Test] public void HeaderTemplatedSetToNull() { var lv = new ListView { Header = "header", HeaderTemplate = new DataTemplate(typeof(Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "HeaderElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "HeaderElement") changed = true; }; lv.Header = null; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.HeaderElement, Is.Null); } [Test] public void FooterAsView() { var label = new Label { Text = "footer" }; var lv = new ListView { Footer = label }; IListViewController controller = lv; Assert.That (controller.FooterElement, Is.SameAs (label)); } [Test] public void FooterTemplated() { var lv = new ListView { Footer = "footer", FooterTemplate = new DataTemplate(typeof(Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; IListViewController controller = lv; Assert.That (controller.FooterElement, Is.Not.Null); Assert.That (controller.FooterElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.FooterElement).Text, Is.EqualTo (lv.Footer)); } [Test] public void FooterObjectTemplatedChanged() { var lv = new ListView { Footer = "footer", FooterTemplate = new DataTemplate (typeof (Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "FooterElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "FooterElement") changed = true; }; lv.Footer = "newfooter"; Assert.That (changing, Is.False); Assert.That (changed, Is.False); IListViewController controller = lv; Assert.That (controller.FooterElement, Is.Not.Null); Assert.That (controller.FooterElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.FooterElement).Text, Is.EqualTo (lv.Footer)); } [Test] public void FooterViewChanged() { var lv = new ListView { Footer = new Label { Text = "footer" } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "FooterElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "FooterElement") changed = true; }; Label label = new Label { Text = "footer" }; lv.Footer = label; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.FooterElement, Is.SameAs (label)); } [Test] public void FooterTemplateChanged() { var lv = new ListView { Footer = "footer", FooterTemplate = new DataTemplate(typeof(Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "FooterElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "FooterElement") changed = true; }; lv.FooterTemplate = new DataTemplate (typeof (Entry)) { Bindings = { { Entry.TextProperty, new Binding (".") } } }; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.FooterElement, Is.Not.Null); Assert.That (controller.FooterElement, Is.InstanceOf<Entry>()); Assert.That (((Entry) controller.FooterElement).Text, Is.EqualTo (lv.Footer)); } [Test] public void FooterTemplateChangedNoObject() { var lv = new ListView { FooterTemplate = new DataTemplate(typeof(Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "FooterElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "FooterElement") changed = true; }; lv.FooterTemplate = new DataTemplate (typeof (Entry)) { Bindings = { { Entry.TextProperty, new Binding (".") } } }; Assert.That (changing, Is.False); Assert.That (changed, Is.False); IListViewController controller = lv; Assert.That (controller.FooterElement, Is.Null); } [Test] public void FooterNoTemplate() { var lv = new ListView { Footer = "foo" }; IListViewController controller = lv; Assert.That (controller.FooterElement, Is.Not.Null); Assert.That (controller.FooterElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.FooterElement).Text, Is.EqualTo (lv.Footer)); } [Test] public void FooterChangedNoTemplate() { var lv = new ListView { Footer = "foo" }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "FooterElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "FooterElement") changed = true; }; lv.Footer = "bar"; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.FooterElement, Is.Not.Null); Assert.That (controller.FooterElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.FooterElement).Text, Is.EqualTo (lv.Footer)); } [Test] public void FooterViewButTemplated() { var lv = new ListView { Footer = new Entry { Text = "foo" }, FooterTemplate = new DataTemplate (typeof(Label)) { Bindings = { { Label.TextProperty, new Binding ("Text") } } } }; IListViewController controller = lv; Assert.That (controller.FooterElement, Is.Not.Null); Assert.That (controller.FooterElement, Is.InstanceOf<Label>()); Assert.That (((Label) controller.FooterElement).Text, Is.EqualTo (((Entry)lv.Footer).Text)); } [Test] public void FooterTemplatedChangedToView() { var lv = new ListView { Footer = new Entry { Text = "foo" }, FooterTemplate = new DataTemplate (typeof(Label)) { Bindings = { { Label.TextProperty, new Binding ("Text") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "FooterElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "FooterElement") changed = true; }; lv.FooterTemplate = null; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.FooterElement, Is.Not.Null); Assert.That (controller.FooterElement, Is.InstanceOf<Entry>()); Assert.That (((Entry) controller.FooterElement).Text, Is.EqualTo (((Entry)lv.Footer).Text)); } [Test] public void FooterTemplatedSetToNull() { var lv = new ListView { Footer = "footer", FooterTemplate = new DataTemplate(typeof(Label)) { Bindings = { { Label.TextProperty, new Binding (".") } } } }; bool changed = false, changing = false; lv.PropertyChanging += (sender, args) => { if (args.PropertyName == "FooterElement") changing = true; }; lv.PropertyChanged += (sender, args) => { if (args.PropertyName == "FooterElement") changed = true; }; lv.Footer = null; Assert.That (changing, Is.True); Assert.That (changed, Is.True); IListViewController controller = lv; Assert.That (controller.FooterElement, Is.Null); } [Test] public void BeginRefresh() { var lv = new ListView(); bool refreshing = false; lv.Refreshing += (sender, args) => { refreshing = true; }; lv.BeginRefresh(); Assert.That (refreshing, Is.True); Assert.That (lv.IsRefreshing, Is.True); } [Test] public void SendRefreshing() { var lv = new ListView(); bool refreshing = false; lv.Refreshing += (sender, args) => { refreshing = true; }; IListViewController controller = lv; controller.SendRefreshing(); Assert.That (refreshing, Is.True); Assert.That (lv.IsRefreshing, Is.True); } [Test] public void RefreshCommand() { var lv = new ListView(); bool commandExecuted = false; Command refresh = new Command (() => commandExecuted = true); lv.RefreshCommand = refresh; IListViewController controller = lv; controller.SendRefreshing(); Assert.That (commandExecuted, Is.True); } [TestCase (true)] [TestCase (false)] public void RefreshCommandCanExecute (bool initial) { var lv = new ListView { IsPullToRefreshEnabled = initial }; bool commandExecuted = false; Command refresh = new Command (() => commandExecuted = true, () => !initial); lv.RefreshCommand = refresh; Assert.That ((lv as IListViewController).RefreshAllowed, Is.EqualTo (!initial)); } [TestCase (true)] [TestCase (false)] public void RefreshCommandCanExecuteChanges (bool initial) { var lv = new ListView { IsPullToRefreshEnabled = initial }; bool commandExecuted = false; Command refresh = new Command (() => commandExecuted = true, () => initial); lv.RefreshCommand = refresh; Assert.That ((lv as IListViewController).RefreshAllowed, Is.EqualTo (initial)); initial = !initial; refresh.ChangeCanExecute(); Assert.That ((lv as IListViewController).RefreshAllowed, Is.EqualTo (initial)); } [Test] public void BeginRefreshDoesNothingWhenCannotExecute() { var lv = new ListView(); bool commandExecuted = false, eventFired = false; lv.Refreshing += (sender, args) => eventFired = true; Command refresh = new Command (() => commandExecuted = true, () => false); lv.RefreshCommand = refresh; lv.BeginRefresh(); Assert.That (lv.IsRefreshing, Is.False); Assert.That (eventFired, Is.False); Assert.That (commandExecuted, Is.False); } [Test] public void SendRefreshingDoesNothingWhenCannotExecute() { var lv = new ListView(); bool commandExecuted = false, eventFired = false; lv.Refreshing += (sender, args) => eventFired = true; Command refresh = new Command (() => commandExecuted = true, () => false); lv.RefreshCommand = refresh; ((IListViewController)lv).SendRefreshing(); Assert.That (lv.IsRefreshing, Is.False); Assert.That (eventFired, Is.False); Assert.That (commandExecuted, Is.False); } [Test] public void SettingIsRefreshingDoesntFireEvent() { var lv = new ListView(); bool refreshing = false; lv.Refreshing += (sender, args) => { refreshing = true; }; lv.IsRefreshing = true; Assert.That (refreshing, Is.False); } [Test] public void EndRefresh() { var lv = new ListView { IsRefreshing = true }; Assert.That (lv.IsRefreshing, Is.True); lv.EndRefresh(); Assert.That (lv.IsRefreshing, Is.False); } [Test] public void CanRefreshAfterCantExecuteCommand() { var lv = new ListView(); bool commandExecuted = false, eventFired = false; lv.Refreshing += (sender, args) => eventFired = true; Command refresh = new Command (() => commandExecuted = true, () => false); lv.RefreshCommand = refresh; lv.RefreshCommand = null; ((IListViewController)lv).SendRefreshing(); Assert.That (lv.IsRefreshing, Is.True); Assert.That (eventFired, Is.True); Assert.That (commandExecuted, Is.False); } [Test] public void StopsListeningToCommandAfterCleared() { var lv = new ListView(); bool commandExecuted = false, canExecuteRequested = false; Command refresh = new Command (() => commandExecuted = true, () => canExecuteRequested = true); lv.RefreshCommand = refresh; canExecuteRequested = false; lv.RefreshCommand = null; Assert.That (() => refresh.ChangeCanExecute(), Throws.Nothing); Assert.That (canExecuteRequested, Is.False); lv.BeginRefresh(); Assert.That (commandExecuted, Is.False); } [Test] [Description ("We should be able to set selected item when using ReadOnlyList")] public void SetItemSelectedOnReadOnlyList() { var source = new ReadOnlySource (); var listView = new ListView { ItemsSource = source }; bool raised = false; listView.ItemSelected += (sender, arg) => raised = true; listView.SelectedItem = source [0]; Assert.That (raised, Is.True, "ItemSelected was raised on ReadOnlySource"); } internal class ReadOnlySource : IReadOnlyList<ListItem> { List<ListItem> items; public ReadOnlySource () { items = new List<ListItem> (); for (int i = 0; i < 100; i++) { items.Add (new ListItem { Name="person " + i } ); } } #region IEnumerable implementation public IEnumerator<ListItem> GetEnumerator () { return items.GetEnumerator (); } #endregion #region IEnumerable implementation System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { return items.GetEnumerator (); } #endregion #region IReadOnlyList implementation public ListItem this [int index] { get { return items [index]; } } #endregion #region IReadOnlyCollection implementation public int Count { get { return items.Count; } } #endregion } [Test] public void ChildElementsParentIsNulledWhenReset() { var list = new ListView(); list.ItemsSource = new[] { "Hi", "Bye" }; var cell = list.TemplatedItems[0]; Assume.That (cell.Parent, Is.SameAs (list)); list.ItemsSource = null; Assert.That (cell.Parent, Is.Null); } [Test] public void ChildElementsParentIsNulledWhenRemoved() { var collection = new ObservableCollection<string> { "Hi", "Bye" }; var list = new ListView(); list.ItemsSource = collection; var cell = list.TemplatedItems[0]; Assume.That (cell.Parent, Is.SameAs (list)); collection.Remove (collection[0]); Assert.That (cell.Parent, Is.Null); } [Test] public void ChildElementsParentIsNulledWhenCleared() { var collection = new ObservableCollection<string> { "Hi", "Bye" }; var list = new ListView(); list.ItemsSource = collection; var cell = list.TemplatedItems[0]; Assume.That (cell.Parent, Is.SameAs (list)); collection.Clear(); Assert.That (cell.Parent, Is.Null); } [TestCase (Device.Android, ListViewCachingStrategy.RecycleElement)] [TestCase (Device.iOS, ListViewCachingStrategy.RecycleElement)] [TestCase (Device.Windows, ListViewCachingStrategy.RetainElement)] [TestCase ("Other", ListViewCachingStrategy.RetainElement)] [TestCase (Device.WinPhone, ListViewCachingStrategy.RetainElement)] public void EnforcesCachingStrategy (string platform, ListViewCachingStrategy expected) { var oldOS = Device.RuntimePlatform; // we need to do this because otherwise we cant set the caching strategy ((MockPlatformServices)Device.PlatformServices).RuntimePlatform = platform; var listView = new ListView (ListViewCachingStrategy.RecycleElement); Assert.AreEqual (expected, listView.CachingStrategy); ((MockPlatformServices)Device.PlatformServices).RuntimePlatform = oldOS; } [Test] public void DefaultCacheStrategy () { var listView = new ListView (); Assert.AreEqual (ListViewCachingStrategy.RetainElement, listView.CachingStrategy); } [Test] public void DoesNotRetainInRecycleMode () { var items = new ObservableCollection<string> { "Foo", "Bar" }; var oldOS = Device.RuntimePlatform; // we need to do this because otherwise we cant set the caching strategy ((MockPlatformServices)Device.PlatformServices).RuntimePlatform = Device.Android; var bindable = new ListView (ListViewCachingStrategy.RecycleElement); bindable.ItemTemplate = new DataTemplate (typeof (TextCell)) { Bindings = { { TextCell.TextProperty, new Binding (".") } } }; bindable.ItemsSource = items; var item1 = bindable.TemplatedItems[0]; var item2 = bindable.TemplatedItems[0]; Assert.False(ReferenceEquals (item1, item2)); ((MockPlatformServices)Device.PlatformServices).RuntimePlatform = oldOS; } } }
namespace Microsoft.Protocols.TestSuites.SharedAdapter { using System; using System.Collections.Generic; /// <summary> /// This class specifies the data element knowledge of the client. /// </summary> public class CellKnowledge : SpecializedKnowledgeData { /// <summary> /// Initializes a new instance of the CellKnowledge class. /// </summary> public CellKnowledge() : base(StreamObjectTypeHeaderStart.CellKnowledge) { this.CellKnowledgeEntryList = new List<CellKnowledgeEntry>(); this.CellKnowledgeRangeList = new List<CellKnowledgeRange>(); } /// <summary> /// Gets or sets a list of cell knowledge ranges. /// </summary> public List<CellKnowledgeRange> CellKnowledgeRangeList { get; set; } /// <summary> /// Gets or sets a list of cell knowledge entries. /// </summary> public List<CellKnowledgeEntry> CellKnowledgeEntryList { get; set; } /// <summary> /// This method is used to deserialize the items of the cell knowledge from the byte array. /// </summary> /// <param name="byteArray">Specify the byte array.</param> /// <param name="currentIndex">Specify the start index from the byte array.</param> /// <param name="lengthOfItems">Specify the current length of items in the cell knowledge.</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { if (lengthOfItems != 0) { throw new KnowledgeParseErrorException(currentIndex, "CellKnowledge object over-parse error", null); } int index = currentIndex; StreamObjectHeaderStart header; int length = 0; this.CellKnowledgeEntryList = new List<CellKnowledgeEntry>(); this.CellKnowledgeRangeList = new List<CellKnowledgeRange>(); while ((length = StreamObjectHeaderStart.TryParse(byteArray, index, out header)) != 0) { index += length; if (header.Type == StreamObjectTypeHeaderStart.CellKnowledgeEntry) { this.CellKnowledgeEntryList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as CellKnowledgeEntry); } else if (header.Type == StreamObjectTypeHeaderStart.CellKnowledgeRange) { this.CellKnowledgeRangeList.Add(StreamObject.ParseStreamObject(header, byteArray, ref index) as CellKnowledgeRange); } else { throw new KnowledgeParseErrorException(currentIndex, "Failed to parse CellKnowledge, expect the inner object type is either CellKnowledgeEntry or CellKnowledgeRange but actual type value is " + header.Type, null); } } currentIndex = index; } /// <summary> /// This method is used to serialize the items of the cell knowledge to the byte list. /// </summary> /// <param name="byteList">Specify the byte list which stores the information of cell knowledge.</param> /// <returns>Return the length in byte of the items in cell knowledge.</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { if (this.CellKnowledgeRangeList != null) { foreach (CellKnowledgeRange cellKnowledgeRange in this.CellKnowledgeRangeList) { byteList.AddRange(cellKnowledgeRange.SerializeToByteList()); } } if (this.CellKnowledgeEntryList != null) { foreach (CellKnowledgeEntry cellKnowledgeEntry in this.CellKnowledgeEntryList) { byteList.AddRange(cellKnowledgeEntry.SerializeToByteList()); } } return 0; } } /// <summary> /// This class specifies cell knowledge range of data elements. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.StyleCop.CSharp.MaintainabilityRules", "SA1402:FileMayOnlyContainASingleClass", Justification = "Easy to maintain one group of classes in one .cs file.")] public class CellKnowledgeRange : StreamObject { /// <summary> /// Initializes a new instance of the CellKnowledgeRange class. /// </summary> public CellKnowledgeRange() : base(StreamObjectTypeHeaderStart.CellKnowledgeRange) { this.CellKnowledgeRangeGUID = Guid.NewGuid(); this.From = new Compact64bitInt(0x0); this.To = new Compact64bitInt(0x5D); } /// <summary> /// Gets or sets a GUID (16 bytes) that specifies the data element. /// </summary> public Guid CellKnowledgeRangeGUID { get; set; } /// <summary> /// Gets or sets a compact unit64 that specifies the starting sequence number. /// </summary> public Compact64bitInt From { get; set; } /// <summary> /// Gets or sets a compact unit64 that specifies the ending sequence number. /// </summary> public Compact64bitInt To { get; set; } /// <summary> /// This method is used to deserialize the items of the cell knowledge range from the byte array. /// </summary> /// <param name="byteArray">Specify the byte array.</param> /// <param name="currentIndex">Specify the start index from the byte array.</param> /// <param name="lengthOfItems">Specify the current length of items in the cell knowledge range.</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; byte[] temp = new byte[16]; Array.Copy(byteArray, index, temp, 0, 16); this.CellKnowledgeRangeGUID = new Guid(temp); index += 16; this.From = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); this.To = BasicObject.Parse<Compact64bitInt>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "CellKnowledgeRange", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// This method is used to serialize the items of the cell knowledge range to the byte list. /// </summary> /// <param name="byteList">Specify the byte list which stores the information of cell knowledge range.</param> /// <returns>Return the length in byte of the items in cell knowledge range.</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { int itemsIndex = byteList.Count; byteList.AddRange(this.CellKnowledgeRangeGUID.ToByteArray()); byteList.AddRange(this.From.SerializeToByteList()); byteList.AddRange(this.To.SerializeToByteList()); return byteList.Count - itemsIndex; } } /// <summary> /// This class specifies cell knowledge entry. /// </summary> public class CellKnowledgeEntry : StreamObject { /// <summary> /// Initializes a new instance of the CellKnowledgeEntry class. /// </summary> public CellKnowledgeEntry() : base(StreamObjectTypeHeaderStart.CellKnowledgeEntry) { this.SerialNumber = new SerialNumber(System.Guid.NewGuid(), SequenceNumberGenerator.GetCurrentSerialNumber()); } /// <summary> /// Gets or sets a serial number that specifies the cell. /// </summary> public SerialNumber SerialNumber { get; set; } /// <summary> /// This method is used to deserialize the items of the cell knowledge entry from the byte array. /// </summary> /// <param name="byteArray">Specify the byte array.</param> /// <param name="currentIndex">Specify the start index from the byte array.</param> /// <param name="lengthOfItems">Specify the current length of items in the cell knowledge entry.</param> protected override void DeserializeItemsFromByteArray(byte[] byteArray, ref int currentIndex, int lengthOfItems) { int index = currentIndex; this.SerialNumber = BasicObject.Parse<SerialNumber>(byteArray, ref index); if (index - currentIndex != lengthOfItems) { throw new StreamObjectParseErrorException(currentIndex, "CellKnowledgeEntry", "Stream object over-parse error", null); } currentIndex = index; } /// <summary> /// This method is used to serialize the items of the cell knowledge entry to the byte list. /// </summary> /// <param name="byteList">Specify the byte list which stores the information of cell knowledge entry.</param> /// <returns>Return the length in byte of the items in cell knowledge entry.</returns> protected override int SerializeItemsToByteList(List<byte> byteList) { int itemsIndex = byteList.Count; byteList.AddRange(this.SerialNumber.SerializeToByteList()); return byteList.Count - itemsIndex; } } }
using System.Linq; using System.Text; namespace Irony.Parsing.Construction { // Methods constructing LALR automaton. // See _about_parser_construction.txt file in this folder for important comments internal class ParserDataBuilder { private readonly Grammar _grammar; private readonly LanguageData _language; private readonly ParserStateHash _stateHash = new ParserStateHash(); private ParserData _data; internal ParserDataBuilder(LanguageData language) { _language = language; _grammar = _language.Grammar; } public void Build() { _stateHash.Clear(); _data = _language.ParserData; CreateParserStates(); var itemsNeedLookaheads = GetReduceItemsInInadequateState(); ComputeTransitions(itemsNeedLookaheads); ComputeLookaheads(itemsNeedLookaheads); ComputeStatesExpectedTerminals(); ComputeConflicts(); ApplyHints(); HandleUnresolvedConflicts(); CreateRemainingReduceActions(); //Create error action - if it is not created yet by some hint or custom code if (_data.ErrorAction == null) _data.ErrorAction = new ErrorRecoveryParserAction(); } //method internal static StringSet ComputeGroupedExpectedSetForState(Grammar grammar, ParserState state) { var terms = new TerminalSet(); terms.UnionWith(state.ExpectedTerminals); var result = new StringSet(); //Eliminate no-report terminals foreach (var group in grammar.TermReportGroups) if (group.GroupType == TermReportGroupType.DoNotReport) terms.ExceptWith(group.Terminals); //Add normal and operator groups foreach (var group in grammar.TermReportGroups) if ((group.GroupType == TermReportGroupType.Normal || group.GroupType == TermReportGroupType.Operator) && terms.Overlaps(group.Terminals)) { result.Add(group.Alias); terms.ExceptWith(group.Terminals); } //Add remaining terminals "as is" foreach (var terminal in terms) result.Add(terminal.ErrorAlias); return result; } #region Creating parser states private void CreateParserStates() { var grammarData = _language.GrammarData; //1. Base automaton: create states for main augmented root for the grammar _data.InitialState = CreateInitialState(grammarData.AugmentedRoot); ExpandParserStateList(0); CreateAcceptAction(_data.InitialState, grammarData.AugmentedRoot); //2. Expand automaton: add parser states from additional roots foreach (var augmRoot in grammarData.AugmentedSnippetRoots) { var initialState = CreateInitialState(augmRoot); ExpandParserStateList(_data.States.Count - 1); //start with just added state - it is the last state in the list CreateAcceptAction(initialState, augmRoot); } } private void CreateAcceptAction(ParserState initialState, NonTerminal augmentedRoot) { var root = augmentedRoot.Productions[0].RValues[0]; var shiftAction = initialState.Actions[root] as ShiftParserAction; var shiftOverRootState = shiftAction.NewState; shiftOverRootState.Actions[_grammar.Eof] = new AcceptParserAction(); } private ParserState CreateInitialState(NonTerminal augmentedRoot) { //for an augmented root there is an initial production "Root' -> .Root"; so we need the LR0 item at 0 index var iniItemSet = new LR0ItemSet(); iniItemSet.Add(augmentedRoot.Productions[0].LR0Items[0]); var initialState = FindOrCreateState(iniItemSet); var rootNt = augmentedRoot.Productions[0].RValues[0] as NonTerminal; _data.InitialStates[rootNt] = initialState; return initialState; } private void ExpandParserStateList(int initialIndex) { // Iterate through states (while new ones are created) and create shift transitions and new states for (var index = initialIndex; index < _data.States.Count; index++) { var state = _data.States[index]; //Get all possible shifts foreach (var term in state.BuilderData.ShiftTerms) { var shiftItems = state.BuilderData.ShiftItems.SelectByCurrent(term); //Get set of shifted cores and find/create target state var shiftedCoreItems = shiftItems.GetShiftedCores(); var newState = FindOrCreateState(shiftedCoreItems); //Create shift action var newAction = new ShiftParserAction(term, newState); state.Actions[term] = newAction; //Link items in old/new states foreach (var shiftItem in shiftItems) { shiftItem.ShiftedItem = newState.BuilderData.AllItems.FindByCore(shiftItem.Core.ShiftedItem); } //foreach shiftItem } //foreach term } //for index } //method private ParserState FindOrCreateState(LR0ItemSet coreItems) { var key = ComputeLR0ItemSetKey(coreItems); ParserState state; if (_stateHash.TryGetValue(key, out state)) return state; //create new state state = new ParserState("S" + _data.States.Count); state.BuilderData = new ParserStateData(state, coreItems); _data.States.Add(state); _stateHash[key] = state; return state; } #endregion #region Compute transitions, lookbacks, lookaheads //We compute only transitions that are really needed to compute lookaheads in inadequate states. // We start with reduce items in inadequate state and find their lookbacks - this is initial list of transitions. // Then for each transition in the list we check if it has items with nullable tails; for those items we compute // lookbacks - these are new or already existing transitons - and so on, we repeat the operation until no new transitions // are created. private void ComputeTransitions(LRItemSet forItems) { var newItemsNeedLookbacks = forItems; while (newItemsNeedLookbacks.Count > 0) { var newTransitions = CreateLookbackTransitions(newItemsNeedLookbacks); newItemsNeedLookbacks = SelectNewItemsThatNeedLookback(newTransitions); } } private LRItemSet SelectNewItemsThatNeedLookback(TransitionList transitions) { //Select items with nullable tails that don't have lookbacks yet var items = new LRItemSet(); foreach (var trans in transitions) foreach (var item in trans.Items) if (item.Core.TailIsNullable && item.Lookbacks.Count == 0) //only if it does not have lookbacks yet items.Add(item); return items; } private LRItemSet GetReduceItemsInInadequateState() { var result = new LRItemSet(); foreach (var state in _data.States) { if (state.BuilderData.IsInadequate) result.UnionWith(state.BuilderData.ReduceItems); } return result; } private TransitionList CreateLookbackTransitions(LRItemSet sourceItems) { var newTransitions = new TransitionList(); //Build set of initial cores - this is optimization for performance //We need to find all initial items in all states that shift into one of sourceItems // Each such initial item would have the core from the "initial" cores set that we build from source items. var iniCores = new LR0ItemSet(); foreach (var sourceItem in sourceItems) iniCores.Add(sourceItem.Core.Production.LR0Items[0]); //find foreach (var state in _data.States) { foreach (var iniItem in state.BuilderData.InitialItems) { if (!iniCores.Contains(iniItem.Core)) continue; var iniItemNt = iniItem.Core.Production.LValue; // iniItem's non-terminal (left side of production) Transition lookback = null; // local var for lookback - transition over iniItemNt var currItem = iniItem; // iniItem is initial item for all currItem's in the shift chain. while (currItem != null) { if (sourceItems.Contains(currItem)) { // We create transitions lazily, only when we actually need them. Check if we have iniItem's transition // in local variable; if not, get it from state's transitions table; if not found, create it. if (lookback == null && !state.BuilderData.Transitions.TryGetValue(iniItemNt, out lookback)) { lookback = new Transition(state, iniItemNt); newTransitions.Add(lookback); } //Now for currItem, either add trans to Lookbacks, or "include" it into currItem.Transition // We need lookbacks ONLY for final items; for non-Final items we need proper Include lists on transitions if (currItem.Core.IsFinal) currItem.Lookbacks.Add(lookback); else // if (currItem.Transition != null) // Note: looks like checking for currItem.Transition is redundant - currItem is either: // - Final - always the case for the first run of this method; // - it has a transition after the first run, due to the way we select sourceItems list // in SelectNewItemsThatNeedLookback (by transitions) currItem.Transition.Include(lookback); } //if //move to next item currItem = currItem.ShiftedItem; } //while } //foreach iniItem } //foreach state return newTransitions; } private void ComputeLookaheads(LRItemSet forItems) { foreach (var reduceItem in forItems) { // Find all source states - those that contribute lookaheads var sourceStates = new ParserStateSet(); foreach (var lookbackTrans in reduceItem.Lookbacks) { sourceStates.Add(lookbackTrans.ToState); sourceStates.UnionWith(lookbackTrans.ToState.BuilderData.ReadStateSet); foreach (var includeTrans in lookbackTrans.Includes) { sourceStates.Add(includeTrans.ToState); sourceStates.UnionWith(includeTrans.ToState.BuilderData.ReadStateSet); } //foreach includeTrans } //foreach lookbackTrans //Now merge all shift terminals from all source states foreach (var state in sourceStates) reduceItem.Lookaheads.UnionWith(state.BuilderData.ShiftTerminals); //Remove SyntaxError - it is pseudo terminal if (reduceItem.Lookaheads.Contains(_grammar.SyntaxError)) reduceItem.Lookaheads.Remove(_grammar.SyntaxError); //Sanity check if (reduceItem.Lookaheads.Count == 0) _language.Errors.Add(GrammarErrorLevel.InternalError, reduceItem.State, "Reduce item '{0}' in state {1} has no lookaheads.", reduceItem.Core, reduceItem.State); } //foreach reduceItem } //method #endregion #region Analyzing and resolving conflicts private void ComputeConflicts() { foreach (var state in _data.States) { if (!state.BuilderData.IsInadequate) continue; //first detect conflicts var stateData = state.BuilderData; stateData.Conflicts.Clear(); var allLkhds = new BnfTermSet(); //reduce/reduce -------------------------------------------------------------------------------------- foreach (var item in stateData.ReduceItems) { foreach (var lkh in item.Lookaheads) { if (allLkhds.Contains(lkh)) state.BuilderData.Conflicts.Add(lkh); allLkhds.Add(lkh); } //foreach lkh } //foreach item //shift/reduce --------------------------------------------------------------------------------------- foreach (var term in stateData.ShiftTerminals) if (allLkhds.Contains(term)) { stateData.Conflicts.Add(term); } } } //method private void ApplyHints() { foreach (var state in _data.States) { var stateData = state.BuilderData; //Add automatic precedence hints if (stateData.Conflicts.Count > 0) foreach (var conflict in stateData.Conflicts.ToList()) if (conflict.Flags.IsSet(TermFlags.IsOperator)) { //Find any reduce item with this lookahead and add PrecedenceHint var reduceItem = stateData.ReduceItems.SelectByLookahead(conflict).First(); var precHint = new PrecedenceHint(); reduceItem.Core.Hints.Add(precHint); } // Apply (activate) hints - these should resolve conflicts as well foreach (var item in state.BuilderData.AllItems) foreach (var hint in item.Core.Hints) hint.Apply(_language, item); } //foreach } //method //Resolve to default actions private void HandleUnresolvedConflicts() { foreach (var state in _data.States) { if (state.BuilderData.Conflicts.Count == 0) continue; var shiftReduceConflicts = state.BuilderData.GetShiftReduceConflicts(); var reduceReduceConflicts = state.BuilderData.GetReduceReduceConflicts(); var stateData = state.BuilderData; if (shiftReduceConflicts.Count > 0) _language.Errors.Add(GrammarErrorLevel.Conflict, state, Resources.ErrSRConflict, state, shiftReduceConflicts.ToString()); if (reduceReduceConflicts.Count > 0) _language.Errors.Add(GrammarErrorLevel.Conflict, state, Resources.ErrRRConflict, state, reduceReduceConflicts.ToString()); //Create default actions for these conflicts. For shift-reduce, default action is shift, and shift action already // exist for all shifts from the state, so we don't need to do anything, only report it //For reduce-reduce create reduce actions for the first reduce item (whatever comes first in the set). foreach (var conflict in reduceReduceConflicts) { var reduceItems = stateData.ReduceItems.SelectByLookahead(conflict); var firstProd = reduceItems.First().Core.Production; var action = new ReduceParserAction(firstProd); state.Actions[conflict] = action; } //stateData.Conflicts.Clear(); -- do not clear them, let the set keep the auto-resolved conflicts, may find more use for this later } } #endregion #region final actions: creating remaining reduce actions, computing expected terminals, cleaning up state data //Create reduce actions for states with a single reduce item (and no shifts) private void CreateRemainingReduceActions() { foreach (var state in _data.States) { if (state.DefaultAction != null) continue; var stateData = state.BuilderData; if (stateData.ShiftItems.Count == 0 && stateData.ReduceItems.Count == 1) { state.DefaultAction = ReduceParserAction.Create(stateData.ReduceItems.First().Core.Production); continue; //next state; if we have default reduce action, we don't need to fill actions dictionary for lookaheads } //create actions foreach (var item in state.BuilderData.ReduceItems) { var action = ReduceParserAction.Create(item.Core.Production); foreach (var lkh in item.Lookaheads) { if (state.Actions.ContainsKey(lkh)) continue; state.Actions[lkh] = action; } } //foreach item } //foreach state } //Note that for states with a single reduce item the result is empty private void ComputeStatesExpectedTerminals() { foreach (var state in _data.States) { state.ExpectedTerminals.UnionWith(state.BuilderData.ShiftTerminals); //Add lookaheads from reduce items foreach (var reduceItem in state.BuilderData.ReduceItems) state.ExpectedTerminals.UnionWith(reduceItem.Lookaheads); RemoveTerminals(state.ExpectedTerminals, _grammar.SyntaxError, _grammar.Eof); } //foreach state } private void RemoveTerminals(TerminalSet terms, params Terminal[] termsToRemove) { foreach (var termToRemove in termsToRemove) if (terms.Contains(termToRemove)) terms.Remove(termToRemove); } public void CleanupStateData() { foreach (var state in _data.States) state.ClearData(); } #endregion #region Utilities: ComputeLR0ItemSetKey //Parser states are distinguished by the subset of kernel LR0 items. // So when we derive new LR0-item list by shift operation, // we need to find out if we have already a state with the same LR0Item list. // We do it by looking up in a state hash by a key - [LR0 item list key]. // Each list's key is a concatenation of items' IDs separated by ','. // Before producing the key for a list, the list must be sorted; // thus we garantee one-to-one correspondence between LR0Item sets and keys. // And of course, we count only kernel items (with dot NOT in the first position). public static string ComputeLR0ItemSetKey(LR0ItemSet items) { if (items.Count == 0) return string.Empty; //Copy non-initial items to separate list, and then sort it var itemList = new LR0ItemList(); foreach (var item in items) itemList.Add(item); //quick shortcut if (itemList.Count == 1) return itemList[0].ID.ToString(); itemList.Sort(CompareLR0Items); //Sort by ID //now build the key var sb = new StringBuilder(100); foreach (var item in itemList) { sb.Append(item.ID); sb.Append(","); } //foreach return sb.ToString(); } private static int CompareLR0Items(LR0Item x, LR0Item y) { if (x.ID < y.ID) return -1; if (x.ID == y.ID) return 0; return 1; } #endregion #region comments // Computes set of expected terms in a parser state. While there may be extended list of symbols expected at some point, // we want to reorganize and reduce it. For example, if the current state expects all arithmetic operators as an input, // it would be better to not list all operators (+, -, *, /, etc) but simply put "operator" covering them all. // To achieve this grammar writer can group operators (or any other terminals) into named groups using Grammar's methods // AddTermReportGroup, AddNoReportGroup etc. Then instead of reporting each operator separately, Irony would include // a single "group name" to represent them all. // The "expected report set" is not computed during parser construction (it would bite considerable time), but on demand during parsing, // when error is detected and the expected set is actually needed for error message. // Multi-threading concerns. When used in multi-threaded environment (web server), the LanguageData would be shared in // application-wide cache to avoid rebuilding the parser data on every request. The LanguageData is immutable, except // this one case - the expected sets are constructed late by CoreParser on the when-needed basis. // We don't do any locking here, just compute the set and on return from this function the state field is assigned. // We assume that this field assignment is an atomic, concurrency-safe operation. The worst thing that might happen // is "double-effort" when two threads start computing the same set around the same time, and the last one to finish would // leave its result in the state field. #endregion } //class } //namespace
using System; using Microsoft.Xna.Framework; using VelcroPhysics.Collision.Shapes; using VelcroPhysics.Dynamics; using VelcroPhysics.Dynamics.Joints; using VelcroPhysics.Factories; using VelcroPhysics.MonoGame.Samples.Testbed.Framework; using VelcroPhysics.Shared; using VelcroPhysics.Tools.PathGenerator; using VelcroPhysics.Utilities; namespace VelcroPhysics.MonoGame.Samples.Testbed.Tests { public class SerializationTest : Test { private bool _save = true; private float _time; private SerializationTest() { Body ground = BodyFactory.CreateEdge(World, new Vector2(-20, 0), new Vector2(20, 0)); //Friction and distance joint { Body bodyA = BodyFactory.CreateCircle(World, 1, 1.5f, new Vector2(10, 25)); bodyA.BodyType = BodyType.Dynamic; Body bodyB = BodyFactory.CreateRectangle(World, 1, 1, 1, new Vector2(-1, 25)); bodyB.BodyType = BodyType.Dynamic; FrictionJoint frictionJoint = JointFactory.CreateFrictionJoint(World, bodyB, ground, Vector2.Zero); frictionJoint.CollideConnected = true; frictionJoint.MaxForce = 100; JointFactory.CreateDistanceJoint(World, bodyA, bodyB); } //Wheel joint { Vertices vertices = new Vertices(6); vertices.Add(new Vector2(-1.5f, -0.5f)); vertices.Add(new Vector2(1.5f, -0.5f)); vertices.Add(new Vector2(1.5f, 0.0f)); vertices.Add(new Vector2(0.0f, 0.9f)); vertices.Add(new Vector2(-1.15f, 0.9f)); vertices.Add(new Vector2(-1.5f, 0.2f)); Body carBody = BodyFactory.CreatePolygon(World, vertices, 1, new Vector2(0, 1)); carBody.BodyType = BodyType.Dynamic; Body wheel1 = BodyFactory.CreateCircle(World, 0.4f, 1, new Vector2(-1.0f, 0.35f)); wheel1.BodyType = BodyType.Dynamic; wheel1.Friction = 0.9f; Body wheel2 = BodyFactory.CreateCircle(World, 0.4f, 1, new Vector2(1.0f, 0.4f)); wheel2.BodyType = BodyType.Dynamic; wheel2.Friction = 0.9f; Vector2 axis = new Vector2(0.0f, 1.0f); WheelJoint spring1 = JointFactory.CreateWheelJoint(World, carBody, wheel1, axis); spring1.MotorSpeed = 0.0f; spring1.MaxMotorTorque = 20.0f; spring1.MotorEnabled = true; spring1.Frequency = 4; spring1.DampingRatio = 0.7f; WheelJoint spring2 = JointFactory.CreateWheelJoint(World, carBody, wheel2, axis); spring2.MotorSpeed = 0.0f; spring2.MaxMotorTorque = 10.0f; spring2.MotorEnabled = false; spring2.Frequency = 4; spring2.DampingRatio = 0.7f; } //Prismatic joint { Body body = BodyFactory.CreateRectangle(World, 2, 2, 5, new Vector2(-10.0f, 10.0f)); body.BodyType = BodyType.Dynamic; body.Rotation = 0.5f * Settings.Pi; Vector2 axis = new Vector2(2.0f, 1.0f); axis.Normalize(); PrismaticJoint joint = JointFactory.CreatePrismaticJoint(World, ground, body, Vector2.Zero, axis); joint.MotorSpeed = 5.0f; joint.MaxMotorForce = 1000.0f; joint.MotorEnabled = true; joint.LowerLimit = -10.0f; joint.UpperLimit = 20.0f; joint.LimitEnabled = true; } // Pulley joint { Body body1 = BodyFactory.CreateRectangle(World, 2, 4, 5, new Vector2(-10.0f, 16.0f)); body1.BodyType = BodyType.Dynamic; Body body2 = BodyFactory.CreateRectangle(World, 2, 4, 5, new Vector2(10.0f, 16.0f)); body2.BodyType = BodyType.Dynamic; Vector2 anchor1 = new Vector2(-10.0f, 16.0f + 2.0f); Vector2 anchor2 = new Vector2(10.0f, 16.0f + 2.0f); Vector2 worldAnchor1 = new Vector2(-10.0f, 16.0f + 2.0f + 12.0f); Vector2 worldAnchor2 = new Vector2(10.0f, 16.0f + 2.0f + 12.0f); JointFactory.CreatePulleyJoint(World, body1, body2, anchor1, anchor2, worldAnchor1, worldAnchor2, 1.5f, true); } //Revolute joint { Body ball = BodyFactory.CreateCircle(World, 3.0f, 5.0f, new Vector2(5.0f, 30.0f)); ball.BodyType = BodyType.Dynamic; Body polygonBody = BodyFactory.CreateRectangle(World, 20, 0.4f, 2, new Vector2(10, 10)); polygonBody.BodyType = BodyType.Dynamic; polygonBody.IsBullet = true; RevoluteJoint joint = JointFactory.CreateRevoluteJoint(World, ground, polygonBody, new Vector2(10, 0)); joint.LowerLimit = -0.25f * Settings.Pi; joint.UpperLimit = 0.0f * Settings.Pi; joint.LimitEnabled = true; } //Weld joint { PolygonShape shape = new PolygonShape(PolygonUtils.CreateRectangle(0.5f, 0.125f), 20); Body prevBody = ground; for (int i = 0; i < 10; ++i) { Body body = BodyFactory.CreateBody(World); body.BodyType = BodyType.Dynamic; body.Position = new Vector2(-14.5f + 1.0f * i, 5.0f); body.CreateFixture(shape); Vector2 anchor = new Vector2(0.5f, 0); if (i == 0) anchor = new Vector2(-15f, 5); JointFactory.CreateWeldJoint(World, prevBody, body, anchor, new Vector2(-0.5f, 0)); prevBody = body; } } //Rope joint { LinkFactory.CreateChain(World, new Vector2(-10, 10), new Vector2(-20, 10), 0.1f, 0.5f, 10, 0.1f, true); } //Angle joint { Body fA = BodyFactory.CreateRectangle(World, 4, 4, 1, new Vector2(-5, 4)); fA.BodyType = BodyType.Dynamic; fA.Rotation = (float)(Math.PI / 3); Body fB = BodyFactory.CreateRectangle(World, 4, 4, 1, new Vector2(5, 4)); fB.BodyType = BodyType.Dynamic; AngleJoint joint = new AngleJoint(fA, fB); joint.TargetAngle = (float)Math.PI / 2; World.AddJoint(joint); } //Motor joint { Body body = BodyFactory.CreateRectangle(World, 4, 1, 2, new Vector2(0, 35)); body.BodyType = BodyType.Dynamic; body.Friction = 0.6f; MotorJoint motorJoint = JointFactory.CreateMotorJoint(World, ground, body); motorJoint.MaxForce = 1000.0f; motorJoint.MaxTorque = 1000.0f; motorJoint.LinearOffset = new Vector2(0, 35); motorJoint.AngularOffset = (float)(Math.PI / 3f); } } public override void Update(GameSettings settings, GameTime gameTime) { _time += gameTime.ElapsedGameTime.Milliseconds; if (_time >= 300) { _time = 0; //if (_save) //{ // WorldSerializer.Serialize(World, "out.xml"); //} //else //{ // World = WorldSerializer.Deserialize("out.xml"); // Initialize(); //To initialize the debug view //} _save = !_save; } base.Update(settings, gameTime); } internal static Test Create() { return new SerializationTest(); } } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using YamlDotNet.Core.Tokens; using MappingStyle = YamlDotNet.Core.Events.MappingStyle; using ParsingEvent = YamlDotNet.Core.Events.ParsingEvent; using SequenceStyle = YamlDotNet.Core.Events.SequenceStyle; namespace YamlDotNet.Core { /// <summary> /// Parses YAML streams. /// </summary> public class Parser : IParser { private readonly Stack<ParserState> states = new Stack<ParserState>(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private ParserState state; private readonly Scanner scanner; private ParsingEvent current; private Token currentToken; private Token GetCurrentToken() { if (currentToken == null) { while (scanner.InternalMoveNext()) { currentToken = scanner.Current; var commentToken = currentToken as Comment; if (commentToken != null) { pendingEvents.Enqueue(new Events.Comment(commentToken.Value, commentToken.IsInline, commentToken.Start, commentToken.End)); } else { break; } } } return currentToken; } /// <summary> /// Initializes a new instance of the <see cref="Parser"/> class. /// </summary> /// <param name="input">The input where the YAML stream is to be read.</param> public Parser(TextReader input) : this(new Scanner(input)) { } /// <summary> /// Initializes a new instance of the <see cref="Parser"/> class. /// </summary> public Parser(Scanner scanner) { this.scanner = scanner; } /// <summary> /// Gets the current event. /// </summary> public ParsingEvent Current { get { return current; } } private readonly Queue<Events.ParsingEvent> pendingEvents = new Queue<Events.ParsingEvent>(); /// <summary> /// Moves to the next event. /// </summary> /// <returns>Returns true if there are more events available, otherwise returns false.</returns> public bool MoveNext() { // No events after the end of the stream or error. if (state == ParserState.StreamEnd) { current = null; return false; } else if (pendingEvents.Count == 0) { // Generate the next event. pendingEvents.Enqueue(StateMachine()); } current = pendingEvents.Dequeue(); return true; } private ParsingEvent StateMachine() { switch (state) { case ParserState.StreamStart: return ParseStreamStart(); case ParserState.ImplicitDocumentStart: return ParseDocumentStart(true); case ParserState.DocumentStart: return ParseDocumentStart(false); case ParserState.DocumentContent: return ParseDocumentContent(); case ParserState.DocumentEnd: return ParseDocumentEnd(); case ParserState.BlockNode: return ParseNode(true, false); case ParserState.BlockNodeOrIndentlessSequence: return ParseNode(true, true); case ParserState.FlowNode: return ParseNode(false, false); case ParserState.BlockSequenceFirstEntry: return ParseBlockSequenceEntry(true); case ParserState.BlockSequenceEntry: return ParseBlockSequenceEntry(false); case ParserState.IndentlessSequenceEntry: return ParseIndentlessSequenceEntry(); case ParserState.BlockMappingFirstKey: return ParseBlockMappingKey(true); case ParserState.BlockMappingKey: return ParseBlockMappingKey(false); case ParserState.BlockMappingValue: return ParseBlockMappingValue(); case ParserState.FlowSequenceFirstEntry: return ParseFlowSequenceEntry(true); case ParserState.FlowSequenceEntry: return ParseFlowSequenceEntry(false); case ParserState.FlowSequenceEntryMappingKey: return ParseFlowSequenceEntryMappingKey(); case ParserState.FlowSequenceEntryMappingValue: return ParseFlowSequenceEntryMappingValue(); case ParserState.FlowSequenceEntryMappingEnd: return ParseFlowSequenceEntryMappingEnd(); case ParserState.FlowMappingFirstKey: return ParseFlowMappingKey(true); case ParserState.FlowMappingKey: return ParseFlowMappingKey(false); case ParserState.FlowMappingValue: return ParseFlowMappingValue(false); case ParserState.FlowMappingEmptyValue: return ParseFlowMappingValue(true); default: Debug.Assert(false, "Invalid state"); // Invalid state. throw new InvalidOperationException(); } } private void Skip() { if (currentToken != null) { currentToken = null; scanner.ConsumeCurrent(); } } /// <summary> /// Parse the production: /// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END /// ************ /// </summary> private ParsingEvent ParseStreamStart() { StreamStart streamStart = GetCurrentToken() as StreamStart; if (streamStart == null) { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "Did not find expected <stream-start>."); } Skip(); state = ParserState.ImplicitDocumentStart; return new Events.StreamStart(streamStart.Start, streamStart.End); } /// <summary> /// Parse the productions: /// implicit_document ::= block_node DOCUMENT-END* /// * /// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* /// ************************* /// </summary> private ParsingEvent ParseDocumentStart(bool isImplicit) { // Parse extra document end indicators. if (!isImplicit) { while (GetCurrentToken() is DocumentEnd) { Skip(); } } // Parse an isImplicit document. if (isImplicit && !(GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is DocumentStart || GetCurrentToken() is StreamEnd)) { TagDirectiveCollection directives = new TagDirectiveCollection(); ProcessDirectives(directives); states.Push(ParserState.DocumentEnd); state = ParserState.BlockNode; return new Events.DocumentStart(null, directives, true, GetCurrentToken().Start, GetCurrentToken().End); } // Parse an explicit document. else if (!(GetCurrentToken() is StreamEnd)) { Mark start = GetCurrentToken().Start; TagDirectiveCollection directives = new TagDirectiveCollection(); VersionDirective versionDirective = ProcessDirectives(directives); var current = GetCurrentToken(); if (!(current is DocumentStart)) { throw new SemanticErrorException(current.Start, current.End, "Did not find expected <document start>."); } states.Push(ParserState.DocumentEnd); state = ParserState.DocumentContent; ParsingEvent evt = new Events.DocumentStart(versionDirective, directives, false, start, current.End); Skip(); return evt; } // Parse the stream end. else { state = ParserState.StreamEnd; ParsingEvent evt = new Events.StreamEnd(GetCurrentToken().Start, GetCurrentToken().End); // Do not call skip here because that would throw an exception if (scanner.InternalMoveNext()) { throw new InvalidOperationException("The scanner should contain no more tokens."); } return evt; } } /// <summary> /// Parse directives. /// </summary> private VersionDirective ProcessDirectives(TagDirectiveCollection tags) { VersionDirective version = null; bool hasOwnDirectives = false; while (true) { VersionDirective currentVersion; TagDirective tag; if ((currentVersion = GetCurrentToken() as VersionDirective) != null) { if (version != null) { throw new SemanticErrorException(currentVersion.Start, currentVersion.End, "Found duplicate %YAML directive."); } if (currentVersion.Version.Major != Constants.MajorVersion || currentVersion.Version.Minor != Constants.MinorVersion) { throw new SemanticErrorException(currentVersion.Start, currentVersion.End, "Found incompatible YAML document."); } version = currentVersion; hasOwnDirectives = true; } else if ((tag = GetCurrentToken() as TagDirective) != null) { if (tags.Contains(tag.Handle)) { throw new SemanticErrorException(tag.Start, tag.End, "Found duplicate %TAG directive."); } tags.Add(tag); hasOwnDirectives = true; } else { break; } Skip(); } AddTagDirectives(tags, Constants.DefaultTagDirectives); if (hasOwnDirectives) { tagDirectives.Clear(); } AddTagDirectives(tagDirectives, tags); return version; } private static void AddTagDirectives(TagDirectiveCollection directives, IEnumerable<TagDirective> source) { foreach (var directive in source) { if (!directives.Contains(directive)) { directives.Add(directive); } } } /// <summary> /// Parse the productions: /// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* /// *********** /// </summary> private ParsingEvent ParseDocumentContent() { if ( GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is DocumentStart || GetCurrentToken() is DocumentEnd || GetCurrentToken() is StreamEnd ) { state = states.Pop(); return ProcessEmptyScalar(scanner.CurrentPosition); } else { return ParseNode(true, false); } } /// <summary> /// Generate an empty scalar event. /// </summary> private static ParsingEvent ProcessEmptyScalar(Mark position) { return new Events.Scalar(null, null, string.Empty, ScalarStyle.Plain, true, false, position, position); } /// <summary> /// Parse the productions: /// block_node_or_indentless_sequence ::= /// ALIAS /// ***** /// | properties (block_content | indentless_block_sequence)? /// ********** * /// | block_content | indentless_block_sequence /// * /// block_node ::= ALIAS /// ***** /// | properties block_content? /// ********** * /// | block_content /// * /// flow_node ::= ALIAS /// ***** /// | properties flow_content? /// ********** * /// | flow_content /// * /// properties ::= TAG ANCHOR? | ANCHOR TAG? /// ************************* /// block_content ::= block_collection | flow_collection | SCALAR /// ****** /// flow_content ::= flow_collection | SCALAR /// ****** /// </summary> private ParsingEvent ParseNode(bool isBlock, bool isIndentlessSequence) { AnchorAlias alias = GetCurrentToken() as AnchorAlias; if (alias != null) { state = states.Pop(); ParsingEvent evt = new Events.AnchorAlias(alias.Value, alias.Start, alias.End); Skip(); return evt; } Mark start = GetCurrentToken().Start; Anchor anchor = null; Tag tag = null; // The anchor and the tag can be in any order. This loop repeats at most twice. while (true) { if (anchor == null && (anchor = GetCurrentToken() as Anchor) != null) { Skip(); } else if (tag == null && (tag = GetCurrentToken() as Tag) != null) { Skip(); } else { break; } } string tagName = null; if (tag != null) { if (string.IsNullOrEmpty(tag.Handle)) { tagName = tag.Suffix; } else if (tagDirectives.Contains(tag.Handle)) { tagName = string.Concat(tagDirectives[tag.Handle].Prefix, tag.Suffix); } else { throw new SemanticErrorException(tag.Start, tag.End, "While parsing a node, find undefined tag handle."); } } if (string.IsNullOrEmpty(tagName)) { tagName = null; } string anchorName = anchor != null ? string.IsNullOrEmpty(anchor.Value) ? null : anchor.Value : null; bool isImplicit = string.IsNullOrEmpty(tagName); if (isIndentlessSequence && GetCurrentToken() is BlockEntry) { state = ParserState.IndentlessSequenceEntry; return new Events.SequenceStart( anchorName, tagName, isImplicit, SequenceStyle.Block, start, GetCurrentToken().End ); } else { Scalar scalar = GetCurrentToken() as Scalar; if (scalar != null) { bool isPlainImplicit = false; bool isQuotedImplicit = false; if ((scalar.Style == ScalarStyle.Plain && tagName == null) || tagName == Constants.DefaultHandle) { isPlainImplicit = true; } else if (tagName == null) { isQuotedImplicit = true; } state = states.Pop(); ParsingEvent evt = new Events.Scalar(anchorName, tagName, scalar.Value, scalar.Style, isPlainImplicit, isQuotedImplicit, start, scalar.End); Skip(); return evt; } FlowSequenceStart flowSequenceStart = GetCurrentToken() as FlowSequenceStart; if (flowSequenceStart != null) { state = ParserState.FlowSequenceFirstEntry; return new Events.SequenceStart(anchorName, tagName, isImplicit, SequenceStyle.Flow, start, flowSequenceStart.End); } FlowMappingStart flowMappingStart = GetCurrentToken() as FlowMappingStart; if (flowMappingStart != null) { state = ParserState.FlowMappingFirstKey; return new Events.MappingStart(anchorName, tagName, isImplicit, MappingStyle.Flow, start, flowMappingStart.End); } if (isBlock) { BlockSequenceStart blockSequenceStart = GetCurrentToken() as BlockSequenceStart; if (blockSequenceStart != null) { state = ParserState.BlockSequenceFirstEntry; return new Events.SequenceStart(anchorName, tagName, isImplicit, SequenceStyle.Block, start, blockSequenceStart.End); } BlockMappingStart blockMappingStart = GetCurrentToken() as BlockMappingStart; if (blockMappingStart != null) { state = ParserState.BlockMappingFirstKey; return new Events.MappingStart(anchorName, tagName, isImplicit, MappingStyle.Block, start, GetCurrentToken().End); } } if (anchorName != null || tag != null) { state = states.Pop(); return new Events.Scalar(anchorName, tagName, string.Empty, ScalarStyle.Plain, isImplicit, false, start, GetCurrentToken().End); } var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a node, did not find expected node content."); } } /// <summary> /// Parse the productions: /// implicit_document ::= block_node DOCUMENT-END* /// ************* /// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* /// ************* /// </summary> private ParsingEvent ParseDocumentEnd() { bool isImplicit = true; Mark start = GetCurrentToken().Start; Mark end = start; if (GetCurrentToken() is DocumentEnd) { end = GetCurrentToken().End; Skip(); isImplicit = false; } state = ParserState.DocumentStart; return new Events.DocumentEnd(isImplicit, start, end); } /// <summary> /// Parse the productions: /// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END /// ******************** *********** * ********* /// </summary> private ParsingEvent ParseBlockSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } if (GetCurrentToken() is BlockEntry) { Mark mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is BlockEnd)) { states.Push(ParserState.BlockSequenceEntry); return ParseNode(true, false); } else { state = ParserState.BlockSequenceEntry; return ProcessEmptyScalar(mark); } } else if (GetCurrentToken() is BlockEnd) { state = states.Pop(); ParsingEvent evt = new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End); Skip(); return evt; } else { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a block collection, did not find expected '-' indicator."); } } /// <summary> /// Parse the productions: /// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ /// *********** * /// </summary> private ParsingEvent ParseIndentlessSequenceEntry() { if (GetCurrentToken() is BlockEntry) { Mark mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) { states.Push(ParserState.IndentlessSequenceEntry); return ParseNode(true, false); } else { state = ParserState.IndentlessSequenceEntry; return ProcessEmptyScalar(mark); } } else { state = states.Pop(); return new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End); } } /// <summary> /// Parse the productions: /// block_mapping ::= BLOCK-MAPPING_START /// ******************* /// ((KEY block_node_or_indentless_sequence?)? /// *** * /// (VALUE block_node_or_indentless_sequence?)?)* /// /// BLOCK-END /// ********* /// </summary> private ParsingEvent ParseBlockMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } if (GetCurrentToken() is Key) { Mark mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) { states.Push(ParserState.BlockMappingValue); return ParseNode(true, true); } else { state = ParserState.BlockMappingValue; return ProcessEmptyScalar(mark); } } else if (GetCurrentToken() is BlockEnd) { state = states.Pop(); ParsingEvent evt = new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End); Skip(); return evt; } else { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a block mapping, did not find expected key."); } } /// <summary> /// Parse the productions: /// block_mapping ::= BLOCK-MAPPING_START /// /// ((KEY block_node_or_indentless_sequence?)? /// /// (VALUE block_node_or_indentless_sequence?)?)* /// ***** * /// BLOCK-END /// /// </summary> private ParsingEvent ParseBlockMappingValue() { if (GetCurrentToken() is Value) { Mark mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) { states.Push(ParserState.BlockMappingKey); return ParseNode(true, true); } else { state = ParserState.BlockMappingKey; return ProcessEmptyScalar(mark); } } else { state = ParserState.BlockMappingKey; return ProcessEmptyScalar(GetCurrentToken().Start); } } /// <summary> /// Parse the productions: /// flow_sequence ::= FLOW-SEQUENCE-START /// ******************* /// (flow_sequence_entry FLOW-ENTRY)* /// * ********** /// flow_sequence_entry? /// * /// FLOW-SEQUENCE-END /// ***************** /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// * /// </summary> private ParsingEvent ParseFlowSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } ParsingEvent evt; if (!(GetCurrentToken() is FlowSequenceEnd)) { if (!isFirst) { if (GetCurrentToken() is FlowEntry) { Skip(); } else { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a flow sequence, did not find expected ',' or ']'."); } } if (GetCurrentToken() is Key) { state = ParserState.FlowSequenceEntryMappingKey; evt = new Events.MappingStart(null, null, true, MappingStyle.Flow); Skip(); return evt; } else if (!(GetCurrentToken() is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntry); return ParseNode(false, false); } } state = states.Pop(); evt = new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End); Skip(); return evt; } /// <summary> /// Parse the productions: /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// *** * /// </summary> private ParsingEvent ParseFlowSequenceEntryMappingKey() { if (!(GetCurrentToken() is Value || GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingValue); return ParseNode(false, false); } else { Mark mark = GetCurrentToken().End; Skip(); state = ParserState.FlowSequenceEntryMappingValue; return ProcessEmptyScalar(mark); } } /// <summary> /// Parse the productions: /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// ***** * /// </summary> private ParsingEvent ParseFlowSequenceEntryMappingValue() { if (GetCurrentToken() is Value) { Skip(); if (!(GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingEnd); return ParseNode(false, false); } } state = ParserState.FlowSequenceEntryMappingEnd; return ProcessEmptyScalar(GetCurrentToken().Start); } /// <summary> /// Parse the productions: /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// * /// </summary> private ParsingEvent ParseFlowSequenceEntryMappingEnd() { state = ParserState.FlowSequenceEntry; return new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End); } /// <summary> /// Parse the productions: /// flow_mapping ::= FLOW-MAPPING-START /// ****************** /// (flow_mapping_entry FLOW-ENTRY)* /// * ********** /// flow_mapping_entry? /// ****************** /// FLOW-MAPPING-END /// **************** /// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// * *** * /// </summary> private ParsingEvent ParseFlowMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } if (!(GetCurrentToken() is FlowMappingEnd)) { if (!isFirst) { if (GetCurrentToken() is FlowEntry) { Skip(); } else { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a flow mapping, did not find expected ',' or '}'."); } } if (GetCurrentToken() is Key) { Skip(); if (!(GetCurrentToken() is Value || GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowMappingEnd)) { states.Push(ParserState.FlowMappingValue); return ParseNode(false, false); } else { state = ParserState.FlowMappingValue; return ProcessEmptyScalar(GetCurrentToken().Start); } } else if (!(GetCurrentToken() is FlowMappingEnd)) { states.Push(ParserState.FlowMappingEmptyValue); return ParseNode(false, false); } } state = states.Pop(); ParsingEvent evt = new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End); Skip(); return evt; } /// <summary> /// Parse the productions: /// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// * ***** * /// </summary> private ParsingEvent ParseFlowMappingValue(bool isEmpty) { if (isEmpty) { state = ParserState.FlowMappingKey; return ProcessEmptyScalar(GetCurrentToken().Start); } if (GetCurrentToken() is Value) { Skip(); if (!(GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowMappingEnd)) { states.Push(ParserState.FlowMappingKey); return ParseNode(false, false); } } state = ParserState.FlowMappingKey; return ProcessEmptyScalar(GetCurrentToken().Start); } } }
using System; namespace Axiom.Input { /// <summary> /// Enum containing all the possible keyboard codes. /// </summary> public enum KeyCodes { /// <summary> /// The keyboard code for LButton. /// </summary> LButton , /// <summary> /// The keyboard code for RButton. /// </summary> RButton , /// <summary> /// The keyboard code for Cancel. /// </summary> Cancel , /// <summary> /// The keyboard code for MButton. /// </summary> MButton , /// <summary> /// The keyboard code for XButton1. /// </summary> XButton1 , /// <summary> /// The keyboard code for XButton2. /// </summary> XButton2 , /// <summary> /// The keyboard code for Backspace. /// </summary> Backspace, /// <summary> /// The keyboard code for Tab. /// </summary> Tab , /// <summary> /// The keyboard code for LineFeed. /// </summary> LineFeed , /// <summary> /// The keyboard code for Clear. /// </summary> Clear , /// <summary> /// The keyboard code for Return. /// </summary> Return , /// <summary> /// The keyboard code for Enter. /// </summary> Enter , /// <summary> /// The keyboard code for ShiftKey. /// </summary> ShiftKey , /// <summary> /// The keyboard code for ControlKey. /// </summary> ControlKey , /// <summary> /// The keyboard code for Menu. /// </summary> Menu , /// <summary> /// The keyboard code for Pause. /// </summary> Pause , /// <summary> /// The keyboard code for Capital. /// </summary> Capital , /// <summary> /// The keyboard code for CapsLock. /// </summary> CapsLock , /// <summary> /// The keyboard code for Escape. /// </summary> Escape , /// <summary> /// The keyboard code for Space. /// </summary> Space , /// <summary> /// The keyboard code for Prior. /// </summary> Prior , /// <summary> /// The keyboard code for PageUp. /// </summary> PageUp , /// <summary> /// The keyboard code for Next. /// </summary> Next , /// <summary> /// The keyboard code for PageDown. /// </summary> PageDown , /// <summary> /// The keyboard code for End. /// </summary> End , /// <summary> /// The keyboard code for Home. /// </summary> Home , /// <summary> /// The keyboard code for Left. /// </summary> Left , /// <summary> /// The keyboard code for Up. /// </summary> Up , /// <summary> /// The keyboard code for Right. /// </summary> Right , /// <summary> /// The keyboard code for Down. /// </summary> Down , /// <summary> /// The keyboard code for Select. /// </summary> Select , /// <summary> /// The keyboard code for Print. /// </summary> Print , /// <summary> /// The keyboard code for Execute. /// </summary> Execute , /// <summary> /// The keyboard code for Snapshot. /// </summary> Snapshot , /// <summary> /// The keyboard code for PrintScreen. /// </summary> PrintScreen , /// <summary> /// The keyboard code for Insert. /// </summary> Insert , /// <summary> /// The keyboard code for Delete. /// </summary> Delete , /// <summary> /// The keyboard code for Help. /// </summary> Help , /// <summary> /// The keyboard code for D0. /// </summary> D0 , /// <summary> /// The keyboard code for D1. /// </summary> D1 , /// <summary> /// The keyboard code for D2. /// </summary> D2 , /// <summary> /// The keyboard code for D3. /// </summary> D3 , /// <summary> /// The keyboard code for D4. /// </summary> D4 , /// <summary> /// The keyboard code for D5. /// </summary> D5 , /// <summary> /// The keyboard code for D6. /// </summary> D6 , /// <summary> /// The keyboard code for D7. /// </summary> D7 , /// <summary> /// The keyboard code for D8. /// </summary> D8 , /// <summary> /// The keyboard code for D9. /// </summary> D9 , /// <summary> /// The keyboard code for A. /// </summary> A , /// <summary> /// The keyboard code for B. /// </summary> B , /// <summary> /// The keyboard code for C. /// </summary> C , /// <summary> /// The keyboard code for D. /// </summary> D , /// <summary> /// The keyboard code for E. /// </summary> E , /// <summary> /// The keyboard code for F. /// </summary> F , /// <summary> /// The keyboard code for G. /// </summary> G , /// <summary> /// The keyboard code for H. /// </summary> H , /// <summary> /// The keyboard code for I. /// </summary> I , /// <summary> /// The keyboard code for J. /// </summary> J , /// <summary> /// The keyboard code for K. /// </summary> K , /// <summary> /// The keyboard code for L. /// </summary> L , /// <summary> /// The keyboard code for M. /// </summary> M , /// <summary> /// The keyboard code for N. /// </summary> N , /// <summary> /// The keyboard code for O. /// </summary> O , /// <summary> /// The keyboard code for P. /// </summary> P , /// <summary> /// The keyboard code for Q. /// </summary> Q , /// <summary> /// The keyboard code for R. /// </summary> R , /// <summary> /// The keyboard code for S. /// </summary> S , /// <summary> /// The keyboard code for T. /// </summary> T , /// <summary> /// The keyboard code for U. /// </summary> U , /// <summary> /// The keyboard code for V. /// </summary> V , /// <summary> /// The keyboard code for W. /// </summary> W , /// <summary> /// The keyboard code for X. /// </summary> X , /// <summary> /// The keyboard code for Y. /// </summary> Y , /// <summary> /// The keyboard code for Z. /// </summary> Z , /// <summary> /// The keyboard code for LWin. /// </summary> LWin , /// <summary> /// The keyboard code for RWin. /// </summary> RWin , /// <summary> /// The keyboard code for Apps. /// </summary> Apps , /// <summary> /// The keyboard code for NumPad0. /// </summary> NumPad0 , /// <summary> /// The keyboard code for NumPad1. /// </summary> NumPad1 , /// <summary> /// The keyboard code for NumPad2. /// </summary> NumPad2 , /// <summary> /// The keyboard code for NumPad3. /// </summary> NumPad3 , /// <summary> /// The keyboard code for NumPad4. /// </summary> NumPad4 , /// <summary> /// The keyboard code for NumPad5. /// </summary> NumPad5 , /// <summary> /// The keyboard code for NumPad6. /// </summary> NumPad6 , /// <summary> /// The keyboard code for NumPad7. /// </summary> NumPad7 , /// <summary> /// The keyboard code for NumPad8. /// </summary> NumPad8 , /// <summary> /// The keyboard code for NumPad9. /// </summary> NumPad9 , /// <summary> /// The keyboard code for Multiply. /// </summary> Multiply , /// <summary> /// The keyboard code for Add. /// </summary> Add , /// <summary> /// The keyboard code for Separator. /// </summary> Separator , /// <summary> /// The keyboard code for Subtract. /// </summary> Subtract , /// <summary> /// The keyboard code for Decimal. /// </summary> Decimal , /// <summary> /// The keyboard code for Divide. /// </summary> Divide , /// <summary> /// The keyboard code for F1. /// </summary> F1 , /// <summary> /// The keyboard code for F2. /// </summary> F2 , /// <summary> /// The keyboard code for F3. /// </summary> F3 , /// <summary> /// The keyboard code for F4. /// </summary> F4 , /// <summary> /// The keyboard code for F5. /// </summary> F5 , /// <summary> /// The keyboard code for F6. /// </summary> F6 , /// <summary> /// The keyboard code for F7. /// </summary> F7 , /// <summary> /// The keyboard code for F8. /// </summary> F8 , /// <summary> /// The keyboard code for F9. /// </summary> F9 , /// <summary> /// The keyboard code for F10. /// </summary> F10 , /// <summary> /// The keyboard code for F11. /// </summary> F11 , /// <summary> /// The keyboard code for F12. /// </summary> F12 , /// <summary> /// The keyboard code for F13. /// </summary> F13 , /// <summary> /// The keyboard code for F14. /// </summary> F14 , /// <summary> /// The keyboard code for F15. /// </summary> F15 , /// <summary> /// The keyboard code for F16. /// </summary> F16 , /// <summary> /// The keyboard code for F17. /// </summary> F17 , /// <summary> /// The keyboard code for F18. /// </summary> F18 , /// <summary> /// The keyboard code for F19. /// </summary> F19 , /// <summary> /// The keyboard code for F20. /// </summary> F20 , /// <summary> /// The keyboard code for F21. /// </summary> F21 , /// <summary> /// The keyboard code for F22. /// </summary> F22 , /// <summary> /// The keyboard code for F23. /// </summary> F23 , /// <summary> /// The keyboard code for F24. /// </summary> F24 , /// <summary> /// The keyboard code for NumLock. /// </summary> NumLock , /// <summary> /// The keyboard code for Scroll. /// </summary> Scroll , /// <summary> /// The keyboard code for LeftShift. /// </summary> LeftShift , /// <summary> /// The keyboard code for RightShift. /// </summary> RightShift , /// <summary> /// The keyboard code for LeftControl. /// </summary> LeftControl , /// <summary> /// The keyboard code for RightControl. /// </summary> RightControl , /// <summary> /// The keyboard code for LMenu. /// </summary> LMenu , /// <summary> /// The keyboard code for RMenu. /// </summary> RMenu , /// <summary> /// The keyboard code for ProcessKey. /// </summary> ProcessKey , /// <summary> /// The keyboard code for Attn. /// </summary> Attn , /// <summary> /// The keyboard code for EraseEof. /// </summary> EraseEof , /// <summary> /// The keyboard code for Play. /// </summary> Play , /// <summary> /// The keyboard code for Zoom. /// </summary> Zoom , /// <summary> /// The keyboard code for NoName. /// </summary> NoName , /// <summary> /// The keyboard code for KanaMode. /// </summary> KanaMode , /// <summary> /// The keyboard code for HanguelMode. /// </summary> HanguelMode , /// <summary> /// The keyboard code for HangulMode. /// </summary> HangulMode , /// <summary> /// The keyboard code for JunjaMode. /// </summary> JunjaMode , /// <summary> /// The keyboard code for FinalMode. /// </summary> FinalMode , /// <summary> /// The keyboard code for HanjaMode. /// </summary> HanjaMode , /// <summary> /// The keyboard code for KanjiMode. /// </summary> KanjiMode , /// <summary> /// The keyboard code for IMEConvert. /// </summary> IMEConvert , /// <summary> /// The keyboard code for IMENonconvert. /// </summary> IMENonconvert , /// <summary> /// The keyboard code for IMEAceept. /// </summary> IMEAceept , /// <summary> /// The keyboard code for IMEModeChange. /// </summary> IMEModeChange , /// <summary> /// The keyboard code for BrowserBack. /// </summary> BrowserBack , /// <summary> /// The keyboard code for BrowserForward. /// </summary> BrowserForward , /// <summary> /// The keyboard code for BrowserRefresh. /// </summary> BrowserRefresh , /// <summary> /// The keyboard code for BrowserStop. /// </summary> BrowserStop , /// <summary> /// The keyboard code for BrowserSearch. /// </summary> BrowserSearch , /// <summary> /// The keyboard code for BrowserFavorites. /// </summary> BrowserFavorites , /// <summary> /// The keyboard code for BrowserHome. /// </summary> BrowserHome , /// <summary> /// The keyboard code for VolumeMute. /// </summary> VolumeMute , /// <summary> /// The keyboard code for VolumeDown. /// </summary> VolumeDown , /// <summary> /// The keyboard code for VolumeUp. /// </summary> VolumeUp , /// <summary> /// The keyboard code for MediaNextTrack. /// </summary> MediaNextTrack , /// <summary> /// The keyboard code for MediaPreviousTrack. /// </summary> MediaPreviousTrack , /// <summary> /// The keyboard code for MediaStop. /// </summary> MediaStop , /// <summary> /// The keyboard code for MediaPlayPause. /// </summary> MediaPlayPause , /// <summary> /// The keyboard code for LaunchMail. /// </summary> LaunchMail , /// <summary> /// The keyboard code for SelectMedia. /// </summary> SelectMedia , /// <summary> /// The keyboard code for LaunchApplication1. /// </summary> LaunchApplication1 , /// <summary> /// The keyboard code for LaunchApplication2. /// </summary> LaunchApplication2 , /// <summary> /// The keyboard code for Semicolon. /// </summary> Semicolon , /// <summary> /// The keyboard code for Plus. /// </summary> Plus , /// <summary> /// The keyboard code for Comma. /// </summary> Comma , /// <summary> /// The keyboard code for Period. /// </summary> Period , /// <summary> /// The keyboard code for QuestionMark. /// </summary> QuestionMark , /// <summary> /// The keyboard code for Tilde. /// </summary> Tilde , /// <summary> /// The keyboard code for OpenBracket. /// </summary> OpenBracket , /// <summary> /// The keyboard code for Pipe. /// </summary> Pipe , /// <summary> /// The keyboard code for CloseBracket. /// </summary> CloseBracket, /// <summary> /// The keyboard code for Quotes. /// </summary> Quotes, /// <summary> /// The keyboard code for Backslash. /// </summary> Backslash , /// <summary> /// The keyboard code for Shift. /// </summary> Shift , /// <summary> /// The keyboard code for Control. /// </summary> Control , /// <summary> /// The keyboard code for LeftAlt. /// </summary> LeftAlt, /// <summary> /// The keyboard code for RightAlt. /// </summary> RightAlt } /// <summary> /// Possible buttons that can be found on a mouse. /// </summary> [Flags] public enum MouseButtons { /// <summary> /// This is for mouse events without a button change /// </summary> None = 0, /// <summary> /// Typically the left button. /// </summary> Left = 1, /// <summary> /// Typically the right button. /// </summary> Right = 2, /// <summary> /// Typically the middle button (pressing the scroll wheel). /// </summary> Middle = 4 } /// <summary> /// Special keys that can alter input behavior when down. /// </summary> [Flags] public enum ModifierKeys { None = 0, Shift = 1, Control = 2, Alt = 4, MouseButton0 = 8, MouseButton1 = 16, MouseButton2 = 32 } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.ComponentModel; using System.Globalization; using DotSpatial.Serialization; using NetTopologySuite.Geometries; namespace DotSpatial.Data { /// <summary> /// Extent works like an envelope but is faster acting, has a minimum memory profile, /// only works in 2D and has no events. /// </summary> [Serializable] [TypeConverter(typeof(ExpandableObjectConverter))] public class Extent : ICloneable, IExtent { /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class. /// This introduces no error checking and assumes that the user knows what they are doing when working with this. /// </summary> public Extent() { MinX = double.NaN; // changed by jany_ (2015-07-17) default extent is empty because if there is no content there is no extent MaxX = double.NaN; MinY = double.NaN; MaxY = double.NaN; } /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class from the specified ordinates. /// </summary> /// <param name="xMin">The minimum X value.</param> /// <param name="yMin">The minimum Y value.</param> /// <param name="xMax">The maximum X value.</param> /// <param name="yMax">The maximum Y value.</param> public Extent(double xMin, double yMin, double xMax, double yMax) { MinX = xMin; MinY = yMin; MaxX = xMax; MaxY = yMax; } /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class based on the given values. /// </summary> /// <param name="values">Values used to initialize XMin, YMin, XMax, YMax in the given order.</param> /// <param name="offset">Offset indicates at which position we can find MinX. The other values follow directly after that.</param> public Extent(double[] values, int offset) { if (values.Length < 4 + offset) throw new IndexOutOfRangeException("The length of the array of double values should be greater than or equal to 4 plus the value of the offset."); MinX = values[0 + offset]; MinY = values[1 + offset]; MaxX = values[2 + offset]; MaxY = values[3 + offset]; } /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class. /// </summary> /// <param name="values">Values used to initialize XMin, YMin, XMax, YMax in the given order.</param> public Extent(double[] values) { if (values.Length < 4) throw new IndexOutOfRangeException("The length of the array of double values should be greater than or equal to 4."); MinX = values[0]; MinY = values[1]; MaxX = values[2]; MaxY = values[3]; } /// <summary> /// Initializes a new instance of the <see cref="Extent"/> class from the specified envelope. /// </summary> /// <param name="env">Envelope used for Extent creation.</param> public Extent(Envelope env) { if (Equals(env, null)) throw new ArgumentNullException(nameof(env)); MinX = env.MinX; MinY = env.MinY; MaxX = env.MaxX; MaxY = env.MaxY; } #region Properties /// <summary> /// Gets the Center of this extent. /// </summary> public Coordinate Center { get { double x = MinX + ((MaxX - MinX) / 2); double y = MinY + ((MaxY - MinY) / 2); return new Coordinate(x, y); } } /// <summary> /// Gets a value indicating whether the M values are used. M values are considered optional, and not mandatory. /// Unused could mean either bound is NaN for some reason, or else that the bounds are invalid by the Min being less than the Max. /// </summary> public virtual bool HasM => false; /// <summary> /// Gets a value indicating whether the Z values are used. Z values are considered optional, and not mandatory. /// Unused could mean either bound is NaN for some reason, or else that the bounds are invalid by the Min being less than the Max. /// </summary> public virtual bool HasZ => false; /// <summary> /// Gets or sets the height. Getting this returns MaxY - MinY. Setting this will update MinY, keeping MaxY the same. (Pinned at top left corner). /// </summary> public double Height { get { return MaxY - MinY; } set { MinY = MaxY - value; } } /// <summary> /// Gets or sets the maximum X. /// </summary> [Serialize("MaxX")] public double MaxX { get; set; } /// <summary> /// Gets or sets the maximum Y. /// </summary> [Serialize("MaxY")] public double MaxY { get; set; } /// <summary> /// Gets or sets the minimumg X. /// </summary> [Serialize("MinX")] public double MinX { get; set; } /// <summary> /// Gets or sets the minimumg Y. /// </summary> [Serialize("MinY")] public double MinY { get; set; } /// <summary> /// Gets or sets the width. Getting this returns MaxX - MinX. Setting this will update MaxX, keeping MinX the same. (Pinned at top left corner). /// </summary> public double Width { get { return MaxX - MinX; } set { MaxX = MinX + value; } } /// <summary> /// Gets or sets the X. Getting this returns MinX. Setting this will shift both MinX and MaxX, keeping the width the same. /// </summary> public double X { get { return MinX; } set { double w = Width; MinX = value; Width = w; } } /// <summary> /// Gets or sets the Y. Getting this will return MaxY. Setting this will shift both MinY and MaxY, keeping the height the same. /// </summary> public double Y { get { return MaxY; } set { double h = Height; MaxY = value; Height = h; } } #endregion /// <summary> /// Equality test. /// </summary> /// <param name="left">First extent to test.</param> /// <param name="right">Second extent to test.</param> /// <returns>True, if the extents equal.</returns> public static bool operator ==(Extent left, IExtent right) { if ((object)left == null) return right == null; return left.Equals(right); } /// <summary> /// Inequality test. /// </summary> /// <param name="left">First extent to test.</param> /// <param name="right">Second extent to test.</param> /// <returns>True, if the extents do not equal.</returns> public static bool operator !=(Extent left, IExtent right) { if ((object)left == null) return right != null; return !left.Equals(right); } #region Methods /// <summary> /// This allows parsing the X and Y values from a string version of the extent as: 'X[-180|180], Y[-90|90]' /// Where minimum always precedes maximum. The correct M or MZ version of extent will be returned if the string has those values. /// </summary> /// <param name="text">The string text to parse.</param> /// <returns>The parsed extent.</returns> /// <exception cref="ExtentParseException">Is thrown if the string could not be parsed to an extent.</exception> public static Extent Parse(string text) { Extent result; string fail; if (TryParse(text, out result, out fail)) return result; throw new ExtentParseException(string.Format(DataStrings.ReadingExtentFromStringFailedOnTerm, fail)) { Expression = text }; } /// <summary> /// This allows parsing the X and Y values from a string version of the extent as: 'X[-180|180], Y[-90|90]' /// Where minimum always precedes maximum. The correct M or MZ version of extent will be returned if the string has those values. /// </summary> /// <param name="text">Text that contains the extent values.</param> /// <param name="result">Extent that was created.</param> /// <param name="nameFailed">Indicates which value failed.</param> /// <returns>True if the string could be parsed to an extent.</returns> public static bool TryParse(string text, out Extent result, out string nameFailed) { double xmin, xmax, ymin, ymax, mmin, mmax; result = null; if (text.Contains("Z")) { double zmin, zmax; nameFailed = "Z"; ExtentMz mz = new ExtentMz(); if (!TryExtract(text, "Z", out zmin, out zmax)) return false; mz.MinZ = zmin; mz.MaxZ = zmax; nameFailed = "M"; if (!TryExtract(text, "M", out mmin, out mmax)) return false; mz.MinM = mmin; mz.MaxM = mmax; result = mz; } else if (text.Contains("M")) { nameFailed = "M"; ExtentM me = new ExtentM(); if (!TryExtract(text, "M", out mmin, out mmax)) return false; me.MinM = mmin; me.MaxM = mmax; result = me; } else { result = new Extent(); } nameFailed = "X"; if (!TryExtract(text, "X", out xmin, out xmax)) return false; result.MinX = xmin; result.MaxX = xmax; nameFailed = "Y"; if (!TryExtract(text, "Y", out ymin, out ymax)) return false; result.MinY = ymin; result.MaxY = ymax; return true; } /// <summary> /// Produces a clone, rather than using this same object. /// </summary> /// <returns>The cloned Extent.</returns> public virtual object Clone() { return new Extent(MinX, MinY, MaxX, MaxY); } /// <summary> /// Tests if the specified extent is contained by this extent. /// </summary> /// <param name="ext">Extent that might be contained.</param> /// <returns>True if this extent contains the specified extent.</returns> /// <exception cref="ArgumentNullException">Thrown if ext is null.</exception> public virtual bool Contains(IExtent ext) { if (Equals(ext, null)) throw new ArgumentNullException(nameof(ext)); return Contains(ext.MinX, ext.MaxX, ext.MinY, ext.MaxY); } /// <summary> /// Tests if the specified coordinate is contained by this extent. /// </summary> /// <param name="c">The coordinate to test.</param> /// <returns>True if this extent contains the specified coordinate.</returns> /// <exception cref="ArgumentNullException">Thrown if c is null.</exception> public virtual bool Contains(Coordinate c) { if (Equals(c, null)) throw new ArgumentNullException(nameof(c)); return Contains(c.X, c.X, c.Y, c.Y); } /// <summary> /// Tests if the specified envelope is contained by this extent. /// </summary> /// <param name="env">Envelope that might be contained.</param> /// <returns>True if this extent contains the specified envelope.</returns> /// <exception cref="ArgumentNullException">Thrown if env is null.</exception> public virtual bool Contains(Envelope env) { if (Equals(env, null)) throw new ArgumentNullException(nameof(env)); return Contains(env.MinX, env.MaxX, env.MinY, env.MaxY); } /// <summary> /// Copies the MinX, MaxX, MinY, MaxY values from extent. /// </summary> /// <param name="extent">Any IExtent implementation.</param> public virtual void CopyFrom(IExtent extent) { if (Equals(extent, null)) throw new ArgumentNullException(nameof(extent)); MinX = extent.MinX; MaxX = extent.MaxX; MinY = extent.MinY; MaxY = extent.MaxY; } /// <summary> /// Checks whether this extent and the specified extent are equal. /// </summary> /// <param name="obj">Second Extent to check.</param> /// <returns>True, if extents are the same (either both null or equal in all X and Y values).</returns> public override bool Equals(object obj) { // Check the identity case for reference equality // ReSharper disable once BaseObjectEqualsIsObjectEquals if (base.Equals(obj)) return true; IExtent other = obj as IExtent; if (other == null) return false; return MinX == other.MinX && MinY == other.MinY && MaxX == other.MaxX && MaxY == other.MaxY; } /// <summary> /// Expand will adjust both the minimum and maximum by the specified sizeX and sizeY. /// </summary> /// <param name="padX">The amount to expand left and right.</param> /// <param name="padY">The amount to expand up and down.</param> public void ExpandBy(double padX, double padY) { MinX -= padX; MaxX += padX; MinY -= padY; MaxY += padY; } /// <summary> /// This expand the extent by the specified padding on all bounds. So the width will /// change by twice the padding for instance. To Expand only x and y, use /// the overload with those values explicitly specified. /// </summary> /// <param name="padding">The double padding to expand the extent.</param> public virtual void ExpandBy(double padding) { MinX -= padding; MaxX += padding; MinY -= padding; MaxY += padding; } /// <summary> /// Expands this extent to include the domain of the specified extent. /// </summary> /// <param name="ext">The extent to include.</param> public virtual void ExpandToInclude(IExtent ext) { if (ext == null) return; ExpandToInclude(ext.MinX, ext.MaxX, ext.MinY, ext.MaxY); } /// <summary> /// Expands this extent to include the domain of the specified point. /// </summary> /// <param name="x">The x value to include.</param> /// <param name="y">The y value to include.</param> public void ExpandToInclude(double x, double y) { ExpandToInclude(x, x, y, y); } /// <summary> /// Spreads the values for the basic X, Y extents across the whole range of int. /// Repetition will occur, but it should be rare. /// </summary> /// <returns>Integer.</returns> public override int GetHashCode() { // 215^4 ~ Int.MaxValue so the value will cover the range based mostly on first 2 sig figs. int xmin = Convert.ToInt32((MinX * 430 / MinX) - 215); int xmax = Convert.ToInt32((MaxX * 430 / MaxX) - 215); int ymin = Convert.ToInt32((MinY * 430 / MinY) - 215); int ymax = Convert.ToInt32((MaxY * 430 / MaxY) - 215); return xmin * xmax * ymin * ymax; } /// <summary> /// Calculates the intersection of this extent and the other extent. A result /// with a min greater than the max in either direction is considered invalid /// and represents no intersection. /// </summary> /// <param name="other">The other extent to intersect with.</param> /// <returns>The resulting extent.</returns> public virtual Extent Intersection(Extent other) { if (Equals(other, null)) throw new ArgumentNullException(nameof(other)); Extent result = new Extent { MinX = MinX > other.MinX ? MinX : other.MinX, MaxX = MaxX < other.MaxX ? MaxX : other.MaxX, MinY = MinY > other.MinY ? MinY : other.MinY, MaxY = MaxY < other.MaxY ? MaxY : other.MaxY }; return result; } /// <summary> /// Tests if this extent intersects the specified coordinate. /// </summary> /// <param name="c">The coordinate that might intersect this extent.</param> /// <returns>True if this extent intersects the specified coordinate.</returns> /// <exception cref="ArgumentNullException">Thrown if c is null.</exception> public virtual bool Intersects(Coordinate c) { if (Equals(c, null)) throw new ArgumentNullException(nameof(c)); return Intersects(c.X, c.Y); } /// <summary> /// Tests for intersection with the specified coordinate. /// </summary> /// <param name="x">The double ordinate to test intersection with in the X direction.</param> /// <param name="y">The double ordinate to test intersection with in the Y direction.</param> /// <returns>True if a point with the specified x and y coordinates is within or on the border /// of this extent object. NAN values will always return false.</returns> public bool Intersects(double x, double y) { if (double.IsNaN(x) || double.IsNaN(y)) return false; return x >= MinX && x <= MaxX && y >= MinY && y <= MaxY; } /// <summary> /// Tests if this extent intersects the specified vertex. /// </summary> /// <param name="vert">The vertex that might intersect this extent.</param> /// <returns>True if this extent intersects the specified vertex.</returns> /// <exception cref="ArgumentNullException">Thrown if vert is null.</exception> public bool Intersects(Vertex vert) { if (Equals(vert, null)) throw new ArgumentNullException(nameof(vert)); return Intersects(vert.X, vert.Y); } /// <summary> /// Tests if this extent intersects the specified extent. /// </summary> /// <param name="ext">The extent that might intersect this extent.</param> /// <returns>True if this extent intersects the specified extent.</returns> /// <exception cref="ArgumentNullException">Thrown if ext is null.</exception> public virtual bool Intersects(IExtent ext) { if (Equals(ext, null)) throw new ArgumentNullException(nameof(ext)); return Intersects(ext.MinX, ext.MaxX, ext.MinY, ext.MaxY); } /// <summary> /// Tests if this extent intersects the specified envelope. /// </summary> /// <param name="env">The envelope that might intersect this extent.</param> /// <returns>True if this extent intersects the specified envelope.</returns> /// <exception cref="ArgumentNullException">Thrown if env is null.</exception> public virtual bool Intersects(Envelope env) { if (Equals(env, null)) throw new ArgumentNullException(nameof(env)); return Intersects(env.MinX, env.MaxX, env.MinY, env.MaxY); } /// <summary> /// If this is undefined, it will have a min that is larger than the max, or else any value is NaN. /// This only applies to the X and Y terms. Check HasM or HasZ for higher dimensions. /// </summary> /// <returns>Boolean, true if the envelope has not had values set for it yet.</returns> public bool IsEmpty() { if (double.IsNaN(MinX) || double.IsNaN(MaxX) || double.IsNaN(MinY) || double.IsNaN(MaxY)) return true; return MinX > MaxX || MinY > MaxY; // Simplified } /// <summary> /// This centers the X and Y aspect of the extent on the specified center location. /// </summary> /// <param name="centerX">The X value of the center coordinate to set.</param> /// <param name="centerY">The Y value of the center coordinate to set.</param> /// <param name="width">The new extent width.</param> /// <param name="height">The new extent height.</param> public void SetCenter(double centerX, double centerY, double width, double height) { MinX = centerX - (width / 2); MaxX = centerX + (width / 2); MinY = centerY - (height / 2); MaxY = centerY + (height / 2); } /// <summary> /// This centers the X and Y aspect of the extent on the specified center location. /// </summary> /// <param name="center">The center coordinate to set.</param> /// <param name="width">The new extent width.</param> /// <param name="height">The new extent height.</param> /// <exception cref="ArgumentNullException">Thrown if center is null.</exception> public void SetCenter(Coordinate center, double width, double height) { if (Equals(center, null)) throw new ArgumentNullException(nameof(center)); SetCenter(center.X, center.Y, width, height); } /// <summary> /// This centers the extent on the specified coordinate, keeping the width and height the same. /// </summary> /// <param name="center">Center value which is used to center the extent.</param> /// <exception cref="ArgumentNullException">Thrown if center is null.</exception> public void SetCenter(Coordinate center) { // prevents NullReferenceException when accessing center.X and center.Y if (Equals(center, null)) throw new ArgumentNullException(nameof(center)); SetCenter(center.X, center.Y, Width, Height); } /// <summary> /// Sets the values for xMin, xMax, yMin and yMax. /// </summary> /// <param name="minX">The double Minimum in the X direction.</param> /// <param name="minY">The double Minimum in the Y direction.</param> /// <param name="maxX">The double Maximum in the X direction.</param> /// <param name="maxY">The double Maximum in the Y direction.</param> public void SetValues(double minX, double minY, double maxX, double maxY) { MinX = minX; MinY = minY; MaxX = maxX; MaxY = maxY; } /// <summary> /// Creates a geometric envelope interface from this. /// </summary> /// <returns>An envelope with the min and max values of this extent.</returns> public Envelope ToEnvelope() { if (double.IsNaN(MinX)) return new Envelope(); return new Envelope(MinX, MaxX, MinY, MaxY); } /// <summary> /// Creates a string that shows the extent. /// </summary> /// <returns>The string form of the extent.</returns> public override string ToString() { return "X[" + MinX + "|" + MaxX + "], Y[" + MinY + "|" + MaxY + "]"; } /// <summary> /// Tests if this extent is within the specified extent. /// </summary> /// <param name="ext">Extent that might contain this extent.</param> /// <returns>True if this extent is within the specified extent.</returns> /// <exception cref="ArgumentNullException">Thrown if ext is null.</exception> public virtual bool Within(IExtent ext) { if (Equals(ext, null)) throw new ArgumentNullException(nameof(ext)); return Within(ext.MinX, ext.MaxX, ext.MinY, ext.MaxY); } /// <summary> /// Tests if this extent is within the specified envelope. /// </summary> /// <param name="env">Envelope that might contain this extent.</param> /// <returns>True if this extent is within the specified envelope.</returns> /// <exception cref="ArgumentNullException">Thrown if env is null.</exception> public virtual bool Within(Envelope env) { if (Equals(env, null)) throw new ArgumentNullException(nameof(env)); return Within(env.MinX, env.MaxX, env.MinY, env.MaxY); } /// <summary> /// Attempts to extract the min and max from one element of text. The element should be /// formatted like X[1.5|2.7] using an invariant culture. /// </summary> /// <param name="entireText">Complete text from which the values should be parsed.</param> /// <param name="name">The name of the dimension, like X.</param> /// <param name="min">The minimum that gets assigned.</param> /// <param name="max">The maximum that gets assigned.</param> /// <returns>Boolean, true if the parse was successful.</returns> private static bool TryExtract(string entireText, string name, out double min, out double max) { int i = entireText.IndexOf(name, StringComparison.Ordinal); i += name.Length + 1; int j = entireText.IndexOf(']', i); string vals = entireText.Substring(i, j - i); return TryParseExtremes(vals, out min, out max); } /// <summary> /// Attempts to extract the min and max from the text. The text should be formatted like 1.5|2.7 using an invariant culture. /// </summary> /// <param name="numeric">Text that should be parsed.</param> /// <param name="min">The minimum that gets assigned.</param> /// <param name="max">The maximum that gets assigned.</param> /// <returns>True, if the numeric was parsed successfully.</returns> private static bool TryParseExtremes(string numeric, out double min, out double max) { string[] res = numeric.Split('|'); max = double.NaN; if (!double.TryParse(res[0].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out min)) return false; if (res.Length < 2) return false; if (!double.TryParse(res[1].Trim(), NumberStyles.Any, CultureInfo.InvariantCulture, out max)) return false; return true; } /// <summary> /// Tests if the specified extent is contained by this extent. /// </summary> /// <param name="minX">MinX value of the extent that might be contained.</param> /// <param name="maxX">MaxX value of the extent that might be contained.</param> /// <param name="minY">MinY value of the extent that might be contained.</param> /// <param name="maxY">MaxY value of the extent that might be contained.</param> /// <returns>True if this extent contains the specified extent.</returns> private bool Contains(double minX, double maxX, double minY, double maxY) { return minX >= MinX && maxX <= MaxX && minY >= MinY && maxY <= MaxY; } /// <summary> /// Expands this extent to include the domain of the specified extent. /// </summary> /// <param name="minX">MinX value of the extent that might intersect this extent.</param> /// <param name="maxX">MaxX value of the extent that might intersect this extent.</param> /// <param name="minY">MinY value of the extent that might intersect this extent.</param> /// <param name="maxY">MaxY value of the extent that might intersect this extent.</param> private void ExpandToInclude(double minX, double maxX, double minY, double maxY) { if (double.IsNaN(MinX) || minX < MinX) MinX = minX; if (double.IsNaN(MinY) || minY < MinY) MinY = minY; if (double.IsNaN(MaxX) || maxX > MaxX) MaxX = maxX; if (double.IsNaN(MaxY) || maxY > MaxY) MaxY = maxY; } /// <summary> /// Tests if this extent intersects the specified extent. /// </summary> /// <param name="minX">MinX value of the extent that might intersect this extent.</param> /// <param name="maxX">MaxX value of the extent that might intersect this extent.</param> /// <param name="minY">MinY value of the extent that might intersect this extent.</param> /// <param name="maxY">MaxY value of the extent that might intersect this extent.</param> /// <returns>True if this extent intersects the specified extent.</returns> private bool Intersects(double minX, double maxX, double minY, double maxY) { return maxX >= MinX && minX <= MaxX && maxY >= MinY && minY <= MaxY; } /// <summary> /// Tests if this extent is within the specified extent. /// </summary> /// <param name="minX">MinX value of the extent that might contain this extent.</param> /// <param name="maxX">MaxX value of the extent that might contain this extent.</param> /// <param name="minY">MinY value of the extent that might contain this extent.</param> /// <param name="maxY">MaxY value of the extent that might contain this extent.</param> /// <returns>True if this extent is within the specified extent.</returns> private bool Within(double minX, double maxX, double minY, double maxY) { return MinX >= minX && MaxX <= maxX && MinY >= minY && MaxY <= maxY; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Samples.WebApi.PolicyService.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Linq; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using System.IO; using Moscrif.IDE.Iface.Entities; using Moscrif.IDE.Iface; namespace Moscrif.IDE.Option { public class Settings { private static Paths paths = new Paths(); private List<string> projectMaskDirectory; private List<string> workspaceMaskDirectory; #region Public Property [XmlIgnore] public string FilePath { get; set; } [XmlAttribute("currentWorkspace")] public string CurrentWorkspace ; [XmlAttribute("precompile")] public bool PreCompile = true; [XmlAttribute("autoselectProject")] public bool AutoSelectProject = true; [XmlAttribute("openLastOpenedWorkspace")] public bool OpenLastOpenedWorkspace = true; [XmlAttribute("rssUrl")] public string RssUrl = "http://moscrif.com/rss/news";//"http://moscrif.com/rss/news.ashx?source=IDE"; [XmlAttribute("tweetUrl")] public string TweetUrl = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=mothiva"; [XmlAttribute("tweetBaseUrl")] public string TweetBaseUrl = "http://twitter.com/mothiva/statuses/" ; [XmlAttribute("maxRssTweetMessageCount")] public int MaxRssTweetMessageCount =3; [XmlAttribute("stopCompilationOnError")] public bool FirstErrorStopCompile = false; [XmlAttribute("bringErrorPaneToFront")] public bool ShowErrorPane = true; //[XmlAttribute("loggAllStep")] [XmlIgnore] public bool LoggAllStep = true; [XmlAttribute("publishDir")] public string PublishDirectory = System.IO.Path.Combine(paths.AppPath,"publish");//@"\work\moscrif-publish\"; [XmlAttribute("frameworkDir")] public string LibDirectory = System.IO.Path.Combine(paths.AppPath,"framework");//@"\work\moscrif-lib\"; [XmlAttribute("emulatorDir")] public string EmulatorDirectory = paths.AppPath;//@"\work\moscrif-publish\"; [XmlAttribute("socetServerPort")] public string SocetServerPort = "4321"; [XmlAttribute("projectCount")] public int ProjectCount = 1; [XmlAttribute("workspaceCount")] public int WorkspaceCount = 1; [XmlElement("remoteIpAdress")] public string RemoteIpAdress ; [XmlElement("samplesBaseUrl")] public string SamplesBaseUrl = "http://moscrif.com/samples?source=IDE" ; [XmlElement("showcaseBaseUrl")] public string ShowcaseBaseUrl = "http://moscrif.com/showcase?source=IDE" ; [XmlElement("apiBaseUrl")] public string ApiBaseUrl = "http://moscrif.com/userfiles/pages/developer/api/index.html" ; [XmlElement("videosBaseUrl")] public string VideosBaseUrl = "http://moscrif.com/videos?source=IDE" ; [XmlElement("tutorialsBaseUrl")] public string TutorialsBaseUrl = "http://moscrif.com/tutorials?source=IDE" ; [XmlElement("demosBaseUrl")] public string DemosBaseUrl = "http://moscrif.com/demos?source=IDE" ; [XmlElement("documentsBaseUrl")] public string DocumentsBaseUrl = "http://moscrif.com/documents?source=IDE" ; /*#if DEBUG [XmlIgnore] public String signUrl = "http://rc.moscrif.com/ide/signApp.ashx?t={0}&a={1}"; [XmlIgnore] public String checkVersion = "http://rc.moscrif.com/ide/signApp.ashx?v={0}"; [XmlIgnore] public String checkVersionLog = "http://rc.moscrif.com/ide/signApp.ashx?v={0}&t={1}"; [XmlIgnore] public String getVersion = "http://rc.moscrif.com/ide/getVersion.ashx?v={0}"; [XmlIgnore] public String getVersionLog = "http://rc.moscrif.com/ide/getVersion.ashx?v={0}&t={1}"; [XmlIgnore] public String redgisterUrl = "http://rc.moscrif.com/ide/registerLogin.ashx"; [XmlIgnore] public String pingUrl = "http://rc.moscrif.com/ide/ping.ashx"; [XmlIgnore] public String loggUrl = "http://rc.moscrif.com/ide/analytics.ashx"; [XmlIgnore] public String loginUrl = "http://rc.moscrif.com/ide/checkLogin.ashx"; [XmlIgnore] public String feedbackUrl = "http://rc.moscrif.com/ide/reportIssue.ashx"; [XmlIgnore] public String bannerUrl = "http://rc.moscrif.com/ide/getBanner.ashx"; [XmlIgnore] public String licenceUrl = "http://rc.moscrif.com/ide/getLicenses.ashx"; */ //#else [XmlIgnore] public String signUrl = "http://moscrif.com/ide/signApp.ashx?t={0}&a={1}"; [XmlIgnore] public String checkVersion = "http://moscrif.com/ide/signApp.ashx?v={0}"; [XmlIgnore] public String checkVersionLog = "http://moscrif.com/ide/signApp.ashx?v={0}&t={1}"; [XmlIgnore] public String getVersion = "http://moscrif.com/ide/getVersion.ashx?v={0}"; [XmlIgnore] public String getVersionLog = "http://moscrif.com/ide/getVersion.ashx?v={0}&t={1}"; [XmlIgnore] public String redgisterUrl = "http://moscrif.com/ide/registerLogin.ashx"; [XmlIgnore] public String pingUrl = "http://moscrif.com/ide/ping.ashx"; [XmlIgnore] public String loggUrl = "http://moscrif.com/ide/analytics.ashx"; [XmlIgnore] public String loginUrl = "http://moscrif.com/ide/checkLogin.ashx"; [XmlIgnore] public String feedbackUrl = "http://moscrif.com/ide/reportIssue.ashx"; [XmlIgnore] public String bannerUrl = "http://moscrif.com/ide/getBanner.ashx"; [XmlIgnore] public String licenceUrl = "http://moscrif.com/ide/getLicenses.ashx"; //#endif [XmlElement("backgroundColor")] public BackgroundColors BackgroundColor = null; [XmlElement("imageEditor")] public ImageEditorSetting ImageEditors = null; [XmlElement("proxy")] public ProxySetting Proxy = null; [XmlElement ("sourceEditor")] public SourceEditorSetting SourceEditorSettings = null; [XmlArrayAttribute("ignoresFolders")] [XmlArrayItem("folder")] public List<IgnoreFolder> IgnoresFolders; //public List<string> IgnoreFolders; [XmlArrayAttribute("ignoresFiles")] [XmlArrayItem("file")] public List<IgnoreFolder> IgnoresFiles; [XmlArray("logicalViews")] [XmlArrayItem("view")] public List<LogicalSystem> LogicalSort = null; [XmlArrayAttribute("extensionList")] [XmlArrayItem("extension")] public List<ExtensionSetting> ExtensionList; [XmlElement("resolution")] public Condition Resolution; [XmlElement("account")] public Account Account; [XmlElement("emulatorSettings")] public EmulatorSetting EmulatorSettings; [XmlAttribute("lastOpenedFileDir")] public string LastOpenedFileDir ; [XmlAttribute("lastOpenedWorkspaceDir")] public string LastOpenedWorkspaceDir ; [XmlAttribute("lastOpenedImportDir")] public string LastOpenedImportDir ; [XmlAttribute("lastOpenedExportDir")] public string LastOpenedExportDir ; [XmlAttribute("clearConsoleBeforeRun")] public bool ClearConsoleBeforRuning = true; [XmlAttribute("openOutputAfterPublish")] public bool OpenOutputAfterPublish= true; [XmlAttribute("consoleTaskFont")] public string ConsoleTaskFont ; [XmlAttribute("saveChangesBeforeRun")] public bool SaveChangesBeforeRun= true; [XmlAttribute("showUnsupportedDevices")] public bool ShowUnsupportedDevices= false; [XmlAttribute("showDebugDevices")] public bool ShowDebugDevices= false; [XmlArrayAttribute("displayOrientations")] [XmlArrayItem("orientation")] public List<SettingValue> DisplayOrientations; [XmlArrayAttribute("applicationType")] [XmlArrayItem("type")] public List<SettingValue> ApplicationType; //GenerateApplicationType [XmlArrayAttribute("InstallLocations")] [XmlArrayItem("location")] public List<SettingValue> InstallLocations; [XmlArrayAttribute("osSupportedDevices")] [XmlArrayItem("supportedDevices")] public List<SettingValue> OSSupportedDevices; [XmlArrayAttribute("androidSupportedDevices")] [XmlArrayItem("supportedDevices")] public List<SettingValue> AndroidSupportedDevices; [XmlArray("platformResolutions")] [XmlArrayItem("platform")] public List<PlatformResolution> PlatformResolutions = null; [XmlAttribute("javaCommand")] public string JavaCommand = "java"; /*[XmlAttribute("signAllow")] public bool SignAllow = false;*/ [XmlAttribute("javaArgument")] public string JavaArgument = "-version"; [XmlAttribute("versionSetting")] public int VersionSetting ; [XmlAttribute("logPublish")] public bool LogPublish = false; [XmlIgnore] public List<string> WorkspaceMaskDirectory { get{ if(workspaceMaskDirectory == null){ workspaceMaskDirectory = new List<string>(); workspaceMaskDirectory.Add("$(workspace_dir)"); //workspaceMaskDirectory.Add("$(workspace_work)"); } return workspaceMaskDirectory; } } [XmlIgnore] public List<string> ProjectMaskDirectory { get{ if(projectMaskDirectory == null){ projectMaskDirectory = new List<string>(); projectMaskDirectory.Add("$(publish_dir)"); projectMaskDirectory.Add("$(project_dir)"); } return projectMaskDirectory; } } [XmlIgnore] public string ThemeDir = ".themes"; [XmlIgnore] public string SkinDir = "uix-skin"; [XmlIgnore] public Condition Platform; //private List<string> libsDefine; //[XmlArrayAttribute("libs")] //[XmlArrayItem("lib")] [XmlIgnore] public List<string> LibsDefine{ get{ return GenerateLibs(); } } [XmlElement("symbian-unprotectedRange")] public Range UnprotectedRange; [XmlElement("symbian-protectedRange")] public Range ProtectedRange; public List<string> GetUnprotectedRange() { if (UnprotectedRange == null){ UnprotectedRange = new Range(); UnprotectedRange.Minimal = "0xA89FDE0E"; UnprotectedRange.Maximal = "0xA89FDE21"; } uint min =0xA89FDE0E; uint max =0xA89FDE21; if (!UInt32.TryParse(UnprotectedRange.Minimal, out min)) min = 0xA89FDE0E; if (!UInt32.TryParse(UnprotectedRange.Maximal, out max)) max = 0xA89FDE21; if(min> max){ min = 0xA89FDE0E; max = 0xA89FDE21; } List<string> unprRange = new List<string>(); for (uint i =min ; i <= max ;i++ ){ unprRange.Add(string.Format( "0x"+"{0:X}", i)); } return unprRange; } public List<string> GetProtectedRange() { if (ProtectedRange == null){ ProtectedRange = new Range(); ProtectedRange.Minimal = "0x20041437"; ProtectedRange.Maximal = "0x2004144A"; } uint min =0xA89FDE0E; uint max =0xA89FDE21; if (!UInt32.TryParse(ProtectedRange.Minimal, out min)) min = 0x20041437; if (!UInt32.TryParse(ProtectedRange.Maximal, out max)) max = 0x2004144A; if(min> max){ min = 0x20041437; max = 0x2004144A; } List<string> unprRange = new List<string>(); for (uint i = min ; i <=max ;i++ ){ unprRange.Add(string.Format( "0x"+"{0:X}", i)); } return unprRange; } #endregion #region RecentFiles [XmlIgnore] public RecentFiles RecentFiles { get { return recentFiles ?? (recentFiles = CreateRecentFilesProvider()); } } protected virtual RecentFiles CreateRecentFilesProvider() { return new FdoRecentFiles(System.IO.Path.Combine(paths.SettingDir, ".recently-used")); } RecentFiles recentFiles; #endregion #region FavoriteFile [XmlIgnore] public RecentFiles FavoriteFiles { get { return favoriteFiles ?? (favoriteFiles = CreateFavoriteFilesProvider()); } } protected virtual RecentFiles CreateFavoriteFilesProvider() { return new FdoRecentFiles(System.IO.Path.Combine(paths.SettingDir, ".favorite-files")); } RecentFiles favoriteFiles; #endregion public Settings() { FilePath = System.IO.Path.Combine(paths.SettingDir, "moscrif.mss"); if (Platform == null) GeneratePlatform(); if (Resolution == null) GenerateResolution(); } public Settings(string filePath) { FilePath = filePath; if (Platform == null) GeneratePlatform(); if (Resolution == null) GenerateResolution(); if(Resolution.Rules[0].Width<0){ GenerateResolution(); } if (IgnoresFolders == null) GenerateIgnoreFolder(); if (IgnoresFiles == null) GenerateIgnoreFiles(); if (ExtensionList == null) GenerateExtensionList(); if (DisplayOrientations == null) GenerateOrientations(); if (InstallLocations == null) GenerateInstallLocation(); if (OSSupportedDevices == null) GenerateOSSupportedDevices(); if (PlatformResolutions == null) GeneratePlatformResolutions(); if (ApplicationType == null) GenerateApplicationType(); if (AndroidSupportedDevices == null) GenerateAndroidSupportedDevices(); if ((EmulatorSettings == null)) EmulatorSettings = new EmulatorSetting(); EmulatorSettings.UsDefault = true; //if(LibsDefine == null)) GenerateLibs(); //VersionSetting = 111202; } public void SaveSettings() { try{ using (FileStream fs = new FileStream(FilePath, FileMode.Create)) { XmlSerializer serializer = new XmlSerializer(typeof(Settings)); serializer.Serialize(fs, this); } } catch(Exception ex){ Moscrif.IDE.Tool.Logger.Error(ex.Message); } } static public Settings OpenSettings(string filePath) { if (System.IO.File.Exists(filePath)) { try { using (FileStream fs = File.OpenRead(filePath)) { XmlSerializer serializer = new XmlSerializer(typeof(Settings)); Settings s = (Settings)serializer.Deserialize(fs); if ((s.EmulatorSettings == null) || ( String.IsNullOrEmpty(s.EmulatorSettings.Exec) ) ) { s.EmulatorSettings = new EmulatorSetting(); s.EmulatorSettings.UsDefault = true; } if ((s.LogicalSort == null) || ((s.LogicalSort.Count <1 )) ) { s.LogicalSort = LogicalSystem.GetDefaultLogicalSystem(); } if ((s.Resolution == null) || ((s.Resolution.Rules.Count <1 )) ){ s.GenerateResolution(); } else { if(s.Resolution.Rules[1].Width<1){ s.GenerateResolution(); } } if ((s.IgnoresFolders == null) || (s.IgnoresFolders.Count<1)){ s.GenerateIgnoreFolder(); } if((s.ExtensionList == null)||(s.ExtensionList.Count<1)){ s.GenerateExtensionList(); } if ((s.IgnoresFiles == null) || (s.IgnoresFiles.Count<1)){ s.GenerateIgnoreFiles(); } if ((s.Platform == null) || (s.Platform.Rules.Count < 1)){ s.GeneratePlatform(); } if ((s.DisplayOrientations == null) || ((s.DisplayOrientations.Count <1 )) ){ s.GenerateOrientations(); } if ((s.InstallLocations == null) || ((s.InstallLocations.Count <1 )) ){ s.GenerateInstallLocation(); } if ((s.OSSupportedDevices == null) || ((s.OSSupportedDevices.Count <1 )) ){ s.GenerateOSSupportedDevices(); } if ((s.PlatformResolutions == null) || ((s.PlatformResolutions.Count <1 )) ){ s.GeneratePlatformResolutions(); } if ((s.ApplicationType == null) || ((s.ApplicationType.Count <1 )) ){ s.GenerateApplicationType(); } if ((s.AndroidSupportedDevices == null) || ((s.AndroidSupportedDevices.Count <1 )) ){ s.GenerateAndroidSupportedDevices(); } if (s.VersionSetting < 111202){ //year, month, day s.GenerateIgnoreFolder(); s.VersionSetting = 111202; } if (s.VersionSetting < 120314){ //year, month, day s.GenerateResolution(); s.GeneratePlatformResolutions(); s.VersionSetting = 120314; } if (s.VersionSetting < 120828){ //year, month, day s.TweetUrl = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=moscrif"; s.TweetBaseUrl = "http://twitter.com/moscrif/statuses/" ; s.VersionSetting = 120828; } if (s.VersionSetting < 120903){ //year, month, day s.GeneratePlatformResolutions(); s.VersionSetting = 120903; } if (s.VersionSetting < 121001){ //year, month, day s.ShowUnsupportedDevices = false; s.VersionSetting = 121001; } if (s.VersionSetting < 121017){ //year, month, day s.GenerateResolution(); s.GeneratePlatformResolutions(); s.VersionSetting = 121017; } if (s.VersionSetting < 121106){ //year, month, day s.MaxRssTweetMessageCount = 3; s.VersionSetting = 121106; } return s; } } catch (Exception ex) { throw ex; } } else { throw new Exception("Settings file does not exist!"); } } public class EmulatorSetting { public EmulatorSetting(){ } [XmlAttribute("usDefault")] public bool UsDefault ; [XmlAttribute("params")] public string Params = "" ; [XmlAttribute("exec")] public string Exec = "" ; } public class BackgroundColors { public BackgroundColors(){} public BackgroundColors(byte red,byte green,byte blue){ Red= red; Green=green; Blue=blue; } public BackgroundColors(byte red,byte green,byte blue,ushort alpha){ Red= red; Green=green; Blue=blue; Alpha = alpha; } [XmlAttribute("red")] public byte Red; [XmlAttribute("green")] public byte Green; [XmlAttribute("blue")] public byte Blue; [XmlAttribute("alpha")] public ushort Alpha; } public class SourceEditorSetting { public SourceEditorSetting(){ if( MainClass.Platform.IsMac){ EditorFont= "Monaco 12";//"Monospace 15"; } } [XmlAttribute("sourceEditorFont")] public string EditorFont = "Monospace 10"; [XmlAttribute("sourceEditorTabSpace")] public int TabSpace = 4; [XmlAttribute("sourceEditorTabsToSpaces")] public bool TabsToSpaces = true; [XmlAttribute("sourceEditorShowEolMarker")] public bool ShowEolMarker = false; [XmlAttribute("sourceEditorShowTab")] public bool ShowTab = false; [XmlAttribute("sourceEditorSpaces")] public bool ShowSpaces = false; [XmlAttribute("sourceEditorRulerColumn")] public int RulerColumn = 85; [XmlAttribute("sourceEditorShowRuler")] public bool ShowRuler = false; [XmlAttribute("sourceEditorShowLineNumber")] public bool ShowLineNumber = true; [XmlAttribute("sourceEditorEnableAnimations")] public bool EnableAnimations = true; [XmlAttribute("sourceEditorAggressivelyCompletion")] public bool AggressivelyTriggerCL = true; } public class ImageEditorSetting { [XmlAttribute("line")] public int LineWidth; [XmlAttribute("point")] public int PointWidth; [XmlElement("lineColor")] public BackgroundColors LineColor; [XmlElement("pointColor")] public BackgroundColors PointColor; [XmlElement("selectPointColor")] public BackgroundColors SelectPointColor; } public class Range { [XmlAttribute("minimal")] public string Minimal; [XmlAttribute("maximal")] public string Maximal; } private void GeneratePlatform(){ Platform = new Condition(); Platform.Id = -1; Platform.Name = "Platform"; Platform.System = true; Platform.Rules = new List<Rule> (); Platform.Rules.Add(new Rule((int)DeviceType.Android_1_6,"Android 1.6 +","android_1_6",0)); Platform.Rules.Add(new Rule((int)DeviceType.Android_2_2,"Android 2.2 +","android_2_2",0)); Platform.Rules.Add(new Rule((int)DeviceType.iOS_5_0,"iOS","ios_5_0",0)); Platform.Rules.Add(new Rule((int)DeviceType.Bada_1_0,"Bada 1.0","bada_1_0",0)); Platform.Rules.Add(new Rule((int)DeviceType.Bada_1_1,"Bada 1.1","bada_1_1",0)); Platform.Rules.Add(new Rule((int)DeviceType.Symbian_9_4,"Symbian","symbian_9_4",-1)); Platform.Rules.Add(new Rule((int)DeviceType.WindowsMobile_6,"Windows Mobile","wm_6",-1)); Platform.Rules.Add(new Rule((int)DeviceType.Bada_2_0,"Bada 2.0","bada_2_0",-2)); Platform.Rules.Add(new Rule((int)DeviceType.Windows,"Windows","windows",-2)); Platform.Rules.Add(new Rule((int)DeviceType.MacOs,"MacOs","mac",-2)); //Platform.Rules.Add(new Rule((int)DeviceType.webOs,"webOS","webOS")); //Platform.Rules.Add(new Rule((int)DeviceType.MeeGo,"MeeGo","MeeGo")); } public void GeneratePlatformResolutions(){ PlatformResolutions = new List<PlatformResolution>(); PlatformResolution prAndr16 = new PlatformResolution((int)DeviceType.Android_1_6); prAndr16.AllowResolution = new List<int>(); prAndr16.AllowResolution.Add(-1); //prAndr16.AllowResolution.Add(-2); prAndr16.AllowResolution.Add(-3); //prAndr16.AllowResolution.Add(-4); prAndr16.AllowResolution.Add(-5); prAndr16.AllowResolution.Add(-6); prAndr16.AllowResolution.Add(-7); prAndr16.AllowResolution.Add(-8); prAndr16.AllowResolution.Add(-9); prAndr16.AllowResolution.Add(-10); //prAndr16.AllowResolution.Add(-11); prAndr16.AllowResolution.Add(-12); prAndr16.AllowResolution.Add(-13); prAndr16.AllowResolution.Add(-14); prAndr16.AllowResolution.Add(-15); prAndr16.AllowResolution.Add(-16); PlatformResolutions.Add(prAndr16); PlatformResolution prAndr22 = new PlatformResolution((int)DeviceType.Android_2_2); prAndr22.AllowResolution = new List<int>(); prAndr22.AllowResolution.Add(-1); //prAndr22.AllowResolution.Add(-2); prAndr22.AllowResolution.Add(-3); //prAndr22.AllowResolution.Add(-4); prAndr22.AllowResolution.Add(-5); prAndr22.AllowResolution.Add(-6); prAndr22.AllowResolution.Add(-7); prAndr22.AllowResolution.Add(-8); prAndr22.AllowResolution.Add(-9); prAndr22.AllowResolution.Add(-10); //prAndr22.AllowResolution.Add(-11); prAndr22.AllowResolution.Add(-12); prAndr22.AllowResolution.Add(-13); prAndr22.AllowResolution.Add(-14); prAndr22.AllowResolution.Add(-15); prAndr22.AllowResolution.Add(-16); PlatformResolutions.Add(prAndr22); PlatformResolution prIos = new PlatformResolution((int)DeviceType.iOS_5_0); prIos.AllowResolution = new List<int>(); prIos.AllowResolution.Add(-1); prIos.AllowResolution.Add(-3); prIos.AllowResolution.Add(-7); prIos.AllowResolution.Add(-8); prIos.AllowResolution.Add(-15); prIos.AllowResolution.Add(-17); PlatformResolutions.Add(prIos); PlatformResolution prBada10 = new PlatformResolution((int)DeviceType.Bada_1_0); prBada10.AllowResolution = new List<int>(); prBada10.AllowResolution.Add(-1); //prBada10.AllowResolution.Add(-3); prBada10.AllowResolution.Add(-6); //prBada10.AllowResolution.Add(-11); PlatformResolutions.Add(prBada10); PlatformResolution prBada11 = new PlatformResolution((int)DeviceType.Bada_1_1); prBada11.AllowResolution = new List<int>(); prBada11.AllowResolution.Add(-1); prBada11.AllowResolution.Add(-3); //prBada11.AllowResolution.Add(-6); //prBada11.AllowResolution.Add(-11); PlatformResolutions.Add(prBada11); /*PlatformResolution prBada2 = new PlatformResolution((int)DeviceType.Bada_1_2); prBada2.AllowResolution = new List<int>(); prBada2.AllowResolution.Add(-1); prBada2.AllowResolution.Add(-6); PlatformResolutions.Add(prBada2);*/ PlatformResolution prSymbian94 = new PlatformResolution((int)DeviceType.Symbian_9_4); prSymbian94.AllowResolution = new List<int>(); prSymbian94.AllowResolution.Add(-1); //prSymbian94.AllowResolution.Add(-4); prSymbian94.AllowResolution.Add(-6); PlatformResolutions.Add(prSymbian94); /*PlatformResolution prSymbian95 = new PlatformResolution((int)DeviceType.Symbian_9_5); prSymbian95.AllowResolution = new List<int>(); prSymbian95.AllowResolution.Add(-1); prSymbian95.AllowResolution.Add(-4); prSymbian95.AllowResolution.Add(-6); prSymbian95.AllowResolution.Add(-11); PlatformResolutions.Add(prSymbian95);*/ /*PlatformResolution prWindowsMobile5 = new PlatformResolution((int)DeviceType.WindowsMobile_5); prWindowsMobile5.AllowResolution = new List<int>(); prWindowsMobile6.AllowResolution.Add(-1); prWindowsMobile5.AllowResolution.Add(-3); prWindowsMobile5.AllowResolution.Add(-2); prWindowsMobile5.AllowResolution.Add(-5); prWindowsMobile5.AllowResolution.Add(-6); PlatformResolutions.Add(prWindowsMobile5);*/ PlatformResolution prWindowsMobile6 = new PlatformResolution((int)DeviceType.WindowsMobile_6); prWindowsMobile6.AllowResolution = new List<int>(); prWindowsMobile6.AllowResolution.Add(-1); prWindowsMobile6.AllowResolution.Add(-3); //prWindowsMobile6.AllowResolution.Add(-2); prWindowsMobile6.AllowResolution.Add(-5); prWindowsMobile6.AllowResolution.Add(-6); PlatformResolutions.Add(prWindowsMobile6); } public void GenerateResolution(){ Resolution = new Condition(); Resolution.Id = -2; Resolution.Name = "Resolution"; Resolution.System = true; Resolution.Rules = new List<Rule> (); Resolution.Rules.Add(new Rule(-1,"Universal","uni",0,0)); Resolution.Rules.Add(new Rule(-2,"QVGA","qvga",240,320)); Resolution.Rules.Add(new Rule(-3,"HVGA","hvga",320,480)); Resolution.Rules.Add(new Rule(-4,"nHD","nhd",360,640)); Resolution.Rules.Add(new Rule(-5,"VGA","vga",480,640)); Resolution.Rules.Add(new Rule(-6,"WVGA","wvga",480,800)); Resolution.Rules.Add(new Rule(-7,"DVGA","dvga",640,960)); Resolution.Rules.Add(new Rule(-8,"XGA","xga",768,1024)); Resolution.Rules.Add(new Rule(-9,"SVGA","svga",600,800)); Resolution.Rules.Add(new Rule(-10,"qHD","qhd",540,960)); Resolution.Rules.Add(new Rule(-11,"WQVGA","wqvga",240,400)); Resolution.Rules.Add(new Rule(-12,"VXGA","vxga",800,1280)); Resolution.Rules.Add(new Rule(-13,"FWVGA","fwvga",480,854)); Resolution.Rules.Add(new Rule(-14,"WSVGA","wsvga",600,1024)); Resolution.Rules.Add(new Rule(-15,"QXGA","qxga",1536,2048)); Resolution.Rules.Add(new Rule(-16,"HD720","hd720",720,1280)); Resolution.Rules.Add(new Rule(-17,"WDVGA","wdvga",640,1136)); } public void GenerateOrientations(){ DisplayOrientations = new List<SettingValue>(); DisplayOrientations.Add(new SettingValue("portrait","Portrait")); DisplayOrientations.Add(new SettingValue("landscape left","Landscape Left")); DisplayOrientations.Add(new SettingValue("landscape right","Landscape Right")); } public void GenerateApplicationType(){ ApplicationType = new List<SettingValue>(); ApplicationType.Add(new SettingValue("application","Application")); ApplicationType.Add(new SettingValue("game","Game")); } public void GenerateInstallLocation(){ //"internalOnly", "auto", "preferExternal" InstallLocations = new List<SettingValue>(); InstallLocations.Add(new SettingValue("internalOnly","Internal Only")); InstallLocations.Add(new SettingValue("auto","Auto")); InstallLocations.Add(new SettingValue("preferExternal","Prefer External")); } public void GenerateOSSupportedDevices(){ //"internalOnly", "auto", "preferExternal" OSSupportedDevices = new List<SettingValue>(); OSSupportedDevices.Add(new SettingValue("universal","Universal")); OSSupportedDevices.Add(new SettingValue("iPhone","iPhone")); OSSupportedDevices.Add(new SettingValue("iPad","iPad")); } public void GenerateAndroidSupportedDevices(){ //"internalOnly", "auto", "preferExternal" AndroidSupportedDevices = new List<SettingValue>(); AndroidSupportedDevices.Add(new SettingValue("universal","Universal")); AndroidSupportedDevices.Add(new SettingValue("armv7a","ARMv7a only")); } public List<string> GenerateLibs(){ List<string> libsDefine = new List<string>(); DirectoryInfo dirWorkspace = new DirectoryInfo(LibDirectory); DirectoryInfo[] listDirectory = dirWorkspace.GetDirectories("*",SearchOption.TopDirectoryOnly); foreach(DirectoryInfo di in listDirectory){ int ignore = IgnoresFolders.FindIndex( x=> x.Folder == di.Name && x.IsForIde); if(ignore <0){ libsDefine.Add( di.Name); } } return libsDefine; } public void GenerateIgnoreFiles(){ IgnoresFiles = new List<IgnoreFolder>(); IgnoresFiles.Add(new IgnoreFolder(".DS_Store",true,true)); IgnoresFiles.Add(new IgnoreFolder("Thumbs.db",true,true)); } public void GenerateExtensionList(){ ExtensionList = new List<ExtensionSetting>(); ExtensionList.Add(new ExtensionSetting(".xml,.ms,.mso,.txt,.tab,.app,.js",ExtensionSetting.OpenTyp.TEXT )); ExtensionList.Add(new ExtensionSetting(".png,.jpg,.bmp",ExtensionSetting.OpenTyp.IMAGE)); ExtensionList.Add(new ExtensionSetting(".db",ExtensionSetting.OpenTyp.DATABASE)); } public void GenerateIgnoreFolder(){ IgnoresFolders = new List<IgnoreFolder>(); IgnoresFolders.Add(new IgnoreFolder(".svn",true,true)); IgnoresFolders.Add(new IgnoreFolder(".git",true,true)); IgnoresFolders.Add(new IgnoreFolder("platform",false,true)); IgnoresFolders.Add(new IgnoreFolder("marketing",false,true)); IgnoresFolders.Add(new IgnoreFolder("output",false,true)); //IgnoresFolders.Add(new IgnoreFolder("temp",true,true)); } } }
//----------------------------------------------------------------------- // <copyright file="InterpreterSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Stage; using Akka.Streams.Supervision; using Akka.Streams.TestKit.Tests; using FluentAssertions; using Xunit; using Xunit.Abstractions; using OnNext = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.OnNext; using Cancel = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.Cancel; using OnError = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.OnError; using OnComplete = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.OnComplete; using RequestOne = Akka.Streams.Tests.Implementation.Fusing.GraphInterpreterSpecKit.OneBoundedSetup.RequestOne; namespace Akka.Streams.Tests.Implementation.Fusing { public class InterpreterSpec : GraphInterpreterSpecKit { /* * These tests were writtern for the previous version of the interpreter, the so called OneBoundedInterpreter. * These stages are now properly emulated by the GraphInterpreter and many of the edge cases were relevant to * the execution model of the old one. Still, these tests are very valuable, so please do not remove. */ public InterpreterSpec(ITestOutputHelper output = null) : base(output) { } [Fact] public void Interpreter_should_implement_map_correctly() { WithOneBoundedSetup(new Select<int, int>(x => x + 1, Deciders.StoppingDecider), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(2)); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_implement_chain_of_maps_correctly() { WithOneBoundedSetup(new IStage<int, int>[] { new Select<int, int>(x => x + 1, Deciders.StoppingDecider), new Select<int, int>(x => x * 2, Deciders.StoppingDecider), new Select<int, int>(x => x + 1, Deciders.StoppingDecider) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(3)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(5)); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_work_with_only_boundary_ops() { WithOneBoundedSetup(new IStage<int, int>[0], (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(0)); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_implement_one_to_many_many_to_one_chain_correctly() { WithOneBoundedSetup(new IStage<int, int>[] { new Doubler<int>(), new Where<int>(x => x != 0, Deciders.StoppingDecider) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_implement_many_to_one_one_to_many_chain_correctly() { WithOneBoundedSetup(new IStage<int, int>[] { new Where<int>(x => x != 0, Deciders.StoppingDecider), new Doubler<int>() }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_implement_take() { WithOneBoundedSetup(new IStage<int, int>[] { new Take<int>(2) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(0)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new Cancel(), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_take_inside_a_chain() { WithOneBoundedSetup(new IStage<int, int>[] { new Where<int>(x => x != 0, Deciders.StoppingDecider), new Take<int>(2), new Select<int, int>(x => x + 1, Deciders.StoppingDecider) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(2)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new OnNext(3), new Cancel(), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_fold() { WithOneBoundedSetup(new IStage<int, int>[] { new Aggregate<int, int>(0, (agg, x) => agg + x, Deciders.StoppingDecider) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnNext(3), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_fold_with_proper_cancel() { WithOneBoundedSetup(new IStage<int, int>[] { new Aggregate<int, int>(0, (agg, x) => agg + x, Deciders.StoppingDecider) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_work_if_fold_completes_while_not_in_a_push_position() { WithOneBoundedSetup(new IStage<int, int>[] { new Aggregate<int, int>(0, (agg, x) => agg + x, Deciders.StoppingDecider) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); upstream.OnComplete(); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(0), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_grouped() { WithOneBoundedSetup<int, IEnumerable<int>>(ToGraphStage( new Grouped<int>(3) ), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new OnNext(new [] {0, 1, 2})); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(3); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnNext(new [] {3}), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_batch_conflate() { WithOneBoundedSetup<int>(new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEmpty(); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new OnNext(0), new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(3)); downstream.RequestOne(); lastEvents().Should().BeEmpty(); upstream.OnNext(4); lastEvents().Should().BeEquivalentTo(new OnNext(4), new RequestOne()); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_implement_expand() { WithOneBoundedSetup<int>(new Expand<int, int>(e => Enumerable.Repeat(e, int.MaxValue).GetEnumerator()), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(), new OnNext(0)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(0)); upstream.OnNext(1); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne(), new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); upstream.OnComplete(); lastEvents().Should().BeEquivalentTo(new OnComplete()); }); } [Fact] public void Interpreter_should_work_with_batch_batch_conflate_conflate() { WithOneBoundedSetup<int>(new IGraphStageWithMaterializedValue<Shape, object>[] { new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x), new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEmpty(); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne(), new OnNext(0)); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(3)); downstream.RequestOne(); lastEvents().Should().BeEmpty(); upstream.OnNext(4); lastEvents().Should().BeEquivalentTo(new RequestOne(), new OnNext(4)); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_work_with_expand_expand() { WithOneBoundedSetup<int>(new IGraphStageWithMaterializedValue<Shape, object>[] { new Expand<int, int>(e => Enumerable.Range(e, 100).GetEnumerator()), new Expand<int, int>(e => Enumerable.Range(e, 100).GetEnumerator()) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(0)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); upstream.OnNext(10); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(2), new RequestOne()); // one element is still in the pipeline downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(10)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(11)); upstream.OnComplete(); downstream.RequestOne(); // This is correct! If you don't believe, run the interpreter with Debug on lastEvents().Should().BeEquivalentTo(new OnNext(12), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_batch_expand_conflate_expand() { WithOneBoundedSetup<int>(new IGraphStageWithMaterializedValue<Shape, object>[] { new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x), new Expand<int, int>(e => Enumerable.Repeat(e, int.MaxValue).GetEnumerator()) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(0); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(0)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(1)); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(2)); downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); } [Fact] public void Interpreter_should_implement_doubler_batch_doubler_conflate() { WithOneBoundedSetup<int>(new IGraphStageWithMaterializedValue<Shape, object>[] { ToGraphStage(new Doubler<int>()), new Batch<int, int>(1L, e => 0L, e => e, (agg, x) => agg + x) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new RequestOne()); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(6)); }); } // Note, the new interpreter has no jumpback table, still did not want to remove the test [Fact] public void Interpreter_should_work_with_jumpback_table_and_completed_elements() { WithOneBoundedSetup(new IStage<int, int>[] { new Select<int, int>(x => x, Deciders.StoppingDecider), new Select<int, int>(x => x, Deciders.StoppingDecider), new KeepGoing<int>(), new Select<int, int>(x => x, Deciders.StoppingDecider), new Select<int, int>(x => x, Deciders.StoppingDecider) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new OnNext(1)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(2); lastEvents().Should().BeEquivalentTo(new OnNext(2)); upstream.OnComplete(); lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(2)); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new OnNext(2)); }); } [Fact] public void Interpreter_should_work_with_PushAndFinish_if_upstream_completes_with_PushAndFinish() { WithOneBoundedSetup(new PushFinishStage<int>(), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNextAndComplete(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_work_with_PushAndFinish_if_indirect_upstream_completes_with_PushAndFinish() { WithOneBoundedSetup(new IStage<int, int>[] { new Select<int, int>(x => x, Deciders.StoppingDecider), new PushFinishStage<int>(), new Select<int, int>(x => x, Deciders.StoppingDecider) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNextAndComplete(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_work_with_PushAndFinish_if_upstream_completes_with_PushAndFinish_and_downstream_immediately_pulls() { WithOneBoundedSetup(new IStage<int, int>[] { new PushFinishStage<int>(), new Aggregate<int, int>(0, (x, y) => x + y, Deciders.StoppingDecider) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNextAndComplete(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_report_error_if_pull_is_called_while_op_is_terminating() { WithOneBoundedSetup(new PullWhileOpIsTerminating<int>(), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); EventFilter.Exception<ArgumentException>(new Regex(".*Cannot pull a closed port.*")) .ExpectOne(upstream.OnComplete); var ev = lastEvents(); ev.Should().NotBeEmpty(); ev.Where(e => !((e as OnError)?.Cause is ArgumentException)).Should().BeEmpty(); }); } [Fact] public void Interpreter_should_implement_take_take() { WithOneBoundedSetup(new IStage<int, int>[] { new Take<int>(1), new Take<int>(1) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNext(1); lastEvents().Should().BeEquivalentTo(new Cancel(), new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_implement_take_take_with_PushAndFinish_from_upstream() { WithOneBoundedSetup(new IStage<int, int>[] { new Take<int>(1), new Take<int>(1) }, (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); downstream.RequestOne(); lastEvents().Should().BeEquivalentTo(new RequestOne()); upstream.OnNextAndComplete(1); lastEvents().Should().BeEquivalentTo(new OnNext(1), new OnComplete()); }); } [Fact] public void Interpreter_should_not_allow_AbsorbTermination_from_OnDownstreamFinish() { WithOneBoundedSetup(new InvalidAbsorbTermination<int>(), (lastEvents, upstream, downstream) => { lastEvents().Should().BeEmpty(); EventFilter.Exception<NotSupportedException>( "It is not allowed to call AbsorbTermination() from OnDownstreamFinish.") .ExpectOne(() => { downstream.Cancel(); lastEvents().Should().BeEquivalentTo(new Cancel()); }); }); } public class Doubler<T> : PushPullStage<T, T> { private bool _oneMore; private T _lastElement; public override ISyncDirective OnPush(T element, IContext<T> context) { _lastElement = element; _oneMore = true; return context.Push(element); } public override ISyncDirective OnPull(IContext<T> context) { if (_oneMore) { _oneMore = false; return context.Push(_lastElement); } return context.Pull(); } } public class KeepGoing<T> : PushPullStage<T, T> { private T _lastElement; public override ISyncDirective OnPush(T element, IContext<T> context) { _lastElement = element; return context.Push(element); } public override ISyncDirective OnPull(IContext<T> context) { if (context.IsFinishing) { return context.Push(_lastElement); } return context.Pull(); } public override ITerminationDirective OnUpstreamFinish(IContext<T> context) { return context.AbsorbTermination(); } } public class PushFinishStage<T> : PushStage<T, T> { private readonly Action _onPostStop; public PushFinishStage(Action onPostStop = null) { _onPostStop = onPostStop ?? (() => {}); } public override ISyncDirective OnPush(T element, IContext<T> context) { return context.PushAndFinish(element); } public override ITerminationDirective OnUpstreamFinish(IContext<T> context) { return context.Fail(new TestException("Cannot happen")); } public override void PostStop() { _onPostStop(); } } public class PullWhileOpIsTerminating<T> : PushPullStage<T, T> { public override ISyncDirective OnPush(T element, IContext<T> context) { return context.Pull(); } public override ISyncDirective OnPull(IContext<T> context) { return context.Pull(); } public override ITerminationDirective OnUpstreamFinish(IContext<T> context) { return context.AbsorbTermination(); } } public class InvalidAbsorbTermination<T> : PushPullStage<T, T> { public override ISyncDirective OnPush(T element, IContext<T> context) { return context.Push(element); } public override ISyncDirective OnPull(IContext<T> context) { return context.Pull(); } public override ITerminationDirective OnDownstreamFinish(IContext<T> context) { return context.AbsorbTermination(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.InteropServices; using Internal.Runtime; namespace System.Runtime { internal static unsafe class DispatchResolve { [StructLayout(LayoutKind.Sequential)] public struct DispatchMapEntry { public ushort _usInterfaceIndex; public ushort _usInterfaceMethodSlot; public ushort _usImplMethodSlot; } [StructLayout(LayoutKind.Sequential)] public struct DispatchMap { public uint _entryCount; public DispatchMapEntry _dispatchMap; // Actually a variable length array } public static IntPtr FindInterfaceMethodImplementationTarget(EEType* pTgtType, EEType* pItfType, ushort itfSlotNumber) { DynamicModule* dynamicModule = pTgtType->DynamicModule; // Use the dynamic module resolver if it's present if ((dynamicModule != null) && (dynamicModule->DynamicTypeSlotDispatchResolve != IntPtr.Zero)) { return CalliIntrinsics.Call<IntPtr>(dynamicModule->DynamicTypeSlotDispatchResolve, (IntPtr)pTgtType, (IntPtr)pItfType, itfSlotNumber); } // Start at the current type and work up the inheritance chain EEType* pCur = pTgtType; if (pItfType->IsCloned) pItfType = pItfType->CanonicalEEType; while (pCur != null) { UInt16 implSlotNumber; if (FindImplSlotForCurrentType( pCur, pItfType, itfSlotNumber, &implSlotNumber)) { IntPtr targetMethod; if (implSlotNumber < pCur->NumVtableSlots) { // true virtual - need to get the slot from the target type in case it got overridden targetMethod = pTgtType->GetVTableStartAddress()[implSlotNumber]; } else { // sealed virtual - need to get the slot form the implementing type, because // it's not present on the target type targetMethod = pCur->GetSealedVirtualSlot((ushort)(implSlotNumber - pCur->NumVtableSlots)); } return targetMethod; } if (pCur->IsArray) pCur = pCur->GetArrayEEType(); else pCur = pCur->NonArrayBaseType; } return IntPtr.Zero; } private static bool FindImplSlotForCurrentType(EEType* pTgtType, EEType* pItfType, UInt16 itfSlotNumber, UInt16* pImplSlotNumber) { bool fRes = false; // If making a call and doing virtual resolution don't look into the dispatch map, // take the slot number directly. if (!pItfType->IsInterface) { *pImplSlotNumber = itfSlotNumber; // Only notice matches if the target type and search types are the same // This will make dispatch to sealed slots work correctly return pTgtType == pItfType; } if (pTgtType->HasDispatchMap) { // For variant interface dispatch, the algorithm is to walk the parent hierarchy, and at each level // attempt to dispatch exactly first, and then if that fails attempt to dispatch variantly. This can // result in interesting behavior such as a derived type only overriding one particular instantiation // and funneling all the dispatches to it, but its the algorithm. bool fDoVariantLookup = false; // do not check variance for first scan of dispatch map fRes = FindImplSlotInSimpleMap( pTgtType, pItfType, itfSlotNumber, pImplSlotNumber, fDoVariantLookup); if (!fRes) { fDoVariantLookup = true; // check variance for second scan of dispatch map fRes = FindImplSlotInSimpleMap( pTgtType, pItfType, itfSlotNumber, pImplSlotNumber, fDoVariantLookup); } } return fRes; } private static bool FindImplSlotInSimpleMap(EEType* pTgtType, EEType* pItfType, UInt32 itfSlotNumber, UInt16* pImplSlotNumber, bool actuallyCheckVariance) { Debug.Assert(pTgtType->HasDispatchMap, "Missing dispatch map"); EEType* pItfOpenGenericType = null; EETypeRef* pItfInstantiation = null; int itfArity = 0; GenericVariance* pItfVarianceInfo = null; bool fCheckVariance = false; bool fArrayCovariance = false; if (actuallyCheckVariance) { fCheckVariance = pItfType->HasGenericVariance; fArrayCovariance = pTgtType->IsArray; // Non-arrays can follow array variance rules iff // 1. They have one generic parameter // 2. That generic parameter is array covariant. // // This special case is to allow array enumerators to work if (!fArrayCovariance && pTgtType->HasGenericVariance) { int tgtEntryArity = (int)pTgtType->GenericArity; GenericVariance* pTgtVarianceInfo = pTgtType->GenericVariance; if ((tgtEntryArity == 1) && pTgtVarianceInfo[0] == GenericVariance.ArrayCovariant) { fArrayCovariance = true; } } // Arrays are covariant even though you can both get and set elements (type safety is maintained by // runtime type checks during set operations). This extends to generic interfaces implemented on those // arrays. We handle this by forcing all generic interfaces on arrays to behave as though they were // covariant (over their one type parameter corresponding to the array element type). if (fArrayCovariance && pItfType->IsGeneric) fCheckVariance = true; // TypeEquivalent interface dispatch is handled at covariance time. At this time we don't have general // type equivalent interface dispatch, but we do use the model for the interface underlying CastableObject // which is done by checking the interface types involved for ICastable. if (pItfType->IsICastable) fCheckVariance = true; // If there is no variance checking, there is no operation to perform. (The non-variance check loop // has already completed) if (!fCheckVariance) { return false; } } DispatchMap* pMap = pTgtType->DispatchMap; DispatchMapEntry* i = &pMap->_dispatchMap; DispatchMapEntry* iEnd = (&pMap->_dispatchMap) + pMap->_entryCount; for (; i != iEnd; ++i) { if (i->_usInterfaceMethodSlot == itfSlotNumber) { EEType* pCurEntryType = pTgtType->InterfaceMap[i->_usInterfaceIndex].InterfaceType; if (pCurEntryType->IsCloned) pCurEntryType = pCurEntryType->CanonicalEEType; if (pCurEntryType == pItfType) { *pImplSlotNumber = i->_usImplMethodSlot; return true; } else if (fCheckVariance && pCurEntryType->IsICastable && pItfType->IsICastable) { *pImplSlotNumber = i->_usImplMethodSlot; return true; } else if (fCheckVariance && ((fArrayCovariance && pCurEntryType->IsGeneric) || pCurEntryType->HasGenericVariance)) { // Interface types don't match exactly but both the target interface and the current interface // in the map are marked as being generic with at least one co- or contra- variant type // parameter. So we might still have a compatible match. // Retrieve the unified generic instance for the callsite interface if we haven't already (we // lazily get this then cache the result since the lookup isn't necessarily cheap). if (pItfOpenGenericType == null) { pItfOpenGenericType = pItfType->GenericDefinition; itfArity = (int)pItfType->GenericArity; pItfInstantiation = pItfType->GenericArguments; pItfVarianceInfo = pItfType->GenericVariance; } // Retrieve the unified generic instance for the interface we're looking at in the map. EEType* pCurEntryGenericType = pCurEntryType->GenericDefinition; // If the generic types aren't the same then the types aren't compatible. if (pItfOpenGenericType != pCurEntryGenericType) continue; // Grab instantiation details for the candidate interface. EETypeRef* pCurEntryInstantiation = pCurEntryType->GenericArguments; // The types represent different instantiations of the same generic type. The // arity of both had better be the same. Debug.Assert(itfArity == (int)pCurEntryType->GenericArity, "arity mismatch betweeen generic instantiations"); if (TypeCast.TypeParametersAreCompatible(itfArity, pCurEntryInstantiation, pItfInstantiation, pItfVarianceInfo, fArrayCovariance)) { *pImplSlotNumber = i->_usImplMethodSlot; return true; } } } } return false; } } }
// This file has been generated by the GUI designer. Do not modify. namespace Valle.TpvFinal { public partial class ElegirMoneda { private global::Gtk.VBox vbox1; private global::Valle.GtkUtilidades.MiLabel lblTitulo; private global::Gtk.HBox hbox1; private global::Gtk.VBox pneBillestes; private global::Gtk.HButtonBox hbuttonbox1; private global::Gtk.Button btn500; private global::Gtk.Button btn200; private global::Gtk.Button btn100; private global::Gtk.HButtonBox hbuttonbox2; private global::Gtk.Button btn50; private global::Gtk.Button btn20; private global::Gtk.Button btn10; private global::Gtk.HButtonBox hbuttonbox3; private global::Gtk.Button btn5; private global::Gtk.Button btnManual; private global::Gtk.VBox vbox3; private global::Gtk.Image image69; private global::Gtk.Label label1; private global::Gtk.Button btnJusto; private global::Gtk.VBox vbox4; private global::Gtk.Image imgJusto; private global::Gtk.Label label2; private global::Gtk.HBox hbox2; private global::Gtk.Label lblImporte; private global::Gtk.Button btnSalir; private global::Gtk.Button btnBackSp; private global::Gtk.VBox pneMonedas; private global::Gtk.HButtonBox hbuttonbox4; private global::Gtk.Button btn2; private global::Gtk.Button btnVenteC; private global::Gtk.HButtonBox hbuttonbox5; private global::Gtk.Button btn1; private global::Gtk.Button btn10C; private global::Gtk.HButtonBox hbuttonbox6; private global::Gtk.Button btn50C; private global::Gtk.Button btn5C; private global::Gtk.HButtonBox hbuttonbox7; private global::Gtk.Button btnCancelar; private global::Gtk.Button btnAceptar; protected virtual void Init () { global::Stetic.Gui.Initialize (this); // Widget Valle.TpvFinal.ElegirMoneda this.WidthRequest = 700; this.Name ="Valle.Tpv.iconos.ElegirMoneda"; this.Title = global::Mono.Unix.Catalog.GetString ("ElegirMoneda"); this.WindowPosition = ((global::Gtk.WindowPosition)(4)); this.Resizable = false; this.AllowGrow = false; this.SkipTaskbarHint = true; // Container child Valle.TpvFinal.ElegirMoneda.Gtk.Container+ContainerChild this.vbox1 = new global::Gtk.VBox (); this.vbox1.Name = "vbox1"; this.vbox1.Spacing = 6; this.vbox1.BorderWidth = ((uint)(12)); // Container child vbox1.Gtk.Box+BoxChild this.lblTitulo = new global::Valle.GtkUtilidades.MiLabel (); this.lblTitulo.HeightRequest = 25; this.lblTitulo.Events = ((global::Gdk.EventMask)(256)); this.lblTitulo.Name = "lblTitulo"; this.vbox1.Add (this.lblTitulo); global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.lblTitulo])); w1.Position = 0; w1.Expand = false; // Container child vbox1.Gtk.Box+BoxChild this.hbox1 = new global::Gtk.HBox (); this.hbox1.Name = "hbox1"; this.hbox1.Spacing = 6; // Container child hbox1.Gtk.Box+BoxChild this.pneBillestes = new global::Gtk.VBox (); this.pneBillestes.Name = "pneBillestes"; this.pneBillestes.Spacing = 6; // Container child pneBillestes.Gtk.Box+BoxChild this.hbuttonbox1 = new global::Gtk.HButtonBox (); this.hbuttonbox1.Name = "hbuttonbox1"; this.hbuttonbox1.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1)); // Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btn500 = new global::Gtk.Button (); this.btn500.WidthRequest = 120; this.btn500.HeightRequest = 100; this.btn500.CanFocus = true; this.btn500.Name = "btn500"; this.btn500.UseUnderline = true; // Container child btn500.Gtk.Container+ContainerChild global::Gtk.Alignment w2 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w3 = new global::Gtk.HBox (); w3.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w4 = new global::Gtk.Image (); w4.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.500E.jpeg"); w3.Add (w4); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w6 = new global::Gtk.Label (); w3.Add (w6); w2.Add (w3); this.btn500.Add (w2); this.hbuttonbox1.Add (this.btn500); global::Gtk.ButtonBox.ButtonBoxChild w10 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btn500])); w10.Expand = false; w10.Fill = false; // Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btn200 = new global::Gtk.Button (); this.btn200.CanFocus = true; this.btn200.Name = "btn200"; this.btn200.UseUnderline = true; // Container child btn200.Gtk.Container+ContainerChild global::Gtk.Alignment w11 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w12 = new global::Gtk.HBox (); w12.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w13 = new global::Gtk.Image (); w13.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.200E.jpeg"); w12.Add (w13); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w15 = new global::Gtk.Label (); w12.Add (w15); w11.Add (w12); this.btn200.Add (w11); this.hbuttonbox1.Add (this.btn200); global::Gtk.ButtonBox.ButtonBoxChild w19 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btn200])); w19.Position = 1; w19.Expand = false; w19.Fill = false; // Container child hbuttonbox1.Gtk.ButtonBox+ButtonBoxChild this.btn100 = new global::Gtk.Button (); this.btn100.CanFocus = true; this.btn100.Name = "btn100"; this.btn100.UseUnderline = true; // Container child btn100.Gtk.Container+ContainerChild global::Gtk.Alignment w20 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w21 = new global::Gtk.HBox (); w21.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w22 = new global::Gtk.Image (); w22.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.100E.jpeg"); w21.Add (w22); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w24 = new global::Gtk.Label (); w21.Add (w24); w20.Add (w21); this.btn100.Add (w20); this.hbuttonbox1.Add (this.btn100); global::Gtk.ButtonBox.ButtonBoxChild w28 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox1[this.btn100])); w28.Position = 2; w28.Expand = false; w28.Fill = false; this.pneBillestes.Add (this.hbuttonbox1); global::Gtk.Box.BoxChild w29 = ((global::Gtk.Box.BoxChild)(this.pneBillestes[this.hbuttonbox1])); w29.Position = 0; w29.Expand = false; w29.Fill = false; // Container child pneBillestes.Gtk.Box+BoxChild this.hbuttonbox2 = new global::Gtk.HButtonBox (); this.hbuttonbox2.Name = "hbuttonbox2"; this.hbuttonbox2.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1)); // Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild this.btn50 = new global::Gtk.Button (); this.btn50.WidthRequest = 120; this.btn50.HeightRequest = 100; this.btn50.CanFocus = true; this.btn50.Name = "btn50"; this.btn50.UseUnderline = true; // Container child btn50.Gtk.Container+ContainerChild global::Gtk.Alignment w30 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w31 = new global::Gtk.HBox (); w31.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w32 = new global::Gtk.Image (); w32.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.50E.jpeg"); w31.Add (w32); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w34 = new global::Gtk.Label (); w31.Add (w34); w30.Add (w31); this.btn50.Add (w30); this.hbuttonbox2.Add (this.btn50); global::Gtk.ButtonBox.ButtonBoxChild w38 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btn50])); w38.Expand = false; w38.Fill = false; // Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild this.btn20 = new global::Gtk.Button (); this.btn20.CanFocus = true; this.btn20.Name = "btn20"; this.btn20.UseUnderline = true; // Container child btn20.Gtk.Container+ContainerChild global::Gtk.Alignment w39 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w40 = new global::Gtk.HBox (); w40.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w41 = new global::Gtk.Image (); w41.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.20E.jpeg"); w40.Add (w41); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w43 = new global::Gtk.Label (); w40.Add (w43); w39.Add (w40); this.btn20.Add (w39); this.hbuttonbox2.Add (this.btn20); global::Gtk.ButtonBox.ButtonBoxChild w47 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btn20])); w47.Position = 1; w47.Expand = false; w47.Fill = false; // Container child hbuttonbox2.Gtk.ButtonBox+ButtonBoxChild this.btn10 = new global::Gtk.Button (); this.btn10.CanFocus = true; this.btn10.Name = "btn10"; this.btn10.UseUnderline = true; // Container child btn10.Gtk.Container+ContainerChild global::Gtk.Alignment w48 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w49 = new global::Gtk.HBox (); w49.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w50 = new global::Gtk.Image (); w50.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.10E.jpeg"); w49.Add (w50); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w52 = new global::Gtk.Label (); w49.Add (w52); w48.Add (w49); this.btn10.Add (w48); this.hbuttonbox2.Add (this.btn10); global::Gtk.ButtonBox.ButtonBoxChild w56 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox2[this.btn10])); w56.Position = 2; w56.Expand = false; w56.Fill = false; this.pneBillestes.Add (this.hbuttonbox2); global::Gtk.Box.BoxChild w57 = ((global::Gtk.Box.BoxChild)(this.pneBillestes[this.hbuttonbox2])); w57.Position = 1; w57.Expand = false; w57.Fill = false; // Container child pneBillestes.Gtk.Box+BoxChild this.hbuttonbox3 = new global::Gtk.HButtonBox (); this.hbuttonbox3.Name = "hbuttonbox3"; this.hbuttonbox3.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1)); // Container child hbuttonbox3.Gtk.ButtonBox+ButtonBoxChild this.btn5 = new global::Gtk.Button (); this.btn5.WidthRequest = 120; this.btn5.HeightRequest = 100; this.btn5.CanFocus = true; this.btn5.Name = "btn5"; this.btn5.UseUnderline = true; // Container child btn5.Gtk.Container+ContainerChild global::Gtk.Alignment w58 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w59 = new global::Gtk.HBox (); w59.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w60 = new global::Gtk.Image (); w60.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.5E.jpeg"); w59.Add (w60); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w62 = new global::Gtk.Label (); w59.Add (w62); w58.Add (w59); this.btn5.Add (w58); this.hbuttonbox3.Add (this.btn5); global::Gtk.ButtonBox.ButtonBoxChild w66 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox3[this.btn5])); w66.Expand = false; w66.Fill = false; // Container child hbuttonbox3.Gtk.ButtonBox+ButtonBoxChild this.btnManual = new global::Gtk.Button (); this.btnManual.CanFocus = true; this.btnManual.Name = "btnManual"; // Container child btnManual.Gtk.Container+ContainerChild this.vbox3 = new global::Gtk.VBox (); this.vbox3.Name = "vbox3"; this.vbox3.Spacing = 6; // Container child vbox3.Gtk.Box+BoxChild this.image69 = new global::Gtk.Image (); this.image69.Name = "image69"; this.image69.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-edit", global::Gtk.IconSize.Dialog); this.vbox3.Add (this.image69); global::Gtk.Box.BoxChild w67 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.image69])); w67.Position = 0; // Container child vbox3.Gtk.Box+BoxChild this.label1 = new global::Gtk.Label (); this.label1.Name = "label1"; this.label1.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Manual</big>"); this.label1.UseMarkup = true; this.vbox3.Add (this.label1); global::Gtk.Box.BoxChild w68 = ((global::Gtk.Box.BoxChild)(this.vbox3[this.label1])); w68.Position = 1; w68.Expand = false; w68.Fill = false; this.btnManual.Add (this.vbox3); this.btnManual.Label = null; this.hbuttonbox3.Add (this.btnManual); global::Gtk.ButtonBox.ButtonBoxChild w70 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox3[this.btnManual])); w70.Position = 1; w70.Expand = false; w70.Fill = false; // Container child hbuttonbox3.Gtk.ButtonBox+ButtonBoxChild this.btnJusto = new global::Gtk.Button (); this.btnJusto.CanFocus = true; this.btnJusto.Name = "btnJusto1"; // Container child btnJusto1.Gtk.Container+ContainerChild this.vbox4 = new global::Gtk.VBox (); this.vbox4.Name = "vbox4"; this.vbox4.Spacing = 6; // Container child vbox4.Gtk.Box+BoxChild this.imgJusto = new global::Gtk.Image (); this.imgJusto.Name = "imgJusto"; this.imgJusto.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.justo.jpeg"); this.vbox4.Add (this.imgJusto); global::Gtk.Box.BoxChild w71 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.imgJusto])); w71.Position = 0; // Container child vbox4.Gtk.Box+BoxChild this.label2 = new global::Gtk.Label (); this.label2.Name = "label2"; this.label2.LabelProp = global::Mono.Unix.Catalog.GetString ("<big>Justo</big>"); this.label2.UseMarkup = true; this.vbox4.Add (this.label2); global::Gtk.Box.BoxChild w72 = ((global::Gtk.Box.BoxChild)(this.vbox4[this.label2])); w72.Position = 1; w72.Expand = false; w72.Fill = false; this.btnJusto.Add (this.vbox4); this.btnJusto.Label = null; this.hbuttonbox3.Add (this.btnJusto); global::Gtk.ButtonBox.ButtonBoxChild w74 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox3[this.btnJusto])); w74.Position = 2; w74.Expand = false; w74.Fill = false; this.pneBillestes.Add (this.hbuttonbox3); global::Gtk.Box.BoxChild w75 = ((global::Gtk.Box.BoxChild)(this.pneBillestes[this.hbuttonbox3])); w75.Position = 2; w75.Expand = false; w75.Fill = false; // Container child pneBillestes.Gtk.Box+BoxChild this.hbox2 = new global::Gtk.HBox (); this.hbox2.Name = "hbox2"; this.hbox2.Spacing = 6; // Container child hbox2.Gtk.Box+BoxChild this.lblImporte = new global::Gtk.Label (); this.lblImporte.Name = "lblImporte"; this.lblImporte.UseMarkup = true; this.lblImporte.Wrap = true; this.hbox2.Add (this.lblImporte); global::Gtk.Box.BoxChild w76 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.lblImporte])); w76.Position = 0; // Container child hbox2.Gtk.Box+BoxChild this.btnSalir = new global::Gtk.Button (); this.btnSalir.WidthRequest = 120; this.btnSalir.HeightRequest = 100; this.btnSalir.CanFocus = true; this.btnSalir.Name = "btnSalir"; // Container child btnSalir.Gtk.Container+ContainerChild global::Gtk.Alignment w77 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w78 = new global::Gtk.HBox (); w78.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w79 = new global::Gtk.Image (); w79.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.~APP21MB.ICO"); w78.Add (w79); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w81 = new global::Gtk.Label (); w78.Add (w81); w77.Add (w78); this.btnSalir.Add (w77); this.hbox2.Add (this.btnSalir); global::Gtk.Box.BoxChild w85 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.btnSalir])); w85.Position = 1; w85.Expand = false; w85.Fill = false; // Container child hbox2.Gtk.Box+BoxChild this.btnBackSp = new global::Gtk.Button (); this.btnBackSp.WidthRequest = 120; this.btnBackSp.HeightRequest = 100; this.btnBackSp.CanFocus = true; this.btnBackSp.Name = "btnBackSp"; // Container child btnBackSp.Gtk.Container+ContainerChild global::Gtk.Alignment w86 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w87 = new global::Gtk.HBox (); w87.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w88 = new global::Gtk.Image (); w88.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-undo", global::Gtk.IconSize.Dialog); w87.Add (w88); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w90 = new global::Gtk.Label (); w87.Add (w90); w86.Add (w87); this.btnBackSp.Add (w86); this.hbox2.Add (this.btnBackSp); global::Gtk.Box.BoxChild w94 = ((global::Gtk.Box.BoxChild)(this.hbox2[this.btnBackSp])); w94.Position = 2; w94.Expand = false; w94.Fill = false; this.pneBillestes.Add (this.hbox2); global::Gtk.Box.BoxChild w95 = ((global::Gtk.Box.BoxChild)(this.pneBillestes[this.hbox2])); w95.Position = 3; w95.Expand = false; w95.Fill = false; this.hbox1.Add (this.pneBillestes); global::Gtk.Box.BoxChild w96 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.pneBillestes])); w96.Position = 0; // Container child hbox1.Gtk.Box+BoxChild this.pneMonedas = new global::Gtk.VBox (); this.pneMonedas.Name = "pneMonedas"; this.pneMonedas.Spacing = 6; // Container child pneMonedas.Gtk.Box+BoxChild this.hbuttonbox4 = new global::Gtk.HButtonBox (); this.hbuttonbox4.Name = "hbuttonbox4"; this.hbuttonbox4.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1)); // Container child hbuttonbox4.Gtk.ButtonBox+ButtonBoxChild this.btn2 = new global::Gtk.Button (); this.btn2.WidthRequest = 120; this.btn2.HeightRequest = 100; this.btn2.CanFocus = true; this.btn2.Name = "btn2"; this.btn2.UseUnderline = true; // Container child btn2.Gtk.Container+ContainerChild global::Gtk.Alignment w97 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w98 = new global::Gtk.HBox (); w98.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w99 = new global::Gtk.Image (); w99.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.dosE.jpeg"); w98.Add (w99); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w101 = new global::Gtk.Label (); w98.Add (w101); w97.Add (w98); this.btn2.Add (w97); this.hbuttonbox4.Add (this.btn2); global::Gtk.ButtonBox.ButtonBoxChild w105 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox4[this.btn2])); w105.Expand = false; w105.Fill = false; // Container child hbuttonbox4.Gtk.ButtonBox+ButtonBoxChild this.btnVenteC = new global::Gtk.Button (); this.btnVenteC.CanFocus = true; this.btnVenteC.Name = "btnVenteC"; this.btnVenteC.UseUnderline = true; // Container child btnVenteC.Gtk.Container+ContainerChild global::Gtk.Alignment w106 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w107 = new global::Gtk.HBox (); w107.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w108 = new global::Gtk.Image (); w108.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.20C.jpeg"); w107.Add (w108); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w110 = new global::Gtk.Label (); w107.Add (w110); w106.Add (w107); this.btnVenteC.Add (w106); this.hbuttonbox4.Add (this.btnVenteC); global::Gtk.ButtonBox.ButtonBoxChild w114 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox4[this.btnVenteC])); w114.Position = 1; w114.Expand = false; w114.Fill = false; this.pneMonedas.Add (this.hbuttonbox4); global::Gtk.Box.BoxChild w115 = ((global::Gtk.Box.BoxChild)(this.pneMonedas[this.hbuttonbox4])); w115.Position = 0; w115.Expand = false; w115.Fill = false; // Container child pneMonedas.Gtk.Box+BoxChild this.hbuttonbox5 = new global::Gtk.HButtonBox (); this.hbuttonbox5.Name = "hbuttonbox5"; this.hbuttonbox5.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1)); // Container child hbuttonbox5.Gtk.ButtonBox+ButtonBoxChild this.btn1 = new global::Gtk.Button (); this.btn1.WidthRequest = 120; this.btn1.HeightRequest = 100; this.btn1.CanFocus = true; this.btn1.Name = "btn1"; this.btn1.UseUnderline = true; // Container child btn1.Gtk.Container+ContainerChild global::Gtk.Alignment w116 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w117 = new global::Gtk.HBox (); w117.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w118 = new global::Gtk.Image (); w118.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.UnE.jpeg"); w117.Add (w118); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w120 = new global::Gtk.Label (); w117.Add (w120); w116.Add (w117); this.btn1.Add (w116); this.hbuttonbox5.Add (this.btn1); global::Gtk.ButtonBox.ButtonBoxChild w124 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox5[this.btn1])); w124.Expand = false; w124.Fill = false; // Container child hbuttonbox5.Gtk.ButtonBox+ButtonBoxChild this.btn10C = new global::Gtk.Button (); this.btn10C.CanFocus = true; this.btn10C.Name = "btn10C"; this.btn10C.UseUnderline = true; // Container child btn10C.Gtk.Container+ContainerChild global::Gtk.Alignment w125 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w126 = new global::Gtk.HBox (); w126.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w127 = new global::Gtk.Image (); w127.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.10C.jpeg"); w126.Add (w127); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w129 = new global::Gtk.Label (); w126.Add (w129); w125.Add (w126); this.btn10C.Add (w125); this.hbuttonbox5.Add (this.btn10C); global::Gtk.ButtonBox.ButtonBoxChild w133 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox5[this.btn10C])); w133.Position = 1; w133.Expand = false; w133.Fill = false; this.pneMonedas.Add (this.hbuttonbox5); global::Gtk.Box.BoxChild w134 = ((global::Gtk.Box.BoxChild)(this.pneMonedas[this.hbuttonbox5])); w134.Position = 1; w134.Expand = false; w134.Fill = false; // Container child pneMonedas.Gtk.Box+BoxChild this.hbuttonbox6 = new global::Gtk.HButtonBox (); this.hbuttonbox6.Name = "hbuttonbox6"; this.hbuttonbox6.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1)); // Container child hbuttonbox6.Gtk.ButtonBox+ButtonBoxChild this.btn50C = new global::Gtk.Button (); this.btn50C.WidthRequest = 120; this.btn50C.HeightRequest = 100; this.btn50C.CanFocus = true; this.btn50C.Name = "btn50C"; this.btn50C.UseUnderline = true; // Container child btn50C.Gtk.Container+ContainerChild global::Gtk.Alignment w135 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w136 = new global::Gtk.HBox (); w136.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w137 = new global::Gtk.Image (); w137.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.50C.jpeg"); w136.Add (w137); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w139 = new global::Gtk.Label (); w136.Add (w139); w135.Add (w136); this.btn50C.Add (w135); this.hbuttonbox6.Add (this.btn50C); global::Gtk.ButtonBox.ButtonBoxChild w143 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox6[this.btn50C])); w143.Expand = false; w143.Fill = false; // Container child hbuttonbox6.Gtk.ButtonBox+ButtonBoxChild this.btn5C = new global::Gtk.Button (); this.btn5C.CanFocus = true; this.btn5C.Name = "btn5C"; // Container child btn5C.Gtk.Container+ContainerChild global::Gtk.Alignment w144 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w145 = new global::Gtk.HBox (); w145.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w146 = new global::Gtk.Image (); w146.Pixbuf = global::Gdk.Pixbuf.LoadFromResource ("Valle.Tpv.iconos.5C.jpeg"); w145.Add (w146); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w148 = new global::Gtk.Label (); w145.Add (w148); w144.Add (w145); this.btn5C.Add (w144); this.hbuttonbox6.Add (this.btn5C); global::Gtk.ButtonBox.ButtonBoxChild w152 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox6[this.btn5C])); w152.Position = 1; w152.Expand = false; w152.Fill = false; this.pneMonedas.Add (this.hbuttonbox6); global::Gtk.Box.BoxChild w153 = ((global::Gtk.Box.BoxChild)(this.pneMonedas[this.hbuttonbox6])); w153.Position = 2; w153.Expand = false; w153.Fill = false; // Container child pneMonedas.Gtk.Box+BoxChild this.hbuttonbox7 = new global::Gtk.HButtonBox (); this.hbuttonbox7.Name = "hbuttonbox7"; this.hbuttonbox7.LayoutStyle = ((global::Gtk.ButtonBoxStyle)(1)); // Container child hbuttonbox7.Gtk.ButtonBox+ButtonBoxChild this.btnCancelar = new global::Gtk.Button (); this.btnCancelar.WidthRequest = 120; this.btnCancelar.HeightRequest = 100; this.btnCancelar.CanFocus = true; this.btnCancelar.Name = "btnCancelar"; this.btnCancelar.UseUnderline = true; // Container child btnCancelar.Gtk.Container+ContainerChild global::Gtk.Alignment w154 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w155 = new global::Gtk.HBox (); w155.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w156 = new global::Gtk.Image (); w156.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-cancel", global::Gtk.IconSize.Dialog); w155.Add (w156); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w158 = new global::Gtk.Label (); w155.Add (w158); w154.Add (w155); this.btnCancelar.Add (w154); this.hbuttonbox7.Add (this.btnCancelar); global::Gtk.ButtonBox.ButtonBoxChild w162 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox7[this.btnCancelar])); w162.Expand = false; w162.Fill = false; // Container child hbuttonbox7.Gtk.ButtonBox+ButtonBoxChild this.btnAceptar = new global::Gtk.Button (); this.btnAceptar.CanFocus = true; this.btnAceptar.Name = "btnAceptar"; // Container child btnAceptar.Gtk.Container+ContainerChild global::Gtk.Alignment w163 = new global::Gtk.Alignment (0.5f, 0.5f, 0f, 0f); // Container child GtkAlignment.Gtk.Container+ContainerChild global::Gtk.HBox w164 = new global::Gtk.HBox (); w164.Spacing = 2; // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Image w165 = new global::Gtk.Image (); w165.Pixbuf = global::Stetic.IconLoaderEx.LoadIcon (this, "gtk-apply", global::Gtk.IconSize.Dialog); w164.Add (w165); // Container child GtkHBox.Gtk.Container+ContainerChild global::Gtk.Label w167 = new global::Gtk.Label (); w164.Add (w167); w163.Add (w164); this.btnAceptar.Add (w163); this.hbuttonbox7.Add (this.btnAceptar); global::Gtk.ButtonBox.ButtonBoxChild w171 = ((global::Gtk.ButtonBox.ButtonBoxChild)(this.hbuttonbox7[this.btnAceptar])); w171.Position = 1; w171.Expand = false; w171.Fill = false; this.pneMonedas.Add (this.hbuttonbox7); global::Gtk.Box.BoxChild w172 = ((global::Gtk.Box.BoxChild)(this.pneMonedas[this.hbuttonbox7])); w172.Position = 3; w172.Expand = false; w172.Fill = false; this.hbox1.Add (this.pneMonedas); global::Gtk.Box.BoxChild w173 = ((global::Gtk.Box.BoxChild)(this.hbox1[this.pneMonedas])); w173.Position = 1; this.vbox1.Add (this.hbox1); global::Gtk.Box.BoxChild w174 = ((global::Gtk.Box.BoxChild)(this.vbox1[this.hbox1])); w174.Position = 1; w174.Expand = false; w174.Fill = false; this.Add (this.vbox1); if ((this.Child != null)) { this.Child.ShowAll (); } this.DefaultWidth = 702; this.DefaultHeight = 525; this.pneMonedas.Hide (); this.btn500.Clicked += new global::System.EventHandler (this.OnBtn500Clicked); this.btn200.Clicked += new global::System.EventHandler (this.OnBtn200Clicked); this.btn100.Clicked += new global::System.EventHandler (this.OnBtn100Clicked); this.btn50.Clicked += new global::System.EventHandler (this.OnBtn50Clicked); this.btn20.Clicked += new global::System.EventHandler (this.OnBtn20Clicked); this.btn10.Clicked += new global::System.EventHandler (this.OnBtn10Clicked); this.btn5.Clicked += new global::System.EventHandler (this.OnBtn5Clicked); this.btnManual.Clicked += new global::System.EventHandler (this.OnBtnManualClicked); this.btnJusto.Clicked += new global::System.EventHandler (this.OnBtnJusto1Clicked); this.btnSalir.Clicked += new global::System.EventHandler (this.OnBtnSalirClicked); this.btnBackSp.Clicked += new global::System.EventHandler (this.OnBtnBackSpClicked); this.btn2.Clicked += new global::System.EventHandler (this.OnBtn2Clicked); this.btnVenteC.Clicked += new global::System.EventHandler (this.OnBtn21Clicked); this.btn1.Clicked += new global::System.EventHandler (this.OnBtn1Clicked); this.btn10C.Clicked += new global::System.EventHandler (this.OnBtn11Clicked); this.btn50C.Clicked += new global::System.EventHandler (this.OnBtn51Clicked); this.btn5C.Clicked += new global::System.EventHandler (this.OnBtn6Clicked); this.btnCancelar.Clicked += new global::System.EventHandler (this.OnBtnCancelarClicked); this.btnAceptar.Clicked += new global::System.EventHandler (this.OnBtnAceptarClicked); } } }
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Text; using System.Collections.Generic; using ASPNET.StarterKit.BusinessLogicLayer; public partial class Project_Details_aspx : System.Web.UI.Page { public Project_Details_aspx() { LoadComplete += new EventHandler(Page_LoadComplete); } private Project CurrentProject = null; void GetCurrentProject() { int projectIdFromQueryString; if (Request.QueryString["ProjectId"] != null && Int32.TryParse((string)Request.QueryString["ProjectId"], out projectIdFromQueryString)) { CurrentProject = Project.GetProjectById(projectIdFromQueryString); } } void Page_Load(object sender, EventArgs e) { GetCurrentProject(); if (!Page.IsPostBack) { ManagerData.SelectParameters.Add(new Parameter("roleName", TypeCode.String, "ProjectManager")); ProjectConsultantData.SelectParameters.Add(new Parameter("roleName", TypeCode.String, "Consultant")); if (CurrentProject != null) { ProjectName.Text = CurrentProject.Name; DateTime dt = Convert.ToDateTime(CurrentProject.CompletionDate); CompletionDate.Text = dt.ToString("d"); Duration.Text = Convert.ToString(CurrentProject.EstimateDuration); Description.Text = CurrentProject.Description; Managers.SelectedValue = CurrentProject.ManagerUserName; Consultants.DataBind(); ProjectCategoryColumn.Visible = true; } else { ProjectCategoryColumn.Visible = false; } if ((Page.User.IsInRole("ProjectAdministrator"))) ProjectData.SelectMethod = "GetAllProjects"; else { ProjectData.SelectParameters.Add(new Parameter("userName", TypeCode.String, Page.User.Identity.Name)); ProjectData.SelectMethod = "GetProjectsByManagerUserName"; ProjectData.SortParameterName = "sortParameter"; } } DeleteButton2.Attributes.Add("onclick", "return confirm('Deleting a project will also delete all the time entries and categories associated with the project. This deletion cannot be undone. Are you sure you want to delete this project?')"); } void Page_LoadComplete(object sender, EventArgs e) { if (CurrentProject != null) { SelectProjectMembers(CurrentProject.Id); } } void Page_PreRender(object sender, EventArgs e) { ViewState["ActiveConsultants"] = BuildValueList(Consultants.Items, true); } protected void AddButton_Click(object obj, EventArgs args) { if (Page.IsValid == false) return; if (CurrentProject != null) { bool wasCategorySave = false; Category newCategory = new Category(Abbrev.Text, Convert.ToDecimal(CatDuration.Text), CategoryName.Text, CurrentProject.Id); wasCategorySave = newCategory.Save(); ListAllCategories.DataBind(); } } protected string BuildValueList(ListItemCollection items, bool itemMustBeSelected) { StringBuilder idList = new StringBuilder(); foreach (ListItem item in items) { if (itemMustBeSelected && !item.Selected) continue; else { idList.Append(item.Value.ToString()); idList.Append(","); } } return idList.ToString(); } protected void CancelButton_Click(object obj, EventArgs args) { Response.Redirect("Project_List.aspx"); } protected void CopyButton_Click(object obj, EventArgs args) { if (CurrentProject != null) { int selectedProjectId = Convert.ToInt32(ProjectList.SelectedValue); List<Category> newCategories = Category.GetCategoriesByProjectId(selectedProjectId); foreach (Category cat in newCategories) { Category newCat = new Category(cat.Abbreviation, cat.EstimateDuration, cat.Name, CurrentProject.Id); newCat.Save(); } CategoryData.DataBind(); ListAllCategories.DataBind(); } } protected void DeleteButton_Click(object obj, EventArgs args) { if (CurrentProject != null) { Project newProject = Project.GetProjectById(CurrentProject.Id); newProject.Delete(); Response.Redirect("Project_List.aspx"); } } protected void SaveButton_Click(object obj, EventArgs args) { if (Page.IsValid == false) return; Project newProject; if (CurrentProject != null) { newProject = Project.GetProjectById(CurrentProject.Id); } else newProject = new Project(Page.User.Identity.Name, Page.User.Identity.Name, ProjectName.Text); newProject.Name = ProjectName.Text; newProject.CompletionDate = Convert.ToDateTime(CompletionDate.Text); newProject.Description = Description.Text; newProject.EstimateDuration = Convert.ToDecimal(Duration.Text); newProject.ManagerUserName = Managers.SelectedItem.Value; if (!newProject.Save()) { ErrorMessage.Text = "There was an error. Please fix it and try it again."; } UpdateProjectMembers(newProject.Id); string strUrl = "Project_Details.aspx?ProjectId=" + newProject.Id.ToString(); Response.Redirect(strUrl); } protected void SelectProjectMembers(int projectId) { Consultants.DataBind(); List<string> userList = Project.GetProjectMembers(projectId); foreach (string user in userList) { ListItem item = Consultants.Items.FindByValue(user); item.Selected = true; } } protected void UpdateProjectMembers(int projectId) { string activeConsultants = string.Empty; if (ViewState["ActiveConsultants"] != null) { activeConsultants = ViewState["ActiveConsultants"].ToString(); } foreach (ListItem item in Consultants.Items) { if (item.Selected) { if (!activeConsultants.Contains(item.Value + ",")) { Project.AddUserToProject(projectId, item.Text); } } else { if (activeConsultants.Contains(item.Value + ",")) { Project.RemoveUserFromProject(projectId, item.Text); } } } } protected void ProjectList_PreRender(object sender, EventArgs e) { ListItem item = ProjectList.Items.FindByText(ProjectName.Text); if (item != null) { ProjectList.Items.Remove(item); } if (ProjectList.Items.Count == 0) { ProjectList.Enabled = false; } } protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) { if (Description.Text.Length > 200) args.IsValid = false; else args.IsValid = true; } }
namespace Microsoft.Protocols.TestSuites.Common.DataStructures { using System; /// <summary> /// This class contains all the properties which are associated with the elements defined in the MS-ASNOTE protocol /// </summary> public class Note { /// <summary> /// Gets or sets note body information of the note, which contains type and content of the note /// </summary> public Response.Body Body { get; set; } /// <summary> /// Gets or sets Categories information of the note /// </summary> public Response.Categories3 Categories { get; set; } /// <summary> /// Gets or sets a value indicating whether include LastModifiedDate in the response /// </summary> public bool IsLastModifiedDateSpecified { get; set; } /// <summary> /// Gets or sets LastModifiedDate information of the note /// </summary> public DateTime LastModifiedDate { get; set; } /// <summary> /// Gets or sets MessageClass information of the note /// </summary> public string MessageClass { get; set; } /// <summary> /// Gets or sets subject information of the note /// </summary> public string Subject { get; set; } /// <summary> /// Gets or sets the value of LastModifiedDate element from the server response /// </summary> public string LastModifiedDateString { get; set; } /// <summary> /// Deserialize to object instance from Properties /// </summary> /// <typeparam name="T">The generic type parameter</typeparam> /// <param name="properties">The Properties data which contains new added information</param> /// <returns>The object instance</returns> public static T DeserializeFromFetchProperties<T>(Response.Properties properties) { T obj = Activator.CreateInstance<T>(); if (properties.ItemsElementName.Length > 0) { for (int itemIndex = 0; itemIndex < properties.ItemsElementName.Length; itemIndex++) { switch (properties.ItemsElementName[itemIndex]) { case Response.ItemsChoiceType3.Categories: case Response.ItemsChoiceType3.Categories1: case Response.ItemsChoiceType3.Categories2: case Response.ItemsChoiceType3.Categories4: case Response.ItemsChoiceType3.LastModifiedDate: case Response.ItemsChoiceType3.Subject: case Response.ItemsChoiceType3.Subject1: case Response.ItemsChoiceType3.Subject3: case Response.ItemsChoiceType3.MessageClass: break; case Response.ItemsChoiceType3.Categories3: Common.SetSpecifiedPropertyValueByName(obj, "Categories", properties.Items[itemIndex]); break; case Response.ItemsChoiceType3.Body: Common.SetSpecifiedPropertyValueByName(obj, "Body", properties.Items[itemIndex]); break; case Response.ItemsChoiceType3.LastModifiedDate1: string lastModifiedDateString = properties.Items[itemIndex].ToString(); if (!string.IsNullOrEmpty(lastModifiedDateString)) { Common.SetSpecifiedPropertyValueByName(obj, "IsLastModifiedDateSpecified", true); Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDate", Common.GetNoSeparatorDateTime(lastModifiedDateString)); Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDateString", lastModifiedDateString); } break; case Response.ItemsChoiceType3.Subject2: Common.SetSpecifiedPropertyValueByName(obj, "Subject", properties.Items[itemIndex]); break; case Response.ItemsChoiceType3.MessageClass1: Common.SetSpecifiedPropertyValueByName(obj, "MessageClass", properties.Items[itemIndex]); break; default: Common.SetSpecifiedPropertyValueByName(obj, properties.ItemsElementName[itemIndex].ToString(), properties.Items[itemIndex]); break; } } } return obj; } /// <summary> /// Get note instance from the Properties element of Search response /// </summary> /// <typeparam name="T">The generic type parameter</typeparam> /// <param name="properties">The data which contains information for note</param> /// <returns>The returned note instance</returns> public static T DeserializeFromSearchProperties<T>(Response.SearchResponseStoreResultProperties properties) { T obj = Activator.CreateInstance<T>(); if (properties.ItemsElementName.Length > 0) { for (int itemIndex = 0; itemIndex < properties.ItemsElementName.Length; itemIndex++) { switch (properties.ItemsElementName[itemIndex]) { case Response.ItemsChoiceType6.Categories: case Response.ItemsChoiceType6.Categories1: case Response.ItemsChoiceType6.Categories3: case Response.ItemsChoiceType6.Subject: case Response.ItemsChoiceType6.Subject1: case Response.ItemsChoiceType6.Subject3: case Response.ItemsChoiceType6.LastModifiedDate: case Response.ItemsChoiceType6.MessageClass: break; case Response.ItemsChoiceType6.Categories2: Common.SetSpecifiedPropertyValueByName(obj, "Categories", (Response.Categories3)properties.Items[itemIndex]); break; case Response.ItemsChoiceType6.Subject2: Common.SetSpecifiedPropertyValueByName(obj, "Subject", properties.Items[itemIndex]); break; case Response.ItemsChoiceType6.Body: Common.SetSpecifiedPropertyValueByName(obj, "Body", (Response.Body)properties.Items[itemIndex]); break; case Response.ItemsChoiceType6.LastModifiedDate1: string lastModifiedDateString = properties.Items[itemIndex].ToString(); if (!string.IsNullOrEmpty(lastModifiedDateString)) { Common.SetSpecifiedPropertyValueByName(obj, "IsLastModifiedDateSpecified", true); Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDate", Common.GetNoSeparatorDateTime(lastModifiedDateString)); Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDateString", lastModifiedDateString); } break; case Response.ItemsChoiceType6.MessageClass1: Common.SetSpecifiedPropertyValueByName(obj, "MessageClass", properties.Items[itemIndex]); break; default: Common.SetSpecifiedPropertyValueByName(obj, properties.ItemsElementName[itemIndex].ToString(), properties.Items[itemIndex]); break; } } } return obj; } /// <summary> /// Get note instance from the ApplicationData element of Sync add response /// </summary> /// <typeparam name="T">The generic type parameter</typeparam> /// <param name="applicationData">The data which contains information for note</param> /// <returns>The returned instance</returns> public static T DeserializeFromAddApplicationData<T>(Response.SyncCollectionsCollectionCommandsAddApplicationData applicationData) { T obj = Activator.CreateInstance<T>(); if (applicationData.ItemsElementName.Length > 0) { for (int itemIndex = 0; itemIndex < applicationData.ItemsElementName.Length; itemIndex++) { switch (applicationData.ItemsElementName[itemIndex]) { case Response.ItemsChoiceType8.Categories: case Response.ItemsChoiceType8.Categories1: case Response.ItemsChoiceType8.Categories2: case Response.ItemsChoiceType8.Categories4: case Response.ItemsChoiceType8.Subject: case Response.ItemsChoiceType8.Subject1: case Response.ItemsChoiceType8.Subject3: case Response.ItemsChoiceType8.LastModifiedDate: case Response.ItemsChoiceType8.MessageClass: break; case Response.ItemsChoiceType8.Categories3: Common.SetSpecifiedPropertyValueByName(obj, "Categories", applicationData.Items[itemIndex]); break; case Response.ItemsChoiceType8.Subject2: Common.SetSpecifiedPropertyValueByName(obj, "Subject", applicationData.Items[itemIndex]); break; case Response.ItemsChoiceType8.Body: Common.SetSpecifiedPropertyValueByName(obj, "Body", applicationData.Items[itemIndex]); break; case Response.ItemsChoiceType8.LastModifiedDate1: string lastModifiedDateString = applicationData.Items[itemIndex].ToString(); if (!string.IsNullOrEmpty(lastModifiedDateString)) { Common.SetSpecifiedPropertyValueByName(obj, "IsLastModifiedDateSpecified", true); Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDate", Common.GetNoSeparatorDateTime(lastModifiedDateString)); Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDateString", lastModifiedDateString); } break; case Response.ItemsChoiceType8.MessageClass1: Common.SetSpecifiedPropertyValueByName(obj, "MessageClass", applicationData.Items[itemIndex]); break; default: Common.SetSpecifiedPropertyValueByName(obj, applicationData.ItemsElementName[itemIndex].ToString(), applicationData.Items[itemIndex]); break; } } } return obj; } /// <summary> /// Get note instance from the ApplicationData element of Sync change response /// </summary> /// <typeparam name="T">The generic type parameter</typeparam> /// <param name="applicationData">The data which contains information for note</param> /// <returns>The returned instance</returns> public static T DeserializeFromChangeApplicationData<T>(Response.SyncCollectionsCollectionCommandsChangeApplicationData applicationData) { T obj = Activator.CreateInstance<T>(); if (applicationData.ItemsElementName.Length > 0) { for (int itemIndex = 0; itemIndex < applicationData.ItemsElementName.Length; itemIndex++) { switch (applicationData.ItemsElementName[itemIndex]) { case Response.ItemsChoiceType7.Categories: case Response.ItemsChoiceType7.Categories1: case Response.ItemsChoiceType7.Categories2: case Response.ItemsChoiceType7.Categories4: case Response.ItemsChoiceType7.Subject: case Response.ItemsChoiceType7.Subject1: case Response.ItemsChoiceType7.Subject3: case Response.ItemsChoiceType7.LastModifiedDate: case Response.ItemsChoiceType7.MessageClass: break; case Response.ItemsChoiceType7.Categories3: Common.SetSpecifiedPropertyValueByName(obj, "Categories", applicationData.Items[itemIndex]); break; case Response.ItemsChoiceType7.Subject2: Common.SetSpecifiedPropertyValueByName(obj, "Subject", applicationData.Items[itemIndex]); break; case Response.ItemsChoiceType7.Body: Common.SetSpecifiedPropertyValueByName(obj, "Body", applicationData.Items[itemIndex]); break; case Response.ItemsChoiceType7.LastModifiedDate1: string lastModifiedDateString = applicationData.Items[itemIndex].ToString(); if (!string.IsNullOrEmpty(lastModifiedDateString)) { Common.SetSpecifiedPropertyValueByName(obj, "IsLastModifiedDateSpecified", true); Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDate", Common.GetNoSeparatorDateTime(lastModifiedDateString)); Common.SetSpecifiedPropertyValueByName(obj, "LastModifiedDateString", lastModifiedDateString); } break; case Response.ItemsChoiceType7.MessageClass1: Common.SetSpecifiedPropertyValueByName(obj, "MessageClass", applicationData.Items[itemIndex]); break; default: Common.SetSpecifiedPropertyValueByName(obj, applicationData.ItemsElementName[itemIndex].ToString(), applicationData.Items[itemIndex]); break; } } } return obj; } } }
/* Matali Physics Demo Copyright (c) 2013 KOMIRES Sp. z o. o. */ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics.OpenGL; using OpenTK.Input; using Komires.MataliPhysics; using Komires.MataliRender; namespace MataliPhysicsDemo { /// <summary> /// This is the main type for your game /// </summary> public class Camera2Draw1 { Demo demo; PhysicsScene scene; string instanceIndexName; string quadName; DemoKeyboardState oldKeyboardState; bool enableDrawBoundingBoxes; bool enableDrawContactPoints; bool enableDrawSlipingObjects; bool enableDrawImpactFactors; bool enableDrawLights; bool enableWireframe; DrawBuffersEnum[] targets; RenderClearDeferredQuadP renderClear; RenderLightDirectionalDeferredQuadP renderLightDirectional; RenderLightPointDeferredP renderLightPoint; RenderLightSpotDeferredP renderLightSpot; RenderScreenDeferredQuadP renderScreen; RenderPC render; VertexPositionColor[] cameraVertices; Vector3 position; Vector3 direction; Vector3 lightDiffuse; Vector3 lightSpecular; BoundingBox boundingBox; Matrix4 world; Matrix4 view; Matrix4 projection; Matrix4 matrixIdentity; public Camera2Draw1(Demo demo, int instanceIndex) { this.demo = demo; instanceIndexName = " " + instanceIndex.ToString(); quadName = "Quad"; matrixIdentity = Matrix4.Identity; } public void Initialize(PhysicsScene scene) { this.scene = scene; targets = new DrawBuffersEnum[4]; cameraVertices = new VertexPositionColor[24]; renderClear = new RenderClearDeferredQuadP(); renderLightDirectional = new RenderLightDirectionalDeferredQuadP(); renderLightPoint = new RenderLightPointDeferredP(); renderLightSpot = new RenderLightSpotDeferredP(); renderScreen = new RenderScreenDeferredQuadP(); render = new RenderPC(); } public void SetControllers(bool enableDrawBoundingBoxes, bool enableDrawContactPoints, bool enableDrawSlipingObjects, bool enableDrawImpactFactors, bool enableDrawLights, bool enableWireframe) { oldKeyboardState = demo.GetKeyboardState(); this.enableDrawBoundingBoxes = enableDrawBoundingBoxes; this.enableDrawContactPoints = enableDrawContactPoints; this.enableDrawSlipingObjects = enableDrawSlipingObjects; this.enableDrawImpactFactors = enableDrawImpactFactors; this.enableDrawLights = enableDrawLights; this.enableWireframe = enableWireframe; PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Find("Camera 2 Up" + instanceIndexName); if (objectBase != null) { objectBase.UserControllers.DrawMethods += new DrawMethod(Draw); objectBase.UserControllers.DrawMethods += new DrawMethod(DrawBoundingBoxes); objectBase.UserControllers.DrawMethods += new DrawMethod(DrawContactPoints); objectBase.UserControllers.DrawMethods += new DrawMethod(DrawImpactFactors); } } public void RefreshControllers() { oldKeyboardState = demo.GetKeyboardState(); } public void Draw(DrawMethodArgs args) { PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex); PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex); if (!objectBase.Camera.Enabled) return; if (!objectBase.Camera.Active) return; DemoKeyboardState keyboardState = demo.GetKeyboardState(); if (keyboardState[Key.B] && !oldKeyboardState[Key.B]) enableDrawBoundingBoxes = !enableDrawBoundingBoxes; if (keyboardState[Key.C] && !oldKeyboardState[Key.C]) enableDrawContactPoints = !enableDrawContactPoints; if (keyboardState[Key.V] && !oldKeyboardState[Key.V]) enableDrawSlipingObjects = !enableDrawSlipingObjects; if (keyboardState[Key.I] && !oldKeyboardState[Key.I]) enableDrawImpactFactors = !enableDrawImpactFactors; if (keyboardState[Key.G] && !oldKeyboardState[Key.G]) enableDrawLights = !enableDrawLights; if (keyboardState[Key.N] && !oldKeyboardState[Key.N]) enableWireframe = !enableWireframe; oldKeyboardState = keyboardState; demo.EnableWireframe = enableWireframe; PhysicsObject menuPhysicsObjectWithCamera = demo.MenuScene.PhysicsScene.GetPhysicsObjectWithCamera(0); if (menuPhysicsObjectWithCamera != null) { if (menuPhysicsObjectWithCamera.Camera.UserDataObj != null) { Camera3Draw1 menuCamera = menuPhysicsObjectWithCamera.Camera.UserDataObj as Camera3Draw1; if (menuCamera != null) { menuCamera.EnableDrawBoundingBoxes = enableDrawBoundingBoxes; menuCamera.EnableDrawContactPoints = enableDrawContactPoints; menuCamera.EnableDrawSlipingObjects = enableDrawSlipingObjects; menuCamera.EnableDrawLights = enableDrawLights; menuCamera.EnableWireframe = enableWireframe; } } } float time = args.Time; PhysicsObject drawPhysicsObject, transparentPhysicsObject, lightPhysicsObject; PhysicsLight sceneLight, drawLight; DemoMesh mesh, quad; objectBase.Camera.View.GetViewMatrix(ref view); objectBase.Camera.Projection.GetProjectionMatrix(ref projection); sceneLight = scene.Light; quad = demo.Meshes[quadName]; GL.BindFramebuffer(FramebufferTarget.Framebuffer, demo.SceneFrameBuffer); targets[0] = DrawBuffersEnum.ColorAttachment0; targets[1] = DrawBuffersEnum.ColorAttachment1; targets[2] = DrawBuffersEnum.ColorAttachment2; targets[3] = DrawBuffersEnum.ColorAttachment3; GL.DrawBuffers(4, targets); GL.Clear(ClearBufferMask.DepthBufferBit); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.Zero); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.Disable(EnableCap.Blend); GL.Disable(EnableCap.DepthTest); GL.DepthMask(false); GL.Disable(EnableCap.CullFace); renderClear.SetClearScreenColor(ref demo.ClearScreenColor); quad.Draw(renderClear); GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.DepthTest); GL.DepthMask(true); for (int i = 0; i < objectBase.Camera.DrawPhysicsObjectCount; i++) { drawPhysicsObject = objectBase.Camera.GetDrawPhysicsObject(i); if ((drawPhysicsObject.UserControllers.DrawMethods == null) || (drawPhysicsObject == objectBase)) { if (drawPhysicsObject.UserDataStr == null) continue; if ((drawPhysicsObject.Shape == null) && drawPhysicsObject.IsBrokenRigidGroup) continue; if ((drawPhysicsObject.RigidGroupOwner != drawPhysicsObject) && (drawPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; drawPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); mesh = demo.Meshes[drawPhysicsObject.UserDataStr]; mesh.Draw(ref world, ref view, ref projection, sceneLight, drawPhysicsObject.Material, objectBase.Camera, drawPhysicsObject.RigidGroupOwner.IsSleeping && enableDrawSlipingObjects, enableWireframe); } else { if (drawPhysicsObject.UserControllers.EnableDraw) continue; if ((drawPhysicsObject.Shape == null) && drawPhysicsObject.IsBrokenRigidGroup) continue; if ((drawPhysicsObject.RigidGroupOwner != drawPhysicsObject) && (drawPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; drawPhysicsObject.UserControllers.DrawMethodArgs.Time = time; drawPhysicsObject.UserControllers.DrawMethodArgs.OwnerIndex = drawPhysicsObject.Index; drawPhysicsObject.UserControllers.DrawMethodArgs.OwnerSceneIndex = scene.Index; drawPhysicsObject.UserControllers.DrawMethods(drawPhysicsObject.UserControllers.DrawMethodArgs); } } if (objectBase.Camera.TransparentPhysicsObjectCount != 0) { targets[0] = DrawBuffersEnum.ColorAttachment0; targets[1] = DrawBuffersEnum.ColorAttachment1; targets[2] = DrawBuffersEnum.None; targets[3] = DrawBuffersEnum.None; GL.DrawBuffers(4, targets); GL.DepthMask(false); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.OneMinusSrcAlpha); GL.BlendEquation(BlendEquationMode.FuncAdd); for (int i = 0; i < objectBase.Camera.TransparentPhysicsObjectCount; i++) { transparentPhysicsObject = objectBase.Camera.GetTransparentPhysicsObject(i); if ((transparentPhysicsObject.UserControllers.DrawMethods == null) || (transparentPhysicsObject == objectBase)) { if (transparentPhysicsObject.UserDataStr == null) continue; if ((transparentPhysicsObject.Shape == null) && transparentPhysicsObject.IsBrokenRigidGroup) continue; if ((transparentPhysicsObject.RigidGroupOwner != transparentPhysicsObject) && (transparentPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; transparentPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); mesh = demo.Meshes[transparentPhysicsObject.UserDataStr]; mesh.Draw(ref world, ref view, ref projection, sceneLight, transparentPhysicsObject.Material, objectBase.Camera, transparentPhysicsObject.RigidGroupOwner.IsSleeping && enableDrawSlipingObjects, enableWireframe); } else { if (transparentPhysicsObject.UserControllers.EnableDraw) continue; if ((transparentPhysicsObject.Shape == null) && transparentPhysicsObject.IsBrokenRigidGroup) continue; if ((transparentPhysicsObject.RigidGroupOwner != transparentPhysicsObject) && (transparentPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; transparentPhysicsObject.UserControllers.DrawMethodArgs.Time = time; transparentPhysicsObject.UserControllers.DrawMethodArgs.OwnerIndex = transparentPhysicsObject.Index; transparentPhysicsObject.UserControllers.DrawMethodArgs.OwnerSceneIndex = scene.Index; transparentPhysicsObject.UserControllers.DrawMethods(transparentPhysicsObject.UserControllers.DrawMethodArgs); } } targets[0] = DrawBuffersEnum.None; targets[1] = DrawBuffersEnum.None; targets[2] = DrawBuffersEnum.ColorAttachment2; targets[3] = DrawBuffersEnum.ColorAttachment3; GL.DrawBuffers(4, targets); GL.DepthMask(true); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.Zero); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.Disable(EnableCap.Blend); for (int i = 0; i < objectBase.Camera.TransparentPhysicsObjectCount; i++) { transparentPhysicsObject = objectBase.Camera.GetTransparentPhysicsObject(i); if (!transparentPhysicsObject.Material.TransparencySecondPass) continue; if ((transparentPhysicsObject.UserControllers.DrawMethods == null) || (transparentPhysicsObject == objectBase)) { if (transparentPhysicsObject.UserDataStr == null) continue; if ((transparentPhysicsObject.Shape == null) && transparentPhysicsObject.IsBrokenRigidGroup) continue; if ((transparentPhysicsObject.RigidGroupOwner != transparentPhysicsObject) && (transparentPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; transparentPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); mesh = demo.Meshes[transparentPhysicsObject.UserDataStr]; mesh.Draw(ref world, ref view, ref projection, sceneLight, transparentPhysicsObject.Material, objectBase.Camera, transparentPhysicsObject.RigidGroupOwner.IsSleeping && enableDrawSlipingObjects, enableWireframe); } else { if (transparentPhysicsObject.UserControllers.EnableDraw) continue; if ((transparentPhysicsObject.Shape == null) && transparentPhysicsObject.IsBrokenRigidGroup) continue; if ((transparentPhysicsObject.RigidGroupOwner != transparentPhysicsObject) && (transparentPhysicsObject.RigidGroupOwner.UserDataStr != null)) continue; transparentPhysicsObject.UserControllers.DrawMethodArgs.Time = time; transparentPhysicsObject.UserControllers.DrawMethodArgs.OwnerIndex = transparentPhysicsObject.Index; transparentPhysicsObject.UserControllers.DrawMethodArgs.OwnerSceneIndex = scene.Index; transparentPhysicsObject.UserControllers.DrawMethods(transparentPhysicsObject.UserControllers.DrawMethodArgs); } } } GL.BindFramebuffer(FramebufferTarget.Framebuffer, demo.LightFrameBuffer); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); GL.ClearColor(demo.ClearLightColor); GL.Clear(ClearBufferMask.ColorBufferBit); GL.Disable(EnableCap.DepthTest); GL.DepthMask(false); GL.Enable(EnableCap.Blend); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.SrcAlpha); GL.BlendEquation(BlendEquationMode.FuncAdd); if ((sceneLight != null) && sceneLight.Enabled) { GL.Disable(EnableCap.CullFace); sceneLight.GetDirection(ref direction); sceneLight.GetDiffuse(ref lightDiffuse); sceneLight.GetSpecular(ref lightSpecular); renderLightDirectional.Enable = true; renderLightDirectional.Width = objectBase.Camera.Projection.Width; renderLightDirectional.Height = objectBase.Camera.Projection.Height; renderLightDirectional.SetView(ref view); renderLightDirectional.SetProjection(ref projection); renderLightDirectional.SetLightDirection(ref direction); renderLightDirectional.SetLightDiffuse(ref lightDiffuse); renderLightDirectional.SetLightSpecular(ref lightSpecular); renderLightDirectional.Intensity = sceneLight.Intensity; renderLightDirectional.SpecularTexture = demo.SpecularTexture; renderLightDirectional.NormalTexture = demo.NormalTexture; renderLightDirectional.DepthTexture = demo.DepthTexture; quad.Draw(renderLightDirectional); } for (int i = 0; i < objectBase.Camera.LightPhysicsObjectCount; i++) { lightPhysicsObject = objectBase.Camera.GetLightPhysicsObject(i); drawLight = lightPhysicsObject.Light; if ((drawLight == null) || !drawLight.Enabled) continue; if (drawLight.Type == PhysicsLightType.Directional) { GL.Disable(EnableCap.CullFace); drawLight.GetDirection(ref direction); drawLight.GetDiffuse(ref lightDiffuse); drawLight.GetSpecular(ref lightSpecular); renderLightDirectional.Enable = true; renderLightDirectional.Width = objectBase.Camera.Projection.Width; renderLightDirectional.Height = objectBase.Camera.Projection.Height; renderLightDirectional.SetView(ref view); renderLightDirectional.SetProjection(ref projection); renderLightDirectional.SetLightDirection(ref direction); renderLightDirectional.SetLightDiffuse(ref lightDiffuse); renderLightDirectional.SetLightSpecular(ref lightSpecular); renderLightDirectional.Intensity = drawLight.Intensity; renderLightDirectional.SpecularTexture = demo.SpecularTexture; renderLightDirectional.NormalTexture = demo.NormalTexture; renderLightDirectional.DepthTexture = demo.DepthTexture; quad.Draw(renderLightDirectional); } else if (drawLight.Type == PhysicsLightType.Point) { lightPhysicsObject.EnableAddToCameraDrawTransparentPhysicsObjects = false; if (enableDrawLights) { lightPhysicsObject.EnableAddToCameraDrawTransparentPhysicsObjects = true; lightPhysicsObject.Material.TransparencyFactor = 0.5f; lightPhysicsObject.Material.TransparencySecondPass = false; } GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode.Front); lightPhysicsObject.MainWorldTransform.GetPosition(ref position); lightPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); drawLight.GetDiffuse(ref lightDiffuse); drawLight.GetSpecular(ref lightSpecular); renderLightPoint.Enable = true; renderLightPoint.Width = objectBase.Camera.Projection.Width; renderLightPoint.Height = objectBase.Camera.Projection.Height; renderLightPoint.SetWorld(ref world); renderLightPoint.SetView(ref view); renderLightPoint.SetProjection(ref projection); renderLightPoint.SetLightPosition(ref position); renderLightPoint.SetLightDiffuse(ref lightDiffuse); renderLightPoint.SetLightSpecular(ref lightSpecular); renderLightPoint.Range = drawLight.Range; renderLightPoint.Intensity = drawLight.Intensity; renderLightPoint.SpecularTexture = demo.SpecularTexture; renderLightPoint.NormalTexture = demo.NormalTexture; renderLightPoint.DepthTexture = demo.DepthTexture; mesh = demo.Meshes[lightPhysicsObject.UserDataStr]; mesh.Draw(renderLightPoint); } else if (drawLight.Type == PhysicsLightType.Spot) { lightPhysicsObject.EnableAddToCameraDrawTransparentPhysicsObjects = false; if (enableDrawLights) { lightPhysicsObject.EnableAddToCameraDrawTransparentPhysicsObjects = true; lightPhysicsObject.Material.TransparencyFactor = 0.5f; lightPhysicsObject.Material.TransparencySecondPass = false; } GL.Enable(EnableCap.CullFace); GL.CullFace(CullFaceMode.Front); lightPhysicsObject.MainWorldTransform.GetPosition(ref position); lightPhysicsObject.MainWorldTransform.GetTransformMatrix(ref world); drawLight.GetDiffuse(ref lightDiffuse); drawLight.GetSpecular(ref lightSpecular); direction.X = -world.Row2.X; direction.Y = -world.Row2.Y; direction.Z = -world.Row2.Z; Vector3.Subtract(ref position, ref direction, out position); renderLightSpot.Enable = true; renderLightSpot.Width = objectBase.Camera.Projection.Width; renderLightSpot.Height = objectBase.Camera.Projection.Height; renderLightSpot.SetWorld(ref world); renderLightSpot.SetView(ref view); renderLightSpot.SetProjection(ref projection); renderLightSpot.SetLightPosition(ref position); renderLightSpot.SetLightDirection(ref direction); renderLightSpot.SetLightDiffuse(ref lightDiffuse); renderLightSpot.SetLightSpecular(ref lightSpecular); renderLightSpot.Range = drawLight.Range; renderLightSpot.Intensity = drawLight.Intensity; renderLightSpot.InnerRadAngle = drawLight.SpotInnerRadAngle; renderLightSpot.OuterRadAngle = drawLight.SpotOuterRadAngle; renderLightSpot.SpecularTexture = demo.SpecularTexture; renderLightSpot.NormalTexture = demo.NormalTexture; renderLightSpot.DepthTexture = demo.DepthTexture; mesh = demo.Meshes[lightPhysicsObject.UserDataStr]; mesh.Draw(renderLightSpot); } } if (!demo.EnableMenu) { GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0); } else { GL.BindFramebuffer(FramebufferTarget.Framebuffer, demo.ScreenFrameBuffer); GL.DrawBuffer(DrawBufferMode.ColorAttachment0); } GL.Disable(EnableCap.CullFace); GL.BlendFunc(BlendingFactorSrc.One, BlendingFactorDest.Zero); GL.BlendEquation(BlendEquationMode.FuncAdd); GL.Disable(EnableCap.Blend); renderScreen.Width = objectBase.Camera.Projection.Width; renderScreen.Height = objectBase.Camera.Projection.Height; renderScreen.ColorTexture = demo.ColorTexture; renderScreen.LightTexture = demo.LightTexture; quad.Draw(renderScreen); GL.Enable(EnableCap.CullFace); GL.Enable(EnableCap.DepthTest); GL.DepthMask(true); } public void DrawBoundingBoxes(DrawMethodArgs args) { PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex); PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex); if (!objectBase.Camera.Enabled) return; if (!objectBase.Camera.Active) return; if (!enableDrawBoundingBoxes) return; float time = args.Time; PhysicsObject visiblePhysicsObject; Vector3 min, max; objectBase.Camera.View.GetViewMatrix(ref view); objectBase.Camera.Projection.GetProjectionMatrix(ref projection); world = matrixIdentity; GL.Color3(1.0f, 1.0f, 1.0f); render.SetWorld(ref world); render.SetView(ref view); render.SetProjection(ref projection); render.Apply(); for (int i = 0; i < objectBase.Camera.VisiblePhysicsObjectCount; i++) { visiblePhysicsObject = objectBase.Camera.GetVisiblePhysicsObject(i); visiblePhysicsObject.GetBoundingBox(ref boundingBox); min = boundingBox.Min; max = boundingBox.Max; cameraVertices[0].Position.X = min.X; cameraVertices[0].Position.Y = min.Y; cameraVertices[0].Position.Z = min.Z; cameraVertices[1].Position.X = max.X; cameraVertices[1].Position.Y = min.Y; cameraVertices[1].Position.Z = min.Z; cameraVertices[2].Position.X = min.X; cameraVertices[2].Position.Y = min.Y; cameraVertices[2].Position.Z = min.Z; cameraVertices[3].Position.X = min.X; cameraVertices[3].Position.Y = max.Y; cameraVertices[3].Position.Z = min.Z; cameraVertices[4].Position.X = min.X; cameraVertices[4].Position.Y = min.Y; cameraVertices[4].Position.Z = min.Z; cameraVertices[5].Position.X = min.X; cameraVertices[5].Position.Y = min.Y; cameraVertices[5].Position.Z = max.Z; cameraVertices[6].Position.X = max.X; cameraVertices[6].Position.Y = max.Y; cameraVertices[6].Position.Z = max.Z; cameraVertices[7].Position.X = min.X; cameraVertices[7].Position.Y = max.Y; cameraVertices[7].Position.Z = max.Z; cameraVertices[8].Position.X = max.X; cameraVertices[8].Position.Y = max.Y; cameraVertices[8].Position.Z = max.Z; cameraVertices[9].Position.X = max.X; cameraVertices[9].Position.Y = min.Y; cameraVertices[9].Position.Z = max.Z; cameraVertices[10].Position.X = max.X; cameraVertices[10].Position.Y = max.Y; cameraVertices[10].Position.Z = max.Z; cameraVertices[11].Position.X = max.X; cameraVertices[11].Position.Y = max.Y; cameraVertices[11].Position.Z = min.Z; cameraVertices[12].Position.X = min.X; cameraVertices[12].Position.Y = max.Y; cameraVertices[12].Position.Z = min.Z; cameraVertices[13].Position.X = min.X; cameraVertices[13].Position.Y = max.Y; cameraVertices[13].Position.Z = max.Z; cameraVertices[14].Position.X = min.X; cameraVertices[14].Position.Y = max.Y; cameraVertices[14].Position.Z = min.Z; cameraVertices[15].Position.X = max.X; cameraVertices[15].Position.Y = max.Y; cameraVertices[15].Position.Z = min.Z; cameraVertices[16].Position.X = max.X; cameraVertices[16].Position.Y = min.Y; cameraVertices[16].Position.Z = max.Z; cameraVertices[17].Position.X = max.X; cameraVertices[17].Position.Y = min.Y; cameraVertices[17].Position.Z = min.Z; cameraVertices[18].Position.X = max.X; cameraVertices[18].Position.Y = min.Y; cameraVertices[18].Position.Z = max.Z; cameraVertices[19].Position.X = min.X; cameraVertices[19].Position.Y = min.Y; cameraVertices[19].Position.Z = max.Z; cameraVertices[20].Position.X = min.X; cameraVertices[20].Position.Y = max.Y; cameraVertices[20].Position.Z = max.Z; cameraVertices[21].Position.X = min.X; cameraVertices[21].Position.Y = min.Y; cameraVertices[21].Position.Z = max.Z; cameraVertices[22].Position.X = max.X; cameraVertices[22].Position.Y = max.Y; cameraVertices[22].Position.Z = min.Z; cameraVertices[23].Position.X = max.X; cameraVertices[23].Position.Y = min.Y; cameraVertices[23].Position.Z = min.Z; GL.Begin(PrimitiveType.Lines); for (int j = 0; j < 24; j += 2) { GL.Vertex3(cameraVertices[j].Position); GL.Vertex3(cameraVertices[j + 1].Position); } GL.End(); } } public void DrawContactPoints(DrawMethodArgs args) { PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex); PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex); if (!objectBase.Camera.Enabled) return; if (!objectBase.Camera.Active) return; if (!enableDrawContactPoints) return; GL.Disable(EnableCap.DepthTest); GL.DepthMask(false); float time = args.Time; PhysicsObject visiblePhysicsObject; int contactPointCount; Vector3 start1, end1, start2, end2; objectBase.Camera.View.GetViewMatrix(ref view); objectBase.Camera.Projection.GetProjectionMatrix(ref projection); world = matrixIdentity; render.SetWorld(ref world); render.SetView(ref view); render.SetProjection(ref projection); render.Apply(); for (int i = 0; i < objectBase.Camera.VisiblePhysicsObjectCount; i++) { visiblePhysicsObject = objectBase.Camera.GetVisiblePhysicsObject(i); for (int j = 0; j < visiblePhysicsObject.CollisionPairCount; j++) { contactPointCount = visiblePhysicsObject.GetCollisionPairContactPointCount(j); for (int k = 0; k < contactPointCount; k++) { visiblePhysicsObject.GetCollisionPairContactPointAnchor2(j, k, ref position); visiblePhysicsObject.GetCollisionPairContactPointNormal(j, k, ref direction); Vector3.Multiply(ref direction, 0.5f, out direction); start1 = position; end1 = direction; Vector3.Add(ref start1, ref end1, out end1); start2 = end1; end2 = direction; Vector3.Add(ref start2, ref end2, out end2); GL.Begin(PrimitiveType.Lines); GL.Color3(1.0f, 1.0f, 1.0f); GL.Vertex3(start1); GL.Vertex3(end1); GL.Color3(0.6f, 0.8f, 0.2f); GL.Vertex3(start2); GL.Vertex3(end2); GL.End(); } } } GL.DepthMask(true); GL.Enable(EnableCap.DepthTest); } public void DrawImpactFactors(DrawMethodArgs args) { PhysicsScene scene = demo.Engine.Factory.PhysicsSceneManager.Get(args.OwnerSceneIndex); PhysicsObject objectBase = scene.Factory.PhysicsObjectManager.Get(args.OwnerIndex); if (!objectBase.Camera.Enabled) return; if (!objectBase.Camera.Active) return; if (!enableDrawImpactFactors) return; GL.Disable(EnableCap.DepthTest); GL.DepthMask(false); float time = args.Time; PhysicsObject visiblePhysicsObject; int contactPointCount; Vector3 start1, end1, start2, end2; float impactFactor, velocityMagnitude; objectBase.Camera.View.GetViewMatrix(ref view); objectBase.Camera.Projection.GetProjectionMatrix(ref projection); world = matrixIdentity; render.SetWorld(ref world); render.SetView(ref view); render.SetProjection(ref projection); render.Apply(); for (int i = 0; i < objectBase.Camera.VisiblePhysicsObjectCount; i++) { visiblePhysicsObject = objectBase.Camera.GetVisiblePhysicsObject(i); for (int j = 0; j < visiblePhysicsObject.CollisionPairCount; j++) { contactPointCount = visiblePhysicsObject.GetCollisionPairContactPointCount(j); for (int k = 0; k < contactPointCount; k++) { visiblePhysicsObject.GetCollisionPairContactPointAnchor2(j, k, ref position); visiblePhysicsObject.GetCollisionPairContactPointNormal(j, k, ref direction); impactFactor = visiblePhysicsObject.GetCollisionPairContactPointImpactFactor(j, k); velocityMagnitude = Math.Min(Math.Max(visiblePhysicsObject.MainWorldTransform.GetLinearVelocityMagnitude() - visiblePhysicsObject.MaxSleepLinearVelocity, 0.0f) + Math.Max(visiblePhysicsObject.MainWorldTransform.GetAngularVelocityMagnitude() - visiblePhysicsObject.MaxSleepAngularVelocity, 0.0f), 1.0f); impactFactor *= velocityMagnitude; if (impactFactor < 0.001f) continue; Vector3.Multiply(ref direction, (float)impactFactor, out direction); Vector3.Multiply(ref direction, 0.5f, out direction); start1 = position; end1 = direction; Vector3.Add(ref start1, ref end1, out end1); start2 = end1; end2 = direction; Vector3.Add(ref start2, ref end2, out end2); GL.Begin(PrimitiveType.Lines); GL.Color3(1.0f, 1.0f, 1.0f); GL.Vertex3(start1); GL.Vertex3(end1); GL.Color3(0.6f, 0.8f, 0.2f); GL.Vertex3(start2); GL.Vertex3(end2); GL.End(); } } } GL.DepthMask(true); GL.Enable(EnableCap.DepthTest); } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2009 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using OpenTK.Audio.OpenAL; namespace OpenTK.Audio { internal static class AudioDeviceEnumerator { #region All device strings private static readonly List<string> available_playback_devices = new List<string>(); private static readonly List<string> available_recording_devices = new List<string>(); internal static IList<string> AvailablePlaybackDevices { get { return available_playback_devices.AsReadOnly(); } } internal static IList<string> AvailableRecordingDevices { get { return available_recording_devices.AsReadOnly(); } } #endregion All device strings #region Default device strings private static string default_playback_device; internal static string DefaultPlaybackDevice { get { return default_playback_device; } } private static string default_recording_device; internal static string DefaultRecordingDevice { get { return default_recording_device; } } #endregion Default device strings #region Is OpenAL supported? private static bool openal_supported = true; internal static bool IsOpenALSupported { get { return openal_supported; } } #endregion Is OpenAL supported? #region Alc Version number internal enum AlcVersion { Alc1_0, Alc1_1 } private static AlcVersion version; internal static AlcVersion Version { get { return version; } } #endregion Alc Version number #region Constructors // Loads all available audio devices into the available_*_devices lists. static AudioDeviceEnumerator() { IntPtr dummy_device = IntPtr.Zero; ContextHandle dummy_context = ContextHandle.Zero; try { Debug.WriteLine("Enumerating audio devices."); Debug.Indent(); // need a dummy context for correct results dummy_device = Alc.OpenDevice(null); dummy_context = Alc.CreateContext(dummy_device, (int[])null); bool dummy_success = Alc.MakeContextCurrent(dummy_context); AlcError dummy_error = Alc.GetError(dummy_device); if (!dummy_success || dummy_error != AlcError.NoError) { throw new AudioContextException("Failed to create dummy Context. Device (" + dummy_device.ToString() + ") Context (" + dummy_context.Handle.ToString() + ") MakeContextCurrent " + (dummy_success ? "succeeded" : "failed") + ", Alc Error (" + dummy_error.ToString() + ") " + Alc.GetString(IntPtr.Zero, (AlcGetString)dummy_error)); } // Get a list of all known playback devices, using best extension available if (Alc.IsExtensionPresent(IntPtr.Zero, "ALC_ENUMERATION_EXT")) { version = AlcVersion.Alc1_1; if (Alc.IsExtensionPresent(IntPtr.Zero, "ALC_ENUMERATE_ALL_EXT")) { available_playback_devices.AddRange(Alc.GetString(IntPtr.Zero, AlcGetStringList.AllDevicesSpecifier)); default_playback_device = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultAllDevicesSpecifier); } else { available_playback_devices.AddRange(Alc.GetString(IntPtr.Zero, AlcGetStringList.DeviceSpecifier)); default_playback_device = Alc.GetString(IntPtr.Zero, AlcGetString.DefaultDeviceSpecifier); } } else { version = AlcVersion.Alc1_0; Debug.Print("Device enumeration extension not available. Failed to enumerate playback devices."); } AlcError playback_err = Alc.GetError(dummy_device); if (playback_err != AlcError.NoError) throw new AudioContextException("Alc Error occured when querying available playback devices. " + playback_err.ToString()); // Get a list of all known recording devices, at least ALC_ENUMERATION_EXT is needed too if (version == AlcVersion.Alc1_1 && Alc.IsExtensionPresent(IntPtr.Zero, "ALC_EXT_CAPTURE")) { available_recording_devices.AddRange(Alc.GetString(IntPtr.Zero, AlcGetStringList.CaptureDeviceSpecifier)); default_recording_device = Alc.GetString(IntPtr.Zero, AlcGetString.CaptureDefaultDeviceSpecifier); } else { Debug.Print("Capture extension not available. Failed to enumerate recording devices."); } AlcError record_err = Alc.GetError(dummy_device); if (record_err != AlcError.NoError) throw new AudioContextException("Alc Error occured when querying available recording devices. " + record_err.ToString()); #if DEBUG Debug.WriteLine("Found playback devices:"); foreach (string s in available_playback_devices) Debug.WriteLine(s); Debug.WriteLine("Default playback device: " + default_playback_device); Debug.WriteLine("Found recording devices:"); foreach (string s in available_recording_devices) Debug.WriteLine(s); Debug.WriteLine("Default recording device: " + default_recording_device); #endif } catch (DllNotFoundException e) { Trace.WriteLine(e.ToString()); openal_supported = false; } catch (AudioContextException ace) { Trace.WriteLine(ace.ToString()); openal_supported = false; } finally { Debug.Unindent(); // clean up the dummy context Alc.MakeContextCurrent(ContextHandle.Zero); if (dummy_context != ContextHandle.Zero && dummy_context.Handle != IntPtr.Zero) Alc.DestroyContext(dummy_context); if (dummy_device != IntPtr.Zero) Alc.CloseDevice(dummy_device); } } #endregion } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ #region Using directives using System; using System.IO; using System.Xml; using System.Text; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Axiom.Core; using Axiom.MathLib; using Axiom.Collections; using Axiom.Utility; using Multiverse.Network; using Multiverse.Config; #endregion namespace Multiverse.Test { public struct DirUpdate { public bool dirty; public long timestamp; // in local time public Vector3 direction; public Vector3 position; } public struct OrientationUpdate { public bool dirty; public Quaternion orientation; } public class TestObject { public long Oid; public DirUpdate dirUpdate; public OrientationUpdate orientUpdate; public Vector3 position; public Vector3 direction; public Vector3 scale; public Quaternion orientation; public bool followTerrain; public string name; public ObjectNodeType objectType; protected long lastDirTimestamp = -1; protected long lastLocTimestamp = -1; protected Vector3 lastPosition; protected Vector3 lastDirection; public long lastDirSent; public long lastOrientSent; public TestObject(long Oid, string name) { this.Oid = Oid; this.name = name; } public void SetDirection(Vector3 dir, Vector3 pos) { position = pos; if (dir != direction) { dirUpdate.direction = dir; dirUpdate.position = pos; dirUpdate.dirty = true; direction = dir; } } public TestObject() { } public ObjectNodeType ObjectType { get { return objectType; } set { objectType = value; } } public Vector3 Position { get { return position; } set { position = value; } } public Vector3 Direction { get { return direction; } set { direction = value; } } public string Name { get { return name; } set { name = value; } } public Quaternion Orientation { get { return orientation; } set { if (value != orientation) { orientUpdate.orientation = value; orientUpdate.dirty = true; } } } public bool FollowTerrain { get { return followTerrain; } set { followTerrain = value; } } public void SetDirLoc(long timestamp, Vector3 dir, Vector3 pos) { Logger.Log(0, "dir for node {0} = {1} timestamp = {2}/{3}", this, dir, timestamp, System.Environment.TickCount); if (timestamp <= lastDirTimestamp) { Logger.Log(0, string.Format("ignoring dirloc,since timestamps are too close {0}, {1}", timestamp, lastDirTimestamp)); return; } // timestamp is newer. lastDirTimestamp = timestamp; lastPosition = pos; lastDirection = dir; SetLoc(timestamp, pos); } protected void SetLoc(long timestamp, Vector3 loc) { if (timestamp <= lastLocTimestamp) return; // timestamp is newer. lastLocTimestamp = timestamp; this.Position = loc; Logger.Log(0, "loc for node {0} = {1}/{2}", this, loc, this.Position); } public virtual void SetOrientation(Quaternion orient) { orientation = orient; } } public class WorldManager : IWorldManager { //public WorldManager worldManager = null; public delegate void ObjectEventHandler(object sender, TestObject objNode); public class PreloadEntry { public bool loaded; public bool cancelled; public string entityName; public long oid; public string meshFile; public string[] submeshNames; public string[] materialNames; } long playerId = 0; bool playerInitialized = false; bool playerStubInitialized = false; bool terrainInitialized = false; bool loadCompleted = false; long nextLocalOid = int.MaxValue; // The network helper object NetworkHelper networkHelper = null; // The player object TestObject player = null; Thread asyncLoadThread = null; Thread asyncBehaviorThread = null; Thread verifyServerTimeoutThread = null; bool shuttingDown = false; // Timer for updating the server with the player's position and other information System.Timers.Timer playerUpdateTimer; // Complete objects Dictionary<long, TestObject> nodeDictionary; // Intermediate entities - there are three states for entries here. // 1) No entry - we haven't requested a load of the entry yet // 2) Entry exists, loaded is false - we haven't loaded the mesh and materials // 3) Entry exists, loaded is true - we have loaded the mesh and materials Dictionary<long, PreloadEntry> preloadDictionary; public event ObjectEventHandler ObjectAdded; public event ObjectEventHandler ObjectRemoved; int entityCounter = 0; private bool verifyServer = false; protected BehaviorParms behaviorParms = null; public WorldManager(bool verifyServer, BehaviorParms behaviorParms) { this.verifyServer = verifyServer; this.behaviorParms = behaviorParms; } public void Dispose() { shuttingDown = true; if (asyncLoadThread != null) { asyncLoadThread.Interrupt(); asyncLoadThread.Join(); asyncLoadThread = null; } if (asyncBehaviorThread != null) { asyncBehaviorThread.Interrupt(); asyncBehaviorThread.Join(); asyncBehaviorThread = null; } if (networkHelper != null) { networkHelper.Dispose(); networkHelper = null; } if (verifyServerTimeoutThread != null) { verifyServerTimeoutThread.Interrupt(); verifyServerTimeoutThread.Join(); verifyServerTimeoutThread = null; } } public void Init(Client client) { nodeDictionary = new Dictionary<long, TestObject>(); preloadDictionary = new Dictionary<long, PreloadEntry>(); playerUpdateTimer = new System.Timers.Timer(); playerUpdateTimer.Enabled = true; playerUpdateTimer.Interval = behaviorParms.playerUpdateInterval; playerUpdateTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.SendPlayerData); asyncLoadThread = new Thread(new ThreadStart(this.AsyncLoadEntities)); asyncLoadThread.Name = "Async Resource Loader"; asyncLoadThread.Start(); asyncBehaviorThread = new Thread(new ThreadStart(this.AsyncBehavior)); asyncBehaviorThread.Name = "Async Player Behavior"; asyncBehaviorThread.Start(); if (verifyServer) { verifyServerTimeoutThread = new Thread(new ThreadStart(this.VerifyServerTimeout)); verifyServerTimeoutThread.Name = "Verify Server Timeout"; verifyServerTimeoutThread.Start(); } MessageDispatcher.Instance.RegisterPreHandler(WorldMessageType.ModelInfo, new WorldMessageHandler(this.PreHandleModelInfo)); // MessageDispatcher.Instance.RegisterHandler(MessageType.Location, // new MessageHandler(this.HandleLocation)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.Direction, new WorldMessageHandler(this.HandleDirection)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.NewObject, new WorldMessageHandler(this.HandleNewObject)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.FreeObject, new WorldMessageHandler(this.HandleFreeObject)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.Orientation, new WorldMessageHandler(this.HandleOrientation)); //MessageDispatcher.Instance.RegisterHandler(MessageType.StatUpdate, // new MessageHandler(this.HandleStatUpdate)); //MessageDispatcher.Instance.RegisterHandler(WorldMessageType.Animation, // new WorldMessageHandler(this.HandleAnimation)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.Attach, new WorldMessageHandler(this.HandleAttach)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.Detach, new WorldMessageHandler(this.HandleDetach)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.Comm, new WorldMessageHandler(this.HandleComm)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.Sound, new WorldMessageHandler(this.HandleSound)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.AmbientLight, new WorldMessageHandler(this.HandleAmbientLight)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.NewLight, new WorldMessageHandler(this.HandleNewLight)); //MessageDispatcher.Instance.RegisterHandler(MessageType.StateMessage, // new MessageHandler(this.HandleState)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.TerrainConfig, new WorldMessageHandler(this.HandleTerrainConfig)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.RegionConfig, new WorldMessageHandler(this.HandleRegionConfig)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.SkyboxMaterial, new WorldMessageHandler(this.HandleSkyboxMaterial)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.ModelInfo, new WorldMessageHandler(this.HandleModelInfo)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.RoadInfo, new WorldMessageHandler(this.HandleRoadInfo)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.Fog, new WorldMessageHandler(this.HandleFogMessage)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.AddParticleEffect, new WorldMessageHandler(this.HandleAddParticleEffect)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.RemoveParticleEffect, new WorldMessageHandler(this.HandleRemoveParticleEffect)); MessageDispatcher.Instance.RegisterHandler(WorldMessageType.ObjectProperty, new WorldMessageHandler(this.HandleObjectProperty)); // Initialize the network helper networkHelper.Init(); } public long GetLocalOid() { return nextLocalOid++; } /// <summary> /// Get the first preload entry that has not been loaded /// </summary> /// <returns></returns> private PreloadEntry GetUnloadedPreloadEntry() { PreloadEntry rv = null; Monitor.Enter(preloadDictionary); try { foreach (PreloadEntry entry in preloadDictionary.Values) { if (entry.loaded) continue; return entry; } } finally { Monitor.Exit(preloadDictionary); } return rv; } public void VerifyServerTimeout() { // Sleep for 5 minutes. If we haven't terminated yet, log // the fact, and exit with error code -1 Thread.Sleep(5 * 60 * 1000); // We're still alive, so the verification failed Logger.Log(4, "In --verify_server mode, 5 minutes has elapsed and we haven't gotten the --verify_server Comm message, so exiting with exit code -1"); System.Environment.Exit(-1); } /// <summary> /// This method can be called from another thread and will preload the entity. /// TODO: Lock the underlying EntityManager.entityList /// </summary> public void AsyncLoadEntities() { while (!shuttingDown) { try { PreloadEntry entry = GetUnloadedPreloadEntry(); if (entry == null) { Thread.Sleep(100); continue; } try { Logger.Log(3, "Preparing entity for {0}", entry.entityName); // if (entry.materialNames != null) { // foreach (string materialName in entry.materialNames) { // Material material = MaterialManager.Instance.GetByName(materialName); // if (material == null) // continue; // // ensure the material is loaded. It will skip it if it already is // material.Load(); // } // } // Debug.Assert(entry.meshFile != null && entry.meshFile != ""); // Mesh mesh = MeshManager.Instance.Load(entry.meshFile); // Put the entry in our node dictionary lock(nodeDictionary) { nodeDictionary[entry.oid] = new TestObject(entry.oid, entry.entityName); } entry.loaded = true; Logger.Log(3, "Prepared entity {0} for {1}", entry.meshFile, entry.entityName); } catch (AxiomException ex) { Trace.TraceError("Unable to create entity; AxiomException: " + ex); entry.loaded = true; } } catch (ThreadInterruptedException) { continue; } catch (ThreadAbortException e) { Logger.Log(4, "Aborting thread due to " + e); return; } } } /// <summary> /// Used to manually change the model being used /// </summary> /// <param name="node"></param> /// <param name="meshFile"></param> /// <param name="subMeshNames"></param> /// <param name="materialNames"></param> public void SetModel(TestObject node, string meshFile, List<string> subMeshNames, List<string> materialNames) { for (int tries = 0; tries < 100; ++tries) { if (PrepareModel(node.Oid, meshFile, subMeshNames, materialNames)) { ApplyModel(node); return; } Thread.Sleep(100); } Logger.Log(4, "Timed out trying to change model"); } /// <summary> /// Call this method to set the mesh for a model. /// When it returns true, the model is ready. /// Counter to intuition, this returns true on an error, /// since returning true means you can stop waiting and move on. /// The error is dealt with by the later call to SetModel. /// </summary> /// <param name="oid"></param> /// <param name="meshFile"></param> /// <param name="submeshNames"></param> /// <param name="materialNames"></param> /// <returns>true when the model has been loaded, or we have given up</returns> protected bool PrepareModel(long oid, string meshFile, List<string> submeshNames, List<string> materialNames) { Monitor.Enter(preloadDictionary); try { // have we already started loading this model? if (preloadDictionary.ContainsKey(oid)) { // we have already started. if we are done, we can proceed PreloadEntry entry = preloadDictionary[oid]; if (entry.loaded || entry.cancelled) { //Logger.Log(0, "finished preparing model for " + oid); return true; //} else { //Logger.Log(1, "still preparing model for " + oid); } } else { // start loading the model PreloadEntry entry = new PreloadEntry(); entry.loaded = false; entry.cancelled = false; entry.meshFile = meshFile; entry.submeshNames = (submeshNames == null ? null : submeshNames.ToArray()); entry.materialNames = (materialNames == null ? null : materialNames.ToArray()); entry.entityName = string.Format("entity.{0}.{1}", oid, entityCounter++); entry.oid = oid; // entry.entity = null; preloadDictionary[oid] = entry; //Logger.Log(0, "preparing model for " + oid); } } finally { Monitor.Exit(preloadDictionary); } return false; } private static string ArrayToString(string[] array) { if (array == null) return null; StringBuilder buf = new StringBuilder(); buf.Append("[ "); foreach (string str in array) { buf.Append("'"); buf.Append(str); buf.Append("' "); } buf.Append("]"); return buf.ToString(); } #region Pre-Message handlers public void PreHandleModelInfo(BaseWorldMessage message) { ModelInfoMessage modelInfo = (ModelInfoMessage)message; Debug.Assert(modelInfo.ModelInfo.Count == 1); MeshInfo meshInfo = modelInfo.ModelInfo[0]; // TODO: I changed the way these submeshes are handled, and don't want to // bother maintaining test. Just skip this for now. // bool rv = PrepareModel(modelInfo.Oid, meshInfo.MeshFile, meshInfo.SubmeshList); // message.DelayHandling = !rv; message.DelayHandling = false; } #endregion #region Message handlers public void HandleNewObject(BaseWorldMessage message) { if (!this.TerrainInitialized) { Trace.TraceError("Ignoring new object message, since terrain is not initialized"); return; } NewObjectMessage newObj = (NewObjectMessage)message; AddObjectStub(newObj.ObjectId, newObj.Name, newObj.Location, newObj.Orientation, newObj.ScaleFactor, newObj.ObjectType, newObj.FollowTerrain); } public void HandleModelInfo(BaseWorldMessage message) { ModelInfoMessage modelInfo = (ModelInfoMessage)message; Debug.Assert(modelInfo.ModelInfo.Count == 1); MeshInfo meshInfo = modelInfo.ModelInfo[0]; AddObject(modelInfo.Oid, meshInfo.MeshFile); } public void HandleFreeObject(BaseWorldMessage message) { FreeObjectMessage freeObj = (FreeObjectMessage)message; RemoveObject(freeObj.ObjectId); } public void HandleDirection(BaseWorldMessage message) { DirectionMessage dirMessage = (DirectionMessage)message; long now = WorldManager.CurrentTime; Logger.Log(0, "Got dir message at {0}:{1}", now, dirMessage.Timestamp); if (dirMessage.Oid == playerId) Trace.TraceWarning("Got DirLoc for Player"); SetDirLoc(dirMessage.Oid, dirMessage.Timestamp, dirMessage.Direction, dirMessage.Location); } public void HandleOrientation(BaseWorldMessage message) { OrientationMessage orientMessage = (OrientationMessage)message; SetOrientation(orientMessage.Oid, orientMessage.Orientation); } //public void HandleStatUpdate(BaseMessage message) { // StatUpdateMessage statUpdateMessage = (StatUpdateMessage)message; // TestObject objNode = GetObjectNode(statUpdateMessage.Oid); // if (objNode == null) { // Trace.TraceWarning("Got stat update message for nonexistent object: " + message.Oid); // return; // } // objNode.UpdateStats(statUpdateMessage.StatValues); //} //public void HandleState(BaseMessage message) { // StateMessage stateMessage = (StateMessage)message; // TestObject objNode = GetObjectNode(stateMessage.Oid); // if (objNode == null) { // Trace.TraceWarning("Got state message for nonexistent object: " + message.Oid); // return; // } // objNode.UpdateStates(stateMessage.States); //} //public void HandleAnimation(BaseWorldMessage message) { // AnimationMessage animMessage = (AnimationMessage)message; // TestObject objNode = GetObjectNode(animMessage.Oid); // if (objNode == null) { // Trace.TraceWarning("Got animation message for nonexistent object: " + message.Oid); // return; // } // if (animMessage.Clear) { // Logger.Log(1, "Cleared animation queue for: " + objNode.Oid); // } // List<AnimationEntry> animations = animMessage.Animations; // foreach (AnimationEntry animEntry in animations) { // Logger.Log(1, "Queued animation " + // animEntry.animationName + " for " + objNode.Oid + // " with loop set to " + animEntry.loop); // } //} public void HandleAttach(BaseWorldMessage message) { AttachMessage attachMessage = (AttachMessage)message; TestObject parentObj = GetObjectNode(attachMessage.Oid); if (parentObj == null) { Trace.TraceWarning("Got attach message for nonexistent object: " + message.Oid); return; } } public void HandleDetach(BaseWorldMessage message) { DetachMessage detachMessage = (DetachMessage)message; TestObject parentObj = GetObjectNode(detachMessage.Oid); if (parentObj == null) { Trace.TraceWarning("Got detach message for nonexistent object: " + message.Oid); return; } } public void HandleComm(BaseWorldMessage message) { CommMessage commMessage = (CommMessage)message; Logger.Log(2, "Received comm message with text '" + commMessage.Message + "'"); if (verifyServer && commMessage.Message.Substring(0, 28) == "--verify_server Comm Message") { // We need to exit with a code of 0, indicating success Logger.Log(4, "Called with --verify_server; got Comm message we sent, exiting with exit code 0"); Trace.Flush(); System.Environment.Exit(0); } if (commMessage.ChannelId != (int)CommChannel.Say) return; if (!this.PlayerInitialized || this.Player == null) return; // bubbleManager.SetBubbleText(commMessage.Oid, // commMessage.Message, // System.Environment.TickCount); } public void HandleSound(BaseWorldMessage message) { SoundMessage soundMessage = (SoundMessage)message; TestObject node = GetObjectNode(soundMessage.Oid); if (node == null) { Trace.TraceWarning("Got sound message for invalid object: " + soundMessage.Oid); return; } Logger.Log(0, "Sound entries for " + soundMessage.Oid + (soundMessage.Clear ? " (cleared)" : "")); } public void HandleAmbientLight(BaseWorldMessage message) { AmbientLightMessage ambientLightMessage = (AmbientLightMessage)message; Trace.TraceWarning("Got ambient light message color " + ambientLightMessage.Color); } public void HandleNewLight(BaseWorldMessage message) { NewLightMessage newLightMessage = (NewLightMessage)message; Trace.TraceWarning("Got new light message with oid " + newLightMessage.ObjectId); } public void HandleTerrainConfig(BaseWorldMessage message) { TerrainConfigMessage terrainConfigMessage = (TerrainConfigMessage)message; Trace.TraceWarning("Got terrain config message"); string s = terrainConfigMessage.ConfigString; terrainInitialized = true; // if (terrainConfigMessage.ConfigKind == "file") { // Stream fileStream = ResourceManager.FindCommonResourceData(s); // StreamReader reader = new StreamReader(fileStream); // s = reader.ReadToEnd(); // reader.Close(); // } // lock (nodeDictionary) { // foreach (TestObject node in nodeDictionary.Values) { // if (node.FollowTerrain) { // Vector3 loc = node.Position; // loc.y = GetHeightAt(loc); // node.Position = loc; // } // } // } } public void HandleRegionConfig(BaseWorldMessage message) { RegionConfigMessage regionConfigMessage = (RegionConfigMessage)message; Trace.TraceWarning("Got region config message"); } public void HandleSkyboxMaterial(BaseWorldMessage message) { SkyboxMaterialMessage skyboxMaterialMessage = (SkyboxMaterialMessage)message; Trace.TraceWarning("Got skybox material message"); } public void HandleRoadInfo(BaseWorldMessage message) { RoadInfoMessage roadInfo = (RoadInfoMessage)message; Trace.TraceWarning("Got road info message"); } public void HandleFogMessage(BaseWorldMessage message) { FogMessage fogMessage = (FogMessage)message; Trace.TraceWarning("Got fog message"); } public void HandleAddParticleEffect(BaseWorldMessage message) { AddParticleEffectMessage particleMessage = (AddParticleEffectMessage)message; Trace.TraceWarning("Got add particle effect message for object " + particleMessage.Oid); TestObject parentObj = GetObjectNode(particleMessage.Oid); if (parentObj == null) { Trace.TraceWarning("Got particle effects message for nonexistent object: " + message.Oid); return; } } public void HandleRemoveParticleEffect(BaseWorldMessage message) { RemoveParticleEffectMessage particleMessage = (RemoveParticleEffectMessage)message; Trace.TraceWarning("Got remove particle effect message for object " + particleMessage.Oid); TestObject parentObj = GetObjectNode(particleMessage.Oid); if (parentObj == null) { Trace.TraceWarning("Got particle effects message for nonexistent object: " + message.Oid); return; } } public void HandleObjectProperty(BaseWorldMessage message) { ObjectPropertyMessage propMessage = (ObjectPropertyMessage)message; foreach (string key in propMessage.Properties.Keys) { object val = propMessage.Properties[key]; Logger.Log(1, "HandleObjectProperty for OID {0}, setting prop {1} = {2}", message.Oid, key, val); } } #endregion /// <summary> /// Update the time offset. /// </summary> /// <param name="timestamp">timestamp received from the server</param> public void AdjustTimestamp(long timestamp) { networkHelper.AdjustTimestamp(timestamp, System.Environment.TickCount); } /// <summary> /// We already hold the lock on the sceneManager and the nodeDictionary. /// This doesn't remove the node from the dictionary, but it does remove /// it from the scene, and cleans up. /// </summary> /// <param name="oid"></param> private void RemoveNode(TestObject node) { // nameManager.RemoveNode(node.Oid); // bubbleManager.RemoveNode(node.Oid); if (ObjectRemoved != null) ObjectRemoved(this, node); } // Removes a node from the nodeDictionary and also does whatever // cleanup needs to be done on that node. private void RemoveNode(long oid) { lock (nodeDictionary) { TestObject node = nodeDictionary[oid]; RemoveNode(node); nodeDictionary.Remove(oid); } } public void ClearWorld() { // Remove all objects from the scene lock (nodeDictionary) { foreach (TestObject node in nodeDictionary.Values) { RemoveNode(node); } nodeDictionary.Clear(); } SetPlayer(null); playerId = 0; playerInitialized = false; terrainInitialized = false; loadCompleted = false; } protected void SetupSubEntities(Entity entity, string[] submeshNames, string[] materialNames) { Logger.Log(2, "Submesh names for {0}: {1}", entity, ArrayToString(submeshNames)); Logger.Log(2, "Material names for {0}: {1}", entity, ArrayToString(materialNames)); } protected bool ApplyModel(TestObject node) { PreloadEntry entry = null; Monitor.Enter(preloadDictionary); try { if (!preloadDictionary.ContainsKey(node.Oid)) return false; entry = preloadDictionary[node.Oid]; preloadDictionary.Remove(node.Oid); } finally { Monitor.Exit(preloadDictionary); } // Our load of that entry may have been cancelled if (entry.cancelled == true) { Logger.Log(2, "Application of model to node cancelled for " + node.Oid); return false; } return true; } public float GetHeightAt(Vector3 location) { return 0; } public Vector3 MoveMobNode(TestObject mobNode, Vector3 desiredDisplacement) { Vector3 pos = mobNode.position + desiredDisplacement; return pos; } // At some point, I would like to expose the scene node tree, so that // I can have objects move with other objects. private void AddObjectStub(long oid, string name, Vector3 location, Quaternion orientation, Vector3 scale, ObjectNodeType objType, bool followTerrain) { Logger.Log(2, "In AddObjectStub - oid: {0}; name: {1}; objType {2}; followTerrain: {3}", oid, name, objType, followTerrain); TestObject stub = new TestObject(); stub.Oid = oid; stub.name = name; stub.followTerrain = followTerrain; stub.objectType = objType; nodeDictionary[oid] = stub; if (oid == playerId) { playerStubInitialized = true; playerInitialized = true; player = stub; } } // At some point, I would like to expose the scene node tree, so that // I can have objects move with other objects. // Also at some point I should expose multiple mesh files private void AddObject(long oid, string meshFile) { Logger.Log(2, "In AddObject - oid: {0}; model: {1}", oid, meshFile); TestObject node; lock (nodeDictionary) { if (nodeDictionary.ContainsKey(oid)) { Logger.Log(3, "Got duplicate AddObject for oid {0}", oid); if (!(nodeDictionary[oid] is TestObject)) { Logger.Log(3, "AddObject for exisisting non-object entity"); return; } node = nodeDictionary[oid]; ApplyModel(node); if (player == null && oid == playerId) player = node; return; } } TestObject objStub = GetObjectNode(oid); switch (objStub.objectType) { case ObjectNodeType.User: case ObjectNodeType.Npc: node = objStub; if (player == null && oid == playerId) player = node; break; case ObjectNodeType.Item: case ObjectNodeType.Prop: node = objStub; break; default: node = null; break; } node.FollowTerrain = objStub.followTerrain; bool status = ApplyModel(node); if (!status) return; // Pretend this message was created at time 0. Since the // direction vector is zero, this will not mess up the // interpolation, but will allow any of the server's queued // dirloc messages about this object to be processed node.SetDirLoc(0, Vector3.Zero, objStub.Position); node.SetOrientation(objStub.Orientation); if (node.Oid == playerId) player = node; lock (nodeDictionary) { nodeDictionary[oid] = node; if (ObjectAdded != null) ObjectAdded(this, node); } // if (objStub.objectType == ObjectNodeType.Npc || // objStub.objectType == ObjectNodeType.User) { // nameManager.AddNode(oid, node); // bubbleManager.AddNode(oid, node); // } } private void RemoveObject(long oid) { Logger.Log(2, "Got RemoveObject for oid {0}", oid); Debug.Assert(oid != playerId); if (oid == playerId) { Trace.TraceError("Attempted to remove the player from the world"); return; } // Clear the entry from the preload dictionary lock (preloadDictionary) { if (preloadDictionary.ContainsKey(oid)) { PreloadEntry entry = preloadDictionary[oid]; entry.cancelled = true; } } // Clear the entry from the world dictionary lock (nodeDictionary) { if (!nodeDictionary.ContainsKey(oid)) { Trace.TraceWarning("Got RemoveObject for invalid oid {0}", oid); return; } RemoveNode(oid); } Logger.Log(2, "Removed object for oid {0}", oid); } protected TestObject GetObjectStub(long oid) { lock (nodeDictionary) { return nodeDictionary[oid]; } } public TestObject GetObjectNode(long oid) { lock (nodeDictionary) { TestObject node; if (nodeDictionary.TryGetValue(oid, out node)) return node; return null; } } public TestObject GetObjectNode(string name) { lock (nodeDictionary) { foreach (TestObject node in nodeDictionary.Values) if (node.Name == name) return node; return null; } } // The timer event public void SendPlayerData(object sender, System.Timers.ElapsedEventArgs e) { if (player == null || networkHelper == null) return; long now = WorldManager.CurrentTime; SendDirectionMessage(player, now); SendOrientationMessage(player, now); } protected void SendOrientationMessage(TestObject node, long now) { if (node.orientUpdate.dirty) { Quaternion orient = node.orientUpdate.orientation; node.orientUpdate.dirty = false; networkHelper.SendOrientationMessage(orient); } else { // normal periodic send Quaternion orient = node.orientUpdate.orientation; networkHelper.SendOrientationMessage(orient); } } protected void SendDirectionMessage(TestObject node, long now) { if (node.dirUpdate.dirty) { long timestamp = node.dirUpdate.timestamp; Vector3 dir = node.dirUpdate.direction; Vector3 pos = node.dirUpdate.position; networkHelper.SendDirectionMessage(timestamp, dir, pos); node.dirUpdate.dirty = false; } else { long timestamp = node.dirUpdate.timestamp; Vector3 dir = node.Direction; Vector3 pos = node.Position; networkHelper.SendDirectionMessage(timestamp, dir, pos); } } protected static TimingMeter tickMeter = MeterManager.GetMeter("Tick Nodes", "WorldManager"); protected static TimingMeter directionMeter = MeterManager.GetMeter("Direction Message", "WorldManager"); protected static TimingMeter orientationMeter = MeterManager.GetMeter("Orientation Message", "WorldManager"); /// <summary> /// Called on each frame to update the nodes /// </summary> /// <param name="timeSinceLastFrame">time since the last frame in seconds</param> public void OnFrameStarted(long now) { if (player == null) return; tickMeter.Enter(); // lock (nodeDictionary) { // foreach (TestObject node in nodeDictionary.Values) // node.Tick(timeSinceLastFrame); // } // nameManager.Tick(timeSinceLastFrame, now); // bubbleManager.Tick(timeSinceLastFrame, now); tickMeter.Exit(); MessageDispatcher.Instance.HandleMessageQueue(behaviorParms.MaxMessagesPerFrame); if (player.dirUpdate.dirty && (player.lastDirSent + behaviorParms.DirUpdateInterval < now)) { directionMeter.Enter(); SendDirectionMessage(player, now); directionMeter.Exit(); } if (player.orientUpdate.dirty && (player.lastOrientSent + behaviorParms.OrientUpdateInterval < now)) { orientationMeter.Enter(); SendOrientationMessage(player, now); orientationMeter.Exit(); } // Also update animation states for objects that are not // on the server. } protected float playerYaw = 180; public void AsyncBehavior() { // We start out active if we're ever active bool playerActive = behaviorParms.maxActiveTime > 0; DateTime changeActivityTime = DateTime.Now; // Stall until we have our player while (player == null) Thread.Sleep(1000); // Now life starts. Every moveInterval milliseconds, we // move. If there is anyone nearby to chat with, we do // so. Random moveRand = new Random(); // Start out moving in a randon direction playerYaw = 360f * (float)moveRand.NextDouble(); // Remember where we started Vector3 startingPosition = Player.Position; // A counter of steps since we last changed direction, // used to ensure that we don't continuously reverse int changeCounter = 100; // Every 30 seconds we send a Comm message int commCounter = 30 * 1000 / behaviorParms.moveInterval; int messageNumber = 2; // Loop forever while (true) { Thread.Sleep(behaviorParms.moveInterval); // Count down the comm counter; send a message every 30 seconds commCounter--; if (commCounter < 0) { string s = (verifyServer ? "--verify_server Comm Message" : "Comm Message #" + messageNumber.ToString()); Logger.Log(1, "Sending Comm Message: " + s); networkHelper.SendCommMessage(s); commCounter = 30 * 1000 / behaviorParms.moveInterval; messageNumber = (messageNumber == 2 ? 1 : 2); } // Process any pending messages OnFrameStarted(CurrentTime); // See if we are reversing activity level DateTime n = DateTime.Now; if (changeActivityTime <= n) { float m = (float)moveRand.NextDouble(); int nextPeriodMS = (int)(m * (playerActive ? behaviorParms.maxIdleTime : behaviorParms.maxActiveTime)); if (nextPeriodMS > 0) { playerActive = !playerActive; changeActivityTime = n.AddMilliseconds(nextPeriodMS); } else { int currentPeriodMS = (int)(m * (playerActive ? behaviorParms.maxActiveTime : behaviorParms.maxIdleTime)); changeActivityTime = n.AddMilliseconds(currentPeriodMS); } } if (playerActive) { // If the last move left us outside the moveMaximum // limit, reverse directions changeCounter--; if (changeCounter < 0 && (Player.Position - startingPosition).Length > behaviorParms.moveMaximum * Client.OneMeter) { Logger.Log(1, "Reversing direction because the character is more than {0} meters from the starting position", behaviorParms.moveMaximum); PlayerYaw += 180; changeCounter = 100; continue; } float r = (float)moveRand.NextDouble(); float zMult = 0f; float xMult = 0f; float rotateMult = 0f; if (r < behaviorParms.forwardFraction) zMult = 1f; else { r -= behaviorParms.forwardFraction; if (r < behaviorParms.backFraction) zMult = -1f; else { r -= behaviorParms.backFraction; if (r < behaviorParms.rotateFraction) rotateMult = (r >= behaviorParms.rotateFraction * .5f ? 1f : -1f); else { r -= behaviorParms.rotateFraction; xMult = (r >= behaviorParms.sideFraction * .5f ? 1f : -1f); } } } MovePlayer(xMult, zMult, rotateMult); // Now that we're moved, is there anyone nearby to chat with? } else if (playerDir != Vector3.Zero) { playerDir = Vector3.Zero; Player.SetDirection(playerDir, Player.Position); } } } protected Vector3 playerDir = Vector3.Zero; protected Vector3 playerAccel = Vector3.Zero; protected void MovePlayer(float xMult, float zMult, float rotateMult) { // Now handle movement and stuff // reset acceleration zero playerAccel = Vector3.Zero; playerAccel.x += xMult * 0.5f; playerAccel.z += zMult * 1.0f; PlayerYaw += rotateMult * behaviorParms.rotateSpeed * behaviorParms.moveInterval / 1000f; Quaternion playerOrientation = Quaternion.FromAngleAxis(MathUtil.DegreesToRadians(PlayerYaw), Vector3.UnitY); Player.Orientation = playerOrientation; Matrix3 yawMatrix = Player.Orientation.ToRotationMatrix(); playerAccel.Normalize(); playerDir = (yawMatrix * behaviorParms.playerSpeed * playerAccel); Vector3 playerPos = Player.Position + (playerDir.ToNormalized() * behaviorParms.playerSpeed * behaviorParms.moveInterval / 1000f); Logger.Log(1, string.Format("Moving player in direction {0}, new position {1}", playerDir, playerPos)); Player.SetDirection(playerDir, playerPos); } /// <summary> /// Sets up the data needed for interpolated movement of an object. /// In this case, it is the direction, location, and timestamp when /// that location was the current location. /// </summary> /// <param name="oid">object id of the object for which we are setting the dir and loc</param> /// <param name="timestamp">time that the message was created (in client time)</param> /// <param name="dir">direction of motion of the object</param> /// <param name="loc">initial location of the object (at the time the message was created)</param> private void SetDirLoc(long oid, long timestamp, Vector3 dir, Vector3 loc) { TestObject node = GetObjectNode(oid); if (node != null) node.SetDirLoc(timestamp, dir, loc); else Trace.TraceWarning("No node match for: " + oid); } private void SetOrientation(long oid, Quaternion orient) { TestObject node = GetObjectNode(oid); if (node != null && node == player) Trace.TraceWarning("Ignoring orientation for player."); else if (node != null) node.SetOrientation(orient); else Trace.TraceWarning("No node match for: " + oid); // DEBUG if (node != null && node == player) Trace.TraceWarning("Server set player orientation to " + orient + " instead of " + player.Orientation); } private void SetPlayer(TestObject node) { player = node; } public long PlayerId { get { Monitor.Enter(this); long rv = playerId; Monitor.Exit(this); return rv; } set { Monitor.Enter(this); playerId = value; playerInitialized = true; SetPlayer(null); Monitor.Exit(this); } } public bool PlayerInitialized { get { Monitor.Enter(this); bool rv = playerInitialized; Monitor.Exit(this); return rv; } } public bool TerrainInitialized { get { return terrainInitialized; } } public bool PlayerStubInitialized { get { return playerStubInitialized; } } public bool LoadCompleted { get { return loadCompleted; } } public NetworkHelper NetworkHelper { set { networkHelper = value; } get { return networkHelper; } } public TestObject Player { get { Monitor.Enter(this); TestObject rv = player; Monitor.Exit(this); return rv; } } public static long CurrentTime { get { long timestamp = System.Environment.TickCount; while (timestamp < 0) { timestamp += int.MaxValue; timestamp -= int.MinValue; } return timestamp; } } public float PlayerYaw { get { return playerYaw; } set { while (value < 0) value += 360; playerYaw = value % 360; } } public bool VerifyServer { get { return verifyServer; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Text; using Moq; using NuGet.Test.Utility; namespace NuGet.Test { public class PackageUtility { public static IPackage CreateProjectLevelPackage(string id, string version = "1.0", IEnumerable<PackageDependency> dependencies = null) { return CreatePackage(id, version, assemblyReferences: new[] { id + ".dll" }, dependencies: dependencies); } public static IPackage CreatePackage(string id, string version = "1.0", IEnumerable<string> content = null, IEnumerable<string> assemblyReferences = null, IEnumerable<string> tools = null, IEnumerable<PackageDependency> dependencies = null, int downloadCount = 0, string description = null, string summary = null, bool listed = true, string tags = "", string language = null, IEnumerable<string> satelliteAssemblies = null, string minClientVersion = null, bool createRealStream = true) { assemblyReferences = assemblyReferences ?? Enumerable.Empty<string>(); satelliteAssemblies = satelliteAssemblies ?? Enumerable.Empty<string>(); return CreatePackage(id, version, content, CreateAssemblyReferences(assemblyReferences), tools, dependencies, downloadCount, description, summary, listed, tags, language, CreateAssemblyReferences(satelliteAssemblies), minClientVersion, createRealStream); } public static IPackage CreatePackage(string id, string version, IEnumerable<string> content, IEnumerable<IPackageAssemblyReference> assemblyReferences, IEnumerable<string> tools, IEnumerable<PackageDependency> dependencies, int downloadCount, string description, string summary, bool listed, string tags, string minClientVersion = null) { return CreatePackage(id, version, content, assemblyReferences, tools, dependencies, downloadCount, description, summary, listed, tags, language: null, satelliteAssemblies: null, minClientVersion: minClientVersion); } public static IPackage CreatePackageWithDependencySets(string id, string version = "1.0", IEnumerable<string> content = null, IEnumerable<string> assemblyReferences = null, IEnumerable<string> tools = null, IEnumerable<PackageDependencySet> dependencySets = null, int downloadCount = 0, string description = null, string summary = null, bool listed = true, string tags = "", string language = null, IEnumerable<string> satelliteAssemblies = null, string minClientVersion = null, bool createRealStream = true) { assemblyReferences = assemblyReferences ?? Enumerable.Empty<string>(); satelliteAssemblies = satelliteAssemblies ?? Enumerable.Empty<string>(); return CreatePackage(id, version, content, CreateAssemblyReferences(assemblyReferences), tools, dependencySets, downloadCount, description, summary, listed, tags, language, CreateAssemblyReferences(satelliteAssemblies), minClientVersion, createRealStream); } public static IPackage CreatePackage(string id, string version, IEnumerable<string> content, IEnumerable<IPackageAssemblyReference> assemblyReferences, IEnumerable<string> tools, IEnumerable<PackageDependency> dependencies, int downloadCount, string description, string summary, bool listed, string tags, string language, IEnumerable<IPackageAssemblyReference> satelliteAssemblies, string minClientVersion = null, bool createRealStream = true) { var dependencySets = new List<PackageDependencySet> { new PackageDependencySet(null, dependencies ?? Enumerable.Empty<PackageDependency>()) }; return CreatePackage(id, version, content, assemblyReferences, tools, dependencySets, downloadCount, description, summary, listed, tags, language, satelliteAssemblies, minClientVersion, createRealStream); } // If content is null, "file1.txt" is used added as a content file. public static IPackage CreatePackage(string id, string version, IEnumerable<string> content, IEnumerable<IPackageAssemblyReference> assemblyReferences, IEnumerable<string> tools, IEnumerable<PackageDependencySet> dependencySets, int downloadCount, string description, string summary, bool listed, string tags, string language, IEnumerable<IPackageAssemblyReference> satelliteAssemblies, string minClientVersion = null, bool createRealStream = true) { content = content ?? new[] { "file1.txt" }; assemblyReferences = assemblyReferences ?? Enumerable.Empty<IPackageAssemblyReference>(); satelliteAssemblies = satelliteAssemblies ?? Enumerable.Empty<IPackageAssemblyReference>(); dependencySets = dependencySets ?? Enumerable.Empty<PackageDependencySet>(); tools = tools ?? Enumerable.Empty<string>(); description = description ?? "Mock package " + id; var allFiles = new List<IPackageFile>(); allFiles.AddRange(CreateFiles(content, "content")); allFiles.AddRange(CreateFiles(tools, "tools")); allFiles.AddRange(assemblyReferences); allFiles.AddRange(satelliteAssemblies); var mockPackage = new Mock<IPackage>(MockBehavior.Strict) { CallBase = true }; mockPackage.Setup(m => m.IsAbsoluteLatestVersion).Returns(true); mockPackage.Setup(m => m.IsLatestVersion).Returns(String.IsNullOrEmpty(SemanticVersion.Parse(version).SpecialVersion)); mockPackage.Setup(m => m.Id).Returns(id); mockPackage.Setup(m => m.Listed).Returns(true); mockPackage.Setup(m => m.Version).Returns(new SemanticVersion(version)); mockPackage.Setup(m => m.GetFiles()).Returns(allFiles); mockPackage.Setup(m => m.AssemblyReferences).Returns(assemblyReferences); mockPackage.Setup(m => m.DependencySets).Returns(dependencySets); mockPackage.Setup(m => m.Description).Returns(description); mockPackage.Setup(m => m.Language).Returns("en-US"); mockPackage.Setup(m => m.Authors).Returns(new[] { "Tester" }); mockPackage.Setup(m => m.LicenseUrl).Returns(new Uri("ftp://test/somelicense.txts")); mockPackage.Setup(m => m.Summary).Returns(summary); mockPackage.Setup(m => m.FrameworkAssemblies).Returns(Enumerable.Empty<FrameworkAssemblyReference>()); mockPackage.Setup(m => m.Tags).Returns(tags); mockPackage.Setup(m => m.Title).Returns(String.Empty); mockPackage.Setup(m => m.DownloadCount).Returns(downloadCount); mockPackage.Setup(m => m.RequireLicenseAcceptance).Returns(false); mockPackage.Setup(m => m.DevelopmentDependency).Returns(false); mockPackage.Setup(m => m.Listed).Returns(listed); mockPackage.Setup(m => m.Language).Returns(language); mockPackage.Setup(m => m.IconUrl).Returns((Uri)null); mockPackage.Setup(m => m.ProjectUrl).Returns((Uri)null); mockPackage.Setup(m => m.ReleaseNotes).Returns(""); mockPackage.Setup(m => m.Owners).Returns(new string[0]); mockPackage.Setup(m => m.Copyright).Returns(""); mockPackage.Setup(m => m.MinClientVersion).Returns(minClientVersion == null ? new Version() : Version.Parse(minClientVersion)); mockPackage.Setup(m => m.PackageAssemblyReferences).Returns(new PackageReferenceSet[0]); if (!listed) { mockPackage.Setup(m => m.Published).Returns(Constants.Unpublished); } var targetFramework = allFiles.Select(f => f.TargetFramework).Where(f => f != null); mockPackage.Setup(m => m.GetSupportedFrameworks()).Returns(targetFramework); // Create the package's stream if (createRealStream) { PackageBuilder builder = new PackageBuilder(); builder.Id = id; builder.Version = new SemanticVersion(version); builder.Description = description; builder.Authors.Add("Tester"); foreach (var f in allFiles) { builder.Files.Add(f); } var packageStream = new MemoryStream(); builder.Save(packageStream); packageStream.Seek(0, SeekOrigin.Begin); mockPackage.Setup(m => m.GetStream()).Returns(packageStream); } else { mockPackage.Setup(m => m.GetStream()).Returns(new MemoryStream()); } return mockPackage.Object; } private static List<IPackageAssemblyReference> CreateAssemblyReferences(IEnumerable<string> fileNames) { var assemblyReferences = new List<IPackageAssemblyReference>(); foreach (var fileName in fileNames) { var mockAssemblyReference = new Mock<IPackageAssemblyReference>(); mockAssemblyReference.Setup(m => m.GetStream()).Returns(() => new MemoryStream()); mockAssemblyReference.Setup(m => m.Path).Returns(fileName); mockAssemblyReference.Setup(m => m.Name).Returns(Path.GetFileName(fileName)); string effectivePath; FrameworkName fn; try { fn = ParseFrameworkName(fileName, out effectivePath); } catch (ArgumentException) { effectivePath = fileName; fn = VersionUtility.UnsupportedFrameworkName; } if (fn != null) { mockAssemblyReference.Setup(m => m.EffectivePath).Returns(effectivePath); mockAssemblyReference.Setup(m => m.TargetFramework).Returns(fn); mockAssemblyReference.Setup(m => m.SupportedFrameworks).Returns(new[] { fn }); } else { mockAssemblyReference.Setup(m => m.EffectivePath).Returns(fileName); } assemblyReferences.Add(mockAssemblyReference.Object); } return assemblyReferences; } private static FrameworkName ParseFrameworkName(string fileName, out string effectivePath) { if (fileName.StartsWith("lib\\")) { fileName = fileName.Substring(4); return VersionUtility.ParseFrameworkFolderName(fileName, strictParsing: false, effectivePath: out effectivePath); } effectivePath = fileName; return null; } public static IPackageAssemblyReference CreateAssemblyReference(string path, FrameworkName targetFramework) { var mockAssemblyReference = new Mock<IPackageAssemblyReference>(); mockAssemblyReference.Setup(m => m.GetStream()).Returns(() => new MemoryStream()); mockAssemblyReference.Setup(m => m.Path).Returns(path); mockAssemblyReference.Setup(m => m.Name).Returns(path); mockAssemblyReference.Setup(m => m.TargetFramework).Returns(targetFramework); mockAssemblyReference.Setup(m => m.SupportedFrameworks).Returns(new[] { targetFramework }); return mockAssemblyReference.Object; } public static List<IPackageFile> CreateFiles(IEnumerable<string> fileNames, string directory = "") { var files = new List<IPackageFile>(); foreach (var fileName in fileNames) { var mockFile = CreateMockedPackageFile(directory, fileName); files.Add(mockFile.Object); } return files; } public static Mock<IPackageFile> CreateMockedPackageFile(string directory, string fileName, string content = null) { string path = PathFixUtility.FixPath(Path.Combine(directory, fileName)); content = content ?? path; var mockFile = new Mock<IPackageFile>(); mockFile.Setup(m => m.Path).Returns(path); mockFile.Setup(m => m.GetStream()).Returns(() => new MemoryStream(Encoding.Default.GetBytes(content))); string effectivePath; FrameworkName fn = VersionUtility.ParseFrameworkNameFromFilePath(path, out effectivePath); mockFile.Setup(m => m.TargetFramework).Returns(fn); mockFile.Setup(m => m.EffectivePath).Returns(effectivePath); mockFile.Setup(m => m.SupportedFrameworks).Returns( fn == null ? new FrameworkName[0] : new FrameworkName[] { fn }); return mockFile; } public static Stream CreateSimplePackageStream(string id, string version = "1.0") { var packageBuilder = new PackageBuilder { Id = id, Version = SemanticVersion.Parse(version), Description = "Test description", }; var dependencySet = new PackageDependencySet(VersionUtility.DefaultTargetFramework, new PackageDependency[] { new PackageDependency("Foo") }); packageBuilder.DependencySets.Add(dependencySet); packageBuilder.Authors.Add("foo"); var memoryStream = new MemoryStream(); packageBuilder.Save(memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); return memoryStream; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; using Summae.HashAlgorithms; namespace Summae { internal partial class CalculateForm : Form { private FileInfo _file; private IList<SumItem> _items; internal CalculateForm(FileInfo file, IList<SumItem> items) { InitializeComponent(); this.Font = SystemFonts.MessageBoxFont; this.Cursor = Cursors.WaitCursor; this._file = file; this._items = items; this.Text = this._file.Name + " - " + this.Text; int dluW, dluH; using (var graphics = this.CreateGraphics()) { var fewCharSize = graphics.MeasureString("0123456789abcdef", SystemFonts.MessageBoxFont); dluW = (int)System.Math.Ceiling(fewCharSize.Width / 16); dluH = (int)System.Math.Ceiling(fewCharSize.Height); } if (items != null) { var labelWidth = 8 * dluW; var textWidth = 32 * dluW; foreach (var iItem in items) { var lw = iItem.Algorithm.DisplayName.Length * dluW; if (labelWidth < lw) { labelWidth = lw; } var tw = (int)(iItem.Algorithm.ResultByteCount * 2 + 3) * dluW; if (textWidth < tw) { textWidth = tw; } } var screenRect = Screen.GetBounds(this); if ((labelWidth + textWidth) > screenRect.Width) { labelWidth = (screenRect.Width / 10) * 1; textWidth = (screenRect.Width / 10) * 8; } textFileName.Top = dluW; textFileName.Left = dluW + labelWidth + dluW; textFileName.Width = textWidth + textFileName.Height; textFileName.ReadOnly = true; textFileName.Text = this._file.FullName; textFileName.SelectionStart = textFileName.Text.Length; textFileName.GotFocus += new EventHandler(text_GotFocus); textFileName.KeyDown += new KeyEventHandler(text_KeyDown); labelFileName.AutoSize = false; labelFileName.Left = dluW; labelFileName.Top = dluW; labelFileName.Width = labelWidth + dluW / 2; labelFileName.Height = textFileName.Height; labelFileName.TextAlign = ContentAlignment.MiddleLeft; labelFileName.AutoEllipsis = true; var top = dluW + textFileName.Height + dluW + dluW / 2; foreach (var iItem in items) { var text = new TextBox { Top = top, Left = dluW + labelWidth + dluW, Width = textWidth, ReadOnly = true, Visible = false }; text.GotFocus += new EventHandler(text_GotFocus); text.KeyDown += new KeyEventHandler(text_KeyDown); this.Controls.Add(text); iItem.TextBoxControl = text; var buttonCopy = new Button { Width = text.Height, Height = text.Height, Top = top, Left = text.Left + text.Width, Image = Properties.Resources.btnCopy_16, Tag = iItem, Visible = false }; buttonCopy.Click += new EventHandler(buttonCopy_Click); toolTip.SetToolTip(buttonCopy, "Copies " + iItem.Algorithm.DisplayName + " result."); this.Controls.Add(buttonCopy); iItem.ButtonCopyControl = buttonCopy; var buttonSave = new Button { Width = text.Height, Height = text.Height, Top = top, Left = buttonCopy.Left + buttonCopy.Width, Image = Properties.Resources.btnSave_16, Tag = iItem, Visible = false }; buttonSave.Click += new EventHandler(buttonSave_Click); toolTip.SetToolTip(buttonSave, "Creates new file that will contain result of " + iItem.Algorithm.DisplayName + " calculation. File will have same name as original with added ." + iItem.Algorithm.Name + " as extension."); this.Controls.Add(buttonSave); iItem.ButtonSaveControl = buttonSave; var label = new Label { AutoSize = false, Left = dluW, Top = top, Width = labelWidth + dluW / 2, Height = text.Height, Text = iItem.Algorithm.DisplayName + ":", TextAlign = ContentAlignment.MiddleLeft, AutoEllipsis = true, Visible = false }; this.Controls.Add(label); iItem.LabelControl = label; top += text.Height + dluW; } top += dluW; top += buttonCancel.Height; this.ClientSize = new Size(dluW + labelWidth + dluW + textWidth + textFileName.Height + textFileName.Height + dluW, top + dluW); buttonCancel.Location = new Point(this.ClientRectangle.Right - buttonCancel.Width - dluW, this.ClientRectangle.Bottom - buttonCancel.Height - dluW); progress.Location = new Point(dluW, dluW + textFileName.Height + dluW + dluW / 2); progress.Width = this.ClientRectangle.Width - dluW - dluW; labelSpeed.Location = new Point(dluW, progress.Top + progress.Height + dluW); var workArea = Screen.GetWorkingArea(this); if (this.Right > workArea.Right) { this.Left = workArea.Right - this.Width; } if (this.Bottom > workArea.Bottom) { this.Top = workArea.Bottom - this.Height; } //this.Location = new Point((screenRect.Width - this.Width) / 2, (screenRect.Height - this.Height) / 2); } Medo.Windows.Forms.TaskbarProgress.DefaultOwner = this; Medo.Windows.Forms.TaskbarProgress.DoNotThrowNotImplementedException = true; Medo.Windows.Forms.TaskbarProgress.SetState(Medo.Windows.Forms.TaskbarProgressState.Normal); bwFileReader.RunWorkerAsync(); } void buttonCopy_Click(object sender, EventArgs e) { var thisButton = (Button)sender; var thisItem = (SumItem)thisButton.Tag; try { Clipboard.Clear(); Clipboard.SetText(Settings.SpacedHash ? thisItem.ToSpacedString(Settings.UppercaseHash) : thisItem.ToNonspacedString(Settings.UppercaseHash)); } catch (ExternalException) { } } void buttonSave_Click(object sender, EventArgs e) { var thisButton = (Button)sender; var thisItem = (SumItem)thisButton.Tag; try { File.WriteAllText(this._file.FullName + "." + thisItem.Algorithm.Name, thisItem.ToNonspacedString(Settings.UppercaseHash)); thisButton.Enabled = false; buttonCancel.Select(); } catch (UnauthorizedAccessException ex) { Medo.MessageBox.ShowError(this, ex.Message); } catch (System.IO.IOException ex2) { Medo.MessageBox.ShowError(this, ex2.Message); } } void text_KeyDown(object sender, KeyEventArgs e) { if (e.KeyData == (Keys.Control | Keys.A)) { ((TextBox)sender).SelectAll(); } } void text_GotFocus(object sender, EventArgs e) { ((TextBox)sender).SelectAll(); } private void buttonCancel_Click(object sender, EventArgs e) { if (buttonCancel.Text.Equals("Cancel")) { bwFileReader.CancelAsync(); } else { this.Close(); } } private void bwFileReader_DoWork(object sender, DoWorkEventArgs e) { try { using (var sr = new System.IO.FileStream(this._file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read)) { var buffer = new byte[256 * 1024]; var stopWatch = new Stopwatch(); stopWatch.Start(); long lastMilliseconds = 0; do { if (bwFileReader.CancellationPending) { e.Cancel = true; break; } var count = sr.Read(buffer, 0, buffer.Length); foreach (var iItem in this._items) { if (sr.Position < sr.Length) { iItem.Algorithm.TransformBlock(buffer, 0, count); } else { iItem.Algorithm.TransformFinalBlock(buffer, 0, count); } } if (lastMilliseconds + 250 < stopWatch.ElapsedMilliseconds) { lastMilliseconds = stopWatch.ElapsedMilliseconds; var mbPerSecond = ((double)sr.Position / 1024 / 1024) / (stopWatch.ElapsedMilliseconds / 1000); if (!double.IsInfinity(mbPerSecond) && !double.IsNaN(mbPerSecond)) { var percent = (int)((sr.Position * 100) / sr.Length); if ((stopWatch.ElapsedMilliseconds < 15000) || (percent < 10)) { bwFileReader.ReportProgress(percent, mbPerSecond.ToString("0") + " MB/s"); } else if ((stopWatch.ElapsedMilliseconds < 60000) || (percent < 50)) { bwFileReader.ReportProgress(percent, mbPerSecond.ToString("0.0") + " MB/s"); } else { bwFileReader.ReportProgress(percent, mbPerSecond.ToString("0.00") + " MB/s"); } } } } while (sr.Position < sr.Length); var finalMbPerSecond = ((double)sr.Length / 1024 / 1024) / (stopWatch.ElapsedMilliseconds / 1000); if (double.IsInfinity(finalMbPerSecond) || double.IsNaN(finalMbPerSecond)) { bwFileReader.ReportProgress(100, ""); } else { bwFileReader.ReportProgress(100, finalMbPerSecond.ToString("0.00") + " MB/s"); } } } catch (Exception ex) { throw ex; } } private void bwFileReader_ProgressChanged(object sender, ProgressChangedEventArgs e) { progress.Value = e.ProgressPercentage; labelSpeed.Text = e.UserState.ToString(); Medo.Windows.Forms.TaskbarProgress.SetPercentage(e.ProgressPercentage); } private void bwFileReader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { this.Cursor = Cursors.Default; if (e.Error != null) { Medo.Windows.Forms.TaskbarProgress.SetState(Medo.Windows.Forms.TaskbarProgressState.Error); Medo.MessageBox.ShowError(this, e.Error.Message); this.Close(); } else if (e.Cancelled) { this.Close(); } else { Medo.Windows.Forms.TaskbarProgress.SetState(Medo.Windows.Forms.TaskbarProgressState.Normal); buttonCancel.Text = "Close"; progress.Visible = false; labelSpeed.Top = this.ClientRectangle.Height - labelSpeed.Height - labelSpeed.Left; var clipboardBytes = SumItem.GetExpectedResult(Clipboard.GetText()); foreach (var iItem in this._items) { if ((clipboardBytes != null) && (clipboardBytes.Length == iItem.Algorithm.ResultByteCount)) { iItem.ExpectedResult2 = clipboardBytes; } iItem.LabelControl.Visible = true; iItem.TextBoxControl.Text = Settings.SpacedHash ? iItem.ToSpacedString(Settings.UppercaseHash) : iItem.ToNonspacedString(Settings.UppercaseHash); if (iItem.AreResultsSame || iItem.AreResultsSame2) { iItem.TextBoxControl.BackColor = Color.LightGreen; iItem.ButtonSaveControl.Enabled = false; } else if (iItem.AreResultsDifferent) { iItem.TextBoxControl.BackColor = Color.Pink; } iItem.TextBoxControl.Visible = true; iItem.ButtonCopyControl.Visible = true; iItem.ButtonSaveControl.Visible = true; } } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (bwFileReader.IsBusy) { bwFileReader.CancelAsync(); } this.Hide(); while (bwFileReader.IsBusy) { Application.DoEvents(); //in order to allow call to RunWorkerCompleted } if (Application.OpenForms.Count == 1) { Application.Exit(); } } } }
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Testing.TimeZones; using NodaTime.Text; using NodaTime.TimeZones; using NUnit.Framework; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace NodaTime.Test.Text { public class ZonedDateTimePatternTest : PatternTestBase<ZonedDateTime> { // Three zones with a deliberately leading-substring-matching set of names. // Transition is at 1am local time, going forward an hour. private static readonly SingleTransitionDateTimeZone TestZone1 = new SingleTransitionDateTimeZone( Instant.FromUtc(2010, 1, 1, 0, 0), Offset.FromHours(1), Offset.FromHours(2), "ab"); // Transition is at 2am local time, going back an hour. private static readonly SingleTransitionDateTimeZone TestZone2 = new SingleTransitionDateTimeZone( Instant.FromUtc(2010, 1, 1, 0, 0), Offset.FromHours(2), Offset.FromHours(1), "abc"); private static readonly SingleTransitionDateTimeZone TestZone3 = new SingleTransitionDateTimeZone( Instant.FromUtc(2010, 1, 1, 0, 0), Offset.FromHours(1), Offset.FromHours(2), "abcd"); private static readonly IDateTimeZoneProvider TestProvider = new FakeDateTimeZoneSource.Builder { TestZone1, TestZone2, TestZone3 }.Build().ToProvider(); private static readonly DateTimeZone FixedPlus1 = FixedDateTimeZone.ForOffset(Offset.FromHours(1)); private static readonly DateTimeZone FixedWithMinutes = FixedDateTimeZone.ForOffset(Offset.FromHoursAndMinutes(1, 30)); private static readonly DateTimeZone FixedWithSeconds = FixedDateTimeZone.ForOffset(Offset.FromSeconds(5)); private static readonly DateTimeZone FixedMinus1 = FixedDateTimeZone.ForOffset(Offset.FromHours(-1)); private static readonly DateTimeZone France = DateTimeZoneProviders.Tzdb["Europe/Paris"]; private static readonly DateTimeZone Athens = DateTimeZoneProviders.Tzdb["Europe/Athens"]; private static readonly ZonedDateTime SampleZonedDateTimeCoptic = LocalDateTimePatternTest.SampleLocalDateTimeCoptic.InUtc(); // The standard example date/time used in all the MSDN samples, which means we can just cut and paste // the expected results of the standard patterns. private static readonly ZonedDateTime MsdnStandardExample = LocalDateTimePatternTest.MsdnStandardExample.InUtc(); private static readonly ZonedDateTime MsdnStandardExampleNoMillis = LocalDateTimePatternTest.MsdnStandardExampleNoMillis.InUtc(); internal static readonly Data[] InvalidPatternData = { new Data { Pattern = "", Message = TextErrorMessages.FormatStringEmpty }, new Data { Pattern = "dd MM uuuu HH:MM:SS", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'M' } }, // Note incorrect use of "u" (year) instead of "y" (year of era) new Data { Pattern = "dd MM uuuu HH:mm:ss gg", Message = TextErrorMessages.EraWithoutYearOfEra }, // Era specifier and calendar specifier in the same pattern. new Data { Pattern = "dd MM yyyy HH:mm:ss gg c", Message = TextErrorMessages.CalendarAndEra }, new Data { Pattern = "g", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { 'g', typeof(ZonedDateTime) } }, // Invalid patterns involving embedded values new Data { Pattern = "ld<d> uuuu", Message = TextErrorMessages.DateFieldAndEmbeddedDate }, new Data { Pattern = "l<uuuu-MM-dd HH:mm:ss> dd", Message = TextErrorMessages.DateFieldAndEmbeddedDate }, new Data { Pattern = "ld<d> ld<f>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "lt<T> HH", Message = TextErrorMessages.TimeFieldAndEmbeddedTime }, new Data { Pattern = "l<uuuu-MM-dd HH:mm:ss> HH", Message = TextErrorMessages.TimeFieldAndEmbeddedTime }, new Data { Pattern = "lt<T> lt<t>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "ld<d> l<F>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "l<F> ld<d>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "lt<T> l<F>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "l<F> lt<T>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, }; internal static Data[] ParseFailureData = { // Skipped value new Data { Pattern = "uuuu-MM-dd HH:mm z", Text = "2010-01-01 01:30 ab", Message = TextErrorMessages.SkippedLocalTime}, // Ambiguous value new Data { Pattern = "uuuu-MM-dd HH:mm z", Text = "2010-01-01 01:30 abc", Message = TextErrorMessages.AmbiguousLocalTime }, // Invalid offset within a skipped time new Data { Pattern = "uuuu-MM-dd HH:mm z o<g>", Text = "2010-01-01 01:30 ab +01", Message = TextErrorMessages.InvalidOffset}, // Invalid offset within an ambiguous time (doesn't match either option) new Data { Pattern = "uuuu-MM-dd HH:mm z o<g>", Text = "2010-01-01 01:30 abc +05", Message = TextErrorMessages.InvalidOffset}, // Invalid offset for an unambiguous time new Data { Pattern = "uuuu-MM-dd HH:mm z o<g>", Text = "2005-01-01 01:30 ab +02", Message = TextErrorMessages.InvalidOffset}, // Failures copied from LocalDateTimePatternTest new Data { Pattern = "dd MM uuuu HH:mm:ss", Text = "Complete mismatch", Message = TextErrorMessages.MismatchedNumber, Parameters = { "dd" }}, new Data { Pattern = "(c)", Text = "(xxx)", Message = TextErrorMessages.NoMatchingCalendarSystem }, // 24 as an hour is only valid when the time is midnight new Data { Pattern = "uuuu-MM-dd HH:mm:ss", Text = "2011-10-19 24:00:05", Message = TextErrorMessages.InvalidHour24 }, new Data { Pattern = "uuuu-MM-dd HH:mm:ss", Text = "2011-10-19 24:01:00", Message = TextErrorMessages.InvalidHour24 }, new Data { Pattern = "uuuu-MM-dd HH:mm", Text = "2011-10-19 24:01", Message = TextErrorMessages.InvalidHour24 }, new Data { Pattern = "uuuu-MM-dd HH:mm", Text = "2011-10-19 24:00", Template = new LocalDateTime(1970, 1, 1, 0, 0, 5).InZoneStrictly(TestZone1), Message = TextErrorMessages.InvalidHour24}, new Data { Pattern = "uuuu-MM-dd HH", Text = "2011-10-19 24", Template = new LocalDateTime(1970, 1, 1, 0, 5, 0).InZoneStrictly(TestZone1), Message = TextErrorMessages.InvalidHour24}, // Redundant specification of fixed zone but not enough digits - we'll parse UTC+01:00:00 and unexpectedly be left with 00 new Data { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 UTC+01:00:00.00", Message = TextErrorMessages.ExtraValueCharacters, Parameters = { ".00" }}, // Can't parse a pattern with a time zone abbreviation. new Data { Pattern = "uuuu-MM-dd HH:mm x", Text = "ignored", Message = TextErrorMessages.FormatOnlyPattern }, // Can't parse using a pattern that has no provider new Data { ZoneProvider = null, Pattern = "uuuu-MM-dd z", Text = "ignored", Message = TextErrorMessages.FormatOnlyPattern }, // Invalid ID new Data { Pattern = "uuuu-MM-dd z", Text = "2017-08-21 LemonCurdIceCream", Message = TextErrorMessages.NoMatchingZoneId } }; internal static Data[] ParseOnlyData = { // Template value time zone is from a different provider, but it's not part of the pattern. new Data(2013, 1, 13, 16, 2, France) { Pattern = "uuuu-MM-dd HH:mm", Text = "2013-01-13 16:02", Template = NodaConstants.UnixEpoch.InZone(France) }, // Skipped value, resolver returns start of second interval new Data(TestZone1.Transition.InZone(TestZone1)) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2010-01-01 01:30 ab", Resolver = Resolvers.CreateMappingResolver(Resolvers.ThrowWhenAmbiguous, Resolvers.ReturnStartOfIntervalAfter) }, // Skipped value, resolver returns end of first interval new Data(TestZone1.Transition.Minus(Duration.Epsilon).InZone(TestZone1)) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2010-01-01 01:30 ab", Resolver = Resolvers.CreateMappingResolver(Resolvers.ThrowWhenAmbiguous, Resolvers.ReturnEndOfIntervalBefore) }, // Parse-only tests from LocalDateTimeTest. new Data(2011, 10, 19, 16, 05, 20) { Pattern = "dd MM uuuu", Text = "19 10 2011", Template = new LocalDateTime(2000, 1, 1, 16, 05, 20).InUtc() }, new Data(2011, 10, 19, 16, 05, 20) { Pattern = "HH:mm:ss", Text = "16:05:20", Template = new LocalDateTime(2011, 10, 19, 0, 0, 0).InUtc() }, // Parsing using the semi-colon "comma dot" specifier new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "uuuu-MM-dd HH:mm:ss;fff", Text = "2011-10-19 16:05:20,352" }, new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "uuuu-MM-dd HH:mm:ss;FFF", Text = "2011-10-19 16:05:20,352" }, // 24:00 meaning "start of next day" new Data(2011, 10, 20) { Pattern = "uuuu-MM-dd HH:mm:ss", Text = "2011-10-19 24:00:00" }, new Data(2011, 10, 20, 0, 0, TestZone1) { Pattern = "uuuu-MM-dd HH:mm:ss", Text = "2011-10-19 24:00:00", Template = new LocalDateTime(1970, 1, 1, 0, 5, 0).InZoneStrictly(TestZone1) }, new Data(2011, 10, 20) { Pattern = "uuuu-MM-dd HH:mm", Text = "2011-10-19 24:00" }, new Data(2011, 10, 20) { Pattern = "uuuu-MM-dd HH", Text = "2011-10-19 24" }, // Redundant specification of offset new Data(2013, 01, 13, 15, 44, FixedPlus1) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 UTC+01:00" }, new Data(2013, 01, 13, 15, 44, FixedPlus1) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 UTC+01:00:00" }, }; internal static Data[] FormatOnlyData = { new Data(2011, 10, 19, 16, 05, 20) { Pattern = "ddd uuuu", Text = "Wed 2011" }, // Time zone isn't in the provider new Data(2013, 1, 13, 16, 2, France) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 16:02 Europe/Paris" }, // Ambiguous value - would be invalid if parsed with a strict parser. new Data(TestZone2.Transition.Plus(Duration.FromMinutes(30)).InZone(TestZone2)) { Pattern = "uuuu-MM-dd HH:mm", Text = "2010-01-01 01:30" }, // Winter new Data(2013, 1, 13, 16, 2, France) { Pattern = "uuuu-MM-dd HH:mm x", Text = "2013-01-13 16:02 CET" }, // Summer new Data(2013, 6, 13, 16, 2, France) { Pattern = "uuuu-MM-dd HH:mm x", Text = "2013-06-13 16:02 CEST" }, new Data(2013, 6, 13, 16, 2, France) { ZoneProvider = null, Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-06-13 16:02 Europe/Paris" }, // Standard patterns without a DateTimeZoneProvider new Data(MsdnStandardExampleNoMillis) { StandardPattern = ZonedDateTimePattern.GeneralFormatOnlyIso, Pattern = "G", Text = "2009-06-15T13:45:30 UTC (+00)", Culture = Cultures.FrFr, ZoneProvider = null}, new Data(MsdnStandardExample) { StandardPattern = ZonedDateTimePattern.ExtendedFormatOnlyIso, Pattern = "F", Text = "2009-06-15T13:45:30.09 UTC (+00)", Culture = Cultures.FrFr, ZoneProvider = null }, // Standard patterns without a resolver new Data(MsdnStandardExampleNoMillis) { StandardPattern = ZonedDateTimePattern.GeneralFormatOnlyIso, Pattern = "G", Text = "2009-06-15T13:45:30 UTC (+00)", Culture = Cultures.FrFr, Resolver = null}, new Data(MsdnStandardExample) { StandardPattern = ZonedDateTimePattern.ExtendedFormatOnlyIso, Pattern = "F", Text = "2009-06-15T13:45:30.09 UTC (+00)", Culture = Cultures.FrFr, Resolver = null }, }; internal static Data[] FormatAndParseData = { // Zone ID at the end new Data(2013, 01, 13, 15, 44, TestZone1) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 ab" }, new Data(2013, 01, 13, 15, 44, TestZone2) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 abc" }, new Data(2013, 01, 13, 15, 44, TestZone3) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 abcd" }, new Data(2013, 01, 13, 15, 44, FixedPlus1) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 UTC+01" }, new Data(2013, 01, 13, 15, 44, FixedMinus1) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 UTC-01" }, new Data(2013, 01, 13, 15, 44, DateTimeZone.Utc) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 UTC" }, // Zone ID at the start new Data(2013, 01, 13, 15, 44, TestZone1) { Pattern = "z uuuu-MM-dd HH:mm", Text = "ab 2013-01-13 15:44" }, new Data(2013, 01, 13, 15, 44, TestZone2) { Pattern = "z uuuu-MM-dd HH:mm", Text = "abc 2013-01-13 15:44" }, new Data(2013, 01, 13, 15, 44, TestZone3) { Pattern = "z uuuu-MM-dd HH:mm", Text = "abcd 2013-01-13 15:44" }, new Data(2013, 01, 13, 15, 44, FixedPlus1) { Pattern = "z uuuu-MM-dd HH:mm", Text = "UTC+01 2013-01-13 15:44" }, new Data(2013, 01, 13, 15, 44, FixedMinus1) { Pattern = "z uuuu-MM-dd HH:mm", Text = "UTC-01 2013-01-13 15:44" }, new Data(2013, 01, 13, 15, 44, DateTimeZone.Utc) { Pattern = "z uuuu-MM-dd HH:mm", Text = "UTC 2013-01-13 15:44" }, // More precise fixed zones. new Data(2013, 01, 13, 15, 44, FixedWithMinutes) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 UTC+01:30" }, new Data(2013, 01, 13, 15, 44, FixedWithSeconds) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 15:44 UTC+00:00:05" }, // Valid offset for an unambiguous time new Data(new LocalDateTime(2005, 1, 1, 1, 30).InZoneStrictly(TestZone1)) { Pattern = "uuuu-MM-dd HH:mm z o<g>", Text = "2005-01-01 01:30 ab +01"}, // Valid offset (in the middle of the pattern) for an unambiguous time new Data(new LocalDateTime(2005, 1, 1, 1, 30).InZoneStrictly(TestZone1)) { Pattern = "uuuu-MM-dd o<g> HH:mm z", Text = "2005-01-01 +01 01:30 ab"}, // Ambiguous value, resolver returns later value. new Data(TestZone2.Transition.Plus(Duration.FromMinutes(30)).InZone(TestZone2)) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2010-01-01 01:30 abc", Resolver = Resolvers.CreateMappingResolver(Resolvers.ReturnLater, Resolvers.ThrowWhenSkipped) }, // Ambiguous value, resolver returns earlier value. new Data(TestZone2.Transition.Plus(Duration.FromMinutes(-30)).InZone(TestZone2)) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2010-01-01 01:30 abc", Resolver = Resolvers.CreateMappingResolver(Resolvers.ReturnEarlier, Resolvers.ThrowWhenSkipped) }, // Ambiguous local value, but with offset for later value (smaller offset). new Data(TestZone2.Transition.Plus(Duration.FromMinutes(30)).InZone(TestZone2)) { Pattern = "uuuu-MM-dd HH:mm z o<g>", Text = "2010-01-01 01:30 abc +01"}, // Ambiguous local value, but with offset for earlier value (greater offset). new Data(TestZone2.Transition.Plus(Duration.FromMinutes(-30)).InZone(TestZone2)) { Pattern = "uuuu-MM-dd HH:mm z o<g>", Text = "2010-01-01 01:30 abc +02"}, // Specify the provider new Data(2013, 1, 13, 16, 2, France) { Pattern = "uuuu-MM-dd HH:mm z", Text = "2013-01-13 16:02 Europe/Paris", ZoneProvider = DateTimeZoneProviders.Tzdb}, // Tests without zones, copied from LocalDateTimePatternTest // Calendar patterns are invariant new Data(MsdnStandardExample) { Pattern = "(c) uuuu-MM-dd'T'HH:mm:ss.FFFFFFF", Text = "(ISO) 2009-06-15T13:45:30.09", Culture = Cultures.FrFr }, new Data(MsdnStandardExample) { Pattern = "uuuu-MM-dd(c)'T'HH:mm:ss.FFFFFFF", Text = "2009-06-15(ISO)T13:45:30.09", Culture = Cultures.EnUs }, new Data(SampleZonedDateTimeCoptic) { Pattern = "(c) uuuu-MM-dd'T'HH:mm:ss.FFFFFFFFF", Text = "(Coptic) 1976-06-19T21:13:34.123456789", Culture = Cultures.FrFr }, new Data(SampleZonedDateTimeCoptic) { Pattern = "uuuu-MM-dd'C'c'T'HH:mm:ss.FFFFFFFFF", Text = "1976-06-19CCopticT21:13:34.123456789", Culture = Cultures.EnUs }, // Use of the semi-colon "comma dot" specifier new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "uuuu-MM-dd HH:mm:ss;fff", Text = "2011-10-19 16:05:20.352" }, new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "uuuu-MM-dd HH:mm:ss;FFF", Text = "2011-10-19 16:05:20.352" }, new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "uuuu-MM-dd HH:mm:ss;FFF 'end'", Text = "2011-10-19 16:05:20.352 end" }, new Data(2011, 10, 19, 16, 05, 20) { Pattern = "uuuu-MM-dd HH:mm:ss;FFF 'end'", Text = "2011-10-19 16:05:20 end" }, // Standard patterns with a time zone provider new Data(2013, 01, 13, 15, 44, 30, 0, TestZone1) { StandardPattern = ZonedDateTimePattern.GeneralFormatOnlyIso.WithZoneProvider(TestProvider) , Pattern = "G", Text = "2013-01-13T15:44:30 ab (+02)", Culture = Cultures.FrFr }, new Data(2013, 01, 13, 15, 44, 30, 90, TestZone1) { StandardPattern = ZonedDateTimePattern.ExtendedFormatOnlyIso.WithZoneProvider(TestProvider), Pattern = "F", Text = "2013-01-13T15:44:30.09 ab (+02)", Culture = Cultures.FrFr }, // Custom embedded patterns (or mixture of custom and standard) new Data(2015, 10, 24, 11, 55, 30, 0, Athens) { Pattern = "ld<uuuu*MM*dd>'X'lt<HH_mm_ss> z o<g>", Text = "2015*10*24X11_55_30 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, new Data(2015, 10, 24, 11, 55, 30, 0, Athens) { Pattern = "lt<HH_mm_ss>'Y'ld<uuuu*MM*dd> z o<g>", Text = "11_55_30Y2015*10*24 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, new Data(2015, 10, 24, 11, 55, 30, 0, Athens) { Pattern = "l<HH_mm_ss'Y'uuuu*MM*dd> z o<g>", Text = "11_55_30Y2015*10*24 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, new Data(2015, 10, 24, 11, 55, 30, 0, Athens) { Pattern = "ld<d>'X'lt<HH_mm_ss> z o<g>", Text = "10/24/2015X11_55_30 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, new Data(2015, 10, 24, 11, 55, 30, 0, Athens) { Pattern = "ld<uuuu*MM*dd>'X'lt<T> z o<g>", Text = "2015*10*24X11:55:30 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, // Standard embedded patterns. Short time versions have a seconds value of 0 so they can round-trip. new Data(2015, 10, 24, 11, 55, 30, 90, Athens) { Pattern = "ld<D> lt<r> z o<g>", Text = "Saturday, 24 October 2015 11:55:30.09 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, new Data(2015, 10, 24, 11, 55, 0, 0, Athens) { Pattern = "l<f> z o<g>", Text = "Saturday, 24 October 2015 11:55 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, new Data(2015, 10, 24, 11, 55, 30, 0, Athens) { Pattern = "l<F> z o<g>", Text = "Saturday, 24 October 2015 11:55:30 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, new Data(2015, 10, 24, 11, 55, 0, 0, Athens) { Pattern = "l<g> z o<g>", Text = "10/24/2015 11:55 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, new Data(2015, 10, 24, 11, 55, 30, 0, Athens) { Pattern = "l<G> z o<g>", Text = "10/24/2015 11:55:30 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, // Nested embedded patterns new Data(2015, 10, 24, 11, 55, 30, 90, Athens) { Pattern = "l<ld<D> lt<r>> z o<g>", Text = "Saturday, 24 October 2015 11:55:30.09 Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, new Data(2015, 10, 24, 11, 55, 30, 0, Athens) { Pattern = "l<'X'lt<HH_mm_ss>'Y'ld<uuuu*MM*dd>'X'> z o<g>", Text = "X11_55_30Y2015*10*24X Europe/Athens +03", ZoneProvider = DateTimeZoneProviders.Tzdb }, // Check that unquoted T still works. new Data(2012, 1, 31, 17, 36, 45) { Text = "2012-01-31T17:36:45", Pattern = "uuuu-MM-ddTHH:mm:ss" }, // Check handling of F after non-period. new Data(2012, 1, 31, 17, 36, 45, 123) { Text = "2012-01-31T17:36:45x123", Pattern = "uuuu-MM-dd'T'HH:mm:ss'x'FFF" }, // Issue981 new Data(1906, 8, 29, 20, 58, 32, 0, DateTimeZoneProviders.Tzdb["Etc/GMT-12"]) { Text = "1906-08-29T20:58:32 Etc/GMT-12 (+12)", Pattern = "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFF z '('o<g>')'", ZoneProvider = DateTimeZoneProviders.Tzdb }, // Fields not otherwise covered (according to tests running on AppVeyor...) new Data(MsdnStandardExample) { Pattern = "d MMMM yyyy (g) h:mm:ss.FF tt", Text = "15 June 2009 (A.D.) 1:45:30.09 PM" }, }; internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData); internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData); [Test] public void WithTemplateValue() { var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("uuuu-MM-dd", TestProvider) .WithTemplateValue(Instant.FromUtc(1970, 1, 1, 11, 30).InZone(TestZone3)); var parsed = pattern.Parse("2017-08-23").Value; Assert.AreSame(TestZone3, parsed.Zone); // TestZone3 is at UTC+1 in 1970, so the template value's *local* time is 12pm. // Even though we're parsing a date in 2017, it's the local time from the template value that's used. Assert.AreEqual(new LocalDateTime(2017, 8, 23, 12, 30, 0), parsed.LocalDateTime); Assert.AreEqual(Offset.FromHours(2), parsed.Offset); } [Test] public void WithCalendar() { var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("uuuu-MM-dd", TestProvider).WithCalendar(CalendarSystem.Coptic); var parsed = pattern.Parse("0284-08-29").Value; Assert.AreEqual(new LocalDateTime(284, 8, 29, 0, 0, CalendarSystem.Coptic), parsed.LocalDateTime); } [Test] public void WithPatternText() { var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("uuuu", TestProvider).WithPatternText("uuuu-MM-dd"); var text = pattern.Format(NodaConstants.UnixEpoch.InUtc()); Assert.AreEqual("1970-01-01", text); } [Test] public void CreateWithCurrentCulture() { using (CultureSaver.SetCultures(Cultures.DotTimeSeparator)) { var pattern = ZonedDateTimePattern.CreateWithCurrentCulture("HH:mm", null); var text = pattern.Format(Instant.FromUtc(2000, 1, 1, 19, 30).InUtc()); Assert.AreEqual("19.30", text); } } [Test] public void WithCulture() { var pattern = ZonedDateTimePattern.CreateWithInvariantCulture("HH:mm", null).WithCulture(Cultures.DotTimeSeparator); var text = pattern.Format(Instant.FromUtc(2000, 1, 1, 19, 30).InUtc()); Assert.AreEqual("19.30", text); } // Test to hit each exit condition in the time zone ID parsing part of ZonedDateTimePatternParser [Test] public void FindLongestZoneId() { var source = new FakeDateTimeZoneSource.Builder { CreateZone("ABC"), CreateZone("ABCA"), CreateZone("ABCB"), CreateZone("ABCBX"), CreateZone("ABCD") }.Build(); var provider = new DateTimeZoneCache(source); var pattern = ZonedDateTimePattern.Create("z 'x'", CultureInfo.InvariantCulture, Resolvers.StrictResolver, provider, NodaConstants.UnixEpoch.InUtc()); foreach (var id in provider.Ids) { var value = pattern.Parse($"{id} x").Value; Assert.AreEqual(id, value.Zone.Id); } DateTimeZone CreateZone(string id) => new SingleTransitionDateTimeZone(NodaConstants.UnixEpoch - Duration.FromDays(1),Offset.FromHours(-1), Offset.FromHours(0), id); } [Test] public void ParseNull() => AssertParseNull(ZonedDateTimePattern.ExtendedFormatOnlyIso.WithZoneProvider(TestProvider)); public sealed class Data : PatternTestData<ZonedDateTime> { // Default to the start of the year 2000 UTC protected override ZonedDateTime DefaultTemplate => ZonedDateTimePattern.DefaultTemplateValue; internal ZoneLocalMappingResolver? Resolver { get; set; } internal IDateTimeZoneProvider? ZoneProvider { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Data" /> class. /// </summary> /// <param name="value">The value.</param> public Data(ZonedDateTime value) : base(value) { Resolver = Resolvers.StrictResolver; ZoneProvider = TestProvider; } public Data(int year, int month, int day) : this(new LocalDateTime(year, month, day, 0, 0).InUtc()) { } // Coincidentally, we don't specify time zones in tests other than the // ones which just go down to the date and hour/minute. public Data(int year, int month, int day, int hour, int minute, DateTimeZone zone) : this(new LocalDateTime(year, month, day, hour, minute).InZoneStrictly(zone)) { } public Data(int year, int month, int day, int hour, int minute, int second) : this(new LocalDateTime(year, month, day, hour, minute, second).InUtc()) { } public Data(int year, int month, int day, int hour, int minute, int second, int millis) : this(new LocalDateTime(year, month, day, hour, minute, second, millis).InUtc()) { } public Data(int year, int month, int day, int hour, int minute, int second, int millis, DateTimeZone zone) : this(new LocalDateTime(year, month, day, hour, minute, second, millis).InZoneStrictly(zone)) { } public Data() : this(ZonedDateTimePattern.DefaultTemplateValue) { } internal override IPattern<ZonedDateTime> CreatePattern() => ZonedDateTimePattern.Create(Pattern!, Culture, Resolver, ZoneProvider, Template); public override string ToString() => $"{base.ToString()};Resolver? {(Resolver==null ? "N" : "Y")}; Provider: {ZoneProvider?.VersionId}"; } } }
// Copyright 2022 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 gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="AdGroupCriterionCustomizerServiceClient"/> instances.</summary> public sealed partial class AdGroupCriterionCustomizerServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="AdGroupCriterionCustomizerServiceSettings"/>. /// </summary> /// <returns>A new instance of the default <see cref="AdGroupCriterionCustomizerServiceSettings"/>.</returns> public static AdGroupCriterionCustomizerServiceSettings GetDefault() => new AdGroupCriterionCustomizerServiceSettings(); /// <summary> /// Constructs a new <see cref="AdGroupCriterionCustomizerServiceSettings"/> object with default settings. /// </summary> public AdGroupCriterionCustomizerServiceSettings() { } private AdGroupCriterionCustomizerServiceSettings(AdGroupCriterionCustomizerServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateAdGroupCriterionCustomizersSettings = existing.MutateAdGroupCriterionCustomizersSettings; OnCopy(existing); } partial void OnCopy(AdGroupCriterionCustomizerServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupCriterionCustomizerServiceClient.MutateAdGroupCriterionCustomizers</c> and /// <c>AdGroupCriterionCustomizerServiceClient.MutateAdGroupCriterionCustomizersAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateAdGroupCriterionCustomizersSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AdGroupCriterionCustomizerServiceSettings"/> object.</returns> public AdGroupCriterionCustomizerServiceSettings Clone() => new AdGroupCriterionCustomizerServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupCriterionCustomizerServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> internal sealed partial class AdGroupCriterionCustomizerServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupCriterionCustomizerServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupCriterionCustomizerServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupCriterionCustomizerServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupCriterionCustomizerServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupCriterionCustomizerServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupCriterionCustomizerServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupCriterionCustomizerServiceClient Build() { AdGroupCriterionCustomizerServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupCriterionCustomizerServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupCriterionCustomizerServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupCriterionCustomizerServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupCriterionCustomizerServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupCriterionCustomizerServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupCriterionCustomizerServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupCriterionCustomizerServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupCriterionCustomizerServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupCriterionCustomizerServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AdGroupCriterionCustomizerService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ad group criterion customizer /// </remarks> public abstract partial class AdGroupCriterionCustomizerServiceClient { /// <summary> /// The default endpoint for the AdGroupCriterionCustomizerService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AdGroupCriterionCustomizerService scopes.</summary> /// <remarks> /// The default AdGroupCriterionCustomizerService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AdGroupCriterionCustomizerServiceClient"/> using the default /// credentials, endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupCriterionCustomizerServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupCriterionCustomizerServiceClient"/>.</returns> public static stt::Task<AdGroupCriterionCustomizerServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupCriterionCustomizerServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupCriterionCustomizerServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupCriterionCustomizerServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupCriterionCustomizerServiceClient"/>.</returns> public static AdGroupCriterionCustomizerServiceClient Create() => new AdGroupCriterionCustomizerServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupCriterionCustomizerServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AdGroupCriterionCustomizerServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupCriterionCustomizerServiceClient"/>.</returns> internal static AdGroupCriterionCustomizerServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupCriterionCustomizerServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupCriterionCustomizerService.AdGroupCriterionCustomizerServiceClient grpcClient = new AdGroupCriterionCustomizerService.AdGroupCriterionCustomizerServiceClient(callInvoker); return new AdGroupCriterionCustomizerServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AdGroupCriterionCustomizerService client</summary> public virtual AdGroupCriterionCustomizerService.AdGroupCriterionCustomizerServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes ad group criterion customizers. Operation /// statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupCriterionCustomizersResponse MutateAdGroupCriterionCustomizers(MutateAdGroupCriterionCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes ad group criterion customizers. Operation /// statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupCriterionCustomizersResponse> MutateAdGroupCriterionCustomizersAsync(MutateAdGroupCriterionCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates or removes ad group criterion customizers. Operation /// statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupCriterionCustomizersResponse> MutateAdGroupCriterionCustomizersAsync(MutateAdGroupCriterionCustomizersRequest request, st::CancellationToken cancellationToken) => MutateAdGroupCriterionCustomizersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates or removes ad group criterion customizers. Operation /// statuses are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group criterion customizers are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group criterion /// customizers. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupCriterionCustomizersResponse MutateAdGroupCriterionCustomizers(string customerId, scg::IEnumerable<AdGroupCriterionCustomizerOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupCriterionCustomizers(new MutateAdGroupCriterionCustomizersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes ad group criterion customizers. Operation /// statuses are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group criterion customizers are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group criterion /// customizers. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupCriterionCustomizersResponse> MutateAdGroupCriterionCustomizersAsync(string customerId, scg::IEnumerable<AdGroupCriterionCustomizerOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupCriterionCustomizersAsync(new MutateAdGroupCriterionCustomizersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates or removes ad group criterion customizers. Operation /// statuses are returned. /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose ad group criterion customizers are being /// modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group criterion /// customizers. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupCriterionCustomizersResponse> MutateAdGroupCriterionCustomizersAsync(string customerId, scg::IEnumerable<AdGroupCriterionCustomizerOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupCriterionCustomizersAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupCriterionCustomizerService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ad group criterion customizer /// </remarks> public sealed partial class AdGroupCriterionCustomizerServiceClientImpl : AdGroupCriterionCustomizerServiceClient { private readonly gaxgrpc::ApiCall<MutateAdGroupCriterionCustomizersRequest, MutateAdGroupCriterionCustomizersResponse> _callMutateAdGroupCriterionCustomizers; /// <summary> /// Constructs a client wrapper for the AdGroupCriterionCustomizerService service, with the specified gRPC /// client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="AdGroupCriterionCustomizerServiceSettings"/> used within this client. /// </param> public AdGroupCriterionCustomizerServiceClientImpl(AdGroupCriterionCustomizerService.AdGroupCriterionCustomizerServiceClient grpcClient, AdGroupCriterionCustomizerServiceSettings settings) { GrpcClient = grpcClient; AdGroupCriterionCustomizerServiceSettings effectiveSettings = settings ?? AdGroupCriterionCustomizerServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateAdGroupCriterionCustomizers = clientHelper.BuildApiCall<MutateAdGroupCriterionCustomizersRequest, MutateAdGroupCriterionCustomizersResponse>(grpcClient.MutateAdGroupCriterionCustomizersAsync, grpcClient.MutateAdGroupCriterionCustomizers, effectiveSettings.MutateAdGroupCriterionCustomizersSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupCriterionCustomizers); Modify_MutateAdGroupCriterionCustomizersApiCall(ref _callMutateAdGroupCriterionCustomizers); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateAdGroupCriterionCustomizersApiCall(ref gaxgrpc::ApiCall<MutateAdGroupCriterionCustomizersRequest, MutateAdGroupCriterionCustomizersResponse> call); partial void OnConstruction(AdGroupCriterionCustomizerService.AdGroupCriterionCustomizerServiceClient grpcClient, AdGroupCriterionCustomizerServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupCriterionCustomizerService client</summary> public override AdGroupCriterionCustomizerService.AdGroupCriterionCustomizerServiceClient GrpcClient { get; } partial void Modify_MutateAdGroupCriterionCustomizersRequest(ref MutateAdGroupCriterionCustomizersRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates or removes ad group criterion customizers. Operation /// statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateAdGroupCriterionCustomizersResponse MutateAdGroupCriterionCustomizers(MutateAdGroupCriterionCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupCriterionCustomizersRequest(ref request, ref callSettings); return _callMutateAdGroupCriterionCustomizers.Sync(request, callSettings); } /// <summary> /// Creates, updates or removes ad group criterion customizers. Operation /// statuses are returned. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateAdGroupCriterionCustomizersResponse> MutateAdGroupCriterionCustomizersAsync(MutateAdGroupCriterionCustomizersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupCriterionCustomizersRequest(ref request, ref callSettings); return _callMutateAdGroupCriterionCustomizers.Async(request, callSettings); } } }
//------------------------------------------------------------------------------ // Symbooglix // // // Copyright 2014-2017 Daniel Liew // // This file is licensed under the MIT license. // See LICENSE.txt for details. //------------------------------------------------------------------------------ using System; using Microsoft.Boogie; using System.Collections.Generic; using System.Linq; using System.Collections.Immutable; using System.Numerics; using System.Diagnostics; namespace Symbooglix { public interface IVariableStore : IEnumerable<KeyValuePair<Variable,Expr>> { // FIXME: Change name void Add(Variable v, Expr initialValue); // FIXME: Change name bool ContainsKey(Variable v); IEnumerable<Variable> Keys { get; } IVariableStore Clone(); int Count { get; } // Direct Read and Write. // Avoid using this for maps if possible // TODO: Remove this. This is here to make refactoring easier but eventually Expr this [Variable v] { get; set; } // Note here that the indicies are ordered as they would be used // to perform an access syntactically in Boogie (i.e. left to right) // e.g. if the access is m[0][1] then the indicies should be {0, 1}. Expr ReadMap(Variable mapVariable, IList<Expr> indicies); void WriteMap(Variable mapVariable, IList<Expr> indicies, Expr value); void MapCopy(Variable dest, Variable src, IVariableStore srcStore); } public class SimpleVariableStore : IVariableStore { private ImmutableDictionary<Variable, Expr>.Builder BasicTypeVariableStore; private ImmutableDictionary<Variable, MapProxy>.Builder MapTypeVariableStore; private BigInteger CopyOnWriteKey; // Epoch counter for MapProxy objects public SimpleVariableStore() { var emptyDict = ImmutableDictionary<Variable, Expr>.Empty; BasicTypeVariableStore = emptyDict.ToBuilder(); var emptyMPDict = ImmutableDictionary<Variable, MapProxy>.Empty; MapTypeVariableStore = emptyMPDict.ToBuilder(); CopyOnWriteKey = new BigInteger(0); } private bool IsMapVariable(Variable v) { return v.TypedIdent.Type.IsMap; } private void TypeCheckDirectAssign(Variable v, Expr initialValue) { if (initialValue == null) throw new ArgumentException("assignment cannot be null"); if (!v.TypedIdent.Type.Equals(initialValue.Type)) throw new ExprTypeCheckException("Variable type and expression type do not match"); } public void Add(Variable v, Expr initialValue) { TypeCheckDirectAssign(v, initialValue); if (IsMapVariable(v)) { var mp = new MapProxy(initialValue, this.CopyOnWriteKey); MapTypeVariableStore.Add(v, mp); } else BasicTypeVariableStore.Add(v, initialValue); } public bool ContainsKey(Variable v) { if (IsMapVariable(v)) return MapTypeVariableStore.ContainsKey(v); else return BasicTypeVariableStore.ContainsKey(v); } public IEnumerable<Variable> Keys { get { return BasicTypeVariableStore.Keys.Concat(MapTypeVariableStore.Keys); } } public IVariableStore Clone() { var that = (SimpleVariableStore) this.MemberwiseClone(); // Expressions are immutable so no cloning is necessary. var copyBasicTypeVariableStore = this.BasicTypeVariableStore.ToImmutable(); that.BasicTypeVariableStore = copyBasicTypeVariableStore.ToBuilder(); var copyMapTypeVariableStore = this.MapTypeVariableStore.ToImmutable(); that.MapTypeVariableStore = copyMapTypeVariableStore.ToBuilder(); // Note we delay cloning the MapStore objects until an attempt is made to write to one of them. // This requires that we be must be very careful and make sure that any public interface that allows // writing to the MapProxy triggers a clone of the MapStore. // // Now that a copy has been performed we need to increment to CopyOnWrite key of this and that // so any MapStore objects we created before cloning will be copied if an attempt is // made to write to them (using one of the IVariable interfaces) from this or that. ++this.CopyOnWriteKey; ++that.CopyOnWriteKey; return that; } public Expr ReadMap(Variable mapVariable, IList<Expr> indicies) { if (!IsMapVariable(mapVariable)) throw new ArgumentException("expected map variable"); MapProxy mapProxyObj = null; MapTypeVariableStore.TryGetValue(mapVariable, out mapProxyObj); if (mapProxyObj == null) throw new KeyNotFoundException("map variable not in store"); return mapProxyObj.ReadMapAt(indicies); } public void WriteMap(Variable mapVariable, IList<Expr> indicies, Expr value) { if (!IsMapVariable(mapVariable)) throw new ArgumentException("expected map variable"); MapProxy mapProxyObj = null; MapTypeVariableStore.TryGetValue(mapVariable, out mapProxyObj); if (mapProxyObj == null) throw new KeyNotFoundException("map variable not in store"); if (mapProxyObj.CopyOnWriteOwnerKey != this.CopyOnWriteKey) { // Perform copy var newMp = mapProxyObj.Clone(this.CopyOnWriteKey); MapTypeVariableStore[mapVariable] = newMp; mapProxyObj = newMp; } Debug.Assert(mapProxyObj.CopyOnWriteOwnerKey == this.CopyOnWriteKey); mapProxyObj.WriteMapAt(indicies, value); } public void MapCopy(Variable dest, Variable src, IVariableStore srcStore) { if (!IsMapVariable(dest)) throw new ArgumentException("dest is not a map variable"); if (!IsMapVariable(src)) throw new ArgumentException("src is not a map variable"); if (!dest.TypedIdent.Type.Equals(src.TypedIdent.Type)) throw new ArgumentException("src and dest type do not match"); if (!MapTypeVariableStore.ContainsKey(dest)) throw new ArgumentException("destination variable not in store"); if (!srcStore.ContainsKey(src)) throw new ArgumentException("src is not in srcStore"); if (Object.ReferenceEquals(dest, src)) { // Copying to self shouldn't do anything. return; } if (srcStore is SimpleVariableStore) { // We can peak into the internals var srcInternalsMaps = ( srcStore as SimpleVariableStore ).MapTypeVariableStore; // Clone the internal representation of the map to avoid causing any flushes var mapProxyClone = srcInternalsMaps[src].Clone(this.CopyOnWriteKey); this.MapTypeVariableStore[dest] = mapProxyClone; Debug.Assert(this.MapTypeVariableStore[dest].CopyOnWriteOwnerKey == this.CopyOnWriteKey); } else { // Do potentially the expensive way (may trigger a flush of map stores) this[dest] = srcStore[src]; } } // Warning: This will trigger map store flushes public IEnumerator<KeyValuePair<Variable, Expr>> GetEnumerator() { foreach (var pair in BasicTypeVariableStore) yield return pair; foreach (var pair in MapTypeVariableStore) { var flushedExpr = pair.Value.Read(); yield return new KeyValuePair<Variable, Expr>(pair.Key, flushedExpr); } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return BasicTypeVariableStore.Count + MapTypeVariableStore.Count; } } // Avoid using this for maps. It will force map store flushes public Expr this[Variable v] { get { if (IsMapVariable(v)) { return MapTypeVariableStore[v].Read(); } else return BasicTypeVariableStore[v]; } set { TypeCheckDirectAssign(v, value); if (IsMapVariable(v)) { if (MapTypeVariableStore.ContainsKey(v)) { var mp = MapTypeVariableStore[v]; if (mp.CopyOnWriteOwnerKey != this.CopyOnWriteKey) { // Make copy var newMp = mp.Clone(this.CopyOnWriteKey); MapTypeVariableStore[v] = newMp; } MapTypeVariableStore[v].Write(value); } else { MapTypeVariableStore[v] = new MapProxy(value, this.CopyOnWriteKey); } Debug.Assert(MapTypeVariableStore[v].CopyOnWriteOwnerKey == this.CopyOnWriteKey); } else BasicTypeVariableStore[v] = value; } } } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace Python { namespace VisualC.WarningSuppression { sealed class PythonLibraryParser : C.SuppressWarningsDelegate { public PythonLibraryParser() { this.Add("grammar.c", "4244"); this.Add("myreadline.c", "4456", "4706"); this.Add("node.c", "4244"); this.Add("tokenizer.c", "4244", "4100", "4706"); } } sealed class PythonLibraryObjects : C.SuppressWarningsDelegate { public PythonLibraryObjects() { this.Add("abstract.c", "4100", "4706"); this.Add("boolobject.c", "4100"); this.Add("bytearrayobject.c", "4100", "4244", "4702"); this.Add("bytesobject.c", "4100", "4244", "4702"); this.Add("bytes_methods.c", "4100", "4244", "4702"); this.Add("cellobject.c", "4100"); this.Add("classobject.c", "4100"); this.Add("codeobject.c", "4100", "4244"); this.Add("complexobject.c", "4100", "4701"); this.Add("descrobject.c", "4100"); this.Add("dictobject.c", "4100", "4702", "4706"); this.Add("dictobject.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("exceptions.c", "4100"); this.Add("fileobject.c", "4100", "4244"); this.Add("floatobject.c", "4100", "4244"); this.Add("frameobject.c", "4100"); this.Add("funcobject.c", "4100", "4244"); this.Add("genobject.c", "4100"); this.Add("genobject.c", VisualCCommon.ToolchainVersion.VC2015, null, "4457"); this.Add("listobject.c", "4100"); this.Add("longobject.c", "4100", "4701"); this.Add("longobject.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("longobject.c", VisualCCommon.ToolchainVersion.VC2015, null, C.EBit.ThirtyTwo, "4244"); this.Add("memoryobject.c", "4100"); this.Add("memoryobject.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("methodobject.c", "4100"); this.Add("methodobject.c", VisualCCommon.ToolchainVersion.VC2015, VisualCCommon.ToolchainVersion.VC2015, "4054"); this.Add("moduleobject.c", "4100", "4152"); this.Add("moduleobject.c", VisualCCommon.ToolchainVersion.VC2015, VisualCCommon.ToolchainVersion.VC2015, "4055"); this.Add("namespaceobject.c", "4100"); this.Add("object.c", "4100"); this.Add("obmalloc.c", "4100"); this.Add("setobject.c", "4245"); this.Add("structseq.c", "4706"); this.Add("tupleobject.c", "4245"); this.Add("typeobject.c", "4204"); this.Add("typeobject.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("typeobject.c", VisualCCommon.ToolchainVersion.VC2015, VisualCCommon.ToolchainVersion.VC2015, "4054", "4055"); this.Add("unicodeobject.c", "4127", "4310", "4389", "4701", "4702", "4706"); this.Add("unicodeobject.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456", "4457"); } } sealed class PythonLibraryPython : C.SuppressWarningsDelegate { public PythonLibraryPython() { this.Add("ast.c", "4100", "4702"); this.Add("ast.c", VisualCCommon.ToolchainVersion.VC2015, null, "4457"); this.Add("bltinmodule.c", "4100", "4204", "4706"); this.Add("ceval.c", "4100", "4918", "4702"); this.Add("ceval.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456", "4457"); this.Add("codecs.c", "4310", "4244", "4100", "4706"); this.Add("codecs.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("compile.c", "4100", "4244", "4702"); this.Add("compile.c", VisualCCommon.ToolchainVersion.VC2015, null, "4457"); this.Add("dtoa.c", "4244", "4706"); this.Add("errors.c", "4706"); this.Add("fileutils.c", "4244", "4706"); this.Add("formatter_unicode.c", "4100"); this.Add("getargs.c", "4100", "4127", "4244", "4706"); this.Add("getargs.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("import.c", "4100", "4706"); this.Add("marshal.c", "4100", "4244"); this.Add("marshal.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("peephole.c", "4100", "4244", "4267"); this.Add("pyfpe.c", "4100"); this.Add("pylifecycle.c", "4100", "4210", "4706"); this.Add("pylifecycle.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("pystate.c", "4706"); this.Add("Python-ast.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("pythonrun.c", "4100"); this.Add("pytime.c", "4100"); this.Add("random.c", "4100"); this.Add("symtable.c", "4100", "4706"); this.Add("symtable.c", VisualCCommon.ToolchainVersion.VC2015, null, "4457"); this.Add("sysmodule.c", "4100", "4706"); this.Add("thread.c", "4100", "4189", "4389"); this.Add("traceback.c", "4100"); this.Add("_warnings.c", "4100"); this.Add("_warnings.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); } } sealed class PythonLibraryBuiltinModules : C.SuppressWarningsDelegate { public PythonLibraryBuiltinModules() { this.Add("main.c", "4706"); this.Add("_opcode.c", "4100"); this.Add("_lsprof.c", "4100"); this.Add("_json.c", "4100", "4244"); this.Add("_threadmodule.c", "4100", "4706"); this.Add("arraymodule.c", "4100", "4127", "4244", "4152"); this.Add("arraymodule.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("cmathmodule.c", "4100"); this.Add("mathmodule.c", "4100", "4701"); this.Add("_struct.c", "4100"); this.Add("pickle.c", "4100", "4127", "4702", "4706"); this.Add("pickle.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456", "4457"); this.Add("_datetimemodule.c", "4100", "4244"); this.Add("_datetimemodule.c", VisualCCommon.ToolchainVersion.VC2015, null, "4457"); this.Add("_bisectmodule.c", "4100"); this.Add("_heapqmodule.c", "4100"); this.Add("mmapmodule.c", "4100", "4057"); this.Add("_csv.c", "4100", "4245", "4706"); this.Add("audioop.c", "4100", "4244"); this.Add("md5module.c", "4100", "4701"); this.Add("sha1module.c", "4100", "4701"); this.Add("sha256module.c", "4100", "4701"); this.Add("sha512module.c", "4100", "4701"); this.Add("binascii.c", "4100", "4244"); this.Add("parsermodule.c", "4100"); this.Add("parsermodule.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("zlibmodule.c", "4100", "4267", "4706"); this.Add("xxsubtype.c", "4100", "4152"); this.Add("blake2s_impl.c", "4100", "4244", "4245"); this.Add("blake2b_impl.c", "4100", "4244", "4245"); this.Add("sha3module.c", "4100", "4324", "4245"); this.Add("signalmodule.c", "4100", "4057", "4706"); this.Add("signalmodule.c", VisualCCommon.ToolchainVersion.VC2015, VisualCCommon.ToolchainVersion.VC2015, "4054"); this.Add("gcmodule.c", "4100", "4244", "4706"); this.Add("posixmodule.c", "4100", "4057", "4389", "4201", "4701", "4702", "4703", "4706"); this.Add("_sre.c", "4100", "4918"); this.Add("codecsmodule.c", "4100"); this.Add("_weakref.c", "4100"); this.Add("_functoolsmodule.c", "4100", "4701", "4706"); this.Add("_operator.c", "4100"); this.Add("_operator.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("_collectionsmodule.c", "4100"); this.Add("itertoolsmodule.c", "4100", "4702"); this.Add("atexitmodule.c", "4100", "4701", "4703"); this.Add("_stat.c", "4100"); this.Add("timemodule.c", "4100", "4244"); this.Add("_localemodule.c", "4100"); this.Add("zipimport.c", "4100", "4127"); this.Add("faulthandler.c", "4100", "4702", "4706"); this.Add("faulthandler.c", VisualCCommon.ToolchainVersion.VC2015, null, "4459"); this.Add("_tracemalloc.c", "4100", "4204", "4359", "4706"); this.Add("hashtable.c", "4100"); this.Add("symtablemodule.c", "4100"); this.Add("_winapi.c", "4100", "4201", "4204", "4702"); this.Add("_winapi.c", C.EBit.ThirtyTwo, "4389"); this.Add("msvcrtmodule.c", "4100", "4244", "4310", "4311", "4312"); } } sealed class PythonLibraryCJKCodecs : C.SuppressWarningsDelegate { public PythonLibraryCJKCodecs() { this.Add("multibytecodec.c", "4100", "4127"); this.Add("_codecs_cn.c", "4100", "4244"); this.Add("_codecs_hk.c", "4100"); this.Add("_codecs_iso2022.c", "4100", "4244"); this.Add("_codecs_jp.c", "4100", "4244"); this.Add("_codecs_kr.c", "4100", "4244"); this.Add("_codecs_tw.c", "4100"); } } sealed class PythonLibraryIO : C.SuppressWarningsDelegate { public PythonLibraryIO() { this.Add("bufferedio.c", "4100", "4701", "4703"); this.Add("bufferedio.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("bytesio.c", "4100"); this.Add("fileio.c", "4100", "4701", "4703", "4706"); this.Add("iobase.c", "4100"); this.Add("stringio.c", "4100"); this.Add("textio.c", "4100", "4244", "4701", "4703"); this.Add("textio.c", VisualCCommon.ToolchainVersion.VC2015, null, "4456"); this.Add("winconsoleio.c", "4100", "4189", "4389", "4701", "4703"); this.Add("_iomodule.c", "4100", "4706"); } } } namespace Gcc.WarningSuppression { sealed class PythonLibraryParser : C.SuppressWarningsDelegate { public PythonLibraryParser() { this.Add("grammar.c", "format"); this.Add("metagrammar.c", "missing-field-initializers"); this.Add("tokenizer.c", "unused-parameter"); } } sealed class PythonLibraryObjects : C.SuppressWarningsDelegate { public PythonLibraryObjects() { this.Add("listobject.c", "unused-parameter", "missing-field-initializers"); this.Add("object.c", "format", "unused-parameter", "missing-field-initializers"); this.Add("bytes_methods.c", "unused-parameter", "missing-field-initializers"); this.Add("methodobject.c", "pedantic"); this.Add("typeobject.c", "pedantic"); this.Add("bytesobject.c", "unused-function"); this.Add("bytearrayobject.c", "unused-function"); this.Add("bytearrayobject.c", GccCommon.ToolchainVersion.GCC_5, null, Bam.Core.EConfiguration.NotDebug, "strict-overflow"); this.Add("obmalloc.c", "unused-parameter"); this.Add("capsule.c", "missing-field-initializers"); this.Add("moduleobject.c", "pedantic"); this.Add("abstract.c", "unused-parameter"); this.Add("unicodeobject.c", "unused-function"); this.Add("unicodeobject.c", GccCommon.ToolchainVersion.GCC_7, null, "implicit-fallthrough"); this.Add("structseq.c", "missing-field-initializers"); this.Add("exceptions.c", "missing-field-initializers", "unused-parameter"); this.Add("odictobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("namespaceobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("memoryobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("structseq.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("setobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("bytesobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("methodobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("frameobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("genobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("tupleobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("complexobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("dictobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("unicodeobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("funcobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("listobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("enumobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("typeobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("iterobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("longobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("bytearrayobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("rangeobject.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("exceptions.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("object.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("structseq.c", GccCommon.ToolchainVersion.GCC_9, null, Bam.Core.EConfiguration.NotDebug, "stringop-overflow"); } } sealed class PythonLibraryPython : C.SuppressWarningsDelegate { public PythonLibraryPython() { this.Add("sysmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("graminit.c", "missing-field-initializers"); this.Add("ast.c", "unused-parameter"); this.Add("ast.c", GccCommon.ToolchainVersion.GCC_7, null, "implicit-fallthrough"); this.Add("traceback.c", "unused-parameter", "missing-field-initializers"); this.Add("symtable.c", "unused-parameter", "missing-field-initializers"); this.Add("peephole.c", "unused-parameter"); this.Add("peephole.c", GccCommon.ToolchainVersion.GCC_7, null, "implicit-fallthrough"); this.Add("formatter_unicode.c", "unused-parameter"); this.Add("formatter_unicode.c", GccCommon.ToolchainVersion.GCC_7, null, "implicit-fallthrough"); this.Add("import.c", "unused-parameter", "missing-field-initializers"); this.Add("codecs.c", "unused-parameter", "missing-field-initializers"); this.Add("pylifecycle.c", "unused-parameter"); this.Add("getargs.c", "unused-parameter"); this.Add("getargs.c", GccCommon.ToolchainVersion.GCC_7, null, "implicit-fallthrough"); this.Add("random.c", "unused-parameter", "missing-field-initializers"); this.Add("compile.c", "unused-parameter", "overlength-strings"); this.Add("compile.c", GccCommon.ToolchainVersion.GCC_7, null, "implicit-fallthrough"); this.Add("bltinmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("_warnings.c", "unused-parameter", "missing-field-initializers"); this.Add("Python-ast.c", "missing-field-initializers"); this.Add("pyfpe.c", "unused-parameter"); this.Add("pythonrun.c", "unused-parameter"); this.Add("ceval.c", "unused-parameter"); this.Add("marshal.c", "unused-parameter", "missing-field-initializers"); this.Add("marshal.c", GccCommon.ToolchainVersion.GCC_7, null, "implicit-fallthrough"); this.Add("thread.c", "format"); this.Add("eval.c", GccCommon.ToolchainVersion.GCC_7, null, "implicit-fallthrough"); this.Add("pyhash.c", GccCommon.ToolchainVersion.GCC_7, null, "implicit-fallthrough"); this.Add("traceback.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("thread.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("sysmodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("_warnings.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("bltinmodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("Python-ast.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); } } sealed class PythonLibraryBuiltinModules : C.SuppressWarningsDelegate { public PythonLibraryBuiltinModules() { this.Add("pwdmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("signalmodule.c", "unused-parameter", "missing-field-initializers", "pedantic"); this.Add("gcmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("posixmodule.c", "unused-parameter", "missing-field-initializers", "implicit-function-declaration", "unused-function"); this.Add("errnomodule.c", "missing-field-initializers"); this.Add("_sre.c", "unused-parameter", "missing-field-initializers"); this.Add("_codecsmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("_weakref.c", "unused-parameter"); this.Add("_functoolsmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("_operator.c", "unused-parameter", "missing-field-initializers"); this.Add("_collectionsmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("itertoolsmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("atexitmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("_stat.c", "unused-parameter", "missing-field-initializers"); this.Add("timemodule.c", "unused-parameter", "missing-field-initializers"); this.Add("_localemodule.c", "unused-parameter", "missing-field-initializers"); this.Add("zipimport.c", "unused-parameter", "missing-field-initializers"); this.Add("faulthandler.c", "unused-parameter", "missing-field-initializers"); this.Add("_tracemalloc.c", "unused-parameter", "missing-field-initializers"); this.Add("hashtable.c", "unused-parameter", "format"); this.Add("symtablemodule.c", "unused-parameter", "missing-field-initializers"); this.Add("gcmodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("posixmodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("_sre.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("_codecsmodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("_functoolsmodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("_operator.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("_collectionsmodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("itertoolsmodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("atexitmodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("_localemodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("faulthandler.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("_tracemalloc.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); } } sealed class PythonLibraryCJKCodecs : C.SuppressWarningsDelegate { public PythonLibraryCJKCodecs() { } } sealed class PythonLibraryIO : C.SuppressWarningsDelegate { public PythonLibraryIO() { this.Add("_iomodule.c", "unused-parameter", "missing-field-initializers", "overlength-strings"); this.Add("bufferedio.c", "unused-parameter", "missing-field-initializers"); this.Add("textio.c", "unused-parameter", "missing-field-initializers"); this.Add("stringio.c", "unused-parameter", "missing-field-initializers"); this.Add("bytesio.c", "unused-parameter", "missing-field-initializers"); this.Add("iobase.c", "unused-parameter", "missing-field-initializers"); this.Add("fileio.c", "unused-parameter", "missing-field-initializers"); this.Add("textio.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("fileio.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("stringio.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("bytesio.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); this.Add("_iomodule.c", GccCommon.ToolchainVersion.GCC_8, null, "cast-function-type"); } } } namespace Clang.WarningSuppression { sealed class PythonLibraryParser : C.SuppressWarningsDelegate { public PythonLibraryParser() { this.Add("grammar.c", "format-pedantic"); this.Add("metagrammar.c", "missing-field-initializers"); this.Add("tokenizer.c", "unused-parameter"); } } sealed class PythonLibraryObjects : C.SuppressWarningsDelegate { public PythonLibraryObjects() { this.Add("setobject.c", "unused-parameter", "missing-field-initializers"); this.Add("odictobject.c", "missing-field-initializers"); this.Add("moduleobject.c", "unused-parameter", "missing-field-initializers", "pedantic"); this.Add("enumobject.c", "missing-field-initializers"); this.Add("object.c", "unused-parameter", "missing-field-initializers", "format-pedantic"); this.Add("complexobject.c", null, ClangCommon.ToolchainVersion.Xcode_9_4_1, "extended-offsetof"); this.Add("capsule.c", "missing-field-initializers"); this.Add("typeobject.c", null, ClangCommon.ToolchainVersion.Xcode_9_4_1, "extended-offsetof"); this.Add("obmalloc.c", "unused-parameter", "format-pedantic"); this.Add("unicodeobject.c", "unused-function"); this.Add("structseq.c", "missing-field-initializers"); this.Add("bytearrayobject.c", "unused-function"); this.Add("bytes_methods.c", "unused-parameter", "missing-field-initializers"); this.Add("bytesobject.c", "unused-function"); this.Add("abstract.c", "unused-parameter"); this.Add("exceptions.c", "unused-parameter", "missing-field-initializers"); } } sealed class PythonLibraryPython : C.SuppressWarningsDelegate { public PythonLibraryPython() { this.Add("codecs.c", "unused-parameter", "missing-field-initializers"); this.Add("formatter_unicode.c", "unused-parameter"); this.Add("compile.c", "unused-parameter"); this.Add("ast.c", "unused-parameter"); this.Add("thread.c", "missing-field-initializers", "format-pedantic"); this.Add("symtable.c", "unused-parameter", "missing-field-initializers"); this.Add("pyfpe.c", "unused-parameter"); this.Add("traceback.c", "unused-parameter", "missing-field-initializers"); this.Add("Python-ast.c", "missing-field-initializers"); this.Add("pythonrun.c", "unused-parameter"); this.Add("import.c", "unused-parameter", "missing-field-initializers"); this.Add("pytime.c", "unused-parameter"); this.Add("random.c", "unused-parameter", "missing-field-initializers"); this.Add("graminit.c", "missing-field-initializers"); this.Add("sysmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("bltinmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("marshal.c", "unused-parameter", "missing-field-initializers"); this.Add("getargs.c", "unused-parameter"); this.Add("_warnings.c", "unused-parameter", "missing-field-initializers"); this.Add("peephole.c", "unused-parameter"); this.Add("ceval.c", "unused-parameter"); this.Add("pylifecycle.c", "unused-parameter", "unused-function"); } } sealed class PythonLibraryBuiltinModules : C.SuppressWarningsDelegate { public PythonLibraryBuiltinModules() { this.Add("pwdmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("signalmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("gcmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("posixmodule.c", "unused-parameter", "missing-field-initializers", "implicit-function-declaration", "unused-function"); this.Add("errnomodule.c", "missing-field-initializers"); this.Add("_sre.c", "unused-parameter", "missing-field-initializers"); this.Add("_codecsmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("_weakref.c", "unused-parameter"); this.Add("_functoolsmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("_operator.c", "unused-parameter", "missing-field-initializers"); this.Add("_collectionsmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("itertoolsmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("atexitmodule.c", "unused-parameter", "missing-field-initializers"); this.Add("_stat.c", "unused-parameter", "missing-field-initializers"); this.Add("timemodule.c", "unused-parameter", "missing-field-initializers", "unused-function"); this.Add("_localemodule.c", "unused-parameter", "missing-field-initializers"); this.Add("zipimport.c", "unused-parameter", "missing-field-initializers"); this.Add("faulthandler.c", "unused-parameter", "missing-field-initializers"); this.Add("_tracemalloc.c", "unused-parameter", "missing-field-initializers"); this.Add("hashtable.c", "unused-parameter", "format-pedantic"); this.Add("symtablemodule.c", "unused-parameter", "missing-field-initializers"); } } sealed class PythonLibraryCJKCodecs : C.SuppressWarningsDelegate { public PythonLibraryCJKCodecs() { } } sealed class PythonLibraryIO : C.SuppressWarningsDelegate { public PythonLibraryIO() { this.Add("_iomodule.c", "unused-parameter", "missing-field-initializers", "overlength-strings"); this.Add("fileio.c", "unused-parameter", "missing-field-initializers"); this.Add("textio.c", "unused-parameter", "missing-field-initializers"); this.Add("bufferedio.c", "unused-parameter", "missing-field-initializers"); this.Add("iobase.c", "unused-parameter", "missing-field-initializers"); this.Add("bytesio.c", "unused-parameter", "missing-field-initializers"); this.Add("stringio.c", "unused-parameter", "missing-field-initializers"); } } } }
namespace System.Workflow.ComponentModel.Serialization { using System; using System.IO; using System.CodeDom; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Collections; using System.Xml; using System.Xml.Serialization; using System.Reflection; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Globalization; using System.Workflow.ComponentModel.Compiler; using System.Workflow.ComponentModel.Design; using System.Runtime.Serialization; using System.Security.Permissions; using System.Collections.ObjectModel; using System.Drawing; #region X:Key Support internal delegate object GetValueHandler(ExtendedPropertyInfo extendedProperty, object extendee); internal delegate void SetValueHandler(ExtendedPropertyInfo extendedProperty, object extendee, object value); internal delegate XmlQualifiedName GetQualifiedNameHandler(ExtendedPropertyInfo extendedProperty, WorkflowMarkupSerializationManager manager, out string prefix); #region Class ExtendedPropertyInfo internal sealed class ExtendedPropertyInfo : PropertyInfo { #region Members and Constructors private PropertyInfo realPropertyInfo = null; private GetValueHandler OnGetValue; private SetValueHandler OnSetValue; private GetQualifiedNameHandler OnGetXmlQualifiedName; private WorkflowMarkupSerializationManager manager = null; internal ExtendedPropertyInfo(PropertyInfo propertyInfo, GetValueHandler getValueHandler, SetValueHandler setValueHandler, GetQualifiedNameHandler qualifiedNameHandler) { this.realPropertyInfo = propertyInfo; this.OnGetValue = getValueHandler; this.OnSetValue = setValueHandler; this.OnGetXmlQualifiedName = qualifiedNameHandler; } internal ExtendedPropertyInfo(PropertyInfo propertyInfo, GetValueHandler getValueHandler, SetValueHandler setValueHandler, GetQualifiedNameHandler qualifiedNameHandler, WorkflowMarkupSerializationManager manager) : this(propertyInfo, getValueHandler, setValueHandler, qualifiedNameHandler) { this.manager = manager; } internal PropertyInfo RealPropertyInfo { get { return this.realPropertyInfo; } } internal WorkflowMarkupSerializationManager SerializationManager { get { return this.manager; } } #endregion #region Property Info overrides public override string Name { get { return this.realPropertyInfo.Name; } } public override Type DeclaringType { get { return this.realPropertyInfo.DeclaringType; } } public override Type ReflectedType { get { return this.realPropertyInfo.ReflectedType; } } public override Type PropertyType { get { return this.realPropertyInfo.PropertyType; } } public override MethodInfo[] GetAccessors(bool nonPublic) { return this.realPropertyInfo.GetAccessors(nonPublic); } public override MethodInfo GetGetMethod(bool nonPublic) { return this.realPropertyInfo.GetGetMethod(nonPublic); } public override MethodInfo GetSetMethod(bool nonPublic) { return this.realPropertyInfo.GetSetMethod(nonPublic); } public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { if (OnGetValue != null) return OnGetValue(this, obj); else return null; } public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, CultureInfo culture) { if (OnSetValue != null) OnSetValue(this, obj, value); } public XmlQualifiedName GetXmlQualifiedName(WorkflowMarkupSerializationManager manager, out string prefix) { prefix = String.Empty; if (OnGetXmlQualifiedName != null) return OnGetXmlQualifiedName(this, manager, out prefix); else return null; } public override ParameterInfo[] GetIndexParameters() { return this.realPropertyInfo.GetIndexParameters(); } public override PropertyAttributes Attributes { get { return this.realPropertyInfo.Attributes; } } public override bool CanRead { get { return this.realPropertyInfo.CanRead; } } public override bool CanWrite { get { return this.realPropertyInfo.CanWrite; } } #endregion #region MemberInfo Overrides public override object[] GetCustomAttributes(bool inherit) { return this.realPropertyInfo.GetCustomAttributes(inherit); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return this.realPropertyInfo.GetCustomAttributes(attributeType, inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return this.realPropertyInfo.IsDefined(attributeType, inherit); } #endregion #region Helpers internal static bool IsExtendedProperty(WorkflowMarkupSerializationManager manager, XmlQualifiedName xmlQualifiedName) { bool isExtendedProperty = false; object extendee = manager.Context.Current; if (extendee != null) { foreach (ExtendedPropertyInfo extendedProperty in manager.GetExtendedProperties(extendee)) { string prefix = String.Empty; XmlQualifiedName qualifiedPropertyName = extendedProperty.GetXmlQualifiedName(manager, out prefix); if (qualifiedPropertyName.Name.Equals(xmlQualifiedName.Name, StringComparison.Ordinal) && qualifiedPropertyName.Namespace.Equals(xmlQualifiedName.Namespace, StringComparison.Ordinal)) { isExtendedProperty = true; break; } } } return isExtendedProperty; } internal static bool IsExtendedProperty(WorkflowMarkupSerializationManager manager, IList<PropertyInfo> propInfos, XmlQualifiedName xmlQualifiedName) { foreach (PropertyInfo propInfo in propInfos) { ExtendedPropertyInfo extendedProperty = propInfo as ExtendedPropertyInfo; if (extendedProperty == null) continue; string prefix = String.Empty; XmlQualifiedName qualifiedPropertyName = extendedProperty.GetXmlQualifiedName(manager, out prefix); if (qualifiedPropertyName.Name.Equals(xmlQualifiedName.Name, StringComparison.Ordinal) && qualifiedPropertyName.Namespace.Equals(xmlQualifiedName.Namespace, StringComparison.Ordinal)) { return true; } } return false; } #endregion } #endregion #endregion }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using static System.Math; namespace LD34 { public class LevelManager : IRenderer, IUpdater { private const int GRID_WIDTH = 50; private const int GRID_HEIGHT = 80; private const int SPAWN_HEIGHT = 30; private const int CURRENT_BOARD_INDEX = 4; private readonly Color _bg1 = new Color(30, 30, 30); private readonly Color _bg2 = new Color(50, 50, 50); private readonly BeatTrigger _beatTrigger; private readonly Random _random; private readonly Queue<CellState[,]> _boards; private bool _bg12; private GraphicsDevice _graphicsDevice; private Rectangle _windowBounds; private int _pixelsPerX; private int _pixelsPerY; private Texture2D[] _textures; private int _virtualBoardWidth; private int _virtualBoardHeight; private GameEntity[] _newShapes; private const int MAX_NEW_SHAPES = 10; private Color CurrentBackground => _bg12 ? _bg1 : _bg2; public LevelManager(BeatTrigger beatBeatTrigger) { _random = new Random(); _beatTrigger = beatBeatTrigger; _virtualBoardWidth = (int)Ceiling(Sqrt(Pow(GRID_WIDTH, 2) * 2)); _virtualBoardHeight = 400; // TODO lol this works for the values w = 50, h = 80, gave up trying to work this out. also the name doesn't mean what it says const int boardCount = CURRENT_BOARD_INDEX + 1; _boards = new Queue<CellState[,]>(boardCount); _newShapes = new GameEntity[10]; } public void Initialise() { ResetGrid(); } private void ResetGrid() { _boards.Clear(); for (int i = 0; i <= CURRENT_BOARD_INDEX; i++) { // Seed the grid var grid = new CellState[GRID_WIDTH, _virtualBoardHeight]; for (int x = 0; x < GRID_WIDTH; x++) { for (int y = 0; y < _virtualBoardHeight; y++) { grid[x, y] = _random.NextDouble() > 0.8 ? CellState.Pending : CellState.Empty; } } _boards.Enqueue(grid); } } public void LoadContent(ContentManager contentManager, GraphicsDevice graphicsDevice, Rectangle windowBounds) { _graphicsDevice = graphicsDevice; _windowBounds = windowBounds; _pixelsPerX = _windowBounds.Width/GRID_WIDTH; _pixelsPerY = _windowBounds.Height/GRID_HEIGHT; _textures = new[] { Texture2DEx.NewSolid(graphicsDevice, _pixelsPerX, _pixelsPerY, _bg1), Texture2DEx.NewSolid(graphicsDevice, _pixelsPerX, _pixelsPerY, _bg1) }; } private void LoadGameEntities(long iteration, IList<GestureEvent> completedGestures, GameEntity[] newShapes) { // 3 gliders and 1 dot every ten iterations var gliders = Enumerable.Range(0, 5) .Select(i => new Point(_random.Next(0, GRID_WIDTH), _random.Next(0, SPAWN_HEIGHT))) .OrderBy(p => p.X) .Select(GameEntity.Glider); var dots = Enumerable.Range(0, 5) .Select(i => new Point(_random.Next(0, GRID_WIDTH), _random.Next(0, SPAWN_HEIGHT))) .OrderBy(p => p.X) .Select(GameEntity.Dot); var shapes = iteration % 10 == 0 ? gliders.Concat(dots) : Enumerable.Empty<GameEntity>(); var enumerator = shapes.GetEnumerator(); for (int i = 0; i < MAX_NEW_SHAPES; i++) { newShapes[i] = enumerator.MoveNext() ? enumerator.Current : null; } } public void Update(GameTime gameTime, IList<GestureEvent> completedGestures) { if (completedGestures.GetEvents<KeyboardEvent>().Any(k => k.Key == Keys.F5)) { ResetGrid(); return; } long iteration; if (!_beatTrigger.Triggering(gameTime, out iteration)) { return; } LoadGameEntities(iteration, completedGestures, _newShapes); GameEntity currentSpawning = null; var currentState = new CellState[9]; var newGrid = new CellState[GRID_WIDTH, _virtualBoardHeight]; var currentGrid = _boards.ElementAt(CURRENT_BOARD_INDEX); for (int virtualX = 0; virtualX < GRID_WIDTH * 2; virtualX++) // TODO not sure how many iterations this should actually do { for (int virtualY = 0; virtualY < GRID_HEIGHT; virtualY++) { currentState[0] = GetCellState(currentGrid, virtualX, virtualY); // Self if (currentSpawning == null) { currentSpawning = _newShapes .Where(shape => shape != null) .FirstOrDefault(shape => shape.Start.X == virtualX && shape.Start.Y == virtualY); } CellState? newState = null; if (currentSpawning != null) { var p = currentSpawning.Start; var oX = virtualX - p.X; var oY = virtualY - p.Y; var boundX = currentSpawning.Template.GetUpperBound(0); var boundY = currentSpawning.Template.GetUpperBound(1); if (oY >= 0 && oX >= 0 && oY <= boundY && oX <= boundX) { newState = currentSpawning.Template[oX, oY]; if (oY == boundY && oX == boundX) { currentSpawning = null; } } } if (currentState[0] == CellState.Pending) { newState = CellState.Active; } else if (!newState.HasValue) { currentState[1] = GetCellState(currentGrid, virtualX, virtualY - 1); // North currentState[2] = GetCellState(currentGrid, virtualX + 1, virtualY - 1); // NE currentState[3] = GetCellState(currentGrid, virtualX + 1, virtualY); // East currentState[4] = GetCellState(currentGrid, virtualX + 1, virtualY + 1); // SE currentState[5] = GetCellState(currentGrid, virtualX, virtualY + 1); // South currentState[6] = GetCellState(currentGrid, virtualX - 1, virtualY + 1); // SW currentState[7] = GetCellState(currentGrid, virtualX - 1, virtualY); // West currentState[8] = GetCellState(currentGrid, virtualX - 1, virtualY - 1); // NW var neighbourCount = currentState.Skip(1).Count(s => s.Collides()); // 2. Any live cell with two or three live neighbours lives on to the next generation. if (currentState[0].Collides() && neighbourCount >= 2 && neighbourCount <= 3) { newState = currentState[0]; } else if (!currentState[0].Collides() && neighbourCount == 3) { // 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. newState = CellState.Active; } else { // 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population. // 3. Any live cell with more than three live neighbours dies, as if by over-population. newState = CellState.Empty; } } if (newState.Value.Collides() && _boards.All(b => GetCellState(b, virtualX, virtualY).Collides())) { newState = CellState.Empty; } var actualX = virtualX % GRID_WIDTH; var band = (virtualX / GRID_WIDTH); var actualY = virtualY + (band * GRID_WIDTH); newGrid[actualX, actualY] = newState.Value; } } _boards.Enqueue(newGrid); _boards.Dequeue(); } public void Render(SpriteBatch spriteBatch, GameTime gameTime) { spriteBatch.Begin(); // Draw background //if (_beatTrigger.Triggering(gameTime)) //{ // _bg12 = !_bg12; //} var newBgColor = _bg12 ? _bg1 : _bg2; _graphicsDevice.Clear(newBgColor); // Draw pixel overlay var rotMat = Matrix.CreateRotationZ(MathHelper.ToRadians(45)); var rotRect = new Vector2[4]; var currentBoard = _boards.ElementAt(CURRENT_BOARD_INDEX); var boardOffset = new Vector2(0, 0); var yOffset = Sqrt(Pow(GRID_WIDTH, 2)/2) - 10; for (int x = 0; x < GRID_HEIGHT + yOffset; x++) { for (int y = 0; y < GRID_HEIGHT; y++) { Color c; switch (GetCellState(currentBoard, x, y)) { case CellState.Active: c = Color.Crimson; break; case CellState.Pending: c = Color.OrangeRed; break; case CellState.Player: c = Color.CornflowerBlue; break; case CellState.Bound: c = Color.CornflowerBlue; break; default: continue; } var targetO = new Vector2(_pixelsPerX * x, _pixelsPerY * y); var rotTranslation = new Vector2(GRID_WIDTH * _pixelsPerX, 0); var targetT = targetO - rotTranslation; var targetR = Vector2.Transform(targetT, rotMat); var targetN = targetR + rotTranslation + boardOffset; var tex = _textures[0]; spriteBatch.Draw(tex, targetN, new Rectangle(0,0, _pixelsPerX, _pixelsPerY), c, MathHelper.ToRadians(45), new Vector2(0, 0), Vector2.One, SpriteEffects.None, 1); } } spriteBatch.End(); } private CellState GetCellState(CellState[,] grid, int virtualX, int virtualY) { if (virtualX < 0 || virtualY < 0) { return CellState.Bound; } // Clip the top side if (virtualX + virtualY < GRID_WIDTH) { return CellState.Active; } // Clip the left side if (virtualY - virtualX == GRID_WIDTH) { return CellState.Bound; } // Clip the right side if (virtualX - virtualY == GRID_WIDTH + 1) { return CellState.Bound; } // clip the bottom if (virtualX + virtualY >= _virtualBoardHeight) { return CellState.Bound; } var band = virtualX / GRID_WIDTH; var actualX = virtualX % GRID_WIDTH; var actualY = band * GRID_WIDTH + virtualY; return grid[actualX, actualY]; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A pair of schedulers that together support concurrent (reader) / exclusive (writer) // task scheduling. Using just the exclusive scheduler can be used to simulate a serial // processing queue, and using just the concurrent scheduler with a specified // MaximumConcurrentlyLevel can be used to achieve a MaxDegreeOfParallelism across // a bunch of tasks, parallel loops, dataflow blocks, etc. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; using System.Security.Permissions; namespace System.Threading.Tasks { /// <summary> /// Provides concurrent and exclusive task schedulers that coordinate to execute /// tasks while ensuring that concurrent tasks may run concurrently and exclusive tasks never do. /// </summary> [HostProtection(Synchronization = true, ExternalThreading = true)] [DebuggerDisplay("Concurrent={ConcurrentTaskCountForDebugger}, Exclusive={ExclusiveTaskCountForDebugger}, Mode={ModeForDebugger}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveSchedulerPair.DebugView))] public class ConcurrentExclusiveSchedulerPair { /// <summary>A dictionary mapping thread ID to a processing mode to denote what kinds of tasks are currently being processed on this thread.</summary> private readonly ConcurrentDictionary<int, ProcessingMode> m_threadProcessingMapping = new ConcurrentDictionary<int, ProcessingMode>(); /// <summary>The scheduler used to queue and execute "concurrent" tasks that may run concurrently with other concurrent tasks.</summary> private readonly ConcurrentExclusiveTaskScheduler m_concurrentTaskScheduler; /// <summary>The scheduler used to queue and execute "exclusive" tasks that must run exclusively while no other tasks for this pair are running.</summary> private readonly ConcurrentExclusiveTaskScheduler m_exclusiveTaskScheduler; /// <summary>The underlying task scheduler to which all work should be scheduled.</summary> private readonly TaskScheduler m_underlyingTaskScheduler; /// <summary> /// The maximum number of tasks allowed to run concurrently. This only applies to concurrent tasks, /// since exlusive tasks are inherently limited to 1. /// </summary> private readonly int m_maxConcurrencyLevel; /// <summary>The maximum number of tasks we can process before recyling our runner tasks.</summary> private readonly int m_maxItemsPerTask; /// <summary> /// If positive, it represents the number of concurrently running concurrent tasks. /// If negative, it means an exclusive task has been scheduled. /// If 0, nothing has been scheduled. /// </summary> private int m_processingCount; /// <summary>Completion state for a task representing the completion of this pair.</summary> /// <remarks>Lazily-initialized only if the scheduler pair is shutting down or if the Completion is requested.</remarks> private CompletionState m_completionState; /// <summary>A constant value used to signal unlimited processing.</summary> private const int UNLIMITED_PROCESSING = -1; /// <summary>Constant used for m_processingCount to indicate that an exclusive task is being processed.</summary> private const int EXCLUSIVE_PROCESSING_SENTINEL = -1; /// <summary>Default MaxItemsPerTask to use for processing if none is specified.</summary> private const int DEFAULT_MAXITEMSPERTASK = UNLIMITED_PROCESSING; /// <summary>Default MaxConcurrencyLevel is the processor count if not otherwise specified.</summary> private static Int32 DefaultMaxConcurrencyLevel { get { return Environment.ProcessorCount; } } /// <summary>Gets the sync obj used to protect all state on this instance.</summary> private object ValueLock { get { return m_threadProcessingMapping; } } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair. /// </summary> public ConcurrentExclusiveSchedulerPair() : this(TaskScheduler.Default, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler) : this(taskScheduler, DefaultMaxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum concurrency level. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel) : this(taskScheduler, maxConcurrencyLevel, DEFAULT_MAXITEMSPERTASK) { } /// <summary> /// Initializes the ConcurrentExclusiveSchedulerPair to target the specified scheduler with a maximum /// concurrency level and a maximum number of scheduled tasks that may be processed as a unit. /// </summary> /// <param name="taskScheduler">The target scheduler on which this pair should execute.</param> /// <param name="maxConcurrencyLevel">The maximum number of tasks to run concurrently.</param> /// <param name="maxItemsPerTask">The maximum number of tasks to process for each underlying scheduled task used by the pair.</param> public ConcurrentExclusiveSchedulerPair(TaskScheduler taskScheduler, int maxConcurrencyLevel, int maxItemsPerTask) { // Validate arguments if (taskScheduler == null) throw new ArgumentNullException(nameof(taskScheduler)); if (maxConcurrencyLevel == 0 || maxConcurrencyLevel < -1) throw new ArgumentOutOfRangeException(nameof(maxConcurrencyLevel)); if (maxItemsPerTask == 0 || maxItemsPerTask < -1) throw new ArgumentOutOfRangeException(nameof(maxItemsPerTask)); Contract.EndContractBlock(); // Store configuration m_underlyingTaskScheduler = taskScheduler; m_maxConcurrencyLevel = maxConcurrencyLevel; m_maxItemsPerTask = maxItemsPerTask; // Downgrade to the underlying scheduler's max degree of parallelism if it's lower than the user-supplied level int mcl = taskScheduler.MaximumConcurrencyLevel; if (mcl > 0 && mcl < m_maxConcurrencyLevel) m_maxConcurrencyLevel = mcl; // Treat UNLIMITED_PROCESSING/-1 for both MCL and MIPT as the biggest possible value so that we don't // have to special case UNLIMITED_PROCESSING later on in processing. if (m_maxConcurrencyLevel == UNLIMITED_PROCESSING) m_maxConcurrencyLevel = Int32.MaxValue; if (m_maxItemsPerTask == UNLIMITED_PROCESSING) m_maxItemsPerTask = Int32.MaxValue; // Create the concurrent/exclusive schedulers for this pair m_exclusiveTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, 1, ProcessingMode.ProcessingExclusiveTask); m_concurrentTaskScheduler = new ConcurrentExclusiveTaskScheduler(this, m_maxConcurrencyLevel, ProcessingMode.ProcessingConcurrentTasks); } /// <summary>Informs the scheduler pair that it should not accept any more tasks.</summary> /// <remarks> /// Calling <see cref="Complete"/> is optional, and it's only necessary if the <see cref="Completion"/> /// will be relied on for notification of all processing being completed. /// </remarks> public void Complete() { lock (ValueLock) { if (!CompletionRequested) { RequestCompletion(); CleanupStateIfCompletingAndQuiesced(); } } } /// <summary>Gets a <see cref="System.Threading.Tasks.Task"/> that will complete when the scheduler has completed processing.</summary> public Task Completion { // ValueLock not needed, but it's ok if it's held get { return EnsureCompletionStateInitialized().Task; } } /// <summary>Gets the lazily-initialized completion state.</summary> private CompletionState EnsureCompletionStateInitialized() { // ValueLock not needed, but it's ok if it's held return LazyInitializer.EnsureInitialized(ref m_completionState, () => new CompletionState()); } /// <summary>Gets whether completion has been requested.</summary> private bool CompletionRequested { // ValueLock not needed, but it's ok if it's held get { return m_completionState != null && Volatile.Read(ref m_completionState.m_completionRequested); } } /// <summary>Sets that completion has been requested.</summary> private void RequestCompletion() { ContractAssertMonitorStatus(ValueLock, held: true); EnsureCompletionStateInitialized().m_completionRequested = true; } /// <summary> /// Cleans up state if and only if there's no processing currently happening /// and no more to be done later. /// </summary> private void CleanupStateIfCompletingAndQuiesced() { ContractAssertMonitorStatus(ValueLock, held: true); if (ReadyToComplete) CompleteTaskAsync(); } /// <summary>Gets whether the pair is ready to complete.</summary> private bool ReadyToComplete { get { ContractAssertMonitorStatus(ValueLock, held: true); // We can only complete if completion has been requested and no processing is currently happening. if (!CompletionRequested || m_processingCount != 0) return false; // Now, only allow shutdown if an exception occurred or if there are no more tasks to process. var cs = EnsureCompletionStateInitialized(); return (cs.m_exceptions != null && cs.m_exceptions.Count > 0) || (m_concurrentTaskScheduler.m_tasks.IsEmpty && m_exclusiveTaskScheduler.m_tasks.IsEmpty); } } /// <summary>Completes the completion task asynchronously.</summary> private void CompleteTaskAsync() { Contract.Requires(ReadyToComplete, "The block must be ready to complete to be here."); ContractAssertMonitorStatus(ValueLock, held: true); // Ensure we only try to complete once, then schedule completion // in order to escape held locks and the caller's context var cs = EnsureCompletionStateInitialized(); if (!cs.m_completionQueued) { cs.m_completionQueued = true; ThreadPool.QueueUserWorkItem(state => { var localCs = (CompletionState)state; // don't use 'cs', as it'll force a closure Contract.Assert(!localCs.Task.IsCompleted, "Completion should only happen once."); var exceptions = localCs.m_exceptions; bool success = (exceptions != null && exceptions.Count > 0) ? localCs.TrySetException(exceptions) : localCs.TrySetResult(default(VoidTaskResult)); Contract.Assert(success, "Expected to complete completion task."); }, cs); } } /// <summary>Initiatites scheduler shutdown due to a worker task faulting..</summary> /// <param name="faultedTask">The faulted worker task that's initiating the shutdown.</param> private void FaultWithTask(Task faultedTask) { Contract.Requires(faultedTask != null && faultedTask.IsFaulted && faultedTask.Exception.InnerExceptions.Count > 0, "Needs a task in the faulted state and thus with exceptions."); ContractAssertMonitorStatus(ValueLock, held: true); // Store the faulted task's exceptions var cs = EnsureCompletionStateInitialized(); if (cs.m_exceptions == null) cs.m_exceptions = new List<Exception>(); cs.m_exceptions.AddRange(faultedTask.Exception.InnerExceptions); // Now that we're doomed, request completion RequestCompletion(); } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that may run concurrently with other tasks on this pair. /// </summary> public TaskScheduler ConcurrentScheduler { get { return m_concurrentTaskScheduler; } } /// <summary> /// Gets a TaskScheduler that can be used to schedule tasks to this pair /// that must run exclusively with regards to other tasks on this pair. /// </summary> public TaskScheduler ExclusiveScheduler { get { return m_exclusiveTaskScheduler; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ConcurrentTaskCountForDebugger { get { return m_concurrentTaskScheduler.m_tasks.Count; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> /// <remarks>This does not take the necessary lock, as it's only called from under the debugger.</remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int ExclusiveTaskCountForDebugger { get { return m_exclusiveTaskScheduler.m_tasks.Count; } } /// <summary>Notifies the pair that new work has arrived to be processed.</summary> /// <param name="fairly">Whether tasks should be scheduled fairly with regards to other tasks.</param> /// <remarks>Must only be called while holding the lock.</remarks> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals")] [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ProcessAsyncIfNecessary(bool fairly = false) { ContractAssertMonitorStatus(ValueLock, held: true); // If the current processing count is >= 0, we can potentially launch further processing. if (m_processingCount >= 0) { // We snap whether there are any exclusive tasks or concurrent tasks waiting. // (We grab the concurrent count below only once we know we need it.) // With processing happening concurrent to this operation, this data may // immediately be out of date, but it can only go from non-empty // to empty and not the other way around. As such, this is safe, // as worst case is we'll schedule an extra task when we didn't // otherwise need to, and we'll just eat its overhead. bool exclusiveTasksAreWaiting = !m_exclusiveTaskScheduler.m_tasks.IsEmpty; // If there's no processing currently happening but there are waiting exclusive tasks, // let's start processing those exclusive tasks. Task processingTask = null; if (m_processingCount == 0 && exclusiveTasksAreWaiting) { // Launch exclusive task processing m_processingCount = EXCLUSIVE_PROCESSING_SENTINEL; // -1 try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessExclusiveTasks(), this, default(CancellationToken), GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // When we call Start, if the underlying scheduler throws in QueueTask, TPL will fault the task and rethrow // the exception. To deal with that, we need a reference to the task object, so that we can observe its exception. // Hence, we separate creation and starting, so that we can store a reference to the task before we attempt QueueTask. } catch { m_processingCount = 0; FaultWithTask(processingTask); } } // If there are no waiting exclusive tasks, there are concurrent tasks, and we haven't reached our maximum // concurrency level for processing, let's start processing more concurrent tasks. else { int concurrentTasksWaitingCount = m_concurrentTaskScheduler.m_tasks.Count; if (concurrentTasksWaitingCount > 0 && !exclusiveTasksAreWaiting && m_processingCount < m_maxConcurrencyLevel) { // Launch concurrent task processing, up to the allowed limit for (int i = 0; i < concurrentTasksWaitingCount && m_processingCount < m_maxConcurrencyLevel; ++i) { ++m_processingCount; try { processingTask = new Task(thisPair => ((ConcurrentExclusiveSchedulerPair)thisPair).ProcessConcurrentTasks(), this, default(CancellationToken), GetCreationOptionsForTask(fairly)); processingTask.Start(m_underlyingTaskScheduler); // See above logic for why we use new + Start rather than StartNew } catch { --m_processingCount; FaultWithTask(processingTask); } } } } // Check to see if all tasks have completed and if completion has been requested. CleanupStateIfCompletingAndQuiesced(); } else Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing count must be the sentinel if it's not >= 0."); } /// <summary> /// Processes exclusive tasks serially until either there are no more to process /// or we've reached our user-specified maximum limit. /// </summary> private void ProcessExclusiveTasks() { Contract.Requires(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "Processing exclusive tasks requires being in exclusive mode."); Contract.Requires(!m_exclusiveTaskScheduler.m_tasks.IsEmpty, "Processing exclusive tasks requires tasks to be processed."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing exclusive tasks on the current thread Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingExclusiveTask; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available exclusive task. If we can't find one, bail. Task exclusiveTask; if (!m_exclusiveTaskScheduler.m_tasks.TryDequeue(out exclusiveTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!exclusiveTask.IsFaulted) m_exclusiveTaskScheduler.ExecuteTask(exclusiveTask); } } finally { // We're no longer processing exclusive tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); Contract.Assert(currentMode == ProcessingMode.ProcessingExclusiveTask, "Somehow we ended up escaping exclusive mode."); lock (ValueLock) { // When this task was launched, we tracked it by setting m_processingCount to WRITER_IN_PROGRESS. // now reset it to 0. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Contract.Assert(m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL, "The processing mode should not have deviated from exclusive."); m_processingCount = 0; ProcessAsyncIfNecessary(true); } } } /// <summary> /// Processes concurrent tasks serially until either there are no more to process, /// we've reached our user-specified maximum limit, or exclusive tasks have arrived. /// </summary> private void ProcessConcurrentTasks() { Contract.Requires(m_processingCount > 0, "Processing concurrent tasks requires us to be in concurrent mode."); ContractAssertMonitorStatus(ValueLock, held: false); try { // Note that we're processing concurrent tasks on the current thread Contract.Assert(!m_threadProcessingMapping.ContainsKey(Thread.CurrentThread.ManagedThreadId), "This thread should not yet be involved in this pair's processing."); m_threadProcessingMapping[Thread.CurrentThread.ManagedThreadId] = ProcessingMode.ProcessingConcurrentTasks; // Process up to the maximum number of items per task allowed for (int i = 0; i < m_maxItemsPerTask; i++) { // Get the next available concurrent task. If we can't find one, bail. Task concurrentTask; if (!m_concurrentTaskScheduler.m_tasks.TryDequeue(out concurrentTask)) break; // Execute the task. If the scheduler was previously faulted, // this task could have been faulted when it was queued; ignore such tasks. if (!concurrentTask.IsFaulted) m_concurrentTaskScheduler.ExecuteTask(concurrentTask); // Now check to see if exclusive tasks have arrived; if any have, they take priority // so we'll bail out here. Note that we could have checked this condition // in the for loop's condition, but that could lead to extra overhead // in the case where a concurrent task arrives, this task is launched, and then // before entering the loop an exclusive task arrives. If we didn't execute at // least one task, we would have spent all of the overhead to launch a // task but with none of the benefit. There's of course also an inherent // race condition here with regards to exclusive tasks arriving, and we're ok with // executing one more concurrent task than we should before giving priority to exclusive tasks. if (!m_exclusiveTaskScheduler.m_tasks.IsEmpty) break; } } finally { // We're no longer processing concurrent tasks on the current thread ProcessingMode currentMode; m_threadProcessingMapping.TryRemove(Thread.CurrentThread.ManagedThreadId, out currentMode); Contract.Assert(currentMode == ProcessingMode.ProcessingConcurrentTasks, "Somehow we ended up escaping concurrent mode."); lock (ValueLock) { // When this task was launched, we tracked it with a positive processing count; // decrement that count. Then check to see whether there's more processing to be done. // There might be more concurrent tasks available, for example, if concurrent tasks arrived // after we exited the loop, or if we exited the loop while concurrent tasks were still // available but we hit our maxItemsPerTask limit. Contract.Assert(m_processingCount > 0, "The procesing mode should not have deviated from concurrent."); if (m_processingCount > 0) --m_processingCount; ProcessAsyncIfNecessary(true); } } } #if PRENET45 /// <summary> /// Type used with TaskCompletionSource(Of TResult) as the TResult /// to ensure that the resulting task can't be upcast to something /// that in the future could lead to compat problems. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] [DebuggerNonUserCode] private struct VoidTaskResult { } #endif /// <summary> /// Holder for lazily-initialized state about the completion of a scheduler pair. /// Completion is only triggered either by rare exceptional conditions or by /// the user calling Complete, and as such we only lazily initialize this /// state in one of those conditions or if the user explicitly asks for /// the Completion. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] private sealed class CompletionState : TaskCompletionSource<VoidTaskResult> { /// <summary>Whether the scheduler has had completion requested.</summary> /// <remarks>This variable is not volatile, so to gurantee safe reading reads, Volatile.Read is used in TryExecuteTaskInline.</remarks> internal bool m_completionRequested; /// <summary>Whether completion processing has been queued.</summary> internal bool m_completionQueued; /// <summary>Unrecoverable exceptions incurred while processing.</summary> internal List<Exception> m_exceptions; } /// <summary> /// A scheduler shim used to queue tasks to the pair and execute those tasks on request of the pair. /// </summary> [DebuggerDisplay("Count={CountForDebugger}, MaxConcurrencyLevel={m_maxConcurrencyLevel}, Id={Id}")] [DebuggerTypeProxy(typeof(ConcurrentExclusiveTaskScheduler.DebugView))] private sealed class ConcurrentExclusiveTaskScheduler : TaskScheduler { /// <summary>Cached delegate for invoking TryExecuteTaskShim.</summary> private static readonly Func<object, bool> s_tryExecuteTaskShim = new Func<object, bool>(TryExecuteTaskShim); /// <summary>The parent pair.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>The maximum concurrency level for the scheduler.</summary> private readonly int m_maxConcurrencyLevel; /// <summary>The processing mode of this scheduler, exclusive or concurrent.</summary> private readonly ProcessingMode m_processingMode; /// <summary>Gets the queue of tasks for this scheduler.</summary> internal readonly IProducerConsumerQueue<Task> m_tasks; /// <summary>Initializes the scheduler.</summary> /// <param name="pair">The parent pair.</param> /// <param name="maxConcurrencyLevel">The maximum degree of concurrency this scheduler may use.</param> /// <param name="processingMode">The processing mode of this scheduler.</param> internal ConcurrentExclusiveTaskScheduler(ConcurrentExclusiveSchedulerPair pair, int maxConcurrencyLevel, ProcessingMode processingMode) { Contract.Requires(pair != null, "Scheduler must be associated with a valid pair."); Contract.Requires(processingMode == ProcessingMode.ProcessingConcurrentTasks || processingMode == ProcessingMode.ProcessingExclusiveTask, "Scheduler must be for concurrent or exclusive processing."); Contract.Requires( (processingMode == ProcessingMode.ProcessingConcurrentTasks && (maxConcurrencyLevel >= 1 || maxConcurrencyLevel == UNLIMITED_PROCESSING)) || (processingMode == ProcessingMode.ProcessingExclusiveTask && maxConcurrencyLevel == 1), "If we're in concurrent mode, our concurrency level should be positive or unlimited. If exclusive, it should be 1."); m_pair = pair; m_maxConcurrencyLevel = maxConcurrencyLevel; m_processingMode = processingMode; m_tasks = (processingMode == ProcessingMode.ProcessingExclusiveTask) ? (IProducerConsumerQueue<Task>)new SingleProducerSingleConsumerQueue<Task>() : (IProducerConsumerQueue<Task>)new MultiProducerMultiConsumerQueue<Task>(); } /// <summary>Gets the maximum concurrency level this scheduler is able to support.</summary> public override int MaximumConcurrencyLevel { get { return m_maxConcurrencyLevel; } } /// <summary>Queues a task to the scheduler.</summary> /// <param name="task">The task to be queued.</param> [SecurityCritical] protected internal override void QueueTask(Task task) { Contract.Assert(task != null, "Infrastructure should have provided a non-null task."); lock (m_pair.ValueLock) { // If the scheduler has already had completion requested, no new work is allowed to be scheduled if (m_pair.CompletionRequested) throw new InvalidOperationException(GetType().Name); // Queue the task, and then let the pair know that more work is now available to be scheduled m_tasks.Enqueue(task); m_pair.ProcessAsyncIfNecessary(); } } /// <summary>Executes a task on this scheduler.</summary> /// <param name="task">The task to be executed.</param> [SecuritySafeCritical] internal void ExecuteTask(Task task) { Contract.Assert(task != null, "Infrastructure should have provided a non-null task."); base.TryExecuteTask(task); } /// <summary>Tries to execute the task synchronously on this scheduler.</summary> /// <param name="task">The task to execute.</param> /// <param name="taskWasPreviouslyQueued">Whether the task was previously queued to the scheduler.</param> /// <returns>true if the task could be executed; otherwise, false.</returns> [SecurityCritical] protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { Contract.Assert(task != null, "Infrastructure should have provided a non-null task."); // If the scheduler has had completion requested, no new work is allowed to be scheduled. // A non-locked read on m_completionRequested (in CompletionRequested) is acceptable here because: // a) we don't need to be exact... a Complete call could come in later in the function anyway // b) this is only a fast path escape hatch. To actually inline the task, // we need to be inside of an already executing task, and in such a case, // while completion may have been requested, we can't have shutdown yet. if (!taskWasPreviouslyQueued && m_pair.CompletionRequested) return false; // We know the implementation of the default scheduler and how it will behave. // As it's the most common underlying scheduler, we optimize for it. bool isDefaultScheduler = m_pair.m_underlyingTaskScheduler == TaskScheduler.Default; // If we're targeting the default scheduler and taskWasPreviouslyQueued is true, // we know that the default scheduler will only allow it to be inlined // if we're on a thread pool thread (but it won't always allow it in that case, // since it'll only allow inlining if it can find the task in the local queue). // As such, if we're not on a thread pool thread, we know for sure the // task won't be inlined, so let's not even try. if (isDefaultScheduler && taskWasPreviouslyQueued && !Thread.CurrentThread.IsThreadPoolThread) { return false; } else { // If a task is already running on this thread, allow inline execution to proceed. // If there's already a task from this scheduler running on the current thread, we know it's safe // to run this task, in effect temporarily taking that task's count allocation. ProcessingMode currentThreadMode; if (m_pair.m_threadProcessingMapping.TryGetValue(Thread.CurrentThread.ManagedThreadId, out currentThreadMode) && currentThreadMode == m_processingMode) { // If we're targeting the default scheduler and taskWasPreviouslyQueued is false, // we know the default scheduler will allow it, so we can just execute it here. // Otherwise, delegate to the target scheduler's inlining. return (isDefaultScheduler && !taskWasPreviouslyQueued) ? TryExecuteTask(task) : TryExecuteTaskInlineOnTargetScheduler(task); } } // We're not in the context of a task already executing on this scheduler. Bail. return false; } /// <summary> /// Implements a reasonable approximation for TryExecuteTaskInline on the underlying scheduler, /// which we can't call directly on the underlying scheduler. /// </summary> /// <param name="task">The task to execute inline if possible.</param> /// <returns>true if the task was inlined successfully; otherwise, false.</returns> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "ignored")] private bool TryExecuteTaskInlineOnTargetScheduler(Task task) { // We'd like to simply call TryExecuteTaskInline here, but we can't. // As there's no built-in API for this, a workaround is to create a new task that, // when executed, will simply call TryExecuteTask to run the real task, and then // we run our new shim task synchronously on the target scheduler. If all goes well, // our synchronous invocation will succeed in running the shim task on the current thread, // which will in turn run the real task on the current thread. If the scheduler // doesn't allow that execution, RunSynchronously will block until the underlying scheduler // is able to invoke the task, which might account for an additional but unavoidable delay. // Once it's done, we can return whether the task executed by returning the // shim task's Result, which is in turn the result of TryExecuteTask. var t = new Task<bool>(s_tryExecuteTaskShim, Tuple.Create(this, task)); try { t.RunSynchronously(m_pair.m_underlyingTaskScheduler); return t.Result; } catch { Contract.Assert(t.IsFaulted, "Task should be faulted due to the scheduler faulting it and throwing the exception."); var ignored = t.Exception; throw; } finally { t.Dispose(); } } /// <summary>Shim used to invoke this.TryExecuteTask(task).</summary> /// <param name="state">A tuple of the ConcurrentExclusiveTaskScheduler and the task to execute.</param> /// <returns>true if the task was successfully inlined; otherwise, false.</returns> /// <remarks> /// This method is separated out not because of performance reasons but so that /// the SecuritySafeCritical attribute may be employed. /// </remarks> [SecuritySafeCritical] private static bool TryExecuteTaskShim(object state) { var tuple = (Tuple<ConcurrentExclusiveTaskScheduler, Task>)state; return tuple.Item1.TryExecuteTask(tuple.Item2); } /// <summary>Gets for debugging purposes the tasks scheduled to this scheduler.</summary> /// <returns>An enumerable of the tasks queued.</returns> [SecurityCritical] protected override IEnumerable<Task> GetScheduledTasks() { return m_tasks; } /// <summary>Gets the number of tasks queued to this scheduler.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private int CountForDebugger { get { return m_tasks.Count; } } /// <summary>Provides a debug view for ConcurrentExclusiveTaskScheduler.</summary> private sealed class DebugView { /// <summary>The scheduler being debugged.</summary> private readonly ConcurrentExclusiveTaskScheduler m_taskScheduler; /// <summary>Initializes the debug view.</summary> /// <param name="scheduler">The scheduler being debugged.</param> public DebugView(ConcurrentExclusiveTaskScheduler scheduler) { Contract.Requires(scheduler != null, "Need a scheduler with which to construct the debug view."); m_taskScheduler = scheduler; } /// <summary>Gets this pair's maximum allowed concurrency level.</summary> public int MaximumConcurrencyLevel { get { return m_taskScheduler.m_maxConcurrencyLevel; } } /// <summary>Gets the tasks scheduled to this scheduler.</summary> public IEnumerable<Task> ScheduledTasks { get { return m_taskScheduler.m_tasks; } } /// <summary>Gets the scheduler pair with which this scheduler is associated.</summary> public ConcurrentExclusiveSchedulerPair SchedulerPair { get { return m_taskScheduler.m_pair; } } } } /// <summary>Provides a debug view for ConcurrentExclusiveSchedulerPair.</summary> private sealed class DebugView { /// <summary>The pair being debugged.</summary> private readonly ConcurrentExclusiveSchedulerPair m_pair; /// <summary>Initializes the debug view.</summary> /// <param name="pair">The pair being debugged.</param> public DebugView(ConcurrentExclusiveSchedulerPair pair) { Contract.Requires(pair != null, "Need a pair with which to construct the debug view."); m_pair = pair; } /// <summary>Gets a representation of the execution state of the pair.</summary> public ProcessingMode Mode { get { return m_pair.ModeForDebugger; } } /// <summary>Gets the number of tasks waiting to run exclusively.</summary> public IEnumerable<Task> ScheduledExclusive { get { return m_pair.m_exclusiveTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks waiting to run concurrently.</summary> public IEnumerable<Task> ScheduledConcurrent { get { return m_pair.m_concurrentTaskScheduler.m_tasks; } } /// <summary>Gets the number of tasks currently being executed.</summary> public int CurrentlyExecutingTaskCount { get { return (m_pair.m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) ? 1 : m_pair.m_processingCount; } } /// <summary>Gets the underlying task scheduler that actually executes the tasks.</summary> public TaskScheduler TargetScheduler { get { return m_pair.m_underlyingTaskScheduler; } } } /// <summary>Gets an enumeration for debugging that represents the current state of the scheduler pair.</summary> /// <remarks>This is only for debugging. It does not take the necessary locks to be useful for runtime usage.</remarks> private ProcessingMode ModeForDebugger { get { // If our completion task is done, so are we. if (m_completionState != null && m_completionState.Task.IsCompleted) return ProcessingMode.Completed; // Otherwise, summarize our current state. var mode = ProcessingMode.NotCurrentlyProcessing; if (m_processingCount == EXCLUSIVE_PROCESSING_SENTINEL) mode |= ProcessingMode.ProcessingExclusiveTask; if (m_processingCount >= 1) mode |= ProcessingMode.ProcessingConcurrentTasks; if (CompletionRequested) mode |= ProcessingMode.Completing; return mode; } } /// <summary>Asserts that a given synchronization object is either held or not held.</summary> /// <param name="syncObj">The monitor to check.</param> /// <param name="held">Whether we want to assert that it's currently held or not held.</param> [Conditional("DEBUG")] internal static void ContractAssertMonitorStatus(object syncObj, bool held) { Contract.Requires(syncObj != null, "The monitor object to check must be provided."); #if PRENET45 #if DEBUG // This check is expensive, // which is why it's protected by ShouldCheckMonitorStatus and controlled by an environment variable DEBUGSYNC. if (ShouldCheckMonitorStatus) { bool exceptionThrown; try { Monitor.Pulse(syncObj); // throws a SynchronizationLockException if the monitor isn't held by this thread exceptionThrown = false; } catch (SynchronizationLockException) { exceptionThrown = true; } Contract.Assert(held == !exceptionThrown, "The locking scheme was not correctly followed."); } #endif #else Contract.Assert(Monitor.IsEntered(syncObj) == held, "The locking scheme was not correctly followed."); #endif } /// <summary>Gets the options to use for tasks.</summary> /// <param name="isReplacementReplica">If this task is being created to replace another.</param> /// <remarks> /// These options should be used for all tasks that have the potential to run user code or /// that are repeatedly spawned and thus need a modicum of fair treatment. /// </remarks> /// <returns>The options to use.</returns> internal static TaskCreationOptions GetCreationOptionsForTask(bool isReplacementReplica = false) { TaskCreationOptions options = #if PRENET45 TaskCreationOptions.None; #else TaskCreationOptions.DenyChildAttach; #endif if (isReplacementReplica) options |= TaskCreationOptions.PreferFairness; return options; } /// <summary>Provides an enumeration that represents the current state of the scheduler pair.</summary> [Flags] private enum ProcessingMode : byte { /// <summary>The scheduler pair is currently dormant, with no work scheduled.</summary> NotCurrentlyProcessing = 0x0, /// <summary>The scheduler pair has queued processing for exclusive tasks.</summary> ProcessingExclusiveTask = 0x1, /// <summary>The scheduler pair has queued processing for concurrent tasks.</summary> ProcessingConcurrentTasks = 0x2, /// <summary>Completion has been requested.</summary> Completing = 0x4, /// <summary>The scheduler pair is finished processing.</summary> Completed = 0x8 } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Reflection; using System.Diagnostics; using System.Collections.Generic; using System.Collections.Concurrent; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.Assemblies; using System.Reflection.Runtime.CustomAttributes; using Internal.LowLevelLinq; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; using Internal.Metadata.NativeFormat; using CharSet = System.Runtime.InteropServices.CharSet; using LayoutKind = System.Runtime.InteropServices.LayoutKind; using StructLayoutAttribute = System.Runtime.InteropServices.StructLayoutAttribute; namespace System.Reflection.Runtime.TypeInfos { // // TypeInfos that represent type definitions (i.e. Foo or Foo<>, but not Foo<int> or arrays/pointers/byrefs.) // // internal sealed partial class RuntimeNamedTypeInfo : RuntimeTypeInfo, IEquatable<RuntimeNamedTypeInfo> { private RuntimeNamedTypeInfo(MetadataReader reader, TypeDefinitionHandle typeDefinitionHandle, RuntimeTypeHandle typeHandle) { _reader = reader; _typeDefinitionHandle = typeDefinitionHandle; _typeDefinition = _typeDefinitionHandle.GetTypeDefinition(reader); _typeHandle = typeHandle; } public sealed override Assembly Assembly { get { // If an assembly is split across multiple metadata blobs then the defining scope may // not be the canonical scope representing the assembly. We need to look up the assembly // by name to ensure we get the right one. ScopeDefinitionHandle scopeDefinitionHandle = NamespaceChain.DefiningScope; RuntimeAssemblyName runtimeAssemblyName = scopeDefinitionHandle.ToRuntimeAssemblyName(_reader); return RuntimeAssembly.GetRuntimeAssembly(runtimeAssemblyName); } } public sealed override bool ContainsGenericParameters { get { return IsGenericTypeDefinition; } } public sealed override IEnumerable<CustomAttributeData> CustomAttributes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_CustomAttributes(this); #endif IEnumerable<CustomAttributeData> customAttributes = RuntimeCustomAttributeData.GetCustomAttributes(_reader, _typeDefinition.CustomAttributes); foreach (CustomAttributeData cad in customAttributes) yield return cad; foreach (CustomAttributeData cad in ReflectionCoreExecution.ExecutionEnvironment.GetPsuedoCustomAttributes(_reader, _typeDefinitionHandle)) { yield return cad; } } } public sealed override IEnumerable<TypeInfo> DeclaredNestedTypes { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_DeclaredNestedTypes(this); #endif foreach (TypeDefinitionHandle nestedTypeHandle in _typeDefinition.NestedTypes) { yield return nestedTypeHandle.GetNamedType(_reader); } } } public bool Equals(RuntimeNamedTypeInfo other) { // RuntimeTypeInfo.Equals(object) is the one that encapsulates our unification strategy so defer to him. object otherAsObject = other; return base.Equals(otherAsObject); } public sealed override Guid GUID { get { // // Look for a [Guid] attribute. If found, return that. // foreach (CustomAttributeHandle cah in _typeDefinition.CustomAttributes) { // We can't reference the GuidAttribute class directly as we don't have an official dependency on System.Runtime.InteropServices. // Following age-old CLR tradition, we search for the custom attribute using a name-based search. Since this makes it harder // to be sure we won't run into custom attribute constructors that comply with the GuidAttribute(String) signature, // we'll check that it does and silently skip the CA if it doesn't match the expected pattern. if (cah.IsCustomAttributeOfType(_reader, "System.Runtime.InteropServices", "GuidAttribute")) { CustomAttribute ca = cah.GetCustomAttribute(_reader); IEnumerator<FixedArgumentHandle> fahEnumerator = ca.FixedArguments.GetEnumerator(); if (!fahEnumerator.MoveNext()) continue; FixedArgumentHandle guidStringArgumentHandle = fahEnumerator.Current; if (fahEnumerator.MoveNext()) continue; FixedArgument guidStringArgument = guidStringArgumentHandle.GetFixedArgument(_reader); String guidString = guidStringArgument.Value.ParseConstantValue(_reader) as String; if (guidString == null) continue; return new Guid(guidString); } } // // If we got here, there was no [Guid] attribute. // // Ideally, we'd now compute the same GUID the desktop returns - however, that algorithm is complex and has questionable dependencies // (in particular, the GUID changes if the language compilers ever change the way it emits metadata tokens into certain unordered lists. // We don't even retain that order across the Project N toolchain.) // // For now, this is a compromise that satisfies our app-compat goals. We ensure that each unique Type receives a different GUID (at least one app // uses the GUID as a dictionary key to look up types.) It will not be the same GUID on multiple runs of the app but so far, there's // no evidence that's needed. // return s_namedTypeToGuidTable.GetOrAdd(this).Item1; } } public sealed override bool IsGenericTypeDefinition { get { return _typeDefinition.GenericParameters.GetEnumerator().MoveNext(); } } public sealed override string Namespace { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_Namespace(this); #endif return EscapeIdentifier(NamespaceChain.NameSpace); } } public sealed override string FullName { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.TypeInfo_FullName(this); #endif Debug.Assert(!IsConstructedGenericType); Debug.Assert(!IsGenericParameter); Debug.Assert(!HasElementType); string name = Name; Type declaringType = this.DeclaringType; if (declaringType != null) { string declaringTypeFullName = declaringType.FullName; return declaringTypeFullName + "+" + name; } string ns = Namespace; if (ns == null) return name; return ns + "." + name; } } public sealed override Type GetGenericTypeDefinition() { if (_typeDefinition.GenericParameters.GetEnumerator().MoveNext()) return this.AsType(); return base.GetGenericTypeDefinition(); } public sealed override StructLayoutAttribute StructLayoutAttribute { get { const int DefaultPackingSize = 8; // Note: CoreClr checks HasElementType and IsGenericParameter in addition to IsInterface but those properties cannot be true here as this // RuntimeTypeInfo subclass is solely for TypeDef types.) if (IsInterface) return null; TypeAttributes attributes = Attributes; LayoutKind layoutKind; switch (attributes & TypeAttributes.LayoutMask) { case TypeAttributes.ExplicitLayout: layoutKind = LayoutKind.Explicit; break; case TypeAttributes.AutoLayout: layoutKind = LayoutKind.Auto; break; case TypeAttributes.SequentialLayout: layoutKind = LayoutKind.Sequential; break; default: layoutKind = LayoutKind.Auto; break; } CharSet charSet; switch (attributes & TypeAttributes.StringFormatMask) { case TypeAttributes.AnsiClass: charSet = CharSet.Ansi; break; case TypeAttributes.AutoClass: charSet = CharSet.Auto; break; case TypeAttributes.UnicodeClass: charSet = CharSet.Unicode; break; default: charSet = CharSet.None; break; } int pack = _typeDefinition.PackingSize; int size = unchecked((int)(_typeDefinition.Size)); // Metadata parameter checking should not have allowed 0 for packing size. // The runtime later converts a packing size of 0 to 8 so do the same here // because it's more useful from a user perspective. if (pack == 0) pack = DefaultPackingSize; return new StructLayoutAttribute(layoutKind) { CharSet = charSet, Pack = pack, Size = size, }; } } public sealed override string ToString() { StringBuilder sb = null; foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { if (sb == null) { sb = new StringBuilder(FullName); sb.Append('['); } else { sb.Append(','); } sb.Append(genericParameterHandle.GetGenericParameter(_reader).Name.GetString(_reader)); } if (sb == null) { return FullName; } else { return sb.Append(']').ToString(); } } protected sealed override TypeAttributes GetAttributeFlagsImpl() { TypeAttributes attr = _typeDefinition.Flags; return attr; } protected sealed override int InternalGetHashCode() { return _typeDefinitionHandle.GetHashCode(); } // // Returns the anchoring typedef that declares the members that this type wants returned by the Declared*** properties. // The Declared*** properties will project the anchoring typedef's members by overriding their DeclaringType property with "this" // and substituting the value of this.TypeContext into any generic parameters. // // Default implementation returns null which causes the Declared*** properties to return no members. // // Note that this does not apply to DeclaredNestedTypes. Nested types and their containers have completely separate generic instantiation environments // (despite what C# might lead you to think.) Constructed generic types return the exact same same nested types that its generic type definition does // - i.e. their DeclaringTypes refer back to the generic type definition, not the constructed generic type.) // // Note also that we cannot use this anchoring concept for base types because of generic parameters. Generic parameters return // baseclass and interfaces based on its constraints. // internal sealed override RuntimeNamedTypeInfo AnchoringTypeDefinitionForDeclaredMembers { get { return this; } } internal sealed override Type InternalDeclaringType { get { RuntimeTypeInfo declaringType = null; TypeDefinitionHandle enclosingTypeDefHandle = _typeDefinition.EnclosingType; if (!enclosingTypeDefHandle.IsNull(_reader)) { declaringType = enclosingTypeDefHandle.ResolveTypeDefinition(_reader); } return declaringType; } } internal sealed override string InternalFullNameOfAssembly { get { NamespaceChain namespaceChain = NamespaceChain; ScopeDefinitionHandle scopeDefinitionHandle = namespaceChain.DefiningScope; return scopeDefinitionHandle.ToRuntimeAssemblyName(_reader).FullName; } } internal sealed override string InternalGetNameIfAvailable(ref Type rootCauseForFailure) { ConstantStringValueHandle nameHandle = _typeDefinition.Name; string name = nameHandle.GetString(_reader); return EscapeIdentifier(name); } internal sealed override RuntimeTypeHandle InternalTypeHandleIfAvailable { get { return _typeHandle; } } internal sealed override RuntimeTypeInfo[] RuntimeGenericTypeParameters { get { LowLevelList<RuntimeTypeInfo> genericTypeParameters = new LowLevelList<RuntimeTypeInfo>(); foreach (GenericParameterHandle genericParameterHandle in _typeDefinition.GenericParameters) { RuntimeTypeInfo genericParameterType = RuntimeGenericParameterTypeInfoForTypes.GetRuntimeGenericParameterTypeInfoForTypes(this, genericParameterHandle); genericTypeParameters.Add(genericParameterType); } return genericTypeParameters.ToArray(); } } // // Returns the base type as a typeDef, Ref, or Spec. Default behavior is to QTypeDefRefOrSpec.Null, which causes BaseType to return null. // internal sealed override QTypeDefRefOrSpec TypeRefDefOrSpecForBaseType { get { Handle baseType = _typeDefinition.BaseType; if (baseType.IsNull(_reader)) return QTypeDefRefOrSpec.Null; return new QTypeDefRefOrSpec(_reader, baseType); } } // // Returns the *directly implemented* interfaces as typedefs, specs or refs. ImplementedInterfaces will take care of the transitive closure and // insertion of the TypeContext. // internal sealed override QTypeDefRefOrSpec[] TypeRefDefOrSpecsForDirectlyImplementedInterfaces { get { LowLevelList<QTypeDefRefOrSpec> directlyImplementedInterfaces = new LowLevelList<QTypeDefRefOrSpec>(); foreach (Handle ifcHandle in _typeDefinition.Interfaces) directlyImplementedInterfaces.Add(new QTypeDefRefOrSpec(_reader, ifcHandle)); return directlyImplementedInterfaces.ToArray(); } } // // Returns the generic parameter substitutions to use when enumerating declared members, base class and implemented interfaces. // internal sealed override TypeContext TypeContext { get { return new TypeContext(this.RuntimeGenericTypeParameters, null); } } internal MetadataReader Reader { get { return _reader; } } internal TypeDefinitionHandle TypeDefinitionHandle { get { return _typeDefinitionHandle; } } internal IEnumerable<MethodHandle> DeclaredConstructorHandles { get { foreach (MethodHandle methodHandle in _typeDefinition.Methods) { if (methodHandle.IsConstructor(_reader)) yield return methodHandle; } } } internal IEnumerable<EventHandle> DeclaredEventHandles { get { return _typeDefinition.Events; } } internal IEnumerable<FieldHandle> DeclaredFieldHandles { get { return _typeDefinition.Fields; } } internal IEnumerable<MethodHandle> DeclaredMethodAndConstructorHandles { get { return _typeDefinition.Methods; } } internal IEnumerable<PropertyHandle> DeclaredPropertyHandles { get { return _typeDefinition.Properties; } } private readonly MetadataReader _reader; private readonly TypeDefinitionHandle _typeDefinitionHandle; private readonly TypeDefinition _typeDefinition; private readonly RuntimeTypeHandle _typeHandle; private NamespaceChain NamespaceChain { get { if (_lazyNamespaceChain == null) _lazyNamespaceChain = new NamespaceChain(_reader, _typeDefinition.NamespaceDefinition); return _lazyNamespaceChain; } } private volatile NamespaceChain _lazyNamespaceChain; private static readonly NamedTypeToGuidTable s_namedTypeToGuidTable = new NamedTypeToGuidTable(); private sealed class NamedTypeToGuidTable : ConcurrentUnifier<RuntimeNamedTypeInfo, Tuple<Guid>> { protected sealed override Tuple<Guid> Factory(RuntimeNamedTypeInfo key) { return new Tuple<Guid>(Guid.NewGuid()); } } private static readonly char[] s_charsToEscape = new char[] { '\\', '[', ']', '+', '*', '&', ',' }; // Escape identifiers as described in "Specifying Fully Qualified Type Names" on msdn. // Current link is http://msdn.microsoft.com/en-us/library/yfsftwz6(v=vs.110).aspx private static string EscapeIdentifier(string identifier) { // Some characters in a type name need to be escaped if (identifier != null && identifier.IndexOfAny(s_charsToEscape) != -1) { StringBuilder sbEscapedName = new StringBuilder(identifier); sbEscapedName.Replace("\\", "\\\\"); sbEscapedName.Replace("+", "\\+"); sbEscapedName.Replace("[", "\\["); sbEscapedName.Replace("]", "\\]"); sbEscapedName.Replace("*", "\\*"); sbEscapedName.Replace("&", "\\&"); sbEscapedName.Replace(",", "\\,"); identifier = sbEscapedName.ToString(); } return identifier; } } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="Networking.ARPBinding", Namespace="urn:iControl")] [System.Xml.Serialization.SoapIncludeAttribute(typeof(NetworkingARPStaticEntry))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(NetworkingARPARPStatistics))] [System.Xml.Serialization.SoapIncludeAttribute(typeof(NetworkingARPNDPStatistics))] public partial class NetworkingARP : iControlInterface { public NetworkingARP() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_static_entry //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] public void add_static_entry( NetworkingARPStaticEntry [] entries ) { this.Invoke("add_static_entry", new object [] { entries}); } public System.IAsyncResult Beginadd_static_entry(NetworkingARPStaticEntry [] entries, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_static_entry", new object[] { entries}, callback, asyncState); } public void Endadd_static_entry(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create_static_entry //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] public void create_static_entry( string [] entries, string [] addresses, string [] macs ) { this.Invoke("create_static_entry", new object [] { entries, addresses, macs}); } public System.IAsyncResult Begincreate_static_entry(string [] entries,string [] addresses,string [] macs, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create_static_entry", new object[] { entries, addresses, macs}, callback, asyncState); } public void Endcreate_static_entry(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_dynamic_arps //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] public void delete_all_dynamic_arps( ) { this.Invoke("delete_all_dynamic_arps", new object [0]); } public System.IAsyncResult Begindelete_all_dynamic_arps(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_dynamic_arps", new object[0], callback, asyncState); } public void Enddelete_all_dynamic_arps(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_dynamic_ndps //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] public void delete_all_dynamic_ndps( ) { this.Invoke("delete_all_dynamic_ndps", new object [0]); } public System.IAsyncResult Begindelete_all_dynamic_ndps(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_dynamic_ndps", new object[0], callback, asyncState); } public void Enddelete_all_dynamic_ndps(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_static_entries //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] public void delete_all_static_entries( ) { this.Invoke("delete_all_static_entries", new object [0]); } public System.IAsyncResult Begindelete_all_static_entries(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_static_entries", new object[0], callback, asyncState); } public void Enddelete_all_static_entries(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_static_entry //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] public void delete_static_entry( NetworkingARPStaticEntry [] entries ) { this.Invoke("delete_static_entry", new object [] { entries}); } public System.IAsyncResult Begindelete_static_entry(NetworkingARPStaticEntry [] entries, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_static_entry", new object[] { entries}, callback, asyncState); } public void Enddelete_static_entry(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_static_entry_v2 //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] public void delete_static_entry_v2( string [] entries ) { this.Invoke("delete_static_entry_v2", new object [] { entries}); } public System.IAsyncResult Begindelete_static_entry_v2(string [] entries, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_static_entry_v2", new object[] { entries}, callback, asyncState); } public void Enddelete_static_entry_v2(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_dynamic_arp //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingARPARPStatistics get_dynamic_arp( string [] arp_addresses ) { object [] results = this.Invoke("get_dynamic_arp", new object [] { arp_addresses}); return ((NetworkingARPARPStatistics)(results[0])); } public System.IAsyncResult Beginget_dynamic_arp(string [] arp_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dynamic_arp", new object[] { arp_addresses}, callback, asyncState); } public NetworkingARPARPStatistics Endget_dynamic_arp(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingARPARPStatistics)(results[0])); } //----------------------------------------------------------------------- // get_dynamic_ndp //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingARPNDPStatistics get_dynamic_ndp( string [] ndp_addresses ) { object [] results = this.Invoke("get_dynamic_ndp", new object [] { ndp_addresses}); return ((NetworkingARPNDPStatistics)(results[0])); } public System.IAsyncResult Beginget_dynamic_ndp(string [] ndp_addresses, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_dynamic_ndp", new object[] { ndp_addresses}, callback, asyncState); } public NetworkingARPNDPStatistics Endget_dynamic_ndp(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingARPNDPStatistics)(results[0])); } //----------------------------------------------------------------------- // get_static_entry //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public NetworkingARPStaticEntry [] get_static_entry( ) { object [] results = this.Invoke("get_static_entry", new object [0]); return ((NetworkingARPStaticEntry [])(results[0])); } public System.IAsyncResult Beginget_static_entry(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_static_entry", new object[0], callback, asyncState); } public NetworkingARPStaticEntry [] Endget_static_entry(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((NetworkingARPStaticEntry [])(results[0])); } //----------------------------------------------------------------------- // get_static_entry_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_static_entry_address( string [] entries ) { object [] results = this.Invoke("get_static_entry_address", new object [] { entries}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_static_entry_address(string [] entries, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_static_entry_address", new object[] { entries}, callback, asyncState); } public string [] Endget_static_entry_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_static_entry_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_static_entry_description( string [] entries ) { object [] results = this.Invoke("get_static_entry_description", new object [] { entries}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_static_entry_description(string [] entries, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_static_entry_description", new object[] { entries}, callback, asyncState); } public string [] Endget_static_entry_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_static_entry_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_static_entry_list( ) { object [] results = this.Invoke("get_static_entry_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_static_entry_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_static_entry_list", new object[0], callback, asyncState); } public string [] Endget_static_entry_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_static_entry_mac_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_static_entry_mac_address( string [] entries ) { object [] results = this.Invoke("get_static_entry_mac_address", new object [] { entries}); return ((string [])(results[0])); } public System.IAsyncResult Beginget_static_entry_mac_address(string [] entries, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_static_entry_mac_address", new object[] { entries}, callback, asyncState); } public string [] Endget_static_entry_mac_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // set_static_entry_description //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] public void set_static_entry_description( string [] entries, string [] descriptions ) { this.Invoke("set_static_entry_description", new object [] { entries, descriptions}); } public System.IAsyncResult Beginset_static_entry_description(string [] entries,string [] descriptions, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_static_entry_description", new object[] { entries, descriptions}, callback, asyncState); } public void Endset_static_entry_description(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_static_entry_mac_address //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Networking/ARP", RequestNamespace="urn:iControl:Networking/ARP", ResponseNamespace="urn:iControl:Networking/ARP")] public void set_static_entry_mac_address( string [] entries, string [] macs ) { this.Invoke("set_static_entry_mac_address", new object [] { entries, macs}); } public System.IAsyncResult Beginset_static_entry_mac_address(string [] entries,string [] macs, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_static_entry_mac_address", new object[] { entries, macs}, callback, asyncState); } public void Endset_static_entry_mac_address(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.ARP.NDPState", Namespace = "urn:iControl")] public enum NetworkingARPNDPState { NDP_STATE_INCOMPLETE, NDP_STATE_REACHABLE, NDP_STATE_STALE, NDP_STATE_DELAY, NDP_STATE_PROBE, NDP_STATE_PERMANENT, } //======================================================================= // Structs //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.ARP.ARPEntry", Namespace = "urn:iControl")] public partial class NetworkingARPARPEntry { private string arp_addressField; public string arp_address { get { return this.arp_addressField; } set { this.arp_addressField = value; } } private string mac_addressField; public string mac_address { get { return this.mac_addressField; } set { this.mac_addressField = value; } } private string vlanField; public string vlan { get { return this.vlanField; } set { this.vlanField = value; } } private long expirationField; public long expiration { get { return this.expirationField; } set { this.expirationField = value; } } private bool is_downField; public bool is_down { get { return this.is_downField; } set { this.is_downField = value; } } private bool is_dynamicField; public bool is_dynamic { get { return this.is_dynamicField; } set { this.is_dynamicField = value; } } private bool is_resolvedField; public bool is_resolved { get { return this.is_resolvedField; } set { this.is_resolvedField = value; } } private bool is_keepaliveField; public bool is_keepalive { get { return this.is_keepaliveField; } set { this.is_keepaliveField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.ARP.ARPStatistics", Namespace = "urn:iControl")] public partial class NetworkingARPARPStatistics { private NetworkingARPARPEntry [] statisticsField; public NetworkingARPARPEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.ARP.NDPEntry", Namespace = "urn:iControl")] public partial class NetworkingARPNDPEntry { private string ndp_addressField; public string ndp_address { get { return this.ndp_addressField; } set { this.ndp_addressField = value; } } private string mac_addressField; public string mac_address { get { return this.mac_addressField; } set { this.mac_addressField = value; } } private string vlanField; public string vlan { get { return this.vlanField; } set { this.vlanField = value; } } private long expirationField; public long expiration { get { return this.expirationField; } set { this.expirationField = value; } } private bool is_routerField; public bool is_router { get { return this.is_routerField; } set { this.is_routerField = value; } } private NetworkingARPNDPState stateField; public NetworkingARPNDPState state { get { return this.stateField; } set { this.stateField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.ARP.NDPStatistics", Namespace = "urn:iControl")] public partial class NetworkingARPNDPStatistics { private NetworkingARPNDPEntry [] statisticsField; public NetworkingARPNDPEntry [] statistics { get { return this.statisticsField; } set { this.statisticsField = value; } } private CommonTimeStamp time_stampField; public CommonTimeStamp time_stamp { get { return this.time_stampField; } set { this.time_stampField = value; } } }; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "Networking.ARP.StaticEntry", Namespace = "urn:iControl")] public partial class NetworkingARPStaticEntry { private string addressField; public string address { get { return this.addressField; } set { this.addressField = value; } } private string mac_addressField; public string mac_address { get { return this.mac_addressField; } set { this.mac_addressField = value; } } }; }
namespace QI4N.Framework.Runtime { using System; using System.Collections.Generic; using Bootstrap; //[DebuggerDisplay("Name {Name}")] public class ModuleAssemblyImpl : ModuleAssembly { private readonly IList<EntityDeclaration> entityDeclarations = new List<EntityDeclaration>(); private readonly LayerAssembly layerAssembly; private readonly MetaInfo metaInfo; private readonly MetaInfoDeclaration metaInfoDeclaration = new MetaInfoDeclaration(); private readonly string name; private readonly List<ServiceDeclaration> serviceDeclarations = new List<ServiceDeclaration>(); private readonly List<TransientDeclaration> transientDeclarations = new List<TransientDeclaration>(); private readonly List<ValueDeclaration> valueDeclarations = new List<ValueDeclaration>(); public ModuleAssemblyImpl(LayerAssembly layerAssembly, string name, MetaInfo metaInfo) { this.layerAssembly = layerAssembly; this.name = name; this.metaInfo = metaInfo; } public IList<EntityDeclaration> EntityDeclarations { get { return this.entityDeclarations; } } public MetaInfo MetaInfo { get { return this.metaInfo; } } public string Name { get { return this.name; } } public IList<ServiceDeclaration> ServiceDeclarations { get { return this.serviceDeclarations; } } public IList<TransientDeclaration> TransientDeclarations { get { return this.transientDeclarations; } } public IList<ValueDeclaration> ValueDeclarations { get { return this.valueDeclarations; } } public EntityDeclaration AddEntities() { var declaration = new EntityDeclarationImpl(); this.EntityDeclarations.Add(declaration); return declaration; } public ServiceDeclaration AddServices() { var declaration = new ServiceDeclarationImpl(this); this.ServiceDeclarations.Add(declaration); return declaration; } public TransientDeclaration AddTransients() { var declaration = new TransientDeclarationImpl(); this.transientDeclarations.Add(declaration); return declaration; } public ValueDeclaration AddValues() { var declaration = new ValueDeclarationImpl(); this.ValueDeclarations.Add(declaration); return declaration; } public ModuleModel AssembleModule() { var compositeModels = new List<TransientModel>(); var entityModels = new List<EntityModel>(); var objectModels = new List<ObjectModel>(); var valueModels = new List<ValueModel>(); var serviceModels = new List<ServiceModel>(); var importedServiceModels = new List<ImportedServiceModel>(); if (this.name == null) { throw new Exception("Module must have name set"); } var moduleModel = new ModuleModel(this.name, this.metaInfo, new TransientsModel(compositeModels), new EntitiesModel(entityModels), new ObjectsModel(objectModels), new ValuesModel(valueModels), new ServicesModel(serviceModels), new ImportedServicesModel(importedServiceModels)); foreach (TransientDeclarationImpl transientDeclaration in this.transientDeclarations) { transientDeclaration.AddTransients(compositeModels, this.metaInfoDeclaration); } foreach (ValueDeclarationImpl valueDeclaration in this.valueDeclarations) { valueDeclaration.AddValues(valueModels, this.metaInfoDeclaration); } foreach (EntityDeclarationImpl entityDeclaration in this.entityDeclarations) { entityDeclaration.AddEntities(entityModels, this.metaInfoDeclaration); } foreach (ServiceDeclarationImpl serviceDeclaration in this.serviceDeclarations) { serviceDeclaration.AddServices(serviceModels, this.metaInfoDeclaration); } return moduleModel; // for( ObjectDeclarationImpl objectDeclaration : objectDeclarations ) //{ // objectDeclaration.addObjects( objectModels ); //} //for( ImportedServiceDeclarationImpl importedServiceDeclaration : importedServiceDeclarations ) //{ // importedServiceDeclaration.addServices( importedServiceModels ); //} //// Check for duplicate service identities //Set<String> identities = new HashSet<String>(); //for( ServiceModel serviceModel : serviceModels ) //{ // String identity = serviceModel.identity(); // if( identities.contains( identity ) ) // { // throw new DuplicateServiceIdentityException( // "Duplicated service identity: " + identity + " in module " + moduleModel.name() // ); // } // identities.add( identity ); //} //for( ImportedServiceModel serviceModel : importedServiceModels ) //{ // String identity = serviceModel.identity(); // if( identities.contains( identity ) ) // { // throw new DuplicateServiceIdentityException( // "Duplicated service identity: " + identity + " in module " + moduleModel.name() // ); // } // identities.add( identity ); //} //for( ImportedServiceModel importedServiceModel : importedServiceModels ) //{ // boolean found = false; // for( ObjectModel objectModel : objectModels ) // { // if( objectModel.type().equals( importedServiceModel.serviceImporter() ) ) // { // found = true; // break; // } // } // if( !found ) // { // Class<? extends ServiceImporter> serviceFactoryType = importedServiceModel.serviceImporter(); // ObjectModel objectModel = new ObjectModel( serviceFactoryType, Visibility.module, new MetaInfo() ); // objectModels.add( objectModel ); // } //} } public void Visit(AssemblyVisitor visitor) { throw new NotImplementedException(); } } public class ObjectModel { } }
using MonoTouch.UIKit; using System.Drawing; using FeedbackIOS.Utility; using System; using SharableTypes.Model; using System.IO; using System.Net; namespace Feedback { public partial class FeedbackViewController : UIViewController { QuestionViewController _questionScreen; ScannerViewController _scanScreen; // Variables for web service response data private string _surveyCode; private int _questionCount; LoadingOverlay _loadPop; public FeedbackViewController () : base ("FeedbackViewController", null) { } public override void ViewWillAppear (bool animated) { NavigationItem.Title = "Feedback Survey App"; StorageHelper.SaveToIsolatedStorage(StorageHelper.SURVEY_NAME, ""); StorageHelper.SaveToIsolatedStorage(StorageHelper.RESPONSES, ""); var fromScan = StorageHelper.LoadFromIsolatedStorage(StorageHelper.FROM_SCAN); if (fromScan == "Y") { _surveyCode = StorageHelper.LoadFromIsolatedStorage(StorageHelper.SURVEY_CODE); StorageHelper.SaveToIsolatedStorage(StorageHelper.SUBMISSION_ID, Guid.NewGuid().ToString()); if (!string.IsNullOrEmpty (_surveyCode)) { LoadQuestions(); } StorageHelper.SaveToIsolatedStorage(StorageHelper.FROM_SCAN, "N"); } else { StorageHelper.SaveToIsolatedStorage(StorageHelper.SURVEY_CODE, ""); } } public override void ViewWillDisappear (bool animated) { NavigationItem.Title = ""; } public override void ViewDidLoad () { base.ViewDidLoad (); var stackPanel = new StackPanel (View.Bounds); Title = "Feedback Survey App"; //IndustrialTheme.Apply(this); var header = new UILabel (new RectangleF(25,40,200,40)) { Text = "Welcome to the Feedback survey application", LineBreakMode = UILineBreakMode.WordWrap, Lines = 0 }; //IndustrialTheme.Apply (header, "aluminum"); header.Font = UIFont.FromName ("Arial-BoldMT", 18); stackPanel.AddSubview (header); var subHeader = new UILabel (new RectangleF(0,0,200,40)) { Text = "Enter your survey code" }; //IndustrialTheme.Apply (subHeader); stackPanel.AddSubview (subHeader); var surveyCode = new UITextField (new RectangleF (25, 80, 268, 40)) { Placeholder = "", BorderStyle = UITextBorderStyle.RoundedRect, ShouldReturn = field => { field.ResignFirstResponder(); return true; } }; //IndustrialTheme.Apply (surveyCode); //var paddingView = new UIView(new RectangleF(0, 0, 10, 10)); //surveyCode.LeftView = paddingView; //surveyCode.LeftViewMode = UITextFieldViewMode.WhileEditing; stackPanel.AddSubview (surveyCode); var startSurvey = AddButton(stackPanel, "confirm", "start survey"); startSurvey.TouchUpInside += (sender, e) => { if (string.IsNullOrEmpty(surveyCode.Text)) { InvokeOnMainThread(() => { var av = new UIAlertView("Validation Message", "Please enter a survey code", null, "OK", null); av.Show(); }); } else { _surveyCode = surveyCode.Text; StorageHelper.SaveToIsolatedStorage(StorageHelper.SURVEY_CODE, surveyCode.Text); StorageHelper.SaveToIsolatedStorage(StorageHelper.SUBMISSION_ID, Guid.NewGuid().ToString()); LoadQuestions(); } }; var scanText = new UILabel (new RectangleF(25,40,200,40)) { Text = "Have a QR code?", LineBreakMode = UILineBreakMode.WordWrap, Lines = 0 }; //IndustrialTheme.Apply (scanText); stackPanel.AddSubview (scanText); var startScan = AddButton(stackPanel, "confirm", "start scan"); startScan.TouchUpInside += (sender, e) => { _scanScreen = new ScannerViewController(); NavigationController.PushViewController(_scanScreen, true); }; View.AddSubview (stackPanel); View.LayoutSubviews (); base.EdgesForExtendedLayout = UIRectEdge.None; } private UIButton AddButton (StackPanel panel, string options, string title) { var button = new UIButton (new RectangleF(25, 120, 298, 57)); //IndustrialTheme.Apply (button, options); button.BackgroundColor = UIColor.LightGray; button.SetTitleColor (UIColor.Black, UIControlState.Normal); button.SetTitle (title, UIControlState.Normal); panel.AddSubview (button); return button; } #region Webservice calls private void ShowLoading() { InvokeOnMainThread(() => { _loadPop = new LoadingOverlay(UIScreen.MainScreen.Bounds, "Loading Questions..."); View.Add(_loadPop); }); } private void HideLoading() { InvokeOnMainThread(() => { if (_loadPop != null) { _loadPop.Hide(); } }); } private void DisplayErrorMessage() { InvokeOnMainThread(() => { var av = new UIAlertView("Error", "Unable to retrieve the survey data. Please try again", null, "OK", null); av.Show(); }); } private void LoadQuestions() { var question = new QuestionM { SurveyCode = _surveyCode }; var requestContent = Newtonsoft.Json.JsonConvert.SerializeObject(question); var request = APIHelper.InitializeRequest(UIConstants.GET_QUESTION_CONTAINER); if (ConnectionHelper.IsConnected()) { ShowLoading(); request.BeginGetRequestStream(result => { var req = ((HttpWebRequest)result.AsyncState).EndGetRequestStream(result); using (var streamWriter = new StreamWriter(req)) { streamWriter.Write(requestContent); } request.BeginGetResponse(responseResult => { try { var response = (HttpWebResponse)((HttpWebRequest)result.AsyncState).EndGetResponse(responseResult); string responseContent; using (var streamReader = new StreamReader(response.GetResponseStream())) { responseContent = streamReader.ReadToEnd(); } var questionContainer = Newtonsoft.Json.JsonConvert.DeserializeObject<QuestionContainerM>(responseContent); if (questionContainer != null && questionContainer.QuestionList != null && questionContainer.QuestionList.Length > 0) { _questionCount = questionContainer.QuestionList.Length; StorageHelper.SaveToIsolatedStorage(StorageHelper.QUESTIONCONTAINER, responseContent); LoadQuestionDefinitionLines(); } else { InvokeOnMainThread(() => { if (_loadPop != null) { _loadPop.Hide(); _loadPop.RemoveFromSuperview(); } var av = new UIAlertView("Survey Error", "Unable to locate survey. Please check your code and try again", null, "OK", null); av.Show(); }); } } catch (Exception ex) { LittleWatson.ReportException(ex); DisplayErrorMessage(); } finally { HideLoading(); } }, request); }, request); } else { InvokeOnMainThread(() => { var av = new UIAlertView("Connection Error", "Unable to detect a network connection. Please try again", null, "OK", null); av.Show(); }); } } private void LoadQuestionDefinitionLines() { var question = new QuestionM { SurveyCode = _surveyCode }; var requestContent = Newtonsoft.Json.JsonConvert.SerializeObject(question); var request = APIHelper.InitializeRequest(UIConstants.GET_QUESTION_DEFINITION_LINES); request.BeginGetRequestStream(result => { var req = ((HttpWebRequest)result.AsyncState).EndGetRequestStream(result); using (var streamWriter = new StreamWriter(req)) { streamWriter.Write(requestContent); } request.BeginGetResponse(responseResult => { try { var response = (HttpWebResponse)((HttpWebRequest)result.AsyncState).EndGetResponse(responseResult); string responseContent; using (var streamReader = new StreamReader(response.GetResponseStream())) { responseContent = streamReader.ReadToEnd(); } InvokeOnMainThread(() => { StorageHelper.SaveToIsolatedStorage(StorageHelper.QUESTION_DEFINITION_LINES, responseContent); LoadQuestionDefinitionResponses(); }); } catch (Exception ex) { HideLoading(); LittleWatson.ReportException(ex); DisplayErrorMessage(); } }, request); }, request); } private void LoadQuestionDefinitionResponses() { var question = new QuestionM { SurveyCode = _surveyCode }; var requestContent = Newtonsoft.Json.JsonConvert.SerializeObject(question); var request = APIHelper.InitializeRequest(UIConstants.GET_QUESTION_DEFINITION_RESPONSES); request.BeginGetRequestStream(result => { var req = ((HttpWebRequest)result.AsyncState).EndGetRequestStream(result); using (var streamWriter = new StreamWriter(req)) { streamWriter.Write(requestContent); } request.BeginGetResponse(responseResult => { try { var response = (HttpWebResponse)((HttpWebRequest)result.AsyncState).EndGetResponse(responseResult); string responseContent; using (var streamReader = new StreamReader(response.GetResponseStream())) { responseContent = streamReader.ReadToEnd(); } InvokeOnMainThread(() => { StorageHelper.SaveToIsolatedStorage(StorageHelper.QUESTION_DEFINITION_RESPONSES, responseContent); LoadQuestionDefinitionHeaders(); }); } catch (Exception ex) { HideLoading(); LittleWatson.ReportException(ex); DisplayErrorMessage(); } }, request); }, request); } private void LoadQuestionDefinitionHeaders() { var question = new QuestionM { SurveyCode = _surveyCode }; var requestContent = Newtonsoft.Json.JsonConvert.SerializeObject(question); var request = APIHelper.InitializeRequest(UIConstants.GET_QUESTION_DEFINITION_HEADERS); request.BeginGetRequestStream(result => { var req = ((HttpWebRequest)result.AsyncState).EndGetRequestStream(result); using (var streamWriter = new StreamWriter(req)) { streamWriter.Write(requestContent); } request.BeginGetResponse(responseResult => { try { var response = (HttpWebResponse)((HttpWebRequest)result.AsyncState).EndGetResponse(responseResult); string responseContent; using (var streamReader = new StreamReader(response.GetResponseStream())) { responseContent = streamReader.ReadToEnd(); } InvokeOnMainThread(() => { StorageHelper.SaveToIsolatedStorage(StorageHelper.QUESTION_DEFINITION_HEADERS, responseContent); LoadQuestionEvents(); }); } catch (Exception ex) { HideLoading(); LittleWatson.ReportException(ex); DisplayErrorMessage(); } }, request); }, request); } private void LoadQuestionEvents() { try { var question = new QuestionM { SurveyCode = _surveyCode }; var requestContent = Newtonsoft.Json.JsonConvert.SerializeObject(question); var request = APIHelper.InitializeRequest(UIConstants.GET_QUESTION_EVENTS); request.BeginGetRequestStream(result => { var req = ((HttpWebRequest)result.AsyncState).EndGetRequestStream(result); using (var streamWriter = new StreamWriter(req)) { streamWriter.Write(requestContent); } request.BeginGetResponse(responseResult => { try { var response = (HttpWebResponse)((HttpWebRequest)result.AsyncState).EndGetResponse(responseResult); string responseContent; using (var streamReader = new StreamReader(response.GetResponseStream())) { responseContent = streamReader.ReadToEnd(); } InvokeOnMainThread(() => { _questionScreen = new QuestionViewController(); NavigationController.PushViewController(_questionScreen, true); }); StorageHelper.SaveToIsolatedStorage(StorageHelper.QUESTION_EVENTS, responseContent); } catch (Exception ex) { HideLoading(); LittleWatson.ReportException(ex); DisplayErrorMessage(); } finally { HideLoading(); } }, request); }, request); } catch (Exception ex) { LittleWatson.ReportException(ex); } } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Globalization; using System.Linq; using System.Xml; using System.Text; using System.Xml.Serialization; using WebsitePanel.Providers; using WebsitePanel.Providers.DNS; namespace WebsitePanel.EnterpriseServer { public class DnsServerController : IImportController, IBackupController { private static string GetAsciiZoneName(string zoneName) { if (string.IsNullOrEmpty(zoneName)) return zoneName; var idn = new IdnMapping(); return idn.GetAscii(zoneName); } private static DNSServer GetDNSServer(int serviceId) { DNSServer dns = new DNSServer(); ServiceProviderProxy.Init(dns, serviceId); return dns; } public static int AddZone(int packageId, int serviceId, string zoneName) { return AddZone(packageId, serviceId, zoneName, true, false); } public static int AddZone(int packageId, int serviceId, string zoneName, bool addPackageItem, bool ignoreGlobalDNSRecords) { // get DNS provider DNSServer dns = GetDNSServer(serviceId); // Ensure zoneName is in ascii before saving to database zoneName = GetAsciiZoneName(zoneName); // check if zone already exists if (dns.ZoneExists(zoneName)) return BusinessErrorCodes.ERROR_DNS_ZONE_EXISTS; // TaskManager.StartTask("DNS_ZONE", "ADD", zoneName); // int zoneItemId = default(int); // try { // get secondary DNS services StringDictionary primSettings = ServerController.GetServiceSettings(serviceId); string[] primaryIPAddresses = GetExternalIPAddressesFromString(primSettings["ListeningIPAddresses"]); List<string> secondaryIPAddresses = new List<string>(); List<int> secondaryServiceIds = new List<int>(); string strSecondaryServices = primSettings["SecondaryDNSServices"]; if (!String.IsNullOrEmpty(strSecondaryServices)) { string[] secondaryServices = strSecondaryServices.Split(','); foreach (string strSecondaryId in secondaryServices) { int secondaryId = Utils.ParseInt(strSecondaryId, 0); if (secondaryId == 0) continue; secondaryServiceIds.Add(secondaryId); StringDictionary secondarySettings = ServerController.GetServiceSettings(secondaryId); // add secondary IPs to the master array secondaryIPAddresses.AddRange( GetExternalIPAddressesFromString(secondarySettings["ListeningIPAddresses"])); } } // add "Allow zone transfers" string allowTransfers = primSettings["AllowZoneTransfers"]; if (!String.IsNullOrEmpty(allowTransfers)) { string[] ips = Utils.ParseDelimitedString(allowTransfers, '\n', ' ', ',', ';'); foreach (string ip in ips) { if (!secondaryIPAddresses.Contains(ip)) secondaryIPAddresses.Add(ip); } } // add primary zone dns.AddPrimaryZone(zoneName, secondaryIPAddresses.ToArray()); // get DNS zone records List<GlobalDnsRecord> records = ServerController.GetDnsRecordsTotal(packageId); // get name servers PackageSettings packageSettings = PackageController.GetPackageSettings(packageId, PackageSettings.NAME_SERVERS); string[] nameServers = new string[] { }; if (!String.IsNullOrEmpty(packageSettings["NameServers"])) nameServers = packageSettings["NameServers"].Split(';'); // build records list List<DnsRecord> zoneRecords = new List<DnsRecord>(); string primaryNameServer = "ns." + zoneName; if (nameServers.Length > 0) primaryNameServer = nameServers[0]; // update SOA record string hostmaster = primSettings["ResponsiblePerson"]; if (String.IsNullOrEmpty(hostmaster)) { hostmaster = "hostmaster." + zoneName; } else { hostmaster = Utils.ReplaceStringVariable(hostmaster, "domain_name", zoneName); } dns.UpdateSoaRecord(zoneName, "", primaryNameServer, hostmaster); // add name servers foreach (string nameServer in nameServers) { DnsRecord ns = new DnsRecord(); ns.RecordType = DnsRecordType.NS; ns.RecordName = ""; ns.RecordData = nameServer; zoneRecords.Add(ns); } if (!ignoreGlobalDNSRecords) { // add all other records zoneRecords.AddRange(BuildDnsResourceRecords(records, "", zoneName, "")); } // add zone records dns.AddZoneRecords(zoneName, zoneRecords.ToArray()); // add secondary zones foreach (int secondaryId in secondaryServiceIds) { try { // add secondary zone DNSServer secDns = GetDNSServer(secondaryId); secDns.AddSecondaryZone(zoneName, primaryIPAddresses); RegisterZoneItems(packageId, secondaryId, zoneName, false); } catch (Exception ex) { TaskManager.WriteError(ex, "Error adding secondary zone (service ID = " + secondaryId + ")"); } } if (!addPackageItem) return 0; // add service item zoneItemId = RegisterZoneItems(packageId, serviceId, zoneName, true); // TaskManager.ItemId = zoneItemId; } catch (Exception ex) { TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } // return zoneItemId; } private static int RegisterZoneItems(int spaceId, int serviceId, string zoneName, bool primaryZone) { // zone item DnsZone zone = primaryZone ? new DnsZone() : new SecondaryDnsZone(); zone.Name = GetAsciiZoneName(zoneName); zone.PackageId = spaceId; zone.ServiceId = serviceId; int zoneItemId = PackageController.AddPackageItem(zone); return zoneItemId; } public static int DeleteZone(int zoneItemId) { // delete DNS zone if applicable DnsZone zoneItem = (DnsZone)PackageController.GetPackageItem(zoneItemId); // if (zoneItem != null) { TaskManager.StartTask("DNS_ZONE", "DELETE", zoneItem.Name, zoneItemId); // try { // delete DNS zone DNSServer dns = new DNSServer(); ServiceProviderProxy.Init(dns, zoneItem.ServiceId); // delete secondary zones StringDictionary primSettings = ServerController.GetServiceSettings(zoneItem.ServiceId); string strSecondaryServices = primSettings["SecondaryDNSServices"]; if (!String.IsNullOrEmpty(strSecondaryServices)) { string[] secondaryServices = strSecondaryServices.Split(','); foreach (string strSecondaryId in secondaryServices) { try { int secondaryId = Utils.ParseInt(strSecondaryId, 0); if (secondaryId == 0) continue; DNSServer secDns = new DNSServer(); ServiceProviderProxy.Init(secDns, secondaryId); secDns.DeleteZone(zoneItem.Name); } catch (Exception ex1) { // problem when deleting secondary zone TaskManager.WriteError(ex1, "Error deleting secondary DNS zone"); } } } try { dns.DeleteZone(zoneItem.Name); } catch (Exception ex2) { TaskManager.WriteError(ex2, "Error deleting primary DNS zone"); } // delete service item PackageController.DeletePackageItem(zoneItemId); // Delete also all seconday service items var zoneItems = PackageController.GetPackageItemsByType(zoneItem.PackageId, ResourceGroups.Dns, typeof (SecondaryDnsZone)); foreach (var item in zoneItems.Where(z => z.Name == zoneItem.Name)) { PackageController.DeletePackageItem(item.Id); } } catch (Exception ex) { TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } // return 0; } public static List<DnsRecord> BuildDnsResourceRecords(List<GlobalDnsRecord> records, string hostName, string domainName, string serviceIP) { List<DnsRecord> zoneRecords = new List<DnsRecord>(); foreach (GlobalDnsRecord record in records) { domainName = GetAsciiZoneName(domainName); DnsRecord rr = new DnsRecord(); rr.RecordType = (DnsRecordType)Enum.Parse(typeof(DnsRecordType), record.RecordType, true); rr.RecordName = Utils.ReplaceStringVariable(record.RecordName, "host_name", hostName, true); if (record.RecordType == "A" || record.RecordType == "AAAA") { // If the service IP address and the DNS records external address are empty / null SimpleDNS will fail to properly create the zone record if (String.IsNullOrEmpty(serviceIP) && String.IsNullOrEmpty(record.ExternalIP) && String.IsNullOrEmpty(record.RecordData)) continue; rr.RecordData = String.IsNullOrEmpty(record.RecordData) ? record.ExternalIP : record.RecordData; rr.RecordData = Utils.ReplaceStringVariable(rr.RecordData, "ip", string.IsNullOrEmpty(serviceIP) ? record.ExternalIP : serviceIP); rr.RecordData = Utils.ReplaceStringVariable(rr.RecordData, "domain_name", string.IsNullOrEmpty(domainName) ? string.Empty : domainName); if (String.IsNullOrEmpty(rr.RecordData) && !String.IsNullOrEmpty(serviceIP)) rr.RecordData = serviceIP; } else if (record.RecordType == "SRV") { rr.SrvPriority = record.SrvPriority; rr.SrvWeight = record.SrvWeight; rr.SrvPort = record.SrvPort; rr.RecordText = record.RecordData; rr.RecordData = record.RecordData; } else { rr.RecordData = record.RecordData; } // substitute variables rr.RecordData = Utils.ReplaceStringVariable(rr.RecordData, "domain_name", domainName); // add MX priority if (record.RecordType == "MX") rr.MxPriority = record.MxPriority; if (!String.IsNullOrEmpty(rr.RecordData)) { if (rr.RecordName != "[host_name]") zoneRecords.Add(rr); } } return zoneRecords; } public static string[] GetExternalIPAddressesFromString(string str) { List<string> ips = new List<string>(); if (str != null && str.Trim() != "") { string[] sips = str.Split(','); foreach (string sip in sips) { IPAddressInfo ip = ServerController.GetIPAddress(Int32.Parse(sip)); if (ip != null) ips.Add(ip.ExternalIP); } } return ips.ToArray(); } #region IImportController Members public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group) { List<string> items = new List<string>(); // get service id int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName); if (serviceId == 0) return items; // Mail provider DNSServer dns = new DNSServer(); ServiceProviderProxy.Init(dns, serviceId); // IDN: The list of importable names is populated with unicode names, to make it easier for the user var idn = new IdnMapping(); if (itemType == typeof(DnsZone)) items.AddRange(dns.GetZones().Select(z => Encoding.UTF8.GetByteCount(z) == z.Length ? // IsASCII idn.GetUnicode(z) : z )); return items; } public void ImportItem(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group, string itemName) { // get service id int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName); if (serviceId == 0) return; if (itemType == typeof(DnsZone)) { // Get ascii form in punycode var zoneName = GetAsciiZoneName(itemName); // add DNS zone DnsZone zone = new DnsZone(); zone.Name = zoneName; zone.ServiceId = serviceId; zone.PackageId = packageId; int zoneId = PackageController.AddPackageItem(zone); // Add secondary zone(s) try { // get secondary DNS services var primSettings = ServerController.GetServiceSettings(serviceId); var secondaryServiceIds = new List<int>(); var strSecondaryServices = primSettings["SecondaryDNSServices"]; if (!String.IsNullOrEmpty(strSecondaryServices)) { var secondaryServices = strSecondaryServices.Split(','); secondaryServiceIds.AddRange(secondaryServices.Select(strSecondaryId => Utils.ParseInt(strSecondaryId, 0)).Where(secondaryId => secondaryId != 0)); } // add secondary zones var secondaryZoneFound = false; foreach (var secondaryId in secondaryServiceIds) { var secDns = GetDNSServer(secondaryId); if (secDns.ZoneExists(zoneName)) { secondaryZoneFound = true; var secondaryZone = new SecondaryDnsZone { Name = zoneName, ServiceId = secondaryId, PackageId = packageId }; PackageController.AddPackageItem(secondaryZone); } } if (!secondaryZoneFound) { TaskManager.WriteWarning("No secondary zone(s) found when importing zone " + itemName); } } catch (Exception ex) { TaskManager.WriteError(ex, "Error importing secondary zone(s)"); } // add/update domains/pointers RestoreDomainByZone(itemName, packageId, zoneId); } } private void RestoreDomainByZone(string itemName, int packageId, int zoneId) { DomainInfo domain = ServerController.GetDomain(itemName); if (domain == null) { domain = new DomainInfo(); domain.DomainName = itemName; domain.PackageId = packageId; domain.ZoneItemId = zoneId; ServerController.AddDomainItem(domain); } else { domain.ZoneItemId = zoneId; ServerController.UpdateDomain(domain); } } #endregion #region IBackupController Members public int BackupItem(string tempFolder, XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group) { if (!(item is DnsZone)) return 0; // DNS provider DNSServer dns = GetDNSServer(item.ServiceId); // zone records serialized XmlSerializer serializer = new XmlSerializer(typeof(DnsRecord)); try { // get zone records DnsRecord[] records = dns.GetZoneRecords(item.Name); // serialize zone records foreach (DnsRecord record in records) serializer.Serialize(writer, record); } catch (Exception ex) { TaskManager.WriteError(ex, "Could not read zone records"); } return 0; } public int RestoreItem(string tempFolder, XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group) { if (itemType != typeof(DnsZone)) return 0; // DNS provider DNSServer dns = GetDNSServer(serviceId); // check service item if (!dns.ZoneExists(itemName)) { // create primary and secondary zones AddZone(packageId, serviceId, itemName, false, false); // restore records XmlSerializer serializer = new XmlSerializer(typeof(DnsRecord)); List<DnsRecord> records = new List<DnsRecord>(); foreach (XmlNode childNode in itemNode.ChildNodes) { if (childNode.Name == "DnsRecord") { records.Add((DnsRecord)serializer.Deserialize(new XmlNodeReader(childNode))); } } dns.AddZoneRecords(itemName, records.ToArray()); } // check if meta-item exists int zoneId = 0; DnsZone item = (DnsZone)PackageController.GetPackageItemByName(packageId, itemName, typeof(DnsZone)); if (item == null) { // restore meta-item item = new DnsZone(); item.Name = itemName; item.PackageId = packageId; item.ServiceId = serviceId; zoneId = PackageController.AddPackageItem(item); } else { zoneId = item.Id; } // restore domains RestoreDomainByZone(itemName, packageId, zoneId); return 0; } #endregion } }
/* * Copyright (C) Sony Computer Entertainment America LLC. * All Rights Reserved. */ using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; namespace Sce.Sled.SyntaxEditor { /// <summary> /// Method called when KeyPress occurs</summary> /// <param name="sender">Sender</param> /// <param name="e">KeyPressEventArgs arguments containing event data</param> public delegate void OnKeyPressEventHandler(object sender, KeyPressEventArgs e); /// <summary> /// Interface for syntax aware editor controls</summary> public interface ISyntaxEditorControl : IDisposable { /// <summary> /// Gets underlying control</summary> Control Control { get; } /// <summary> /// Gets and sets the control's text</summary> string Text { get; set; } /// <summary> /// Gets and sets whether the document has a vertical splitter</summary> bool VerticalSplitter { get; set; } /// <summary> /// Gets and sets whether the document has a horizontal splitter</summary> bool HorizontalSplitter { get; set; } /// <summary> /// Event raised when a key is pressed</summary> event OnKeyPressEventHandler OnKeyPressEvent; /// <summary> /// Event that is raised after the control's text has changed</summary> event EventHandler<EditorTextChangedEventArgs> EditorTextChanged; /// <summary> /// Event that is raised after the ReadOnly property changes</summary> event EventHandler ReadOnlyChanged; /// <summary> /// Event that is raised when the context menu should be displayed by right clicking /// on the SyntaxEditor control</summary> event EventHandler<ShowContextMenuEventArg> ShowContextMenu; /// <summary> /// Event that is raised after an alpha-numerical key is pressed</summary> event KeyPressEventHandler KeyPress; /// <summary> /// Event that is raised when the user drag and drops a file or folder onto the editor.</summary> event EventHandler<FileDragDropEventArgs> FileDragDropping; /// <summary> /// Event that is raised when the user drag and drops a file or folder onto the editor.</summary> event EventHandler<FileDragDropEventArgs> FileDragDropped; /// <summary> /// Gets and sets whether to enable a default context menu</summary> /// <remarks>Set this property to false when implementing a custom context menu. /// Default value is true.</remarks> bool DefaultContextMenuEnabled { get; set; } /// <summary> /// Gets and sets whether to enable word wrap</summary> bool EnableWordWrap { get; set; } /// <summary> /// Gets and sets whether the content is read-only</summary> bool ReadOnly { get; set; } /// <summary> /// Gets and sets whether the control's text is dirty</summary> bool Dirty { get; set; } /// <summary> /// Gets the current selection's text</summary> string Selection { get; } /// <summary> /// Gets whether the selection is not null or an empty string</summary> bool HasSelection { get; } /// <summary> /// Event raised when the selection changes</summary> event EventHandler SelectionChanged; /// <summary> /// Gets whether the editor can paste</summary> bool CanPaste { get; } /// <summary> /// Gets whether the editor can undo</summary> bool CanUndo { get; } /// <summary> /// Gets whether the editor can redo</summary> bool CanRedo { get; } /// <summary> /// Gets the number of document lines</summary> int DocumentLineCount { get; } /// <summary> /// Gets and sets current line number</summary> int CurrentLineNumber { get; set; } /// <summary> /// Event raised when the CurrentLineNumber property changes</summary> event EventHandler CurrentLineNumberChanged; /// <summary> /// Gets and sets the caret offset</summary> int CurrentOffset { get; set; } /// <summary> /// Gets substring</summary> /// <param name="startOffset">Start offset of the substring</param> /// <param name="count">Length of the substring in characters</param> /// <returns>Specified substring</returns> string GetSubString( int startOffset, int count ); /// <summary> /// Gets caret position in client coordinates</summary> Point CaretPosition { get; } /// <summary> /// Selects line, given a line number. /// This method throws ArgumentOutOfRangeException /// if the line number is out of range.</summary> /// <param name="lineNumber">The line number to be selected</param> void SelectLine(int lineNumber); /// <summary> /// Selects line, given line number</summary> /// <remarks>Selection is [startOffset, endOffset] inclusive</remarks> /// <param name="lineNumber">The line number to be selected</param> /// <param name="startOffset">Beginning offset of the selection; starting index is zero</param> /// <param name="endOffset">Ending offset of selection</param> void SelectLine(int lineNumber, int startOffset, int endOffset); /// <summary> /// Gets the text for the given line number</summary> /// <param name="lineNumber">The line number</param> /// <returns>Text of the given line</returns> /// <remarks>If the line is empty, an empty string is returned; /// this method does not return null. /// If the line number is out of range, the ArgumentOutOfRangeException /// exception is thrown.</remarks> string GetLineText(int lineNumber); /// <summary> /// Cuts the selection and copies it to the clipboard</summary> void Cut(); /// <summary> /// Copies the selection to the clipboard</summary> void Copy(); /// <summary> /// Pastes the clipboard at the current selection</summary> void Paste(); /// <summary> /// Deletes the selection</summary> void Delete(); /// <summary> /// Undoes the last change</summary> void Undo(); /// <summary> /// Redoes the last undone</summary> void Redo(); /// <summary> /// Selects all text in the document</summary> void SelectAll(); /// <summary> /// Shows the find/replace dialog</summary> void ShowFindReplaceForm(); /// <summary> /// Shows the go to line dialog</summary> void ShowGoToLineForm(); /// <summary> /// Sets control to one of the built-in languages</summary> /// <param name="language">Language to be edited in control</param> void SetLanguage(Languages language); /// <summary> /// Sets control to a custom language</summary> /// <param name="stream">XML stream containing the syntax rules for the language</param> void SetLanguage(Stream stream); /// <summary> /// Sets control to a custom language</summary> /// <param name="baseLanguage">Language custom stream is based off of</param> /// <param name="stream">XML stream containing the syntax rules for the language</param> void SetLanguage(Languages baseLanguage, Stream stream); /// <summary> /// Displays a print preview dialog for the document</summary> void PrintPreview(); /// <summary> /// Prints the current document to the printer</summary> /// <param name="showDialog">Whether to show the standard Print dialog /// before printing</param> void Print(bool showDialog); /// <summary> /// Gets and sets multiline property</summary> bool Multiline { get; set; } /// <summary> /// Gets and sets whether the line number margin is visible</summary> bool LineNumberMarginVisible { get; set; } /// <summary> /// Gets and sets whether the indicator margin is visible</summary> bool IndicatorMarginVisible { get; set; } /// <summary> /// Clears the IntelliPrompt member collection</summary> void ClearIntelliPromptMemberList(); /// <summary> /// Adds an item to the IntelliPrompt member collection</summary> /// <param name="item">Item to add</param> void AddIntelliPromptMemberListItem(string item); /// <summary> /// Adds an item to the IntelliPrompt member collection</summary> /// <param name="item">Item to add</param> /// <param name="description">Item's description</param> /// <param name="autoCompletePreText">Text before auto completion</param> /// <param name="autoCompletePostText">Text after auto completion</param> void AddIntelliPromptMemberListItem(string item, string description, string autoCompletePreText, string autoCompletePostText); /// <summary> /// Shows the IntelliPrompt member list</summary> void ShowIntelliPromptMemberList(); /// <summary> /// Shows the IntelliPrompt member list</summary> /// <param name="offset">Offset of list</param> /// <param name="length">List length</param> void ShowIntelliPromptMemberList(int offset, int length); /// <summary> /// Gets list of IBreakpoints</summary> IBreakpoint[] GetBreakpoints(); /// <summary> /// Sets breakpoint for specified lines</summary> /// <param name="list">List of lines</param> void SetBreakpoints(IList<int> list); /// <summary> /// Gets IBreakpoint for a given line number</summary> /// <param name="lineNumber">Line number</param> /// <returns>IBreakpoint or null if there is none for given line</returns> IBreakpoint GetBreakpoint(int lineNumber); /// <summary> /// Clears all breakpoints for the current document</summary> void ClearAllBreakpoints(); /// <summary> /// Toggles break point for the current line</summary> void ToggleBreakpoint(); /// <summary> /// Sets or unsets breakpoint for a given line</summary> /// <param name="lineNumber">The line to set or unset breakpoint</param> /// <param name="set">True to set break point, false to unset it</param> /// <remarks> /// Setting an already set breakpoint will not have any side effect. /// Unsetting an already unset breakpoint will not have any side effect. /// This method throws ArgumentOutOfRangeException if line number is out of range.</remarks> void Breakpoint(int lineNumber, bool set); /// <summary> /// Sets/unsets current-statement indicator for the specified line</summary> /// <param name="lineNumber">Line to set/unset statement indicator</param> /// <param name="set">True to set statement indicator, false to unset it</param> /// <remarks> /// Setting an already set current-statement indicator will not have any side effect. /// Unsetting an already unsetted current-statement indicator will not have any side effect. /// This method throws ArgumentOutOfRangeException if line number is out of range.</remarks> void CurrentStatement(int lineNumber, bool set); /// <summary> /// Gets or sets list of current-statement-indicators' line number</summary> IList<int> CurrentStatements { get; set; } /// <summary> /// Event that is raised after a new breakpoint added.</summary> event EventHandler<IBreakpointEventArgs> BreakpointAdded; /// <summary> /// Event that is raised after an existing breakpoint is removed.</summary> event EventHandler<IBreakpointEventArgs> BreakpointRemoved; /// <summary> /// Event that is raised before the break point is changed</summary> event EventHandler<BreakpointEventArgs> BreakpointChanging; /// <summary> /// Event that is raised after the mouse hovers over a token</summary> event EventHandler<MouseHoverOverTokenEventArgs> MouseHoveringOverToken; /// <summary> /// Gets the current language</summary> string CurrentLanguageId { get; } /// <summary> /// Returns the SyntaxEditor region for the given point</summary> /// <param name="location">Point</param> /// <returns>SyntaxEditor region</returns> /// <remarks> /// A mouse location can be passed, then the region under /// the mouse pointer is returned.</remarks> SyntaxEditorRegions GetRegion(Point location); /// <summary> /// Gets all the tokens for the current line</summary> /// <param name="lineNumber">Line number</param> /// <returns>An array of tokens</returns> Token[] GetTokens(int lineNumber); /// <summary> /// Returns line number from offset</summary> /// <param name="offset">Offset in the document</param> /// <returns>Line number of offset</returns> int GetLineFromOffset(int offset); /// <summary> /// Gets or sets the selected range of text in the document</summary> ISyntaxEditorTextRange SelectRange { get; set; } /// <summary> /// Gets a word text range starting at an offset in the document</summary> /// <param name="offset">Offset in the document</param> /// <returns>Word range based on offset</returns> ISyntaxEditorTextRange GetWordTextRange(int offset); /// <summary> /// Clears any bookmarks that have been placed due to a MarkAll</summary> void ClearSpanIndicatorMarks(); /// <summary> /// Computes the location of the specified client point into screen coordinates</summary> /// <param name="p"></param> /// <returns></returns> Point PointToScreen(Point p); /// <summary> /// Finds text instance based on options starting at offset</summary> /// <param name="options">Find/replace options</param> /// <param name="startOffset">Offset in the document at which to start find operation</param> /// <returns>Find/replace result set</returns> ISyntaxEditorFindReplaceResultSet Find(ISyntaxEditorFindReplaceOptions options, int startOffset); /// <summary> /// Finds all instances of text based on options in entire document</summary> /// <param name="options">Find/replace options</param> /// <returns>Find/replace result set</returns> ISyntaxEditorFindReplaceResultSet FindAll(ISyntaxEditorFindReplaceOptions options); /// <summary> /// Finds all instances of text based on options in text range</summary> /// <param name="options">Find/replace options</param> /// <param name="textRange">Text range to search</param> /// <returns>Find/replace result set</returns> ISyntaxEditorFindReplaceResultSet FindAll(ISyntaxEditorFindReplaceOptions options, ISyntaxEditorTextRange textRange); /// <summary> /// Marks all instances of text based on options in entire document</summary> /// <param name="options">Find/replace options</param> /// <returns>Find/replace result set</returns> ISyntaxEditorFindReplaceResultSet MarkAll(ISyntaxEditorFindReplaceOptions options); /// <summary> /// Marks all instances of text based on options in text range</summary> /// <param name="options">Find/replace options</param> /// <param name="textRange">Text range to search</param> /// <returns>Find/replace result set</returns> ISyntaxEditorFindReplaceResultSet MarkAll(ISyntaxEditorFindReplaceOptions options, ISyntaxEditorTextRange textRange); /// <summary> /// Replaces text based on options in previously found text indicated by a ISyntaxEditorFindReplaceResult</summary> /// <param name="options">Find/replace options</param> /// <param name="result">Previously found text in which to do the replace</param> /// <returns>Find/replace result set</returns> ISyntaxEditorFindReplaceResultSet Replace(ISyntaxEditorFindReplaceOptions options, ISyntaxEditorFindReplaceResult result); /// <summary> /// Replaces all text based on options in entire document</summary> /// <param name="options">Find/replace options</param> /// <returns>Find/replace result set</returns> ISyntaxEditorFindReplaceResultSet ReplaceAll(ISyntaxEditorFindReplaceOptions options); /// <summary> /// Replaces all text based on options in text range</summary> /// <param name="options">Find/replace options</param> /// <param name="textRange">Text range in which to replace text</param> /// <returns>Find/replace result set</returns> ISyntaxEditorFindReplaceResultSet ReplaceAll(ISyntaxEditorFindReplaceOptions options, ISyntaxEditorTextRange textRange); } /// <summary> /// Enum for type of search</summary> public enum SyntaxEditorFindReplaceSearchType { /// <summary> /// Search for text</summary> Normal, /// <summary> /// Search for regular expression</summary> RegularExpression, /// <summary> /// Search for text with wildcard(s)</summary> Wildcard, } /// <summary> /// Interface for find replace options</summary> public interface ISyntaxEditorFindReplaceOptions { /// <summary> /// Gets and sets whether to change the selection</summary> bool ChangeSelection { get; set; } /// <summary> /// Gets and sets the text to find</summary> string FindText { get; set; } /// <summary> /// Gets and sets whether to match case</summary> bool MatchCase { get; set; } /// <summary> /// Gets and sets whether to match whole words</summary> bool MatchWholeWord { get; set; } /// <summary> /// Gets whether text should be modifed</summary> bool Modified { get; } /// <summary> /// Gets and sets whether to replace text</summary> string ReplaceText { get; set; } /// <summary> /// Gets and sets whether to search in hidden text</summary> bool SearchHiddenText { get; set; } /// <summary> /// Gets and sets whether to search in selected text only</summary> bool SearchInSelection { get; set; } /// <summary> /// Gets and sets whether to search backwards</summary> bool SearchUp { get; set; } /// <summary> /// Gets and sets the search type</summary> SyntaxEditorFindReplaceSearchType SearchType { get; set; } /// <summary> /// Disposes of resources</summary> void Dispose(); } /// <summary> /// Interface for find replace result</summary> public interface ISyntaxEditorFindReplaceResult { /// <summary> /// Gets text found</summary> string Text { get; } /// <summary> /// Gets starting offset of found text in document</summary> int StartOffset { get; } /// <summary> /// Gets ending offset of found text in document</summary> int EndOffset { get; } } /// <summary> /// Interface for set of find replace results</summary> public interface ISyntaxEditorFindReplaceResultSet { /// <summary> /// Gets whether search went past end of document</summary> bool PastDocumentEnd { get; } /// <summary> /// Gets whether search went past end of starting offset</summary> bool PastSearchStartOffset { get; } /// <summary> /// Gets whether text replacement occurred</summary> bool ReplaceOccurred { get; } /// <summary> /// Gets result from array of find replace results</summary> /// <param name="index">Index of a find replace result</param> /// <returns>Find replace result at index</returns> ISyntaxEditorFindReplaceResult this[int index] { get; } /// <summary> /// Gets count of find replace results</summary> int Count { get; } /// <summary> /// Gets enumerator for collection of find replace results</summary> /// <returns>enumerator for collection of find replace results</returns> IEnumerator GetEnumerator(); } /// <summary> /// Interface for text range in document</summary> public interface ISyntaxEditorTextRange { /// <summary> /// Gets starting offset</summary> int StartOffset { get; } /// <summary> /// Gets ending offset</summary> int EndOffset { get; } } public class SyntaxEditorTextRange : ISyntaxEditorTextRange { /// <summary> /// Constructor for initializing from the internal type we're trying to avoid exposing /// </summary> /// <param name="textRange"></param> internal SyntaxEditorTextRange(ActiproSoftware.SyntaxEditor.TextRange textRange) : this(textRange.StartOffset, textRange.EndOffset) { } /// <summary> /// Constructor with starting and ending offset</summary> /// <param name="startOffset">Starting offset</param> /// <param name="endOffset">Ending offset</param> public SyntaxEditorTextRange(int startOffset, int endOffset) { StartOffset = startOffset; EndOffset = endOffset; } /// <summary> /// Gets starting offset</summary> public int StartOffset { get; private set; } /// <summary> /// Gets ending offset</summary> public int EndOffset { get; private set; } /// <summary> /// Internal method to convert back to the type we're avoiding exposing /// </summary> /// <returns></returns> internal ActiproSoftware.SyntaxEditor.TextRange ToTextRange() { return new ActiproSoftware.SyntaxEditor.TextRange(StartOffset, EndOffset); } } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace System.ServiceModel.Configuration { static class ConfigurationStrings { internal const string AcknowledgementInterval = "acknowledgementInterval"; internal const string ActivityTracing = "activityTracing"; internal const string Add = "add"; internal const string AdditionalRequestParameters = "additionalRequestParameters"; internal const string Address = "address"; internal const string AlgorithmSuite = "algorithmSuite"; internal const string AllowAnonymousLogons = "allowAnonymousLogons"; internal const string AllowCookies = "allowCookies"; internal const string AllowedAudienceUris = "allowedAudienceUris"; internal const string AllowedAudienceUri = "allowedAudienceUri"; internal const string AllowedImpersonationLevel = "allowedImpersonationLevel"; internal const string AllowInsecureTransport = "allowInsecureTransport"; internal const string AllowNtlm = "allowNtlm"; internal const string AllowSerializedSigningTokenOnReply = "allowSerializedSigningTokenOnReply"; internal const string AllowUntrustedRsaIssuers = "allowUntrustedRsaIssuers"; internal const string AlternativeIssuedTokenParameters = "alternativeIssuedTokenParameters"; internal const string ApplicationContainerSettings = "applicationContainerSettings"; internal const string AspNetCompatibilityEnabled = "aspNetCompatibilityEnabled"; internal const string AsynchronousSendEnabled = "asynchronousSendEnabled"; internal const string AudienceUriMode = "audienceUriMode"; internal const string AuditLogLocation = "auditLogLocation"; internal const string Authentication = "authentication"; internal const string AuthenticationMode = "authenticationMode"; internal const string AuthenticationScheme = "authenticationScheme"; internal const string AuthenticationSchemes = "authenticationSchemes"; internal const string AuthorizationPolicies = "authorizationPolicies"; internal const string BaseAddress = "baseAddress"; internal const string BaseAddresses = "baseAddresses"; internal const string BaseAddressPrefixFilters = "baseAddressPrefixFilters"; internal const string Basic128 = "Basic128"; internal const string Basic192 = "Basic192"; internal const string Basic256 = "Basic256"; internal const string Basic128Rsa15 = "Basic128Rsa15"; internal const string Basic192Rsa15 = "Basic192Rsa15"; internal const string Basic256Rsa15 = "Basic256Rsa15"; internal const string Basic128Sha256 = "Basic128Sha256"; internal const string Basic192Sha256 = "Basic192Sha256"; internal const string Basic256Sha256 = "Basic256Sha256"; internal const string Basic128Sha256Rsa15 = "Basic128Sha256Rsa15"; internal const string Basic192Sha256Rsa15 = "Basic192Sha256Rsa15"; internal const string Basic256Sha256Rsa15 = "Basic256Sha256Rsa15"; internal const string BasicHttpBindingCollectionElementName = "basicHttpBinding"; internal const string BasicHttpsBindingCollectionElementName = "basicHttpsBinding"; internal const string Behavior = "behavior"; internal const string BehaviorConfiguration = "behaviorConfiguration"; internal const string BehaviorExtensions = "behaviorExtensions"; internal const string BehaviorsSectionName = "behaviors"; internal const string BinaryMessageEncodingSectionName = "binaryMessageEncoding"; internal const string Binding = "binding"; internal const string BindingConfiguration = "bindingConfiguration"; internal const string BindingElementExtensions = "bindingElementExtensions"; internal const string BindingExtensions = "bindingExtensions"; internal const string BindingName = "bindingName"; internal const string BindingNamespace = "bindingNamespace"; internal const string BindingsSectionGroupName = "bindings"; internal const string BypassProxyOnLocal = "bypassProxyOnLocal"; internal const string CacheCookies = "cacheCookies"; internal const string CachedLogonTokenLifetime = "cachedLogonTokenLifetime"; internal const string CacheIssuedTokens = "cacheIssuedTokens"; internal const string CacheLogonTokens = "cacheLogonTokens"; internal const string CallbackDebugSectionName = "callbackDebug"; internal const string CallbackTimeouts = "callbackTimeouts"; internal const string CanRenewSecurityContextToken = "canRenewSecurityContextToken"; internal const string Certificate = "certificate"; internal const string CertificateReference = "certificateReference"; internal const string CertificateValidationMode = "certificateValidationMode"; internal const string Channel = "channel"; internal const string ChannelInitializationTimeout = "channelInitializationTimeout"; internal const string ChannelPoolSettings = "channelPoolSettings"; internal const string ClaimType = "claimType"; internal const string ClaimTypeRequirements = "claimTypeRequirements"; internal const string Clear = "clear"; internal const string ClientBaseAddress = "clientBaseAddress"; internal const string ClientCallbackAddressName = "clientCallbackAddress"; internal const string ClientCertificate = "clientCertificate"; internal const string ClientCredentials = "clientCredentials"; internal const string ClientCredentialType = "clientCredentialType"; internal const string ClientSectionName = "client"; internal const string ClientViaSectionName = "clientVia"; internal const string CloseIdleServicesAtLowMemory = "closeIdleServicesAtLowMemory"; internal const string CloseTimeout = "closeTimeout"; internal const string ComContract = "comContract"; internal const string ComContractName = "name"; internal const string ComContractNamespace = "namespace"; internal const string ComContractsSectionName = "comContracts"; internal const string ComMethod = "exposedMethod"; internal const string ComMethodCollection = "exposedMethods"; internal const string CommonBehaviorsSectionName = "commonBehaviors"; internal const string ComPersistableTypes = "persistableTypes"; internal const string CompositeDuplexSectionName = "compositeDuplex"; internal const string CompressionFormat = "compressionFormat"; internal const string ComSessionRequired = "requiresSession"; internal const string ComUdt = "userDefinedType"; internal const string ComUdtCollection = "userDefinedTypes"; internal const string ConnectionBufferSize = "connectionBufferSize"; internal const string ConnectionPoolSettings = "connectionPoolSettings"; internal const string Contract = "contract"; internal const string Cookie = "Cookie"; internal const string CookieRenewalThresholdPercentage = "cookieRenewalThresholdPercentage"; internal const string CreateNotificationOnConnection = "createNotificationOnConnection"; internal const string Custom = "custom"; internal const string CustomBindingCollectionElementName = "customBinding"; internal const string CustomCertificateValidatorType = "customCertificateValidatorType"; internal const string CustomDeadLetterQueue = "customDeadLetterQueue"; internal const string CustomUserNamePasswordValidatorType = "customUserNamePasswordValidatorType"; internal const string DataContractSerializerSectionName = "dataContractSerializer"; internal const string DeadLetterQueue = "deadLetterQueue"; internal const string DecompressionEnabled = "decompressionEnabled"; internal const string Default = "Default"; internal const string DefaultAlgorithmSuite = "defaultAlgorithmSuite"; internal const string DefaultCertificate = "defaultCertificate"; internal const string DefaultCollectionName = ""; // String.Empty internal const string DefaultKeyEntropyMode = "defaultKeyEntropyMode"; internal const string DefaultMessageSecurityVersion = "defaultMessageSecurityVersion"; internal const string DefaultName = ""; internal const string DefaultPorts = "defaultPorts"; internal const string DetectReplays = "detectReplays"; internal const string DiagnosticSectionName = "diagnostics"; internal const string DisablePayloadMasking = "disablePayloadMasking"; internal const string Dns = "dns"; internal const string Durable = "durable"; internal const string Enabled = "enabled"; internal const string EnableUnsecuredResponse = "enableUnsecuredResponse"; internal const string EncodedValue = "encodedValue"; internal const string Endpoint = "endpoint"; internal const string EndpointBehaviors = "endpointBehaviors"; internal const string EndpointConfiguration = "endpointConfiguration"; internal const string EndpointExtensions = "endpointExtensions"; internal const string EndToEndTracing = "endToEndTracing"; internal const string EstablishSecurityContext = "establishSecurityContext"; internal const string EtwProviderId = "etwProviderId"; internal const string ExactlyOnce = "exactlyOnce"; internal const string ExposedMethod = "exposedMethod"; internal const string ExtendedProtectionPolicy = "extendedProtectionPolicy"; internal const string Extension = "extension"; internal const string Extensions = "extensions"; internal const string ExternalMetadataLocation = "externalMetadataLocation"; internal const string Factory = "factory"; internal const string Filter = "filter"; internal const string Filters = "filters"; internal const string FindValue = "findValue"; internal const string FlowControlEnabled = "flowControlEnabled"; internal const string GroupName = "groupName"; internal const string Handler = "handler"; internal const string Handlers = "handlers"; internal const string Header = "header"; internal const string Headers = "headers"; internal const string Host = "host"; internal const string HostNameComparisonMode = "hostNameComparisonMode"; internal const string HttpDigest = "httpDigest"; internal const string HttpGetEnabled = "httpGetEnabled"; internal const string HttpGetUrl = "httpGetUrl"; internal const string HttpsGetEnabled = "httpsGetEnabled"; internal const string HttpsGetUrl = "httpsGetUrl"; internal const string HttpHelpPageEnabled = "httpHelpPageEnabled"; internal const string HttpHelpPageUrl = "httpHelpPageUrl"; internal const string HttpsHelpPageEnabled = "httpsHelpPageEnabled"; internal const string HttpsHelpPageUrl = "httpsHelpPageUrl"; internal const string HttpHelpPageBinding = "httpHelpPageBinding"; internal const string HttpHelpPageBindingConfiguration = "httpHelpPageBindingConfiguration"; internal const string HttpsHelpPageBinding = "httpsHelpPageBinding"; internal const string HttpsHelpPageBindingConfiguration = "httpsHelpPageBindingConfiguration"; internal const string HttpGetBinding = "httpGetBinding"; internal const string HttpGetBindingConfiguration = "httpGetBindingConfiguration"; internal const string HttpsGetBinding = "httpsGetBinding"; internal const string HttpsGetBindingConfiguration = "httpsGetBindingConfiguration"; internal const string MexHttpBindingCollectionElementName = "mexHttpBinding"; internal const string HttpsTransportSectionName = "httpsTransport"; internal const string HttpTransportSectionName = "httpTransport"; internal const string MexHttpsBindingCollectionElementName = "mexHttpsBinding"; internal const string ID = "ID"; internal const string Identity = "identity"; internal const string IdentityConfiguration = "identityConfiguration"; internal const string IdleTimeout = "idleTimeout"; internal const string IgnoreExtensionDataObject = "ignoreExtensionDataObject"; internal const string ImpersonateCallerForAllOperations = "impersonateCallerForAllOperations"; internal const string ImpersonateOnSerializingReply = "impersonateOnSerializingReply"; internal const string ImpersonationLevel = "impersonationLevel"; internal const string InactivityTimeout = "inactivityTimeout"; internal const string IncludeExceptionDetailInFaults = "includeExceptionDetailInFaults"; internal const string IncludeTimestamp = "includeTimestamp"; internal const string IncludeWindowsGroups = "includeWindowsGroups"; internal const string IsChainIncluded = "isChainIncluded"; internal const string IsOptional = "isOptional"; internal const string IssuedCookieLifetime = "issuedCookieLifetime"; internal const string IssuedKeyType = "issuedKeyType"; internal const string IssuedToken = "issuedToken"; internal const string IssuedTokenAuthentication = "issuedTokenAuthentication"; internal const string IssuedTokenParameters = "issuedTokenParameters"; internal const string IssuedTokenRenewalThresholdPercentage = "issuedTokenRenewalThresholdPercentage"; internal const string IssuedTokenType = "issuedTokenType"; internal const string Issuer = "issuer"; internal const string IssuerAddress = "issuerAddress"; internal const string IssuerChannelBehaviors = "issuerChannelBehaviors"; internal const string IssuerMetadata = "issuerMetadata"; internal const string IsSystemEndpoint = "isSystemEndpoint"; internal const string KeepAliveEnabled = "keepAliveEnabled"; internal const string KeepAliveInterval = "keepAliveInterval"; internal const string KeyEntropyMode = "keyEntropyMode"; internal const string KeySize = "keySize"; internal const string KeyType = "keyType"; internal const string Kind = "kind"; internal const string KnownCertificates = "knownCertificates"; internal const string LeaseTimeout = "leaseTimeout"; internal const string ListenBacklog = "listenBacklog"; internal const string ListenIPAddress = "listenIPAddress"; internal const string ListenUri = "listenUri"; internal const string ListenUriMode = "listenUriMode"; internal const string LocalClientSettings = "localClientSettings"; internal const string LocalIssuer = "localIssuer"; internal const string LocalIssuerChannelBehaviors = "localIssuerChannelBehaviors"; internal const string LocalServiceSettings = "localServiceSettings"; internal const string LogEntireMessage = "logEntireMessage"; internal const string LogKnownPii = "logKnownPii"; internal const string LogMalformedMessages = "logMalformedMessages"; internal const string LogMessagesAtServiceLevel = "logMessagesAtServiceLevel"; internal const string LogMessagesAtTransportLevel = "logMessagesAtTransportLevel"; internal const string ManualAddressing = "manualAddressing"; internal const string MapClientCertificateToWindowsAccount = "mapClientCertificateToWindowsAccount"; internal const string MaxAcceptedChannels = "maxAcceptedChannels"; internal const string MaxArrayLength = "maxArrayLength"; internal const string MaxBatchSize = "maxBatchSize"; internal const string MaxBufferPoolSize = "maxBufferPoolSize"; internal const string MaxBufferSize = "maxBufferSize"; internal const string MaxBytesPerRead = "maxBytesPerRead"; internal const string MaxCachedCookies = "maxCachedCookies"; internal const string MaxCachedLogonTokens = "maxCachedLogonTokens"; internal const string MaxClockSkew = "maxClockSkew"; internal const string MaxConcurrentCalls = "maxConcurrentCalls"; internal const string MaxConcurrentInstances = "maxConcurrentInstances"; internal const string MaxConcurrentSessions = "maxConcurrentSessions"; internal const string MaxConnections = "maxConnections"; internal const string MaxCookieCachingTime = "maxCookieCachingTime"; internal const string MaxDepth = "maxDepth"; internal const string MaxIssuedTokenCachingTime = "maxIssuedTokenCachingTime"; internal const string MaxItemsInObjectGraph = "maxItemsInObjectGraph"; internal const string MaxMessagesToLog = "maxMessagesToLog"; internal const string MaxNameTableCharCount = "maxNameTableCharCount"; internal const string MaxOutboundChannelsPerEndpoint = "maxOutboundChannelsPerEndpoint"; internal const string MaxOutboundConnectionsPerEndpoint = "maxOutboundConnectionsPerEndpoint"; internal const string MaxOutputDelay = "maxOutputDelay"; internal const string MaxPendingAccepts = "maxPendingAccepts"; internal const string MaxPendingChannels = "maxPendingChannels"; internal const string MaxPendingConnections = "maxPendingConnections"; internal const string MaxPendingReceives = "maxPendingReceives"; internal const string MaxPendingSessions = "maxPendingSessions"; internal const string MaxPoolSize = "maxPoolSize"; internal const string MaxReadPoolSize = "maxReadPoolSize"; internal const string MaxReceivedMessageSize = "maxReceivedMessageSize"; internal const string MaxRetryCount = "maxRetryCount"; internal const string MaxRetryCycles = "maxRetryCycles"; internal const string MaxSessionSize = "maxSessionSize"; internal const string MaxSizeOfMessageToLog = "maxSizeOfMessageToLog"; internal const string MaxStatefulNegotiations = "maxStatefulNegotiations"; internal const string MaxStringContentLength = "maxStringContentLength"; internal const string MaxTransferWindowSize = "maxTransferWindowSize"; internal const string MaxWritePoolSize = "maxWritePoolSize"; internal const string MembershipProviderName = "membershipProviderName"; internal const string Message = "message"; internal const string MessageAuthenticationAuditLevel = "messageAuthenticationAuditLevel"; internal const string MessageEncoding = "messageEncoding"; internal const string MessageFlowTracing = "messageFlowTracing"; internal const string MessageHandlerFactory = "messageHandlerFactory"; internal const string MessageLogging = "messageLogging"; internal const string MessageProtectionOrder = "messageProtectionOrder"; internal const string MessageSecurityVersion = "messageSecurityVersion"; internal const string MessageSenderAuthentication = "messageSenderAuthentication"; internal const string MessageVersion = "messageVersion"; internal const string Metadata = "metadata"; internal const string MinFreeMemoryPercentageToActivateService = "minFreeMemoryPercentageToActivateService"; internal const string Mode = "mode"; internal const string MsmqAuthenticationMode = "msmqAuthenticationMode"; internal const string MsmqEncryptionAlgorithm = "msmqEncryptionAlgorithm"; internal const string MsmqIntegrationBindingCollectionElementName = "msmqIntegrationBinding"; internal const string MsmqIntegrationSectionName = "msmqIntegration"; internal const string MsmqProtectionLevel = "msmqProtectionLevel"; internal const string MsmqSecureHashAlgorithm = "msmqSecureHashAlgorithm"; internal const string MsmqTransportSectionName = "msmqTransport"; internal const string MsmqTransportSecurity = "msmqTransportSecurity"; internal const string MtomMessageEncodingSectionName = "mtomMessageEncoding"; internal const string MultipleSiteBindingsEnabled = "multipleSiteBindingsEnabled"; internal const string Name = "name"; internal const string NamedPipeTransportSectionName = "namedPipeTransport"; internal const string NegotiateServiceCredential = "negotiateServiceCredential"; internal const string NegotiationTimeout = "negotiationTimeout"; internal const string NetMsmqBindingCollectionElementName = "netMsmqBinding"; internal const string NetNamedPipeBindingCollectionElementName = "netNamedPipeBinding"; internal const string MexNamedPipeBindingCollectionElementName = "mexNamedPipeBinding"; internal const string NetPeerTcpBindingCollectionElementName = "netPeerTcpBinding"; internal const string NetTcpBindingCollectionElementName = "netTcpBinding"; internal const string NetHttpBindingCollectionElementName = "netHttpBinding"; internal const string NetHttpsBindingCollectionElementName = "netHttpsBinding"; internal const string NodeQuota = "nodeQuota"; internal const string None = "None"; internal const string OleTransactions = "OleTransactions"; internal const string OneWaySectionName = "oneWay"; internal const string MexTcpBindingCollectionElementName = "mexTcpBinding"; internal const string MexStandardEndpointCollectionElementName = "mexEndpoint"; internal const string OpenTimeout = "openTimeout"; internal const string Ordered = "ordered"; internal const string PackageFullName = "packageFullName"; internal const string PacketRoutable = "packetRoutable"; internal const string Peer = "peer"; internal const string PeerAuthentication = "peerAuthentication"; internal const string PeerResolver = "resolver"; internal const string PeerResolverType = "resolverType"; internal const string PeerTransportCredentialType = "credentialType"; internal const string PeerTransportSectionName = "peerTransport"; internal const string PerformanceCounters = "performanceCounters"; internal const string PipeSettings = "pipeSettings"; internal const string PnrpPeerResolverSectionName = "pnrpPeerResolver"; internal const string Policy12 = "Policy12"; internal const string Policy15 = "Policy15"; internal const string PolicyImporters = "policyImporters"; internal const string PolicyType = "policyType"; internal const string PolicyVersion = "policyVersion"; internal const string Port = "port"; internal const string PortSharingEnabled = "portSharingEnabled"; internal const string Prefix = "prefix"; internal const string PrincipalPermissionMode = "principalPermissionMode"; internal const string PrivacyNoticeAt = "privacyNoticeAt"; internal const string PrivacyNoticeSectionName = "privacyNoticeAt"; internal const string PrivacyNoticeVersion = "privacyNoticeVersion"; internal const string PropagateActivity = "propagateActivity"; internal const string ProtectionLevel = "protectionLevel"; internal const string ProtectTokens = "protectTokens"; internal const string ProtocolMappingSectionName = "protocolMapping"; internal const string ProxyAddress = "proxyAddress"; internal const string ProxyAuthenticationScheme = "proxyAuthenticationScheme"; internal const string ProxyCredentialType = "proxyCredentialType"; internal const string QueueTransferProtocol = "queueTransferProtocol"; internal const string ReaderQuotas = "readerQuotas"; internal const string Realm = "realm"; internal const string ReceiveContextEnabled = "receiveContextEnabled"; internal const string ReceiveErrorHandling = "receiveErrorHandling"; internal const string ReceiveRetryCount = "receiveRetryCount"; internal const string ReceiveTimeout = "receiveTimeout"; internal const string ReconnectTransportOnFailure = "reconnectTransportOnFailure"; internal const string ReferralPolicy = "referralPolicy"; internal const string ReliableMessagingVersion = "reliableMessagingVersion"; internal const string RelativeAddress = "relativeAddress"; internal const string ReliableSession = "reliableSession"; internal const string ReliableSessionSectionName = "reliableSession"; internal const string Remove = "remove"; internal const string ReplayCacheSize = "replayCacheSize"; internal const string ReplayWindow = "replayWindow"; internal const string RequestInitializationTimeout = "requestInitializationTimeout"; internal const string RequireClientCertificate = "requireClientCertificate"; internal const string RequireDerivedKeys = "requireDerivedKeys"; internal const string RequireSecurityContextCancellation = "requireSecurityContextCancellation"; internal const string RequireSignatureConfirmation = "requireSignatureConfirmation"; internal const string RetryCycleDelay = "retryCycleDelay"; internal const string RevocationMode = "revocationMode"; internal const string RoleProviderName = "roleProviderName"; internal const string Rsa = "rsa"; internal const string SamlSerializerType = "samlSerializerType"; internal const string Scheme = "scheme"; internal const string ScopedCertificates = "scopedCertificates"; internal const string SectionGroupName = "system.serviceModel"; internal const string SecureConversationAuthentication = "secureConversationAuthentication"; internal const string SecureConversationBootstrap = "secureConversationBootstrap"; internal const string Security = "security"; internal const string SecurityHeaderLayout = "securityHeaderLayout"; internal const string SecuritySectionName = "security"; internal const string SecurityStateEncoderType = "securityStateEncoderType"; internal const string SendTimeout = "sendTimeout"; internal const string SerializationFormat = "serializationFormat"; internal const string Service = "service"; internal const string ServiceActivations = "serviceActivations"; internal const string ServiceAuthenticationManagerSectionName = "serviceAuthenticationManager"; internal const string ServiceAuthenticationManagerType = "serviceAuthenticationManagerType"; internal const string ServiceAuthorizationAuditLevel = "serviceAuthorizationAuditLevel"; internal const string ServiceAuthorizationManagerType = "serviceAuthorizationManagerType"; internal const string ServiceAuthorizationSectionName = "serviceAuthorization"; internal const string ServiceBehaviors = "serviceBehaviors"; internal const string ServiceCertificate = "serviceCertificate"; internal const string ServiceCredentials = "serviceCredentials"; internal const string ServiceDebugSectionName = "serviceDebug"; internal const string ServiceHostingEnvironmentSectionName = "serviceHostingEnvironment"; internal const string ServiceMetadataPublishingSectionName = "serviceMetadata"; internal const string ServicePrincipalName = "servicePrincipalName"; internal const string ServiceSecurityAuditSectionName = "serviceSecurityAudit"; internal const string ServicesSectionName = "services"; internal const string ServiceThrottlingSectionName = "serviceThrottling"; internal const string ServiceTimeouts = "serviceTimeouts"; internal const string Session = "Session"; internal const string SessionIdAttribute = "sessionId"; internal const string SessionKeyRenewalInterval = "sessionKeyRenewalInterval"; internal const string SessionKeyRolloverInterval = "sessionKeyRolloverInterval"; internal const string Soap11 = "Soap11"; internal const string Soap11WSAddressing10 = "Soap11WSAddressing10"; internal const string Soap11WSAddressingAugust2004 = "Soap11WSAddressingAugust2004"; internal const string Soap12 = "Soap12"; internal const string Soap12WSAddressing10 = "Soap12WSAddressing10"; internal const string Soap12WSAddressingAugust2004 = "Soap12WSAddressingAugust2004"; internal const string SslCertificateAuthentication = "sslCertificateAuthentication"; internal const string SslProtocols = "sslProtocols"; internal const string SslStreamSecuritySectionName = "sslStreamSecurity"; internal const string StandardEndpoint = "standardEndpoint"; internal const string StandardEndpointsSectionName = "standardEndpoints"; internal const string StoreLocation = "storeLocation"; internal const string StoreName = "storeName"; internal const string SubProtocol = "subProtocol"; internal const string SupportInteractive = "supportInteractive"; internal const string SuppressAuditFailure = "suppressAuditFailure"; internal const string SynchronousReceiveSectionName = "synchronousReceive"; internal const string DispatcherSynchronizationSectionName = "dispatcherSynchronization"; internal const string TargetUri = "targetUri"; internal const string TcpTransportSectionName = "tcpTransport"; internal const string TeredoEnabled = "teredoEnabled"; internal const string TextEncoding = "textEncoding"; internal const string TextMessageEncodingSectionName = "textMessageEncoding"; internal const string Timeouts = "timeouts"; internal const string TimeSpanInfinite = "-00:00:00.001"; internal const string TimeSpanOneTick = "00:00:00.0000001"; internal const string TimeSpanZero = "00:00:00"; internal const string TimestampValidityDuration = "timestampValidityDuration"; internal const string TimeToLive = "timeToLive"; internal const string TokenRequestParameters = "tokenRequestParameters"; internal const string TokenType = "tokenType"; internal const string TransactedBatchingSectionName = "transactedBatching"; internal const string TransactionFlow = "transactionFlow"; internal const string TransactionFlowSectionName = "transactionFlow"; internal const string TransactionProtocol = "transactionProtocol"; internal const string TransactionTimeout = "transactionTimeout"; internal const string TransactionAllowWildcardAction = "allowWildcardAction"; internal const string TransferMode = "transferMode"; internal const string Transport = "transport"; internal const string TransportConfigurationType = "transportConfigurationType"; internal const string TransportUsage = "transportUsage"; internal const string TripleDes = "TripleDes"; internal const string TripleDesRsa15 = "TripleDesRsa15"; internal const string TripleDesSha256 = "TripleDesSha256"; internal const string TripleDesSha256Rsa15 = "TripleDesSha256Rsa15"; internal const string TrustedStoreLocation = "trustedStoreLocation"; internal const string Type = "type"; internal const string TypeDefID = "typeDefID"; internal const string TypeLibID = "typeLibID"; internal const string TypeLibVersion = "typeLibVersion"; internal const string UdpBindingCollectionElementName = "udpBinding"; internal const string UdpBindingCollectionElementType = "System.ServiceModel.Configuration.UdpBindingCollectionElement, System.ServiceModel.Channels, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; internal const string UdpTransportElementType = "System.ServiceModel.Configuration.UdpTransportElement, System.ServiceModel.Channels, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; internal const string UdpTransportImporterType = "System.ServiceModel.Channels.UdpTransportImporter, System.ServiceModel.Channels, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; internal const string UdpTransportSectionName = "udpTransport"; internal const string UnrecognizedPolicyAssertionSectionName = "unrecognizedPolicyAssertions"; internal const string UnsafeConnectionNtlmAuthentication = "unsafeConnectionNtlmAuthentication"; internal const string Url = "url"; internal const string UseActiveDirectory = "useActiveDirectory"; internal const string UseDefaultWebProxy = "useDefaultWebProxy"; internal const string UseIdentityConfiguration = "useIdentityConfiguration"; internal const string UseManagedPresentationSectionName = "useManagedPresentation"; internal const string UseMsmqTracing = "useMsmqTracing"; internal const string UserNameAuthentication = "userNameAuthentication"; internal const string UserNamePasswordValidationMode = "userNamePasswordValidationMode"; internal const string UserPrincipalName = "userPrincipalName"; internal const string UseRequestHeadersForMetadataAddress = "useRequestHeadersForMetadataAddress"; internal const string UseSourceJournal = "useSourceJournal"; internal const string UseStrTransform = "useStrTransform"; internal const string ValidityDuration = "validityDuration"; internal const string Value = "value"; internal const string Version = "version"; internal const string ViaUri = "viaUri"; internal const string WebSocketSettingsSectionName = "webSocketSettings"; internal const string Windows = "windows"; internal const string WindowsAuthentication = "windowsAuthentication"; internal const string WindowsStreamSecuritySectionName = "windowsStreamSecurity"; internal const string WmiProviderEnabled = "wmiProviderEnabled"; internal const string WriteEncoding = "writeEncoding"; internal const string WSAtomicTransactionOctober2004 = "WSAtomicTransactionOctober2004"; internal const string WSAtomicTransaction11 = "WSAtomicTransaction11"; internal const string WsdlImporters = "wsdlImporters"; internal const string WSDualHttpBindingCollectionElementName = "wsDualHttpBinding"; internal const string WSFederationHttpBindingCollectionElementName = "wsFederationHttpBinding"; internal const string WS2007FederationHttpBindingCollectionElementName = "ws2007FederationHttpBinding"; internal const string WS2007HttpBindingCollectionElementName = "ws2007HttpBinding"; internal const string WSHttpBindingCollectionElementName = "wsHttpBinding"; internal const string WSReliableMessaging11 = "WSReliableMessaging11"; internal const string WSReliableMessagingFebruary2005 = "WSReliableMessagingFebruary2005"; internal const string WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10 = "WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"; internal const string WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11 = "WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11"; internal const string WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10 = "WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"; internal const string WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 = "WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"; internal const string WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12 = "WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12"; internal const string WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 = "WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"; internal const string X509FindType = "x509FindType"; internal const string XmlElement = "xmlElement"; internal static string BehaviorsSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.BehaviorsSectionName); } } internal static string BindingsSectionGroupPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.BindingsSectionGroupName); } } internal static string ClientSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.ClientSectionName); } } internal static string ComContractsSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.ComContractsSectionName); } } internal static string CommonBehaviorsSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.CommonBehaviorsSectionName); } } internal static string DiagnosticSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.DiagnosticSectionName); } } internal static string ExtensionsSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.Extensions); } } internal static string ProtocolMappingSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.ProtocolMappingSectionName); } } internal static string ServiceHostingEnvironmentSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.ServiceHostingEnvironmentSectionName); } } internal static string ServicesSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.ServicesSectionName); } } internal static string StandardEndpointsSectionPath { get { return ConfigurationHelpers.GetSectionPath(ConfigurationStrings.StandardEndpointsSectionName); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace VehicleStatisticsApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using ProtoBuf; namespace FileTape.Appenders { public class BufferedAppender: IAppender,IDisposable { private readonly IAppender _underlingAppender; private readonly int? _bufferByteSizeLimit; private readonly int? _bufferRecordCountLimit; private readonly int? _bufferChunkCountLimit; private readonly Action<Exception> _onError; private readonly bool _backGround; private readonly ConcurrentQueue<BufferedItem> _bufferedItems = new ConcurrentQueue<BufferedItem>(); private int _isRunned = 0; private long _stamp = 0; public BufferedAppender( IAppender underlingAppender, int? bufferByteSizeLimit, int? bufferRecordCountLimit, int? bufferChunkCountLimit, Action<Exception> onError, bool backGround=true) { _underlingAppender = underlingAppender; _bufferByteSizeLimit = bufferByteSizeLimit; _bufferRecordCountLimit = bufferRecordCountLimit; _bufferChunkCountLimit = bufferChunkCountLimit; _onError = onError; _backGround = backGround; if ((bufferByteSizeLimit ==null)&& (bufferRecordCountLimit ==null)&& (bufferChunkCountLimit == null)) { throw new ArgumentException("You should specify at least one limit"); } } public void Flush() { var spin = new SpinWait(); while (true) { var allocated = WithStampGuard(TryAllocateWriteLoop); if (allocated.Result) { StartWriteLoopSync(true); return; } spin.SpinOnce(); } } public void Append(IReadOnlyCollection<byte[]> records, byte[] customProperties = null) { var spin = new SpinWait(); _bufferedItems.Enqueue(new BufferedItem(records,customProperties)); while (true) { var allocated = WithStampGuard(TryAllocateWriteLoop); if (allocated.Result) { if (_backGround) { StartWriteLoopAsync(); } else { StartWriteLoopSync(false); } return; } if (allocated.StapmNotChanged) { return; } spin.SpinOnce(); } } public void Dispose() { Flush(); } public static byte[] SerializeCustomPropertiesArray(byte[][] customProperties) { using (var memoryStream = new MemoryStream()) { Serializer.Serialize(memoryStream, customProperties); return memoryStream.ToArray(); } } public static byte[][] DeserializeCutomPropertiesArray(byte[] customProperties) { using (var s = new MemoryStream(customProperties)) { return Serializer.Deserialize<byte[][]>(s); } } private GuardResult<T> WithStampGuard<T>(Func<T> a) { var t1 = Interlocked.Read(ref _stamp); T res; long t2; try { res = a(); } finally { t2 = Interlocked.CompareExchange(ref _stamp,t1+1,t1); } return new GuardResult<T> { Result = res, StapmNotChanged = t2 == t1 }; } private void StartWriteLoopAsync() { Task.Run( () => { try { StartWriteLoopSync(false); } catch (Exception) { } }); } private void StartWriteLoopSync(bool flush) { var spinWait = new SpinWait(); while (true) { if (NeedWrite(flush)) { try { WriteBuffer(); } catch (Exception ex) { try { _onError(ex); } catch (Exception) { ReleaseWriteLoop(); } throw; } } else { var res = WithStampGuard<object>( () => { ReleaseWriteLoop(); return null; } ); if (res.StapmNotChanged) { return; } var loopRealocated = TryAllocateWriteLoop(); if (!loopRealocated) { return; } spinWait.SpinOnce(); } } } private bool NeedWrite(bool flush) { if (flush && _bufferedItems.Count > 0) { return true; } if (_bufferChunkCountLimit.HasValue && _bufferChunkCountLimit <= _bufferedItems.Count) { return true; } if (_bufferRecordCountLimit.HasValue && _bufferRecordCountLimit <= _bufferedItems.Sum(i => i.Records.Count)) { return true; } if (_bufferByteSizeLimit.HasValue && _bufferByteSizeLimit <= _bufferedItems.Sum(i => i.TotalLength)) { return true; } return false; } private bool TryAllocateWriteLoop() { return Interlocked.CompareExchange(ref _isRunned, 1, 0) == 0; } private void ReleaseWriteLoop() { Interlocked.Exchange(ref _isRunned, 0); } private struct GuardResult<T> { public bool StapmNotChanged; public T Result; } private void WriteBuffer() { List<BufferedItem> items =new List<BufferedItem>(); BufferedItem item; while (_bufferedItems.TryDequeue(out item)) { items.Add(item); } if (items.Any()) { var customProperties = items .Select(i => i.CustomProperties) .Where(i => i !=null) .ToArray(); var records = items.SelectMany(i => i.Records) .ToArray(); _underlingAppender.Append(records, SerializeCustomPropertiesArray(customProperties)); } } private class BufferedItem { public IReadOnlyCollection<byte[]> Records { get; private set; } public byte[] CustomProperties { get; private set; } public long TotalLength { get; private set; } public BufferedItem(IReadOnlyCollection<byte[]> records, byte[] customProperties) { Records = records; CustomProperties = customProperties; TotalLength =records.Sum(i => (long)i.Length) + ((customProperties!=null)?(long)customProperties.Length:0); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: money/cards/card_merchant.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 HOLMS.Types.Money.Cards { /// <summary>Holder for reflection information generated from money/cards/card_merchant.proto</summary> public static partial class CardMerchantReflection { #region Descriptor /// <summary>File descriptor for money/cards/card_merchant.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CardMerchantReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ch9tb25leS9jYXJkcy9jYXJkX21lcmNoYW50LnByb3RvEhdob2xtcy50eXBl", "cy5tb25leS5jYXJkcxopbW9uZXkvY2FyZHMvY2FyZF9tZXJjaGFudF9pbmRp", "Y2F0b3IucHJvdG8aKm1vbmV5L2NhcmRzL2NhcmRfcHJvY2Vzc29yX2luZGlj", "YXRvci5wcm90byK6AwoMQ2FyZE1lcmNoYW50EkEKCWVudGl0eV9pZBgBIAEo", "CzIuLmhvbG1zLnR5cGVzLm1vbmV5LmNhcmRzLkNhcmRNZXJjaGFudEluZGlj", "YXRvchIMCgRuYW1lGAIgASgJEkcKDmNhcmRfcHJvY2Vzc29yGAMgASgOMi8u", "aG9sbXMudHlwZXMubW9uZXkuY2FyZHMuQ2FyZFByb2Nlc3NvckluZGljYXRv", "chIWCg5jYXJkX2FncmVlbWVudBgEIAEoCRISCgpsaWNlbnNlX2lkGAUgASgF", "Eg8KB3NpdGVfaWQYBiABKAUSEQoJZGV2aWNlX2lkGAcgASgFEhAKCHVzZXJu", "YW1lGAggASgJEhAKCHBhc3N3b3JkGAkgASgJEhUKDXNlcnZpY2VfdV9yX2kY", "CiABKAkSHQoVZGVidWdfbG9nZ2luZ19lbmFibGVkGAsgASgIEhwKFHBvcnRp", "Y29fZGV2ZWxvcGVyX2lkGAwgASgJEh4KFnBvcnRpY29fdmVyc2lvbl9udW1i", "ZXIYDSABKAkSKAogc3VwcHJlc3NfYXV0aG9yaXphdGlvbnNfaW5fZm9saW8Y", "DiABKAhCJ1oLbW9uZXkvY2FyZHOqAhdIT0xNUy5UeXBlcy5Nb25leS5DYXJk", "c2IGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Money.Cards.CardMerchantIndicatorReflection.Descriptor, global::HOLMS.Types.Money.Cards.CardProcessorIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Money.Cards.CardMerchant), global::HOLMS.Types.Money.Cards.CardMerchant.Parser, new[]{ "EntityId", "Name", "CardProcessor", "CardAgreement", "LicenseId", "SiteId", "DeviceId", "Username", "Password", "ServiceURI", "DebugLoggingEnabled", "PorticoDeveloperId", "PorticoVersionNumber", "SuppressAuthorizationsInFolio" }, null, null, null) })); } #endregion } #region Messages public sealed partial class CardMerchant : pb::IMessage<CardMerchant> { private static readonly pb::MessageParser<CardMerchant> _parser = new pb::MessageParser<CardMerchant>(() => new CardMerchant()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<CardMerchant> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Money.Cards.CardMerchantReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CardMerchant() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CardMerchant(CardMerchant other) : this() { EntityId = other.entityId_ != null ? other.EntityId.Clone() : null; name_ = other.name_; cardProcessor_ = other.cardProcessor_; cardAgreement_ = other.cardAgreement_; licenseId_ = other.licenseId_; siteId_ = other.siteId_; deviceId_ = other.deviceId_; username_ = other.username_; password_ = other.password_; serviceURI_ = other.serviceURI_; debugLoggingEnabled_ = other.debugLoggingEnabled_; porticoDeveloperId_ = other.porticoDeveloperId_; porticoVersionNumber_ = other.porticoVersionNumber_; suppressAuthorizationsInFolio_ = other.suppressAuthorizationsInFolio_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public CardMerchant Clone() { return new CardMerchant(this); } /// <summary>Field number for the "entity_id" field.</summary> public const int EntityIdFieldNumber = 1; private global::HOLMS.Types.Money.Cards.CardMerchantIndicator entityId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Money.Cards.CardMerchantIndicator EntityId { get { return entityId_; } set { entityId_ = value; } } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 2; private string name_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "card_processor" field.</summary> public const int CardProcessorFieldNumber = 3; private global::HOLMS.Types.Money.Cards.CardProcessorIndicator cardProcessor_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Money.Cards.CardProcessorIndicator CardProcessor { get { return cardProcessor_; } set { cardProcessor_ = value; } } /// <summary>Field number for the "card_agreement" field.</summary> public const int CardAgreementFieldNumber = 4; private string cardAgreement_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string CardAgreement { get { return cardAgreement_; } set { cardAgreement_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "license_id" field.</summary> public const int LicenseIdFieldNumber = 5; private int licenseId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int LicenseId { get { return licenseId_; } set { licenseId_ = value; } } /// <summary>Field number for the "site_id" field.</summary> public const int SiteIdFieldNumber = 6; private int siteId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int SiteId { get { return siteId_; } set { siteId_ = value; } } /// <summary>Field number for the "device_id" field.</summary> public const int DeviceIdFieldNumber = 7; private int deviceId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int DeviceId { get { return deviceId_; } set { deviceId_ = value; } } /// <summary>Field number for the "username" field.</summary> public const int UsernameFieldNumber = 8; private string username_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Username { get { return username_; } set { username_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "password" field.</summary> public const int PasswordFieldNumber = 9; private string password_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Password { get { return password_; } set { password_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "service_u_r_i" field.</summary> public const int ServiceURIFieldNumber = 10; private string serviceURI_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ServiceURI { get { return serviceURI_; } set { serviceURI_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "debug_logging_enabled" field.</summary> public const int DebugLoggingEnabledFieldNumber = 11; private bool debugLoggingEnabled_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool DebugLoggingEnabled { get { return debugLoggingEnabled_; } set { debugLoggingEnabled_ = value; } } /// <summary>Field number for the "portico_developer_id" field.</summary> public const int PorticoDeveloperIdFieldNumber = 12; private string porticoDeveloperId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PorticoDeveloperId { get { return porticoDeveloperId_; } set { porticoDeveloperId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "portico_version_number" field.</summary> public const int PorticoVersionNumberFieldNumber = 13; private string porticoVersionNumber_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string PorticoVersionNumber { get { return porticoVersionNumber_; } set { porticoVersionNumber_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "suppress_authorizations_in_folio" field.</summary> public const int SuppressAuthorizationsInFolioFieldNumber = 14; private bool suppressAuthorizationsInFolio_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool SuppressAuthorizationsInFolio { get { return suppressAuthorizationsInFolio_; } set { suppressAuthorizationsInFolio_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as CardMerchant); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(CardMerchant other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EntityId, other.EntityId)) return false; if (Name != other.Name) return false; if (CardProcessor != other.CardProcessor) return false; if (CardAgreement != other.CardAgreement) return false; if (LicenseId != other.LicenseId) return false; if (SiteId != other.SiteId) return false; if (DeviceId != other.DeviceId) return false; if (Username != other.Username) return false; if (Password != other.Password) return false; if (ServiceURI != other.ServiceURI) return false; if (DebugLoggingEnabled != other.DebugLoggingEnabled) return false; if (PorticoDeveloperId != other.PorticoDeveloperId) return false; if (PorticoVersionNumber != other.PorticoVersionNumber) return false; if (SuppressAuthorizationsInFolio != other.SuppressAuthorizationsInFolio) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (entityId_ != null) hash ^= EntityId.GetHashCode(); if (Name.Length != 0) hash ^= Name.GetHashCode(); if (CardProcessor != 0) hash ^= CardProcessor.GetHashCode(); if (CardAgreement.Length != 0) hash ^= CardAgreement.GetHashCode(); if (LicenseId != 0) hash ^= LicenseId.GetHashCode(); if (SiteId != 0) hash ^= SiteId.GetHashCode(); if (DeviceId != 0) hash ^= DeviceId.GetHashCode(); if (Username.Length != 0) hash ^= Username.GetHashCode(); if (Password.Length != 0) hash ^= Password.GetHashCode(); if (ServiceURI.Length != 0) hash ^= ServiceURI.GetHashCode(); if (DebugLoggingEnabled != false) hash ^= DebugLoggingEnabled.GetHashCode(); if (PorticoDeveloperId.Length != 0) hash ^= PorticoDeveloperId.GetHashCode(); if (PorticoVersionNumber.Length != 0) hash ^= PorticoVersionNumber.GetHashCode(); if (SuppressAuthorizationsInFolio != false) hash ^= SuppressAuthorizationsInFolio.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 (entityId_ != null) { output.WriteRawTag(10); output.WriteMessage(EntityId); } if (Name.Length != 0) { output.WriteRawTag(18); output.WriteString(Name); } if (CardProcessor != 0) { output.WriteRawTag(24); output.WriteEnum((int) CardProcessor); } if (CardAgreement.Length != 0) { output.WriteRawTag(34); output.WriteString(CardAgreement); } if (LicenseId != 0) { output.WriteRawTag(40); output.WriteInt32(LicenseId); } if (SiteId != 0) { output.WriteRawTag(48); output.WriteInt32(SiteId); } if (DeviceId != 0) { output.WriteRawTag(56); output.WriteInt32(DeviceId); } if (Username.Length != 0) { output.WriteRawTag(66); output.WriteString(Username); } if (Password.Length != 0) { output.WriteRawTag(74); output.WriteString(Password); } if (ServiceURI.Length != 0) { output.WriteRawTag(82); output.WriteString(ServiceURI); } if (DebugLoggingEnabled != false) { output.WriteRawTag(88); output.WriteBool(DebugLoggingEnabled); } if (PorticoDeveloperId.Length != 0) { output.WriteRawTag(98); output.WriteString(PorticoDeveloperId); } if (PorticoVersionNumber.Length != 0) { output.WriteRawTag(106); output.WriteString(PorticoVersionNumber); } if (SuppressAuthorizationsInFolio != false) { output.WriteRawTag(112); output.WriteBool(SuppressAuthorizationsInFolio); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (entityId_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EntityId); } if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (CardProcessor != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CardProcessor); } if (CardAgreement.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(CardAgreement); } if (LicenseId != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(LicenseId); } if (SiteId != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(SiteId); } if (DeviceId != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(DeviceId); } if (Username.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Username); } if (Password.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Password); } if (ServiceURI.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ServiceURI); } if (DebugLoggingEnabled != false) { size += 1 + 1; } if (PorticoDeveloperId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PorticoDeveloperId); } if (PorticoVersionNumber.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(PorticoVersionNumber); } if (SuppressAuthorizationsInFolio != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(CardMerchant other) { if (other == null) { return; } if (other.entityId_ != null) { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Money.Cards.CardMerchantIndicator(); } EntityId.MergeFrom(other.EntityId); } if (other.Name.Length != 0) { Name = other.Name; } if (other.CardProcessor != 0) { CardProcessor = other.CardProcessor; } if (other.CardAgreement.Length != 0) { CardAgreement = other.CardAgreement; } if (other.LicenseId != 0) { LicenseId = other.LicenseId; } if (other.SiteId != 0) { SiteId = other.SiteId; } if (other.DeviceId != 0) { DeviceId = other.DeviceId; } if (other.Username.Length != 0) { Username = other.Username; } if (other.Password.Length != 0) { Password = other.Password; } if (other.ServiceURI.Length != 0) { ServiceURI = other.ServiceURI; } if (other.DebugLoggingEnabled != false) { DebugLoggingEnabled = other.DebugLoggingEnabled; } if (other.PorticoDeveloperId.Length != 0) { PorticoDeveloperId = other.PorticoDeveloperId; } if (other.PorticoVersionNumber.Length != 0) { PorticoVersionNumber = other.PorticoVersionNumber; } if (other.SuppressAuthorizationsInFolio != false) { SuppressAuthorizationsInFolio = other.SuppressAuthorizationsInFolio; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (entityId_ == null) { entityId_ = new global::HOLMS.Types.Money.Cards.CardMerchantIndicator(); } input.ReadMessage(entityId_); break; } case 18: { Name = input.ReadString(); break; } case 24: { cardProcessor_ = (global::HOLMS.Types.Money.Cards.CardProcessorIndicator) input.ReadEnum(); break; } case 34: { CardAgreement = input.ReadString(); break; } case 40: { LicenseId = input.ReadInt32(); break; } case 48: { SiteId = input.ReadInt32(); break; } case 56: { DeviceId = input.ReadInt32(); break; } case 66: { Username = input.ReadString(); break; } case 74: { Password = input.ReadString(); break; } case 82: { ServiceURI = input.ReadString(); break; } case 88: { DebugLoggingEnabled = input.ReadBool(); break; } case 98: { PorticoDeveloperId = input.ReadString(); break; } case 106: { PorticoVersionNumber = input.ReadString(); break; } case 112: { SuppressAuthorizationsInFolio = input.ReadBool(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Data; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.News; using Nop.Core.Domain.Stores; using Nop.Services.Events; namespace Nop.Services.News { /// <summary> /// News service /// </summary> public partial class NewsService : INewsService { #region Fields private readonly IRepository<NewsItem> _newsItemRepository; private readonly IRepository<NewsComment> _newsCommentRepository; private readonly IRepository<StoreMapping> _storeMappingRepository; private readonly CatalogSettings _catalogSettings; private readonly IEventPublisher _eventPublisher; #endregion #region Ctor public NewsService(IRepository<NewsItem> newsItemRepository, IRepository<NewsComment> newsCommentRepository, IRepository<StoreMapping> storeMappingRepository, CatalogSettings catalogSettings, IEventPublisher eventPublisher) { this._newsItemRepository = newsItemRepository; this._newsCommentRepository = newsCommentRepository; this._storeMappingRepository = storeMappingRepository; this._catalogSettings = catalogSettings; this._eventPublisher = eventPublisher; } #endregion #region Methods /// <summary> /// Deletes a news /// </summary> /// <param name="newsItem">News item</param> public virtual void DeleteNews(NewsItem newsItem) { if (newsItem == null) throw new ArgumentNullException("newsItem"); _newsItemRepository.Delete(newsItem); //event notification _eventPublisher.EntityDeleted(newsItem); } /// <summary> /// Gets a news /// </summary> /// <param name="newsId">The news identifier</param> /// <returns>News</returns> public virtual NewsItem GetNewsById(int newsId) { if (newsId == 0) return null; return _newsItemRepository.GetById(newsId); } /// <summary> /// Gets all news /// </summary> /// <param name="languageId">Language identifier; 0 if you want to get all records</param> /// <param name="storeId">Store identifier; 0 if you want to get all records</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <param name="showHidden">A value indicating whether to show hidden records</param> /// <returns>News items</returns> public virtual IPagedList<NewsItem> GetAllNews(int languageId = 0, int storeId = 0, int pageIndex = 0, int pageSize = int.MaxValue, bool showHidden = false) { var query = _newsItemRepository.Table; if (languageId > 0) query = query.Where(n => languageId == n.LanguageId); if (!showHidden) { var utcNow = DateTime.UtcNow; query = query.Where(n => n.Published); query = query.Where(n => !n.StartDateUtc.HasValue || n.StartDateUtc <= utcNow); query = query.Where(n => !n.EndDateUtc.HasValue || n.EndDateUtc >= utcNow); } query = query.OrderByDescending(n => n.CreatedOnUtc); //Store mapping if (storeId > 0 && !_catalogSettings.IgnoreStoreLimitations) { query = from n in query join sm in _storeMappingRepository.Table on new { c1 = n.Id, c2 = "NewsItem" } equals new { c1 = sm.EntityId, c2 = sm.EntityName } into n_sm from sm in n_sm.DefaultIfEmpty() where !n.LimitedToStores || storeId == sm.StoreId select n; //only distinct items (group by ID) query = from n in query group n by n.Id into nGroup orderby nGroup.Key select nGroup.FirstOrDefault(); query = query.OrderByDescending(n => n.CreatedOnUtc); } var news = new PagedList<NewsItem>(query, pageIndex, pageSize); return news; } /// <summary> /// Inserts a news item /// </summary> /// <param name="news">News item</param> public virtual void InsertNews(NewsItem news) { if (news == null) throw new ArgumentNullException("news"); _newsItemRepository.Insert(news); //event notification _eventPublisher.EntityInserted(news); } /// <summary> /// Updates the news item /// </summary> /// <param name="news">News item</param> public virtual void UpdateNews(NewsItem news) { if (news == null) throw new ArgumentNullException("news"); _newsItemRepository.Update(news); //event notification _eventPublisher.EntityUpdated(news); } /// <summary> /// Gets all comments /// </summary> /// <param name="customerId">Customer identifier; 0 to load all records</param> /// <returns>Comments</returns> public virtual IList<NewsComment> GetAllComments(int customerId) { var query = from c in _newsCommentRepository.Table orderby c.CreatedOnUtc where (customerId == 0 || c.CustomerId == customerId) select c; var content = query.ToList(); return content; } /// <summary> /// Gets a news comment /// </summary> /// <param name="newsCommentId">News comment identifier</param> /// <returns>News comment</returns> public virtual NewsComment GetNewsCommentById(int newsCommentId) { if (newsCommentId == 0) return null; return _newsCommentRepository.GetById(newsCommentId); } /// <summary> /// Get news comments by identifiers /// </summary> /// <param name="commentIds">News comment identifiers</param> /// <returns>News comments</returns> public virtual IList<NewsComment> GetNewsCommentsByIds(int[] commentIds) { if (commentIds == null || commentIds.Length == 0) return new List<NewsComment>(); var query = from nc in _newsCommentRepository.Table where commentIds.Contains(nc.Id) select nc; var comments = query.ToList(); //sort by passed identifiers var sortedComments = new List<NewsComment>(); foreach (int id in commentIds) { var comment = comments.Find(x => x.Id == id); if (comment != null) sortedComments.Add(comment); } return sortedComments; } /// <summary> /// Deletes a news comment /// </summary> /// <param name="newsComment">News comment</param> public virtual void DeleteNewsComment(NewsComment newsComment) { if (newsComment == null) throw new ArgumentNullException("newsComment"); _newsCommentRepository.Delete(newsComment); } #endregion } }
/* ==================================================================== 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 fyiReporting.RDL; using System.IO; using System.Collections; using System.Text; namespace fyiReporting.RDL { ///<summary> ///The primary class to "run" a report to XML ///</summary> internal class RenderXml: IPresent { Report r; // report TextWriter tw; // where the output is going Stack stkReportItem; // stack of nested report items Stack stkContainers; // stack to hold container elements string rowstart=null; public RenderXml(Report rep, IStreamGen sg) { r = rep; tw = sg.GetTextWriter(); stkReportItem = new Stack(); stkContainers = new Stack(); } public void Dispose() { } public Report Report() { return r; } public bool IsPagingNeeded() { return false; } public void Start() { tw.WriteLine("<?xml version='1.0' encoding='UTF-8'?>"); PushContainer(r.ReportDefinition.DataElementName); return; } public void End() { ContainerIO cio = (ContainerIO) stkContainers.Pop(); // this pop should empty the stack cio.WriteAttribute(">"); tw.WriteLine(cio.attribute_sb); tw.WriteLine(cio.subelement_sb); tw.WriteLine("</" + r.ReportDefinition.DataElementName + ">"); return; } // Body: main container for the report public void BodyStart(Body b) { } public void BodyEnd(Body b) { } public void PageHeaderStart(PageHeader ph) { } public void PageHeaderEnd(PageHeader ph) { } public void PageFooterStart(PageFooter pf) { } public void PageFooterEnd(PageFooter pf) { } public void Textbox(Textbox tb, string t, Row row) { if (tb.DataElementOutput != DataElementOutputEnum.Output || tb.DataElementName == null) return; if (rowstart != null) // In case no items in row are visible { // we delay until we get one. // WriteElement(rowstart); rowstart = null; } t = XmlUtil.XmlAnsi(t); if (tb.DataElementStyle == DataElementStyleEnum.AttributeNormal) { // write out as attribute WriteAttribute(" {0}='{1}'", tb.DataElementName, XmlUtil.EscapeXmlAttribute(t)); } else { // write out as element WriteElement("<{0}>{1}</{0}>", tb.DataElementName, t); } } public void DataRegionNoRows(DataRegion t, string noRowMsg) { } // Lists public bool ListStart(List l, Row r) { if (l.DataElementOutput == DataElementOutputEnum.NoOutput) return false; if (l.DataElementOutput == DataElementOutputEnum.ContentsOnly) return true; WriteElementLine("<{0}>", l.DataElementName); return true; //want to continue } public void ListEnd(List l, Row r) { if (l.DataElementOutput == DataElementOutputEnum.NoOutput || l.DataElementOutput == DataElementOutputEnum.ContentsOnly) return; WriteElementLine("</{0}>", l.DataElementName); return; } public void ListEntryBegin(List l, Row r) { string d; if (l.Grouping == null) { if (l.DataElementOutput != DataElementOutputEnum.Output) return; d = string.Format("<{0}", l.DataInstanceName); } else { Grouping g = l.Grouping; if (g.DataElementOutput != DataElementOutputEnum.Output) return; d = string.Format("<{0}", l.DataInstanceName); } PushContainer(l.DataInstanceName); return; } public void ListEntryEnd(List l, Row r) { if (l.DataElementOutput != DataElementOutputEnum.Output) return; PopContainer(l.DataInstanceName); } // Tables // Report item table public bool TableStart(Table t, Row row) { if (t.DataElementOutput == DataElementOutputEnum.NoOutput) return false; PushContainer(t.DataElementName); stkReportItem.Push(t); string cName = TableGetCollectionName(t); if (cName != null) WriteAttributeLine("><{0}", cName); return true; } public void TableEnd(Table t, Row row) { if (t.DataElementOutput == DataElementOutputEnum.NoOutput) return; string cName = TableGetCollectionName(t); PopContainer(cName); WriteElementLine("</{0}>", t.DataElementName); stkReportItem.Pop(); return; } string TableGetCollectionName(Table t) { string cName; if (t.TableGroups == null) { if (t.Details != null && t.Details.Grouping != null) cName = t.Details.Grouping.DataCollectionName; else cName = t.DetailDataCollectionName; } else cName = null; return cName; } public void TableBodyStart(Table t, Row row) { } public void TableBodyEnd(Table t, Row row) { } public void TableFooterStart(Footer f, Row row) { } public void TableFooterEnd(Footer f, Row row) { } public void TableHeaderStart(Header h, Row row) { } public void TableHeaderEnd(Header h, Row row) { } public void TableRowStart(TableRow tr, Row row) { string n = TableGetRowElementName(tr); if (n == null) return; PushContainer(n); } public void TableRowEnd(TableRow tr, Row row) { string n = TableGetRowElementName(tr); if (n == null) return; this.PopContainer(n); } string TableGetRowElementName(TableRow tr) { for (ReportLink rl = tr.Parent; !(rl is Table); rl = rl.Parent) { if (rl is Header || rl is Footer) return null; if (rl is TableGroup) { TableGroup tg = rl as TableGroup; Grouping g = tg.Grouping; return g.DataElementName; } if (rl is Details) { Table t = (Table) stkReportItem.Peek(); return t.DetailDataElementOutput == DataElementOutputEnum.NoOutput? null: t.DetailDataElementName; } } return null; } public void TableCellStart(TableCell t, Row row) { return; } public void TableCellEnd(TableCell t, Row row) { return; } public bool MatrixStart(Matrix m, MatrixCellEntry[,] matrix, Row r, int headerRows, int maxRows, int maxCols) // called first { if (m.DataElementOutput != DataElementOutputEnum.Output) return false; tw.WriteLine("<" + (m.DataElementName == null? "Matrix": m.DataElementName) + ">"); return true; } public void MatrixColumns(Matrix m, MatrixColumns mc) // called just after MatrixStart { } public void MatrixCellStart(Matrix m, ReportItem ri, int row, int column, Row r, float h, float w, int colSpan) { } public void MatrixCellEnd(Matrix m, ReportItem ri, int row, int column, Row r) { } public void MatrixRowStart(Matrix m, int row, Row r) { } public void MatrixRowEnd(Matrix m, int row, Row r) { } public void MatrixEnd(Matrix m, Row r) // called last { tw.WriteLine("</" + (m.DataElementName == null? "Matrix": m.DataElementName) + ">"); } public void Chart(Chart c, Row r, ChartBase cb) { } public void Image(Image i, Row r, string mimeType, Stream io) { } public void Line(Line l, Row r) { } public bool RectangleStart(RDL.Rectangle rect, Row r) { bool rc=true; switch (rect.DataElementOutput) { case DataElementOutputEnum.NoOutput: rc = false; break; case DataElementOutputEnum.Output: if (rowstart != null) // In case no items in row are visible { // we delay until we get one. tw.Write(rowstart); rowstart = null; } PushContainer(rect.DataElementName); break; case DataElementOutputEnum.Auto: case DataElementOutputEnum.ContentsOnly: default: break; } return rc; } public void RectangleEnd(RDL.Rectangle rect, Row r) { if (rect.DataElementOutput != DataElementOutputEnum.Output) return; PopContainer(rect.DataElementName); } public void Subreport(Subreport s, Row r) { if (s.DataElementOutput != DataElementOutputEnum.Output) return; PushContainer(s.DataElementName); s.ReportDefn.Run(this); PopContainer(s.DataElementName); return; } public void GroupingStart(Grouping g) // called at start of grouping { if (g.DataElementOutput != DataElementOutputEnum.Output) return; PushContainer(g.DataCollectionName); } public void GroupingInstanceStart(Grouping g) // called at start for each grouping instance { if (g.DataElementOutput != DataElementOutputEnum.Output) return; PushContainer(g.DataElementName); } public void GroupingInstanceEnd(Grouping g) // called at start for each grouping instance { if (g.DataElementOutput != DataElementOutputEnum.Output) return; PopContainer(g.DataElementName); } public void GroupingEnd(Grouping g) // called at end of grouping { if (g.DataElementOutput != DataElementOutputEnum.Output) return; PopContainer(g.DataCollectionName); } public void RunPages(Pages pgs) // we don't have paging turned on for xml { return; } void PopContainer(string name) { ContainerIO cio = (ContainerIO) this.stkContainers.Pop(); if (cio.bEmpty) return; cio.WriteAttribute(">"); WriteElementLine(cio.attribute_sb.ToString()); WriteElementLine(cio.subelement_sb.ToString()); if (name != null) WriteElementLine("</{0}>", name); } void PushContainer(string name) { ContainerIO cio = new ContainerIO("<" + name); stkContainers.Push(cio); } void WriteElement(string format) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteElement(format); } void WriteElement(string format, params object[] arg) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteElement(format, arg); } void WriteElementLine(string format) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteElementLine(format); } void WriteElementLine(string format, params object[] arg) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteElementLine(format, arg); } void WriteAttribute(string format) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteAttribute(format); } void WriteAttribute(string format, params object[] arg) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteAttribute(format, arg); } void WriteAttributeLine(string format) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteAttributeLine(format); } void WriteAttributeLine(string format, params object[] arg) { ContainerIO cio = (ContainerIO) this.stkContainers.Peek(); cio.WriteAttributeLine(format, arg); } class ContainerIO { internal StringBuilder attribute_sb; internal StringWriter attribute_sw; internal StringBuilder subelement_sb; internal StringWriter subelement_sw; internal bool bEmpty=true; internal ContainerIO(string begin) { subelement_sb = new StringBuilder(); subelement_sw = new StringWriter(subelement_sb); attribute_sb = new StringBuilder(begin); attribute_sw = new StringWriter(attribute_sb); } internal void WriteElement(string format) { bEmpty = false; subelement_sw.Write(format); } internal void WriteElement(string format, params object[] arg) { bEmpty = false; subelement_sw.Write(format, arg); } internal void WriteElementLine(string format) { bEmpty = false; subelement_sw.WriteLine(format); } internal void WriteElementLine(string format, params object[] arg) { bEmpty = false; subelement_sw.WriteLine(format, arg); } internal void WriteAttribute(string format) { bEmpty = false; attribute_sw.Write(format); } internal void WriteAttribute(string format, params object[] arg) { bEmpty = false; attribute_sw.Write(format, arg); } internal void WriteAttributeLine(string format) { bEmpty = false; attribute_sw.WriteLine(format); } internal void WriteAttributeLine(string format, params object[] arg) { bEmpty = false; attribute_sw.WriteLine(format, arg); } } } }
// // KeyPairPersistence.cs: Keypair persistence // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using Mono.Xml; namespace Mono.Security.Cryptography { /* File name * [type][unique name][key number].xml * * where * type CspParameters.ProviderType * unique name A unique name for the keypair, which is * a. default (for a provider default keypair) * b. a GUID derived from * i. random if no container name was * specified at generation time * ii. the MD5 hash of the container * name (CspParameters.KeyContainerName) * key number CspParameters.KeyNumber * * File format * <KeyPair> * <Properties> * <Provider Name="" Type=""/> * <Container Name=""/> * </Properties> * <KeyValue Id=""> * RSAKeyValue, DSAKeyValue ... * </KeyValue> * </KeyPair> */ /* NOTES * * - There's NO confidentiality / integrity built in this * persistance mechanism. The container directories (both user and * machine) are created with restrited ACL. The ACL is also checked * when a key is accessed (so totally public keys won't be used). * see /mono/mono/metadata/security.c for implementation * * - As we do not use CSP we limit ourselves to provider types (not * names). This means that for a same type and container type, but * two different provider names) will return the same keypair. This * should work as CspParameters always requires a csp type in its * constructors. * * - Assert (CAS) are used so only the OS permission will limit access * to the keypair files. I.e. this will work even in high-security * scenarios where users do not have access to file system (e.g. web * application). We can allow this because the filename used is * TOTALLY under our control (no direct user input is used). * * - You CAN'T changes properties of the keypair once it's been * created (saved). You must remove the container than save it * back. This is the same behaviour as CSP under Windows. */ internal class KeyPairPersistence { private static bool _userPathExists; // check at 1st use private static string _userPath; private static bool _machinePathExists; // check at 1st use private static string _machinePath; private CspParameters _params; private string _keyvalue; private string _filename; private string _container; // constructors public KeyPairPersistence (CspParameters parameters) : this (parameters, null) { } public KeyPairPersistence (CspParameters parameters, string keyPair) { if (parameters == null) throw new ArgumentNullException ("parameters"); _params = Copy (parameters); _keyvalue = keyPair; } // properties public string Filename { get { if (_filename == null) { _filename = String.Format (CultureInfo.InvariantCulture, "[{0}][{1}][{2}].xml", _params.ProviderType, this.ContainerName, _params.KeyNumber); if (UseMachineKeyStore) _filename = Path.Combine (MachinePath, _filename); else _filename = Path.Combine (UserPath, _filename); } return _filename; } } public string KeyValue { get { return _keyvalue; } set { if (this.CanChange) _keyvalue = value; } } // return a (read-only) copy public CspParameters Parameters { get { return Copy (_params); } } // methods public bool Load () { // see NOTES // FIXME new FileIOPermission (FileIOPermissionAccess.Read, this.Filename).Assert (); bool result = File.Exists (this.Filename); if (result) { using (StreamReader sr = File.OpenText (this.Filename)) { FromXml (sr.ReadToEnd ()); } } return result; } public void Save () { // see NOTES // FIXME new FileIOPermission (FileIOPermissionAccess.Write, this.Filename).Assert (); using (FileStream fs = File.Open (this.Filename, FileMode.Create)) { StreamWriter sw = new StreamWriter (fs, Encoding.UTF8); sw.Write (this.ToXml ()); sw.Close (); } // apply protection to newly created files if (UseMachineKeyStore) ProtectMachine (Filename); else ProtectUser (Filename); } public void Remove () { // see NOTES // FIXME new FileIOPermission (FileIOPermissionAccess.Write, this.Filename).Assert (); File.Delete (this.Filename); // it's now possible to change the keypair un the container } // private static stuff static object lockobj = new object (); private static string UserPath { get { lock (lockobj) { if ((_userPath == null) || (!_userPathExists)) { _userPath = Path.Combine ( Environment.GetFolderPath (Environment.SpecialFolder.ApplicationData), ".mono"); _userPath = Path.Combine (_userPath, "keypairs"); _userPathExists = Directory.Exists (_userPath); if (!_userPathExists) { try { Directory.CreateDirectory (_userPath); } catch (Exception e) { string msg = Locale.GetText ("Could not create user key store '{0}'."); throw new CryptographicException (String.Format (msg, _userPath), e); } _userPathExists = true; } } if (!IsUserProtected (_userPath) && !ProtectUser (_userPath)) { string msg = Locale.GetText ("Could not secure user key store '{0}'."); throw new IOException (String.Format (msg, _userPath)); } } // is it properly protected ? if (!IsUserProtected (_userPath)) { string msg = Locale.GetText ("Improperly protected user's key pairs in '{0}'."); throw new CryptographicException (String.Format (msg, _userPath)); } return _userPath; } } private static string MachinePath { get { lock (lockobj) { if ((_machinePath == null) || (!_machinePathExists)) { _machinePath = Path.Combine ( Environment.GetFolderPath (Environment.SpecialFolder.CommonApplicationData), ".mono"); _machinePath = Path.Combine (_machinePath, "keypairs"); _machinePathExists = Directory.Exists (_machinePath); if (!_machinePathExists) { try { Directory.CreateDirectory (_machinePath); } catch (Exception e) { string msg = Locale.GetText ("Could not create machine key store '{0}'."); throw new CryptographicException (String.Format (msg, _machinePath), e); } _machinePathExists = true; } } if (!IsMachineProtected (_machinePath) && !ProtectMachine (_machinePath)) { string msg = Locale.GetText ("Could not secure machine key store '{0}'."); throw new IOException (String.Format (msg, _machinePath)); } } // is it properly protected ? if (!IsMachineProtected (_machinePath)) { string msg = Locale.GetText ("Improperly protected machine's key pairs in '{0}'."); throw new CryptographicException (String.Format (msg, _machinePath)); } return _machinePath; } } #if INSIDE_CORLIB [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _CanSecure (string root); [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _ProtectUser (string path); [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _ProtectMachine (string path); [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _IsUserProtected (string path); [MethodImplAttribute (MethodImplOptions.InternalCall)] internal static extern bool _IsMachineProtected (string path); #else // Mono.Security.dll assembly can't use the internal // call (and still run with other runtimes) // Note: Class is only available in Mono.Security.dll as // a management helper (e.g. build a GUI app) internal static bool _CanSecure (string root) { return true; } internal static bool _ProtectUser (string path) { return true; } internal static bool _ProtectMachine (string path) { return true; } internal static bool _IsUserProtected (string path) { return true; } internal static bool _IsMachineProtected (string path) { return true; } #endif // private stuff private static bool CanSecure (string path) { // we assume POSIX filesystems can always be secured // check for Unix platforms - see FAQ for more details // http://www.mono-project.com/FAQ:_Technical#How_to_detect_the_execution_platform_.3F int platform = (int) Environment.OSVersion.Platform; if ((platform == 4) || (platform == 128) || (platform == 6)) return true; // while we ask the runtime for Windows OS return _CanSecure (Path.GetPathRoot (path)); } private static bool ProtectUser (string path) { // we cannot protect on some filsystem (like FAT) if (CanSecure (path)) { return _ProtectUser (path); } // but Mono still needs to run on them :( return true; } private static bool ProtectMachine (string path) { // we cannot protect on some filsystem (like FAT) if (CanSecure (path)) { return _ProtectMachine (path); } // but Mono still needs to run on them :( return true; } private static bool IsUserProtected (string path) { // we cannot protect on some filsystem (like FAT) if (CanSecure (path)) { return _IsUserProtected (path); } // but Mono still needs to run on them :( return true; } private static bool IsMachineProtected (string path) { // we cannot protect on some filsystem (like FAT) if (CanSecure (path)) { return _IsMachineProtected (path); } // but Mono still needs to run on them :( return true; } private bool CanChange { get { return (_keyvalue == null); } } private bool UseDefaultKeyContainer { get { return ((_params.Flags & CspProviderFlags.UseDefaultKeyContainer) == CspProviderFlags.UseDefaultKeyContainer); } } private bool UseMachineKeyStore { get { return ((_params.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore); } } private string ContainerName { get { if (_container == null) { if (UseDefaultKeyContainer) { // easy to spot _container = "default"; } else if ((_params.KeyContainerName == null) || (_params.KeyContainerName.Length == 0)) { _container = Guid.NewGuid ().ToString (); } else { // we don't want to trust the key container name as we don't control it // anyway some characters may not be compatible with the file system byte[] data = Encoding.UTF8.GetBytes (_params.KeyContainerName); // Note: We use MD5 as it is faster than SHA1 and has the same length // as a GUID. Recent problems found in MD5 (like collisions) aren't a // problem in this case. MD5 hash = MD5.Create (); byte[] result = hash.ComputeHash (data); _container = new Guid (result).ToString (); } } return _container; } } // we do not want any changes after receiving the csp informations private CspParameters Copy (CspParameters p) { CspParameters copy = new CspParameters (p.ProviderType, p.ProviderName, p.KeyContainerName); copy.KeyNumber = p.KeyNumber; copy.Flags = p.Flags; return copy; } private void FromXml (string xml) { SecurityParser sp = new SecurityParser (); sp.LoadXml (xml); SecurityElement root = sp.ToXml (); if (root.Tag == "KeyPair") { //SecurityElement prop = root.SearchForChildByTag ("Properties"); SecurityElement keyv = root.SearchForChildByTag ("KeyValue"); if (keyv.Children.Count > 0) _keyvalue = keyv.Children [0].ToString (); // Note: we do not read other stuff because // it can't be changed after key creation } } private string ToXml () { // note: we do not use SecurityElement here because the // keypair is a XML string (requiring parsing) StringBuilder xml = new StringBuilder (); xml.AppendFormat ("<KeyPair>{0}\t<Properties>{0}\t\t<Provider ", Environment.NewLine); if ((_params.ProviderName != null) && (_params.ProviderName.Length != 0)) { xml.AppendFormat ("Name=\"{0}\" ", _params.ProviderName); } xml.AppendFormat ("Type=\"{0}\" />{1}\t\t<Container ", _params.ProviderType, Environment.NewLine); xml.AppendFormat ("Name=\"{0}\" />{1}\t</Properties>{1}\t<KeyValue", this.ContainerName, Environment.NewLine); if (_params.KeyNumber != -1) { xml.AppendFormat (" Id=\"{0}\" ", _params.KeyNumber); } xml.AppendFormat (">{1}\t\t{0}{1}\t</KeyValue>{1}</KeyPair>{1}", this.KeyValue, Environment.NewLine); return xml.ToString (); } } }
using System; using Gtk; using ShadowrunLogic; using ShadowrunCoreContent; using System.Collections.Generic; using ShadowrunGui; public partial class CharacterImportWindow: Gtk.Window { private List<IManifest<IManifestItem>> rangedWeaponManifests; private List<IManifest<IManifestItem>> meleeWeaponManifests; private List<IManifest<IManifestItem>> attributeManifests; public Character character; public CharacterImportWindow (): base (Gtk.WindowType.Toplevel) { Build (); rangedWeaponManifests = new List<IManifest<IManifestItem>>(); meleeWeaponManifests = new List<IManifest<IManifestItem>>(); attributeManifests = new List<IManifest<IManifestItem>>(); LoadContentFromManifests(); } public CharacterImportWindow (Character c): base (Gtk.WindowType.Toplevel) { Build (); rangedWeaponManifests = new List<IManifest<IManifestItem>>(); meleeWeaponManifests = new List<IManifest<IManifestItem>>(); attributeManifests = new List<IManifest<IManifestItem>>(); LoadContentFromManifests(); SetRenderedAttributes(c.attributes); SetRenderedMeleeWeapon(c.meleeWeapon); SetRenderedRangedWeapon(c.rangedWeapon); } private void LoadContentFromManifests () { rangedWeaponManifests.Add(new ShadowrunCoreContent.RangedWeaponsManifest()); meleeWeaponManifests.Add (new ShadowrunCoreContent.MeleeWeaponsManifest()); attributeManifests.Add(new ShadowrunCoreContent.AttributesManifest()); } #region FormEvents protected void AttributeImport_Click (object sender, EventArgs e) { var attributesImportWindow = new ItemImportWindow(attributeManifests,"Attribute Import"); attributesImportWindow.TransientFor = this; attributesImportWindow.Destroyed+= delegate { if(attributesImportWindow.selectedItem == null) return; var selectedAttributes = (AbstractAttributes)attributesImportWindow.selectedItem; SetRenderedAttributes(selectedAttributes); }; } protected void RangedWeaponImport_Click (object sender, EventArgs e) { var rangedImportWeaponWindow = new ItemImportWindow(rangedWeaponManifests,"Ranged Weapon Import"); rangedImportWeaponWindow.TransientFor = this; rangedImportWeaponWindow.Destroyed+= delegate { if(rangedImportWeaponWindow.selectedItem == null) return; var selectedRangedWeapon = (AbstractRangedWeapon)rangedImportWeaponWindow.selectedItem; SetRenderedRangedWeapon(selectedRangedWeapon); }; } protected void MeleeWeaponImport_Click (object sender, EventArgs e) { var meleeImportWeaponWindow = new ItemImportWindow(meleeWeaponManifests,"Melee Weapon Import"); meleeImportWeaponWindow.TransientFor = this; meleeImportWeaponWindow.Destroyed+= delegate { if(meleeImportWeaponWindow.selectedItem == null) return; var selectedMeleeWeapon = (AbstractMeleeWeapon)meleeImportWeaponWindow.selectedItem; SetRenderedMeleeWeapon(selectedMeleeWeapon); }; } protected void SubmitCharacter_Click (object sender, EventArgs e) { try { this.character = new Character ( attributesFromFormInput (), rangedWeaponFromFormInput (), meleeWeaponFromFormInput () ); this.Destroy (); } catch (Exception ex) { new MessageWindow(this,"Character Import Window", "Error: " + ex.Message); } } #endregion #region DisplayStuff protected void SetRenderedRangedWeapon (AbstractRangedWeapon r) { RangedWeaponName_Textbox.Text = r.Name (); RangedDamage_Textbox.Text = r.Damage ().ToString (); if (r.DamageType () == DamageType.Stun) RangedStunDamage_Radio.Activate (); else RangedPhysicalDamage_Radio.Activate (); RangedAccuracy_Textbox.Text = r.Accuracy ().ToString (); RangedWeaponAP_Textbox.Text = r.AP ().ToString (); RangedRecoil_Textbox.Text = r.Recoil ().ToString (); var modes = r.FiringModes (); SingleShot_Checkbox.Active = modes.SingleShot; SemiAutomatic_Checkbox.Active = modes.SemiAutomatic; SemiAutomaticBurst_Checkbox.Active = modes.SemiAutomaticBurst; BurstFire_Checkbox.Active = modes.BurstFire; LongBurst_Checkbox.Active = modes.LongBurst; FullAuto_Checkbox.Active = modes.FullAuto; MagSize_Textbox.Text = r.MagSize().ToString(); switch (r.Skill ()) { case RangedWeaponSkills.Archery: Archery_Radio.Activate (); break; case RangedWeaponSkills.Automatics: Automatics_Radio.Activate (); break; case RangedWeaponSkills.HeavyWeapons: HeavyWeapons_Radio.Activate (); break; case RangedWeaponSkills.Longarms: Longarms_Radio.Activate (); break; case RangedWeaponSkills.Pistols: Pistols_Radio.Activate (); break; case RangedWeaponSkills.ThrowingWeapons: ThrowingWeapons_Radio.Activate (); break; } } protected void SetRenderedMeleeWeapon (AbstractMeleeWeapon m) { MeleeWeaponName_Textbox.Text = m.Name (); MeleeAP_Textbox.Text = m.AP ().ToString (); if (m.DamageType () == DamageType.Stun) MeleeStunDamage_Radio.Activate (); else MeleePhysicalDamage_Radio.Activate (); MeleeDamage_Textbox.Text = m.Damage ().ToString (); MeleeAccuracy_Textbox.Text = m.Accuracy().ToString(); switch (m.Skill ()) { case MeleeWeaponSkills.Blades: Blades_Radio.Activate(); break; case MeleeWeaponSkills.Clubs: Clubs_Radio.Activate(); break; case MeleeWeaponSkills.UnarmedCombat: Unarmed_Radio.Activate(); break; } } protected void SetRenderedAttributes(AbstractAttributes a){ this.Armor_Textbox.Text = a.Armor().ToString(); //attributes this.Body_Textbox.Text = a.Body().ToString(); this.Agility_Textbox.Text = a.Agility().ToString(); this.Charisma_Textbox.Text = a.Charisma().ToString(); this.InitiativeDiceCount_Textbox.Text = a.InitiativeDice().ToString(); this.InitiativeModifier_Textbox.Text = a.InitiativeModifier().ToString(); this.Intuition_Textbox.Text = a.Intuition().ToString(); this.Logic_Textbox.Text = a.Logic().ToString(); this.Reaction_Textbox.Text = a.Reaction().ToString(); this.Strength_Textbox.Text = a.Strength().ToString(); this.Willpower_Textbox.Text = a.Willpower().ToString(); this.Name_Textbox.Text = a.Name(); //combat skills this.Archery_Spinbox.Value = a.Archery(); this.AutomaticsSpinbox.Value = a.Automatics(); this.Blades_Spinbox.Value = a.Blades(); this.Clubs_Spinbox.Value = a.Clubs(); this.HeavyWeapons_Spinbox.Value = a.HeavyWeapons(); this.Longarms_Spinbox.Value = a.Longarms(); this.Pistols_Spinbox.Value = a.Pistols(); this.ThrowingWeapons_Spinbox.Value = a.ThrowingWeapons(); this.UnarmedCombat_Spinbox.Value = a.UnarmedCombat(); } protected AbstractAttributes attributesFromFormInput(){ return new CustomAttributes( Int32.Parse(Body_Textbox.Text), Int32.Parse(Agility_Textbox.Text), Int32.Parse(Reaction_Textbox.Text), Int32.Parse(Strength_Textbox.Text), Int32.Parse (Willpower_Textbox.Text), Int32.Parse (Logic_Textbox.Text), Int32.Parse (Intuition_Textbox.Text), Int32.Parse (Charisma_Textbox.Text), Int32.Parse (InitiativeDiceCount_Textbox.Text), Int32.Parse (InitiativeModifier_Textbox.Text), Int32.Parse (Armor_Textbox.Text), Name_Textbox.Text, AttributeType.Custom, (int)Archery_Spinbox.Value, (int)AutomaticsSpinbox.Value, (int)Blades_Spinbox.Value, (int)Clubs_Spinbox.Value, (int)HeavyWeapons_Spinbox.Value, (int)Longarms_Spinbox.Value, (int)Pistols_Spinbox.Value, (int)ThrowingWeapons_Spinbox.Value, (int)UnarmedCombat_Spinbox.Value); } protected RangedFiringModes rangedFiringModesFromFormInput () { RangedFiringModes mode = new RangedFiringModes(); if(BurstFire_Checkbox.Active) mode.BurstFire = true; if(FullAuto_Checkbox.Active) mode.FullAuto = true; if(LongBurst_Checkbox.Active) mode.LongBurst = true; if(SemiAutomatic_Checkbox.Active) mode.SemiAutomatic = true; if(SemiAutomaticBurst_Checkbox.Active) mode.SemiAutomaticBurst = true; if(SingleShot_Checkbox.Active) mode.SingleShot = true; return mode; } protected RangedWeaponSkills rangedWeaponSkillFromFormInput () { if (Archery_Radio.Active) { return RangedWeaponSkills.Archery; } else if (Automatics_Radio.Active) { return RangedWeaponSkills.Automatics; } else if (HeavyWeapons_Radio.Active) { return RangedWeaponSkills.HeavyWeapons; } else if (Longarms_Radio.Active) { return RangedWeaponSkills.Longarms; } else if (Pistols_Radio.Active) { return RangedWeaponSkills.Pistols; } else if (ThrowingWeapons_Radio.Active) { return RangedWeaponSkills.ThrowingWeapons; } else { throw new ArgumentOutOfRangeException(); } } protected AbstractRangedWeapon rangedWeaponFromFormInput () { return new CustomRangedWeapon( Int32.Parse(MeleeDamage_Textbox.Text), (RangedPhysicalDamage_Radio.Active ? DamageType.Physical : DamageType.Stun), Int32.Parse(RangedAccuracy_Textbox.Text), Int32.Parse(RangedWeaponAP_Textbox.Text), rangedFiringModesFromFormInput(), Int32.Parse(this.MagSize_Textbox.Text), RangedWeaponName_Textbox.Text, Int32.Parse(RangedRecoil_Textbox.Text), rangedWeaponSkillFromFormInput()); } protected MeleeWeaponSkills meleeWeaponSkillsFromFormInput () { if (Blades_Radio.Active) { return MeleeWeaponSkills.Blades; } else if (Clubs_Radio.Active) { return MeleeWeaponSkills.Clubs; } else if (Unarmed_Radio.Active) { return MeleeWeaponSkills.UnarmedCombat; } else { throw new ArgumentOutOfRangeException(); } } protected AbstractMeleeWeapon meleeWeaponFromFormInput () { return new CustomMeleeWeapon( Int32.Parse(MeleeDamage_Textbox.Text), (MeleePhysicalDamage_Radio.Active ? DamageType.Physical : DamageType.Stun), Int32.Parse(MeleeAP_Textbox.Text), MeleeWeaponName_Textbox.Text, Int32.Parse(MeleeAccuracy_Textbox.Text), meleeWeaponSkillsFromFormInput()); } #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 OLEDB.Test.ModuleCore; using System.IO; namespace System.Xml.Tests { ///////////////////////////////////////////////////////////////////////// // TestCase ReadOuterXml // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCReadToFollowing : TCXMLReaderBaseGeneral { #region XMLSTR private string _xmlStr = @"<?xml version='1.0'?> <root><!--Comment--> <elem><!-- Comment --> <child1 att='1'><?pi target?> <child2 xmlns='child2'> <child3/> blahblahblah<![CDATA[ blah ]]> <child4/> </child2> <?pi target1?> </child1> </elem> <elem att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah <child4/> </child2> <?pi target1?> </child1> </elem> <elem xmlns='elem'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <elem xmlns='elem' att='1'> <child1 att='1'> <child2 xmlns='child2'> <child3/> blahblahblah2 <child4/> </child2> </child1> </elem> <e:elem xmlns:e='elem2'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> <e:elem xmlns:e='elem2' att='1'> <e:child1 att='1'> <e:child2 xmlns='child2'> <e:child3/> blahblahblah2 <e:child4/> </e:child2> </e:child1> </e:elem> </root>"; #endregion //[Variation("Simple positive test", Pri = 0, Params = new object[] { "NNS" })] //[Variation("Simple positive test", Pri = 0, Params = new object[] { "DNS" })] //[Variation("Simple positive test", Pri = 0, Params = new object[] { "NS" })] public int v1() { string type = CurVariation.Params[0].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); switch (type) { case "NNS": DataReader.ReadToFollowing("elem"); CError.Compare(DataReader.HasAttributes, false, "Positioned on wrong element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToFollowing("elem", "elem"); if (DataReader.HasAttributes) CError.Compare(DataReader.GetAttribute("xmlns") != null, "Positioned on wrong element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToFollowing("e:elem"); if (DataReader.HasAttributes) CError.Compare(DataReader.GetAttribute("xmlns:e") != null, "Positioned on wrong element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } //[Variation("Read on following with same names", Pri = 1, Params = new object[] { "NNS" })] //[Variation("Read on following with same names", Pri = 1, Params = new object[] { "DNS" })] //[Variation("Read on following with same names", Pri = 1, Params = new object[] { "NS" })] public int v2() { string type = CurVariation.Params[0].ToString(); CError.WriteLine("Test Type : " + type); ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); //Doing a sequential read. switch (type) { case "NNS": DataReader.ReadToFollowing("elem"); int depth = DataReader.Depth; CError.Compare(DataReader.HasAttributes, false, "Positioned on wrong element"); CError.Compare(DataReader.ReadToFollowing("elem"), true, "There are no more elem nodes"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "DNS": DataReader.ReadToFollowing("elem", "elem"); if (DataReader.HasAttributes) CError.Compare(DataReader.GetAttribute("xmlns") != null, "Positioned on wrong element, not on NS"); CError.Compare(DataReader.ReadToFollowing("elem", "elem"), true, "There are no more elem,elem nodes"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; case "NS": DataReader.ReadToFollowing("e:elem"); if (DataReader.HasAttributes) CError.Compare(DataReader.GetAttribute("xmlns:e") != null, "Positioned on wrong element, not on NS"); CError.Compare(DataReader.ReadToFollowing("e:elem"), true, "There are no more descendants"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; default: throw new CTestFailedException("Error in Test type"); } } [Variation("If name not found, go to eof", Pri = 1)] public int v4() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("elem"); CError.Compare(DataReader.ReadToFollowing("abc"), false, "Reader returned true for an invalid name"); CError.Compare(DataReader.NodeType, XmlNodeType.None, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("If localname not found go to eof", Pri = 1)] public int v5_1() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("elem"); CError.Compare(DataReader.ReadToFollowing("abc", "elem"), false, "Reader returned true for an invalid localname"); CError.Compare(DataReader.NodeType, XmlNodeType.None, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("If uri not found, go to eof", Pri = 1)] public int v5_2() { ReloadSource(new StringReader(_xmlStr)); CError.Compare(DataReader.ReadToFollowing("elem", "abc"), false, "Reader returned true for an invalid uri"); CError.Compare(DataReader.NodeType, XmlNodeType.None, "Wrong node type"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to Following on one level and again to level below it", Pri = 1)] public int v6() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToFollowing("elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToFollowing("child1"), true, "Cant find child1"); CError.Compare(DataReader.ReadToFollowing("child2"), true, "Cant find child2"); CError.Compare(DataReader.ReadToFollowing("child3"), true, "Cant find child3"); CError.Compare(DataReader.ReadToFollowing("child4"), true, "Shouldn't find child4"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on Element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to Following on one level and again to level below it, with namespace", Pri = 1)] public int v7() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToFollowing("elem", "elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToFollowing("child1", "elem"), true, "Cant find child1"); CError.Compare(DataReader.ReadToFollowing("child2", "child2"), true, "Cant find child2"); CError.Compare(DataReader.ReadToFollowing("child3", "child2"), true, "Cant find child3"); CError.Compare(DataReader.ReadToFollowing("child4", "child2"), true, "Cant find child4"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on Element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Read to Following on one level and again to level below it, with prefix", Pri = 1)] public int v8() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToFollowing("e:elem"), true, "Cant find elem"); CError.Compare(DataReader.ReadToFollowing("e:child1"), true, "Cant find child1"); CError.Compare(DataReader.ReadToFollowing("e:child2"), true, "Cant find child2"); CError.Compare(DataReader.ReadToFollowing("e:child3"), true, "Cant find child3"); CError.Compare(DataReader.ReadToFollowing("e:child4"), true, "Cant fine child4"); CError.Compare(DataReader.NodeType, XmlNodeType.Element, "Not on Element"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Multiple Reads to children and then next siblings, NNS", Pri = 2)] public int v9() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToFollowing("elem"), true, "Read fails elem"); CError.Compare(DataReader.ReadToFollowing("child3"), true, "Read fails child3"); CError.Compare(DataReader.ReadToNextSibling("child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Multiple Reads to children and then next siblings, DNS", Pri = 2)] public int v10() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToFollowing("elem", "elem"), true, "Read fails elem"); CError.Compare(DataReader.ReadToFollowing("child3", "child2"), true, "Read fails child3"); CError.Compare(DataReader.ReadToNextSibling("child4", "child2"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Multiple Reads to children and then next siblings, NS", Pri = 2)] public int v11() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToFollowing("e:elem"), true, "Read fails elem"); CError.Compare(DataReader.ReadToFollowing("e:child3"), true, "Read fails child3"); CError.Compare(DataReader.ReadToNextSibling("e:child4"), true, "Read fails child4"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Only child has namespaces and read to it", Pri = 2)] public int v14() { ReloadSource(new StringReader(_xmlStr)); DataReader.PositionOnElement("root"); CError.Compare(DataReader.ReadToFollowing("child2", "child2"), true, "Fails on child2"); DataReader.Close(); return TEST_PASS; } [Variation("Pass null to both arguments throws ArgumentException", Pri = 2)] public int v15() { ReloadSource(new StringReader("<root><b/></root>")); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); try { DataReader.ReadToFollowing(null); } catch (ArgumentNullException) { CError.WriteLine("Caught for single param"); } try { DataReader.ReadToFollowing("b", null); } catch (ArgumentNullException) { CError.WriteLine("Caught for single param"); } while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } [Variation("Different names, same uri works correctly", Pri = 2)] public int v17() { ReloadSource(new StringReader("<root><child1 xmlns='foo'/>blah<child1 xmlns='bar'>blah</child1></root>")); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); DataReader.ReadToFollowing("child1", "bar"); CError.Compare(DataReader.IsEmptyElement, false, "Not on the correct node"); while (DataReader.Read()) ; DataReader.Close(); return TEST_PASS; } } }
using System; using System.Data; using System.Data.Odbc; using System.Data.OleDb; namespace MyMeta.Pervasive { #if ENTERPRISE using System.Runtime.InteropServices; [ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IColumns))] #endif public class PervasiveColumns : Columns { public PervasiveColumns() { } internal DataColumn f_TypeName = null; internal DataColumn f_AutoKey = null; override internal void LoadForTable() { DataTable metaData = this.LoadData(OleDbSchemaGuid.Columns, new Object[] {null, null, this.Table.Name}); metaData.DefaultView.Sort = "ORDINAL_POSITION"; PopulateArray(metaData); LoadExtraDataForTable(); } override internal void LoadForView() { DataTable metaData = this.LoadData(OleDbSchemaGuid.Columns, new Object[] {null, null, this.View.Name}); metaData.DefaultView.Sort = "ORDINAL_POSITION"; PopulateArray(metaData); LoadExtraDataForView(); } private void LoadExtraDataForTable() { try { string select = "SELECT \"X$Field\".Xe$Name AS Name, \"X$Field\".Xe$DataType as Type, \"X$Field\".Xe$Size AS Size, \"X$Field\".Xe$Flags AS Flags " + "FROM X$File,X$Field WHERE Xf$Id=Xe$File AND Xf$Name = '" + this.Table.Name + "' " + "AND \"X$Field\".Xe$DataType < 27 " + "ORDER BY Xe$Offset"; OleDbDataAdapter adapter = new OleDbDataAdapter(select, this.dbRoot.ConnectionString); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); if(this._array.Count > 0) { Column col = this._array[0] as Column; f_TypeName = new DataColumn("TYPE_NAME", typeof(string)); col._row.Table.Columns.Add(f_TypeName); f_AutoKey = new DataColumn("AUTO_INCREMENT", typeof(Boolean)); col._row.Table.Columns.Add(f_AutoKey); string typeName = ""; DataRowCollection rows = dataTable.Rows; int type = 0; int size = 0; int flags = 0; int index = 0; foreach(Column c in this) { DataRow row = rows[index++]; type = Convert.ToInt32(row["Type"]); size = Convert.ToInt32(row["Size"]); flags = Convert.ToInt32(row["Flags"]); switch(type) { case 0: if(flags == 4100) { typeName = "BINARY"; } else { typeName = "CHAR"; } break; case 1: switch(size) { case 1: typeName = "TINYINT"; break; case 2: typeName = "SMALLINT"; break; case 4: typeName = "INTEGER"; break; case 8: typeName = "BIGINT"; break; } break; case 2: switch(size) { case 4: typeName = "REAL"; break; case 8: typeName = "DOUBLE"; break; } break; case 3: typeName = "DATE"; break; case 4: typeName = "TIME"; break; case 5: typeName = "DECIMAL"; break; case 6: typeName = "MONEY"; break; case 8: typeName = "NUMERIC"; break; case 9: switch(size) { case 4: typeName = "BFLOAT4"; break; case 8: typeName = "BFLOAT8"; break; } break; case 11: typeName = "VARCHAR"; break; case 14: switch(size) { case 1: typeName = "UTINYINT"; break; case 2: typeName = "USMALLINT"; break; case 4: typeName = "UINTEGER"; break; case 8: typeName = "UBIGINT"; break; } break; case 15: switch(size) { case 2: typeName = "SMALLIDENTITY"; c._row["AUTO_INCREMENT"] = true; break; case 4: typeName = "IDENTITY"; c._row["AUTO_INCREMENT"] = true; break; } break; case 16: typeName = "BIT"; break; case 17: typeName = "NUMERICSTS"; break; case 18: typeName = "NUMERICSA"; break; case 19: typeName = "CURRENCY"; break; case 20: typeName = "TIMESTAMP"; break; case 21: if(flags == 4100) { typeName = "LONGVARBINARY"; } else { typeName = "LONGVARCHAR"; } break; case 22: typeName = "LONGVARBINARY"; break; case 25: typeName = "WSTRING"; break; case 26: typeName = "WSZSTRING"; break; } c._row["TYPE_NAME"] = typeName; } } } catch {} } private void LoadExtraDataForView() { try { if(this._array.Count > 0) { ADODB.Connection cnn = new ADODB.Connection(); ADODB.Recordset rs = new ADODB.Recordset(); ADOX.Catalog cat = new ADOX.Catalog(); // Open the Connection cnn.Open(dbRoot.ConnectionString, null, null, 0); cat.ActiveConnection = cnn; rs.Source = cat.Views[this.View.Name].Command; rs.Fields.Refresh(); ADODB.Fields flds = rs.Fields; Column col = this._array[0] as Column; f_TypeName = new DataColumn("TYPE_NAME", typeof(string)); col._row.Table.Columns.Add(f_TypeName); f_AutoKey = new DataColumn("AUTO_INCREMENT", typeof(Boolean)); col._row.Table.Columns.Add(f_AutoKey); Column c = null; ADODB.Field fld = null; int count = this._array.Count; for( int index = 0; index < count; index++) { fld = flds[index]; c = (Column)this[fld.Name]; c._row["TYPE_NAME"] = fld.Type.ToString(); c._row["AUTO_INCREMENT"] = false; } rs.Close(); cnn.Close(); } } catch {} } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace GameOfDrones.API.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 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.Drawing; using System.Windows.Forms; using XenAdmin.Actions; using XenAdmin.Core; using XenAdmin.Model; using XenAdmin.Properties; using XenAPI; namespace XenAdmin.Dialogs.HealthCheck { public partial class HealthCheckSettingsDialog : XenDialogBase { private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly Pool pool; private HealthCheckSettings healthCheckSettings; private bool authenticationRequired; private bool authenticated; private string authenticationToken; private string diagnosticToken; private string xsUserName; private string xsPassword; public HealthCheckSettingsDialog(Pool pool, bool enrollNow) { this.pool = pool; this.connection = pool.Connection; healthCheckSettings = pool.HealthCheckSettings; if (enrollNow) healthCheckSettings.Status = HealthCheckStatus.Enabled; authenticated = healthCheckSettings.TryGetExistingTokens(pool.Connection, out authenticationToken, out diagnosticToken); authenticationRequired = !authenticated; xsUserName = healthCheckSettings.GetSecretyInfo(pool.Connection, HealthCheckSettings.UPLOAD_CREDENTIAL_USER_SECRET); xsPassword = healthCheckSettings.GetSecretyInfo(pool.Connection, HealthCheckSettings.UPLOAD_CREDENTIAL_PASSWORD_SECRET); InitializeComponent(); PopulateControls(); InitializeControls(); UpdateButtons(); } private void PopulateControls() { var list = BuildDays(); var ds = new BindingSource(list, null); dayOfWeekComboBox.DataSource = ds; dayOfWeekComboBox.ValueMember = "key"; dayOfWeekComboBox.DisplayMember = "value"; var list1 = BuildHours(); var ds1 = new BindingSource(list1, null); timeOfDayComboBox.DataSource = ds1; timeOfDayComboBox.ValueMember = "key"; timeOfDayComboBox.DisplayMember = "value"; } private Dictionary<int, string> BuildDays() { Dictionary<int, string> days = new Dictionary<int, string>(); foreach (var dayOfWeek in Enum.GetValues(typeof(DayOfWeek))) { days.Add((int)dayOfWeek, dayOfWeek.ToString()); } return days; } private SortedDictionary<int, string> BuildHours() { SortedDictionary<int, string> hours = new SortedDictionary<int, string>(); for (int hour = 0; hour <= 23; hour++) { DateTime time = new DateTime(1900, 1, 1, hour, 0, 0); hours.Add(hour, HelpersGUI.DateTimeToString(time, Messages.DATEFORMAT_HM, true)); } return hours; } private void InitializeControls() { Text = String.Format(Messages.HEALTHCHECK_ENROLLMENT_TITLE, pool.Name); authenticationRubricLabel.Text = authenticationRequired ? Messages.HEALTHCHECK_AUTHENTICATION_RUBRIC_NO_TOKEN : Messages.HEALTHCHECK_AUTHENTICATION_RUBRIC_EXISTING_TOKEN; enrollmentCheckBox.Checked = healthCheckSettings.Status != HealthCheckStatus.Disabled; frequencyNumericBox.Value = healthCheckSettings.IntervalInWeeks; dayOfWeekComboBox.SelectedValue = (int)healthCheckSettings.DayOfWeek; timeOfDayComboBox.SelectedValue = healthCheckSettings.TimeOfDay; existingAuthenticationRadioButton.Enabled = existingAuthenticationRadioButton.Checked = !authenticationRequired; newAuthenticationRadioButton.Checked = authenticationRequired; SetMyCitrixCredentials(existingAuthenticationRadioButton.Checked); bool useCurrentXsCredentials = string.IsNullOrEmpty(xsUserName) || xsUserName == pool.Connection.Username; newXsCredentialsRadioButton.Checked = !useCurrentXsCredentials; currentXsCredentialsRadioButton.Checked = useCurrentXsCredentials; SetXSCredentials(currentXsCredentialsRadioButton.Checked); } private bool ChangesMade() { if (enrollmentCheckBox.Checked && healthCheckSettings.Status != HealthCheckStatus.Enabled) return true; if (!enrollmentCheckBox.Checked && healthCheckSettings.Status != HealthCheckStatus.Disabled) return true; if (frequencyNumericBox.Value != healthCheckSettings.IntervalInWeeks) return true; if (dayOfWeekComboBox.SelectedIndex != (int)healthCheckSettings.DayOfWeek) return true; if (timeOfDayComboBox.SelectedIndex != healthCheckSettings.TimeOfDay) return true; if (authenticationToken != healthCheckSettings.GetSecretyInfo(pool.Connection, HealthCheckSettings.UPLOAD_TOKEN_SECRET)) return true; if (textboxXSUserName.Text != xsUserName) return true; if (textboxXSPassword.Text != xsPassword) return true; return false; } private void UpdateButtons() { okButton.Enabled = m_ctrlError.PerformCheck(CheckCredentialsEntered); } private void okButton_Click(object sender, EventArgs e) { okButton.Enabled = false; if (enrollmentCheckBox.Checked && newAuthenticationRadioButton.Checked && !m_ctrlError.PerformCheck(CheckUploadAuthentication)) { okButton.Enabled = true; return; } if (ChangesMade()) { var newHealthCheckSettings = new HealthCheckSettings(pool.health_check_config); newHealthCheckSettings.Status = enrollmentCheckBox.Checked ? HealthCheckStatus.Enabled : HealthCheckStatus.Disabled; newHealthCheckSettings.IntervalInDays = (int)(frequencyNumericBox.Value * 7); newHealthCheckSettings.DayOfWeek = (DayOfWeek)dayOfWeekComboBox.SelectedValue; newHealthCheckSettings.TimeOfDay = (int)timeOfDayComboBox.SelectedValue; newHealthCheckSettings. RetryInterval = HealthCheckSettings.DEFAULT_RETRY_INTERVAL; new SaveHealthCheckSettingsAction(pool, newHealthCheckSettings, authenticationToken, diagnosticToken, textboxXSUserName.Text, textboxXSPassword.Text, false).RunAsync(); new TransferHealthCheckSettingsAction(pool, newHealthCheckSettings, textboxXSUserName.Text, textboxXSPassword.Text, true).RunAsync(); } okButton.Enabled = true; DialogResult = DialogResult.OK; Close(); } private void cancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } private void enrollmentCheckBox_CheckedChanged(object sender, EventArgs e) { UpdateButtons(); } private void newAuthenticationRadioButton_CheckedChanged(object sender, EventArgs e) { SetMyCitrixCredentials(existingAuthenticationRadioButton.Checked); } private void radioButton2_CheckedChanged(object sender, EventArgs e) { SetXSCredentials(currentXsCredentialsRadioButton.Checked); testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked && !string.IsNullOrEmpty(textboxXSUserName.Text) && !string.IsNullOrEmpty(textboxXSPassword.Text); } private void SetXSCredentials(bool useCurrent) { if (useCurrent) { textboxXSUserName.Text = pool.Connection.Username; textboxXSPassword.Text = pool.Connection.Password; textboxXSUserName.Enabled = false; textboxXSPassword.Enabled = false; } else { textboxXSUserName.Text = xsUserName; textboxXSPassword.Text = xsPassword; textboxXSUserName.Enabled = true; textboxXSPassword.Enabled = true; } } private void SetMyCitrixCredentials(bool useExisting) { if (useExisting) { //textBoxMyCitrixUsername.Text = String.Empty; //textBoxMyCitrixPassword.Text = String.Empty; textBoxMyCitrixUsername.Enabled = false; textBoxMyCitrixPassword.Enabled = false; } else { //textBoxMyCitrixUsername.Text = String.Empty; //textBoxMyCitrixPassword.Text = String.Empty; textBoxMyCitrixUsername.Enabled = true; textBoxMyCitrixPassword.Enabled = true; } } private bool CheckCredentialsEntered() { if (!enrollmentCheckBox.Checked || !newAuthenticationRadioButton.Checked) return true; if (newAuthenticationRadioButton.Checked && (string.IsNullOrEmpty(textBoxMyCitrixUsername.Text) || string.IsNullOrEmpty(textBoxMyCitrixPassword.Text))) return false; if (newXsCredentialsRadioButton.Checked && (string.IsNullOrEmpty(textboxXSUserName.Text) || string.IsNullOrEmpty(textboxXSPassword.Text))) return false; return true; } private bool CheckCredentialsEntered(out string error) { error = string.Empty; return CheckCredentialsEntered(); } private bool CheckUploadAuthentication(out string error) { error = string.Empty; if (!CheckCredentialsEntered()) return false; var action = new HealthCheckAuthenticationAction(textBoxMyCitrixUsername.Text.Trim(), textBoxMyCitrixPassword.Text.Trim(), Registry.HealthCheckIdentityTokenDomainName, Registry.HealthCheckUploadGrantTokenDomainName, Registry.HealthCheckUploadTokenDomainName, Registry.HealthCheckDiagnosticDomainName, Registry.HealthCheckProductKey, 0, false); try { action.RunExternal(null); } catch { error = action.Exception != null ? action.Exception.Message : Messages.ERROR_UNKNOWN; authenticationToken = null; authenticated = false; return authenticated; } authenticationToken = action.UploadToken; // curent upload token diagnosticToken = action.DiagnosticToken; // curent diagnostic token authenticated = !String.IsNullOrEmpty(authenticationToken) && !String.IsNullOrEmpty(diagnosticToken); return authenticated; } private void credentials_TextChanged(object sender, EventArgs e) { UpdateButtons(); } private void xsCredentials_TextChanged(object sender, EventArgs e) { UpdateButtons(); testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked && !string.IsNullOrEmpty(textboxXSUserName.Text) && !string.IsNullOrEmpty(textboxXSPassword.Text); HideTestCredentialsStatus(); } private void PolicyStatementLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { new HealthCheckPolicyStatementDialog().ShowDialog(this); } private void testCredentialsButton_Click(object sender, EventArgs e) { CheckXenServerCredentials(); } private void CheckXenServerCredentials() { if (!CheckCredentialsEntered()) return; bool passedRbacChecks = false; DelegatedAsyncAction action = new DelegatedAsyncAction(connection, Messages.CREDENTIALS_CHECKING, "", "", delegate { Session elevatedSession = null; try { elevatedSession = connection.ElevatedSession(textboxXSUserName.Text.Trim(), textboxXSPassword.Text); if (elevatedSession != null && (elevatedSession.IsLocalSuperuser || SessionAuthorized(elevatedSession, Role.ValidRoleList("pool.set_health_check_config", connection)))) passedRbacChecks = true; } finally { if (elevatedSession != null) { elevatedSession.Connection.Logout(elevatedSession); elevatedSession = null; } } }, true); action.Completed += delegate { log.DebugFormat("Logging with the new credentials returned: {0} ", passedRbacChecks); Program.Invoke(Program.MainWindow, () => { if (passedRbacChecks) ShowTestCredentialsStatus(Resources._000_Tick_h32bit_16, null); else ShowTestCredentialsStatus(Resources._000_error_h32bit_16, action.Exception != null ? action.Exception.Message : Messages.HEALTH_CHECK_USER_NOT_AUTHORIZED); textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = newXsCredentialsRadioButton.Checked; }); }; log.Debug("Testing logging in with the new credentials"); ShowTestCredentialsStatus(Resources.ajax_loader, null); textboxXSUserName.Enabled = textboxXSPassword.Enabled = testCredentialsButton.Enabled = false; action.RunAsync(); } private void ShowTestCredentialsStatus(Image image, string errorMessage) { testCredentialsStatusImage.Visible = true; testCredentialsStatusImage.Image = image; errorLabel.Text = errorMessage; errorLabel.Visible = !string.IsNullOrEmpty(errorMessage); } private void HideTestCredentialsStatus() { testCredentialsStatusImage.Visible = false; errorLabel.Visible = false; } private bool SessionAuthorized(Session s, List<Role> authorizedRoles) { UserDetails ud = s.CurrentUserDetails; foreach (Role r in s.Roles) { if (authorizedRoles.Contains(r)) { log.DebugFormat("Subject '{0}' is authorized to complete the action", ud.UserName ?? ud.UserSid); return true; } } log.DebugFormat("Subject '{0}' is not authorized to complete the action", ud.UserName ?? ud.UserSid); return false; } } }
// // PlayerEngine.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-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.Collections; using System.Runtime.InteropServices; using System.Threading; using Mono.Unix; using Hyena; using Hyena.Data; using Banshee.Base; using Banshee.Streaming; using Banshee.MediaEngine; using Banshee.ServiceStack; using Banshee.Configuration; using Banshee.Preferences; using Banshee.Collection; namespace Banshee.GStreamer { internal enum GstState { VoidPending = 0, Null = 1, Ready = 2, Paused = 3, Playing = 4 } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerEosCallback (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerErrorCallback (IntPtr player, uint domain, int code, IntPtr error, IntPtr debug); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerStateChangedCallback (IntPtr player, GstState old_state, GstState new_state, GstState pending_state); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerBufferingCallback (IntPtr player, int buffering_progress); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerVisDataCallback (IntPtr player, int channels, int samples, IntPtr data, int bands, IntPtr spectrum); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerNextTrackStartingCallback (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerAboutToFinishCallback (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr VideoPipelineSetupHandler (IntPtr player, IntPtr bus); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void VideoPrepareWindowHandler (IntPtr player); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void BansheePlayerVolumeChangedCallback (IntPtr player, double newVolume); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void GstTaggerTagFoundCallback (IntPtr player, string tagName, ref GLib.Value value); public class PlayerEngine : Banshee.MediaEngine.PlayerEngine, IEqualizer, IVisualizationDataSource, ISupportClutter { internal static string reserved1 = Catalog.GetString ("Enable _gapless playback"); internal static string reserved2 = Catalog.GetString ("Eliminate the small playback gap on track change. Useful for concept albums and classical music"); private uint GST_CORE_ERROR = 0; private uint GST_LIBRARY_ERROR = 0; private uint GST_RESOURCE_ERROR = 0; private uint GST_STREAM_ERROR = 0; private HandleRef handle; private bool is_initialized; private BansheePlayerEosCallback eos_callback; private BansheePlayerErrorCallback error_callback; private BansheePlayerStateChangedCallback state_changed_callback; private BansheePlayerBufferingCallback buffering_callback; private BansheePlayerVisDataCallback vis_data_callback; private VideoPipelineSetupHandler video_pipeline_setup_callback; private VideoPrepareWindowHandler video_prepare_window_callback; private GstTaggerTagFoundCallback tag_found_callback; private BansheePlayerNextTrackStartingCallback next_track_starting_callback; private BansheePlayerAboutToFinishCallback about_to_finish_callback; private BansheePlayerVolumeChangedCallback volume_changed_callback; private bool next_track_pending; private SafeUri pending_uri; private bool pending_maybe_video; private bool buffering_finished; private bool xid_is_set = false; private uint iterate_timeout_id = 0; private bool gapless_enabled; private EventWaitHandle next_track_set; private event VisualizationDataHandler data_available = null; public event VisualizationDataHandler DataAvailable { add { if (value == null) { return; } else if (data_available == null) { bp_set_vis_data_callback (handle, vis_data_callback); } data_available += value; } remove { if (value == null) { return; } data_available -= value; if (data_available == null) { bp_set_vis_data_callback (handle, null); } } } protected override bool DelayedInitialize { get { return true; } } public PlayerEngine () { IntPtr ptr = bp_new (); if (ptr == IntPtr.Zero) { throw new ApplicationException (Catalog.GetString ("Could not initialize GStreamer library")); } handle = new HandleRef (this, ptr); bp_get_error_quarks (out GST_CORE_ERROR, out GST_LIBRARY_ERROR, out GST_RESOURCE_ERROR, out GST_STREAM_ERROR); eos_callback = new BansheePlayerEosCallback (OnEos); error_callback = new BansheePlayerErrorCallback (OnError); state_changed_callback = new BansheePlayerStateChangedCallback (OnStateChange); buffering_callback = new BansheePlayerBufferingCallback (OnBuffering); vis_data_callback = new BansheePlayerVisDataCallback (OnVisualizationData); video_pipeline_setup_callback = new VideoPipelineSetupHandler (OnVideoPipelineSetup); video_prepare_window_callback = new VideoPrepareWindowHandler (OnVideoPrepareWindow); tag_found_callback = new GstTaggerTagFoundCallback (OnTagFound); next_track_starting_callback = new BansheePlayerNextTrackStartingCallback (OnNextTrackStarting); about_to_finish_callback = new BansheePlayerAboutToFinishCallback (OnAboutToFinish); volume_changed_callback = new BansheePlayerVolumeChangedCallback (OnVolumeChanged); bp_set_eos_callback (handle, eos_callback); bp_set_error_callback (handle, error_callback); bp_set_state_changed_callback (handle, state_changed_callback); bp_set_buffering_callback (handle, buffering_callback); bp_set_tag_found_callback (handle, tag_found_callback); bp_set_next_track_starting_callback (handle, next_track_starting_callback); bp_set_video_pipeline_setup_callback (handle, video_pipeline_setup_callback); bp_set_video_prepare_window_callback (handle, video_prepare_window_callback); bp_set_volume_changed_callback (handle, volume_changed_callback); next_track_set = new EventWaitHandle (false, EventResetMode.ManualReset); } protected override void Initialize () { if (ServiceManager.Get<Banshee.GStreamer.Service> () == null) { var service = new Banshee.GStreamer.Service (); ((IExtensionService)service).Initialize (); } if (!bp_initialize_pipeline (handle)) { bp_destroy (handle); handle = new HandleRef (this, IntPtr.Zero); throw new ApplicationException (Catalog.GetString ("Could not initialize GStreamer library")); } OnStateChanged (PlayerState.Ready); InstallPreferences (); ReplayGainEnabled = ReplayGainEnabledSchema.Get (); GaplessEnabled = GaplessEnabledSchema.Get (); Log.InformationFormat ("GStreamer version {0}, gapless: {1}, replaygain: {2}", gstreamer_version_string (), GaplessEnabled, ReplayGainEnabled); is_initialized = true; if (!bp_audiosink_has_volume (handle)) { Volume = (ushort)PlayerEngineService.VolumeSchema.Get (); } } public override void Dispose () { UninstallPreferences (); base.Dispose (); bp_destroy (handle); handle = new HandleRef (this, IntPtr.Zero); is_initialized = false; } public override void Close (bool fullShutdown) { bp_stop (handle, fullShutdown); base.Close (fullShutdown); } protected override void OpenUri (SafeUri uri, bool maybeVideo) { // The GStreamer engine can use the XID of the main window if it ever // needs to bring up the plugin installer so it can be transient to // the main window. if (!xid_is_set) { var service = ServiceManager.Get ("GtkElementsService") as IPropertyStoreExpose; if (service != null) { bp_set_application_gdk_window (handle, service.PropertyStore.Get<IntPtr> ("PrimaryWindow.RawHandle")); } xid_is_set = true; } IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (uri.AbsoluteUri); try { if (!bp_open (handle, uri_ptr, maybeVideo)) { throw new ApplicationException ("Could not open resource"); } } finally { GLib.Marshaller.Free (uri_ptr); } } public override void Play () { bp_play (handle); } public override void Pause () { bp_pause (handle); } public override void SetNextTrackUri (SafeUri uri, bool maybeVideo) { next_track_pending = false; if (next_track_set.WaitOne (0, false)) { // We're not waiting for the next track to be set. // This means that we've missed the window for gapless. // Save this URI to be played when we receive EOS. pending_uri = uri; pending_maybe_video = maybeVideo; return; } // If there isn't a next track for us, release the block on the about-to-finish callback. if (uri == null) { next_track_set.Set (); return; } IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (uri.AbsoluteUri); try { bp_set_next_track (handle, uri_ptr, maybeVideo); } finally { GLib.Marshaller.Free (uri_ptr); next_track_set.Set (); } } public override void VideoExpose (IntPtr window, bool direct) { bp_video_window_expose (handle, window, direct); } public override void VideoWindowRealize (IntPtr window) { bp_video_window_realize (handle, window); } public override IntPtr [] GetBaseElements () { IntPtr [] elements = new IntPtr[3]; if (bp_get_pipeline_elements (handle, out elements[0], out elements[1], out elements[2])) { return elements; } return null; } private void OnEos (IntPtr player) { StopIterating (); Close (false); OnEventChanged (PlayerEvent.EndOfStream); if (!next_track_pending && (!GaplessEnabled || (CurrentTrack != null && CurrentTrack.HasAttribute (TrackMediaAttributes.VideoStream)))) { // We don't request next track in OnEoS if gapless playback is enabled and current track has no video stream contained. // The request next track is already called in OnAboutToFinish(). OnEventChanged (PlayerEvent.RequestNextTrack); } else if (pending_uri != null) { Log.Warning ("[Gapless] EOS signalled while waiting for next track. This means that Banshee " + "was too slow at calculating what track to play next. " + "If this happens frequently, please file a bug"); OnStateChanged (PlayerState.Loading); OpenUri (pending_uri, pending_maybe_video); Play (); pending_uri = null; } else if (!GaplessEnabled || (CurrentTrack != null && CurrentTrack.HasAttribute (TrackMediaAttributes.VideoStream))) { // This should be unreachable - the RequestNextTrack event is delegated to the main thread // and so blocks the bus callback from delivering the EOS message. // // Playback should continue as normal from here, when the RequestNextTrack message gets handled. Log.Warning ("[Gapless] EndOfStream message received before the next track has been set. " + "If this happens frequently, please file a bug"); } else { Log.Debug ("[Gapless] Reach the last music under repeat off mode"); } } private bool OnIterate () { // Actual iteration. OnEventChanged (PlayerEvent.Iterate); // Run forever until we are stopped return true; } private void StartIterating () { if (iterate_timeout_id > 0) { GLib.Source.Remove (iterate_timeout_id); iterate_timeout_id = 0; } iterate_timeout_id = GLib.Timeout.Add (200, OnIterate); } private void StopIterating () { if (iterate_timeout_id > 0) { GLib.Source.Remove (iterate_timeout_id); iterate_timeout_id = 0; } } private void OnNextTrackStarting (IntPtr player) { if (GaplessEnabled) { // Must do it here because the next track is already playing. // If the state is anything other than loaded, assume we were just playing a track and should // EoS it and increment its playcount etc. if (CurrentState != PlayerState.Loaded) { ServiceManager.PlayerEngine.IncrementLastPlayed (1.0); OnEventChanged (PlayerEvent.EndOfStream); OnEventChanged (PlayerEvent.StartOfStream); } } } private void OnAboutToFinish (IntPtr player) { // This is needed to make Shuffle-by-* work. // Shuffle-by-* uses the LastPlayed field to determine what track in the grouping to play next. // Therefore, we need to update this before requesting the next track. // // This will be overridden by IncrementLastPlayed () called by // PlaybackControllerService's EndOfStream handler. CurrentTrack.UpdateLastPlayed (); next_track_set.Reset (); pending_uri = null; next_track_pending = true; OnEventChanged (PlayerEvent.RequestNextTrack); // Gapless playback with Playbin2 requires that the about-to-finish callback does not return until // the next uri has been set. Block here for a second or until the RequestNextTrack event has // finished triggering. if (!next_track_set.WaitOne (1000, false)) { Log.Debug ("[Gapless] Timed out while waiting for next_track_set to be raised"); next_track_set.Set (); } } private void OnStateChange (IntPtr player, GstState old_state, GstState new_state, GstState pending_state) { // Start by clearing any timeout we might have StopIterating (); if (CurrentState != PlayerState.Loaded && old_state == GstState.Ready && new_state == GstState.Paused && pending_state == GstState.Playing) { if (ready_timeout != 0) { Application.IdleTimeoutRemove (ready_timeout); ready_timeout = 0; } OnStateChanged (PlayerState.Loaded); return; } else if (old_state == GstState.Paused && new_state == GstState.Playing && pending_state == GstState.VoidPending) { if (CurrentState == PlayerState.Loaded) { OnEventChanged (PlayerEvent.StartOfStream); } OnStateChanged (PlayerState.Playing); // Start iterating only when going to playing StartIterating (); return; } else if (CurrentState == PlayerState.Playing && old_state == GstState.Playing && new_state == GstState.Paused) { OnStateChanged (PlayerState.Paused); return; } else if (new_state == GstState.Ready && pending_state == GstState.Playing) { if (ready_timeout == 0) { ready_timeout = Application.RunTimeout (1000, OnReadyTimeout); } return; } } private uint ready_timeout; private bool OnReadyTimeout () { ready_timeout = 0; var uri = CurrentUri; if (CurrentState == PlayerState.Loading && Position == 0 && uri != null && uri.IsLocalPath) { // This is a dirty workaround. I was seeing the playback get stuck on track transition, // about one in 20 songs, where it would load the new track's duration, but be stuck at 0:00, // but if I moved the seek slider it would unstick it, hence setting Position... Log.WarningFormat ("Seem to be stuck loading {0}, so re-trying", uri); Position = 0; } return false; } private void OnError (IntPtr player, uint domain, int code, IntPtr error, IntPtr debug) { Close (true); string error_message = error == IntPtr.Zero ? Catalog.GetString ("Unknown Error") : GLib.Marshaller.Utf8PtrToString (error); if (domain == GST_RESOURCE_ERROR) { GstResourceError domain_code = (GstResourceError) code; if (CurrentTrack != null) { switch (domain_code) { case GstResourceError.NotFound: CurrentTrack.SavePlaybackError (StreamPlaybackError.ResourceNotFound); break; default: break; } } Log.Error (String.Format ("GStreamer resource error: {0}", domain_code), false); } else if (domain == GST_STREAM_ERROR) { GstStreamError domain_code = (GstStreamError) code; if (CurrentTrack != null) { switch (domain_code) { case GstStreamError.CodecNotFound: CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound); break; default: break; } } Log.Error (String.Format("GStreamer stream error: {0}", domain_code), false); } else if (domain == GST_CORE_ERROR) { GstCoreError domain_code = (GstCoreError) code; if (CurrentTrack != null) { switch (domain_code) { case GstCoreError.MissingPlugin: CurrentTrack.SavePlaybackError (StreamPlaybackError.CodecNotFound); break; default: break; } } if (domain_code != GstCoreError.MissingPlugin) { Log.Error (String.Format("GStreamer core error: {0}", (GstCoreError) code), false); } } else if (domain == GST_LIBRARY_ERROR) { Log.Error (String.Format("GStreamer library error: {0}", (GstLibraryError) code), false); } OnEventChanged (new PlayerEventErrorArgs (error_message)); } private void OnBuffering (IntPtr player, int progress) { if (buffering_finished && progress >= 100) { return; } buffering_finished = progress >= 100; OnEventChanged (new PlayerEventBufferingArgs ((double) progress / 100.0)); } private void OnTagFound (IntPtr player, string tagName, ref GLib.Value value) { OnTagFound (ProcessNativeTagResult (tagName, ref value)); } private void OnVisualizationData (IntPtr player, int channels, int samples, IntPtr data, int bands, IntPtr spectrum) { VisualizationDataHandler handler = data_available; if (handler == null) { return; } float [] flat = new float[channels * samples]; Marshal.Copy (data, flat, 0, flat.Length); float [][] cbd = new float[channels][]; for (int i = 0; i < channels; i++) { float [] channel = new float[samples]; Array.Copy (flat, i * samples, channel, 0, samples); cbd[i] = channel; } float [] spec = new float[bands]; Marshal.Copy (spectrum, spec, 0, bands); try { handler (cbd, new float[][] { spec }); } catch (Exception e) { Log.Exception ("Uncaught exception during visualization data post.", e); } } private void OnVolumeChanged (IntPtr player, double newVolume) { OnEventChanged (PlayerEvent.Volume); } private static StreamTag ProcessNativeTagResult (string tagName, ref GLib.Value valueRaw) { if (tagName == String.Empty || tagName == null) { return StreamTag.Zero; } object value = null; try { value = valueRaw.Val; } catch { return StreamTag.Zero; } if (value == null) { return StreamTag.Zero; } StreamTag item; item.Name = tagName; item.Value = value; return item; } public override ushort Volume { get { return is_initialized ? (ushort)Math.Round (bp_get_volume (handle) * 100.0) : (ushort)0; } set { if (!is_initialized) { return; } bp_set_volume (handle, value / 100.0); if (!bp_audiosink_has_volume (handle)) { PlayerEngineService.VolumeSchema.Set ((int)value); } OnEventChanged (PlayerEvent.Volume); } } public override uint Position { get { return (uint)bp_get_position(handle); } set { bp_set_position (handle, (ulong)value); OnEventChanged (PlayerEvent.Seek); } } public override bool CanSeek { get { return bp_can_seek (handle); } } public override uint Length { get { return (uint)bp_get_duration (handle); } } public override string Id { get { return "gstreamer"; } } public override string Name { get { return "GStreamer 0.10"; } } private bool? supports_equalizer = null; public override bool SupportsEqualizer { get { if (supports_equalizer == null) { supports_equalizer = bp_equalizer_is_supported (handle); } return supports_equalizer.Value; } } public override VideoDisplayContextType VideoDisplayContextType { get { return bp_video_get_display_context_type (handle); } } public override IntPtr VideoDisplayContext { set { bp_video_set_display_context (handle, value); } get { return bp_video_get_display_context (handle); } } public double AmplifierLevel { set { double scale = Math.Pow (10.0, value / 20.0); bp_equalizer_set_preamp_level (handle, scale); } } public int [] BandRange { get { int min = -1; int max = -1; bp_equalizer_get_bandrange (handle, out min, out max); return new int [] { min, max }; } } public uint [] EqualizerFrequencies { get { uint count = bp_equalizer_get_nbands (handle); double [] freq = new double[count]; bp_equalizer_get_frequencies (handle, out freq); uint [] ret = new uint[count]; for (int i = 0; i < count; i++) { ret[i] = (uint)freq[i]; } return ret; } } public void SetEqualizerGain (uint band, double gain) { bp_equalizer_set_gain (handle, band, gain); } private static string [] source_capabilities = { "file", "http", "cdda" }; public override IEnumerable SourceCapabilities { get { return source_capabilities; } } private static string [] decoder_capabilities = { "ogg", "wma", "asf", "flac" }; public override IEnumerable ExplicitDecoderCapabilities { get { return decoder_capabilities; } } private bool ReplayGainEnabled { get { return bp_replaygain_get_enabled (handle); } set { bp_replaygain_set_enabled (handle, value); } } private bool GaplessEnabled { get { return gapless_enabled; } set { if (bp_supports_gapless (handle)) { gapless_enabled = value; if (value) { bp_set_about_to_finish_callback (handle, about_to_finish_callback); } else { bp_set_about_to_finish_callback (handle, null); } } else { gapless_enabled = false; next_track_pending = false; } } } public override int SubtitleCount { get { return bp_get_subtitle_count (handle); } } public override int SubtitleIndex { set { bp_set_subtitle (handle, value); } } public override SafeUri SubtitleUri { set { if (value != null) { IntPtr uri_ptr = GLib.Marshaller.StringToPtrGStrdup (value.AbsoluteUri); try { bp_set_subtitle_uri (handle, uri_ptr); } finally { GLib.Marshaller.Free (uri_ptr); } } } get { IntPtr uri_ptr = IntPtr.Zero; try { uri_ptr = bp_get_subtitle_uri (handle); string uri = GLib.Marshaller.Utf8PtrToString (uri_ptr); return new SafeUri(uri); } finally { GLib.Marshaller.Free (uri_ptr); } } } public override string GetSubtitleDescription (int index) { IntPtr desc_ptr = IntPtr.Zero; try { desc_ptr = bp_get_subtitle_description (handle, index); return GLib.Marshaller.Utf8PtrToString (desc_ptr); } finally { GLib.Marshaller.Free (desc_ptr); } } #region ISupportClutter private IntPtr clutter_video_sink; private IntPtr clutter_video_texture; private bool clutter_video_sink_enabled; public void EnableClutterVideoSink (IntPtr videoTexture) { clutter_video_sink_enabled = true; clutter_video_texture = videoTexture; } public void DisableClutterVideoSink () { clutter_video_sink_enabled = false; clutter_video_texture = IntPtr.Zero; } public bool IsClutterVideoSinkInitialized { get { return clutter_video_sink_enabled && clutter_video_texture != IntPtr.Zero && clutter_video_sink != IntPtr.Zero; } } private IntPtr OnVideoPipelineSetup (IntPtr player, IntPtr bus) { try { if (clutter_video_sink_enabled) { if (clutter_video_sink != IntPtr.Zero) { // FIXME: does this get unreffed by the pipeline? } clutter_video_sink = clutter_gst_video_sink_new (clutter_video_texture); } else if (!clutter_video_sink_enabled && clutter_video_sink != IntPtr.Zero) { clutter_video_sink = IntPtr.Zero; clutter_video_texture = IntPtr.Zero; } } catch (Exception e) { Log.Exception ("Clutter support could not be initialized", e); clutter_video_sink = IntPtr.Zero; clutter_video_texture = IntPtr.Zero; clutter_video_sink_enabled = false; } return clutter_video_sink; } private void OnVideoPrepareWindow (IntPtr player) { OnEventChanged (PlayerEvent.PrepareVideoWindow); } #endregion #region Preferences private PreferenceBase replaygain_preference; private PreferenceBase gapless_preference; private void InstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } replaygain_preference = service["general"]["misc"].Add (new SchemaPreference<bool> (ReplayGainEnabledSchema, Catalog.GetString ("_Enable ReplayGain correction"), Catalog.GetString ("For tracks that have ReplayGain data, automatically scale (normalize) playback volume"), delegate { ReplayGainEnabled = ReplayGainEnabledSchema.Get (); } )); if (bp_supports_gapless (handle)) { gapless_preference = service["general"]["misc"].Add (new SchemaPreference<bool> (GaplessEnabledSchema, Catalog.GetString ("Enable _gapless playback"), Catalog.GetString ("Eliminate the small playback gap on track change. Useful for concept albums and classical music."), delegate { GaplessEnabled = GaplessEnabledSchema.Get (); } )); } } private void UninstallPreferences () { PreferenceService service = ServiceManager.Get<PreferenceService> (); if (service == null) { return; } service["general"]["misc"].Remove (replaygain_preference); if (bp_supports_gapless (handle)) { service["general"]["misc"].Remove (gapless_preference); } replaygain_preference = null; gapless_preference = null; } public static readonly SchemaEntry<bool> ReplayGainEnabledSchema = new SchemaEntry<bool> ( "player_engine", "replay_gain_enabled", false, "Enable ReplayGain", "If ReplayGain data is present on tracks when playing, allow volume scaling" ); public static readonly SchemaEntry<bool> GaplessEnabledSchema = new SchemaEntry<bool> ( "player_engine", "gapless_playback_enabled", true, "Enable gapless playback", "Eliminate the small playback gap on track change. Useful for concept albums & classical music." ); #endregion [DllImport ("libbanshee.dll")] private static extern IntPtr bp_new (); [DllImport ("libbanshee.dll")] private static extern bool bp_initialize_pipeline (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_destroy (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_set_eos_callback (HandleRef player, BansheePlayerEosCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_error_callback (HandleRef player, BansheePlayerErrorCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_vis_data_callback (HandleRef player, BansheePlayerVisDataCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_state_changed_callback (HandleRef player, BansheePlayerStateChangedCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_buffering_callback (HandleRef player, BansheePlayerBufferingCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_video_pipeline_setup_callback (HandleRef player, VideoPipelineSetupHandler cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_tag_found_callback (HandleRef player, GstTaggerTagFoundCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_video_prepare_window_callback (HandleRef player, VideoPrepareWindowHandler cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_next_track_starting_callback (HandleRef player, BansheePlayerNextTrackStartingCallback cb); [DllImport ("libbanshee.dll")] private static extern void bp_set_about_to_finish_callback (HandleRef player, BansheePlayerAboutToFinishCallback cb); [DllImport ("libbanshee.dll")] private static extern bool bp_supports_gapless (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_open (HandleRef player, IntPtr uri, bool maybeVideo); [DllImport ("libbanshee.dll")] private static extern void bp_stop (HandleRef player, bool nullstate); [DllImport ("libbanshee.dll")] private static extern void bp_pause (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_play (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_set_next_track (HandleRef player, IntPtr uri, bool maybeVideo); [DllImport ("libbanshee.dll")] private static extern void bp_set_volume (HandleRef player, double volume); [DllImport("libbanshee.dll")] private static extern double bp_get_volume (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_set_volume_changed_callback (HandleRef player, BansheePlayerVolumeChangedCallback cb); [DllImport ("libbanshee.dll")] private static extern bool bp_can_seek (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_audiosink_has_volume (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_set_position (HandleRef player, ulong time_ms); [DllImport ("libbanshee.dll")] private static extern ulong bp_get_position (HandleRef player); [DllImport ("libbanshee.dll")] private static extern ulong bp_get_duration (HandleRef player); [DllImport ("libbanshee.dll")] private static extern bool bp_get_pipeline_elements (HandleRef player, out IntPtr playbin, out IntPtr audiobin, out IntPtr audiotee); [DllImport ("libbanshee.dll")] private static extern void bp_set_application_gdk_window (HandleRef player, IntPtr window); [DllImport ("libbanshee.dll")] private static extern VideoDisplayContextType bp_video_get_display_context_type (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_video_set_display_context (HandleRef player, IntPtr displayContext); [DllImport ("libbanshee.dll")] private static extern IntPtr bp_video_get_display_context (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_video_window_expose (HandleRef player, IntPtr displayContext, bool direct); [DllImport ("libbanshee.dll")] private static extern void bp_video_window_realize (HandleRef player, IntPtr window); [DllImport ("libbanshee.dll")] private static extern void bp_get_error_quarks (out uint core, out uint library, out uint resource, out uint stream); [DllImport ("libbanshee.dll")] private static extern bool bp_equalizer_is_supported (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_set_preamp_level (HandleRef player, double level); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_set_gain (HandleRef player, uint bandnum, double gain); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_get_bandrange (HandleRef player, out int min, out int max); [DllImport ("libbanshee.dll")] private static extern uint bp_equalizer_get_nbands (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_equalizer_get_frequencies (HandleRef player, [MarshalAs (UnmanagedType.LPArray)] out double [] freq); [DllImport ("libbanshee.dll")] private static extern void bp_replaygain_set_enabled (HandleRef player, bool enabled); [DllImport ("libbanshee.dll")] private static extern bool bp_replaygain_get_enabled (HandleRef player); [DllImport ("libbanshee.dll")] private static extern IntPtr clutter_gst_video_sink_new (IntPtr texture); [DllImport ("libbanshee.dll")] private static extern int bp_get_subtitle_count (HandleRef player); [DllImport ("libbanshee.dll")] private static extern void bp_set_subtitle (HandleRef player, int index); [DllImport ("libbanshee.dll")] private static extern void bp_set_subtitle_uri (HandleRef player, IntPtr uri); [DllImport ("libbanshee.dll")] private static extern IntPtr bp_get_subtitle_uri (HandleRef player); [DllImport ("libbanshee.dll")] private static extern IntPtr bp_get_subtitle_description (HandleRef player, int index); [DllImport ("libbanshee.dll")] private static extern string gstreamer_version_string (); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Document = Lucene.Net.Documents.Document; using Fieldable = Lucene.Net.Documents.Fieldable; using Directory = Lucene.Net.Store.Directory; using IndexInput = Lucene.Net.Store.IndexInput; using IndexOutput = Lucene.Net.Store.IndexOutput; using StringHelper = Lucene.Net.Util.StringHelper; namespace Lucene.Net.Index { /// <summary>Access to the Fieldable Info file that describes document fields and whether or /// not they are indexed. Each segment has a separate Fieldable Info file. Objects /// of this class are thread-safe for multiple readers, but only one thread can /// be adding documents at a time, with no other reader or writer threads /// accessing this object. /// </summary> public sealed class FieldInfos : System.ICloneable { // Used internally (ie not written to *.fnm files) for pre-2.9 files public const int FORMAT_PRE = - 1; // First used in 2.9; prior to 2.9 there was no format header public const int FORMAT_START = - 2; internal static readonly int CURRENT_FORMAT = FORMAT_START; internal const byte IS_INDEXED = (byte) (0x1); internal const byte STORE_TERMVECTOR = (byte) (0x2); internal const byte STORE_POSITIONS_WITH_TERMVECTOR = (byte) (0x4); internal const byte STORE_OFFSET_WITH_TERMVECTOR = (byte) (0x8); internal const byte OMIT_NORMS = (byte) (0x10); internal const byte STORE_PAYLOADS = (byte) (0x20); internal const byte OMIT_TERM_FREQ_AND_POSITIONS = (byte) (0x40); private System.Collections.ArrayList byNumber = new System.Collections.ArrayList(); private System.Collections.Hashtable byName = new System.Collections.Hashtable(); private int format; public /*internal*/ FieldInfos() { } /// <summary> Construct a FieldInfos object using the directory and the name of the file /// IndexInput /// </summary> /// <param name="d">The directory to open the IndexInput from /// </param> /// <param name="name">The name of the file to open the IndexInput from in the Directory /// </param> /// <throws> IOException </throws> public /*internal*/ FieldInfos(Directory d, System.String name) { IndexInput input = d.OpenInput(name); try { try { Read(input, name); } catch (System.IO.IOException ioe) { if (format == FORMAT_PRE) { // LUCENE-1623: FORMAT_PRE (before there was a // format) may be 2.3.2 (pre-utf8) or 2.4.x (utf8) // encoding; retry with input set to pre-utf8 input.Seek(0); input.SetModifiedUTF8StringsMode(); byNumber.Clear(); byName.Clear(); try { Read(input, name); } catch (System.Exception t) { // Ignore any new exception & throw original IOE throw ioe; } } else { // The IOException cannot be caused by // LUCENE-1623, so re-throw it throw ioe; } } } finally { input.Close(); } } /// <summary> Returns a deep clone of this FieldInfos instance.</summary> public System.Object Clone() { lock (this) { FieldInfos fis = new FieldInfos(); int numField = byNumber.Count; for (int i = 0; i < numField; i++) { FieldInfo fi = (FieldInfo)((FieldInfo)byNumber[i]).Clone(); fis.byNumber.Add(fi); fis.byName[fi.name] = fi; } return fis; } } /// <summary>Adds field info for a Document. </summary> public void Add(Document doc) { lock (this) { System.Collections.IList fields = doc.GetFields(); System.Collections.IEnumerator fieldIterator = fields.GetEnumerator(); while (fieldIterator.MoveNext()) { Fieldable field = (Fieldable) fieldIterator.Current; Add(field.Name(), field.IsIndexed(), field.IsTermVectorStored(), field.IsStorePositionWithTermVector(), field.IsStoreOffsetWithTermVector(), field.GetOmitNorms(), false, field.GetOmitTf()); } } } /// <summary>Returns true if any fields do not omitTermFreqAndPositions </summary> internal bool HasProx() { int numFields = byNumber.Count; for (int i = 0; i < numFields; i++) { FieldInfo fi = FieldInfo(i); if (fi.isIndexed && !fi.omitTermFreqAndPositions) { return true; } } return false; } /// <summary> Add fields that are indexed. Whether they have termvectors has to be specified. /// /// </summary> /// <param name="names">The names of the fields /// </param> /// <param name="storeTermVectors">Whether the fields store term vectors or not /// </param> /// <param name="storePositionWithTermVector">true if positions should be stored. /// </param> /// <param name="storeOffsetWithTermVector">true if offsets should be stored /// </param> public void AddIndexed(System.Collections.ICollection names, bool storeTermVectors, bool storePositionWithTermVector, bool storeOffsetWithTermVector) { lock (this) { System.Collections.IEnumerator i = names.GetEnumerator(); while (i.MoveNext()) { Add((System.String) i.Current, true, storeTermVectors, storePositionWithTermVector, storeOffsetWithTermVector); } } } /// <summary> Assumes the fields are not storing term vectors. /// /// </summary> /// <param name="names">The names of the fields /// </param> /// <param name="isIndexed">Whether the fields are indexed or not /// /// </param> /// <seealso cref="Add(String, boolean)"> /// </seealso> public void Add(System.Collections.Generic.ICollection<string> names, bool isIndexed) { lock (this) { System.Collections.IEnumerator i = names.GetEnumerator(); while (i.MoveNext()) { Add((System.String) i.Current, isIndexed); } } } /// <summary> Calls 5 parameter add with false for all TermVector parameters. /// /// </summary> /// <param name="name">The name of the Fieldable /// </param> /// <param name="isIndexed">true if the field is indexed /// </param> /// <seealso cref="Add(String, boolean, boolean, boolean, boolean)"> /// </seealso> public void Add(System.String name, bool isIndexed) { lock (this) { Add(name, isIndexed, false, false, false, false); } } /// <summary> Calls 5 parameter add with false for term vector positions and offsets. /// /// </summary> /// <param name="name">The name of the field /// </param> /// <param name="isIndexed"> true if the field is indexed /// </param> /// <param name="storeTermVector">true if the term vector should be stored /// </param> public void Add(System.String name, bool isIndexed, bool storeTermVector) { lock (this) { Add(name, isIndexed, storeTermVector, false, false, false); } } /// <summary>If the field is not yet known, adds it. If it is known, checks to make /// sure that the isIndexed flag is the same as was given previously for this /// field. If not - marks it as being indexed. Same goes for the TermVector /// parameters. /// /// </summary> /// <param name="name">The name of the field /// </param> /// <param name="isIndexed">true if the field is indexed /// </param> /// <param name="storeTermVector">true if the term vector should be stored /// </param> /// <param name="storePositionWithTermVector">true if the term vector with positions should be stored /// </param> /// <param name="storeOffsetWithTermVector">true if the term vector with offsets should be stored /// </param> public void Add(System.String name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector) { lock (this) { Add(name, isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, false); } } /// <summary>If the field is not yet known, adds it. If it is known, checks to make /// sure that the isIndexed flag is the same as was given previously for this /// field. If not - marks it as being indexed. Same goes for the TermVector /// parameters. /// /// </summary> /// <param name="name">The name of the field /// </param> /// <param name="isIndexed">true if the field is indexed /// </param> /// <param name="storeTermVector">true if the term vector should be stored /// </param> /// <param name="storePositionWithTermVector">true if the term vector with positions should be stored /// </param> /// <param name="storeOffsetWithTermVector">true if the term vector with offsets should be stored /// </param> /// <param name="omitNorms">true if the norms for the indexed field should be omitted /// </param> public void Add(System.String name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms) { lock (this) { Add(name, isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, false, false); } } /// <summary>If the field is not yet known, adds it. If it is known, checks to make /// sure that the isIndexed flag is the same as was given previously for this /// field. If not - marks it as being indexed. Same goes for the TermVector /// parameters. /// /// </summary> /// <param name="name">The name of the field /// </param> /// <param name="isIndexed">true if the field is indexed /// </param> /// <param name="storeTermVector">true if the term vector should be stored /// </param> /// <param name="storePositionWithTermVector">true if the term vector with positions should be stored /// </param> /// <param name="storeOffsetWithTermVector">true if the term vector with offsets should be stored /// </param> /// <param name="omitNorms">true if the norms for the indexed field should be omitted /// </param> /// <param name="storePayloads">true if payloads should be stored for this field /// </param> /// <param name="omitTermFreqAndPositions">true if term freqs should be omitted for this field /// </param> public FieldInfo Add(System.String name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms, bool storePayloads, bool omitTermFreqAndPositions) { lock (this) { FieldInfo fi = FieldInfo(name); if (fi == null) { return AddInternal(name, isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions); } else { fi.Update(isIndexed, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions); } return fi; } } private FieldInfo AddInternal(System.String name, bool isIndexed, bool storeTermVector, bool storePositionWithTermVector, bool storeOffsetWithTermVector, bool omitNorms, bool storePayloads, bool omitTermFreqAndPositions) { name = StringHelper.Intern(name); FieldInfo fi = new FieldInfo(name, isIndexed, byNumber.Count, storeTermVector, storePositionWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions); byNumber.Add(fi); byName[name] = fi; return fi; } public int FieldNumber(System.String fieldName) { FieldInfo fi = FieldInfo(fieldName); return (fi != null)?fi.number:- 1; } public FieldInfo FieldInfo(System.String fieldName) { return (FieldInfo) byName[fieldName]; } /// <summary> Return the fieldName identified by its number. /// /// </summary> /// <param name="fieldNumber"> /// </param> /// <returns> the fieldName or an empty string when the field /// with the given number doesn't exist. /// </returns> public System.String FieldName(int fieldNumber) { FieldInfo fi = FieldInfo(fieldNumber); return (fi != null)?fi.name:""; } /// <summary> Return the fieldinfo object referenced by the fieldNumber.</summary> /// <param name="fieldNumber"> /// </param> /// <returns> the FieldInfo object or null when the given fieldNumber /// doesn't exist. /// </returns> public FieldInfo FieldInfo(int fieldNumber) { return (fieldNumber >= 0)?(FieldInfo) byNumber[fieldNumber]:null; } public int Size() { return byNumber.Count; } public bool HasVectors() { bool hasVectors = false; for (int i = 0; i < Size(); i++) { if (FieldInfo(i).storeTermVector) { hasVectors = true; break; } } return hasVectors; } public void Write(Directory d, System.String name) { IndexOutput output = d.CreateOutput(name); try { Write(output); } finally { output.Close(); } } public void Write(IndexOutput output) { output.WriteVInt(CURRENT_FORMAT); output.WriteVInt(Size()); for (int i = 0; i < Size(); i++) { FieldInfo fi = FieldInfo(i); byte bits = (byte) (0x0); if (fi.isIndexed) bits |= IS_INDEXED; if (fi.storeTermVector) bits |= STORE_TERMVECTOR; if (fi.storePositionWithTermVector) bits |= STORE_POSITIONS_WITH_TERMVECTOR; if (fi.storeOffsetWithTermVector) bits |= STORE_OFFSET_WITH_TERMVECTOR; if (fi.omitNorms) bits |= OMIT_NORMS; if (fi.storePayloads) bits |= STORE_PAYLOADS; if (fi.omitTermFreqAndPositions) bits |= OMIT_TERM_FREQ_AND_POSITIONS; output.WriteString(fi.name); output.WriteByte(bits); } } private void Read(IndexInput input, System.String fileName) { int firstInt = input.ReadVInt(); if (firstInt < 0) { // This is a real format format = firstInt; } else { format = FORMAT_PRE; } if (format != FORMAT_PRE & format != FORMAT_START) { throw new CorruptIndexException("unrecognized format " + format + " in file \"" + fileName + "\""); } int size; if (format == FORMAT_PRE) { size = firstInt; } else { size = input.ReadVInt(); //read in the size } for (int i = 0; i < size; i++) { System.String name = StringHelper.Intern(input.ReadString()); byte bits = input.ReadByte(); bool isIndexed = (bits & IS_INDEXED) != 0; bool storeTermVector = (bits & STORE_TERMVECTOR) != 0; bool storePositionsWithTermVector = (bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0; bool storeOffsetWithTermVector = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0; bool omitNorms = (bits & OMIT_NORMS) != 0; bool storePayloads = (bits & STORE_PAYLOADS) != 0; bool omitTermFreqAndPositions = (bits & OMIT_TERM_FREQ_AND_POSITIONS) != 0; AddInternal(name, isIndexed, storeTermVector, storePositionsWithTermVector, storeOffsetWithTermVector, omitNorms, storePayloads, omitTermFreqAndPositions); } if (input.GetFilePointer() != input.Length()) { throw new CorruptIndexException("did not read all bytes from file \"" + fileName + "\": read " + input.GetFilePointer() + " vs size " + input.Length()); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security.AccessControl; using System.Security.Principal; using System.Text; using System.Threading; using System.Threading.Tasks; using Bloom; using Bloom.Api; using Bloom.Book; using Bloom.Collection; using Bloom.TeamCollection; using Bloom.web; using BloomTemp; using BloomTests.DataBuilders; using Moq; using Newtonsoft.Json; using NUnit.Framework; namespace BloomTests.TeamCollection { /// <summary> /// This class sets up a local team collection folder (on the filesystem) and TeamCollectionAPI /// before starting the tests. /// </summary> public class TeamCollectionApiTests { private TeamCollectionApi _api; private TemporaryFolder _localCollection; private TeamCollectionManager _tcManager; [OneTimeSetUp] public void OneTimeSetUp() { _localCollection = new TemporaryFolder("TeamCollectionApiTests"); var collectionPath = Path.Combine(_localCollection.FolderPath, Path.ChangeExtension(Path.GetFileName(_localCollection.FolderPath), ".bloomCollection")); _tcManager = new TeamCollectionManager(collectionPath, new BloomWebSocketServer(), new BookRenamedEvent(), null, null, null, null); _api = new TeamCollectionApi(new CurrentEditableCollectionSelection(), new CollectionSettings(collectionPath), new BookSelection(), _tcManager, null, null, null); } [OneTimeTearDown] public void OneTimeTearDown() { _localCollection.Dispose(); } // a hack for making a settings with a specified name class ControlledNameSettings : CollectionSettings { public ControlledNameSettings(string name) : base() { CollectionName = name; } } [Test] public void ProblemsWithLocation_NoProblem_Succeeds() { using (var tempFolder = new TemporaryFolder(MethodBase.GetCurrentMethod().Name)) { var settings = new ControlledNameSettings("SomeCollection"); _tcManager.Settings = settings; Assert.That(_api.ProblemsWithLocation(tempFolder.FolderPath), Is.EqualTo("")); } } [Test] public void ProblemsWithLocation_ExistingTC_Fails() { using (var tempFolder = new TemporaryFolder(MethodBase.GetCurrentMethod().Name)) { File.WriteAllText(Path.Combine(tempFolder.FolderPath, "Join this Team Collection.JoinBloomTC"), "some random content"); Assert.That(_api.ProblemsWithLocation(tempFolder.FolderPath), Is.EqualTo("There is a problem with this location")); } } [Test] public void ProblemsWithLocation_BloomCollection_Fails() { using (var tempFolder = new TemporaryFolder(MethodBase.GetCurrentMethod().Name)) { File.WriteAllText(Path.Combine(tempFolder.FolderPath, "something.bloomCollection"), "some random content"); Assert.That(_api.ProblemsWithLocation(tempFolder.FolderPath), Is.EqualTo("There is a problem with this location")); } } [Test] public void ProblemsWithLocation_TCExists_Fails() { using (var tempFolder = new TemporaryFolder(MethodBase.GetCurrentMethod().Name)) { var settings = new ControlledNameSettings("SomeCollection"); _tcManager.Settings = settings; Directory.CreateDirectory(Path.Combine(tempFolder.FolderPath, "SomeCollection - TC")); Assert.That(_api.ProblemsWithLocation(tempFolder.FolderPath), Is.EqualTo("There is a problem with this location")); } } [Test] public void MakeLockFailedMessageFromException_CannotLockException_AgentDropbox_MakesExpectedMessage() { var ex = new FolderTeamCollection.CannotLockException("We can't do it") { SyncAgent = "Dropbox" }; var msg =_api.MakeLockFailedMessageFromException(ex, "c:/nowhere/My book"); Assert.That(msg.TextForDisplay, Does.Contain("Bloom was not able to check out \"My book\". Some other program may be busy with it. This may just be Dropbox synchronizing the file. Please try again later. If the problem continues, restart your computer.")); } [Test] public void MakeLockFailedMessageFromException_CannotLockException_AgentUnknown_MakesExpectedMessage() { var ex = new FolderTeamCollection.CannotLockException("We can't do it") { SyncAgent = "Unknown" }; var msg = _api.MakeLockFailedMessageFromException(ex, "c:/nowhere/Some book"); Assert.That(msg.TextForDisplay, Does.Contain("Bloom was not able to check out \"Some book\". Some other program may be busy with it. This may just be something synchronizing the file. Please try again later. If the problem continues, restart your computer.")); } [Test] public void MakeLockFailedMessageFromException_OtherException_MakesExpectedMessage() { var ex = new ArgumentException("We can't do it"); var msg = _api.MakeLockFailedMessageFromException(ex, "c:/nowhere/Other book"); Assert.That(msg.TextForDisplay, Does.Contain("Bloom was not able to check out \"Other book\".")); } [Test] public void ProblemsWithLocation_FolderReadOnly_Fails() { using (var tempFolder = new TemporaryFolder(MethodBase.GetCurrentMethod().Name)) { if (SIL.PlatformUtilities.Platform.IsWindows) { var di = new DirectoryInfo(tempFolder.FolderPath); var directorySecurity = di.GetAccessControl(); var currentUserIdentity = WindowsIdentity.GetCurrent(); var fileSystemRule = new FileSystemAccessRule(currentUserIdentity.Name, FileSystemRights.Write, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Deny); directorySecurity.AddAccessRule(fileSystemRule); di.SetAccessControl(directorySecurity); Assert.That(_api.ProblemsWithLocation(tempFolder.FolderPath), Contains.Substring("Bloom does not have permission to write to the selected folder")); directorySecurity.RemoveAccessRule(fileSystemRule); di.SetAccessControl(directorySecurity); } else { var udi = new Mono.Unix.UnixDirectoryInfo(tempFolder.FolderPath); var permissions = udi.FileAccessPermissions; udi.FileAccessPermissions = Mono.Unix.FileAccessPermissions.UserRead | Mono.Unix.FileAccessPermissions.GroupRead | Mono.Unix.FileAccessPermissions.OtherRead; Assert.That(_api.ProblemsWithLocation(tempFolder.FolderPath), Contains.Substring("Bloom does not have permission to write to the selected folder")); udi.FileAccessPermissions = permissions; } } } } /// <summary> /// This class sets up a BloomServer once at the beginning, for any tests that want to rely on it. /// </summary> /// <remarks> /// This mainly uses a BloomServer to bypass all the setup of an IRequestInfo. /// It's also nice that we view things more from the perspective of the API caller, which will be a lot more frequent /// than the caller of the handler itself (which is largely boilerplate) /// </remarks> [TestFixture] public class TeamCollectionApiServerTests { // FYI: If the tests are run in parallel, you might want some locking, but it doesn't seem needed right now. private BloomServer _server; [OneTimeSetUp] public void OneTimeSetUp() { _server = new BloomServer(new BookSelection()); } [SetUp] public void Setup() { _server?.ApiHandler?.ClearEndpointHandlers(); } [OneTimeTearDown] public void OneTimeTearDown() { _server?.Dispose(); _server = null; } // TODO: HandleAttemptLockOfCurrentBook // TODO: HandleCheckInCurrentBook // TODO: HandleChooseFolderLoaction // TODO: HandleCreateTeamCollection #region HandleCurrentBookStatus [Test] public void HandleCurrentBookStatus_InsufficientRegistration_RequestFails() { var originalValue = SIL.Windows.Forms.Registration.Registration.Default.Email; try { SIL.Windows.Forms.Registration.Registration.Default.Email = ""; var api = new TeamCollectionApiBuilder().WithDefaultMocks().Build(); api.RegisterWithApiHandler(_server.ApiHandler); // System Under Test TestDelegate systemUnderTest = () => ApiTest.GetString(_server, endPoint: "teamCollection/currentBookStatus", returnType: ApiTest.ContentType.Text); Assert.Throws(typeof(System.Net.WebException), systemUnderTest); } finally { SIL.Windows.Forms.Registration.Registration.Default.Email = originalValue; } } [Test] public void HandleCurrentBookStatus_LockedByRealUser_StatusIndicatesThatuser() { var originalValue = SIL.Windows.Forms.Registration.Registration.Default.Email; try { SIL.Windows.Forms.Registration.Registration.Default.Email = "me@example.com"; var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(true); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); var mockTeamCollection = SetupMockTcForBookStatus(apiBuilder); mockTeamCollection.Setup(x => x.WhoHasBookLocked(It.IsAny<string>())).Returns("other@example.com"); mockTeamCollection.Setup(x => x.WhatComputerHasBookLocked(It.IsAny<string>())).Returns("Other's Computer"); // System Under Test var result = ApiTest.GetString(_server, endPoint: "teamCollection/selectedBookStatus", returnType: ApiTest.ContentType.Text); // Verification StringAssert.Contains("\"who\":\"other@example.com\"", result); } finally { // Cleanup SIL.Windows.Forms.Registration.Registration.Default.Email = originalValue; } } private static Mock<FolderTeamCollection> SetupMockTcForBookStatus(TeamCollectionApiBuilder apiBuilder) { var mockTeamCollection = new Mock<Bloom.TeamCollection.FolderTeamCollection>(); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.CurrentCollectionEvenIfDisconnected) .Returns(mockTeamCollection.Object); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.CurrentCollection).Returns(mockTeamCollection.Object); mockTeamCollection.Setup(x => x.GetPathToBookFileInRepo(It.IsAny<string>())).Returns("some fake path"); mockTeamCollection.Setup(x => x.HasLocalChangesThatMustBeClobbered(It.IsAny<string>())).Returns(false); mockTeamCollection.Setup(x => x.HasBeenChangedRemotely(It.IsAny<string>())).Returns(false); mockTeamCollection.Setup(x => x.GetCouldNotOpenCorruptZipMessage()).Returns("some fake message"); return mockTeamCollection; } [Test] public void HandleCurrentBookStatus_LockedByFakeUser_FakeUserConvertedToCurrentUser() { var originalValue = SIL.Windows.Forms.Registration.Registration.Default.Email; try { SIL.Windows.Forms.Registration.Registration.Default.Email = "me@example.com"; var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(true); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); var mockTeamCollection = SetupMockTcForBookStatus(apiBuilder); mockTeamCollection.Setup(x => x.WhoHasBookLocked(It.IsAny<string>())).Returns("this user"); mockTeamCollection.Setup(x => x.WhatComputerHasBookLocked(It.IsAny<string>())).Returns("My Computer"); // System Under Test var result = ApiTest.GetString(_server, endPoint: "teamCollection/selectedBookStatus", returnType: ApiTest.ContentType.Text); // Verification StringAssert.Contains("\"who\":\"me@example.com\"", result); } finally { // Cleanup SIL.Windows.Forms.Registration.Registration.Default.Email = originalValue; } } #endregion #region HandleGetLog [Test] public void HandleGetLog_NullMessageLog_RequestFailed() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.MessageLog).Returns((ITeamCollectionMessageLog)null); TestDelegate systemUnderTest = () => { ApiTest.GetString(_server, endPoint: "teamCollection/getLog", returnType: ApiTest.ContentType.JSON); }; Assert.Throws(typeof(System.Net.WebException), systemUnderTest); } [Test] public void HandleGetLog_NonZeroMessages_MessagesReturned() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); var mockMessageLog = new Mock<ITeamCollectionMessageLog>(); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.MessageLog).Returns(mockMessageLog.Object); mockMessageLog.Setup(x => x.GetProgressMessages()).Returns( new BloomWebSocketProgressEvent[] { new BloomWebSocketProgressEvent("unused", ProgressKind.Progress, "1"), new BloomWebSocketProgressEvent("unused", ProgressKind.Progress, "2") } ); // System Under Test var result = ApiTest.GetString(_server, endPoint: "teamCollection/getLog", returnType: ApiTest.ContentType.JSON); // Verification var deserializedArray = JsonConvert.DeserializeObject<BloomWebSocketProgressEvent[]>(result); var messages = deserializedArray.Select(x => x.message).ToArray(); CollectionAssert.AreEqual(new string[] { "1", "2" }, messages); } #endregion #region HandleIsTeamCollectionEnabled [Test] public void HandleIsTeamCollectionEnabled_NoCollection_ReturnsFalse() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); // apiBuilder.MockTeamCollectionManager.Object.CurrentCollectionEvenIfDisconnected hasn't been changed, // so it will return null // System Under Test var result = ApiTest.GetString(_server, endPoint: "teamCollection/isTeamCollectionEnabled", returnType: ApiTest.ContentType.Text); Assert.That(result, Is.EqualTo("false")); } [Test] public void HandleIsTeamCollectionEnabled_BookSelectedButNotEditable_ReturnsFalse() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); var mockTeamCollection = new Mock<Bloom.TeamCollection.TeamCollection>(); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.CurrentCollectionEvenIfDisconnected).Returns(mockTeamCollection.Object); var mockBook = new Mock<Bloom.Book.Book>(); mockBook.SetupGet(x => x.IsEditable).Returns(false); apiBuilder.MockBookSelection.SetupGet(x => x.CurrentSelection).Returns(mockBook.Object); // System Under Test var result = ApiTest.GetString(_server, endPoint: "teamCollection/isTeamCollectionEnabled", returnType: ApiTest.ContentType.Text); Assert.That(result, Is.EqualTo("false")); } [Test] public void HandleIsTeamCollectionEnabled_CurrentSelectionNull_ReturnsTrue() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); var mockTeamCollection = new Mock<Bloom.TeamCollection.TeamCollection>(); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.CurrentCollectionEvenIfDisconnected).Returns(mockTeamCollection.Object); // apiBuilder.MockBookSelection.Object.CurrentSelection will return null // System Under Test var result = ApiTest.GetString(_server, endPoint: "teamCollection/isTeamCollectionEnabled", returnType: ApiTest.ContentType.Text); Assert.That(result, Is.EqualTo("true")); } [Test] public void HandleIsTeamCollectionEnabled_CurrentSelectionEditable_ReturnsTrue() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); var mockTeamCollection = new Mock<Bloom.TeamCollection.TeamCollection>(); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.CurrentCollectionEvenIfDisconnected).Returns(mockTeamCollection.Object); var mockBook = new Mock<Bloom.Book.Book>(); mockBook.SetupGet(x => x.IsEditable).Returns(true); apiBuilder.MockBookSelection.SetupGet(x => x.CurrentSelection).Returns(mockBook.Object); // System Under Test var result = ApiTest.GetString(_server, endPoint: "teamCollection/isTeamCollectionEnabled", returnType: ApiTest.ContentType.Text); Assert.That(result, Is.EqualTo("true")); } [Test] public void HandleIsTeamCollectionEnabled_ExceptionThrown_RequestFailed() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.CurrentCollectionEvenIfDisconnected).Returns(() => throw new ApplicationException()); // System Under Test TestDelegate systemUnderTest = () => ApiTest.GetString(_server, endPoint: "teamCollection/isTeamCollectionEnabled", returnType: ApiTest.ContentType.Text); Assert.Throws(typeof(System.Net.WebException), systemUnderTest); } #endregion // ENHANCE: Test HandleJoinTeamCollection. But that one is mostly just testing logic in FolderTeamcollection.JoinCollectionTeam. // Not a very interesting test from the TeamCollectionApi side. #region HandleRepoFolderPath [Test] public void HandleRepoFolderPath_NullCurrCollection_ReturnsEmptyString() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); // System Under Test var result = ApiTest.GetString(_server, endPoint: "teamCollection/repoFolderPath", returnType: ApiTest.ContentType.Text); Assert.That(result, Is.EqualTo("")); } [Test] public void HandleRepoFolderPath_NonNullCurrCollection_ReturnsRepoDescription() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); var mockTeamCollection = new Mock<Bloom.TeamCollection.TeamCollection>(); mockTeamCollection.SetupGet(x => x.RepoDescription).Returns("Fake Description"); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.CurrentCollectionEvenIfDisconnected).Returns(mockTeamCollection.Object); // System Under Test var result = ApiTest.GetString(_server, endPoint: "teamCollection/repoFolderPath", returnType: ApiTest.ContentType.Text); Assert.That(result, Is.EqualTo("Fake Description")); } [Test] public void HandleRepoFolderPath_ExceptionThrown_RequestFailed() { var apiBuilder = new TeamCollectionApiBuilder().WithDefaultMocks(); var api = apiBuilder.Build(); api.RegisterWithApiHandler(_server.ApiHandler); apiBuilder.MockTeamCollectionManager.SetupGet(x => x.CurrentCollectionEvenIfDisconnected).Returns(() => throw new ApplicationException() ); TestDelegate systemUnderTest = () => ApiTest.GetString(_server, endPoint: "teamCollection/repoFolderPath", returnType: ApiTest.ContentType.Text); Assert.Throws(typeof(System.Net.WebException), systemUnderTest); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using Xunit; namespace System.Linq.Expressions.Tests { public class UnaryDecrementTests : IncrementDecrementTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryDecrementShortTest(bool useInterpreter) { short[] values = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyDecrementShort(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryDecrementUShortTest(bool useInterpreter) { ushort[] values = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyDecrementUShort(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryDecrementIntTest(bool useInterpreter) { int[] values = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyDecrementInt(values[i], useInterpreter); VerifyDecrementIntMakeUnary(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryDecrementUIntTest(bool useInterpreter) { uint[] values = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyDecrementUInt(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryDecrementLongTest(bool useInterpreter) { long[] values = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyDecrementLong(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckUnaryDecrementULongTest(bool useInterpreter) { ulong[] values = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { VerifyDecrementULong(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDecrementFloatTest(bool useInterpreter) { float[] values = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { VerifyDecrementFloat(values[i], useInterpreter); } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckDecrementDoubleTest(bool useInterpreter) { double[] values = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { VerifyDecrementDouble(values[i], useInterpreter); } } [Fact] public static void ToStringTest() { UnaryExpression e = Expression.Decrement(Expression.Parameter(typeof(int), "x")); Assert.Equal("Decrement(x)", e.ToString()); } [Theory, MemberData(nameof(NonArithmeticObjects), true)] public static void DecrementNonArithmetic(object value) { Expression ex = Expression.Constant(value); Assert.Throws<InvalidOperationException>(() => Expression.Decrement(ex)); } [Theory, PerCompilationType(nameof(DecrementableValues), false)] public static void CustomOpDecrement(Decrementable operand, Decrementable expected, bool useInterpreter) { Func<Decrementable> func = Expression.Lambda<Func<Decrementable>>( Expression.Decrement(Expression.Constant(operand))).Compile(useInterpreter); Assert.Equal(expected.Value, func().Value); } [Theory, PerCompilationType(nameof(DoublyDecrementedDecrementableValues), false)] public static void UserDefinedOpDecrement(Decrementable operand, Decrementable expected, bool useInterpreter) { MethodInfo method = typeof(IncrementDecrementTests).GetMethod(nameof(DoublyDecrement)); Func<Decrementable> func = Expression.Lambda<Func<Decrementable>>( Expression.Decrement(Expression.Constant(operand), method)).Compile(useInterpreter); Assert.Equal(expected.Value, func().Value); } [Theory, PerCompilationType(nameof(DoublyDecrementedInt32s), false)] public static void UserDefinedOpDecrementArithmeticType(int operand, int expected, bool useInterpreter) { MethodInfo method = typeof(IncrementDecrementTests).GetMethod(nameof(DoublyDecrementInt32)); Func<int> func = Expression.Lambda<Func<int>>( Expression.Decrement(Expression.Constant(operand), method)).Compile(useInterpreter); Assert.Equal(expected, func()); } [Fact] public static void NullOperand() { AssertExtensions.Throws<ArgumentNullException>("expression", () => Expression.Decrement(null)); } [Fact] public static void UnreadableOperand() { Expression operand = Expression.Property(null, typeof(Unreadable<int>), nameof(Unreadable<int>.WriteOnly)); AssertExtensions.Throws<ArgumentException>("expression", () => Expression.Decrement(operand)); } #endregion #region Test verifiers private static void VerifyDecrementShort(short value, bool useInterpreter) { Expression<Func<short>> e = Expression.Lambda<Func<short>>( Expression.Decrement(Expression.Constant(value, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<short> f = e.Compile(useInterpreter); Assert.Equal(unchecked((short)(--value)), f()); } private static void VerifyDecrementUShort(ushort value, bool useInterpreter) { Expression<Func<ushort>> e = Expression.Lambda<Func<ushort>>( Expression.Decrement(Expression.Constant(value, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<ushort> f = e.Compile(useInterpreter); Assert.Equal(unchecked((ushort)(--value)), f()); } private static void VerifyDecrementInt(int value, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Decrement(Expression.Constant(value, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(unchecked((int)(--value)), f()); } private static void VerifyDecrementIntMakeUnary(int value, bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.MakeUnary(ExpressionType.Decrement, Expression.Constant(value), null), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(unchecked(--value), f()); } private static void VerifyDecrementUInt(uint value, bool useInterpreter) { Expression<Func<uint>> e = Expression.Lambda<Func<uint>>( Expression.Decrement(Expression.Constant(value, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<uint> f = e.Compile(useInterpreter); Assert.Equal(unchecked((uint)(--value)), f()); } private static void VerifyDecrementLong(long value, bool useInterpreter) { Expression<Func<long>> e = Expression.Lambda<Func<long>>( Expression.Decrement(Expression.Constant(value, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<long> f = e.Compile(useInterpreter); Assert.Equal(unchecked((long)(--value)), f()); } private static void VerifyDecrementULong(ulong value, bool useInterpreter) { Expression<Func<ulong>> e = Expression.Lambda<Func<ulong>>( Expression.Decrement(Expression.Constant(value, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<ulong> f = e.Compile(useInterpreter); Assert.Equal(unchecked((ulong)(--value)), f()); } private static void VerifyDecrementFloat(float value, bool useInterpreter) { Expression<Func<float>> e = Expression.Lambda<Func<float>>( Expression.Decrement(Expression.Constant(value, typeof(float))), Enumerable.Empty<ParameterExpression>()); Func<float> f = e.Compile(useInterpreter); Assert.Equal((float)(--value), f()); } private static void VerifyDecrementDouble(double value, bool useInterpreter) { Expression<Func<double>> e = Expression.Lambda<Func<double>>( Expression.Decrement(Expression.Constant(value, typeof(double))), Enumerable.Empty<ParameterExpression>()); Func<double> f = e.Compile(useInterpreter); Assert.Equal((double)(--value), f()); } #endregion } }
//------------------------------------------------------------------------------ // <license file="ScriptOrFnNode.cs"> // // The use and distribution terms for this software are contained in the file // named 'LICENSE', which can be found in the resources directory of this // distribution. // // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // </license> //------------------------------------------------------------------------------ using System; using EcmaScript.NET.Collections; namespace EcmaScript.NET { public class ScriptOrFnNode : Node { virtual public string SourceName { get { return sourceName; } set { this.sourceName = value; } } virtual public int EncodedSourceStart { get { return encodedSourceStart; } } virtual public int EncodedSourceEnd { get { return encodedSourceEnd; } } virtual public int BaseLineno { get { return baseLineno; } set { // One time action if (value < 0 || baseLineno >= 0) Context.CodeBug (); baseLineno = value; } } virtual public int EndLineno { get { return baseLineno; } set { // One time action if (value < 0 || endLineno >= 0) Context.CodeBug (); endLineno = value; } } virtual public int FunctionCount { get { if (functions == null) { return 0; } return functions.size (); } } virtual public int RegexpCount { get { if (regexps == null) { return 0; } return regexps.size () / 2; } } virtual public int ParamCount { get { return varStart; } } virtual public int ParamAndVarCount { get { return itsVariables.size (); } } virtual public string [] ParamAndVarNames { get { int N = itsVariables.size (); if (N == 0) { return ScriptRuntime.EmptyStrings; } string [] array = new string [N]; itsVariables.ToArray (array); return array; } } virtual public object CompilerData { get { return compilerData; } set { if (value == null) throw new ArgumentException (); // Can only call once if (compilerData != null) throw new ApplicationException (); compilerData = value; } } public ScriptOrFnNode (int nodeType) : base (nodeType) { } public void setEncodedSourceBounds (int start, int end) { this.encodedSourceStart = start; this.encodedSourceEnd = end; } public FunctionNode getFunctionNode (int i) { return (FunctionNode)functions.Get (i); } public int addFunction (FunctionNode fnNode) { if (fnNode == null) Context.CodeBug (); if (functions == null) { functions = new ObjArray (); } functions.add (fnNode); return functions.size () - 1; } public string getRegexpString (int index) { return (string)regexps.Get (index * 2); } public string getRegexpFlags (int index) { return (string)regexps.Get (index * 2 + 1); } public int addRegexp (string str, string flags) { if (str == null) Context.CodeBug (); if (regexps == null) { regexps = new ObjArray (); } regexps.add (str); regexps.add (flags); return regexps.size () / 2 - 1; } public bool hasParamOrVar (string name) { return itsVariableNames.has (name); } public int getParamOrVarIndex (string name) { return itsVariableNames.Get (name, -1); } public string getParamOrVarName (int index) { return (string)itsVariables.Get (index); } public void addParam (string name) { // Check addparam is not called after addLocal if (varStart != itsVariables.size ()) Context.CodeBug (); // Allow non-unique parameter names: use the last occurrence int index = varStart++; itsVariables.add (name); itsVariableNames.put (name, index); } public void addVar (string name) { int vIndex = itsVariableNames.Get (name, -1); if (vIndex != -1) { // There's already a variable or parameter with this name. return; } int index = itsVariables.size (); itsVariables.add (name); itsVariableNames.put (name, index); } public void removeParamOrVar (string name) { int i = itsVariableNames.Get (name, -1); if (i != -1) { itsVariables.remove (i); itsVariableNames.remove (name); ObjToIntMap.Iterator iter = itsVariableNames.newIterator (); for (iter.start (); !iter.done (); iter.next ()) { int v = iter.Value; if (v > i) { iter.Value = v - 1; } } } } private int encodedSourceStart; private int encodedSourceEnd; private string sourceName; private int baseLineno = -1; private int endLineno = -1; private ObjArray functions; private ObjArray regexps; // a list of the formal parameters and local variables private ObjArray itsVariables = new ObjArray (); // mapping from name to index in list private ObjToIntMap itsVariableNames = new ObjToIntMap (11); private int varStart; // index in list of first variable private object compilerData; } }
using System; using System.Linq.Expressions; using System.Reflection; using Nop.Core; using Nop.Core.Configuration; using Nop.Core.Domain.Localization; using Nop.Core.Domain.Security; using Nop.Core.Infrastructure; using Nop.Core.Plugins; using Nop.Services.Configuration; namespace Nop.Services.Localization { public static class LocalizationExtensions { /// <summary> /// Get localized property of an entity /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <param name="entity">Entity</param> /// <param name="keySelector">Key selector</param> /// <returns>Localized property</returns> public static string GetLocalized<T>(this T entity, Expression<Func<T, string>> keySelector) where T : BaseEntity, ILocalizedEntity { var workContext = EngineContext.Current.Resolve<IWorkContext>(); return GetLocalized(entity, keySelector, workContext.WorkingLanguage.Id); } /// <summary> /// Get localized property of an entity /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <param name="entity">Entity</param> /// <param name="keySelector">Key selector</param> /// <param name="languageId">Language identifier</param> /// <param name="returnDefaultValue">A value indicating whether to return default value (if localized is not found)</param> /// <param name="ensureTwoPublishedLanguages">A value indicating whether to ensure that we have at least two published languages; otherwise, load only default value</param> /// <returns>Localized property</returns> public static string GetLocalized<T>(this T entity, Expression<Func<T, string>> keySelector, int languageId, bool returnDefaultValue = true, bool ensureTwoPublishedLanguages = true) where T : BaseEntity, ILocalizedEntity { return GetLocalized<T, string>(entity, keySelector, languageId, returnDefaultValue, ensureTwoPublishedLanguages); } /// <summary> /// Get localized property of an entity /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <typeparam name="TPropType">Property type</typeparam> /// <param name="entity">Entity</param> /// <param name="keySelector">Key selector</param> /// <param name="languageId">Language identifier</param> /// <param name="returnDefaultValue">A value indicating whether to return default value (if localized is not found)</param> /// <param name="ensureTwoPublishedLanguages">A value indicating whether to ensure that we have at least two published languages; otherwise, load only default value</param> /// <returns>Localized property</returns> public static TPropType GetLocalized<T, TPropType>(this T entity, Expression<Func<T, TPropType>> keySelector, int languageId, bool returnDefaultValue = true, bool ensureTwoPublishedLanguages = true) where T : BaseEntity, ILocalizedEntity { if (entity == null) throw new ArgumentNullException("entity"); var member = keySelector.Body as MemberExpression; if (member == null) { throw new ArgumentException(string.Format( "Expression '{0}' refers to a method, not a property.", keySelector)); } var propInfo = member.Member as PropertyInfo; if (propInfo == null) { throw new ArgumentException(string.Format( "Expression '{0}' refers to a field, not a property.", keySelector)); } TPropType result = default(TPropType); string resultStr = string.Empty; //load localized value string localeKeyGroup = typeof(T).Name; string localeKey = propInfo.Name; if (languageId > 0) { //ensure that we have at least two published languages bool loadLocalizedValue = true; if (ensureTwoPublishedLanguages) { var lService = EngineContext.Current.Resolve<ILanguageService>(); var totalPublishedLanguages = lService.GetAllLanguages().Count; loadLocalizedValue = totalPublishedLanguages >= 2; } //localized value if (loadLocalizedValue) { var leService = EngineContext.Current.Resolve<ILocalizedEntityService>(); resultStr = leService.GetLocalizedValue(languageId, entity.Id, localeKeyGroup, localeKey); if (!String.IsNullOrEmpty(resultStr)) result = CommonHelper.To<TPropType>(resultStr); } } //set default value if required if (String.IsNullOrEmpty(resultStr) && returnDefaultValue) { var localizer = keySelector.Compile(); result = localizer(entity); } return result; } /// <summary> /// Get localized property of setting /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <param name="settings">Settings</param> /// <param name="keySelector">Key selector</param> /// <param name="languageId">Language identifier</param> /// <param name="returnDefaultValue">A value indicating whether to return default value (if localized is not found)</param> /// <param name="ensureTwoPublishedLanguages">A value indicating whether to ensure that we have at least two published languages; otherwise, load only default value</param> /// <returns>Localized property</returns> public static string GetLocalizedSetting<T>(this T settings, Expression<Func<T, string>> keySelector, int languageId, bool returnDefaultValue = true, bool ensureTwoPublishedLanguages = true) where T : ISettings, new() { var settingService = EngineContext.Current.Resolve<ISettingService>(); string key = settings.GetSettingKey(keySelector); //we do not support localized settings per store (overridden store settings) var setting = settingService.GetSetting(key, storeId: 0, loadSharedValueIfNotFound: false); if (setting == null) return null; return setting.GetLocalized(x => x.Value, languageId, returnDefaultValue, ensureTwoPublishedLanguages); } /// <summary> /// Save localized property of setting /// </summary> /// <typeparam name="T">Entity type</typeparam> /// <param name="settings">Settings</param> /// <param name="keySelector">Key selector</param> /// <param name="languageId">Language identifier</param> /// <param name="value">Localizaed value</param> /// <returns>Localized property</returns> public static void SaveLocalizedSetting<T>(this T settings, Expression<Func<T, string>> keySelector, int languageId, string value) where T : ISettings, new() { var settingService = EngineContext.Current.Resolve<ISettingService>(); var localizedEntityService = EngineContext.Current.Resolve<ILocalizedEntityService>(); string key = settings.GetSettingKey(keySelector); //we do not support localized settings per store (overridden store settings) var setting = settingService.GetSetting(key, storeId: 0, loadSharedValueIfNotFound: false); if (setting == null) return; localizedEntityService.SaveLocalizedValue(setting, x => x.Value, value, languageId); } /// <summary> /// Get localized value of enum /// </summary> /// <typeparam name="T">Enum</typeparam> /// <param name="enumValue">Enum value</param> /// <param name="localizationService">Localization service</param> /// <param name="workContext">Work context</param> /// <returns>Localized value</returns> public static string GetLocalizedEnum<T>(this T enumValue, ILocalizationService localizationService, IWorkContext workContext) where T : struct { if (workContext == null) throw new ArgumentNullException("workContext"); return GetLocalizedEnum(enumValue, localizationService, workContext.WorkingLanguage.Id); } /// <summary> /// Get localized value of enum /// </summary> /// <typeparam name="T">Enum</typeparam> /// <param name="enumValue">Enum value</param> /// <param name="localizationService">Localization service</param> /// <param name="languageId">Language identifier</param> /// <returns>Localized value</returns> public static string GetLocalizedEnum<T>(this T enumValue, ILocalizationService localizationService, int languageId) where T : struct { if (localizationService == null) throw new ArgumentNullException("localizationService"); if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type"); //localized value string resourceName = string.Format("Enums.{0}.{1}", typeof(T).ToString(), //Convert.ToInt32(enumValue) enumValue.ToString()); string result = localizationService.GetResource(resourceName, languageId, false, "", true); //set default value if required if (String.IsNullOrEmpty(result)) result = CommonHelper.ConvertEnum(enumValue.ToString()); return result; } /// <summary> /// Get localized value of permission /// We don't have UI to manage permission localizable name. That's why we're using this extension method /// </summary> /// <param name="permissionRecord">Permission record</param> /// <param name="localizationService">Localization service</param> /// <param name="workContext">Work context</param> /// <returns>Localized value</returns> public static string GetLocalizedPermissionName(this PermissionRecord permissionRecord, ILocalizationService localizationService, IWorkContext workContext) { if (workContext == null) throw new ArgumentNullException("workContext"); return GetLocalizedPermissionName(permissionRecord, localizationService, workContext.WorkingLanguage.Id); } /// <summary> /// Get localized value of enum /// We don't have UI to manage permission localizable name. That's why we're using this extension method /// </summary> /// <param name="permissionRecord">Permission record</param> /// <param name="localizationService">Localization service</param> /// <param name="languageId">Language identifier</param> /// <returns>Localized value</returns> public static string GetLocalizedPermissionName(this PermissionRecord permissionRecord, ILocalizationService localizationService, int languageId) { if (permissionRecord == null) throw new ArgumentNullException("permissionRecord"); if (localizationService == null) throw new ArgumentNullException("localizationService"); //localized value string resourceName = string.Format("Permission.{0}", permissionRecord.SystemName); string result = localizationService.GetResource(resourceName, languageId, false, "", true); //set default value if required if (String.IsNullOrEmpty(result)) result = permissionRecord.Name; return result; } /// <summary> /// Save localized name of a permission /// </summary> /// <param name="permissionRecord">Permission record</param> /// <param name="localizationService">Localization service</param> /// <param name="languageService">Language service</param> public static void SaveLocalizedPermissionName(this PermissionRecord permissionRecord, ILocalizationService localizationService, ILanguageService languageService) { if (permissionRecord == null) throw new ArgumentNullException("permissionRecord"); if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageService == null) throw new ArgumentNullException("languageService"); string resourceName = string.Format("Permission.{0}", permissionRecord.SystemName); string resourceValue = permissionRecord.Name; foreach (var lang in languageService.GetAllLanguages(true)) { var lsr = localizationService.GetLocaleStringResourceByName(resourceName, lang.Id, false); if (lsr == null) { lsr = new LocaleStringResource { LanguageId = lang.Id, ResourceName = resourceName, ResourceValue = resourceValue }; localizationService.InsertLocaleStringResource(lsr); } else { lsr.ResourceValue = resourceValue; localizationService.UpdateLocaleStringResource(lsr); } } } /// <summary> /// Delete a localized name of a permission /// </summary> /// <param name="permissionRecord">Permission record</param> /// <param name="localizationService">Localization service</param> /// <param name="languageService">Language service</param> public static void DeleteLocalizedPermissionName(this PermissionRecord permissionRecord, ILocalizationService localizationService, ILanguageService languageService) { if (permissionRecord == null) throw new ArgumentNullException("permissionRecord"); if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageService == null) throw new ArgumentNullException("languageService"); string resourceName = string.Format("Permission.{0}", permissionRecord.SystemName); foreach (var lang in languageService.GetAllLanguages(true)) { var lsr = localizationService.GetLocaleStringResourceByName(resourceName, lang.Id, false); if (lsr != null) localizationService.DeleteLocaleStringResource(lsr); } } /// <summary> /// Delete a locale resource /// </summary> /// <param name="plugin">Plugin</param> /// <param name="resourceName">Resource name</param> public static void DeletePluginLocaleResource(this BasePlugin plugin, string resourceName) { var localizationService = EngineContext.Current.Resolve<ILocalizationService>(); var languageService = EngineContext.Current.Resolve<ILanguageService>(); DeletePluginLocaleResource(plugin, localizationService, languageService, resourceName); } /// <summary> /// Delete a locale resource /// </summary> /// <param name="plugin">Plugin</param> /// <param name="localizationService">Localization service</param> /// <param name="languageService">Language service</param> /// <param name="resourceName">Resource name</param> public static void DeletePluginLocaleResource(this BasePlugin plugin, ILocalizationService localizationService, ILanguageService languageService, string resourceName) { //actually plugin instance is not required if (plugin == null) throw new ArgumentNullException("plugin"); if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageService == null) throw new ArgumentNullException("languageService"); foreach (var lang in languageService.GetAllLanguages(true)) { var lsr = localizationService.GetLocaleStringResourceByName(resourceName, lang.Id, false); if (lsr != null) localizationService.DeleteLocaleStringResource(lsr); } } /// <summary> /// Add a locale resource (if new) or update an existing one /// </summary> /// <param name="plugin">Plugin</param> /// <param name="resourceName">Resource name</param> /// <param name="resourceValue">Resource value</param> /// <param name="languageCulture">Language culture code. If null or empty, then a resource will be added for all languages</param> public static void AddOrUpdatePluginLocaleResource(this BasePlugin plugin, string resourceName, string resourceValue, string languageCulture = null) { var localizationService = EngineContext.Current.Resolve<ILocalizationService>(); var languageService = EngineContext.Current.Resolve<ILanguageService>(); AddOrUpdatePluginLocaleResource(plugin, localizationService, languageService, resourceName, resourceValue, languageCulture); } /// <summary> /// Add a locale resource (if new) or update an existing one /// </summary> /// <param name="plugin">Plugin</param> /// <param name="localizationService">Localization service</param> /// <param name="languageService">Language service</param> /// <param name="resourceName">Resource name</param> /// <param name="resourceValue">Resource value</param> /// <param name="languageCulture">Language culture code. If null or empty, then a resource will be added for all languages</param> public static void AddOrUpdatePluginLocaleResource(this BasePlugin plugin, ILocalizationService localizationService, ILanguageService languageService, string resourceName, string resourceValue, string languageCulture = null) { //actually plugin instance is not required if (plugin == null) throw new ArgumentNullException("plugin"); if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageService == null) throw new ArgumentNullException("languageService"); foreach (var lang in languageService.GetAllLanguages(true)) { if (!String.IsNullOrEmpty(languageCulture) && !languageCulture.Equals(lang.LanguageCulture)) continue; var lsr = localizationService.GetLocaleStringResourceByName(resourceName, lang.Id, false); if (lsr == null) { lsr = new LocaleStringResource { LanguageId = lang.Id, ResourceName = resourceName, ResourceValue = resourceValue }; localizationService.InsertLocaleStringResource(lsr); } else { lsr.ResourceValue = resourceValue; localizationService.UpdateLocaleStringResource(lsr); } } } /// <summary> /// Get localized friendly name of a plugin /// </summary> /// <typeparam name="T">Plugin</typeparam> /// <param name="plugin">Plugin</param> /// <param name="localizationService">Localization service</param> /// <param name="languageId">Language identifier</param> /// <param name="returnDefaultValue">A value indicating whether to return default value (if localized is not found)</param> /// <returns>Localized value</returns> public static string GetLocalizedFriendlyName<T>(this T plugin, ILocalizationService localizationService, int languageId, bool returnDefaultValue = true) where T : IPlugin { if (localizationService == null) throw new ArgumentNullException("localizationService"); if (plugin == null) throw new ArgumentNullException("plugin"); if (plugin.PluginDescriptor == null) throw new ArgumentException("Plugin descriptor cannot be loaded"); string systemName = plugin.PluginDescriptor.SystemName; //localized value string resourceName = string.Format("Plugins.FriendlyName.{0}", systemName); string result = localizationService.GetResource(resourceName, languageId, false, "", true); //set default value if required if (String.IsNullOrEmpty(result) && returnDefaultValue) result = plugin.PluginDescriptor.FriendlyName; return result; } /// <summary> /// Save localized friendly name of a plugin /// </summary> /// <typeparam name="T">Plugin</typeparam> /// <param name="plugin">Plugin</param> /// <param name="localizationService">Localization service</param> /// <param name="languageId">Language identifier</param> /// <param name="localizedFriendlyName">Localized friendly name</param> public static void SaveLocalizedFriendlyName<T>(this T plugin, ILocalizationService localizationService, int languageId, string localizedFriendlyName) where T : IPlugin { if (localizationService == null) throw new ArgumentNullException("localizationService"); if (languageId == 0) throw new ArgumentOutOfRangeException("languageId", "Language ID should not be 0"); if (plugin == null) throw new ArgumentNullException("plugin"); if (plugin.PluginDescriptor == null) throw new ArgumentException("Plugin descriptor cannot be loaded"); string systemName = plugin.PluginDescriptor.SystemName; //localized value string resourceName = string.Format("Plugins.FriendlyName.{0}", systemName); var resource = localizationService.GetLocaleStringResourceByName(resourceName, languageId, false); if (resource != null) { if (string.IsNullOrWhiteSpace(localizedFriendlyName)) { //delete localizationService.DeleteLocaleStringResource(resource); } else { //update resource.ResourceValue = localizedFriendlyName; localizationService.UpdateLocaleStringResource(resource); } } else { if (!string.IsNullOrWhiteSpace(localizedFriendlyName)) { //insert resource = new LocaleStringResource { LanguageId = languageId, ResourceName = resourceName, ResourceValue = localizedFriendlyName, }; localizationService.InsertLocaleStringResource(resource); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web.UI.WebControls; using Moq; using NUnit.Framework; using Umbraco.Core.Configuration.UmbracoSettings; using Umbraco.Core.IO; using Umbraco.Core.Models; using Umbraco.Core.Persistence.Repositories; using Umbraco.Core.Persistence.UnitOfWork; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; using Content = Umbraco.Core.Models.Content; namespace Umbraco.Tests.Persistence.Repositories { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture] public class PublicAccessRepositoryTest : BaseDatabaseFactoryTest { [Test] public void Can_Delete() { var content = CreateTestData(3).ToArray(); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, }); repo.AddOrUpdate(entry); unitOfWork.Commit(); repo.Delete(entry); unitOfWork.Commit(); entry = repo.Get(entry.Key); Assert.IsNull(entry); } } [Test] public void Can_Add() { var content = CreateTestData(3).ToArray(); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, }); repo.AddOrUpdate(entry); unitOfWork.Commit(); var found = repo.GetAll().ToArray(); Assert.AreEqual(1, found.Count()); Assert.AreEqual(content[0].Id, found[0].ProtectedNodeId); Assert.AreEqual(content[1].Id, found[0].LoginNodeId); Assert.AreEqual(content[2].Id, found[0].NoAccessNodeId); Assert.IsTrue(found[0].HasIdentity); Assert.AreNotEqual(default(DateTime), found[0].CreateDate); Assert.AreNotEqual(default(DateTime), found[0].UpdateDate); Assert.AreEqual(1, found[0].Rules.Count()); Assert.AreEqual("test", found[0].Rules.First().RuleValue); Assert.AreEqual("RoleName", found[0].Rules.First().RuleType); Assert.AreNotEqual(default(DateTime), found[0].Rules.First().CreateDate); Assert.AreNotEqual(default(DateTime), found[0].Rules.First().UpdateDate); Assert.IsTrue(found[0].Rules.First().HasIdentity); } } [Test] public void Can_Update() { var content = CreateTestData(3).ToArray(); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, }); repo.AddOrUpdate(entry); unitOfWork.Commit(); //re-get entry = repo.Get(entry.Key); entry.Rules.First().RuleValue = "blah"; entry.Rules.First().RuleType = "asdf"; repo.AddOrUpdate(entry); unitOfWork.Commit(); //re-get entry = repo.Get(entry.Key); Assert.AreEqual("blah", entry.Rules.First().RuleValue); Assert.AreEqual("asdf", entry.Rules.First().RuleType); } } [Test] public void Get_By_Id() { var content = CreateTestData(3).ToArray(); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var entry = new PublicAccessEntry(content[0], content[1], content[2], new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, }); repo.AddOrUpdate(entry); unitOfWork.Commit(); //re-get entry = repo.Get(entry.Key); Assert.IsNotNull(entry); } } [Test] public void Get_All() { var content = CreateTestData(3).ToArray(); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var entry1 = new PublicAccessEntry(content[0], content[1], content[2], new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, }); repo.AddOrUpdate(entry1); var entry2 = new PublicAccessEntry(content[1], content[0], content[2], new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, }); repo.AddOrUpdate(entry2); unitOfWork.Commit(); var found = repo.GetAll().ToArray(); Assert.AreEqual(2, found.Count()); } } [Test] public void Get_All_With_Id() { var content = CreateTestData(3).ToArray(); var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); using (var repo = new PublicAccessRepository(unitOfWork, CacheHelper, Logger, SqlSyntax)) { var entry1 = new PublicAccessEntry(content[0], content[1], content[2], new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, }); repo.AddOrUpdate(entry1); var entry2 = new PublicAccessEntry(content[1], content[0], content[2], new[] { new PublicAccessRule { RuleValue = "test", RuleType = "RoleName" }, }); repo.AddOrUpdate(entry2); unitOfWork.Commit(); var found = repo.GetAll(entry1.Key).ToArray(); Assert.AreEqual(1, found.Count()); } } private ContentRepository CreateRepository(IDatabaseUnitOfWork unitOfWork, out ContentTypeRepository contentTypeRepository) { var templateRepository = new TemplateRepository(unitOfWork, CacheHelper, Logger, SqlSyntax, Mock.Of<IFileSystem>(), Mock.Of<IFileSystem>(), Mock.Of<ITemplatesSection>()); var tagRepository = new TagRepository(unitOfWork, CacheHelper, Logger, SqlSyntax); contentTypeRepository = new ContentTypeRepository(unitOfWork, CacheHelper, Logger, SqlSyntax, templateRepository); var repository = new ContentRepository(unitOfWork, CacheHelper, Logger, SqlSyntax, contentTypeRepository, templateRepository, tagRepository, Mock.Of<IContentSection>()); return repository; } private IEnumerable<IContent> CreateTestData(int count) { var provider = new PetaPocoUnitOfWorkProvider(Logger); var unitOfWork = provider.GetUnitOfWork(); ContentTypeRepository ctRepo; using (var repo = CreateRepository(unitOfWork, out ctRepo)) { var ct = MockedContentTypes.CreateBasicContentType("testing"); ctRepo.AddOrUpdate(ct); unitOfWork.Commit(); var result = new List<IContent>(); for (int i = 0; i < count; i++) { var c = new Content("test" + i, -1, ct); repo.AddOrUpdate(c); result.Add(c); } unitOfWork.Commit(); return result; } } } }
/* * LifetimeServices.cs - Implementation of the * "System.Runtime.Remoting.Lifetime.LifetimeServices" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Runtime.Remoting.Lifetime { #if CONFIG_REMOTING using System.Security.Permissions; using System.Collections; using System.Threading; [SecurityPermission(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure)] [TODO] public sealed class LifetimeServices { // Internal state. private static TimeSpan leaseManagerPollTime = new TimeSpan(0, 10, 0); private static TimeSpan leaseTime = new TimeSpan(0, 5, 0); private static TimeSpan renewOnCallTime = new TimeSpan(0, 2, 0); private static TimeSpan sponsorshipTimeout = new TimeSpan(0, 2, 0); // Get or set the global lease manager poll time setting. public static TimeSpan LeaseManagerPollTime { get { return leaseManagerPollTime; } set { lock(typeof(LifetimeServices)) { leaseManagerPollTime = value; AppDomain current = AppDomain.CurrentDomain; if(current.lifetimeManager != null) { current.lifetimeManager.PollTime = value; } } } } // Get or set the global lease time setting. public static TimeSpan LeaseTime { get { return leaseTime; } set { leaseTime = value; } } // Get or set the global renew on call time setting. public static TimeSpan RenewOnCallTime { get { return renewOnCallTime; } set { renewOnCallTime = value; } } // Get or set the global sponsorship timeout setting. public static TimeSpan SponsorshipTimeout { get { return sponsorshipTimeout; } set { sponsorshipTimeout = value; } } // Get the lifetime manager for the current application domain. private static Manager GetLifetimeManager() { lock(typeof(LifetimeServices)) { AppDomain current = AppDomain.CurrentDomain; if(current.lifetimeManager == null) { current.lifetimeManager = new Manager (leaseManagerPollTime); } return current.lifetimeManager; } } // Get the default lifetime service object for a marshal-by-ref object. internal static Object GetLifetimeService(MarshalByRefObject obj) { return GetLifetimeManager().GetLeaseForObject(obj); } // Initialize a lifetime service object for a marshal-by-ref object. internal static Object InitializeLifetimeService(MarshalByRefObject obj) { Manager manager = GetLifetimeManager(); ILease lease = manager.GetLeaseForObject(obj); if(lease != null) { return lease; } return new Lease(obj, LeaseTime, RenewOnCallTime, SponsorshipTimeout); } // Lifetime lease manager for an application domain. internal class Manager { // Internal state. private TimeSpan pollTime; private Hashtable leases; private Timer timer; // Constructor. public Manager(TimeSpan pollTime) { this.pollTime = pollTime; this.leases = new Hashtable(); this.timer = new Timer (new TimerCallback(Callback), null, pollTime, pollTime); } // Get or set the poll time. public TimeSpan PollTime { get { lock(this) { return pollTime; } } set { lock(this) { pollTime = value; timer.Change(pollTime, pollTime); } } } // Get an active lease for an object. public ILease GetLeaseForObject(MarshalByRefObject obj) { // TODO return null; } // Callback for processing lease timeouts. private void Callback(Object state) { // TODO } }; // class Manager // Lease control object. private class Lease : MarshalByRefObject, ILease { // Internal state. private MarshalByRefObject obj; private DateTime leaseTimeout; private TimeSpan initialLeaseTime; private TimeSpan renewOnCallTime; private TimeSpan sponsorshipTimeout; private LeaseState state; // Constructor. public Lease(MarshalByRefObject obj, TimeSpan leaseTime, TimeSpan renewOnCallTime, TimeSpan sponsorshipTimeout) { this.obj = obj; this.initialLeaseTime = leaseTime; this.renewOnCallTime = renewOnCallTime; this.sponsorshipTimeout = sponsorshipTimeout; this.state = LeaseState.Initial; } // Cannot have a lease for a lease! public override Object InitializeLifetimeService() { return null; } // Implement the ILease interface. public TimeSpan CurrentLeaseTime { get { return leaseTimeout - DateTime.UtcNow; } } public LeaseState CurrentState { get { return state; } } public TimeSpan InitialLeaseTime { get { return initialLeaseTime; } set { if(state != LeaseState.Initial) { throw new RemotingException (_("Invalid_ModifyLease")); } initialLeaseTime = value; if(value <= TimeSpan.Zero) { // Disable the lease. state = LeaseState.Null; } } } public TimeSpan RenewOnCallTime { get { return renewOnCallTime; } set { if(state != LeaseState.Initial) { throw new RemotingException (_("Invalid_ModifyLease")); } renewOnCallTime = value; } } public TimeSpan SponsorshipTimeout { get { return renewOnCallTime; } set { if(state != LeaseState.Initial) { throw new RemotingException (_("Invalid_ModifyLease")); } renewOnCallTime = value; } } public void Register(ISponsor obj) { Register(obj, new TimeSpan(0)); } public void Register(ISponsor obj, TimeSpan renewalTime) { // TODO } public TimeSpan Renew(TimeSpan renewalTime) { // TODO return renewalTime; } public void Unregister(ISponsor obj) { // TODO } }; // class Lease }; // class LifetimeServices #endif // CONFIG_REMOTING }; // namespace System.Runtime.Remoting.Lifetime
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.CSharp; using Microsoft.VisualBasic; using Xunit; namespace System.CodeDom.Compiler.Tests { public class CodeDomProviderTests { [Fact] public void GetAllCompilerInfo_ReturnsMinimumOfCSharpAndVB() { Type[] compilerInfos = CodeDomProvider.GetAllCompilerInfo().Where(provider => provider.IsCodeDomProviderTypeValid).Select(provider => provider.CodeDomProviderType).ToArray(); Assert.True(compilerInfos.Length >= 2); Assert.Contains(typeof(CSharpCodeProvider), compilerInfos); Assert.Contains(typeof(VBCodeProvider), compilerInfos); } [Fact] public void FileExtension_ReturnsEmpty() { Assert.Empty(new NullProvider().FileExtension); } [Fact] public void LanguageOptions_ReturnsNone() { Assert.Equal(LanguageOptions.None, new NullProvider().LanguageOptions); } [Fact] public void CreateGenerator_ReturnsOverridenGenerator() { #pragma warning disable 0618 CustomProvider provider = new CustomProvider(); Assert.Same(provider.CreateGenerator(), provider.CreateGenerator("fileName")); Assert.Same(provider.CreateGenerator(), provider.CreateGenerator(new StringWriter())); #pragma warning restore 0618 } [Fact] public void CreateParser_ReturnsNull() { #pragma warning disable 0618 Assert.Null(new NoParserProvider().CreateParser()); #pragma warning restore 0618 } [Fact] public void GetConverter_ReturnsNotNull() { Assert.NotNull(new CustomProvider().GetConverter(typeof(int))); } [Fact] public void GetConverter_NullType_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("type", () => new CustomProvider().GetConverter(null)); } public static IEnumerable<object[]> CreateProvider_String_TestData() { yield return new object[] { "c#", "cs" }; yield return new object[] { " c# ", "cs" }; yield return new object[] { "cs", "cs" }; yield return new object[] { "csharp", "cs" }; yield return new object[] { "CsHaRp", "cs" }; yield return new object[] { "vb", "vb" }; yield return new object[] { "vbs", "vb" }; yield return new object[] { "visualbasic", "vb" }; yield return new object[] { "vbscript", "vb" }; yield return new object[] { "VBSCRIPT", "vb" }; } [Theory] [MemberData(nameof(CreateProvider_String_TestData))] public void CreateProvider_String(string language, string expectedFileExtension) { CodeDomProvider provider = CodeDomProvider.CreateProvider(language); Assert.Equal(expectedFileExtension, provider.FileExtension); } public static IEnumerable<object[]> CreateProvider_String_Dictionary_TestData() { yield return new object[] { "cs", new Dictionary<string, string>(), "cs" }; yield return new object[] { "cs", new Dictionary<string, string>() { { "option", "value" } }, "cs" }; yield return new object[] { "cs", new Dictionary<string, string>() { { "option1", "value1" }, { "option2", "value2" } }, "cs" }; yield return new object[] { "cs", new Dictionary<string, string>() { { "option", null } }, "cs" }; yield return new object[] { "vb", new Dictionary<string, string>(), "vb" }; yield return new object[] { "vb", new Dictionary<string, string>() { { "option", "value" } }, "vb" }; yield return new object[] { "vb", new Dictionary<string, string>() { { "option1", "value1" }, { "option2", "value2" } }, "vb" }; yield return new object[] { "vb", new Dictionary<string, string>() { { "option", null } }, "vb" }; } [Theory] [MemberData(nameof(CreateProvider_String_Dictionary_TestData))] public void CreateProvider_String_Dictionary(string language, Dictionary<string, string> providerOptions, string expectedFileExtension) { CodeDomProvider provider = CodeDomProvider.CreateProvider(language, providerOptions); Assert.Equal(expectedFileExtension, provider.FileExtension); } [Fact] public void CreateProvider_NullProviderOptions_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("providerOptions", () => CodeDomProvider.CreateProvider("cs", null)); AssertExtensions.Throws<ArgumentNullException>("providerOptions", () => CodeDomProvider.CreateProvider("vb", null)); } [Fact] public void CreateProvider_NullLanguage_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.CreateProvider(null)); AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.CreateProvider(null, new Dictionary<string, string>())); } [Theory] [InlineData("")] [InlineData(".cs")] [InlineData("no-such-language")] public void CreateProvider_NoSuchLanguage_ThrowsConfigurationErrorsException(string language) { Exception ex1 = Assert.ThrowsAny<Exception>(() => CodeDomProvider.CreateProvider(language)); AssertIsConfigurationErrorsException(ex1); Exception ex2 = Assert.ThrowsAny<Exception>(() => CodeDomProvider.CreateProvider(language, new Dictionary<string, string>())); AssertIsConfigurationErrorsException(ex2); } [Theory] [InlineData(" cs ", true)] [InlineData("cs", true)] [InlineData("c#", true)] [InlineData("csharp", true)] [InlineData("CsHaRp", true)] [InlineData("vb", true)] [InlineData("vbs", true)] [InlineData("visualbasic", true)] [InlineData("vbscript", true)] [InlineData("VB", true)] [InlineData("", false)] [InlineData(".cs", false)] [InlineData("no-such-language", false)] public void IsDefinedLanguage_ReturnsExpected(string language, bool expected) { Assert.Equal(expected, CodeDomProvider.IsDefinedLanguage(language)); } [Fact] public void IsDefinedLanguage_NullLanguage_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.IsDefinedLanguage(null)); } [Theory] [InlineData("cs", "c#")] [InlineData(" cs ", "c#")] [InlineData(".cs", "c#")] [InlineData("Cs", "c#")] [InlineData("cs", "c#")] [InlineData("vb", "vb")] [InlineData(".vb", "vb")] [InlineData("VB", "vb")] public void GetLanguageFromExtension_ReturnsExpected(string extension, string expected) { Assert.Equal(expected, CodeDomProvider.GetLanguageFromExtension(extension)); } [Fact] public void GetLanguageFromExtension_NullExtension_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("extension", () => CodeDomProvider.GetLanguageFromExtension(null)); } [Theory] [InlineData("")] [InlineData("c#")] [InlineData("no-such-extension")] public void GetLanguageFromExtension_NoSuchExtension_ThrowsConfigurationErrorsException(string extension) { Exception ex = Assert.ThrowsAny<Exception>(() => CodeDomProvider.GetLanguageFromExtension(extension)); AssertIsConfigurationErrorsException(ex); } [Theory] [InlineData("cs", true)] [InlineData(".cs", true)] [InlineData("Cs", true)] [InlineData("cs", true)] [InlineData("vb", true)] [InlineData(".vb", true)] [InlineData("VB", true)] [InlineData("", false)] [InlineData("c#", false)] [InlineData("no-such-extension", false)] public void IsDefinedExtension_ReturnsExpected(string extension, bool expected) { Assert.Equal(expected, CodeDomProvider.IsDefinedExtension(extension)); } [Fact] public void IsDefinedExtension_NullExtension_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("extension", () => CodeDomProvider.IsDefinedExtension(null)); } [Theory] [InlineData(" cs ", typeof(CSharpCodeProvider))] [InlineData("cs", typeof(CSharpCodeProvider))] [InlineData("c#", typeof(CSharpCodeProvider))] [InlineData("csharp", typeof(CSharpCodeProvider))] [InlineData("CsHaRp", typeof(CSharpCodeProvider))] [InlineData("vb", typeof(VBCodeProvider))] [InlineData("vbs", typeof(VBCodeProvider))] [InlineData("visualbasic", typeof(VBCodeProvider))] [InlineData("vbscript", typeof(VBCodeProvider))] [InlineData("VB", typeof(VBCodeProvider))] public void GetCompilerInfo_ReturnsExpected(string language, Type expectedProviderType) { Assert.Equal(expectedProviderType, CodeDomProvider.GetCompilerInfo(language).CodeDomProviderType); } [Fact] public void GetCompilerInfo_NullLanguage_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("language", () => CodeDomProvider.GetCompilerInfo(null)); } [Theory] [InlineData("")] [InlineData(".cs")] [InlineData("no-such-extension")] public void GetCompilerInfo_NoSuchExtension_ThrowsKeyNotFoundException(string language) { Exception ex = Assert.ThrowsAny<Exception>(() => CodeDomProvider.GetCompilerInfo(language)); AssertIsConfigurationErrorsException(ex); } [Fact] public void CompileAssemblyFromDom_CallsCompilerMethod() { Assert.Throws<ArgumentException>(() => new CustomProvider().CompileAssemblyFromDom(new CompilerParameters())); } [Fact] public void CompileAssemblyFromDom_NullCompiler_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CompileAssemblyFromDom(new CompilerParameters())); } [Fact] public void CompileAssemblyFromFile_CallsCompilerMethod() { AssertExtensions.Throws<ArgumentNullException>("2", () => new CustomProvider().CompileAssemblyFromFile(new CompilerParameters())); } [Fact] public void CompileAssemblyFromFile_NullCompiler_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CompileAssemblyFromFile(new CompilerParameters())); } [Fact] public void CompileAssemblyFromSource_CallsCompilerMethod() { AssertExtensions.Throws<ArgumentOutOfRangeException>("3", () => new CustomProvider().CompileAssemblyFromSource(new CompilerParameters())); } [Fact] public void CompileAssemblyFromSource_NullCompiler_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CompileAssemblyFromSource(new CompilerParameters())); } [Fact] public void CreateEscapedIdentifier_CallsGeneratorMethod() { Assert.Throws<ArgumentException>(null, () => new CustomProvider().CreateEscapedIdentifier("value")); } [Fact] public void CreateEscapedIdentifier_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CreateEscapedIdentifier("value")); } [Fact] public void CreateValidIdentifier_CallsGeneratorMethod() { AssertExtensions.Throws<ArgumentNullException>("2", () => new CustomProvider().CreateValidIdentifier("value")); } [Fact] public void CreateValidIdentifier_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().CreateValidIdentifier("value")); } [Fact] public void GenerateCodeFromCompileUnit_CallsGeneratorMethod() { AssertExtensions.Throws<ArgumentOutOfRangeException>("3", () => new CustomProvider().GenerateCodeFromCompileUnit(new CodeCompileUnit(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromCompileUnit_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromCompileUnit(new CodeCompileUnit(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromExpression_CallsGeneratorMethod() { Assert.Throws<ArithmeticException>(() => new CustomProvider().GenerateCodeFromExpression(new CodeExpression(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromExpression_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromExpression(new CodeExpression(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromNamespace_CallsGeneratorMethod() { Assert.Throws<ArrayTypeMismatchException>(() => new CustomProvider().GenerateCodeFromNamespace(new CodeNamespace(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromNamespace_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromNamespace(new CodeNamespace(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromStatement_CallsGeneratorMethod() { Assert.Throws<BadImageFormatException>(() => new CustomProvider().GenerateCodeFromStatement(new CodeStatement(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromStatement_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromStatement(new CodeStatement(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromType_CallsGeneratorMethod() { Assert.Throws<CannotUnloadAppDomainException>(() => new CustomProvider().GenerateCodeFromType(new CodeTypeDeclaration(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GenerateCodeFromType_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromType(new CodeTypeDeclaration(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void GetTypeOutput_CallsGeneratorMethod() { Assert.Throws<DataMisalignedException>(() => new CustomProvider().GetTypeOutput(new CodeTypeReference())); } [Fact] public void GetTypeOutput_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GetTypeOutput(new CodeTypeReference())); } [Fact] public void IsValidIdentifier_CallsGeneratorMethod() { Assert.Throws<DirectoryNotFoundException>(() => new CustomProvider().IsValidIdentifier("value")); } [Fact] public void IsValidIdentifier_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().IsValidIdentifier("value")); } [Fact] public void Supports_CallsGeneratorMethod() { Assert.Throws<DivideByZeroException>(() => new CustomProvider().Supports(GeneratorSupport.ArraysOfArrays)); } [Fact] public void Supports_NullGenerator_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().Supports(GeneratorSupport.ArraysOfArrays)); } [Fact] public void GenerateCodeFromMember_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().GenerateCodeFromMember(new CodeTypeMember(), new StringWriter(), new CodeGeneratorOptions())); } [Fact] public void Parse_CallsParserMethod() { Assert.Same(CustomParser.CompileUnit, new CustomProvider().Parse(new StringReader("abc"))); } [Fact] public void Parse_NullParser_ThrowsNotImplementedException() { Assert.Throws<NotImplementedException>(() => new NullProvider().Parse(new StringReader("abc"))); } private static void AssertIsConfigurationErrorsException(Exception ex) { if (!PlatformDetection.IsNetNative) // Can't do internal Reflection { Assert.Equal("ConfigurationErrorsException", ex.GetType().Name); } } protected class NullProvider : CodeDomProvider { #pragma warning disable 0672 public override ICodeCompiler CreateCompiler() => null; public override ICodeParser CreateParser() => null; public override ICodeGenerator CreateGenerator() => null; #pragma warning restore 067 } protected class NoParserProvider : CodeDomProvider { public override ICodeCompiler CreateCompiler() => null; public override ICodeGenerator CreateGenerator() => null; } protected class CustomProvider : CodeDomProvider { private ICodeCompiler _compiler = new CustomCompiler(); public override ICodeCompiler CreateCompiler() => _compiler; private ICodeGenerator _generator = new CustomGenerator(); public override ICodeGenerator CreateGenerator() => _generator; private ICodeParser _parser = new CustomParser(); public override ICodeParser CreateParser() => _parser; } protected class CustomCompiler : ICodeCompiler { public CompilerResults CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit compilationUnit) => null; public CompilerResults CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] compilationUnits) { throw new ArgumentException("1"); } public CompilerResults CompileAssemblyFromFile(CompilerParameters options, string fileName) => null; public CompilerResults CompileAssemblyFromFileBatch(CompilerParameters options, string[] fileNames) { throw new ArgumentNullException("2"); } public CompilerResults CompileAssemblyFromSource(CompilerParameters options, string source) => null; public CompilerResults CompileAssemblyFromSourceBatch(CompilerParameters options, string[] sources) { throw new ArgumentOutOfRangeException("3"); } } protected class CustomGenerator : ICodeGenerator { public string CreateEscapedIdentifier(string value) { throw new ArgumentException("1"); } public string CreateValidIdentifier(string value) { throw new ArgumentNullException("2"); } public void GenerateCodeFromCompileUnit(CodeCompileUnit e, TextWriter w, CodeGeneratorOptions o) { throw new ArgumentOutOfRangeException("3"); } public void GenerateCodeFromExpression(CodeExpression e, TextWriter w, CodeGeneratorOptions o) { throw new ArithmeticException("4"); } public void GenerateCodeFromNamespace(CodeNamespace e, TextWriter w, CodeGeneratorOptions o) { throw new ArrayTypeMismatchException("5"); } public void GenerateCodeFromStatement(CodeStatement e, TextWriter w, CodeGeneratorOptions o) { throw new BadImageFormatException("6"); } public void GenerateCodeFromType(CodeTypeDeclaration e, TextWriter w, CodeGeneratorOptions o) { throw new CannotUnloadAppDomainException("7"); } public string GetTypeOutput(CodeTypeReference type) { throw new DataMisalignedException("8"); } public bool IsValidIdentifier(string value) { throw new DirectoryNotFoundException("9"); } public bool Supports(GeneratorSupport supports) { throw new DivideByZeroException("10"); } public void ValidateIdentifier(string value) { throw new DllNotFoundException("11"); } } protected class CustomParser : ICodeParser { public static CodeCompileUnit CompileUnit { get; } = new CodeCompileUnit(); public CodeCompileUnit Parse(TextReader codeStream) => CompileUnit; } } }
using NUnit.Framework; namespace FileHelpers.Tests.CommonTests { // SPECIAL FIELD public class AddressField { public string Street; public string Number; public string City; public override string ToString() { return Street + " - " + Number + ", " + City; } } // CUSTOM CONVERTER public class AddressConverter : ConverterBase { public override object StringToField(string from) { string[] splited1 = from.Split(','); string[] splited2 = splited1[0].Split('-'); var res = new AddressField(); res.Street = splited2[0].Trim(); res.Number = splited2[1].Trim(); res.City = splited1[1].Trim(); return res; } } // CUSTOM CONVERTER public class AddressConverter2 : ConverterBase { private readonly char mSep1; private readonly char mSep2; public AddressConverter2(string sep1, string sep2) { mSep1 = sep1[0]; mSep2 = sep2[0]; } public override object StringToField(string from) { string[] splited1 = from.Split(mSep1); string[] splited2 = splited1[0].Split(mSep2); var res = new AddressField(); res.Street = splited2[0].Trim(); res.Number = splited2[1].Trim(); res.City = splited1[1].Trim(); return res; } } // TEST CLASS [DelimitedRecord("|")] public class AddressConvClass { [FieldConverter(typeof (AddressConverter))] public AddressField Address; public int Age; } // TEST CLASS [DelimitedRecord("|")] public class AddressConvClass2 { [FieldConverter(typeof (AddressConverter2), ",", "-")] public AddressField Address; public int Age; } // NUNIT TESTS [TestFixture] public class CustomConvertAddress { [Test] public void NameConverterTest() { var engine = new FileHelperEngine<AddressConvClass>(); AddressConvClass[] res = TestCommon.ReadTest<AddressConvClass>(engine, "Good", "CustomConverter2.txt"); Assert.AreEqual(4, res.Length); Assert.AreEqual("Bahia Blanca", res[0].Address.City); Assert.AreEqual("Sin Nombre", res[0].Address.Street); Assert.AreEqual("13", res[0].Address.Number); Assert.AreEqual("Saavedra", res[1].Address.City); Assert.AreEqual("Florencio Sanches", res[1].Address.Street); Assert.AreEqual("s/n", res[1].Address.Number); Assert.AreEqual("Bs.As", res[2].Address.City); Assert.AreEqual("12 de Octubre", res[2].Address.Street); Assert.AreEqual("4", res[2].Address.Number); Assert.AreEqual("Chilesito", res[3].Address.City); Assert.AreEqual("Pololo", res[3].Address.Street); Assert.AreEqual("5421", res[3].Address.Number); } [Test] public void NameConverterTest2() { var engine = new FileHelperEngine<AddressConvClass2>(); AddressConvClass2[] res = TestCommon.ReadTest<AddressConvClass2>(engine, "Good", "CustomConverter2.txt"); Assert.AreEqual(4, res.Length); Assert.AreEqual("Bahia Blanca", res[0].Address.City); Assert.AreEqual("Sin Nombre", res[0].Address.Street); Assert.AreEqual("13", res[0].Address.Number); Assert.AreEqual("Saavedra", res[1].Address.City); Assert.AreEqual("Florencio Sanches", res[1].Address.Street); Assert.AreEqual("s/n", res[1].Address.Number); Assert.AreEqual("Bs.As", res[2].Address.City); Assert.AreEqual("12 de Octubre", res[2].Address.Street); Assert.AreEqual("4", res[2].Address.Number); Assert.AreEqual("Chilesito", res[3].Address.City); Assert.AreEqual("Pololo", res[3].Address.Street); Assert.AreEqual("5421", res[3].Address.Number); } // TEST CLASS [DelimitedRecord("|")] public class AddressBadClass1 { [FieldConverter(typeof (AddressConverter2), ",")] public AddressField Address; public int Age; } [DelimitedRecord("|")] public class AddressBadClass2 { [FieldConverter(typeof (AddressConverter2))] public AddressField Address; public int Age; } [DelimitedRecord("|")] public class AddressBadClass3 { [FieldConverter(typeof (AddressConverter2), 3, 58.25)] public AddressField Address; public int Age; } [Test] public void NameConverterBad1() { var ex = Assert.Throws<BadUsageException>( () => new FileHelperEngine<AddressBadClass1>()); Assert.AreEqual( "Constructor for converter: AddressConverter2 with these arguments: (String) was not found. You must add a constructor with this signature (can be public or private)" , ex.Message); } [Test] public void NameConverterBad2() { var ex = Assert.Throws<BadUsageException>( () => new FileHelperEngine<AddressBadClass2>()); Assert.AreEqual( "Empty constructor for converter: AddressConverter2 was not found. You must add a constructor without args (can be public or private)" , ex.Message); } [Test] public void NameConverterBad3() { var ex = Assert.Throws<BadUsageException>( () => new FileHelperEngine<AddressBadClass3>()); Assert.AreEqual( "Constructor for converter: AddressConverter2 with these arguments: (Int32, Double) was not found. You must add a constructor with this signature (can be public or private)" , ex.Message); } } }
using System; using System.Globalization; public class DateTimeParse1 { private CultureInfo CurrentCulture = TestLibrary.Utilities.CurrentCulture; private const int c_MIN_STRING_LEN = 1; private const int c_MAX_STRING_LEN = 2048; private const int c_NUM_LOOPS = 100; //new string[12] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; private static string[] c_MONTHS = CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthNames; //new string[12] {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; private static string[] c_MONTHS_SH = CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedMonthGenitiveNames; //new string[7] {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; private static string[] c_DAYS_SH = CultureInfo.InvariantCulture.DateTimeFormat.AbbreviatedDayNames; public static int Main() { DateTimeParse1 test = new DateTimeParse1(); TestLibrary.TestFramework.BeginTestCase("DateTimeParse1"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); TestLibrary.Utilities.CurrentCulture = CultureInfo.InvariantCulture; retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; retVal = PosTest10() && retVal; retVal = PosTest11() && retVal; retVal = PosTest12() && retVal; retVal = PosTest13() && retVal; retVal = PosTest14() && retVal; TestLibrary.Utilities.CurrentCulture = CurrentCulture; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; string dateBefore = ""; DateTime dateAfter; TestLibrary.TestFramework.BeginScenario("PosTest1: DateTime.Parse(DateTime.Now)"); try { dateBefore = DateTime.Now.ToString(); dateAfter = DateTime.Parse( dateBefore ); if (!dateBefore.Equals(dateAfter.ToString())) { TestLibrary.TestFramework.LogError("001", "DateTime.Parse(" + dateBefore + ") did not equal " + dateAfter.ToString()); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int day; // 1 - 29 int year; // 1900 - 2000 int month; // 1 - 12 TestLibrary.TestFramework.BeginScenario("PosTest2: DateTime.Parse(M/d/yyyy (ShortDatePattern ex: 1/3/2002))"); try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 28) + 1; year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1; dateBefore = month + "/" + day + "/" + year; dateAfter = DateTime.Parse( dateBefore ); if (month != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year) { TestLibrary.TestFramework.LogError("003", "DateTime.Parse(" + dateBefore + ") did not equal " + dateAfter.ToString()); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int dayOfWeek; // 0 - 6 int day; // 1 - 28 int year; // 1900 - 2000 int month; // 0 - 11 TestLibrary.TestFramework.BeginScenario("PosTest3: DateTime.Parse(dddd, MMMM dd, yyyy (LongDatePattern ex: Thursday, January 03, 2002))"); try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1; year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12); // cheat and get day of the week dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year); dayOfWeek = (int)dateAfter.DayOfWeek; // parse the date dateBefore = (DayOfWeek)dayOfWeek + ", " + c_MONTHS[month] + " " + day + ", " + year; dateAfter = DateTime.Parse( dateBefore ); if ((month+1) != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek) { TestLibrary.TestFramework.LogError("005", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.DayOfWeek + ", " + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ", " + dateAfter.Year + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int dayOfWeek; // 0 - 6 int day; // 1 - 28 int year; // 1900 - 2000 int month; // 0 - 11 int hour; // 0 - 11 int minute; // 0 - 59 int timeOfDay; // 0 -1 string[] twelveHour = new string[2] {"AM", "PM"}; TestLibrary.TestFramework.BeginScenario("PosTest4: DateTime.Parse(ex: Thursday, January 03, 2002 12:00 AM)"); try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1; year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12); hour = (TestLibrary.Generator.GetInt32(-55) % 12); minute = (TestLibrary.Generator.GetInt32(-55) % 60); timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2); // cheat and get day of the week dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year); dayOfWeek = (int)dateAfter.DayOfWeek; // parse the date dateBefore = (DayOfWeek)dayOfWeek + ", " + c_MONTHS[month] + " " + day + ", " + year + " " + hour + ":" + minute + " " + twelveHour[timeOfDay]; dateAfter = DateTime.Parse( dateBefore ); if ((month+1) != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek || (hour + timeOfDay*12) != dateAfter.Hour || minute != dateAfter.Minute) { TestLibrary.TestFramework.LogError("007", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.DayOfWeek + ", " + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ", " + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int dayOfWeek; // 0 - 6 int day; // 1 - 28 int year; // 1900 - 2000 int month; // 0 - 11 int hour; // 0 - 11 int minute; // 0 - 59 int second; // 0 - 59 int timeOfDay; // 0 -1 string[] twelveHour = new string[2] {"AM", "PM"}; TestLibrary.TestFramework.BeginScenario("PosTest5: DateTime.Parse(dddd, MMMM dd, yyyy h:mm:ss tt (FullDateTimePattern ex: Thursday, January 03, 2002 12:00:00 AM))"); try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1; year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12); hour = (TestLibrary.Generator.GetInt32(-55) % 12); minute = (TestLibrary.Generator.GetInt32(-55) % 60); second = (TestLibrary.Generator.GetInt32(-55) % 60); timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2); // cheat and get day of the week dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year); dayOfWeek = (int)dateAfter.DayOfWeek; // parse the date dateBefore = (DayOfWeek)dayOfWeek + ", " + c_MONTHS[month] + " " + day + ", " + year + " " + hour + ":" + minute + ":" + second + " " + twelveHour[timeOfDay]; dateAfter = DateTime.Parse( dateBefore ); if ((month+1) != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek || (hour + timeOfDay*12) != dateAfter.Hour || minute != dateAfter.Minute || second != dateAfter.Second) { TestLibrary.TestFramework.LogError("009", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.DayOfWeek + ", " + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ", " + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int day; // 1 - 28 int month; // 1 - 12 int year; // 1900 - 2000 int hour; // 0 - 11 int minute; // 0 - 59 int timeOfDay; // 0 -1 string[] twelveHour = new string[2] {"AM", "PM"}; TestLibrary.TestFramework.BeginScenario("PosTest6: DateTime.Parse(ex: 1/3/2002 12:00 AM)"); try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1; year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1; hour = (TestLibrary.Generator.GetInt32(-55) % 12); minute = (TestLibrary.Generator.GetInt32(-55) % 60); timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2); // parse the date dateBefore = month + "/" + day + "/" + year + " " + hour + ":" + minute + " " + twelveHour[timeOfDay]; dateAfter = DateTime.Parse( dateBefore ); if (month != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || (hour + timeOfDay*12) != dateAfter.Hour || minute != dateAfter.Minute) { TestLibrary.TestFramework.LogError("011", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Month + "/" + dateAfter.Day + "/" + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int day; // 1 - 28 int month; // 1 - 12 int year; // 1900 - 2000 int hour; // 0 - 11 int minute; // 0 - 59 int second; // 0 - 59 int timeOfDay; // 0 -1 string[] twelveHour = new string[2] {"AM", "PM"}; TestLibrary.TestFramework.BeginScenario("PosTest7: DateTime.Parse(ex: 1/3/2002 12:00:00 AM)"); try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1; year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1; hour = (TestLibrary.Generator.GetInt32(-55) % 12); minute = (TestLibrary.Generator.GetInt32(-55) % 60); second = (TestLibrary.Generator.GetInt32(-55) % 60); timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2); // parse the date dateBefore = month + "/" + day + "/" + year + " " + hour + ":" + minute + ":" + second + " " + twelveHour[timeOfDay]; dateAfter = DateTime.Parse( dateBefore ); if (month != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || (hour + timeOfDay*12) != dateAfter.Hour || minute != dateAfter.Minute || second != dateAfter.Second) { TestLibrary.TestFramework.LogError("013", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Month + "/" + dateAfter.Day + "/" + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("014", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int day; // 1 - 28 int month; // 0 - 11 TestLibrary.TestFramework.BeginScenario("PosTest8: DateTime.Parse(MMMM dd (MonthDayPattern ex: January 03))"); try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1; month = (TestLibrary.Generator.GetInt32(-55) % 12); // parse the date dateBefore = c_MONTHS[month] + " " + day; dateAfter = DateTime.Parse( dateBefore ); if ((month+1) != dateAfter.Month || day != dateAfter.Day) { TestLibrary.TestFramework.LogError("015", "DateTime.Parse(" + dateBefore + ") did not equal (" + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("016", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest9() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int dayOfWeek; // 0 - 6 int day; // 1 - 28 int year; // 1900 - 2000 int month; // 0 - 11 int hour; // 12 - 23 int minute; // 0 - 59 int second; // 0 - 59 TestLibrary.TestFramework.BeginScenario("PosTest9: DateTime.Parse(ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (RFC1123Pattern ex: Thu, 03 Jan 2002 00:00:00 GMT))"); DateTime now = DateTime.Now; int hourshift; if (now - now.ToUniversalTime() < TimeSpan.Zero) // western hemisphere hourshift = +12; else hourshift = 0; try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1; year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12); hour = (TestLibrary.Generator.GetInt32(-55) % 12) + hourshift; // Parse will convert perform GMT -> PST conversion minute = (TestLibrary.Generator.GetInt32(-55) % 60); second = (TestLibrary.Generator.GetInt32(-55) % 60); dayOfWeek = (TestLibrary.Generator.GetInt32(-55) % 7); // cheat and get day of the week dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year); dayOfWeek = (int)dateAfter.DayOfWeek; // parse the date dateBefore = c_DAYS_SH[dayOfWeek] + ", " + day + " " + c_MONTHS_SH[month] + " " + year + " " + hour + ":" + minute + ":" + second + " GMT"; dateAfter = DateTime.Parse( dateBefore ); if ((month+1) != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek || minute != dateAfter.Minute || second != dateAfter.Second) { TestLibrary.TestFramework.LogError("017", "DateTime.Parse(" + dateBefore + ") did not equal (" + c_DAYS_SH[(int)dateAfter.DayOfWeek] + ", " + dateAfter.Day + " " + c_MONTHS_SH[dateAfter.Month-1] + " " + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + " GMT)"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("018", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest10() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int day; // 1 - 28 int month; // 1 - 12 int year; // 1900 - 2000 int hour; // 0 - 23 int minute; // 0 - 59 int second; // 0 - 59 TestLibrary.TestFramework.BeginScenario("PosTest10: DateTime.Parse(yyyy'-'MM'-'dd'T'HH':'mm':'ss (SortableDateTimePattern ex: 2002-01-03T00:00:00))"); try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1; year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1; hour = (TestLibrary.Generator.GetInt32(-55) % 24); minute = (TestLibrary.Generator.GetInt32(-55) % 60); second = (TestLibrary.Generator.GetInt32(-55) % 60); // parse the date dateBefore = year + "-" + month + "-" + day + "T" + ((10 > hour) ? "0" : "") + hour + ":" + ((10 > minute) ? "0" : "") + minute + ":" + ((10 > second) ? "0" : "") + second; dateAfter = DateTime.Parse( dateBefore ); if (month != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || hour != dateAfter.Hour || minute != dateAfter.Minute || second != dateAfter.Second) { TestLibrary.TestFramework.LogError("019", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Year + "-" + dateAfter.Month + "-" + dateAfter.Day + "T" + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("020", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("020", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest11() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int hour; // 0 - 11 int minute; // 0 - 59 int timeOfDay; // 0 -1 string[] twelveHour = new string[2] {"AM", "PM"}; TestLibrary.TestFramework.BeginScenario("PosTest11: DateTime.Parse(h:mm tt (ShortTimePattern ex: 12:00 AM))"); try { for(int i=0; i<c_NUM_LOOPS; i++) { hour = (TestLibrary.Generator.GetInt32(-55) % 12); minute = (TestLibrary.Generator.GetInt32(-55) % 60); timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2); // parse the date dateBefore = hour + ":" + minute + " " + twelveHour[timeOfDay]; dateAfter = DateTime.Parse( dateBefore ); if ((hour + timeOfDay*12) != dateAfter.Hour || minute != dateAfter.Minute) { TestLibrary.TestFramework.LogError("021", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Hour + ":" + dateAfter.Minute + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("022", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("022", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest12() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int hour; // 0 - 11 int minute; // 0 - 59 int second; // 0 - 59 int timeOfDay; // 0 -1 string[] twelveHour = new string[2] {"AM", "PM"}; TestLibrary.TestFramework.BeginScenario("PosTest12: DateTime.Parse(h:mm:ss tt (LongTimePattern ex: 12:00:00 AM))"); try { for(int i=0; i<c_NUM_LOOPS; i++) { hour = (TestLibrary.Generator.GetInt32(-55) % 12); minute = (TestLibrary.Generator.GetInt32(-55) % 60); second = (TestLibrary.Generator.GetInt32(-55) % 60); timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2); // parse the date dateBefore = hour + ":" + minute + ":" + second + " " + twelveHour[timeOfDay]; dateAfter = DateTime.Parse( dateBefore ); if ((hour + timeOfDay*12) != dateAfter.Hour || minute != dateAfter.Minute || second != dateAfter.Second) { TestLibrary.TestFramework.LogError("023", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("024", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("024", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest13() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int day; // 1 - 28 int month; // 1 - 12 int year; // 1900 - 2000 int hour; // 12 - 23 int minute; // 0 - 59 int second; // 0 - 59 TestLibrary.TestFramework.BeginScenario("PosTest13: DateTime.Parse(yyyy'-'MM'-'dd HH':'mm':'ss'Z' (UniversalSortableDateTimePattern ex: 2002-01-03 00:00:00Z))"); DateTime now = DateTime.Now; int hourshift; if (now - now.ToUniversalTime() < TimeSpan.Zero) // western hemisphere hourshift = +12; else hourshift = 0; try { for(int i=0; i<c_NUM_LOOPS; i++) { day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1; year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1; hour = (TestLibrary.Generator.GetInt32(-55) % 12) + hourshift; // conversion minute = (TestLibrary.Generator.GetInt32(-55) % 60); second = (TestLibrary.Generator.GetInt32(-55) % 60); // parse the date dateBefore = year + "-" + month + "-" + day + " " + ((10 > hour) ? "0" : "") + hour + ":" + ((10 > minute) ? "0" : "") + minute + ":" + ((10 > second) ? "0" : "") + second +"Z"; dateAfter = DateTime.Parse( dateBefore ); if (month != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || minute != dateAfter.Minute || second != dateAfter.Second) { TestLibrary.TestFramework.LogError("025", "DateTime.Parse(" + dateBefore + ") did not equal (" + dateAfter.Year + "-" + dateAfter.Month + "-" + dateAfter.Day + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + "Z)"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("026", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("026", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest14() { bool retVal = true; DateTime dateAfter; string dateBefore = ""; int year; // 1900 - 2000 int month; // 0 - 11 TestLibrary.TestFramework.BeginScenario("PosTest14: DateTime.Parse(MMMM, yyyy (YearMonthPattern ex: January, 2002))"); try { for(int i=0; i<c_NUM_LOOPS; i++) { year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900; month = (TestLibrary.Generator.GetInt32(-55) % 12); // parse the date dateBefore = c_MONTHS[month] + ", " + year; dateAfter = DateTime.Parse( dateBefore ); if ((month+1) != dateAfter.Month || year != dateAfter.Year) { TestLibrary.TestFramework.LogError("027", "DateTime.Parse(" + dateBefore + ") did not equal (" + c_MONTHS[dateAfter.Month-1] + ", " + dateAfter.Year + ")"); retVal = false; } } } catch (Exception e) { TestLibrary.TestFramework.LogError("028", "Failing date: " + dateBefore); TestLibrary.TestFramework.LogError("028", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: DateTime.Parse(null)"); try { DateTime.Parse(null); TestLibrary.TestFramework.LogError("029", "DateTime.Parse(null) should have thrown"); retVal = false; } catch (ArgumentNullException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("030", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: DateTime.Parse(String.Empty)"); try { DateTime.Parse(String.Empty); TestLibrary.TestFramework.LogError("031", "DateTime.Parse(String.Empty) should have thrown"); retVal = false; } catch (FormatException) { // expected } catch (Exception e) { TestLibrary.TestFramework.LogError("032", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; string strDateTime = ""; DateTime dateAfter; TestLibrary.TestFramework.BeginScenario("NegTest3: DateTime.Parse(<garbage>)"); try { for (int i=0; i<c_NUM_LOOPS; i++) { try { strDateTime = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); dateAfter = DateTime.Parse(strDateTime); TestLibrary.TestFramework.LogError("033", "DateTime.Parse(" + strDateTime + ") should have thrown (" + dateAfter + ")"); retVal = false; } catch (FormatException) { // expected } } } catch (Exception e) { TestLibrary.TestFramework.LogError("034", "Failing date: " + strDateTime); TestLibrary.TestFramework.LogError("034", "Unexpected exception: " + e); retVal = false; } return retVal; } }
//! \file ImageAGF.cs //! \date Sun Sep 20 16:17:19 2015 //! \brief Eushully image format. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using GameRes.Compression; using GameRes.Utility; using System; using System.ComponentModel.Composition; using System.IO; using System.Windows.Media; namespace GameRes.Formats.Eushully { internal class AgfMetaData : ImageMetaData { public int SourceBPP; public uint DataOffset; public Color[] Palette; } [Export(typeof(ImageFormat))] public class AgfFormat : ImageFormat { public override string Tag { get { return "AGF"; } } public override string Description { get { return "Eushully image format"; } } public override uint Signature { get { return 0x46474341; } } // 'ACGF' public AgfFormat () { Signatures = new uint[] { 0x46474341, 0 }; } public override ImageMetaData ReadMetaData (Stream stream) { var header = new byte[0x20]; if (0x18 != stream.Read (header, 0, 0x18)) return null; uint id = LittleEndian.ToUInt32 (header, 0); if (Signature != id && 0 != id) return null; int type = LittleEndian.ToInt32 (header, 4); if (type != 1 && type != 2) return null; uint unpacked_size = LittleEndian.ToUInt32 (header, 0x10); uint packed_size = LittleEndian.ToUInt32 (header, 0x14); Stream unpacked; if (unpacked_size != packed_size) unpacked = new LzssStream (stream, LzssMode.Decompress, true); else unpacked = new StreamRegion (stream, stream.Position, packed_size, true); using (unpacked) using (var reader = new BinaryReader (unpacked)) { if (0x20 != reader.Read (header, 0, 0x20)) return null; var info = new AgfMetaData { Width = LittleEndian.ToUInt32 (header, 0x14), Height = LittleEndian.ToUInt32 (header, 0x18), BPP = 1 == type ? 24 : 32, SourceBPP = LittleEndian.ToInt16 (header, 0x1E), DataOffset = 0x18 + packed_size, }; if (0 == info.SourceBPP) return null; if (8 == info.SourceBPP) { reader.Read (header, 0, 0x18); // skip rest of the header info.Palette = ReadPalette (reader.BaseStream); } return info; } } static Color[] ReadPalette (Stream input) { var palette_data = new byte[0x400]; if (0x400 != input.Read (palette_data, 0, 0x400)) throw new EndOfStreamException(); var palette = new Color[0x100]; for (int i = 0; i < palette.Length; ++i) { palette[i] = Color.FromRgb (palette_data[i*4+2], palette_data[i*4+1], palette_data[i*4]); } return palette; } public override ImageData Read (Stream stream, ImageMetaData info) { var meta = info as AgfMetaData; if (null == meta) throw new ArgumentException ("AgfFormat.Read should be supplied with AgfMetaData", "info"); using (var reader = new AgfReader (stream, meta)) { reader.Unpack(); return ImageData.Create (info, reader.Format, null, reader.Data); } } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("AgfFormat.Write not implemented"); } } internal sealed class AgfReader : IDisposable { BinaryReader m_input; byte[] m_output; int m_width; int m_height; int m_bpp; int m_source_bpp; Color[] m_palette; public PixelFormat Format { get; private set; } public byte[] Data { get { return m_output; } } public AgfReader (Stream input, AgfMetaData info) { m_input = new ArcView.Reader (input); m_bpp = info.BPP; m_source_bpp = info.SourceBPP; input.Position = info.DataOffset; m_width = (int)info.Width; m_height = (int)info.Height; m_output = new byte[m_height * m_width * m_bpp / 8]; m_palette = info.Palette; } public void Unpack () { m_input.ReadInt32(); int data_size = m_input.ReadInt32(); int packed_size = m_input.ReadInt32(); var data_pos = m_input.BaseStream.Position; var bmp_data = new byte[data_size]; using (var unpacked = new LzssStream (m_input.BaseStream, LzssMode.Decompress, true)) { if (data_size != unpacked.Read (bmp_data, 0, data_size)) throw new EndOfStreamException(); } byte[] alpha = null; if (32 == m_bpp) { m_input.BaseStream.Position = data_pos + packed_size; alpha = ReadAlphaChannel(); if (null == alpha) m_bpp = 24; } Format = 32 == m_bpp ? PixelFormats.Bgra32 : PixelFormats.Bgr24; int src_pixel_size = m_source_bpp / 8; int dst_pixel_size = m_bpp / 8; int src_stride = (m_width * src_pixel_size + 3) & ~3; int dst_stride = m_width * dst_pixel_size; int src_row = (m_height - 1) * src_stride; int dst_row = 0; int src_alpha = 0; RowUnpacker repack_row = RepackRowTrue; if (1 == src_pixel_size) repack_row = RepackRow8; while (src_row >= 0) { repack_row (bmp_data, src_row, src_pixel_size, dst_row, dst_pixel_size, alpha, src_alpha); src_row -= src_stride; dst_row += dst_stride; src_alpha += m_width; } } delegate void RowUnpacker (byte[] bmp, int src, int src_pixel_size, int dst, int dst_pixel_size, byte[] alpha, int src_alpha); void RepackRow8 (byte[] bmp, int src, int src_pixel_size, int dst, int dst_pixel_size, byte[] alpha, int src_alpha) { for (int i = 0; i < m_width; ++i) { var color = m_palette[bmp[src++]]; m_output[dst] = color.B; m_output[dst+1] = color.G; m_output[dst+2] = color.R; if (null != alpha) m_output[dst+3] = alpha[src_alpha++]; dst += dst_pixel_size; } } void RepackRowTrue (byte[] bmp, int src, int src_pixel_size, int dst, int dst_pixel_size, byte[] alpha, int src_alpha) { for (int i = 0; i < m_width; ++i) { m_output[dst] = bmp[src]; m_output[dst+1] = bmp[src+1]; m_output[dst+2] = bmp[src+2]; if (null != alpha) m_output[dst+3] = alpha[src_alpha++]; src += src_pixel_size; dst += dst_pixel_size; } } byte[] ReadAlphaChannel () { var header = new byte[0x24]; if (0x24 != m_input.Read (header, 0, header.Length)) return null; if (!Binary.AsciiEqual (header, 0, "ACIF")) return null; int unpacked_size = LittleEndian.ToInt32 (header, 0x1C); if (m_width*m_height != unpacked_size) return null; var alpha = new byte[unpacked_size]; using (var unpacked = new LzssStream (m_input.BaseStream, LzssMode.Decompress, true)) if (unpacked_size != unpacked.Read (alpha, 0, unpacked_size)) return null; return alpha; } #region IDisposable methods bool _disposed = false; public void Dispose () { if (!_disposed) { m_input.Dispose(); _disposed = true; } } #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. namespace System.Xml.Serialization { using System; using System.Xml.Schema; using System.Collections; using System.ComponentModel; using System.Reflection; using System.Configuration; using System.Xml.Serialization.Configuration; #if DEBUG using System.Diagnostics; #endif public abstract class SchemaImporter { private XmlSchemas _schemas; private StructMapping _root; private CodeGenerationOptions _options; private TypeScope _scope; private ImportContext _context; private bool _rootImported; private NameTable _typesInUse; private NameTable _groupsInUse; internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, ImportContext context) { if (!schemas.Contains(XmlSchema.Namespace)) { schemas.AddReference(XmlSchemas.XsdSchema); schemas.SchemaSet.Add(XmlSchemas.XsdSchema); } if (!schemas.Contains(XmlReservedNs.NsXml)) { schemas.AddReference(XmlSchemas.XmlSchema); schemas.SchemaSet.Add(XmlSchemas.XmlSchema); } _schemas = schemas; _options = options; _context = context; Schemas.SetCache(Context.Cache, Context.ShareTypes); } internal ImportContext Context { get { if (_context == null) _context = new ImportContext(); return _context; } } internal Hashtable ImportedElements { get { return Context.Elements; } } internal Hashtable ImportedMappings { get { return Context.Mappings; } } internal CodeIdentifiers TypeIdentifiers { get { return Context.TypeIdentifiers; } } internal XmlSchemas Schemas { get { if (_schemas == null) _schemas = new XmlSchemas(); return _schemas; } } internal TypeScope Scope { get { if (_scope == null) _scope = new TypeScope(); return _scope; } } internal NameTable GroupsInUse { get { if (_groupsInUse == null) _groupsInUse = new NameTable(); return _groupsInUse; } } internal NameTable TypesInUse { get { if (_typesInUse == null) _typesInUse = new NameTable(); return _typesInUse; } } internal CodeGenerationOptions Options { get { return _options; } } internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseTypeCanBeIndirect) { structMapping.ReferencedByTopLevelElement = true; TypeDesc baseTypeDesc; if (baseType != null) { baseTypeDesc = Scope.GetTypeDesc(baseType); if (baseTypeDesc != null) { TypeDesc typeDescToChange = structMapping.TypeDesc; if (baseTypeCanBeIndirect) { // if baseTypeCanBeIndirect is true, we apply the supplied baseType to the top of the // inheritance chain, not necessarily directly to the imported type. while (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc) typeDescToChange = typeDescToChange.BaseTypeDesc; } if (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc) throw new InvalidOperationException(SR.Format(SR.XmlInvalidBaseType, structMapping.TypeDesc.FullName, baseType.FullName, typeDescToChange.BaseTypeDesc.FullName)); typeDescToChange.BaseTypeDesc = baseTypeDesc; } } } internal string GenerateUniqueTypeName(string typeName) { typeName = CodeIdentifier.MakeValid(typeName); return TypeIdentifiers.AddUnique(typeName, typeName); } private StructMapping CreateRootMapping() { TypeDesc typeDesc = Scope.GetTypeDesc(typeof(object)); StructMapping mapping = new StructMapping(); mapping.TypeDesc = typeDesc; mapping.Members = Array.Empty<MemberMapping>(); mapping.IncludeInSchema = false; mapping.TypeName = Soap.UrType; mapping.Namespace = XmlSchema.Namespace; return mapping; } internal StructMapping GetRootMapping() { if (_root == null) _root = CreateRootMapping(); return _root; } internal StructMapping ImportRootMapping() { if (!_rootImported) { _rootImported = true; ImportDerivedTypes(XmlQualifiedName.Empty); } return GetRootMapping(); } internal abstract void ImportDerivedTypes(XmlQualifiedName baseName); internal void AddReference(XmlQualifiedName name, NameTable references, string error) { if (name.Namespace == XmlSchema.Namespace) return; if (references[name] != null) { throw new InvalidOperationException(string.Format(error, name.Name, name.Namespace)); } references[name] = name; } internal void RemoveReference(XmlQualifiedName name, NameTable references) { references[name] = null; } internal void AddReservedIdentifiersForDataBinding(CodeIdentifiers scope) { if ((_options & CodeGenerationOptions.EnableDataBinding) != 0) { scope.AddReserved("PropertyChanged"); scope.AddReserved("RaisePropertyChanged"); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using gView.Framework.Data; using gView.Framework.system; namespace gView.Framework.UI.Dialogs { public partial class FormQueryBuilder : Form { private ITableClass _tc; private ITable _table; private CancelTracker _cancelTracker = new CancelTracker(); private Dictionary<string, List<string>> _values = new Dictionary<string, List<string>>(); public FormQueryBuilder(IFeatureLayer layer) : this((layer!=null) ? layer.FeatureClass : null) { } public FormQueryBuilder(ITableClass tc) { _tc = tc; InitializeComponent(); if (_tc == null) return; gView.Framework.Data.QueryFilter filter = new gView.Framework.Data.QueryFilter(); filter.SubFields = "*"; using (ICursor cursor = _tc.Search(filter)) { if (cursor is IFeatureCursor) { _table = new FeatureTable((IFeatureCursor)cursor, _tc.Fields, _tc); } else if (cursor is IRowCursor) { _table = new RowTable((IRowCursor)cursor, _tc.Fields); } else { return; } _table.Fill(2000); } cmbMethod.SelectedIndex = 0; foreach (IField field in _tc.Fields.ToEnumerable()) { if (field.type == FieldType.binary || field.type == FieldType.Shape) continue; lstFields.Items.Add(Field.WhereClauseFieldName(field.name)); } } public string whereClause { get { return txtWhereClause.Text; } set { txtWhereClause.Text = value; } } public CombinationMethod combinationMethod { get { switch (cmbMethod.SelectedIndex) { case 0: return CombinationMethod.New; case 1: return CombinationMethod.Union; case 2: return CombinationMethod.Difference; case 3: return CombinationMethod.Intersection; } return CombinationMethod.New; } set { switch(value) { case CombinationMethod.New: cmbMethod.SelectedIndex = 0; break; case CombinationMethod.Union: cmbMethod.SelectedIndex = 1; break; case CombinationMethod.Difference: cmbMethod.SelectedIndex = 2; break; case CombinationMethod.Intersection: cmbMethod.SelectedIndex = 3; break; } } } private void button1_Click(object sender, EventArgs e) { if (!(sender is Button)) return; string txt = " "+((Button)sender).Text+" "; insertText2WhereClause(txt); } private void insertText2WhereClause(string txt) { if (txtWhereClause.SelectionStart > 0 && txtWhereClause.SelectionStart < txtWhereClause.Text.Length) { string txt1 = txtWhereClause.Text.Substring(0, txtWhereClause.SelectionStart); string txt2 = txtWhereClause.Text.Substring(txtWhereClause.SelectionStart + txtWhereClause.SelectionLength, txtWhereClause.Text.Length - txtWhereClause.SelectionStart - txtWhereClause.SelectionLength); txtWhereClause.Text = txt1 + txt + txt2; } else { txtWhereClause.Text += txt; } } private void FillUniqueValues() { if (_tc == null) return; lstUniqueValues.Items.Clear(); if (lstFields.SelectedItem == null) return; string colName = lstFields.SelectedItem.ToString(); colName = colName.Replace("[", String.Empty).Replace("]", String.Empty); // Joined Fields IField field = _tc.FindField(colName); if (field == null) return; List<string> list; if (_values.TryGetValue(colName, out list)) { foreach (string val in list) { if (field.type == FieldType.String) lstUniqueValues.Items.Add("'" + val + "'"); else lstUniqueValues.Items.Add(val); } } else { foreach (DataRow row in _table.Table.Select("", colName)) { string val = row[colName].ToString(); if (field.type == FieldType.String) val = "'" + val + "'"; if (lstUniqueValues.Items.IndexOf(val) != -1) continue; lstUniqueValues.Items.Add(val); } } } private void lstFields_SelectedIndexChanged(object sender, EventArgs e) { btnCompleteList.Enabled = lstFields.SelectedItem != null; lstUniqueValues.Items.Clear(); if (_tc == null || _table.Table == null || lstFields.SelectedItem == null) return; string colName=lstFields.SelectedItem.ToString(); colName = colName.Replace("[", String.Empty).Replace("]", String.Empty); // Joined Fields if (_table.Table.Columns[colName] == null) return; FillUniqueValues(); } private void lstFields_DoubleClick(object sender, EventArgs e) { if (lstFields.SelectedItem == null) return; insertText2WhereClause(lstFields.SelectedItem.ToString()); } private void lstUniqueValues_DoubleClick(object sender, EventArgs e) { if (lstUniqueValues.SelectedItem == null) return; insertText2WhereClause(lstUniqueValues.SelectedItem.ToString()); } private void btnCompleteList_Click(object sender, EventArgs e) { if (_tc == null || lstFields.SelectedItems == null) return; string fieldName = lstFields.SelectedItem.ToString().Replace("[", String.Empty).Replace("]", String.Empty); // Joined Fields [...] IField field = _tc.FindField(fieldName); DistinctFilter filter = new DistinctFilter(field.name); lstUniqueValues.Items.Clear(); this.Cursor = Cursors.WaitCursor; ICursor cursor = _tc.Search(filter); if(cursor==null) return; _cancelTracker.Reset(); BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += new DoWorkEventHandler(CompleteList_DoWork); bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CompleteList_RunWorkerCompleted); bw.RunWorkerAsync(cursor); } void CompleteList_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { FillUniqueValues(); this.Cursor = Cursors.Default; } void CompleteList_DoWork(object sender, DoWorkEventArgs e) { ICursor cursor = e.Argument as ICursor; if (cursor == null) return; List<string> list = null; try { IRow row; while ((row = (cursor is IFeatureCursor) ? ((IFeatureCursor)cursor).NextFeature : (cursor is IRowCursor) ? ((IRowCursor)cursor).NextRow : null) != null) { if (list == null) { if (_values.TryGetValue(row.Fields[0].Name, out list)) { list.Clear(); } else { _values.Add(row.Fields[0].Name, list = new List<string>()); } } list.Add(row[0].ToString()); if (!_cancelTracker.Continue) break; } } finally { if (cursor != null) cursor.Dispose(); } } private void FormQueryBuilder_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Escape) _cancelTracker.Cancel(); } private void btnOK_Click(object sender, EventArgs e) { } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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. * * 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; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace XenAPI { /// <summary> /// Describes the vusb device /// First published in XenServer 7.3. /// </summary> public partial class VUSB : XenObject<VUSB> { public VUSB() { } public VUSB(string uuid, List<vusb_operations> allowed_operations, Dictionary<string, vusb_operations> current_operations, XenRef<VM> VM, XenRef<USB_group> USB_group, Dictionary<string, string> other_config, bool currently_attached) { this.uuid = uuid; this.allowed_operations = allowed_operations; this.current_operations = current_operations; this.VM = VM; this.USB_group = USB_group; this.other_config = other_config; this.currently_attached = currently_attached; } /// <summary> /// Creates a new VUSB from a Proxy_VUSB. /// </summary> /// <param name="proxy"></param> public VUSB(Proxy_VUSB proxy) { this.UpdateFromProxy(proxy); } /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given VUSB. /// </summary> public override void UpdateFrom(VUSB update) { uuid = update.uuid; allowed_operations = update.allowed_operations; current_operations = update.current_operations; VM = update.VM; USB_group = update.USB_group; other_config = update.other_config; currently_attached = update.currently_attached; } internal void UpdateFromProxy(Proxy_VUSB proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; allowed_operations = proxy.allowed_operations == null ? null : Helper.StringArrayToEnumList<vusb_operations>(proxy.allowed_operations); current_operations = proxy.current_operations == null ? null : Maps.convert_from_proxy_string_vusb_operations(proxy.current_operations); VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM); USB_group = proxy.USB_group == null ? null : XenRef<USB_group>.Create(proxy.USB_group); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); currently_attached = (bool)proxy.currently_attached; } public Proxy_VUSB ToProxy() { Proxy_VUSB result_ = new Proxy_VUSB(); result_.uuid = uuid ?? ""; result_.allowed_operations = (allowed_operations != null) ? Helper.ObjectListToStringArray(allowed_operations) : new string[] {}; result_.current_operations = Maps.convert_to_proxy_string_vusb_operations(current_operations); result_.VM = VM ?? ""; result_.USB_group = USB_group ?? ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); result_.currently_attached = currently_attached; return result_; } /// <summary> /// Creates a new VUSB from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public VUSB(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this VUSB /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("allowed_operations")) allowed_operations = Helper.StringArrayToEnumList<vusb_operations>(Marshalling.ParseStringArray(table, "allowed_operations")); if (table.ContainsKey("current_operations")) current_operations = Maps.convert_from_proxy_string_vusb_operations(Marshalling.ParseHashTable(table, "current_operations")); if (table.ContainsKey("VM")) VM = Marshalling.ParseRef<VM>(table, "VM"); if (table.ContainsKey("USB_group")) USB_group = Marshalling.ParseRef<USB_group>(table, "USB_group"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); if (table.ContainsKey("currently_attached")) currently_attached = Marshalling.ParseBool(table, "currently_attached"); } public bool DeepEquals(VUSB other, bool ignoreCurrentOperations) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; if (!ignoreCurrentOperations && !Helper.AreEqual2(this.current_operations, other.current_operations)) return false; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._allowed_operations, other._allowed_operations) && Helper.AreEqual2(this._VM, other._VM) && Helper.AreEqual2(this._USB_group, other._USB_group) && Helper.AreEqual2(this._other_config, other._other_config) && Helper.AreEqual2(this._currently_attached, other._currently_attached); } internal static List<VUSB> ProxyArrayToObjectList(Proxy_VUSB[] input) { var result = new List<VUSB>(); foreach (var item in input) result.Add(new VUSB(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, VUSB server) { if (opaqueRef == null) { System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server"); return ""; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { VUSB.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static VUSB get_record(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_record(session.opaque_ref, _vusb); else return new VUSB((Proxy_VUSB)session.proxy.vusb_get_record(session.opaque_ref, _vusb ?? "").parse()); } /// <summary> /// Get a reference to the VUSB instance with the specified UUID. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VUSB> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<VUSB>.Create(session.proxy.vusb_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Get the uuid field of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static string get_uuid(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_uuid(session.opaque_ref, _vusb); else return (string)session.proxy.vusb_get_uuid(session.opaque_ref, _vusb ?? "").parse(); } /// <summary> /// Get the allowed_operations field of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static List<vusb_operations> get_allowed_operations(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_allowed_operations(session.opaque_ref, _vusb); else return Helper.StringArrayToEnumList<vusb_operations>(session.proxy.vusb_get_allowed_operations(session.opaque_ref, _vusb ?? "").parse()); } /// <summary> /// Get the current_operations field of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static Dictionary<string, vusb_operations> get_current_operations(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_current_operations(session.opaque_ref, _vusb); else return Maps.convert_from_proxy_string_vusb_operations(session.proxy.vusb_get_current_operations(session.opaque_ref, _vusb ?? "").parse()); } /// <summary> /// Get the VM field of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static XenRef<VM> get_VM(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_vm(session.opaque_ref, _vusb); else return XenRef<VM>.Create(session.proxy.vusb_get_vm(session.opaque_ref, _vusb ?? "").parse()); } /// <summary> /// Get the USB_group field of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static XenRef<USB_group> get_USB_group(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_usb_group(session.opaque_ref, _vusb); else return XenRef<USB_group>.Create(session.proxy.vusb_get_usb_group(session.opaque_ref, _vusb ?? "").parse()); } /// <summary> /// Get the other_config field of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static Dictionary<string, string> get_other_config(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_other_config(session.opaque_ref, _vusb); else return Maps.convert_from_proxy_string_string(session.proxy.vusb_get_other_config(session.opaque_ref, _vusb ?? "").parse()); } /// <summary> /// Get the currently_attached field of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static bool get_currently_attached(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_currently_attached(session.opaque_ref, _vusb); else return (bool)session.proxy.vusb_get_currently_attached(session.opaque_ref, _vusb ?? "").parse(); } /// <summary> /// Set the other_config field of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _vusb, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.vusb_set_other_config(session.opaque_ref, _vusb, _other_config); else session.proxy.vusb_set_other_config(session.opaque_ref, _vusb ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given VUSB. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _vusb, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.vusb_add_to_other_config(session.opaque_ref, _vusb, _key, _value); else session.proxy.vusb_add_to_other_config(session.opaque_ref, _vusb ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given VUSB. If the key is not in that Map, then do nothing. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _vusb, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.vusb_remove_from_other_config(session.opaque_ref, _vusb, _key); else session.proxy.vusb_remove_from_other_config(session.opaque_ref, _vusb ?? "", _key ?? "").parse(); } /// <summary> /// Create a new VUSB record in the database only /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vm">The VM</param> /// <param name="_usb_group"></param> /// <param name="_other_config"></param> public static XenRef<VUSB> create(Session session, string _vm, string _usb_group, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_create(session.opaque_ref, _vm, _usb_group, _other_config); else return XenRef<VUSB>.Create(session.proxy.vusb_create(session.opaque_ref, _vm ?? "", _usb_group ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse()); } /// <summary> /// Create a new VUSB record in the database only /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vm">The VM</param> /// <param name="_usb_group"></param> /// <param name="_other_config"></param> public static XenRef<Task> async_create(Session session, string _vm, string _usb_group, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_vusb_create(session.opaque_ref, _vm, _usb_group, _other_config); else return XenRef<Task>.Create(session.proxy.async_vusb_create(session.opaque_ref, _vm ?? "", _usb_group ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse()); } /// <summary> /// Unplug the vusb device from the vm. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static void unplug(Session session, string _vusb) { if (session.JsonRpcClient != null) session.JsonRpcClient.vusb_unplug(session.opaque_ref, _vusb); else session.proxy.vusb_unplug(session.opaque_ref, _vusb ?? "").parse(); } /// <summary> /// Unplug the vusb device from the vm. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static XenRef<Task> async_unplug(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_vusb_unplug(session.opaque_ref, _vusb); else return XenRef<Task>.Create(session.proxy.async_vusb_unplug(session.opaque_ref, _vusb ?? "").parse()); } /// <summary> /// Removes a VUSB record from the database /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static void destroy(Session session, string _vusb) { if (session.JsonRpcClient != null) session.JsonRpcClient.vusb_destroy(session.opaque_ref, _vusb); else session.proxy.vusb_destroy(session.opaque_ref, _vusb ?? "").parse(); } /// <summary> /// Removes a VUSB record from the database /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> /// <param name="_vusb">The opaque_ref of the given vusb</param> public static XenRef<Task> async_destroy(Session session, string _vusb) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_vusb_destroy(session.opaque_ref, _vusb); else return XenRef<Task>.Create(session.proxy.async_vusb_destroy(session.opaque_ref, _vusb ?? "").parse()); } /// <summary> /// Return a list of all the VUSBs known to the system. /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> public static List<XenRef<VUSB>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_all(session.opaque_ref); else return XenRef<VUSB>.Create(session.proxy.vusb_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the VUSB Records at once, in a single XML RPC call /// First published in XenServer 7.3. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<VUSB>, VUSB> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vusb_get_all_records(session.opaque_ref); else return XenRef<VUSB>.Create<Proxy_VUSB>(session.proxy.vusb_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client. /// </summary> public virtual List<vusb_operations> allowed_operations { get { return _allowed_operations; } set { if (!Helper.AreEqual(value, _allowed_operations)) { _allowed_operations = value; Changed = true; NotifyPropertyChanged("allowed_operations"); } } } private List<vusb_operations> _allowed_operations = new List<vusb_operations>() {}; /// <summary> /// links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task. /// </summary> public virtual Dictionary<string, vusb_operations> current_operations { get { return _current_operations; } set { if (!Helper.AreEqual(value, _current_operations)) { _current_operations = value; Changed = true; NotifyPropertyChanged("current_operations"); } } } private Dictionary<string, vusb_operations> _current_operations = new Dictionary<string, vusb_operations>() {}; /// <summary> /// VM that owns the VUSB /// </summary> [JsonConverter(typeof(XenRefConverter<VM>))] public virtual XenRef<VM> VM { get { return _VM; } set { if (!Helper.AreEqual(value, _VM)) { _VM = value; Changed = true; NotifyPropertyChanged("VM"); } } } private XenRef<VM> _VM = new XenRef<VM>(Helper.NullOpaqueRef); /// <summary> /// USB group used by the VUSB /// </summary> [JsonConverter(typeof(XenRefConverter<USB_group>))] public virtual XenRef<USB_group> USB_group { get { return _USB_group; } set { if (!Helper.AreEqual(value, _USB_group)) { _USB_group = value; Changed = true; NotifyPropertyChanged("USB_group"); } } } private XenRef<USB_group> _USB_group = new XenRef<USB_group>(Helper.NullOpaqueRef); /// <summary> /// Additional configuration /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; /// <summary> /// is the device currently attached /// </summary> public virtual bool currently_attached { get { return _currently_attached; } set { if (!Helper.AreEqual(value, _currently_attached)) { _currently_attached = value; Changed = true; NotifyPropertyChanged("currently_attached"); } } } private bool _currently_attached = false; } }
// <copyright file="MultiListMasterSlaveListAdapter{T}.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics.CodeAnalysis; using System.Linq; using IX.StandardExtensions.Contracts; using IX.StandardExtensions.Extensions; namespace IX.Observable.Adapters; internal class MultiListMasterSlaveListAdapter<T> : ModernListAdapter<T, IEnumerator<T>> { #region Internal state private readonly List<IEnumerable<T>> slaves; [SuppressMessage( "IDisposableAnalyzers.Correctness", "IDISP006:Implement IDisposable.", Justification = "We do not own this instance, disposing it is not advisable.")] private IList<T>? master; #endregion #region Constructors and destructors internal MultiListMasterSlaveListAdapter() { this.slaves = new List<IEnumerable<T>>(); } #endregion #region Properties and indexers public override int Count { get { this.master ??= new ObservableList<T>(); return this.master.Count + this.slaves.Sum(p => p.Count()); } } public override bool IsReadOnly { get { this.master ??= new ObservableList<T>(); return this.master.IsReadOnly; } } public int SlavesCount => this.slaves.Count; internal int MasterCount { get { this.master ??= new ObservableList<T>(); return this.master.Count; } } [SuppressMessage( "ReSharper", "PossibleMultipleEnumeration", Justification = "Appears unavoidable at this time.")] public override T this[int index] { get { this.master ??= new ObservableList<T>(); if (index < this.master.Count) { return this.master[index]; } var idx = index - this.master.Count; foreach (IEnumerable<T> slave in this.slaves) { var count = slave.Count(); if (count > idx) { return slave.ElementAt(idx); } idx -= count; } throw new IndexOutOfRangeException(); } set { this.master ??= new ObservableList<T>(); this.master[index] = value; } } #endregion #region Methods public override int Add(T item) { this.master ??= new ObservableList<T>(); this.master.Add(item); return this.MasterCount - 1; } public override int AddRange(IEnumerable<T> items) { this.master ??= new ObservableList<T>(); var index = this.master.Count; items.ForEach( ( p, masterL1) => masterL1.Add(p), this.master); return index; } public override void Clear() { this.master ??= new ObservableList<T>(); this.master.Clear(); } public override bool Contains(T item) { this.master ??= new ObservableList<T>(); return this.master.Contains(item) || this.slaves.Any( ( p, itemL1) => p.Contains(itemL1), item); } public void MasterCopyTo( T[] array, int arrayIndex) { this.master ??= new ObservableList<T>(); this.master.CopyTo( array, arrayIndex); } [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "We can't avoid this here.")] public override void CopyTo( T[] array, int arrayIndex) { this.master ??= new ObservableList<T>(); var totalCount = this.Count + arrayIndex; using IEnumerator<T> enumerator = this.GetEnumerator(); for (var i = arrayIndex; i < totalCount; i++) { if (!enumerator.MoveNext()) { break; } array[i] = enumerator.Current; } } [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "We can't avoid this here.")] public override IEnumerator<T> GetEnumerator() { this.master ??= new ObservableList<T>(); foreach (T var in this.master) { yield return var; } foreach (IEnumerable<T> lst in this.slaves) { foreach (T var in lst) { yield return var; } } } public override int Remove(T item) { this.master ??= new ObservableList<T>(); var index = this.master.IndexOf(item); this.master.Remove(item); return index; } public override void Insert( int index, T item) { this.master ??= new ObservableList<T>(); this.master.Insert( index, item); } [SuppressMessage( "Performance", "HAA0401:Possible allocation of reference type enumerator", Justification = "We can't avoid this here.")] public override int IndexOf(T item) { this.master ??= new ObservableList<T>(); var offset = 0; int foundIndex; if ((foundIndex = this.master.IndexOf(item)) != -1) { return foundIndex; } offset += this.master.Count; foreach (List<T> slave in this.slaves.Select(p => p.ToList())) { if ((foundIndex = slave.IndexOf(item)) != -1) { return foundIndex + offset; } offset += slave.Count; } return -1; } /// <summary> /// Removes an item at a specific index. /// </summary> /// <param name="index">The index at which to remove from.</param> public override void RemoveAt(int index) { this.master ??= new ObservableList<T>(); this.master.RemoveAt(index); } [SuppressMessage( "IDisposableAnalyzers.Correctness", "IDISP003:Dispose previous before re-assigning", Justification = "We do not own this instance, disposing it is not advisable.")] internal void SetMaster<TList>(TList masterList) where TList : class, IList<T>, INotifyCollectionChanged { TList newMaster = Requires.NotNull(masterList); IList<T>? oldMaster = this.master; if (oldMaster != null) { try { ((INotifyCollectionChanged)oldMaster).CollectionChanged -= this.List_CollectionChanged; } catch { // We need to do nothing here. Inability to remove the event delegate reference is of no consequence. } } this.master = newMaster; masterList.CollectionChanged += this.List_CollectionChanged; } internal void SetSlave<TList>(TList slaveList) where TList : class, IEnumerable<T>, INotifyCollectionChanged { this.slaves.Add(Requires.NotNull(slaveList)); slaveList.CollectionChanged += this.List_CollectionChanged; } internal void RemoveSlave<TList>(TList slaveList) where TList : class, IEnumerable<T>, INotifyCollectionChanged { var localSlaveList = Requires.NotNull( slaveList); try { localSlaveList.CollectionChanged -= this.List_CollectionChanged; } catch { // We need to do nothing here. Inability to remove the event delegate reference is of no consequence. } this.slaves.Remove(localSlaveList); } private void List_CollectionChanged( object? sender, NotifyCollectionChangedEventArgs e) => this.TriggerReset(); #endregion }
using Assets.Gamelogic.Core; using Assets.Gamelogic.Utils; using Improbable; using Improbable.Abilities; using Improbable.Building; using Improbable.Collections; using Improbable.Communication; using Improbable.Core; using Improbable.Fire; using Improbable.Global; using Improbable.Life; using Improbable.Math; using Improbable.Npc; using Improbable.Player; using Improbable.Team; using Improbable.Tree; using Improbable.Unity.Core.Acls; using Improbable.Worker; namespace Assets.Gamelogic.EntityTemplate { public static class EntityTemplateFactory { public static Entity CreatePlayerTemplate(string clientWorkerId, Coordinates initialPosition, uint teamId) { var template = new Entity(); template.Add(new ClientAuthorityCheck.Data()); template.Add(new FSimAuthorityCheck.Data()); template.Add(new TransformComponent.Data(initialPosition, 0)); template.Add(new PlayerInfo.Data(true, initialPosition)); template.Add(new PlayerControls.Data(initialPosition)); template.Add(new Health.Data(SimulationSettings.PlayerMaxHealth, SimulationSettings.PlayerMaxHealth, true)); template.Add(new Flammable.Data(false, true, FireEffectType.SMALL)); template.Add(new Spells.Data(new Map<SpellType, float> { { SpellType.LIGHTNING, 0f }, { SpellType.RAIN, 0f } }, true)); template.Add(new Inventory.Data(0)); template.Add(new Chat.Data()); template.Add(new Heartbeat.Data(SimulationSettings.HeartbeatMax)); template.Add(new TeamAssignment.Data(teamId)); template.Add(new Flammable.Data(false, true, FireEffectType.SMALL)); var specificClientPredicate = CommonPredicates.SpecificClientOnly(clientWorkerId); var permissions = Acl.Build() .SetReadAccess(CommonPredicates.PhysicsOrVisual) .SetWriteAccess<ClientAuthorityCheck>(specificClientPredicate) .SetWriteAccess<FSimAuthorityCheck>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TransformComponent>(CommonPredicates.PhysicsOnly) .SetWriteAccess<PlayerInfo>(CommonPredicates.PhysicsOnly) .SetWriteAccess<PlayerControls>(specificClientPredicate) .SetWriteAccess<Health>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Flammable>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Spells>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Inventory>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Chat>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Heartbeat>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TeamAssignment>(CommonPredicates.PhysicsOnly); template.SetAcl(permissions); return template; } public static SnapshotEntity CreateBarracksTemplate(Coordinates initialPosition, BarracksState barracksState, uint teamId) { var template = new SnapshotEntity { Prefab = SimulationSettings.BarracksPrefabName }; template.Add(new FSimAuthorityCheck.Data()); template.Add(new TransformComponent.Data(initialPosition, (uint)(UnityEngine.Random.value * 360))); template.Add(new BarracksInfo.Data(barracksState)); template.Add(new Health.Data(barracksState == BarracksState.CONSTRUCTION_FINISHED ? SimulationSettings.BarracksMaxHealth : 0, SimulationSettings.BarracksMaxHealth, true)); template.Add(new Flammable.Data(false, false, FireEffectType.BIG)); template.Add(new StockpileDepository.Data(barracksState == BarracksState.UNDER_CONSTRUCTION)); template.Add(new NPCSpawner.Data(barracksState == BarracksState.CONSTRUCTION_FINISHED, new Map<NPCRole, float> { { NPCRole.LUMBERJACK, 0f }, { NPCRole.WIZARD, 0f } })); template.Add(new TeamAssignment.Data(teamId)); var permissions = Acl.Build() .SetReadAccess(CommonPredicates.PhysicsOrVisual) .SetWriteAccess<FSimAuthorityCheck>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TransformComponent>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Flammable>(CommonPredicates.PhysicsOnly) .SetWriteAccess<BarracksInfo>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Health>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Flammable>(CommonPredicates.PhysicsOnly) .SetWriteAccess<StockpileDepository>(CommonPredicates.PhysicsOnly) .SetWriteAccess<NPCSpawner>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TeamAssignment>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Flammable>(CommonPredicates.PhysicsOnly); template.SetAcl(permissions); return template; } public static SnapshotEntity CreateIndividualTemplate(Coordinates initialPosition) { var template = new SnapshotEntity { Prefab = SimulationSettings.PlayerPrefabName }; template.Add(new TransformComponent.Data(initialPosition, (uint)0)); var permissions = Acl.Build() .SetReadAccess(CommonPredicates.PhysicsOrVisual) .SetWriteAccess<TransformComponent>(CommonPredicates.PhysicsOnly); template.SetAcl(permissions); return template; } public static SnapshotEntity CreateCountryTemplate(Coordinates initialPosition) { var template = new SnapshotEntity { Prefab = SimulationSettings.CountryPrefabName }; template.Add(new FSimAuthorityCheck.Data()); template.Add(new TransformComponent.Data(initialPosition, (uint)0)); template.Add(new Harvestable.Data()); template.Add(new Health.Data(SimulationSettings.TreeMaxHealth, SimulationSettings.TreeMaxHealth, true)); template.Add(new Flammable.Data(false, true, FireEffectType.BIG)); template.Add(new TreeState.Data((TreeType)UnityEngine.Random.Range(0, 2), TreeFSMState.HEALTHY, (ulong)0, 5.0f)); var permissions = Acl.Build() .SetReadAccess(CommonPredicates.PhysicsOrVisual) .SetWriteAccess<FSimAuthorityCheck>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TransformComponent>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Harvestable>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Health>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Flammable>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TreeState>(CommonPredicates.PhysicsOnly); template.SetAcl(permissions); return template; } public static SnapshotEntity CreateNPCLumberjackTemplate(Coordinates initialPosition, uint teamId) { var template = new SnapshotEntity { Prefab = SimulationSettings.NPCPrefabName }; template.Add(new TransformComponent.Data(initialPosition, 0)); template.Add(new FSimAuthorityCheck.Data()); template.Add(new Health.Data(SimulationSettings.LumberjackMaxHealth, SimulationSettings.LumberjackMaxHealth, true)); template.Add(new Flammable.Data(false, true, FireEffectType.SMALL)); template.Add(new TargetNavigation.Data(NavigationState.INACTIVE, Vector3f.ZERO, EntityId.InvalidEntityId, 0f)); template.Add(new Inventory.Data(0)); template.Add(new NPCLumberjack.Data(LumberjackFSMState.StateEnum.IDLE, EntityId.InvalidEntityId, SimulationSettings.InvalidPosition.ToVector3f())); template.Add(new TeamAssignment.Data(teamId)); var permissions = Acl.Build() .SetReadAccess(CommonPredicates.PhysicsOrVisual) .SetWriteAccess<TransformComponent>(CommonPredicates.PhysicsOnly) .SetWriteAccess<FSimAuthorityCheck>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Health>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Flammable>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TargetNavigation>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Inventory>(CommonPredicates.PhysicsOnly) .SetWriteAccess<NPCLumberjack>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TeamAssignment>(CommonPredicates.PhysicsOnly); template.SetAcl(permissions); return template; } public static SnapshotEntity CreateNPCWizardTemplate(Coordinates initialPosition, uint teamId) { var template = new SnapshotEntity { Prefab = SimulationSettings.NPCWizardPrefabName }; template.Add(new TransformComponent.Data(initialPosition, 0)); template.Add(new FSimAuthorityCheck.Data()); template.Add(new Health.Data(SimulationSettings.WizardMaxHealth, SimulationSettings.WizardMaxHealth, true)); template.Add(new Flammable.Data(false, true, FireEffectType.SMALL)); template.Add(new TargetNavigation.Data(NavigationState.INACTIVE, Vector3f.ZERO, EntityId.InvalidEntityId, 0f)); template.Add(new Spells.Data(new Map<SpellType, float> { { SpellType.LIGHTNING, 0f }, { SpellType.RAIN, 0f } }, true)); template.Add(new NPCWizard.Data(WizardFSMState.StateEnum.IDLE, EntityId.InvalidEntityId, SimulationSettings.InvalidPosition.ToVector3f())); template.Add(new TeamAssignment.Data(teamId)); var permissions = Acl.Build() .SetReadAccess(CommonPredicates.PhysicsOrVisual) .SetWriteAccess<TransformComponent>(CommonPredicates.PhysicsOnly) .SetWriteAccess<FSimAuthorityCheck>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Health>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Flammable>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TargetNavigation>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Spells>(CommonPredicates.PhysicsOnly) .SetWriteAccess<NPCWizard>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TeamAssignment>(CommonPredicates.PhysicsOnly); template.SetAcl(permissions); return template; } public static SnapshotEntity CreateHQTemplate(Coordinates initialPosition, uint initialRotation, uint teamId) { var template = new SnapshotEntity { Prefab = SimulationSettings.HQPrefabName }; template.Add(new FSimAuthorityCheck.Data()); template.Add(new HQInfo.Data(new List<EntityId>())); template.Add(new TransformComponent.Data(initialPosition, initialRotation)); template.Add(new Health.Data(SimulationSettings.HQMaxHealth, SimulationSettings.HQMaxHealth, true)); template.Add(new TeamAssignment.Data(teamId)); template.Add(new Flammable.Data(false, true, FireEffectType.BIG)); var permissions = Acl.Build() .SetReadAccess(CommonPredicates.PhysicsOrVisual) .SetWriteAccess<FSimAuthorityCheck>(CommonPredicates.PhysicsOnly) .SetWriteAccess<HQInfo>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TransformComponent>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Health>(CommonPredicates.PhysicsOnly) .SetWriteAccess<TeamAssignment>(CommonPredicates.PhysicsOnly) .SetWriteAccess<Flammable>(CommonPredicates.PhysicsOnly); template.SetAcl(permissions); return template; } public static SnapshotEntity CreateSimulationManagerTemplate() { var template = new SnapshotEntity { Prefab = SimulationSettings.SimulationManagerEntityName }; template.Add(new TransformComponent.Data(Coordinates.ZERO, 0)); template.Add(new FSimAuthorityCheck.Data()); template.Add(new PlayerLifeCycle.Data(new Map<string, EntityId>())); var permissions = Acl.Build() .SetReadAccess(CommonPredicates.PhysicsOrVisual) .SetWriteAccess<TransformComponent>(CommonPredicates.PhysicsOnly) .SetWriteAccess<FSimAuthorityCheck>(CommonPredicates.PhysicsOnly) .SetWriteAccess<PlayerLifeCycle>(CommonPredicates.PhysicsOnly); template.SetAcl(permissions); return template; } } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation. All Rights Reserved. // // File: FormatConvertedBitmap.cs // //------------------------------------------------------------------------------ using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using MS.Internal; using MS.Win32.PresentationCore; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Windows.Media; using System.Globalization; using System.Runtime.InteropServices; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; namespace System.Windows.Media.Imaging { #region FormatConvertedBitmap /// <summary> /// FormatConvertedBitmap provides caching functionality for a BitmapSource. /// </summary> public sealed partial class FormatConvertedBitmap : Imaging.BitmapSource, ISupportInitialize { /// <summary> /// Constructor /// </summary> public FormatConvertedBitmap() : base(true) { } /// <summary> /// Construct a FormatConvertedBitmap /// </summary> /// <param name="source">BitmapSource to apply to the format conversion to</param> /// <param name="destinationFormat">Destionation Format to apply to the bitmap</param> /// <param name="destinationPalette">Palette if format is palettized</param> /// <param name="alphaThreshold">Alpha threshold</param> public FormatConvertedBitmap(BitmapSource source, PixelFormat destinationFormat, BitmapPalette destinationPalette, double alphaThreshold) : base(true) // Use base class virtuals { if (source == null) { throw new ArgumentNullException("source"); } if (alphaThreshold < (double)(0.0) || alphaThreshold > (double)(100.0)) { throw new ArgumentException(SR.Get(SRID.Image_AlphaThresholdOutOfRange)); } _bitmapInit.BeginInit(); Source = source; DestinationFormat = destinationFormat; DestinationPalette = destinationPalette; AlphaThreshold = alphaThreshold; _bitmapInit.EndInit(); FinalizeCreation(); } // ISupportInitialize /// <summary> /// Prepare the bitmap to accept initialize paramters. /// </summary> public void BeginInit() { WritePreamble(); _bitmapInit.BeginInit(); } /// <summary> /// Prepare the bitmap to accept initialize paramters. /// </summary> /// <SecurityNote> /// Critical - access critical resources /// PublicOK - All inputs verified /// </SecurityNote> [SecurityCritical ] public void EndInit() { WritePreamble(); _bitmapInit.EndInit(); IsValidForFinalizeCreation(/* throwIfInvalid = */ true); FinalizeCreation(); } private void ClonePrequel(FormatConvertedBitmap otherFormatConvertedBitmap) { BeginInit(); } private void ClonePostscript(FormatConvertedBitmap otherFormatConvertedBitmap) { EndInit(); } /// /// Create the unmanaged resources /// /// <SecurityNote> /// Critical - access critical resource /// </SecurityNote> [SecurityCritical] internal override void FinalizeCreation() { _bitmapInit.EnsureInitializedComplete(); BitmapSourceSafeMILHandle wicFormatter = null; using (FactoryMaker factoryMaker = new FactoryMaker()) { try { IntPtr wicFactory = factoryMaker.ImagingFactoryPtr; HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateFormatConverter( wicFactory, out wicFormatter)); SafeMILHandle internalPalette; if (DestinationPalette != null) internalPalette = DestinationPalette.InternalPalette; else internalPalette = new SafeMILHandle(); Guid format = DestinationFormat.Guid; lock (_syncObject) { HRESULT.Check(UnsafeNativeMethods.WICFormatConverter.Initialize( wicFormatter, Source.WicSourceHandle, ref format, DitherType.DitherTypeErrorDiffusion, internalPalette, AlphaThreshold, WICPaletteType.WICPaletteTypeOptimal )); } // // This is just a link in a BitmapSource chain. The memory is being used by // the BitmapSource at the end of the chain, so no memory pressure needs // to be added here. // WicSourceHandle = wicFormatter; // Even if our source is cached, format conversion is expensive and so we'll // always maintain our own cache for the purpose of rendering. _isSourceCached = false; } catch { _bitmapInit.Reset(); throw; } finally { if (wicFormatter != null) { wicFormatter.Close(); } } } CreationCompleted = true; UpdateCachedSettings(); } /// <summary> /// Notification on source changing. /// </summary> private void SourcePropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { BitmapSource newSource = e.NewValue as BitmapSource; _source = newSource; RegisterDownloadEventSource(_source); _syncObject = (newSource != null) ? newSource.SyncObject : _bitmapInit; } } internal override bool IsValidForFinalizeCreation(bool throwIfInvalid) { if (Source == null) { if (throwIfInvalid) { throw new InvalidOperationException(SR.Get(SRID.Image_NoArgument, "Source")); } return false; } if (DestinationFormat.Palettized) { if (DestinationPalette == null) { if (throwIfInvalid) { throw new InvalidOperationException(SR.Get(SRID.Image_IndexedPixelFormatRequiresPalette)); } return false; } else if ((1 << DestinationFormat.BitsPerPixel) < DestinationPalette.Colors.Count) { if (throwIfInvalid) { throw new InvalidOperationException(SR.Get(SRID.Image_PaletteColorsDoNotMatchFormat)); } return false; } } return true; } /// <summary> /// Notification on destination format changing. /// </summary> private void DestinationFormatPropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _destinationFormat = (PixelFormat)e.NewValue; } } /// <summary> /// Notification on destination palette changing. /// </summary> private void DestinationPalettePropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _destinationPalette = e.NewValue as BitmapPalette; } } /// <summary> /// Notification on alpha threshold changing. /// </summary> private void AlphaThresholdPropertyChangedHook(DependencyPropertyChangedEventArgs e) { if (!e.IsASubPropertyChange) { _alphaThreshold = (double)e.NewValue; } } /// <summary> /// Coerce Source /// </summary> private static object CoerceSource(DependencyObject d, object value) { FormatConvertedBitmap bitmap = (FormatConvertedBitmap)d; if (!bitmap._bitmapInit.IsInInit) { return bitmap._source; } else { return value; } } /// <summary> /// Coerce DestinationFormat /// </summary> private static object CoerceDestinationFormat(DependencyObject d, object value) { FormatConvertedBitmap bitmap = (FormatConvertedBitmap)d; if (!bitmap._bitmapInit.IsInInit) { return bitmap._destinationFormat; } else { // // If the client is trying to create a FormatConvertedBitmap with a // DestinationFormat == PixelFormats.Default, then coerce it to either // the Source bitmaps format (providing the Source bitmap is non-null) // or the original DP value. // if (((PixelFormat)value).Format == PixelFormatEnum.Default) { if (bitmap.Source != null) { return bitmap.Source.Format; } else { return bitmap._destinationFormat; } } else { return value; } } } /// <summary> /// Coerce DestinationPalette /// </summary> private static object CoerceDestinationPalette(DependencyObject d, object value) { FormatConvertedBitmap bitmap = (FormatConvertedBitmap)d; if (!bitmap._bitmapInit.IsInInit) { return bitmap._destinationPalette; } else { return value; } } /// <summary> /// Coerce Transform /// </summary> private static object CoerceAlphaThreshold(DependencyObject d, object value) { FormatConvertedBitmap bitmap = (FormatConvertedBitmap)d; if (!bitmap._bitmapInit.IsInInit) { return bitmap._alphaThreshold; } else { return value; } } #region Data Members private BitmapSource _source; private PixelFormat _destinationFormat; private BitmapPalette _destinationPalette; private double _alphaThreshold; #endregion } #endregion // FormatConvertedBitmap }
//------------------------------------------------------------------------------ // <copyright file="_LoggingObject.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ // // We have function based stack and thread based logging of basic behavior. We // also now have the ability to run a "watch thread" which does basic hang detection // and error-event based logging. The logging code buffers the callstack/picture // of all COMNET threads, and upon error from an assert or a hang, it will open a file // and dump the snapsnot. Future work will allow this to be configed by registry and // to use Runtime based logging. We'd also like to have different levels of logging. // namespace System.Net { using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using System.Diagnostics; using System.Security.Permissions; using System.Security.Principal; using System.Security; using Microsoft.Win32; using System.Runtime.ConstrainedExecution; using System.Globalization; using System.Configuration; // // BaseLoggingObject - used to disable logging, // this is just a base class that does nothing. // internal class BaseLoggingObject { internal BaseLoggingObject() { } internal virtual void EnterFunc(string funcname) { } internal virtual void LeaveFunc(string funcname) { } internal virtual void DumpArrayToConsole() { } internal virtual void PrintLine(string msg) { } internal virtual void DumpArray(bool shouldClose) { } internal virtual void DumpArrayToFile(bool shouldClose) { } internal virtual void Flush() { } internal virtual void Flush(bool close) { } internal virtual void LoggingMonitorTick() { } internal virtual void Dump(byte[] buffer) { } internal virtual void Dump(byte[] buffer, int length) { } internal virtual void Dump(byte[] buffer, int offset, int length) { } internal virtual void Dump(IntPtr pBuffer, int offset, int length) { } } // class BaseLoggingObject #if TRAVE /// <internalonly/> /// <devdoc> /// </devdoc> internal class LoggingObject : BaseLoggingObject { public ArrayList _Logarray; private Hashtable _ThreadNesting; private int _AddCount; private StreamWriter _Stream; private int _IamAlive; private int _LastIamAlive; private bool _Finalized = false; private double _NanosecondsPerTick; private int _StartMilliseconds; private long _StartTicks; internal LoggingObject() : base() { _Logarray = new ArrayList(); _ThreadNesting = new Hashtable(); _AddCount = 0; _IamAlive = 0; _LastIamAlive = -1; if (GlobalLog.s_UsePerfCounter) { long ticksPerSecond; SafeNativeMethods.QueryPerformanceFrequency(out ticksPerSecond); _NanosecondsPerTick = 10000000.0/(double)ticksPerSecond; SafeNativeMethods.QueryPerformanceCounter(out _StartTicks); } else { _StartMilliseconds = Environment.TickCount; } } // // LoggingMonitorTick - this function is run from the monitor thread, // and used to check to see if there any hangs, ie no logging // activitity // internal override void LoggingMonitorTick() { if ( _LastIamAlive == _IamAlive ) { PrintLine("================= Error TIMEOUT - HANG DETECTED ================="); DumpArray(true); } _LastIamAlive = _IamAlive; } internal override void EnterFunc(string funcname) { if (_Finalized) { return; } IncNestingCount(); ValidatePush(funcname); PrintLine(funcname); } internal override void LeaveFunc(string funcname) { if (_Finalized) { return; } PrintLine(funcname); DecNestingCount(); ValidatePop(funcname); } internal override void DumpArrayToConsole() { for (int i=0; i < _Logarray.Count; i++) { Console.WriteLine((string) _Logarray[i]); } } internal override void PrintLine(string msg) { if (_Finalized) { return; } string spc = ""; _IamAlive++; spc = GetNestingString(); string tickString = ""; if (GlobalLog.s_UsePerfCounter) { long nowTicks; SafeNativeMethods.QueryPerformanceCounter(out nowTicks); if (_StartTicks>nowTicks) { // counter reset, restart from 0 _StartTicks = nowTicks; } nowTicks -= _StartTicks; if (GlobalLog.s_UseTimeSpan) { tickString = new TimeSpan((long)(nowTicks*_NanosecondsPerTick)).ToString(); // note: TimeSpan().ToString() doesn't return the uSec part // if its 0. .ToString() returns [H*]HH:MM:SS:uuuuuuu, hence 16 if (tickString.Length < 16) { tickString += ".0000000"; } } else { tickString = ((double)nowTicks*_NanosecondsPerTick/10000).ToString("f3"); } } else { int nowMilliseconds = Environment.TickCount; if (_StartMilliseconds>nowMilliseconds) { _StartMilliseconds = nowMilliseconds; } nowMilliseconds -= _StartMilliseconds; if (GlobalLog.s_UseTimeSpan) { tickString = new TimeSpan(nowMilliseconds*10000).ToString(); // note: TimeSpan().ToString() doesn't return the uSec part // if its 0. .ToString() returns [H*]HH:MM:SS:uuuuuuu, hence 16 if (tickString.Length < 16) { tickString += ".0000000"; } } else { tickString = nowMilliseconds.ToString(); } } uint threadId = 0; if (GlobalLog.s_UseThreadId) { try { object threadData = Thread.GetData(GlobalLog.s_ThreadIdSlot); if (threadData!= null) { threadId = (uint)threadData; } } catch(Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } } if (threadId == 0) { threadId = UnsafeNclNativeMethods.GetCurrentThreadId(); Thread.SetData(GlobalLog.s_ThreadIdSlot, threadId); } } if (threadId == 0) { threadId = (uint)Thread.CurrentThread.GetHashCode(); } string str = "[" + threadId.ToString("x8") + "]" + " (" +tickString+ ") " + spc + msg; lock(this) { _AddCount++; _Logarray.Add(str); int MaxLines = GlobalLog.s_DumpToConsole ? 0 : GlobalLog.MaxLinesBeforeSave; if (_AddCount > MaxLines) { _AddCount = 0; DumpArray(false); _Logarray = new ArrayList(); } } } internal override void DumpArray(bool shouldClose) { if ( GlobalLog.s_DumpToConsole ) { DumpArrayToConsole(); } else { DumpArrayToFile(shouldClose); } } internal unsafe override void Dump(byte[] buffer, int offset, int length) { //if (!GlobalLog.s_DumpWebData) { // return; //} if (buffer==null) { PrintLine("(null)"); return; } if (offset > buffer.Length) { PrintLine("(offset out of range)"); return; } if (length > GlobalLog.s_MaxDumpSize) { PrintLine("(printing " + GlobalLog.s_MaxDumpSize.ToString() + " out of " + length.ToString() + ")"); length = GlobalLog.s_MaxDumpSize; } if ((length < 0) || (length > buffer.Length - offset)) { length = buffer.Length - offset; } fixed (byte* pBuffer = buffer) { Dump((IntPtr)pBuffer, offset, length); } } internal unsafe override void Dump(IntPtr pBuffer, int offset, int length) { //if (!GlobalLog.s_DumpWebData) { // return; //} if (pBuffer==IntPtr.Zero || length<0) { PrintLine("(null)"); return; } if (length > GlobalLog.s_MaxDumpSize) { PrintLine("(printing " + GlobalLog.s_MaxDumpSize.ToString() + " out of " + length.ToString() + ")"); length = GlobalLog.s_MaxDumpSize; } byte* buffer = (byte*)pBuffer + offset; Dump(buffer, length); } unsafe void Dump(byte* buffer, int length) { do { int offset = 0; int n = Math.Min(length, 16); string disp = ((IntPtr)buffer).ToString("X8") + " : " + offset.ToString("X8") + " : "; byte current; for (int i = 0; i < n; ++i) { current = *(buffer + i); disp += current.ToString("X2") + ((i == 7) ? '-' : ' '); } for (int i = n; i < 16; ++i) { disp += " "; } disp += ": "; for (int i = 0; i < n; ++i) { current = *(buffer + i); disp += ((current < 0x20) || (current > 0x7e)) ? '.' : (char)current; } PrintLine(disp); offset += n; buffer += n; length -= n; } while (length > 0); } // SECURITY: This is dev-debugging class and we need some permissions // to use it under trust-restricted environment as well. [PermissionSet(SecurityAction.Assert, Name="FullTrust")] internal override void DumpArrayToFile(bool shouldClose) { lock (this) { if (!shouldClose) { if (_Stream==null) { string mainLogFileRoot = GlobalLog.s_RootDirectory + "System.Net"; string mainLogFile = mainLogFileRoot; for (int k=0; k<20; k++) { if (k>0) { mainLogFile = mainLogFileRoot + "." + k.ToString(); } string fileName = mainLogFile + ".log"; if (!File.Exists(fileName)) { try { _Stream = new StreamWriter(fileName); break; } catch (Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } if (exception is SecurityException || exception is UnauthorizedAccessException) { // can't be CAS (we assert) this is an ACL issue break; } } } } if (_Stream==null) { _Stream = StreamWriter.Null; } // write a header with information about the Process and the AppDomain _Stream.Write("# MachineName: " + Environment.MachineName + "\r\n"); _Stream.Write("# ProcessName: " + Process.GetCurrentProcess().ProcessName + " (pid: " + Process.GetCurrentProcess().Id + ")\r\n"); _Stream.Write("# AppDomainId: " + AppDomain.CurrentDomain.Id + "\r\n"); _Stream.Write("# CurrentIdentity: " + WindowsIdentity.GetCurrent().Name + "\r\n"); _Stream.Write("# CommandLine: " + Environment.CommandLine + "\r\n"); _Stream.Write("# ClrVersion: " + Environment.Version + "\r\n"); _Stream.Write("# CreationDate: " + DateTime.Now.ToString("g") + "\r\n"); } } try { if (_Logarray!=null) { for (int i=0; i<_Logarray.Count; i++) { _Stream.Write((string)_Logarray[i]); _Stream.Write("\r\n"); } if (_Logarray.Count > 0 && _Stream != null) _Stream.Flush(); } } catch (Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } } if (shouldClose && _Stream!=null) { try { _Stream.Close(); } catch (ObjectDisposedException) { } _Stream = null; } } } internal override void Flush() { Flush(false); } internal override void Flush(bool close) { lock (this) { if (!GlobalLog.s_DumpToConsole) { DumpArrayToFile(close); _AddCount = 0; } } } private class ThreadInfoData { public ThreadInfoData(string indent) { Indent = indent; NestingStack = new Stack(); } public string Indent; public Stack NestingStack; }; string IndentString { get { string indent = " "; Object obj = _ThreadNesting[Thread.CurrentThread.GetHashCode()]; if (!GlobalLog.s_DebugCallNesting) { if (obj == null) { _ThreadNesting[Thread.CurrentThread.GetHashCode()] = indent; } else { indent = (String) obj; } } else { ThreadInfoData threadInfo = obj as ThreadInfoData; if (threadInfo == null) { threadInfo = new ThreadInfoData(indent); _ThreadNesting[Thread.CurrentThread.GetHashCode()] = threadInfo; } indent = threadInfo.Indent; } return indent; } set { Object obj = _ThreadNesting[Thread.CurrentThread.GetHashCode()]; if (obj == null) { return; } if (!GlobalLog.s_DebugCallNesting) { _ThreadNesting[Thread.CurrentThread.GetHashCode()] = value; } else { ThreadInfoData threadInfo = obj as ThreadInfoData; if (threadInfo == null) { threadInfo = new ThreadInfoData(value); _ThreadNesting[Thread.CurrentThread.GetHashCode()] = threadInfo; } threadInfo.Indent = value; } } } [System.Diagnostics.Conditional("TRAVE")] private void IncNestingCount() { IndentString = IndentString + " "; } [System.Diagnostics.Conditional("TRAVE")] private void DecNestingCount() { string indent = IndentString; if (indent.Length>1) { try { indent = indent.Substring(1); } catch { indent = string.Empty; } } if (indent.Length==0) { indent = "< "; } IndentString = indent; } private string GetNestingString() { return IndentString; } [System.Diagnostics.Conditional("TRAVE")] private void ValidatePush(string name) { if (GlobalLog.s_DebugCallNesting) { Object obj = _ThreadNesting[Thread.CurrentThread.GetHashCode()]; ThreadInfoData threadInfo = obj as ThreadInfoData; if (threadInfo == null) { return; } threadInfo.NestingStack.Push(name); } } [System.Diagnostics.Conditional("TRAVE")] private void ValidatePop(string name) { if (GlobalLog.s_DebugCallNesting) { try { Object obj = _ThreadNesting[Thread.CurrentThread.GetHashCode()]; ThreadInfoData threadInfo = obj as ThreadInfoData; if (threadInfo == null) { return; } if (threadInfo.NestingStack.Count == 0) { PrintLine("++++====" + "Poped Empty Stack for :"+name); } string popedName = (string) threadInfo.NestingStack.Pop(); string [] parsedList = popedName.Split(new char [] {'(',')',' ','.',':',',','#'}); foreach (string element in parsedList) { if (element != null && element.Length > 1 && name.IndexOf(element) != -1) { return; } } PrintLine("++++====" + "Expected:" + popedName + ": got :" + name + ": StackSize:"+threadInfo.NestingStack.Count); // relevel the stack while(threadInfo.NestingStack.Count>0) { string popedName2 = (string) threadInfo.NestingStack.Pop(); string [] parsedList2 = popedName2.Split(new char [] {'(',')',' ','.',':',',','#'}); foreach (string element2 in parsedList2) { if (element2 != null && element2.Length > 1 && name.IndexOf(element2) != -1) { return; } } } } catch { PrintLine("++++====" + "ValidatePop failed for: "+name); } } } ~LoggingObject() { if(!_Finalized) { _Finalized = true; lock(this) { DumpArray(true); } } } } // class LoggingObject internal static class TraveHelper { private static readonly string Hexizer = "0x{0:x}"; internal static string ToHex(object value) { return String.Format(Hexizer, value); } } #endif // TRAVE #if TRAVE internal class IntegerSwitch : BooleanSwitch { public IntegerSwitch(string switchName, string switchDescription) : base(switchName, switchDescription) { } public new int Value { get { return base.SwitchSetting; } } } #endif [Flags] internal enum ThreadKinds { Unknown = 0x0000, // Mutually exclusive. User = 0x0001, // Thread has entered via an API. System = 0x0002, // Thread has entered via a system callback (e.g. completion port) or is our own thread. // Mutually exclusive. Sync = 0x0004, // Thread should block. Async = 0x0008, // Thread should not block. // Mutually exclusive, not always known for a user thread. Never changes. Timer = 0x0010, // Thread is the timer thread. (Can't call user code.) CompletionPort = 0x0020, // Thread is a ThreadPool completion-port thread. Worker = 0x0040, // Thread is a ThreadPool worker thread. Finalization = 0x0080, // Thread is the finalization thread. Other = 0x0100, // Unknown source. OwnerMask = User | System, SyncMask = Sync | Async, SourceMask = Timer | CompletionPort | Worker | Finalization | Other, // Useful "macros" SafeSources = SourceMask & ~(Timer | Finalization), // Methods that "unsafe" sources can call must be explicitly marked. ThreadPool = CompletionPort | Worker, // Like Thread.CurrentThread.IsThreadPoolThread } /// <internalonly/> /// <devdoc> /// </devdoc> internal static class GlobalLog { // // Logging Initalization - I need to disable Logging code, and limit // the effect it has when it is dissabled, so I use a bool here. // // This can only be set when the logging code is built and enabled. // By specifing the "CSC_DEFINES=/D:TRAVE" in the build environment, // this code will be built and then checks against an enviroment variable // and a BooleanSwitch to see if any of the two have enabled logging. // private static BaseLoggingObject Logobject = GlobalLog.LoggingInitialize(); #if TRAVE internal static LocalDataStoreSlot s_ThreadIdSlot; internal static bool s_UseThreadId; internal static bool s_UseTimeSpan; internal static bool s_DumpWebData; internal static bool s_UsePerfCounter; internal static bool s_DebugCallNesting; internal static bool s_DumpToConsole; internal static int s_MaxDumpSize; internal static string s_RootDirectory; // // Logging Config Variables - below are list of consts that can be used to config // the logging, // // Max number of lines written into a buffer, before a save is invoked // s_DumpToConsole disables. public const int MaxLinesBeforeSave = 0; #endif [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] private static BaseLoggingObject LoggingInitialize() { #if DEBUG if (GetSwitchValue("SystemNetLogging", "System.Net logging module", false) && GetSwitchValue("SystemNetLog_ConnectionMonitor", "System.Net connection monitor thread", false)) { InitConnectionMonitor(); } #endif // DEBUG #if TRAVE // by default we'll log to c:\temp\ so that non interactive services (like w3wp.exe) that don't have environment // variables can easily be debugged, note that the ACLs of the directory might need to be adjusted if (!GetSwitchValue("SystemNetLog_OverrideDefaults", "System.Net log override default settings", false)) { s_ThreadIdSlot = Thread.AllocateDataSlot(); s_UseThreadId = true; s_UseTimeSpan = true; s_DumpWebData = true; s_MaxDumpSize = 256; s_UsePerfCounter = true; s_DebugCallNesting = true; s_DumpToConsole = false; s_RootDirectory = "C:\\Temp\\"; return new LoggingObject(); } if (GetSwitchValue("SystemNetLogging", "System.Net logging module", false)) { s_ThreadIdSlot = Thread.AllocateDataSlot(); s_UseThreadId = GetSwitchValue("SystemNetLog_UseThreadId", "System.Net log display system thread id", false); s_UseTimeSpan = GetSwitchValue("SystemNetLog_UseTimeSpan", "System.Net log display ticks as TimeSpan", false); s_DumpWebData = GetSwitchValue("SystemNetLog_DumpWebData", "System.Net log display HTTP send/receive data", false); s_MaxDumpSize = GetSwitchValue("SystemNetLog_MaxDumpSize", "System.Net log max size of display data", 256); s_UsePerfCounter = GetSwitchValue("SystemNetLog_UsePerfCounter", "System.Net log use QueryPerformanceCounter() to get ticks ", false); s_DebugCallNesting = GetSwitchValue("SystemNetLog_DebugCallNesting", "System.Net used to debug call nesting", false); s_DumpToConsole = GetSwitchValue("SystemNetLog_DumpToConsole", "System.Net log to console", false); s_RootDirectory = GetSwitchValue("SystemNetLog_RootDirectory", "System.Net root directory of log file", string.Empty); return new LoggingObject(); } #endif // TRAVE return new BaseLoggingObject(); } #if TRAVE private static string GetSwitchValue(string switchName, string switchDescription, string defaultValue) { new EnvironmentPermission(PermissionState.Unrestricted).Assert(); try { defaultValue = Environment.GetEnvironmentVariable(switchName); } finally { EnvironmentPermission.RevertAssert(); } return defaultValue; } private static int GetSwitchValue(string switchName, string switchDescription, int defaultValue) { IntegerSwitch theSwitch = new IntegerSwitch(switchName, switchDescription); if (theSwitch.Enabled) { return theSwitch.Value; } new EnvironmentPermission(PermissionState.Unrestricted).Assert(); try { string environmentVar = Environment.GetEnvironmentVariable(switchName); if (environmentVar!=null) { defaultValue = Int32.Parse(environmentVar.Trim(), CultureInfo.InvariantCulture); } } finally { EnvironmentPermission.RevertAssert(); } return defaultValue; } #endif #if TRAVE || DEBUG private static bool GetSwitchValue(string switchName, string switchDescription, bool defaultValue) { BooleanSwitch theSwitch = new BooleanSwitch(switchName, switchDescription); new EnvironmentPermission(PermissionState.Unrestricted).Assert(); try { if (theSwitch.Enabled) { return true; } string environmentVar = Environment.GetEnvironmentVariable(switchName); defaultValue = environmentVar!=null && environmentVar.Trim()=="1"; } catch (ConfigurationException) { } finally { EnvironmentPermission.RevertAssert(); } return defaultValue; } #endif // TRAVE || DEBUG // Enables thread tracing, detects mis-use of threads. #if DEBUG [ThreadStatic] private static Stack<ThreadKinds> t_ThreadKindStack; private static Stack<ThreadKinds> ThreadKindStack { get { if (t_ThreadKindStack == null) { t_ThreadKindStack = new Stack<ThreadKinds>(); } return t_ThreadKindStack; } } #endif internal static ThreadKinds CurrentThreadKind { get { #if DEBUG return ThreadKindStack.Count > 0 ? ThreadKindStack.Peek() : ThreadKinds.Other; #else return ThreadKinds.Unknown; #endif } } #if DEBUG // ifdef'd instead of conditional since people are forced to handle the return value. // [Conditional("DEBUG")] [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] internal static IDisposable SetThreadKind(ThreadKinds kind) { if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown) { throw new InternalException(); } // Ignore during shutdown. if (NclUtilities.HasShutdownStarted) { return null; } ThreadKinds threadKind = CurrentThreadKind; ThreadKinds source = threadKind & ThreadKinds.SourceMask; #if TRAVE // Special warnings when doing dangerous things on a thread. if ((threadKind & ThreadKinds.User) != 0 && (kind & ThreadKinds.System) != 0) { Print("WARNING: Thread changed from User to System; user's thread shouldn't be hijacked."); } if ((threadKind & ThreadKinds.Async) != 0 && (kind & ThreadKinds.Sync) != 0) { Print("WARNING: Thread changed from Async to Sync, may block an Async thread."); } else if ((threadKind & (ThreadKinds.Other | ThreadKinds.CompletionPort)) == 0 && (kind & ThreadKinds.Sync) != 0) { Print("WARNING: Thread from a limited resource changed to Sync, may deadlock or bottleneck."); } #endif ThreadKindStack.Push( (((kind & ThreadKinds.OwnerMask) == 0 ? threadKind : kind) & ThreadKinds.OwnerMask) | (((kind & ThreadKinds.SyncMask) == 0 ? threadKind : kind) & ThreadKinds.SyncMask) | (kind & ~(ThreadKinds.OwnerMask | ThreadKinds.SyncMask)) | source); #if TRAVE if (CurrentThreadKind != threadKind) { Print("Thread becomes:(" + CurrentThreadKind.ToString() + ")"); } #endif return new ThreadKindFrame(); } private class ThreadKindFrame : IDisposable { private int m_FrameNumber; internal ThreadKindFrame() { m_FrameNumber = ThreadKindStack.Count; } void IDisposable.Dispose() { // Ignore during shutdown. if (NclUtilities.HasShutdownStarted) { return; } if (m_FrameNumber != ThreadKindStack.Count) { throw new InternalException(); } ThreadKinds previous = ThreadKindStack.Pop(); #if TRAVE if (CurrentThreadKind != previous) { Print("Thread reverts:(" + CurrentThreadKind.ToString() + ")"); } #endif } } #endif [Conditional("DEBUG")] [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] internal static void SetThreadSource(ThreadKinds source) { #if DEBUG if ((source & ThreadKinds.SourceMask) != source || source == ThreadKinds.Unknown) { throw new ArgumentException("Must specify the thread source.", "source"); } if (ThreadKindStack.Count == 0) { ThreadKindStack.Push(source); return; } if (ThreadKindStack.Count > 1) { Print("WARNING: SetThreadSource must be called at the base of the stack, or the stack has been corrupted."); while (ThreadKindStack.Count > 1) { ThreadKindStack.Pop(); } } if (ThreadKindStack.Peek() != source) { // SQL can fail to clean up the stack, leaving the default Other at the bottom. Replace it. Print("WARNING: The stack has been corrupted."); ThreadKinds last = ThreadKindStack.Pop() & ThreadKinds.SourceMask; Assert(last == source || last == ThreadKinds.Other, "Thread source changed.|Was:({0}) Now:({1})", last, source); ThreadKindStack.Push(source); } #endif } [Conditional("DEBUG")] [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] internal static void ThreadContract(ThreadKinds kind, string errorMsg) { ThreadContract(kind, ThreadKinds.SafeSources, errorMsg); } [Conditional("DEBUG")] [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] internal static void ThreadContract(ThreadKinds kind, ThreadKinds allowedSources, string errorMsg) { if ((kind & ThreadKinds.SourceMask) != ThreadKinds.Unknown || (allowedSources & ThreadKinds.SourceMask) != allowedSources) { throw new InternalException(); } ThreadKinds threadKind = CurrentThreadKind; Assert((threadKind & allowedSources) != 0, errorMsg, "Thread Contract Violation.|Expected source:({0}) Actual source:({1})", allowedSources , threadKind & ThreadKinds.SourceMask); Assert((threadKind & kind) == kind, errorMsg, "Thread Contract Violation.|Expected kind:({0}) Actual kind:({1})", kind, threadKind & ~ThreadKinds.SourceMask); } #if DEBUG // Enables auto-hang detection, which will "snap" a log on hang internal static bool EnableMonitorThread = false; // Default value for hang timer #if FEATURE_PAL // ROTORTODO - after speedups (like real JIT and GC) remove this public const int DefaultTickValue = 1000*60*5; // 5 minutes #else public const int DefaultTickValue = 1000*60; // 60 secs #endif // FEATURE_PAL #endif // DEBUG [System.Diagnostics.Conditional("TRAVE")] public static void AddToArray(string msg) { #if TRAVE GlobalLog.Logobject.PrintLine(msg); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Ignore(object msg) { } [System.Diagnostics.Conditional("TRAVE")] [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] public static void Print(string msg) { #if TRAVE GlobalLog.Logobject.PrintLine(msg); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void PrintHex(string msg, object value) { #if TRAVE GlobalLog.Logobject.PrintLine(msg+TraveHelper.ToHex(value)); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Enter(string func) { #if TRAVE GlobalLog.Logobject.EnterFunc(func + "(*none*)"); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Enter(string func, string parms) { #if TRAVE GlobalLog.Logobject.EnterFunc(func + "(" + parms + ")"); #endif } [Conditional("DEBUG")] [Conditional("_FORCE_ASSERTS")] [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] public static void Assert(bool condition, string messageFormat, params object[] data) { if (!condition) { string fullMessage = string.Format(CultureInfo.InvariantCulture, messageFormat, data); int pipeIndex = fullMessage.IndexOf('|'); if (pipeIndex == -1) { Assert(fullMessage); } else { int detailLength = fullMessage.Length - pipeIndex - 1; Assert(fullMessage.Substring(0, pipeIndex), detailLength > 0 ? fullMessage.Substring(pipeIndex + 1, detailLength) : null); } } } [Conditional("DEBUG")] [Conditional("_FORCE_ASSERTS")] [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] public static void Assert(string message) { Assert(message, null); } [Conditional("DEBUG")] [Conditional("_FORCE_ASSERTS")] [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] public static void Assert(string message, string detailMessage) { try { Print("Assert: " + message + (!string.IsNullOrEmpty(detailMessage) ? ": " + detailMessage : "")); Print("*******"); Logobject.DumpArray(false); } finally { #if DEBUG && !STRESS Debug.Assert(false, message, detailMessage); #else UnsafeNclNativeMethods.DebugBreak(); Debugger.Break(); #endif } } [System.Diagnostics.Conditional("TRAVE")] public static void LeaveException(string func, Exception exception) { #if TRAVE GlobalLog.Logobject.LeaveFunc(func + " exception " + ((exception!=null) ? exception.Message : String.Empty)); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Leave(string func) { #if TRAVE GlobalLog.Logobject.LeaveFunc(func + " returns "); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Leave(string func, string result) { #if TRAVE GlobalLog.Logobject.LeaveFunc(func + " returns " + result); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Leave(string func, int returnval) { #if TRAVE GlobalLog.Logobject.LeaveFunc(func + " returns " + returnval.ToString()); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Leave(string func, bool returnval) { #if TRAVE GlobalLog.Logobject.LeaveFunc(func + " returns " + returnval.ToString()); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void DumpArray() { #if TRAVE GlobalLog.Logobject.DumpArray(true); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Dump(byte[] buffer) { #if TRAVE Logobject.Dump(buffer, 0, buffer!=null ? buffer.Length : -1); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Dump(byte[] buffer, int length) { #if TRAVE Logobject.Dump(buffer, 0, length); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Dump(byte[] buffer, int offset, int length) { #if TRAVE Logobject.Dump(buffer, offset, length); #endif } [System.Diagnostics.Conditional("TRAVE")] public static void Dump(IntPtr buffer, int offset, int length) { #if TRAVE Logobject.Dump(buffer, offset, length); #endif } #if DEBUG private class HttpWebRequestComparer : IComparer { public int Compare( object x1, object y1 ) { HttpWebRequest x = (HttpWebRequest) x1; HttpWebRequest y = (HttpWebRequest) y1; if (x.GetHashCode() == y.GetHashCode()) { return 0; } else if (x.GetHashCode() < y.GetHashCode()) { return -1; } else if (x.GetHashCode() > y.GetHashCode()) { return 1; } return 0; } } private class ConnectionMonitorEntry { public HttpWebRequest m_Request; public int m_Flags; public DateTime m_TimeAdded; public Connection m_Connection; public ConnectionMonitorEntry(HttpWebRequest request, Connection connection, int flags) { m_Request = request; m_Connection = connection; m_Flags = flags; m_TimeAdded = DateTime.Now; } } private static volatile ManualResetEvent s_ShutdownEvent; private static volatile SortedList s_RequestList; internal const int WaitingForReadDoneFlag = 0x1; #endif #if DEBUG private static void ConnectionMonitor() { while(! s_ShutdownEvent.WaitOne(DefaultTickValue, false)) { if (GlobalLog.EnableMonitorThread) { #if TRAVE GlobalLog.Logobject.LoggingMonitorTick(); #endif } int hungCount = 0; lock (s_RequestList) { DateTime dateNow = DateTime.Now; DateTime dateExpired = dateNow.AddSeconds(-DefaultTickValue); foreach (ConnectionMonitorEntry monitorEntry in s_RequestList.GetValueList() ) { if (monitorEntry != null && (dateExpired > monitorEntry.m_TimeAdded)) { hungCount++; #if TRAVE GlobalLog.Print("delay:" + (dateNow - monitorEntry.m_TimeAdded).TotalSeconds + " req#" + monitorEntry.m_Request.GetHashCode() + " cnt#" + monitorEntry.m_Connection.GetHashCode() + " flags:" + monitorEntry.m_Flags); #endif monitorEntry.m_Connection.DebugMembers(monitorEntry.m_Request.GetHashCode()); } } } Assert(hungCount == 0, "Warning: Hang Detected on Connection(s) of greater than {0} ms. {1} request(s) hung.|Please Dump System.Net.GlobalLog.s_RequestList for pending requests, make sure your streams are calling Close(), and that your destination server is up.", DefaultTickValue, hungCount); } } #endif // DEBUG #if DEBUG [ReliabilityContract(Consistency.MayCorruptAppDomain, Cer.None)] internal static void AppDomainUnloadEvent(object sender, EventArgs e) { s_ShutdownEvent.Set(); } #endif #if DEBUG [System.Diagnostics.Conditional("DEBUG")] private static void InitConnectionMonitor() { s_RequestList = new SortedList(new HttpWebRequestComparer(), 10); s_ShutdownEvent = new ManualResetEvent(false); AppDomain.CurrentDomain.DomainUnload += new EventHandler(AppDomainUnloadEvent); AppDomain.CurrentDomain.ProcessExit += new EventHandler(AppDomainUnloadEvent); Thread threadMonitor = new Thread(new ThreadStart(ConnectionMonitor)); threadMonitor.IsBackground = true; threadMonitor.Start(); } #endif [System.Diagnostics.Conditional("DEBUG")] internal static void DebugAddRequest(HttpWebRequest request, Connection connection, int flags) { #if DEBUG // null if the connection monitor is off if(s_RequestList == null) return; lock(s_RequestList) { Assert(!s_RequestList.ContainsKey(request), "s_RequestList.ContainsKey(request)|A HttpWebRequest should not be submitted twice."); ConnectionMonitorEntry requestEntry = new ConnectionMonitorEntry(request, connection, flags); try { s_RequestList.Add(request, requestEntry); } catch { } } #endif } [System.Diagnostics.Conditional("DEBUG")] internal static void DebugRemoveRequest(HttpWebRequest request) { #if DEBUG // null if the connection monitor is off if(s_RequestList == null) return; lock(s_RequestList) { Assert(s_RequestList.ContainsKey(request), "!s_RequestList.ContainsKey(request)|A HttpWebRequest should not be removed twice."); try { s_RequestList.Remove(request); } catch { } } #endif } [System.Diagnostics.Conditional("DEBUG")] internal static void DebugUpdateRequest(HttpWebRequest request, Connection connection, int flags) { #if DEBUG // null if the connection monitor is off if(s_RequestList == null) return; lock(s_RequestList) { if(!s_RequestList.ContainsKey(request)) { return; } ConnectionMonitorEntry requestEntry = new ConnectionMonitorEntry(request, connection, flags); try { s_RequestList.Remove(request); s_RequestList.Add(request, requestEntry); } catch { } } #endif } } // class GlobalLog } // namespace System.Net
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Xml; using System.Xml.Schema; namespace XsdDocumentation.Model { internal sealed class SourceCodeManager : Manager { private const string TempLookupIdNamespace = "558d3140-e819-4535-97c8-305d208918a1"; private Dictionary<XmlSchema, XmlDocument> _schemaSources = new Dictionary<XmlSchema, XmlDocument>(); private Dictionary<XmlSchema, XmlNamespaceManager> _namespaceManagers = new Dictionary<XmlSchema, XmlNamespaceManager>(); private Dictionary<XmlSchemaAnnotated, string> _lookupIds; #region Lookup Id Helper Classes private abstract class IdVisitor : XmlSchemaSetVisitor { private XmlSchema _schema; private HashSet<XmlSchemaType> _processedTypes = new HashSet<XmlSchemaType>(); protected IdVisitor(XmlSchema schema) { _schema = schema; } private void InternalHandleId(XmlSchemaAnnotated element) { if (element.GetSchema() == _schema) HandleId(element); } protected abstract void HandleId(XmlSchemaAnnotated element); private bool AlreadyProcessed(XmlSchemaType type) { return !_processedTypes.Add(type); } protected override void Visit(XmlSchemaAnnotated annotated) { var type = annotated as XmlSchemaType; if (type != null && AlreadyProcessed(type)) return; InternalHandleId(annotated); base.Visit(annotated); } } private sealed class LookupIdAssigner : IdVisitor { private Dictionary<XmlSchemaAnnotated, string> _lookupIds; private XmlDocument _lookupIdAttributeOwner = new XmlDocument(); public LookupIdAssigner(XmlSchema schema, Dictionary<XmlSchemaAnnotated, string> lookupIds) : base(schema) { _lookupIds = lookupIds; } protected override void HandleId(XmlSchemaAnnotated element) { var lookupId = Guid.NewGuid().ToString(); var lookupAttributeId = _lookupIdAttributeOwner.CreateAttribute("temp", "lookupId", TempLookupIdNamespace); lookupAttributeId.Value = lookupId; XmlAttribute[] newUnhandledAttributes; if (element.UnhandledAttributes == null) newUnhandledAttributes = new XmlAttribute[1]; else { newUnhandledAttributes = new XmlAttribute[element.UnhandledAttributes.Length + 1]; Array.Copy(element.UnhandledAttributes, newUnhandledAttributes, element.UnhandledAttributes.Length); } newUnhandledAttributes[newUnhandledAttributes.Length - 1] = lookupAttributeId; element.UnhandledAttributes = newUnhandledAttributes; _lookupIds[element] = lookupId; } } private sealed class LookupIdRemover : IdVisitor { public LookupIdRemover(XmlSchema schema) : base(schema) { } protected override void HandleId(XmlSchemaAnnotated element) { if (element.UnhandledAttributes.Length == 1) element.UnhandledAttributes = null; else { var newUnhandledAttributes = new XmlAttribute[element.UnhandledAttributes.Length - 1]; Array.Copy(element.UnhandledAttributes, newUnhandledAttributes, newUnhandledAttributes.Length); element.UnhandledAttributes = newUnhandledAttributes; } } } #endregion [Flags] private enum PostProcessingOptions { RemoveAnnotations = 0x01, CollapseElements = 0x02, CollapseAttributes = 0x03, Format = 0x04 } public SourceCodeManager(Context context) : base(context) { } public override void Initialize() { _lookupIds = new Dictionary<XmlSchemaAnnotated, string>(); foreach (var schema in Context.SchemaSetManager.SchemaSet.GetAllSchemas()) { var schemaIdGenerator = new LookupIdAssigner(schema, _lookupIds); schemaIdGenerator.Traverse(schema); var schemaSource = GenerateSchemaSource(schema); var schemaIdRestorer = new LookupIdRemover(schema); schemaIdRestorer.Traverse(schema); var namespaceManager = new XmlNamespaceManager(schemaSource.NameTable); namespaceManager.AddNamespace("xs", XmlSchema.Namespace); namespaceManager.AddNamespace("temp", TempLookupIdNamespace); _schemaSources.Add(schema, schemaSource); _namespaceManagers.Add(schema, namespaceManager); } } private static XmlDocument GenerateSchemaSource(XmlSchema schema) { var doc = new XmlDocument(); using (var stringWriter = new StringWriter()) using (var xmlTextWriter = new XmlTextWriter(stringWriter)) { schema.Write(xmlTextWriter); doc.LoadXml(stringWriter.ToString()); } return doc; } public string GetSourceCode(XmlSchemaObject obj) { return InternalGetSourceCode(obj, PostProcessingOptions.Format); } public string GetSourceCodeAbridged(XmlSchemaObject obj) { return InternalGetSourceCode(obj, PostProcessingOptions.RemoveAnnotations | PostProcessingOptions.CollapseElements | PostProcessingOptions.CollapseAttributes | PostProcessingOptions.Format); } private string InternalGetSourceCode(XmlSchemaObject obj, PostProcessingOptions processingOptions) { var schema = obj as XmlSchema; if (schema != null) return GetSchemaSourceCode(schema, processingOptions); var annotated = obj as XmlSchemaAnnotated; return annotated == null ? string.Empty : GetObjectSourceCode(annotated, processingOptions); } private string GetSchemaSourceCode(XmlSchema schema, PostProcessingOptions processingOptions) { XmlDocument schemaSource; if (!_schemaSources.TryGetValue(schema, out schemaSource)) return string.Empty; var namespaceManager = _namespaceManagers[schema]; return PostProcess(namespaceManager, schemaSource, processingOptions); } private string GetObjectSourceCode(XmlSchemaAnnotated annotated, PostProcessingOptions processingOptions) { var schema = annotated.GetSchema(); if (schema == null) return string.Empty; XmlDocument schemaSource; if (!_schemaSources.TryGetValue(schema, out schemaSource)) return string.Empty; var namespaceManager = _namespaceManagers[schema]; var lookupId = _lookupIds[annotated]; var source = GetObjectSourceCode(schemaSource, namespaceManager, lookupId, processingOptions); return source; } private static string GetObjectSourceCode(XmlNode schemaSource, XmlNamespaceManager namespaceManager, string objLookupId, PostProcessingOptions processingOptions) { var node = schemaSource.SelectSingleNode(string.Format("//*[@temp:lookupId='{0}']", objLookupId), namespaceManager); return PostProcess(namespaceManager, node, processingOptions); } private static string PostProcess(XmlNamespaceManager namespaceManager, XmlNode node, PostProcessingOptions processingOptions) { var removeAnnotations = (processingOptions & PostProcessingOptions.RemoveAnnotations) == PostProcessingOptions.RemoveAnnotations; var collapseElements = (processingOptions & PostProcessingOptions.CollapseElements) == PostProcessingOptions.CollapseElements; var collapseAttributes = (processingOptions & PostProcessingOptions.CollapseAttributes) == PostProcessingOptions.CollapseAttributes; var format = (processingOptions & PostProcessingOptions.Format) == PostProcessingOptions.Format; // Create new document to perform post processing. var objSource = new XmlDocument(); objSource.LoadXml(node.OuterXml); RemoveLookupIds(objSource, namespaceManager); if (removeAnnotations) RemoveAnnotations(objSource, namespaceManager); if (collapseElements) CollapseElements(objSource, namespaceManager, "//xs:element|//xs:any"); if (collapseAttributes) CollapseElements(objSource, namespaceManager, "//xs:attribute|//xs:anyAttribute"); return format ? FormatXml(objSource) : objSource.OuterXml; } private static void RemoveLookupIds(XmlDocument objSource, XmlNamespaceManager namespaceManager) { // Remove lookup ids. var lookupIdNodes = objSource.SelectNodes("//@temp:lookupId", namespaceManager); Debug.Assert(lookupIdNodes != null); foreach (XmlAttribute lookupIdNode in lookupIdNodes) { var ownerElement = lookupIdNode.OwnerElement; Debug.Assert(ownerElement != null); ownerElement.Attributes.RemoveNamedItem("lookupId", TempLookupIdNamespace); } objSource.LoadXml(objSource.OuterXml); // Remove namespace binding to our temp lookup id namespace. Debug.Assert(objSource.DocumentElement != null); objSource.DocumentElement.RemoveAttribute("xmlns:temp"); } private static void RemoveAnnotations(XmlNode document, XmlNamespaceManager namespaceManager) { var annotations = document.SelectNodes("//xs:annotation", namespaceManager); if (annotations == null) return; foreach (XmlNode annotation in annotations) annotation.ParentNode.RemoveChild(annotation); } private static void CollapseElements(XmlNode document, XmlNamespaceManager namespaceManager, string xpath) { var rootNode = document.ChildNodes[0]; var nodes = document.SelectNodes(xpath, namespaceManager); if (nodes == null) return; foreach (XmlElement node in nodes) { if (node != rootNode) node.IsEmpty = true; } } private static string FormatXml(XmlDocument document) { // Now we write it the document to a string, but we make sure the // XML declaration is omitted, as this XML only represents a fragment. using (var stringWriter = new StringWriter()) { using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true })) { Debug.Assert(xmlWriter != null); document.Save(xmlWriter); } return stringWriter.ToString(); } } } }
using System; using System.Collections.Generic; using System.Text; namespace AspxCommerce.USPS { public class USPSRateResponse { public USPSRateResponse() { _Postage = new List<Postage>(); } private bool _isDomestic; public bool IsDomestic { get { return _isDomestic; } set { _isDomestic = value; } } private string _originZip = ""; public string OriginZip { get { return _originZip; } set { _originZip = value; } } private string _destZip = ""; public string DestZip { get { return _destZip; } set { _destZip = value; } } private decimal _pounds = 0M; public decimal Pounds { get { return _pounds; } set { _pounds = value; } } private decimal _ounces = 0M; public decimal Ounces { get { return _ounces; } set { _ounces = value; } } private string _container = ""; public string Container { get { return _container; } set { _container = value; } } private string _size = ""; public string Size { get { return _size; } set { _size = value; } } private string _zone = ""; public string Zone { get { return _zone; } set { _zone = value; } } private string _errorMessage; public string ErrorMessage { get { return _errorMessage; } set { _errorMessage = value; } } private List<InterNationalRateList> _intRateList; public List<InterNationalRateList> IntRateList { get { return _intRateList; } set { _intRateList = value; } } private List<Postage> _Postage; public List<Postage> Postage { get { return _Postage; } set { _Postage = value; } } public static USPSRateResponse FromXml(string xml) { USPSRateResponse r = new USPSRateResponse(); int idx1 = 0; int idx2 = 0; if (xml.Contains("<ZipOrigination>")) { idx1 = xml.IndexOf("<ZipOrigination>") + 17; idx2 = xml.IndexOf("</ZipOrigination>"); r.OriginZip = xml.Substring(idx1, idx2 - idx1); } if (xml.Contains("<ZipDestination>")) { idx1 = xml.IndexOf("<ZipDestination>") + 16; idx2 = xml.IndexOf("</ZipDestination>"); r.OriginZip = xml.Substring(idx1, idx2 - idx1); } if (xml.Contains("<Pounds>")) { idx1 = xml.IndexOf("<Pounds>") + 8; idx2 = xml.IndexOf("</Pounds>"); r.OriginZip = xml.Substring(idx1, idx2 - idx1); } if (xml.Contains("<Ounces>")) { idx1 = xml.IndexOf("<Ounces>") + 8; idx2 = xml.IndexOf("</Ounces>"); r.OriginZip = xml.Substring(idx1, idx2 - idx1); } if (xml.Contains("<Container>")) { idx1 = xml.IndexOf("<Container>") + 11; idx2 = xml.IndexOf("</Container>"); r.OriginZip = xml.Substring(idx1, idx2 - idx1); } if (xml.Contains("<Size>")) { idx1 = xml.IndexOf("<Size>") + 6; idx2 = xml.IndexOf("</Size>"); r.OriginZip = xml.Substring(idx1, idx2 - idx1); } if (xml.Contains("<Zone>")) { idx1 = xml.IndexOf("<Zone>") + 6; idx2 = xml.IndexOf("</Zone>"); r.OriginZip = xml.Substring(idx1, idx2 - idx1); } int lastidx = 0; while (xml.IndexOf("<MailService>", lastidx) > -1) { Postage p = new Postage(); idx1 = xml.IndexOf("<MailService>", lastidx) + 13; idx2 = xml.IndexOf("</MailService>", lastidx + 13); p.ShippingMethodName = xml.Substring(idx1, idx2 - idx1); idx1 = xml.IndexOf("<Rate>", lastidx) + 6; idx2 = xml.IndexOf("</Rate>", lastidx + 13); p.TotalCharges = Decimal.Parse(xml.Substring(idx1, idx2 - idx1)); r.Postage.Add(p); lastidx = idx2; } return r; } private string _prohibitions; public string Prohibitions { get { return _prohibitions; } set { _prohibitions = value; } } private string _restrictions; public string Restrictions { get { return _restrictions; } set { _restrictions = value; } } private string _observations; public string Observations { get { return _observations; } set { _observations = value; } } private string _customsForms; public string CustomsForms { get { return _customsForms; } set { _customsForms = value; } } private string _expressMail; public string ExpressMail { get { return _expressMail; } set { _expressMail = value; } } private string _areasServed; public string AreasServed { get { return _areasServed; } set { _areasServed = value; } } private string _additionalRestrictions; public string AdditionalRestrictions { get { return _additionalRestrictions; } set { _additionalRestrictions = value; } } } public class Postage { private string _shippingMethodName; public string ShippingMethodName { get { return _shippingMethodName; } set { _shippingMethodName = value; } } private decimal _totalCharges; public decimal TotalCharges { get { return _totalCharges; } set { _totalCharges = value; } } }; public class InterNationalRateList { private decimal _pounds = 0M; public decimal Pounds { get { return _pounds; } set { _pounds = value; } } private string _container = ""; public string Container { get { return _container; } set { _container = value; } } private string _mailType; public string MailType { get { return _mailType; } set { _mailType = value; } } private string _size; public string Size { get { return _size; } set { _size = value; } } private string _width; public string Width { get { return _width; } set { _width = value; } } private string _height; public string Height { get { return _height; } set { _height = value; } } private string _length; public string Length { get { return _length; } set { _length = value; } } private string _girth; public string Girth { get { return _girth; } set { _girth = value; } } private string _country; public string Country { get { return _country; } set { _country = value; } } private decimal _totalCharges; public decimal TotalCharges { get { return _totalCharges; } set { _totalCharges = value; } } private string _deliveryTime; public string DeliveryTime { get { return _deliveryTime; } set { _deliveryTime = value; } } private string _shippingMethodName; public string ShippingMethodName { get { return _shippingMethodName; } set { _shippingMethodName = value; } } private string _maxDimensions; public string MaxDimensions { get { return _maxDimensions; } set { _maxDimensions = value; } } } }
// Copyright (C) 2004 Kevin Downs // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Diagnostics; using System.Text; using System.ComponentModel; using System.Windows.Forms.Design; using System.Drawing.Design; using System.IO; using NDoc.Core.PropertyGridUI; namespace NDoc.Core { /// <summary> /// A path to search for referenced assemblies. /// </summary> /// <remarks> /// if <see cref="IncludeSubDirectories"/> is set to <see langword="true"/>, subdirectories of /// <see cref="Path"/> will also be searched. /// </remarks> [Serializable] [DefaultProperty("Path")] [TypeConverter(typeof(ReferencePath.TypeConverter))] [Editor(typeof(ReferencePath.UIEditor), typeof(UITypeEditor))] [NDoc.Core.PropertyGridUI.FoldernameEditor.FolderDialogTitle("Select Reference Path")] public class ReferencePath : PathItemBase { #region Private Fields private bool _IncludeSubDirectories = false; #endregion #region Constructors /// <overloads> /// Initializes a new instance of the <see cref="ReferencePath"/> class. /// </overloads> /// <summary> /// Initializes a new instance of the <see cref="ReferencePath"/> class. /// </summary> public ReferencePath() {} /// <summary> /// Initializes a new instance of the <see cref="ReferencePath"/> class from a given path string. /// </summary> /// <param name="path">A relative or absolute path.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is a <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="path"/> is an empty string.</exception> /// <remarks> /// If <paramref name="path"/> end with "**" then <see cref="IncludeSubDirectories"/> /// will be set to <see langword="true"/>. /// </remarks> public ReferencePath(string path) { if (path == null) throw new ArgumentNullException("Path"); if (path.Length == 0) throw new ArgumentOutOfRangeException("path", "path must not be empty."); if (path.EndsWith("**")) { _IncludeSubDirectories = true; path = path.Substring(0, path.Length - 2); } Path = path; } /// <summary> /// Initializes a new instance of the <see cref="ReferencePath"/> class from an existing <see cref="ReferencePath"/> instance. /// </summary> /// <param name="refPath">An existing <see cref="ReferencePath"/> instance.</param> /// <exception cref="ArgumentNullException"><paramref name="refPath"/> is a <see langword="null"/>.</exception> public ReferencePath(ReferencePath refPath) { if (refPath == null) throw new ArgumentNullException("refPath"); base.Path = refPath.Path; base.FixedPath = refPath.FixedPath; this._IncludeSubDirectories = refPath._IncludeSubDirectories; } #endregion #region Properties /// <summary> /// Gets or sets the fully qualified path. /// </summary> /// <value>The fully qualified path</value> /// <exception cref="ArgumentNullException"><paramref name="path"/> is a <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="path"/> is an empty string.</exception> /// <remarks> /// <para> /// If <paramref name="path"/> is not rooted, <see cref="PathItemBase.FixedPath"/> is set to <see langword="false"/>, otherwise /// it left at its current setting. /// </para> /// <para> /// If this property is set to a string that ends with "**" then <see cref="IncludeSubDirectories"/> /// will be set to <see langword="true"/>. /// </para> /// </remarks> [ReadOnly(true)] [Description("A path to search for referenced assemblies.")] [MergableProperty(false)] [PropertyOrder(10)] [RefreshProperties(RefreshProperties.All)] public override string Path { get { return base.Path; } set { if (value == null) throw new ArgumentNullException("Path"); if (value == null) throw new ArgumentOutOfRangeException("Path", "path must not be empty."); if (value.EndsWith("**")) { _IncludeSubDirectories = true; value = value.Substring(0, value.Length - 2); } base.Path = value; } } /// <summary> /// Gets or sets an indication whether to search subdirectories of the given path. /// </summary> /// <value> /// if <see langword="true"/>, the assembly loader will search subdirectories; otherwise, it will only search given path. /// </value> [Description("If true, the assembly loader will search subdirectories; otherwise, it will only search given path.")] [PropertyOrder(100)] [DefaultValue(false)] [RefreshProperties(RefreshProperties.All)] public bool IncludeSubDirectories { get { return _IncludeSubDirectories; } set { _IncludeSubDirectories = value; } } #endregion #region Equality /// <inheritDoc/> public override bool Equals(object obj) { if (!base.Equals(obj)) return false; ReferencePath rp = (ReferencePath) obj; if (!this._IncludeSubDirectories.Equals(rp._IncludeSubDirectories)) return false; return true; } /// <summary>Equality operator.</summary> public static bool operator == (ReferencePath x, ReferencePath y) { if ((object)x == null) return false; return x.Equals(y); } /// <summary>Inequality operator.</summary> public static bool operator != (ReferencePath x, ReferencePath y) { return!(x == y); } /// <inheritDoc/> public override int GetHashCode() { return ToString().GetHashCode(); } #endregion /// <inheritDoc/> public override string ToString() { string displayPath = AppendSubDirInd(base.ToString(), _IncludeSubDirectories); return displayPath; } #region Helpers private string AppendSubDirInd(string path, bool includeSubDirectories) { string displayPath = path; if (includeSubDirectories) { if (path.EndsWith(new String(System.IO.Path.DirectorySeparatorChar, 1)) || path.EndsWith(new String(System.IO.Path.AltDirectorySeparatorChar, 1)) || path.EndsWith(new String(System.IO.Path.VolumeSeparatorChar, 1)) ) displayPath = displayPath + "**"; else displayPath = displayPath + System.IO.Path.DirectorySeparatorChar + "**"; } return displayPath; } #endregion /// <summary> /// <see cref="TypeConverter"/> to convert a string to an instance of <see cref="ReferencePath"/>. /// </summary> new internal class TypeConverter : PropertySorter { /// <inheritDoc/> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) { return true; } return base.CanConvertFrom(context, sourceType); } /// <inheritDoc/> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { Debug.WriteLine("RefPath:TypeConv.ConvertFrom value=>" + value.ToString()); if (value is string) { ReferencePath rp = new ReferencePath((string)value); Debug.WriteLine(" rp=>" + rp.ToString()); return rp; } return base.ConvertFrom(context, culture, value); } } /// <summary> /// /// </summary> internal class UIEditor : FoldernameEditor { /// <summary> /// Creates a new <see cref="UIEditor">ReferencePath.UIEditor</see> instance. /// </summary> public UIEditor() : base() {} /// <inheritDoc/> public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value) { if (value is ReferencePath) { object result = base.EditValue(context, provider, ((ReferencePath)value).Path); if ((string)result == ((ReferencePath)value).Path) { return value; } else { if (((string)result).Length > 0) { ReferencePath newValue = new ReferencePath((ReferencePath)value); newValue.Path = (string)result; return newValue; } else { return new ReferencePath(); } } } else { return base.EditValue(context, provider, value); } } } } }
using System.Collections.Generic; using HipchatApiV2.Enums; using HipchatApiV2.Requests; using HipchatApiV2.Responses; namespace HipchatApiV2 { public interface IHipchatClient { /// <summary> /// Get room details /// </summary> /// <param name="roomId">The id of the room</param> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_room /// </remarks> HipchatGetRoomResponse GetRoom(int roomId); /// <summary> /// Get room details /// </summary> /// <param name="roomName">The name of the room. Valid length 1-100</param> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_room /// </remarks> HipchatGetRoomResponse GetRoom(string roomName); /// <summary> /// Gets an OAuth token for requested grant type. /// </summary> /// <param name="grantType">The type of grant request</param> /// <param name="scopes">List of scopes that is requested</param> /// <param name="username">The user name to generate a token on behalf of. Only valid in /// the 'Password' and 'ClientCredentials' grant types.</param> /// <param name="code">The authorization code to exchange for an access token. Only valid in the 'AuthorizationCode' grant type</param> /// <param name="redirectUri">The Url that was used to generate an authorization code, and it must match that value. Only valid in the 'AuthorizationCode' grant.</param> /// <param name="password">The user's password to use for authentication when creating a token. Only valid in the 'Password' grant.</param> /// <param name="refreshToken">The refresh token to use to generate a new access token. Only valid in the 'RefreshToken' grant.</param> HipchatGenerateTokenResponse GenerateToken( GrantType grantType, IEnumerable<TokenScope> scopes, string username = null, string code = null, string redirectUri = null, string password = null, string refreshToken = null); /// <summary> /// Sends a user a private message. /// </summary> /// <param name="idOrEmailOrMention">The id, email address, or mention name (beginning with an '@') of the user to send a message to.</param> /// <param name="message">The message body. Valid length range: 1 - 10000.</param> /// <param name="notify">Whether this message should trigger a user notification (change the tab color, play a sound, notify mobile phones, etc). Each recipient's notification preferences are taken into account.</param> /// <param name="messageFormat">Determines how the message is treated by our server and rendered inside HipChat applications</param> /// <remarks> /// Auth required with scope 'send_message'. https://www.hipchat.com/docs/apiv2/method/private_message_user /// </remarks> void PrivateMessageUser(string idOrEmailOrMention, string message, bool notify = false, HipchatMessageFormat messageFormat = HipchatMessageFormat.Text); /// <summary> /// Get emoticon details /// </summary> /// <param name="id">The emoticon id</param> /// <returns>the emoticon details</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_emoticon /// </remarks> HipchatGetEmoticonResponse GetEmoticon(int id = 0); /// <summary> /// Get emoticon details /// </summary> /// <param name="shortcut">The emoticon shortcut</param> /// <returns>the emoticon details</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_emoticon /// </remarks> HipchatGetEmoticonResponse GetEmoticon(string shortcut = ""); /// <summary> /// Gets all emoticons for the current group /// </summary> /// <param name="startIndex">The start index for the result set</param> /// <param name="maxResults">The maximum number of results</param> /// <param name="type">The type of emoticons to get</param> /// <returns>the matching set of emoticons</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_all_emoticons /// </remarks> HipchatGetAllEmoticonsResponse GetAllEmoticons(int startIndex = 0, int maxResults = 100, EmoticonType type = EmoticonType.All); HipchatGetAllUsersResponse GetAllUsers(int startIndex = 0, int maxResults = 100, bool includeGuests = false, bool includeDeleted = false); /// <summary> /// Gets information about the requested user /// </summary> /// <param name="emailOrMentionName">The users email address or mention name beginning with @</param> /// <returns>an object with information about the user</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/view_user /// </remarks> HipchatGetUserInfoResponse GetUserInfo(string emailOrMentionName); /// <summary> /// Gets information about the requested user /// </summary> /// <param name="userId">The integer Id of the user</param> /// <returns>an object with information about the user</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/view_user /// </remarks> HipchatGetUserInfoResponse GetUserInfo(int userId); /// <summary> /// Updates a room /// </summary> /// <param name="roomId">The room id</param> /// <param name="request">The request to send</param> /// <returns>true if the call was successful</returns> /// <remarks> /// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/update_room /// </remarks> bool UpdateRoom(int roomId, UpdateRoomRequest request); /// <summary> /// Updates a room /// </summary> /// <param name="roomName">The room name</param> /// <param name="request">The request to send</param> /// <returns>true if the call was successful</returns> /// <remarks> /// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/update_room /// </remarks> bool UpdateRoom(string roomName, UpdateRoomRequest request); /// <summary> /// Creates a webhook /// </summary> /// <param name="roomId">the id of the room</param> /// <param name="url">the url to send the webhook POST to</param> /// <param name="pattern">optional regex pattern to match against messages. Only applicable for message events</param> /// <param name="eventType">The event to listen for</param> /// <param name="name">label for this webhook</param> /// <remarks> /// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/create_webhook /// </remarks> CreateWebHookResponse CreateWebHook(int roomId, string url, string pattern, RoomEvent eventType, string name); /// <summary> /// Creates a webhook /// </summary> /// <param name="roomName">the name of the room</param> /// <param name="url">the url to send the webhook POST to</param> /// <param name="pattern">optional regex pattern to match against messages. Only applicable for message events</param> /// <param name="eventType">The event to listen for</param> /// <param name="name">label for this webhook</param> /// <remarks> /// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/create_webhook /// </remarks> CreateWebHookResponse CreateWebHook(string roomName, string url, string pattern, RoomEvent eventType, string name); /// <summary> /// Creates a webhook /// </summary> /// <param name="roomName">the name of the room</param> /// <param name="request">the request to send</param> /// <remarks> /// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/create_webhook /// </remarks> CreateWebHookResponse CreateWebHook(string roomName, CreateWebHookRequest request); /// <summary> /// Creates a new room /// </summary> /// <param name="nameOfRoom">Name of the room. Valid Length 1-50</param> /// <param name="guestAccess">Whether or not to enable guest access for this room</param> /// <param name="ownerUserId">The id, email address, or mention name (beginning with an '@') of /// the room's owner. Defaults to the current user.</param> /// <param name="privacy">Whether the room is available for access by other users or not</param> /// <returns>response containing id and link of the created room</returns> /// <remarks> /// Auth required with scope 'manage_rooms'. https://api.hipchat.com/v2/room /// </remarks> HipchatCreateRoomResponse CreateRoom(string nameOfRoom, bool guestAccess = false, string ownerUserId = null, RoomPrivacy privacy = RoomPrivacy.Public); /// <summary> /// Creates a new room /// </summary> /// <returns>response containing id and link of the created room</returns> /// <remarks> /// Auth required with scope 'manage_rooms'. https://api.hipchat.com/v2/room /// </remarks> HipchatCreateRoomResponse CreateRoom(CreateRoomRequest request); /// <summary> /// Send a message to a room /// </summary> /// <param name="roomId">The id of the room</param> /// <param name="message">message to send</param> /// <param name="backgroundColor">the background color of the message, only applicable to html format message</param> /// <param name="notify">if the message should notify</param> /// <param name="messageFormat">the format of the message</param> /// <returns>true if the message was sucessfully sent</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/send_room_notification /// </remarks> bool SendNotification(int roomId, string message, RoomColors backgroundColor = RoomColors.Yellow, bool notify = false, HipchatMessageFormat messageFormat = HipchatMessageFormat.Html); /// <summary> /// Send a message to a room /// </summary> /// <param name="roomName">The name of the room</param> /// <param name="message">message to send</param> /// <param name="backgroundColor">the background color of the message, only applicable to html format message</param> /// <param name="notify">if the message should notify</param> /// <param name="messageFormat">the format of the message</param> /// <returns>true if the message was sucessfully sent</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/send_room_notification /// </remarks> bool SendNotification(string roomName, string message, RoomColors backgroundColor = RoomColors.Yellow, bool notify = false, HipchatMessageFormat messageFormat = HipchatMessageFormat.Html); /// <summary> /// Send a message to a room /// </summary> /// <param name="roomId">The id of the room</param> /// <param name="request">The request containing the info about the notification to send</param> /// <returns>true if the message successfully sent</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/send_room_notification /// </remarks> bool SendNotification(int roomId, SendRoomNotificationRequest request); /// <summary> /// Send a message to a room /// </summary> /// <param name="roomName">The id of the room</param> /// <param name="request">The request containing the info about the notification to send</param> /// <returns>true if the message successfully sent</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/send_room_notification /// </remarks> bool SendNotification(string roomName, SendRoomNotificationRequest request); /// <summary> /// Share a file with a room /// </summary> /// <param name="roomName">The id or name of the room</param> /// <param name="fileFullPath">The full path of the file.</param> /// <param name="message">The optional message.</param> /// <returns> /// true if the file was successfully shared /// </returns> /// <remarks> /// Auth required with scope 'send_message'. https://www.hipchat.com/docs/apiv2/method/share_file_with_room /// </remarks> bool ShareFileWithRoom(string roomName, string fileFullPath, string message = null); /// <summary> /// Delets a room and kicks the current particpants. /// </summary> /// <param name="roomId">Id of the room.</param> /// <returns>true if the room was successfully deleted</returns> /// <remarks> /// Authentication required with scope 'manage_rooms'. https://www.hipchat.com/docs/apiv2/method/delete_room /// </remarks> bool DeleteRoom(int roomId); /// <summary> /// Delets a room and kicks the current particpants. /// </summary> /// <param name="roomName">Name of the room.</param> /// <returns>true if the room was successfully deleted</returns> /// <remarks> /// Authentication required with scope 'manage_rooms'. https://www.hipchat.com/docs/apiv2/method/delete_room /// </remarks> bool DeleteRoom(string roomName); /// <summary> /// List non-archived rooms for this group /// </summary> /// <param name="startIndex">The start index for the result set</param> /// <param name="maxResults">The maximum number of results. Valid length 0-100</param> /// <param name="includeArchived">Filter rooms</param> /// <returns>A HipchatGetAllRoomsResponse</returns> /// <remarks> /// Auth required with scope 'view_group'. https://www.hipchat.com/docs/apiv2/method/get_all_rooms /// </remarks> HipchatGetAllRoomsResponse GetAllRooms(int startIndex = 0, int maxResults = 100, bool includePrivate = false, bool includeArchived = false); /// <summary> /// Fetch chat history for this room /// </summary> /// <param name="roomName">Name of the room.</param> /// <param name="date">Either the latest date to fetch history for in ISO-8601 format, or 'recent' to fetch the latest 75 messages. Note, paging isn't supported for 'recent', however they are real-time values, whereas date queries may not include the most recent messages.</param> /// <param name="timezone">Your timezone. Must be a supported timezone name, please see wikipedia TZ database page.</param> /// <param name="startIndex">The start index for the result set</param> /// <param name="maxResults">The maximum number of results. Valid length 0-100</param> /// <param name="reverse">Reverse the output such that the oldest message is first. For consistent paging, set to <c>false</c>.</param> /// <returns> /// A HipchatGetAllRoomsResponse /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// roomName;Valid roomName length is 1-100. /// or /// date;Valid date should be passed. /// or /// timezone;Valid timezone should be passed. /// or /// startIndex;startIndex must be between 0 and 100 /// or /// maxResults;maxResults must be between 0 and 1000 /// </exception> /// <remarks> /// Authentication required, with scope view_group, view_messages. https://www.hipchat.com/docs/apiv2/method/view_room_history /// </remarks> HipchatViewRoomHistoryResponse ViewRoomHistory(string roomName, string date = "recent", string timezone = "UTC", int startIndex = 0, int maxResults = 100, bool reverse = true); /// <summary> /// Fetch latest chat history for this room /// </summary> /// <param name="roomName">Name of the room.</param> /// <param name="notBefore">The id of the message that is oldest in the set of messages to be returned. The server will not return any messages that chronologically precede this message.</param> /// <param name="timezone">Your timezone. Must be a supported timezone name, please see wikipedia TZ database page.</param> /// <param name="startIndex">The start index for the result set</param> /// <param name="maxResults">The maximum number of results. Valid length 0-100</param> /// <returns> /// A HipchatGetAllRoomsResponse /// </returns> /// <exception cref="System.ArgumentOutOfRangeException"> /// roomName;Valid roomName length is 1-100. /// or /// timezone;Valid timezone should be passed. /// or /// startIndex;startIndex must be between 0 and 100 /// or /// maxResults;maxResults must be between 0 and 1000 /// </exception> /// <remarks> /// Authentication required, with scope view_messages. https://www.hipchat.com/docs/apiv2/method/view_recent_room_history /// </remarks> HipchatViewRoomHistoryResponse ViewRecentRoomHistory(string roomName, string notBefore = "", string timezone = "UTC", int startIndex = 0, int maxResults = 100); /// <summary> /// Gets all webhooks for this room /// </summary> /// <param name="roomName">The name of the room</param> /// <param name="startIndex">The start index for the result set</param> /// <param name="maxResults">The maximum number of results</param> /// <returns>A GetAllWebhooks Response</returns> /// <remarks> /// Auth required, with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/get_all_webhooks /// </remarks> HipchatGetAllWebhooksResponse GetAllWebhooks(string roomName, int startIndex = 0, int maxResults = 0); /// <summary> /// Gets all webhooks for this room /// </summary> /// <param name="roomId">The id of the room</param> /// <param name="startIndex">The start index for the result set</param> /// <param name="maxResults">The maximum number of results</param> /// <returns>A GetAllWebhooks Response</returns> /// <remarks> /// Auth required, with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/get_all_webhooks /// </remarks> HipchatGetAllWebhooksResponse GetAllWebhooks(int roomId, int startIndex = 0, int maxResults = 0); /// <summary> /// Deletes a webhook /// </summary> /// <param name="roomName">The name of the room</param> /// <param name="webHookId">The id of the webhook</param> /// <returns>true if the request was successful</returns> /// <remarks> /// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/delete_webhook /// </remarks> bool DeleteWebhook(string roomName, int webHookId); /// <summary> /// Deletes a webhook /// </summary> /// <param name="roomId">The id of the room</param> /// <param name="webHookId">The id of the webhook</param> /// <returns>true if the request was successful</returns> /// <remarks> /// Auth required with scope 'admin_room'. https://www.hipchat.com/docs/apiv2/method/delete_webhook /// </remarks> bool DeleteWebhook(int roomId, int webHookId); /// <summary> /// Set a room's topic. Useful for displaying statistics, important links, server status, you name it! /// </summary> /// <param name="roomName">The name of the room</param> /// <param name="topic">The topic body. (Valid length 0 - 250)</param> /// <returns>true if the call succeeded. There may be slight delay before topic change appears in the room </returns> /// <remarks> /// Auth required with scope 'admin_room'. /// https://www.hipchat.com/docs/apiv2/method/set_topic /// </remarks> bool SetTopic(string roomName, string topic); /// <summary> /// Set a room's topic. Useful for displaying statistics, important links, server status, you name it! /// </summary> /// <param name="roomId">The id of the room</param> /// <param name="topic">The topic body. (Valid length 0 - 250)</param> /// <returns>true if the call succeeded. There may be slight delay before topic change appears in the room </returns> /// <remarks> /// Auth required with scope 'admin_room'. /// https://www.hipchat.com/docs/apiv2/method/set_topic /// </remarks> bool SetTopic(int roomId, string topic); /// <summary> /// Create a new user /// </summary> /// <returns>A HipchatCreateUserReponse</returns> /// <remarks> /// Auth required with scope 'admin_group'. https://www.hipchat.com/docs/apiv2/method/create_user /// </remarks> HipchatCreateUserResponse CreateUser(CreateUserRequest request); /// <summary> /// Delete a user /// </summary> /// <param name="idOrEmail">The id, email address, or mention name (beginning with an '@') of the user to delete.</param> /// <returns>A HipchatDeleteUserReponse</returns> /// <remarks> /// Auth required with scope 'admin_group'. https://api.hipchat.com/v2/user/{id_or_email} /// </remarks> bool DeleteUser(string idOrEmail); /// <summary> /// Add a member to a private room /// </summary> /// <param name="roomName">The name of the room</param> /// <param name="idOrEmail">The id, email address, or mention name (beginning with an '@') of the user to delete.</param> /// <returns>true if the call succeeded. </returns> /// <remarks> /// Auth required with scope 'admin_room'. /// https://www.hipchat.com/docs/apiv2/method/add_member /// </remarks> bool AddMember(string roomName, string idOrEmail); /// <summary> /// Update a user photo /// </summary> /// <param name="idOrEmail">The id, email address, or mention name (beginning with an '@') of the user to delete.</param> /// <param name="photo"> Base64 string of the photo</param> /// <returns>true if the call succeeded. </returns> /// <remarks> /// Auth required with scope 'admin_room'. /// https://www.hipchat.com/docs/apiv2/method/update_photo /// </remarks> bool UpdatePhoto(string idOrEmail, string photo); } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Diagnostics; using dnlib.DotNet.MD; namespace dnlib.DotNet.Writer { /// <summary> /// Preserves metadata tokens /// </summary> sealed class PreserveTokensMetaData : MetaData { readonly ModuleDefMD mod; readonly Rows<TypeRef> typeRefInfos = new Rows<TypeRef>(); readonly Dictionary<TypeDef, uint> typeToRid = new Dictionary<TypeDef, uint>(); MemberDefDict<FieldDef> fieldDefInfos; MemberDefDict<MethodDef> methodDefInfos; MemberDefDict<ParamDef> paramDefInfos; readonly Rows<MemberRef> memberRefInfos = new Rows<MemberRef>(); readonly Rows<StandAloneSig> standAloneSigInfos = new Rows<StandAloneSig>(); MemberDefDict<EventDef> eventDefInfos; MemberDefDict<PropertyDef> propertyDefInfos; readonly Rows<TypeSpec> typeSpecInfos = new Rows<TypeSpec>(); readonly Rows<MethodSpec> methodSpecInfos = new Rows<MethodSpec>(); readonly Dictionary<uint, uint> callConvTokenToSignature = new Dictionary<uint, uint>(); [DebuggerDisplay("{Rid} -> {NewRid} {Def}")] sealed class MemberDefInfo<T> where T : IMDTokenProvider { public readonly T Def; /// <summary> /// Its real rid /// </summary> public uint Rid; /// <summary> /// Its logical rid or real rid. If the ptr table exists (eg. MethodPtr), then it's /// an index into it, else it's the real rid. /// </summary> public uint NewRid; public MemberDefInfo(T def, uint rid) { this.Def = def; this.Rid = rid; this.NewRid = rid; } } [DebuggerDisplay("Count = {Count}")] sealed class MemberDefDict<T> where T : IMDTokenProvider { readonly Type defMDType; uint userRid = 0x01000000; uint newRid = 1; int numDefMDs; int numDefUsers; int tableSize; bool wasSorted; readonly bool preserveRids; readonly bool enableRidToInfo; readonly Dictionary<T, MemberDefInfo<T>> defToInfo = new Dictionary<T, MemberDefInfo<T>>(); Dictionary<uint, MemberDefInfo<T>> ridToInfo; readonly List<MemberDefInfo<T>> defs = new List<MemberDefInfo<T>>(); List<MemberDefInfo<T>> sortedDefs; readonly Dictionary<T, int> collectionPositions = new Dictionary<T, int>(); /// <summary> /// Gets total number of defs in the list. It does <c>not</c> necessarily return /// the table size. Use <see cref="TableSize"/> for that. /// </summary> public int Count { get { return defs.Count; } } /// <summary> /// Gets the number of rows that need to be created in the table /// </summary> public int TableSize { get { return tableSize; } } /// <summary> /// Returns <c>true</c> if the ptr table (eg. <c>MethodPtr</c>) is needed /// </summary> public bool NeedPtrTable { get { return preserveRids && !wasSorted; } } public MemberDefDict(Type defMDType, bool preserveRids) : this(defMDType, preserveRids, false) { } public MemberDefDict(Type defMDType, bool preserveRids, bool enableRidToInfo) { this.defMDType = defMDType; this.preserveRids = preserveRids; this.enableRidToInfo = enableRidToInfo; } public uint Rid(T def) { return defToInfo[def].Rid; } public bool TryGetRid(T def, out uint rid) { MemberDefInfo<T> info; if (def == null || !defToInfo.TryGetValue(def, out info)) { rid = 0; return false; } rid = info.Rid; return true; } /// <summary> /// Sorts the table /// </summary> /// <param name="comparer">Comparer</param> public void Sort(Comparison<MemberDefInfo<T>> comparer) { if (!preserveRids) { // It's already sorted sortedDefs = defs; return; } sortedDefs = new List<MemberDefInfo<T>>(defs); sortedDefs.Sort(comparer); wasSorted = true; for (int i = 0; i < sortedDefs.Count; i++) { var def = sortedDefs[i]; uint newRid = (uint)i + 1; def.NewRid = newRid; if (def.Rid != newRid) wasSorted = false; } } public MemberDefInfo<T> Get(int i) { return defs[i]; } public MemberDefInfo<T> GetSorted(int i) { return sortedDefs[i]; } public MemberDefInfo<T> GetByRid(uint rid) { MemberDefInfo<T> info; ridToInfo.TryGetValue(rid, out info); return info; } /// <summary> /// Adds a def. <see cref="SortDefs()"/> must be called after adding the last def. /// </summary> /// <param name="def">The def</param> /// <param name="collPos">Collection position</param> public void Add(T def, int collPos) { uint rid; if (def.GetType() == defMDType) { numDefMDs++; rid = preserveRids ? def.Rid : newRid++; } else { numDefUsers++; rid = preserveRids ? userRid++ : newRid++; } var info = new MemberDefInfo<T>(def, rid); defToInfo[def] = info; defs.Add(info); collectionPositions.Add(def, collPos); } /// <summary> /// Must be called after <see cref="Add"/>'ing the last def /// </summary> public void SortDefs() { // It's already sorted if we don't preserve rids if (preserveRids) { // Sort all def MDs before user defs defs.Sort((a, b) => a.Rid.CompareTo(b.Rid)); // Fix user created defs' rids uint newRid = numDefMDs == 0 ? 1 : defs[numDefMDs - 1].Rid + 1; for (int i = numDefMDs; i < defs.Count; i++) defs[i].Rid = newRid++; // Now we know total table size tableSize = (int)newRid - 1; } else tableSize = defs.Count; if (enableRidToInfo) { ridToInfo = new Dictionary<uint, MemberDefInfo<T>>(defs.Count); foreach (var info in defs) ridToInfo.Add(info.Rid, info); } if ((uint)tableSize > 0x00FFFFFF) throw new ModuleWriterException("Table is too big"); } public int GetCollectionPosition(T def) { return collectionPositions[def]; } } protected override int NumberOfMethods { get { return methodDefInfos.Count; } } /// <summary> /// Constructor /// </summary> /// <param name="module">Module</param> /// <param name="constants">Constants list</param> /// <param name="methodBodies">Method bodies list</param> /// <param name="netResources">.NET resources list</param> /// <param name="options">Options</param> public PreserveTokensMetaData(ModuleDef module, UniqueChunkList<ByteArrayChunk> constants, MethodBodyChunks methodBodies, NetResources netResources, MetaDataOptions options) : base(module, constants, methodBodies, netResources, options) { mod = module as ModuleDefMD; if (mod == null) throw new ModuleWriterException("Not a ModuleDefMD"); } /// <inheritdoc/> public override uint GetRid(TypeRef tr) { uint rid; typeRefInfos.TryGetRid(tr, out rid); return rid; } /// <inheritdoc/> public override uint GetRid(TypeDef td) { if (td == null) { Error("TypeDef is null"); return 0; } uint rid; if (typeToRid.TryGetValue(td, out rid)) return rid; Error("TypeDef {0} ({1:X8}) is not defined in this module ({2}). A type was removed that is still referenced by this module.", td, td.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(FieldDef fd) { uint rid; if (fieldDefInfos.TryGetRid(fd, out rid)) return rid; if (fd == null) Error("Field is null"); else Error("Field {0} ({1:X8}) is not defined in this module ({2}). A field was removed that is still referenced by this module.", fd, fd.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(MethodDef md) { uint rid; if (methodDefInfos.TryGetRid(md, out rid)) return rid; if (md == null) Error("Method is null"); else Error("Method {0} ({1:X8}) is not defined in this module ({2}). A method was removed that is still referenced by this module.", md, md.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(ParamDef pd) { uint rid; if (paramDefInfos.TryGetRid(pd, out rid)) return rid; if (pd == null) Error("Param is null"); else Error("Param {0} ({1:X8}) is not defined in this module ({2}). A parameter was removed that is still referenced by this module.", pd, pd.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(MemberRef mr) { uint rid; memberRefInfos.TryGetRid(mr, out rid); return rid; } /// <inheritdoc/> public override uint GetRid(StandAloneSig sas) { uint rid; standAloneSigInfos.TryGetRid(sas, out rid); return rid; } /// <inheritdoc/> public override uint GetRid(EventDef ed) { uint rid; if (eventDefInfos.TryGetRid(ed, out rid)) return rid; if (ed == null) Error("Event is null"); else Error("Event {0} ({1:X8}) is not defined in this module ({2}). An event was removed that is still referenced by this module.", ed, ed.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(PropertyDef pd) { uint rid; if (propertyDefInfos.TryGetRid(pd, out rid)) return rid; if (pd == null) Error("Property is null"); else Error("Property {0} ({1:X8}) is not defined in this module ({2}). A property was removed that is still referenced by this module.", pd, pd.MDToken.Raw, module); return 0; } /// <inheritdoc/> public override uint GetRid(TypeSpec ts) { uint rid; typeSpecInfos.TryGetRid(ts, out rid); return rid; } /// <inheritdoc/> public override uint GetRid(MethodSpec ms) { uint rid; methodSpecInfos.TryGetRid(ms, out rid); return rid; } /// <inheritdoc/> protected override void Initialize() { fieldDefInfos = new MemberDefDict<FieldDef>(typeof(FieldDefMD), PreserveFieldRids); methodDefInfos = new MemberDefDict<MethodDef>(typeof(MethodDefMD), PreserveMethodRids, true); paramDefInfos = new MemberDefDict<ParamDef>(typeof(ParamDefMD), PreserveParamRids); eventDefInfos = new MemberDefDict<EventDef>(typeof(EventDefMD), PreserveEventRids); propertyDefInfos = new MemberDefDict<PropertyDef>(typeof(PropertyDefMD), PreservePropertyRids); CreateEmptyTableRows(); } /// <inheritdoc/> protected override List<TypeDef> GetAllTypeDefs() { if (!PreserveTypeDefRids) { var types2 = new List<TypeDef>(module.GetTypes()); InitializeTypeToRid(types2); return types2; } var typeToIndex = new Dictionary<TypeDef, uint>(); var types = new List<TypeDef>(); uint index = 0; const uint IS_TYPEDEFMD = 0x80000000; const uint INDEX_BITS = 0x00FFFFFF; foreach (var type in module.GetTypes()) { if (type == null) continue; types.Add(type); uint val = (uint)index++; if (type.GetType() == typeof(TypeDefMD)) val |= IS_TYPEDEFMD; typeToIndex[type] = val; } var globalType = types[0]; types.Sort((a, b) => { if (a == b) return 0; // Make sure the global <Module> type is always sorted first, even if it's // a TypeDefUser if (a == globalType) return -1; if (b == globalType) return 1; // Sort all TypeDefMDs before all TypeDefUsers uint ai = typeToIndex[a]; uint bi = typeToIndex[b]; bool amd = (ai & IS_TYPEDEFMD) != 0; bool bmd = (bi & IS_TYPEDEFMD) != 0; if (amd == bmd) { // Both are TypeDefMDs or both are TypeDefUsers // If TypeDefMDs, only compare rids since rids are preserved if (amd) return a.Rid.CompareTo(b.Rid); // If TypeDefUsers, rids aren't preserved so compare by index return (ai & INDEX_BITS).CompareTo(bi & INDEX_BITS); } if (amd) return -1; return 1; }); // Some of the original types may have been removed. Create dummy types // so TypeDef rids can be preserved. var newTypes = new List<TypeDef>(types.Count); uint prevRid = 1; newTypes.Add(globalType); for (int i = 1; i < types.Count; i++) { var type = types[i]; // TypeDefUsers were sorted last so when we reach one, we can stop if (type.GetType() != typeof(TypeDefMD)) { while (i < types.Count) newTypes.Add(types[i++]); break; } uint currRid = type.Rid; int extraTypes = (int)(currRid - prevRid - 1); if (extraTypes != 0) { // always >= 0 since currRid > prevRid // At least one type has been removed. Create dummy types. for (int j = 0; j < extraTypes; j++) newTypes.Add(new TypeDefUser("dummy", Guid.NewGuid().ToString("B"), module.CorLibTypes.Object.TypeDefOrRef)); } newTypes.Add(type); prevRid = currRid; } InitializeTypeToRid(newTypes); return newTypes; } void InitializeTypeToRid(IEnumerable<TypeDef> types) { uint rid = 1; foreach (var type in types) { if (type == null) continue; if (typeToRid.ContainsKey(type)) continue; typeToRid[type] = rid++; } } /// <inheritdoc/> protected override void AllocateTypeDefRids() { foreach (var type in allTypeDefs) { uint rid = tablesHeap.TypeDefTable.Create(new RawTypeDefRow()); if (typeToRid[type] != rid) throw new ModuleWriterException("Got a different rid than expected"); } } /// <summary> /// Reserves rows in <c>TypeRef</c>, <c>MemberRef</c>, <c>StandAloneSig</c>, /// <c>TypeSpec</c> and <c>MethodSpec</c> where we will store the original rows /// to make sure they get the same rid. Any user created rows will be stored at /// the end of each table. /// </summary> void CreateEmptyTableRows() { uint rows; if (PreserveTypeRefRids) { rows = mod.TablesStream.TypeRefTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.TypeRefTable.Create(new RawTypeRefRow()); } if (PreserveMemberRefRids) { rows = mod.TablesStream.MemberRefTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.MemberRefTable.Create(new RawMemberRefRow()); } if (PreserveStandAloneSigRids) { rows = mod.TablesStream.StandAloneSigTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.StandAloneSigTable.Create(new RawStandAloneSigRow()); } if (PreserveTypeSpecRids) { rows = mod.TablesStream.TypeSpecTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.TypeSpecTable.Create(new RawTypeSpecRow()); } if (PreserveMethodSpecRids) { rows = mod.TablesStream.MethodSpecTable.Rows; for (uint i = 0; i < rows; i++) tablesHeap.MethodSpecTable.Create(new RawMethodSpecRow()); } } /// <summary> /// Adds any non-referenced rows that haven't been added yet but are present in /// the original file. If there are any non-referenced rows, it's usually a sign /// that an obfuscator has encrypted one or more methods or that it has added /// some rows it uses to decrypt something. /// </summary> void InitializeUninitializedTableRows() { InitializeTypeRefTableRows(); InitializeMemberRefTableRows(); InitializeStandAloneSigTableRows(); InitializeTypeSpecTableRows(); InitializeMethodSpecTableRows(); } bool initdTypeRef = false; void InitializeTypeRefTableRows() { if (!PreserveTypeRefRids || initdTypeRef) return; initdTypeRef = true; uint rows = mod.TablesStream.TypeRefTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddTypeRef(mod.ResolveTypeRef(rid)); tablesHeap.TypeRefTable.ReAddRows(); } bool initdMemberRef = false; void InitializeMemberRefTableRows() { if (!PreserveMemberRefRids || initdMemberRef) return; initdMemberRef = true; uint rows = mod.TablesStream.MemberRefTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddMemberRef(mod.ResolveMemberRef(rid), true); tablesHeap.MemberRefTable.ReAddRows(); } bool initdStandAloneSig = false; void InitializeStandAloneSigTableRows() { if (!PreserveStandAloneSigRids || initdStandAloneSig) return; initdStandAloneSig = true; uint rows = mod.TablesStream.StandAloneSigTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddStandAloneSig(mod.ResolveStandAloneSig(rid), true); tablesHeap.StandAloneSigTable.ReAddRows(); } bool initdTypeSpec = false; void InitializeTypeSpecTableRows() { if (!PreserveTypeSpecRids || initdTypeSpec) return; initdTypeSpec = true; uint rows = mod.TablesStream.TypeSpecTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddTypeSpec(mod.ResolveTypeSpec(rid), true); tablesHeap.TypeSpecTable.ReAddRows(); } bool initdMethodSpec = false; void InitializeMethodSpecTableRows() { if (!PreserveMethodSpecRids || initdMethodSpec) return; initdMethodSpec = true; uint rows = mod.TablesStream.MethodSpecTable.Rows; for (uint rid = 1; rid <= rows; rid++) AddMethodSpec(mod.ResolveMethodSpec(rid), true); tablesHeap.MethodSpecTable.ReAddRows(); } /// <inheritdoc/> protected override void AllocateMemberDefRids() { FindMemberDefs(); Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids0); for (int i = 1; i <= fieldDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.FieldTable.Create(new RawFieldRow())) throw new ModuleWriterException("Invalid field rid"); } for (int i = 1; i <= methodDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.MethodTable.Create(new RawMethodRow())) throw new ModuleWriterException("Invalid method rid"); } for (int i = 1; i <= paramDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.ParamTable.Create(new RawParamRow())) throw new ModuleWriterException("Invalid param rid"); } for (int i = 1; i <= eventDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.EventTable.Create(new RawEventRow())) throw new ModuleWriterException("Invalid event rid"); } for (int i = 1; i <= propertyDefInfos.TableSize; i++) { if ((uint)i != tablesHeap.PropertyTable.Create(new RawPropertyRow())) throw new ModuleWriterException("Invalid property rid"); } SortFields(); SortMethods(); SortParameters(); SortEvents(); SortProperties(); Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids1); if (fieldDefInfos.NeedPtrTable) { for (int i = 0; i < fieldDefInfos.Count; i++) { var info = fieldDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.FieldPtrTable.Add(new RawFieldPtrRow(info.Rid))) throw new ModuleWriterException("Invalid field ptr rid"); } ReUseDeletedFieldRows(); } if (methodDefInfos.NeedPtrTable) { for (int i = 0; i < methodDefInfos.Count; i++) { var info = methodDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.MethodPtrTable.Add(new RawMethodPtrRow(info.Rid))) throw new ModuleWriterException("Invalid method ptr rid"); } ReUseDeletedMethodRows(); } if (paramDefInfos.NeedPtrTable) { // NOTE: peverify does not support the ParamPtr table. It's a bug. for (int i = 0; i < paramDefInfos.Count; i++) { var info = paramDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.ParamPtrTable.Add(new RawParamPtrRow(info.Rid))) throw new ModuleWriterException("Invalid param ptr rid"); } ReUseDeletedParamRows(); } if (eventDefInfos.NeedPtrTable) { for (int i = 0; i < eventDefInfos.Count; i++) { var info = eventDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.EventPtrTable.Add(new RawEventPtrRow(info.Rid))) throw new ModuleWriterException("Invalid event ptr rid"); } } if (propertyDefInfos.NeedPtrTable) { for (int i = 0; i < propertyDefInfos.Count; i++) { var info = propertyDefInfos.GetSorted(i); if ((uint)i + 1 != tablesHeap.PropertyPtrTable.Add(new RawPropertyPtrRow(info.Rid))) throw new ModuleWriterException("Invalid property ptr rid"); } } Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids2); InitializeMethodAndFieldList(); InitializeParamList(); InitializeEventMap(); InitializePropertyMap(); Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids3); // We must re-use deleted event/property rows after we've initialized // the event/prop map tables. if (eventDefInfos.NeedPtrTable) ReUseDeletedEventRows(); if (propertyDefInfos.NeedPtrTable) ReUseDeletedPropertyRows(); Listener.OnMetaDataEvent(this, MetaDataEvent.AllocateMemberDefRids4); InitializeTypeRefTableRows(); InitializeTypeSpecTableRows(); InitializeMemberRefTableRows(); InitializeMethodSpecTableRows(); } /// <summary> /// Re-uses all <c>Field</c> rows which aren't owned by any type due to the fields /// having been deleted by the user. The reason we must do this is that the /// <c>FieldPtr</c> and <c>Field</c> tables must be the same size. /// </summary> void ReUseDeletedFieldRows() { if (tablesHeap.FieldPtrTable.IsEmpty) return; if (fieldDefInfos.TableSize == tablesHeap.FieldPtrTable.Rows) return; var hasOwner = new bool[fieldDefInfos.TableSize]; for (int i = 0; i < fieldDefInfos.Count; i++) hasOwner[(int)fieldDefInfos.Get(i).Rid - 1] = true; CreateDummyPtrTableType(); uint fieldSig = GetSignature(new FieldSig(module.CorLibTypes.Byte)); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint frid = (uint)i + 1; var frow = tablesHeap.FieldTable[frid]; frow.Flags = (ushort)(FieldAttributes.Public | FieldAttributes.Static); frow.Name = stringsHeap.Add(string.Format("f{0:X6}", frid)); frow.Signature = fieldSig; tablesHeap.FieldPtrTable.Create(new RawFieldPtrRow(frid)); } if (fieldDefInfos.TableSize != tablesHeap.FieldPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy fields"); } /// <summary> /// Re-uses all <c>Method</c> rows which aren't owned by any type due to the methods /// having been deleted by the user. The reason we must do this is that the /// <c>MethodPtr</c> and <c>Method</c> tables must be the same size. /// </summary> void ReUseDeletedMethodRows() { if (tablesHeap.MethodPtrTable.IsEmpty) return; if (methodDefInfos.TableSize == tablesHeap.MethodPtrTable.Rows) return; var hasOwner = new bool[methodDefInfos.TableSize]; for (int i = 0; i < methodDefInfos.Count; i++) hasOwner[(int)methodDefInfos.Get(i).Rid - 1] = true; CreateDummyPtrTableType(); uint methodSig = GetSignature(MethodSig.CreateInstance(module.CorLibTypes.Void)); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint mrid = (uint)i + 1; var mrow = tablesHeap.MethodTable[mrid]; mrow.RVA = 0; mrow.ImplFlags = (ushort)(MethodImplAttributes.IL | MethodImplAttributes.Managed); mrow.Flags = (ushort)(MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Abstract); mrow.Name = stringsHeap.Add(string.Format("m{0:X6}", mrid)); mrow.Signature = methodSig; mrow.ParamList = (uint)paramDefInfos.Count; tablesHeap.MethodPtrTable.Create(new RawMethodPtrRow(mrid)); } if (methodDefInfos.TableSize != tablesHeap.MethodPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy methods"); } /// <summary> /// Re-uses all <c>Param</c> rows which aren't owned by any type due to the params /// having been deleted by the user. The reason we must do this is that the /// <c>ParamPtr</c> and <c>Param</c> tables must be the same size. /// This method must be called after <see cref="ReUseDeletedMethodRows()"/> since /// this method will create more methods at the end of the <c>Method</c> table. /// </summary> void ReUseDeletedParamRows() { if (tablesHeap.ParamPtrTable.IsEmpty) return; if (paramDefInfos.TableSize == tablesHeap.ParamPtrTable.Rows) return; var hasOwner = new bool[paramDefInfos.TableSize]; for (int i = 0; i < paramDefInfos.Count; i++) hasOwner[(int)paramDefInfos.Get(i).Rid - 1] = true; CreateDummyPtrTableType(); // For each param, attach it to a new method. Another alternative would be to create // one (or a few) methods with tons of parameters. uint methodSig = GetSignature(MethodSig.CreateInstance(module.CorLibTypes.Void)); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint prid = (uint)i + 1; var prow = tablesHeap.ParamTable[prid]; prow.Flags = 0; prow.Sequence = 0; // Return type parameter prow.Name = stringsHeap.Add(string.Format("p{0:X6}", prid)); uint ptrRid = tablesHeap.ParamPtrTable.Create(new RawParamPtrRow(prid)); var mrow = new RawMethodRow(0, (ushort)(MethodImplAttributes.IL | MethodImplAttributes.Managed), (ushort)(MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Abstract), stringsHeap.Add(string.Format("mp{0:X6}", prid)), methodSig, ptrRid); uint mrid = tablesHeap.MethodTable.Create(mrow); if (tablesHeap.MethodPtrTable.Rows > 0) tablesHeap.MethodPtrTable.Create(new RawMethodPtrRow(mrid)); } if (paramDefInfos.TableSize != tablesHeap.ParamPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy params"); } /// <summary> /// Re-uses all <c>Event</c> rows which aren't owned by any type due to the events /// having been deleted by the user. The reason we must do this is that the /// <c>EventPtr</c> and <c>Event</c> tables must be the same size. /// </summary> void ReUseDeletedEventRows() { if (tablesHeap.EventPtrTable.IsEmpty) return; if (eventDefInfos.TableSize == tablesHeap.EventPtrTable.Rows) return; var hasOwner = new bool[eventDefInfos.TableSize]; for (int i = 0; i < eventDefInfos.Count; i++) hasOwner[(int)eventDefInfos.Get(i).Rid - 1] = true; uint typeRid = CreateDummyPtrTableType(); tablesHeap.EventMapTable.Create(new RawEventMapRow(typeRid, (uint)tablesHeap.EventPtrTable.Rows + 1)); uint eventType = AddTypeDefOrRef(module.CorLibTypes.Object.TypeDefOrRef); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint erid = (uint)i + 1; var frow = tablesHeap.EventTable[erid]; frow.EventFlags = 0; frow.Name = stringsHeap.Add(string.Format("E{0:X6}", erid)); frow.EventType = eventType; tablesHeap.EventPtrTable.Create(new RawEventPtrRow(erid)); } if (eventDefInfos.TableSize != tablesHeap.EventPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy events"); } /// <summary> /// Re-uses all <c>Property</c> rows which aren't owned by any type due to the properties /// having been deleted by the user. The reason we must do this is that the /// <c>PropertyPtr</c> and <c>Property</c> tables must be the same size. /// </summary> void ReUseDeletedPropertyRows() { if (tablesHeap.PropertyPtrTable.IsEmpty) return; if (propertyDefInfos.TableSize == tablesHeap.PropertyPtrTable.Rows) return; var hasOwner = new bool[propertyDefInfos.TableSize]; for (int i = 0; i < propertyDefInfos.Count; i++) hasOwner[(int)propertyDefInfos.Get(i).Rid - 1] = true; uint typeRid = CreateDummyPtrTableType(); tablesHeap.PropertyMapTable.Create(new RawPropertyMapRow(typeRid, (uint)tablesHeap.PropertyPtrTable.Rows + 1)); uint propertySig = GetSignature(PropertySig.CreateStatic(module.CorLibTypes.Object)); for (int i = 0; i < hasOwner.Length; i++) { if (hasOwner[i]) continue; uint prid = (uint)i + 1; var frow = tablesHeap.PropertyTable[prid]; frow.PropFlags = 0; frow.Name = stringsHeap.Add(string.Format("P{0:X6}", prid)); frow.Type = propertySig; tablesHeap.PropertyPtrTable.Create(new RawPropertyPtrRow(prid)); } if (propertyDefInfos.TableSize != tablesHeap.PropertyPtrTable.Rows) throw new ModuleWriterException("Didn't create all dummy properties"); } /// <summary> /// Creates a dummy <c>TypeDef</c> at the end of the <c>TypeDef</c> table that will own /// dummy methods and fields. These dummy methods and fields are only created if the size /// of the ptr table is less than the size of the non-ptr table (eg. size MethodPtr table /// is less than size Method table). The only reason the ptr table would be smaller than /// the non-ptr table is when some field/method has been deleted and we must preserve /// all method/field rids. /// </summary> uint CreateDummyPtrTableType() { if (dummyPtrTableTypeRid != 0) return dummyPtrTableTypeRid; var flags = TypeAttributes.NotPublic | TypeAttributes.AutoLayout | TypeAttributes.Class | TypeAttributes.Abstract | TypeAttributes.AnsiClass; int numFields = fieldDefInfos.NeedPtrTable ? fieldDefInfos.Count : fieldDefInfos.TableSize; int numMethods = methodDefInfos.NeedPtrTable ? methodDefInfos.Count : methodDefInfos.TableSize; var row = new RawTypeDefRow((uint)flags, stringsHeap.Add(Guid.NewGuid().ToString("B")), stringsHeap.Add("dummy_ptr"), AddTypeDefOrRef(module.CorLibTypes.Object.TypeDefOrRef), (uint)numFields + 1, (uint)numMethods + 1); dummyPtrTableTypeRid = tablesHeap.TypeDefTable.Create(row); if (dummyPtrTableTypeRid == 1) throw new ModuleWriterException("Dummy ptr type is the first type"); return dummyPtrTableTypeRid; } uint dummyPtrTableTypeRid; void FindMemberDefs() { int pos; foreach (var type in allTypeDefs) { if (type == null) continue; pos = 0; foreach (var field in type.Fields) { if (field == null) continue; fieldDefInfos.Add(field, pos++); } pos = 0; foreach (var method in type.Methods) { if (method == null) continue; methodDefInfos.Add(method, pos++); } pos = 0; foreach (var evt in type.Events) { if (evt == null) continue; eventDefInfos.Add(evt, pos++); } pos = 0; foreach (var prop in type.Properties) { if (prop == null) continue; propertyDefInfos.Add(prop, pos++); } } fieldDefInfos.SortDefs(); methodDefInfos.SortDefs(); eventDefInfos.SortDefs(); propertyDefInfos.SortDefs(); for (int i = 0; i < methodDefInfos.Count; i++) { var method = methodDefInfos.Get(i).Def; pos = 0; foreach (var param in Sort(method.ParamDefs)) { if (param == null) continue; paramDefInfos.Add(param, pos++); } } paramDefInfos.SortDefs(); } void SortFields() { fieldDefInfos.Sort((a, b) => { var dta = a.Def.DeclaringType == null ? 0 : typeToRid[a.Def.DeclaringType]; var dtb = b.Def.DeclaringType == null ? 0 : typeToRid[b.Def.DeclaringType]; if (dta == 0 || dtb == 0) return a.Rid.CompareTo(b.Rid); if (dta != dtb) return dta.CompareTo(dtb); return fieldDefInfos.GetCollectionPosition(a.Def).CompareTo(fieldDefInfos.GetCollectionPosition(b.Def)); }); } void SortMethods() { methodDefInfos.Sort((a, b) => { var dta = a.Def.DeclaringType == null ? 0 : typeToRid[a.Def.DeclaringType]; var dtb = b.Def.DeclaringType == null ? 0 : typeToRid[b.Def.DeclaringType]; if (dta == 0 || dtb == 0) return a.Rid.CompareTo(b.Rid); if (dta != dtb) return dta.CompareTo(dtb); return methodDefInfos.GetCollectionPosition(a.Def).CompareTo(methodDefInfos.GetCollectionPosition(b.Def)); }); } void SortParameters() { paramDefInfos.Sort((a, b) => { var dma = a.Def.DeclaringMethod == null ? 0 : methodDefInfos.Rid(a.Def.DeclaringMethod); var dmb = b.Def.DeclaringMethod == null ? 0 : methodDefInfos.Rid(b.Def.DeclaringMethod); if (dma == 0 || dmb == 0) return a.Rid.CompareTo(b.Rid); if (dma != dmb) return dma.CompareTo(dmb); return paramDefInfos.GetCollectionPosition(a.Def).CompareTo(paramDefInfos.GetCollectionPosition(b.Def)); }); } void SortEvents() { eventDefInfos.Sort((a, b) => { var dta = a.Def.DeclaringType == null ? 0 : typeToRid[a.Def.DeclaringType]; var dtb = b.Def.DeclaringType == null ? 0 : typeToRid[b.Def.DeclaringType]; if (dta == 0 || dtb == 0) return a.Rid.CompareTo(b.Rid); if (dta != dtb) return dta.CompareTo(dtb); return eventDefInfos.GetCollectionPosition(a.Def).CompareTo(eventDefInfos.GetCollectionPosition(b.Def)); }); } void SortProperties() { propertyDefInfos.Sort((a, b) => { var dta = a.Def.DeclaringType == null ? 0 : typeToRid[a.Def.DeclaringType]; var dtb = b.Def.DeclaringType == null ? 0 : typeToRid[b.Def.DeclaringType]; if (dta == 0 || dtb == 0) return a.Rid.CompareTo(b.Rid); if (dta != dtb) return dta.CompareTo(dtb); return propertyDefInfos.GetCollectionPosition(a.Def).CompareTo(propertyDefInfos.GetCollectionPosition(b.Def)); }); } void InitializeMethodAndFieldList() { uint fieldList = 1, methodList = 1; foreach (var type in allTypeDefs) { var typeRow = tablesHeap.TypeDefTable[typeToRid[type]]; typeRow.FieldList = fieldList; typeRow.MethodList = methodList; fieldList += (uint)type.Fields.Count; methodList += (uint)type.Methods.Count; } } void InitializeParamList() { uint ridList = 1; for (uint methodRid = 1; methodRid <= methodDefInfos.TableSize; methodRid++) { var methodInfo = methodDefInfos.GetByRid(methodRid); var row = tablesHeap.MethodTable[methodRid]; row.ParamList = ridList; if (methodInfo != null) ridList += (uint)methodInfo.Def.ParamDefs.Count; } } void InitializeEventMap() { if (!tablesHeap.EventMapTable.IsEmpty) throw new ModuleWriterException("EventMap table isn't empty"); TypeDef type = null; for (int i = 0; i < eventDefInfos.Count; i++) { var info = eventDefInfos.GetSorted(i); if (type == info.Def.DeclaringType) continue; type = info.Def.DeclaringType; var row = new RawEventMapRow(typeToRid[type], info.NewRid); uint eventMapRid = tablesHeap.EventMapTable.Create(row); eventMapInfos.Add(type, eventMapRid); } } void InitializePropertyMap() { if (!tablesHeap.PropertyMapTable.IsEmpty) throw new ModuleWriterException("PropertyMap table isn't empty"); TypeDef type = null; for (int i = 0; i < propertyDefInfos.Count; i++) { var info = propertyDefInfos.GetSorted(i); if (type == info.Def.DeclaringType) continue; type = info.Def.DeclaringType; var row = new RawPropertyMapRow(typeToRid[type], info.NewRid); uint propertyMapRid = tablesHeap.PropertyMapTable.Create(row); propertyMapInfos.Add(type, propertyMapRid); } } /// <inheritdoc/> protected override uint AddTypeRef(TypeRef tr) { if (tr == null) { Error("TypeRef is null"); return 0; } uint rid; if (typeRefInfos.TryGetRid(tr, out rid)) { if (rid == 0) Error("TypeRef {0:X8} has an infinite ResolutionScope loop", tr.MDToken.Raw); return rid; } typeRefInfos.Add(tr, 0); // Prevent inf recursion bool isOld = PreserveTypeRefRids && mod.ResolveTypeRef(tr.Rid) == tr; var row = isOld ? tablesHeap.TypeRefTable[tr.Rid] : new RawTypeRefRow(); row.ResolutionScope = AddResolutionScope(tr.ResolutionScope); row.Name = stringsHeap.Add(tr.Name); row.Namespace = stringsHeap.Add(tr.Namespace); rid = isOld ? tr.Rid : tablesHeap.TypeRefTable.Add(row); typeRefInfos.SetRid(tr, rid); AddCustomAttributes(Table.TypeRef, rid, tr); return rid; } /// <inheritdoc/> protected override uint AddTypeSpec(TypeSpec ts) { return AddTypeSpec(ts, false); } uint AddTypeSpec(TypeSpec ts, bool forceIsOld) { if (ts == null) { Error("TypeSpec is null"); return 0; } uint rid; if (typeSpecInfos.TryGetRid(ts, out rid)) { if (rid == 0) Error("TypeSpec {0:X8} has an infinite TypeSig loop", ts.MDToken.Raw); return rid; } typeSpecInfos.Add(ts, 0); // Prevent inf recursion bool isOld = forceIsOld || (PreserveTypeSpecRids && mod.ResolveTypeSpec(ts.Rid) == ts); var row = isOld ? tablesHeap.TypeSpecTable[ts.Rid] : new RawTypeSpecRow(); row.Signature = GetSignature(ts.TypeSig, ts.ExtraData); rid = isOld ? ts.Rid : tablesHeap.TypeSpecTable.Add(row); typeSpecInfos.SetRid(ts, rid); AddCustomAttributes(Table.TypeSpec, rid, ts); return rid; } /// <inheritdoc/> protected override uint AddMemberRef(MemberRef mr) { return AddMemberRef(mr, false); } uint AddMemberRef(MemberRef mr, bool forceIsOld) { if (mr == null) { Error("MemberRef is null"); return 0; } uint rid; if (memberRefInfos.TryGetRid(mr, out rid)) return rid; bool isOld = forceIsOld || (PreserveMemberRefRids && mod.ResolveMemberRef(mr.Rid) == mr); var row = isOld ? tablesHeap.MemberRefTable[mr.Rid] : new RawMemberRefRow(); row.Class = AddMemberRefParent(mr.Class); row.Name = stringsHeap.Add(mr.Name); row.Signature = GetSignature(mr.Signature); rid = isOld ? mr.Rid : tablesHeap.MemberRefTable.Add(row); memberRefInfos.Add(mr, rid); AddCustomAttributes(Table.MemberRef, rid, mr); return rid; } /// <inheritdoc/> protected override uint AddStandAloneSig(StandAloneSig sas) { return AddStandAloneSig(sas, false); } uint AddStandAloneSig(StandAloneSig sas, bool forceIsOld) { if (sas == null) { Error("StandAloneSig is null"); return 0; } uint rid; if (standAloneSigInfos.TryGetRid(sas, out rid)) return rid; bool isOld = forceIsOld || (PreserveStandAloneSigRids && mod.ResolveStandAloneSig(sas.Rid) == sas); var row = isOld ? tablesHeap.StandAloneSigTable[sas.Rid] : new RawStandAloneSigRow(); row.Signature = GetSignature(sas.Signature); rid = isOld ? sas.Rid : tablesHeap.StandAloneSigTable.Add(row); standAloneSigInfos.Add(sas, rid); AddCustomAttributes(Table.StandAloneSig, rid, sas); return rid; } /// <inheritdoc/> public override MDToken GetToken(IList<TypeSig> locals, uint origToken) { if (!PreserveStandAloneSigRids || !IsValidStandAloneSigToken(origToken)) return base.GetToken(locals, origToken); uint rid = AddStandAloneSig(new LocalSig(locals, false), origToken); if (rid == 0) return base.GetToken(locals, origToken); return new MDToken(Table.StandAloneSig, rid); } /// <inheritdoc/> protected override uint AddStandAloneSig(MethodSig methodSig, uint origToken) { if (!PreserveStandAloneSigRids || !IsValidStandAloneSigToken(origToken)) return base.AddStandAloneSig(methodSig, origToken); uint rid = AddStandAloneSig(methodSig, origToken); if (rid == 0) return base.AddStandAloneSig(methodSig, origToken); return rid; } uint AddStandAloneSig(CallingConventionSig callConvSig, uint origToken) { uint sig = GetSignature(callConvSig); uint otherSig; if (callConvTokenToSignature.TryGetValue(origToken, out otherSig)) { if (sig == otherSig) return MDToken.ToRID(origToken); Warning("Could not preserve StandAloneSig token {0:X8}", origToken); return 0; } uint rid = MDToken.ToRID(origToken); var sas = mod.ResolveStandAloneSig(rid); if (standAloneSigInfos.Exists(sas)) { Warning("StandAloneSig {0:X8} already exists", origToken); return 0; } // Make sure it uses the updated sig var oldSig = sas.Signature; try { sas.Signature = callConvSig; AddStandAloneSig(sas, true); } finally { sas.Signature = oldSig; } callConvTokenToSignature.Add(origToken, sig); return MDToken.ToRID(origToken); } bool IsValidStandAloneSigToken(uint token) { if (MDToken.ToTable(token) != Table.StandAloneSig) return false; uint rid = MDToken.ToRID(token); return mod.TablesStream.StandAloneSigTable.IsValidRID(rid); } /// <inheritdoc/> protected override uint AddMethodSpec(MethodSpec ms) { return AddMethodSpec(ms, false); } uint AddMethodSpec(MethodSpec ms, bool forceIsOld) { if (ms == null) { Error("MethodSpec is null"); return 0; } uint rid; if (methodSpecInfos.TryGetRid(ms, out rid)) return rid; bool isOld = forceIsOld || (PreserveMethodSpecRids && mod.ResolveMethodSpec(ms.Rid) == ms); var row = isOld ? tablesHeap.MethodSpecTable[ms.Rid] : new RawMethodSpecRow(); row.Method = AddMethodDefOrRef(ms.Method); row.Instantiation = GetSignature(ms.Instantiation); rid = isOld ? ms.Rid : tablesHeap.MethodSpecTable.Add(row); methodSpecInfos.Add(ms, rid); AddCustomAttributes(Table.MethodSpec, rid, ms); return rid; } /// <inheritdoc/> protected override void BeforeSortingCustomAttributes() { InitializeUninitializedTableRows(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel; namespace System.Collections.Immutable { public sealed partial class ImmutableQueue<T> { /// <summary> /// A memory allocation-free enumerator of <see cref="ImmutableQueue{T}"/>. /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced)] public struct Enumerator { /// <summary> /// The original queue being enumerated. /// </summary> private readonly ImmutableQueue<T> _originalQueue; /// <summary> /// The remaining forwards stack of the queue being enumerated. /// </summary> private ImmutableStack<T> _remainingForwardsStack; /// <summary> /// The remaining backwards stack of the queue being enumerated. /// Its order is reversed when the field is first initialized. /// </summary> private ImmutableStack<T> _remainingBackwardsStack; /// <summary> /// Initializes a new instance of the <see cref="Enumerator"/> struct. /// </summary> /// <param name="queue">The queue to enumerate.</param> internal Enumerator(ImmutableQueue<T> queue) { _originalQueue = queue; // The first call to MoveNext will initialize these. _remainingForwardsStack = null; _remainingBackwardsStack = null; } /// <summary> /// The current element. /// </summary> public T Current { get { if (_remainingForwardsStack == null) { // The initial call to MoveNext has not yet been made. throw new InvalidOperationException(); } if (!_remainingForwardsStack.IsEmpty) { return _remainingForwardsStack.Peek(); } else if (!_remainingBackwardsStack.IsEmpty) { return _remainingBackwardsStack.Peek(); } else { // We've advanced beyond the end of the queue. throw new InvalidOperationException(); } } } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { if (_remainingForwardsStack == null) { // This is the initial step. // Empty queues have no forwards or backwards _remainingForwardsStack = _originalQueue._forwards; _remainingBackwardsStack = _originalQueue.BackwardsReversed; } else if (!_remainingForwardsStack.IsEmpty) { _remainingForwardsStack = _remainingForwardsStack.Pop(); } else if (!_remainingBackwardsStack.IsEmpty) { _remainingBackwardsStack = _remainingBackwardsStack.Pop(); } return !_remainingForwardsStack.IsEmpty || !_remainingBackwardsStack.IsEmpty; } } /// <summary> /// A memory allocation-free enumerator of <see cref="ImmutableQueue{T}"/>. /// </summary> private class EnumeratorObject : IEnumerator<T> { /// <summary> /// The original queue being enumerated. /// </summary> private readonly ImmutableQueue<T> _originalQueue; /// <summary> /// The remaining forwards stack of the queue being enumerated. /// </summary> private ImmutableStack<T> _remainingForwardsStack; /// <summary> /// The remaining backwards stack of the queue being enumerated. /// Its order is reversed when the field is first initialized. /// </summary> private ImmutableStack<T> _remainingBackwardsStack; /// <summary> /// A value indicating whether this enumerator has been disposed. /// </summary> private bool _disposed; /// <summary> /// Initializes a new instance of the <see cref="Enumerator"/> struct. /// </summary> /// <param name="queue">The queue to enumerate.</param> internal EnumeratorObject(ImmutableQueue<T> queue) { _originalQueue = queue; } /// <summary> /// The current element. /// </summary> public T Current { get { this.ThrowIfDisposed(); if (_remainingForwardsStack == null) { // The initial call to MoveNext has not yet been made. throw new InvalidOperationException(); } if (!_remainingForwardsStack.IsEmpty) { return _remainingForwardsStack.Peek(); } else if (!_remainingBackwardsStack.IsEmpty) { return _remainingBackwardsStack.Peek(); } else { // We've advanced beyond the end of the queue. throw new InvalidOperationException(); } } } /// <summary> /// The current element. /// </summary> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Advances enumeration to the next element. /// </summary> /// <returns>A value indicating whether there is another element in the enumeration.</returns> public bool MoveNext() { this.ThrowIfDisposed(); if (_remainingForwardsStack == null) { // This is the initial step. // Empty queues have no forwards or backwards _remainingForwardsStack = _originalQueue._forwards; _remainingBackwardsStack = _originalQueue.BackwardsReversed; } else if (!_remainingForwardsStack.IsEmpty) { _remainingForwardsStack = _remainingForwardsStack.Pop(); } else if (!_remainingBackwardsStack.IsEmpty) { _remainingBackwardsStack = _remainingBackwardsStack.Pop(); } return !_remainingForwardsStack.IsEmpty || !_remainingBackwardsStack.IsEmpty; } /// <summary> /// Restarts enumeration. /// </summary> public void Reset() { this.ThrowIfDisposed(); _remainingBackwardsStack = null; _remainingForwardsStack = null; } /// <summary> /// Disposes this instance. /// </summary> public void Dispose() { _disposed = true; } /// <summary> /// Throws an <see cref="ObjectDisposedException"/> if this /// enumerator has already been disposed. /// </summary> private void ThrowIfDisposed() { if (_disposed) { Requires.FailObjectDisposed(this); } } } } }
/* * Pens.cs - Implementation of the "System.Drawing.Pens" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Drawing { public sealed class Pens { // Internal state. private static Pen[] standardPens; // This class cannot be instantiated. private Pens() {} // Get or create a standard pen. private static Pen GetOrCreatePen(KnownColor color) { lock(typeof(Pens)) { if(standardPens == null) { standardPens = new Pen [((int)(KnownColor.YellowGreen)) - ((int)(KnownColor.Transparent)) + 1]; } int index = ((int)color) - ((int)(KnownColor.Transparent)); if(standardPens[index] == null) { standardPens[index] = new Pen(new Color(color)); } return standardPens[index]; } } // Pen objects for the standard colors. public static Pen Transparent { get { return GetOrCreatePen(KnownColor.Transparent); } } public static Pen AliceBlue { get { return GetOrCreatePen(KnownColor.AliceBlue); } } public static Pen AntiqueWhite { get { return GetOrCreatePen(KnownColor.AntiqueWhite); } } public static Pen Aqua { get { return GetOrCreatePen(KnownColor.Aqua); } } public static Pen Aquamarine { get { return GetOrCreatePen(KnownColor.Aquamarine); } } public static Pen Azure { get { return GetOrCreatePen(KnownColor.Azure); } } public static Pen Beige { get { return GetOrCreatePen(KnownColor.Beige); } } public static Pen Bisque { get { return GetOrCreatePen(KnownColor.Bisque); } } public static Pen Black { get { return GetOrCreatePen(KnownColor.Black); } } public static Pen BlanchedAlmond { get { return GetOrCreatePen(KnownColor.BlanchedAlmond); } } public static Pen Blue { get { return GetOrCreatePen(KnownColor.Blue); } } public static Pen BlueViolet { get { return GetOrCreatePen(KnownColor.BlueViolet); } } public static Pen Brown { get { return GetOrCreatePen(KnownColor.Brown); } } public static Pen BurlyWood { get { return GetOrCreatePen(KnownColor.BurlyWood); } } public static Pen CadetBlue { get { return GetOrCreatePen(KnownColor.CadetBlue); } } public static Pen Chartreuse { get { return GetOrCreatePen(KnownColor.Chartreuse); } } public static Pen Chocolate { get { return GetOrCreatePen(KnownColor.Chocolate); } } public static Pen Coral { get { return GetOrCreatePen(KnownColor.Coral); } } public static Pen CornflowerBlue { get { return GetOrCreatePen(KnownColor.CornflowerBlue); } } public static Pen Cornsilk { get { return GetOrCreatePen(KnownColor.Cornsilk); } } public static Pen Crimson { get { return GetOrCreatePen(KnownColor.Crimson); } } public static Pen Cyan { get { return GetOrCreatePen(KnownColor.Cyan); } } public static Pen DarkBlue { get { return GetOrCreatePen(KnownColor.DarkBlue); } } public static Pen DarkCyan { get { return GetOrCreatePen(KnownColor.DarkCyan); } } public static Pen DarkGoldenrod { get { return GetOrCreatePen(KnownColor.DarkGoldenrod); } } public static Pen DarkGray { get { return GetOrCreatePen(KnownColor.DarkGray); } } public static Pen DarkGreen { get { return GetOrCreatePen(KnownColor.DarkGreen); } } public static Pen DarkKhaki { get { return GetOrCreatePen(KnownColor.DarkKhaki); } } public static Pen DarkMagenta { get { return GetOrCreatePen(KnownColor.DarkMagenta); } } public static Pen DarkOliveGreen { get { return GetOrCreatePen(KnownColor.DarkOliveGreen); } } public static Pen DarkOrange { get { return GetOrCreatePen(KnownColor.DarkOrange); } } public static Pen DarkOrchid { get { return GetOrCreatePen(KnownColor.DarkOrchid); } } public static Pen DarkRed { get { return GetOrCreatePen(KnownColor.DarkRed); } } public static Pen DarkSalmon { get { return GetOrCreatePen(KnownColor.DarkSalmon); } } public static Pen DarkSeaGreen { get { return GetOrCreatePen(KnownColor.DarkSeaGreen); } } public static Pen DarkSlateBlue { get { return GetOrCreatePen(KnownColor.DarkSlateBlue); } } public static Pen DarkSlateGray { get { return GetOrCreatePen(KnownColor.DarkSlateGray); } } public static Pen DarkTurquoise { get { return GetOrCreatePen(KnownColor.DarkTurquoise); } } public static Pen DarkViolet { get { return GetOrCreatePen(KnownColor.DarkViolet); } } public static Pen DeepPink { get { return GetOrCreatePen(KnownColor.DeepPink); } } public static Pen DeepSkyBlue { get { return GetOrCreatePen(KnownColor.DeepSkyBlue); } } public static Pen DimGray { get { return GetOrCreatePen(KnownColor.DimGray); } } public static Pen DodgerBlue { get { return GetOrCreatePen(KnownColor.DodgerBlue); } } public static Pen Firebrick { get { return GetOrCreatePen(KnownColor.Firebrick); } } public static Pen FloralWhite { get { return GetOrCreatePen(KnownColor.FloralWhite); } } public static Pen ForestGreen { get { return GetOrCreatePen(KnownColor.ForestGreen); } } public static Pen Fuchsia { get { return GetOrCreatePen(KnownColor.Fuchsia); } } public static Pen Gainsboro { get { return GetOrCreatePen(KnownColor.Gainsboro); } } public static Pen GhostWhite { get { return GetOrCreatePen(KnownColor.GhostWhite); } } public static Pen Gold { get { return GetOrCreatePen(KnownColor.Gold); } } public static Pen Goldenrod { get { return GetOrCreatePen(KnownColor.Goldenrod); } } public static Pen Gray { get { return GetOrCreatePen(KnownColor.Gray); } } public static Pen Green { get { return GetOrCreatePen(KnownColor.Green); } } public static Pen GreenYellow { get { return GetOrCreatePen(KnownColor.GreenYellow); } } public static Pen Honeydew { get { return GetOrCreatePen(KnownColor.Honeydew); } } public static Pen HotPink { get { return GetOrCreatePen(KnownColor.HotPink); } } public static Pen IndianRed { get { return GetOrCreatePen(KnownColor.IndianRed); } } public static Pen Indigo { get { return GetOrCreatePen(KnownColor.Indigo); } } public static Pen Ivory { get { return GetOrCreatePen(KnownColor.Ivory); } } public static Pen Khaki { get { return GetOrCreatePen(KnownColor.Khaki); } } public static Pen Lavender { get { return GetOrCreatePen(KnownColor.Lavender); } } public static Pen LavenderBlush { get { return GetOrCreatePen(KnownColor.LavenderBlush); } } public static Pen LawnGreen { get { return GetOrCreatePen(KnownColor.LawnGreen); } } public static Pen LemonChiffon { get { return GetOrCreatePen(KnownColor.LemonChiffon); } } public static Pen LightBlue { get { return GetOrCreatePen(KnownColor.LightBlue); } } public static Pen LightCoral { get { return GetOrCreatePen(KnownColor.LightCoral); } } public static Pen LightCyan { get { return GetOrCreatePen(KnownColor.LightCyan); } } public static Pen LightGoldenrodYellow { get { return GetOrCreatePen(KnownColor.LightGoldenrodYellow); } } public static Pen LightGray { get { return GetOrCreatePen(KnownColor.LightGray); } } public static Pen LightGreen { get { return GetOrCreatePen(KnownColor.LightGreen); } } public static Pen LightPink { get { return GetOrCreatePen(KnownColor.LightPink); } } public static Pen LightSalmon { get { return GetOrCreatePen(KnownColor.LightSalmon); } } public static Pen LightSeaGreen { get { return GetOrCreatePen(KnownColor.LightSeaGreen); } } public static Pen LightSkyBlue { get { return GetOrCreatePen(KnownColor.LightSkyBlue); } } public static Pen LightSlateGray { get { return GetOrCreatePen(KnownColor.LightSlateGray); } } public static Pen LightSteelBlue { get { return GetOrCreatePen(KnownColor.LightSteelBlue); } } public static Pen LightYellow { get { return GetOrCreatePen(KnownColor.LightYellow); } } public static Pen Lime { get { return GetOrCreatePen(KnownColor.Lime); } } public static Pen LimeGreen { get { return GetOrCreatePen(KnownColor.LimeGreen); } } public static Pen Linen { get { return GetOrCreatePen(KnownColor.Linen); } } public static Pen Magenta { get { return GetOrCreatePen(KnownColor.Magenta); } } public static Pen Maroon { get { return GetOrCreatePen(KnownColor.Maroon); } } public static Pen MediumAquamarine { get { return GetOrCreatePen(KnownColor.MediumAquamarine); } } public static Pen MediumBlue { get { return GetOrCreatePen(KnownColor.MediumBlue); } } public static Pen MediumOrchid { get { return GetOrCreatePen(KnownColor.MediumOrchid); } } public static Pen MediumPurple { get { return GetOrCreatePen(KnownColor.MediumPurple); } } public static Pen MediumSeaGreen { get { return GetOrCreatePen(KnownColor.MediumSeaGreen); } } public static Pen MediumSlateBlue { get { return GetOrCreatePen(KnownColor.MediumSlateBlue); } } public static Pen MediumSpringGreen { get { return GetOrCreatePen(KnownColor.MediumSpringGreen); } } public static Pen MediumTurquoise { get { return GetOrCreatePen(KnownColor.MediumTurquoise); } } public static Pen MediumVioletRed { get { return GetOrCreatePen(KnownColor.MediumVioletRed); } } public static Pen MidnightBlue { get { return GetOrCreatePen(KnownColor.MidnightBlue); } } public static Pen MintCream { get { return GetOrCreatePen(KnownColor.MintCream); } } public static Pen MistyRose { get { return GetOrCreatePen(KnownColor.MistyRose); } } public static Pen Moccasin { get { return GetOrCreatePen(KnownColor.Moccasin); } } public static Pen NavajoWhite { get { return GetOrCreatePen(KnownColor.NavajoWhite); } } public static Pen Navy { get { return GetOrCreatePen(KnownColor.Navy); } } public static Pen OldLace { get { return GetOrCreatePen(KnownColor.OldLace); } } public static Pen Olive { get { return GetOrCreatePen(KnownColor.Olive); } } public static Pen OliveDrab { get { return GetOrCreatePen(KnownColor.OliveDrab); } } public static Pen Orange { get { return GetOrCreatePen(KnownColor.Orange); } } public static Pen OrangeRed { get { return GetOrCreatePen(KnownColor.OrangeRed); } } public static Pen Orchid { get { return GetOrCreatePen(KnownColor.Orchid); } } public static Pen PaleGoldenrod { get { return GetOrCreatePen(KnownColor.PaleGoldenrod); } } public static Pen PaleGreen { get { return GetOrCreatePen(KnownColor.PaleGreen); } } public static Pen PaleTurquoise { get { return GetOrCreatePen(KnownColor.PaleTurquoise); } } public static Pen PaleVioletRed { get { return GetOrCreatePen(KnownColor.PaleVioletRed); } } public static Pen PapayaWhip { get { return GetOrCreatePen(KnownColor.PapayaWhip); } } public static Pen PeachPuff { get { return GetOrCreatePen(KnownColor.PeachPuff); } } public static Pen Peru { get { return GetOrCreatePen(KnownColor.Peru); } } public static Pen Pink { get { return GetOrCreatePen(KnownColor.Pink); } } public static Pen Plum { get { return GetOrCreatePen(KnownColor.Plum); } } public static Pen PowderBlue { get { return GetOrCreatePen(KnownColor.PowderBlue); } } public static Pen Purple { get { return GetOrCreatePen(KnownColor.Purple); } } public static Pen Red { get { return GetOrCreatePen(KnownColor.Red); } } public static Pen RosyBrown { get { return GetOrCreatePen(KnownColor.RosyBrown); } } public static Pen RoyalBlue { get { return GetOrCreatePen(KnownColor.RoyalBlue); } } public static Pen SaddleBrown { get { return GetOrCreatePen(KnownColor.SaddleBrown); } } public static Pen Salmon { get { return GetOrCreatePen(KnownColor.Salmon); } } public static Pen SandyBrown { get { return GetOrCreatePen(KnownColor.SandyBrown); } } public static Pen SeaGreen { get { return GetOrCreatePen(KnownColor.SeaGreen); } } public static Pen SeaShell { get { return GetOrCreatePen(KnownColor.SeaShell); } } public static Pen Sienna { get { return GetOrCreatePen(KnownColor.Sienna); } } public static Pen Silver { get { return GetOrCreatePen(KnownColor.Silver); } } public static Pen SkyBlue { get { return GetOrCreatePen(KnownColor.SkyBlue); } } public static Pen SlateBlue { get { return GetOrCreatePen(KnownColor.SlateBlue); } } public static Pen SlateGray { get { return GetOrCreatePen(KnownColor.SlateGray); } } public static Pen Snow { get { return GetOrCreatePen(KnownColor.Snow); } } public static Pen SpringGreen { get { return GetOrCreatePen(KnownColor.SpringGreen); } } public static Pen SteelBlue { get { return GetOrCreatePen(KnownColor.SteelBlue); } } public static Pen Tan { get { return GetOrCreatePen(KnownColor.Tan); } } public static Pen Teal { get { return GetOrCreatePen(KnownColor.Teal); } } public static Pen Thistle { get { return GetOrCreatePen(KnownColor.Thistle); } } public static Pen Tomato { get { return GetOrCreatePen(KnownColor.Tomato); } } public static Pen Turquoise { get { return GetOrCreatePen(KnownColor.Turquoise); } } public static Pen Violet { get { return GetOrCreatePen(KnownColor.Violet); } } public static Pen Wheat { get { return GetOrCreatePen(KnownColor.Wheat); } } public static Pen White { get { return GetOrCreatePen(KnownColor.White); } } public static Pen WhiteSmoke { get { return GetOrCreatePen(KnownColor.WhiteSmoke); } } public static Pen Yellow { get { return GetOrCreatePen(KnownColor.Yellow); } } public static Pen YellowGreen { get { return GetOrCreatePen(KnownColor.YellowGreen); } } }; // class Pens }; // namespace System.Drawing
// 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 gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>ProductBiddingCategoryConstant</c> resource.</summary> public sealed partial class ProductBiddingCategoryConstantName : gax::IResourceName, sys::IEquatable<ProductBiddingCategoryConstantName> { /// <summary>The possible contents of <see cref="ProductBiddingCategoryConstantName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>. /// </summary> CountryCodeLevelId = 1, } private static gax::PathTemplate s_countryCodeLevelId = new gax::PathTemplate("productBiddingCategoryConstants/{country_code_level_id}"); /// <summary> /// Creates a <see cref="ProductBiddingCategoryConstantName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ProductBiddingCategoryConstantName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ProductBiddingCategoryConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ProductBiddingCategoryConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ProductBiddingCategoryConstantName"/> with the pattern /// <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>. /// </summary> /// <param name="countryCodeId">The <c>CountryCode</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="levelId">The <c>Level</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="idId">The <c>Id</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="ProductBiddingCategoryConstantName"/> constructed from the provided ids. /// </returns> public static ProductBiddingCategoryConstantName FromCountryCodeLevelId(string countryCodeId, string levelId, string idId) => new ProductBiddingCategoryConstantName(ResourceNameType.CountryCodeLevelId, countryCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(countryCodeId, nameof(countryCodeId)), levelId: gax::GaxPreconditions.CheckNotNullOrEmpty(levelId, nameof(levelId)), idId: gax::GaxPreconditions.CheckNotNullOrEmpty(idId, nameof(idId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ProductBiddingCategoryConstantName"/> with /// pattern <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>. /// </summary> /// <param name="countryCodeId">The <c>CountryCode</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="levelId">The <c>Level</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="idId">The <c>Id</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ProductBiddingCategoryConstantName"/> with pattern /// <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>. /// </returns> public static string Format(string countryCodeId, string levelId, string idId) => FormatCountryCodeLevelId(countryCodeId, levelId, idId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ProductBiddingCategoryConstantName"/> with /// pattern <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>. /// </summary> /// <param name="countryCodeId">The <c>CountryCode</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="levelId">The <c>Level</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="idId">The <c>Id</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ProductBiddingCategoryConstantName"/> with pattern /// <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c>. /// </returns> public static string FormatCountryCodeLevelId(string countryCodeId, string levelId, string idId) => s_countryCodeLevelId.Expand($"{(gax::GaxPreconditions.CheckNotNullOrEmpty(countryCodeId, nameof(countryCodeId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(levelId, nameof(levelId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(idId, nameof(idId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="ProductBiddingCategoryConstantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c></description></item> /// </list> /// </remarks> /// <param name="productBiddingCategoryConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="ProductBiddingCategoryConstantName"/> if successful.</returns> public static ProductBiddingCategoryConstantName Parse(string productBiddingCategoryConstantName) => Parse(productBiddingCategoryConstantName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ProductBiddingCategoryConstantName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="productBiddingCategoryConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ProductBiddingCategoryConstantName"/> if successful.</returns> public static ProductBiddingCategoryConstantName Parse(string productBiddingCategoryConstantName, bool allowUnparsed) => TryParse(productBiddingCategoryConstantName, allowUnparsed, out ProductBiddingCategoryConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ProductBiddingCategoryConstantName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c></description></item> /// </list> /// </remarks> /// <param name="productBiddingCategoryConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ProductBiddingCategoryConstantName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string productBiddingCategoryConstantName, out ProductBiddingCategoryConstantName result) => TryParse(productBiddingCategoryConstantName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ProductBiddingCategoryConstantName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="productBiddingCategoryConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ProductBiddingCategoryConstantName"/>, or <c>null</c> if /// parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string productBiddingCategoryConstantName, bool allowUnparsed, out ProductBiddingCategoryConstantName result) { gax::GaxPreconditions.CheckNotNull(productBiddingCategoryConstantName, nameof(productBiddingCategoryConstantName)); gax::TemplatedResourceName resourceName; if (s_countryCodeLevelId.TryParseName(productBiddingCategoryConstantName, out resourceName)) { string[] split0 = ParseSplitHelper(resourceName[0], new char[] { '~', '~', }); if (split0 == null) { result = null; return false; } result = FromCountryCodeLevelId(split0[0], split0[1], split0[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(productBiddingCategoryConstantName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private ProductBiddingCategoryConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string countryCodeId = null, string idId = null, string levelId = null) { Type = type; UnparsedResource = unparsedResourceName; CountryCodeId = countryCodeId; IdId = idId; LevelId = levelId; } /// <summary> /// Constructs a new instance of a <see cref="ProductBiddingCategoryConstantName"/> class from the component /// parts of pattern <c>productBiddingCategoryConstants/{country_code}~{level}~{id}</c> /// </summary> /// <param name="countryCodeId">The <c>CountryCode</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="levelId">The <c>Level</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="idId">The <c>Id</c> ID. Must not be <c>null</c> or empty.</param> public ProductBiddingCategoryConstantName(string countryCodeId, string levelId, string idId) : this(ResourceNameType.CountryCodeLevelId, countryCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(countryCodeId, nameof(countryCodeId)), levelId: gax::GaxPreconditions.CheckNotNullOrEmpty(levelId, nameof(levelId)), idId: gax::GaxPreconditions.CheckNotNullOrEmpty(idId, nameof(idId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>CountryCode</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CountryCodeId { get; } /// <summary> /// The <c>Id</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string IdId { get; } /// <summary> /// The <c>Level</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LevelId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CountryCodeLevelId: return s_countryCodeLevelId.Expand($"{CountryCodeId}~{LevelId}~{IdId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ProductBiddingCategoryConstantName); /// <inheritdoc/> public bool Equals(ProductBiddingCategoryConstantName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ProductBiddingCategoryConstantName a, ProductBiddingCategoryConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ProductBiddingCategoryConstantName a, ProductBiddingCategoryConstantName b) => !(a == b); } public partial class ProductBiddingCategoryConstant { /// <summary> /// <see cref="ProductBiddingCategoryConstantName"/>-typed view over the <see cref="ResourceName"/> resource /// name property. /// </summary> internal ProductBiddingCategoryConstantName ResourceNameAsProductBiddingCategoryConstantName { get => string.IsNullOrEmpty(ResourceName) ? null : ProductBiddingCategoryConstantName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="ProductBiddingCategoryConstantName"/>-typed view over the /// <see cref="ProductBiddingCategoryConstantParent"/> resource name property. /// </summary> internal ProductBiddingCategoryConstantName ProductBiddingCategoryConstantParentAsProductBiddingCategoryConstantName { get => string.IsNullOrEmpty(ProductBiddingCategoryConstantParent) ? null : ProductBiddingCategoryConstantName.Parse(ProductBiddingCategoryConstantParent, allowUnparsed: true); set => ProductBiddingCategoryConstantParent = value?.ToString() ?? ""; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text.RegularExpressions; using System.Windows.Data; using PoESkillTree.Localization; using PoESkillTree.ViewModels; using Attribute = PoESkillTree.ViewModels.Attribute; namespace PoESkillTree.Utils.Converter { [ValueConversion(typeof (string), typeof (AttributeGroup))] //list view sorter here public class GroupStringConverter : IValueConverter, IComparer { public Dictionary<string, AttributeGroup> AttributeGroups = new Dictionary<string, AttributeGroup>(); private IList<string[]> _customGroups; private static readonly string Keystone = L10n.Message("Keystone"); private static readonly string Weapon = L10n.Message("Weapon"); private static readonly string Charges = L10n.Message("Charges"); private static readonly string Minion = L10n.Message("Minion"); private static readonly string Trap = L10n.Message("Trap"); private static readonly string Totem = L10n.Message("Totem"); private static readonly string Curse = L10n.Message("Curse"); private static readonly string Aura = L10n.Message("Aura"); private static readonly string CriticalStrike = L10n.Message("Critical Strike"); private static readonly string Shield = L10n.Message("Shield"); private static readonly string Block = L10n.Message("Block"); private static readonly string General = L10n.Message("General"); private static readonly string Defense = L10n.Message("Defense"); private static readonly string Spell = L10n.Message("Spell"); private static readonly string Flasks = L10n.Message("Flasks"); private static readonly string CoreAttributes = L10n.Message("Core Attributes"); private static readonly string MiscLabel = L10n.Message("Everything Else"); private static readonly string DecimalRegex = "\\d+(\\.\\d*)?"; private static readonly IReadOnlyList<string[]> DefaultGroups = new List<string[]> { new[] {"Share Endurance, Frenzy and Power Charges with nearby party members", Keystone}, new[] {"Critical Strike Chance with Claws", CriticalStrike}, new[] {"with Claws", Weapon}, new[] {"Endurance Charge", Charges}, new[] {"Frenzy Charge", Charges}, new[] {"Power Charge", Charges}, new[] {"Chance to Dodge", Keystone}, new[] {"Spell Damage when on Low Life", Keystone}, new[] {"Cold Damage Converted to Fire Damage", Keystone}, new[] {"Lightning Damage Converted to Fire Damage", Keystone}, new[] {"Physical Damage Converted to Fire Damage", Keystone}, new[] {"Deal no Non-Fire Damage", Keystone}, new[] {"All bonuses from an equipped Shield apply to your Minions instead of you", Keystone}, new[] {"additional totem", Keystone}, new[] {"Cannot be Stunned", Keystone}, new[] {"Cannot Evade enemy Attacks", Keystone}, new[] {"Spend Energy Shield before Mana for Skill Costs", Keystone}, new[] {"Energy Shield protects Mana instead of Life", Keystone}, new[] {"Converts all Evasion Rating to Armour. Dexterity provides no bonus to Evasion Rating", Keystone}, new[] {"Doubles chance to Evade Projectile Attacks", Keystone}, new[] {"Enemies you hit with Elemental Damage temporarily get", Keystone}, new[] {"Life Leech applies instantly", Keystone}, new[] {"Life Leech is Applied to Energy Shield instead", Keystone}, new[] {"Life Regeneration is applied to Energy Shield instead", Keystone}, new[] {"No Critical Strike Multiplier", Keystone}, new[] {"Immune to Chaos Damage", Keystone}, new[] {"Minions explode when reduced to low life", Keystone}, new[] {"Never deal Critical Strikes", Keystone}, new[] {"Projectile Attacks deal up to", Keystone}, new[] {"Removes all mana", Keystone}, new[] {"Share Endurance", Keystone}, new[] {"The increase to Physical Damage from Strength applies to Projectile Attacks as well as Melee Attacks", Keystone}, new[] {"Damage is taken from Mana before Life", Keystone}, new[] {"You can't deal Damage with your Skills yourself", Keystone}, new[] {"Your hits can't be Evaded", Keystone}, new[] {"less chance to Evade Melee Attacks", Keystone}, new[] {"more chance to Evade Projectile Attacks", Keystone}, new[] {"Maximum number of Spectres", Minion}, new[] {"Maximum number of Zombies", Minion}, new[] {"Maximum number of Skeletons", Minion}, new[] {"Minions deal", Minion}, new[] {"Minions have", Minion}, new[] {"Minions Leech", Minion}, new[] {"Minions Regenerate", Minion}, new[] {"Mine Damage", Trap}, new[] {"Trap Damage", Trap}, new[] {"Trap Duration", Trap}, new[] {"Trap Trigger Radius", Trap}, new[] {"Mine Duration", Trap}, new[] {"Mine Laying Speed", Trap}, new[] {"Trap Throwing Speed", Trap}, new[] {"Can set up to", Trap}, new[] {"Can have up to", Trap}, new[] {"Detonating Mines is Instant", Trap}, new[] {"Mine Damage Penetrates", Trap}, new[] {"Mines cannot be Damaged", Trap}, new[] {"Mine Detonation", Trap}, new[] {"Trap Damage Penetrates", Trap}, new[] {"Traps cannot be Damaged", Trap}, new[] {"throwing Traps", Trap}, new[] {"Totem Duration", Totem}, new[] {"Casting Speed for Summoning Totems", Totem}, new[] {"Totem Life", Totem}, new[] {"Totem Damage", Totem}, new[] {"Attacks used by Totems", Totem}, new[] {"Spells Cast by Totems", Totem}, new[] {"Totems gain", Totem}, new[] {"Totems have", Totem}, new[] {"Totem Placement", Totem}, new[] {"Radius of Curse", Curse}, new[] {"Curse Duration", Curse}, new[] {"Effect of your Curses", Curse}, new[] {"Radius of Curses", Curse}, new[] {"Cast Speed for Curses", Curse}, new[] {"Enemies can have 1 additional Curse", Curse}, new[] {"Mana Reserved", Aura}, new[] {"Aura", Aura}, new[] {"Auras", Aura}, new[] {"Weapon Critical Strike Chance", CriticalStrike}, new[] {"increased Critical Strike Chance", CriticalStrike}, new[] {"to Critical Strike Multiplier", CriticalStrike}, new[] {"Global Critical Strike", CriticalStrike}, new[] {"Critical Strikes with Daggers Poison the enemy", CriticalStrike}, new[] {"Knocks Back enemies if you get a Critical Strike", CriticalStrike}, new[] {"to Melee Critical Strike Multiplier", CriticalStrike}, new[] {"increased Melee Critical Strike Chance", CriticalStrike}, new[] {"Elemental Resistances while holding a Shield", Shield}, new[] {"Chance to Block Spells with Shields", Block}, new[] {"Armour from equipped Shield", Shield}, new[] {"additional Block Chance while Dual Wielding or Holding a shield", Block}, new[] {"Chance to Block with Shields", Block}, new[] {"Block and Stun Recovery", Block}, new[] {"Energy Shield from equipped Shield", Shield}, new[] {"Block Recovery", Block}, new[] {"Defences from equipped Shield", Shield}, new[] {"Damage Penetrates", General}, //needs to be here to pull into the correct tab. new[] {"reduced Extra Damage from Critical Strikes", Defense}, new[] {"Armour", Defense}, new[] {"Fortify", Defense}, new[] {"Damage with Weapons Penetrate", Weapon}, //needs to be before resistances new[] {"all Elemental Resistances", Defense}, new[] {"Chaos Resistance", Defense}, new[] {"Evasion Rating", Defense}, new[] {"Cold Resistance", Defense}, new[] {"Lightning Resistance", Defense}, new[] {"maximum Mana", Defense}, new[] {"maximum Energy Shield", Defense}, new[] {"Fire Resistance", Defense}, new[] {"maximum Life", Defense}, new[] {"Light Radius", Defense}, new[] {"Evasion Rating and Armour", Defense}, new[] {"Energy Shield Recharge", Defense}, new[] {"Life Regenerated", Defense}, new[] {"Melee Physical Damage taken reflected to Attacker", Defense}, new[] {"Avoid Elemental Status Ailments", Defense}, new[] {"Damage taken Gained as Mana when Hit", Defense}, new[] {"Avoid being Chilled", Defense}, new[] {"Avoid being Frozen", Defense}, new[] {"Avoid being Ignited", Defense}, new[] {"Avoid being Shocked", Defense}, new[] {"Avoid being Stunned", Defense}, new[] {"increased Stun Recovery", Defense}, new[] {"Mana Regeneration Rate", Defense}, new[] {"maximum Mana", Defense}, new[] {"Armour", Defense}, new[] {"Avoid interruption from Stuns while Casting", Defense}, new[] {"Movement Speed", Defense}, new[] {"Enemies Cannot Leech Life From You", Defense}, new[] {"Enemies Cannot Leech Mana From You", Defense}, new[] {"Ignore all Movement Penalties", Defense}, new[] {"Physical Damage Reduction", Defense}, new[] {"Poison on Hit", General}, new[] {"Hits that Stun Enemies have Culling Strike", General}, new[] {"increased Damage against Frozen, Shocked or Ignited Enemies", General}, new[] {"Shock Duration on enemies", General}, new[] {"Radius of Area Skills", General}, new[] {"chance to Ignite", General}, new[] {"chance to Shock", General}, new[] {"Mana Gained on Kill", General}, new[] {"Life gained on General", General}, new[] {"Burning Damage", General}, new[] {"Projectile Damage", General}, new[] {"Knock enemies Back on hit", General}, new[] {"chance to Freeze", General}, new[] {"Projectile Speed", General}, new[] {"Projectiles Piercing", General}, new[] {"Ignite Duration on enemies", General}, new[] {"Knockback Distance", General}, new[] {"Mana Cost of Skills", General}, new[] {"Chill Duration on enemies", General}, new[] {"Freeze Duration on enemies", General}, new[] {"Damage over Time", General}, new[] {"Chaos Damage", General}, new[] {"Status Ailments", General}, new[] {"increased Damage against Enemies", General}, new[] {"Enemies Become Chilled as they Unfreeze", General}, new[] {"Skill Effect Duration", General}, new[] {"Life Gained on Kill", General}, new[] {"Area Damage", General}, new[] {"Stun Threshold", General}, new[] {"Stun Duration", General}, new[] {"increased Damage against Enemies on Low Life", General}, new[] {"chance to gain Onslaught", General}, new[] {"Accuracy Rating", Weapon}, new[] {"gained for each enemy hit by your Attacks", Weapon}, new[] {"Melee Weapon and Unarmed range", Weapon}, new[] {"chance to cause Bleeding", Weapon}, new[] {"Wand Physical Damage", Weapon}, new[] {"Attack Speed", Weapon}, new[] {"Melee Damage", Weapon}, new[] {"Block Chance With Staves", Block}, new[] {"Attack Damage", Weapon}, new[] {"with Daggers", Weapon}, new[] {"Arrow Speed", Weapon}, new[] {"Cast Speed while Dual Wielding", Weapon}, new[] {"Physical Damage with Staves", Weapon}, new[] {"with Axes", Weapon}, new[] {"Physical Weapon Damage while Dual Wielding", Weapon}, new[] {"with One Handed Melee Weapons", Weapon}, new[] {"with Two Handed Melee Weapons", Weapon}, new[] {"with Maces", Weapon}, new[] {"with Bows", Weapon}, new[] {"Melee Physical Damage", Weapon}, new[] {"with Swords", Weapon}, new[] {"with Wands", Weapon}, new[] {"Cold Damage with Weapons", Weapon}, new[] {"Fire Damage with Weapons", Weapon}, new[] {"Lightning Damage with Weapons", Weapon}, new[] {"Elemental Damage with Weapons", Weapon}, new[] {"Physical Damage with Wands", Weapon}, new[] {"Damage with Wands", Weapon}, new[] {"Damage with Weapons", Weapon}, new[] {"Spell Damage", Spell}, new[] {"Elemental Damage with Spells", Spell}, new[] {"enemy chance to Block Sword Attacks", Block}, new[] {"additional Block Chance while Dual Wielding", Block}, new[] {"mana gained when you Block", Block}, new[] {"Leeched", General}, new[] {"increased Physical Damage", General}, new[] {"Elemental Damage", General}, new[] {"Jewel Socket", General}, new[] {"Cast Speed", Spell}, new[] {"Cold Damage", General}, new[] {"Fire Damage", General}, new[] {"Lightning Damage", General}, new[] {"Damage while Leeching", General}, new[] {"Damage with Poison", General}, new[] {"Flask", Flasks}, new[] {"Flasks", Flasks}, new[] {"Strength", CoreAttributes}, new[] {"Intelligence", CoreAttributes}, new[] {"Dexterity", CoreAttributes}, }; private static readonly Regex NumberRegex = new Regex(@"[0-9]*\.?[0-9]+"); private static readonly Dictionary<string, string?> AttributeToDefaultGroup = new Dictionary<string, string?>(); public GroupStringConverter() { _customGroups = new List<string[]>(); foreach (var group in DefaultGroups) { if (!AttributeGroups.ContainsKey(group[1])) { AttributeGroups.Add(group[1], new AttributeGroup(group[1])); } } foreach (var group in _customGroups) { if (!AttributeGroups.ContainsKey(group[1])) { AttributeGroups.Add(group[1], new AttributeGroup("Custom: "+group[1])); } } AttributeGroups.Add(MiscLabel, new AttributeGroup(MiscLabel)); } public void ResetGroups(IList<string[]> newgroups) { _customGroups = newgroups; AttributeGroups = new Dictionary<string, AttributeGroup>(); foreach (var group in DefaultGroups) { if (!AttributeGroups.ContainsKey(group[1])) { AttributeGroups.Add(group[1], new AttributeGroup(group[1])); } } foreach (var group in _customGroups) { if (!AttributeGroups.ContainsKey(group[1])) { AttributeGroups.Add(group[1], new AttributeGroup("Custom: " + group[1])); } } AttributeGroups.Add(MiscLabel, new AttributeGroup(MiscLabel)); } public void AddGroup(string groupname, string[] attributes) { if (!AttributeGroups.ContainsKey(groupname)) { AttributeGroups.Add(groupname, new AttributeGroup("Custom: "+groupname)); } foreach (string attr in attributes) { AddAttributeToGroup(attr, groupname); } } private void AddAttributeToGroup(string attribute, string groupname) { //Remove it from any existing custom groups first RemoveFromGroup(new string[] { attribute }); _customGroups.Insert(0, new string[] { attribute, groupname }); } public void RemoveFromGroup(string[] attributes) { List<string[]> linesToRemove = new List<string[]>(); foreach (string attr in attributes) { foreach (var gp in _customGroups) { if (NumberRegex.Replace(attr.ToLowerInvariant(), "") == NumberRegex.Replace(gp[0].ToLowerInvariant(), "")) { linesToRemove.Add(gp); } } } foreach (string[] line in linesToRemove) { _customGroups.Remove(line); } } public void DeleteGroup(string groupname) { List<string[]> linesToRemove = new List<string[]>(); foreach (var gp in _customGroups) { if (groupname.ToLower().Equals(gp[1].ToLower())) { linesToRemove.Add(gp); } } foreach (string[] line in linesToRemove) { _customGroups.Remove(line); } AttributeGroups.Remove(groupname); } public void UpdateGroupNames(List<Attribute> attrlist) { Dictionary<string, float> groupTotals = new Dictionary<string, float>(); Dictionary<string, float> groupDeltas = new Dictionary<string, float>(); foreach (var gp in _customGroups) { //only sum for the groups that need it if (!gp[1].Contains("#")) continue; foreach (Attribute attr in attrlist) { if (NumberRegex.Replace(attr.Text.ToLowerInvariant(), "") == NumberRegex.Replace(gp[0].ToLowerInvariant(), "")) { Match matchResult = Regex.Match(attr.Text, DecimalRegex); if (matchResult.Success) { if (!groupTotals.ContainsKey(gp[1])) { groupTotals.Add(gp[1], 0); groupDeltas.Add(gp[1], 0); } groupTotals[gp[1]] += (float)Decimal.Parse(matchResult.Value); if (attr.Deltas.Length > 0) groupDeltas[gp[1]] += attr.Deltas[0]; } } } } string deltaString; foreach (string key in groupTotals.Keys) { if (AttributeGroups.ContainsKey(key)) { if (groupDeltas[key] == 0) deltaString = ""; else if (groupDeltas[key] > 0) deltaString = " +" + groupDeltas[key]; else deltaString = " " + groupDeltas[key]; AttributeGroups[key].GroupName = "Custom: "+key.Replace("#", groupTotals[key].ToString())+deltaString; } } } public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { return Convert(value?.ToString() ?? ""); } private static bool TryGetDefaultGroup(string attribute, [NotNullWhen(true)] out string? group) { if (AttributeToDefaultGroup.TryGetValue(attribute, out group)) { return group != null; } foreach (var gp in DefaultGroups) { if (attribute.Contains(gp[0].ToLowerInvariant())) { group = gp[1]; AttributeToDefaultGroup[attribute] = gp[1]; return true; } } AttributeToDefaultGroup[attribute] = null; return false; } public int Compare(object? a, object? b) { string attr1 = ((Attribute?) a)?.Text ?? ""; string attr2 = ((Attribute?) b)?.Text ?? ""; var attr1Lower = attr1.ToLowerInvariant(); var attr2Lower = attr2.ToLowerInvariant(); //find the group names and types that the attributes belong in //2 = misc group, 1 = default group, 0 = custom group int group1 = 2; int group2 = 2; string attrgroup1 = MiscLabel; string attrgroup2 = MiscLabel; foreach (var gp in _customGroups) { if (NumberRegex.Replace(attr1Lower, "") == NumberRegex.Replace(gp[0].ToLowerInvariant(), "")) { attrgroup1 = gp[1]; group1 = 0; break; } } if (group1 == 2) { if (TryGetDefaultGroup(attr1Lower, out var group)) { attrgroup1 = group; group1 = 1; } } foreach (var gp in _customGroups) { if (NumberRegex.Replace(attr2Lower, "") == NumberRegex.Replace(gp[0].ToLowerInvariant(), "")) { attrgroup2 = gp[1]; group2 = 0; break; } } if (group2 == 2) { if (TryGetDefaultGroup(attr1Lower, out var group)) { attrgroup2 = group; group2 = 1; } } //primary: if group types are different, sort by group type - custom first, then defaults, then misc if (group1 != group2) { return group1 - group2; } //secondary: if groups are different, sort by group names, alphabetically, excluding numbers if (!attrgroup1.Equals(attrgroup2)) { attrgroup1 = Regex.Replace(attrgroup1, DecimalRegex, "#"); attrgroup2 = Regex.Replace(attrgroup2, DecimalRegex, "#"); return attrgroup1.CompareTo(attrgroup2); } //tertiary: if in the same group, sort by attribute string, alphabetically, excluding numbers attr1 = Regex.Replace(attr1, DecimalRegex, "#"); attr2 = Regex.Replace(attr2, DecimalRegex, "#"); return attr1.CompareTo(attr2); } public AttributeGroup Convert(string s) { foreach (var gp in _customGroups) { if (NumberRegex.Replace(s.ToLowerInvariant(), "") == NumberRegex.Replace(gp[0].ToLowerInvariant(), "")) { return AttributeGroups[gp[1]]; } } if (TryGetDefaultGroup(s.ToLowerInvariant(), out var group)) { return AttributeGroups[group]; } return AttributeGroups[MiscLabel]; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization.Formatters.Binary; public class CreateMazeDialog : EditorWindow { string MazeSizeText = "5"; // Add menu named "My Window" to the Window menu [MenuItem ("Tools/Create Map", false, 1)] static void Init () { // Get existing open window or if none, make a new one: EditorWindow Dialog = (CreateMazeDialog)ScriptableObject.CreateInstance(typeof(CreateMazeDialog)); Dialog.position = new Rect(Screen.width/2,Screen.height/2, 250, 75); Dialog.ShowPopup(); } void OnGUI () { int MazeSize; GUILayout.Label ("Create Maze", EditorStyles.boldLabel); MazeSizeText = EditorGUILayout.TextField ("Maze is Y x Y, Y = ", MazeSizeText); int.TryParse(MazeSizeText, out MazeSize); if(GUILayout.Button("Generate Maze")) { MenuItems.CreateMaze(MazeSize,true); this.Close(); } } } public class MenuItems : MonoBehaviour { [MenuItem("Tools/Import Map", false, 2)] public static PathNode[,] ImportMap(string lines = "empty") { string text; if(lines == "empty") { string path = EditorUtility.OpenFilePanel("Open Map File","","txt"); text = File.ReadAllText(path); } else { text = lines; } string[] numbers = text.Split(',',' ','\n'); List<int> maze = new List<int>(); foreach(string number in numbers) { int temp; if(Int32.TryParse(number, out temp)) { maze.Add(temp); } } PathNode[,] mapLayout = new PathNode[maze[0],maze[0]]; int j = maze[0]-1, k = 0; for(int i = maze.Count -1; i > 0; i--) { if(j < 0) { j = maze[0]-1; k++; } RoomInsert(k,j,maze[i]); mapLayout[k,j--] = new PathNode(maze[i]); } if(lines == "empty") { SaveMapPath(mapLayout); } return mapLayout; } private static void RoomInsert(int y, int x, int RoomType) { int RoomInc = 5; GameObject Room; switch(RoomType) { case 11: { Room = Instantiate(Resources.Load("Rooms/1WayRoom1", typeof(GameObject))) as GameObject; break; } case 12: { Room = Instantiate(Resources.Load("Rooms/1WayRoom2", typeof(GameObject))) as GameObject; break; } case 13: { Room = Instantiate(Resources.Load("Rooms/1WayRoom3", typeof(GameObject))) as GameObject; break; } case 14: { Room = Instantiate(Resources.Load("Rooms/1WayRoom4", typeof(GameObject))) as GameObject; break; } case 21: { Room = Instantiate(Resources.Load("Rooms/2WayRoomV", typeof(GameObject))) as GameObject; break; } case 22: { Room = Instantiate(Resources.Load("Rooms/2WayRoomH", typeof(GameObject))) as GameObject; break; } case 31: { Room = Instantiate(Resources.Load("Rooms/3WayRoom1", typeof(GameObject))) as GameObject; break; } case 32: { Room = Instantiate(Resources.Load("Rooms/3WayRoom2", typeof(GameObject))) as GameObject; break; } case 33: { Room = Instantiate(Resources.Load("Rooms/3WayRoom3", typeof(GameObject))) as GameObject; break; } case 34: { Room = Instantiate(Resources.Load("Rooms/3WayRoom4", typeof(GameObject))) as GameObject; break; } case 4: { Room = Instantiate(Resources.Load("Rooms/OpenRoom", typeof(GameObject))) as GameObject; break; } case 512: { Room = Instantiate(Resources.Load("Rooms/Corner12", typeof(GameObject))) as GameObject; break; } case 523: { Room = Instantiate(Resources.Load("Rooms/Corner23", typeof(GameObject))) as GameObject; break; } case 534: { Room = Instantiate(Resources.Load("Rooms/Corner34", typeof(GameObject))) as GameObject; break; } case 514: { Room = Instantiate(Resources.Load("Rooms/Corner14", typeof(GameObject))) as GameObject; break; } case 5: { Room = Instantiate(Resources.Load("Rooms/Closed", typeof(GameObject))) as GameObject; break; } default: { throw new System.InvalidOperationException("Invalid Room Value in File"); } } Room.transform.position = new Vector3(x*RoomInc, 0, y*RoomInc); } private static void SaveMapPath(PathNode[,] mapLayout) { FileStream SaveFile; BinaryFormatter bf = new BinaryFormatter(); string temppath = EditorApplication.currentScene; string path = "Assets/GameObjectPrefabs/Resources/Levels/"+ temppath.Substring(14,temppath.IndexOf(".unity")-14) + ".dat"; SaveFile = File.Open(path, FileMode.Create); LevelData data = new LevelData (mapLayout); bf.Serialize (SaveFile, data); //LevelData newdata = (LevelData)bf.Deserialize(SaveFile); //Deserialize file SaveFile.Close (); } public static string CreateMaze(int MazeSize, bool Save = false) { PathNode[,] MazeArray = new PathNode[MazeSize,MazeSize]; MazeArray[0,0] = new PathNode(534); MazeArray[0,MazeSize-1] = new PathNode(514); MazeArray[MazeSize-1,0] = new PathNode(523); MazeArray[MazeSize-1,MazeSize-1] = new PathNode(512); for(int i = 1; i < MazeSize-1; i++) { MazeArray[0,i] = new PathNode(34); MazeArray[MazeSize-1,i] = new PathNode(32); MazeArray[i,0] = new PathNode(33); MazeArray[i,MazeSize-1] = new PathNode(31); } for(int i = 1; i < MazeSize-1; i++) { for (int j = 1; j < MazeSize-1; j++) { MazeArray[i,j] = new PathNode(4); } } MazeRunner(ref MazeArray, MazeSize); //Create Maze with remaining spaces string[] lines = new string[MazeSize+1]; lines[0] = Convert.ToString(MazeSize); int a = 1; for(int i = MazeSize-1; i >= 0; i--) { string temp = null; for(int j = 0; j < MazeSize; j++) { if(temp == null) { temp = Convert.ToString(MazeArray[i,j].TextVal); } else { temp += Convert.ToString(MazeArray[i,j].TextVal); } if(j == MazeSize - 1) { lines[a++] = temp; } else { temp += ","; } } } if(Save) { String path = EditorUtility.SaveFilePanel("Save Maze","","","txt"); File.WriteAllLines(path,lines); } return String.Join("\n",lines); } public static void MazeRunner(ref PathNode[,] Maze, int MazeSize) { int NUMBEROFWALLS = 5; //At least 3 or larger bool LastRow = false; System.Random lottery = new System.Random(); for(int i = 0; i < MazeSize; i++) { if (i == MazeSize-1) { LastRow = true; } for (int j = 0; j < MazeSize; j++) { int choice; choice = lottery.Next(NUMBEROFWALLS); if(choice == 0) { //Right Maze[i,j].Right = false; if(j != MazeSize-1) { Maze[i,j+1].Left = false; } } else if(choice == 1 && !LastRow) { Maze[i,j].Right = false; if(j != MazeSize-1) { Maze[i,j+1].Left = false; } Maze[i,j].Up = false; if(!LastRow) { Maze[i+1,j].Down = false; } } else if(choice == 2 && !LastRow) { Maze[i,j].Up = false; if(!LastRow) { Maze[i+1,j].Down = false; } } Maze[i,j].PathType(); } } } } [Serializable] class LevelData { public PathNode[,] mapLayout; public LevelData(PathNode[,] mapData) { mapLayout = (PathNode[,]) mapData.Clone(); } }
#pragma warning disable 1587 #region Header /// /// JsonReader.cs /// Stream-like access to JSON text. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace ThirdParty.Json.LitJson { public enum JsonToken { None, ObjectStart, PropertyName, ObjectEnd, ArrayStart, ArrayEnd, Int, Long, Double, String, Boolean, Null } public class JsonReader { #region Fields private Stack<JsonToken> depth = new Stack<JsonToken>(); private int current_input; private int current_symbol; private bool end_of_json; private bool end_of_input; private Lexer lexer; private bool parser_in_string; private bool parser_return; private bool read_started; private TextReader reader; private bool reader_is_owned; private object token_value; private JsonToken token; #endregion #region Public Properties public bool AllowComments { get { return lexer.AllowComments; } set { lexer.AllowComments = value; } } public bool AllowSingleQuotedStrings { get { return lexer.AllowSingleQuotedStrings; } set { lexer.AllowSingleQuotedStrings = value; } } public bool EndOfInput { get { return end_of_input; } } public bool EndOfJson { get { return end_of_json; } } public JsonToken Token { get { return token; } } public object Value { get { return token_value; } } #endregion #region Constructors public JsonReader (string json_text) : this (new StringReader (json_text), true) { } public JsonReader (TextReader reader) : this (reader, false) { } private JsonReader (TextReader reader, bool owned) { if (reader == null) throw new ArgumentNullException ("reader"); parser_in_string = false; parser_return = false; read_started = false; lexer = new Lexer (reader); end_of_input = false; end_of_json = false; this.reader = reader; reader_is_owned = owned; } #endregion #region Private Methods private void ProcessNumber (string number) { if (number.IndexOf ('.') != -1 || number.IndexOf ('e') != -1 || number.IndexOf ('E') != -1) { double n_double; if (Double.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_double)) { token = JsonToken.Double; token_value = n_double; return; } } int n_int32; if (Int32.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_int32)) { token = JsonToken.Int; token_value = n_int32; return; } long n_int64; if (Int64.TryParse(number, NumberStyles.Any, CultureInfo.InvariantCulture, out n_int64)) { token = JsonToken.Long; token_value = n_int64; return; } // Shouldn't happen, but just in case, return something token = JsonToken.Int; token_value = 0; } private void ProcessSymbol () { if (current_symbol == '[') { token = JsonToken.ArrayStart; parser_return = true; } else if (current_symbol == ']') { token = JsonToken.ArrayEnd; parser_return = true; } else if (current_symbol == '{') { token = JsonToken.ObjectStart; parser_return = true; } else if (current_symbol == '}') { token = JsonToken.ObjectEnd; parser_return = true; } else if (current_symbol == '"') { if (parser_in_string) { parser_in_string = false; parser_return = true; } else { if (token == JsonToken.None) token = JsonToken.String; parser_in_string = true; } } else if (current_symbol == (int) ParserToken.CharSeq) { token_value = lexer.StringValue; } else if (current_symbol == (int) ParserToken.False) { token = JsonToken.Boolean; token_value = false; parser_return = true; } else if (current_symbol == (int) ParserToken.Null) { token = JsonToken.Null; parser_return = true; } else if (current_symbol == (int) ParserToken.Number) { ProcessNumber (lexer.StringValue); parser_return = true; } else if (current_symbol == (int) ParserToken.Pair) { token = JsonToken.PropertyName; } else if (current_symbol == (int) ParserToken.True) { token = JsonToken.Boolean; token_value = true; parser_return = true; } } private bool ReadToken () { if (end_of_input) return false; lexer.NextToken (); if (lexer.EndOfInput) { Close (); return false; } current_input = lexer.Token; return true; } #endregion public void Close () { if (end_of_input) return; end_of_input = true; end_of_json = true; reader = null; } public bool Read() { if (end_of_input) return false; if (end_of_json) { end_of_json = false; } token = JsonToken.None; parser_in_string = false; parser_return = false; // Check if the first read call. If so then do an extra ReadToken because Read assumes that the previous // call to Read has already called ReadToken. if (!read_started) { read_started = true; if (!ReadToken()) return false; } do { current_symbol = current_input; ProcessSymbol(); if (parser_return) { if (this.token == JsonToken.ObjectStart || this.token == JsonToken.ArrayStart) { depth.Push(this.token); } else if (this.token == JsonToken.ObjectEnd || this.token == JsonToken.ArrayEnd) { // Clear out property name if is on top. This could happen if the value for the property was null. if (depth.Peek() == JsonToken.PropertyName) depth.Pop(); // Pop the opening token for this closing token. Make sure it is of the right type otherwise // the document is invalid. var opening = depth.Pop(); if (this.token == JsonToken.ObjectEnd && opening != JsonToken.ObjectStart) throw new JsonException("Error: Current token is ObjectEnd which does not match the opening " + opening.ToString()); if (this.token == JsonToken.ArrayEnd && opening != JsonToken.ArrayStart) throw new JsonException("Error: Current token is ArrayEnd which does not match the opening " + opening.ToString()); // If that last element is popped then we reached the end of the JSON object. if (depth.Count == 0) { end_of_json = true; } } // If the top of the stack is an object start and the next read is a string then it must be a property name // to add to the stack. else if (depth.Count > 0 && depth.Peek() != JsonToken.PropertyName && this.token == JsonToken.String && depth.Peek() == JsonToken.ObjectStart) { this.token = JsonToken.PropertyName; depth.Push(this.token); } if ( (this.token == JsonToken.ObjectEnd || this.token == JsonToken.ArrayEnd || this.token == JsonToken.String || this.token == JsonToken.Boolean || this.token == JsonToken.Double || this.token == JsonToken.Int || this.token == JsonToken.Long || this.token == JsonToken.Null || this.token == JsonToken.String )) { // If we found a value but we are not in an array or object then the document is an invalid json document. if (depth.Count == 0) { if (this.token != JsonToken.ArrayEnd && this.token != JsonToken.ObjectEnd) { throw new JsonException("Value without enclosing object or array"); } } // The valud of the property has been processed so pop the property name from the stack. else if (depth.Peek() == JsonToken.PropertyName) { depth.Pop(); } } // Read the next token that will be processed the next time the Read method is called. // This is done ahead of the next read so we can detect if we are at the end of the json document. // Otherwise EndOfInput would not return true until an attempt to read was made. if (!ReadToken() && depth.Count != 0) throw new JsonException("Incomplete JSON Document"); return true; } } while (ReadToken()); // If we reached the end of the document but there is still elements left in the depth stack then // the document is invalid JSON. if (depth.Count != 0) throw new JsonException("Incomplete JSON Document"); end_of_input = true; return false; } } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_7_6 : EcmaTest { [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8NullNull() { RunTest(@"TestCases/ch07/7.6/7.6-1.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8NewNew() { RunTest(@"TestCases/ch07/7.6/7.6-10.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8VarVar() { RunTest(@"TestCases/ch07/7.6/7.6-11.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8TryTry() { RunTest(@"TestCases/ch07/7.6/7.6-12.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8CatchCatch() { RunTest(@"TestCases/ch07/7.6/7.6-13.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8FinallyFinally() { RunTest(@"TestCases/ch07/7.6/7.6-14.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ReturnReturn() { RunTest(@"TestCases/ch07/7.6/7.6-15.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8VoidVoid() { RunTest(@"TestCases/ch07/7.6/7.6-16.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ContinueContinue() { RunTest(@"TestCases/ch07/7.6/7.6-17.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ForFor() { RunTest(@"TestCases/ch07/7.6/7.6-18.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8SwitchSwitch() { RunTest(@"TestCases/ch07/7.6/7.6-19.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8TrueTrue() { RunTest(@"TestCases/ch07/7.6/7.6-2.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8WhileWhile() { RunTest(@"TestCases/ch07/7.6/7.6-20.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8DebuggerDebugger() { RunTest(@"TestCases/ch07/7.6/7.6-21.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8FunctionFunction() { RunTest(@"TestCases/ch07/7.6/7.6-22.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ThisThis() { RunTest(@"TestCases/ch07/7.6/7.6-23.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8IfIf() { RunTest(@"TestCases/ch07/7.6/7.6-24.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8WithWith() { RunTest(@"TestCases/ch07/7.6/7.6-25.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8DefaultDefault() { RunTest(@"TestCases/ch07/7.6/7.6-26.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ThrowThrow() { RunTest(@"TestCases/ch07/7.6/7.6-27.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8InIn() { RunTest(@"TestCases/ch07/7.6/7.6-28.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8DeleteDelete() { RunTest(@"TestCases/ch07/7.6/7.6-29.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8FalseFalse() { RunTest(@"TestCases/ch07/7.6/7.6-3.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ClassClass() { RunTest(@"TestCases/ch07/7.6/7.6-30.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ExtendsExtends() { RunTest(@"TestCases/ch07/7.6/7.6-31.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8EnumEnum() { RunTest(@"TestCases/ch07/7.6/7.6-32.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8SuperSuper() { RunTest(@"TestCases/ch07/7.6/7.6-33.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ConstConst() { RunTest(@"TestCases/ch07/7.6/7.6-34.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ExportExport() { RunTest(@"TestCases/ch07/7.6/7.6-35.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ImportImport() { RunTest(@"TestCases/ch07/7.6/7.6-36.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8BreakBreak() { RunTest(@"TestCases/ch07/7.6/7.6-4.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8CaseCase() { RunTest(@"TestCases/ch07/7.6/7.6-5.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8InstanceofInstanceof() { RunTest(@"TestCases/ch07/7.6/7.6-6.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8TypeofTypeof() { RunTest(@"TestCases/ch07/7.6/7.6-7.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8DoDo() { RunTest(@"TestCases/ch07/7.6/7.6-8.js", false); } [Fact] [Trait("Category", "7.6")] public void SyntaxerrorExpectedReservedWordsUsedAsIdentifierNamesInUtf8ElseElseNull() { RunTest(@"TestCases/ch07/7.6/7.6-9.js", false); } [Fact] [Trait("Category", "7.6")] public void Identifierstart() { RunTest(@"TestCases/ch07/7.6/S7.6_A1.2_T1.js", false); } [Fact] [Trait("Category", "7.6")] public void Identifierstart2() { RunTest(@"TestCases/ch07/7.6/S7.6_A1.2_T2.js", false); } [Fact] [Trait("Category", "7.6")] public void Identifierstart3() { RunTest(@"TestCases/ch07/7.6/S7.6_A1.2_T3.js", false); } [Fact] [Trait("Category", "7.6")] public void Identifierstart4() { RunTest(@"TestCases/ch07/7.6/S7.6_A1.3_T1.js", false); } [Fact] [Trait("Category", "7.6")] public void Identifierstart5() { RunTest(@"TestCases/ch07/7.6/S7.6_A1.3_T2.js", false); } [Fact] [Trait("Category", "7.6")] public void Identifierstart6() { RunTest(@"TestCases/ch07/7.6/S7.6_A1.3_T3.js", false); } [Fact] [Trait("Category", "7.6")] public void IdentifierpartIdentifierstart() { RunTest(@"TestCases/ch07/7.6/S7.6_A2.1_T1.js", false); } [Fact] [Trait("Category", "7.6")] public void IdentifierpartIdentifierstart2() { RunTest(@"TestCases/ch07/7.6/S7.6_A2.1_T2.js", false); } [Fact] [Trait("Category", "7.6")] public void IdentifierpartIdentifierstart3() { RunTest(@"TestCases/ch07/7.6/S7.6_A2.1_T3.js", false); } [Fact] [Trait("Category", "7.6")] public void IdentifierpartIdentifierstart4() { RunTest(@"TestCases/ch07/7.6/S7.6_A2.1_T4.js", false); } [Fact] [Trait("Category", "7.6")] public void CorrectInterpretationOfEnglishAlphabet() { RunTest(@"TestCases/ch07/7.6/S7.6_A4.1_T1.js", false); } [Fact] [Trait("Category", "7.6")] public void CorrectInterpretationOfEnglishAlphabet2() { RunTest(@"TestCases/ch07/7.6/S7.6_A4.1_T2.js", false); } [Fact] [Trait("Category", "7.6")] public void CorrectInterpretationOfRussianAlphabet() { RunTest(@"TestCases/ch07/7.6/S7.6_A4.2_T1.js", false); } [Fact] [Trait("Category", "7.6")] public void CorrectInterpretationOfRussianAlphabet2() { RunTest(@"TestCases/ch07/7.6/S7.6_A4.2_T2.js", false); } [Fact] [Trait("Category", "7.6")] public void CorrectInterpretationOfDigits() { RunTest(@"TestCases/ch07/7.6/S7.6_A4.3_T1.js", false); } } }
using System; using System.Collections; using System.Configuration; using System.Data.SqlClient; using System.Diagnostics; using System.Xml; using Rainbow.Framework.Data; using Rainbow.Framework.Helpers; using Rainbow.Framework; namespace Rainbow.Tests { [Serializable] class UpdateEntry : IComparable { /// <summary> /// IComparable.CompareTo implementation. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance is less than obj. Zero This instance is equal to obj. Greater than zero This instance is greater than obj. /// </returns> /// <exception cref="T:System.ArgumentException">obj is not the same type as this instance. </exception> public int CompareTo( object obj ) { if ( obj is UpdateEntry ) { UpdateEntry upd = ( UpdateEntry ) obj; if ( VersionNumber.CompareTo( upd.VersionNumber ) == 0 ) //Version numbers are equal { return Version.CompareTo( upd.Version ); } else { return VersionNumber.CompareTo( upd.VersionNumber ); } } throw new ArgumentException( "object is not a UpdateEntry" ); } public int VersionNumber = 0; public string Version = string.Empty; public ArrayList scriptNames = new ArrayList(); public DateTime Date; public ArrayList Modules = new ArrayList(); public bool Apply = false; } public class TestHelper { #region Tear down DB public static void TearDownDB() { RunDataScript( "TearDown.sql" ); } #endregion #region Recreate DB based off last Update static UpdateEntry[] scriptsList; public static void RecreateDBSchema() { InitializeScriptList(); RunScriptList(); } private static void InitializeScriptList() { int dbVersion = 0; XmlDocument myDoc = new XmlDocument(); ArrayList tempScriptsList = new ArrayList(); // load the history file string myDocPath = ConfigurationManager.AppSettings["RainbowSetupScriptsPath"] + "History.xml"; myDoc.Load( myDocPath ); // get a list of <Release> nodes XmlNodeList releases = myDoc.DocumentElement.SelectNodes( "Release" ); foreach ( XmlNode release in releases ) { UpdateEntry myUpdate = new UpdateEntry(); // get the header information // we check for null to avoid exception if any of these nodes are not present if ( release.SelectSingleNode( "ID" ) != null ) { myUpdate.VersionNumber = Int32.Parse( release.SelectSingleNode( "ID/text()" ).Value ); } if ( release.SelectSingleNode( "Version" ) != null ) { myUpdate.Version = release.SelectSingleNode( "Version/text()" ).Value; } if ( release.SelectSingleNode( "Script" ) != null ) { myUpdate.scriptNames.Add( release.SelectSingleNode( "Script/text()" ).Value ); } if ( release.SelectSingleNode( "Date" ) != null ) { myUpdate.Date = DateTime.Parse( release.SelectSingleNode( "Date/text()" ).Value ); } //We should apply this patch if ( dbVersion < myUpdate.VersionNumber ) { //Rainbow.Framework.Helpers.LogHelper.Logger.Log(Rainbow.Framework.Site.Configuration.LogLevel.Debug, "Detected version to apply: " + myUpdate.Version); myUpdate.Apply = true; // get a list of <Installer> nodes XmlNodeList installers = release.SelectNodes( "Modules/Installer/text()" ); // iterate over the <Installer> Nodes (in original document order) // (we can do this because XmlNodeList implements IEnumerable) foreach ( XmlNode installer in installers ) { //and build an ArrayList of the scripts... myUpdate.Modules.Add( installer.Value ); //Rainbow.Framework.Helpers.LogHelper.Logger.Log(Rainbow.Framework.Site.Configuration.LogLevel.Debug, "Detected module to install: " + installer.Value); } // get a <Script> node, if any XmlNodeList sqlScripts = release.SelectNodes( "Scripts/Script/text()" ); // iterate over the <Installer> Nodes (in original document order) // (we can do this because XmlNodeList implements IEnumerable) foreach ( XmlNode sqlScript in sqlScripts ) { //and build an ArrayList of the scripts... myUpdate.scriptNames.Add( sqlScript.Value ); //Rainbow.Framework.Helpers.LogHelper.Logger.Log(Rainbow.Framework.Site.Configuration.LogLevel.Debug, "Detected script to run: " + sqlScript.Value); } tempScriptsList.Add( myUpdate ); } } //If we have some version to apply... if ( tempScriptsList.Count > 0 ) { scriptsList = ( UpdateEntry[] )tempScriptsList.ToArray( typeof( UpdateEntry ) ); //by Manu. Versions are sorted by version number Array.Sort( scriptsList ); //Create a flat version for binding int currentVersion = 0; foreach ( UpdateEntry myUpdate in scriptsList ) { if ( myUpdate.Apply ) { if ( currentVersion != myUpdate.VersionNumber ) { LogHelper.Logger.Log( LogLevel.Debug, "Version: " + myUpdate.VersionNumber ); currentVersion = myUpdate.VersionNumber; } foreach ( string scriptName in myUpdate.scriptNames ) { if ( scriptName.Length > 0 ) { LogHelper.Logger.Log( LogLevel.Debug, "-- Script: " + scriptName ); } } foreach ( string moduleInstaller in myUpdate.Modules ) { if ( moduleInstaller.Length > 0 ) LogHelper.Logger.Log( LogLevel.Debug, "-- Module: " + moduleInstaller + " (ignored recreating test DB)" ); } } } } } private static void RunScriptList() { XmlDocument dataScriptsDoc = new XmlDocument(); dataScriptsDoc.Load( ConfigurationManager.AppSettings["DataScriptsDefinitionFile"] ); int DatabaseVersion = 0; ArrayList errors = new ArrayList(); foreach ( UpdateEntry myUpdate in scriptsList ) { //Version check (a script may update more than one version at once) if ( myUpdate.Apply && DatabaseVersion < myUpdate.VersionNumber ) { foreach ( string scriptName in myUpdate.scriptNames ) { //It may be a module update only if ( scriptName.Length > 0 ) { string currentScriptName = scriptName; Console.WriteLine( "DB: " + DatabaseVersion + " - CURR: " + myUpdate.VersionNumber + " - Applying: " + currentScriptName ); RunRainbowScript( currentScriptName ); } } ////Installing modules //foreach ( string moduleInstaller in myUpdate.Modules ) { // string currentModuleInstaller = // Server.MapPath( System.IO.Path.Combine( Path.ApplicationRoot + "/", moduleInstaller ) ); // try { // ModuleInstall.InstallGroup( currentModuleInstaller, true ); // } // catch ( Exception ex ) { // Console.WriteLine( "Exception in UpdateDatabaseCommand installing module: " + // currentModuleInstaller, ex ); // if ( ex.InnerException != null ) { // // Display more meaningful error message if InnerException is defined // Console.WriteLine( "Exception in UpdateDatabaseCommand installing module: " + // currentModuleInstaller, ex.InnerException ); // errors.Add( "Exception in UpdateDatabaseCommand installing module: " + // currentModuleInstaller + "<br/>" + ex.InnerException.Message + "<br/>" + // ex.InnerException.StackTrace ); // } // else { // Console.WriteLine( "Exception in UpdateDatabaseCommand installing module: " + // currentModuleInstaller, ex ); // errors.Add( ex.Message ); // } // } //} if ( Equals( errors.Count, 0 ) ) { //Update db with version DatabaseVersion = myUpdate.VersionNumber; Console.WriteLine( "Version number: " + myUpdate.Version + " applied successfully." ); // apply any additional data scripts after applying version XmlNodeList dataScriptsNodeList = dataScriptsDoc.SelectNodes( "/SqlDataScripts/SqlDataScript[@runAfterVersion=" + myUpdate.VersionNumber + "]" ); foreach ( XmlNode node in dataScriptsNodeList ) { Console.WriteLine( "Running data script " + node.Attributes["fileName"].Value + " after version " + myUpdate.VersionNumber ); RunDataScript( node.Attributes["fileName"].Value ); } //Mark this update as done Console.WriteLine( "Sucessfully applied version: " + myUpdate.Version ); } } else { Console.WriteLine( "DB: " + DatabaseVersion + " - CURR: " + myUpdate.VersionNumber + " - Skipping: " + myUpdate.Version ); } } } #endregion #region RunScript public static void RunRainbowScript( string strRelativeScriptPath ) { //1 - prepend full root /*NOTE: we can't simply get the Executing Path of the calling assembly * because that will vary if the assembly is shadow-copied by NUnit or * other testing tools. Therefore, for simplicity in this demo, we just * get it as a App key. */ string strUTRoot = ConfigurationManager.AppSettings[ "RainbowSetupScriptsPath" ].ToString(); string strFullScriptPath = strUTRoot + strRelativeScriptPath; _RunScript( strFullScriptPath ); } public static void RunDataScript( string strRelativeScriptPath ) { //1 - prepend full root /*NOTE: we can't simply get the Executing Path of the calling assembly * because that will vary if the assembly is shadow-copied by NUnit or * other testing tools. Therefore, for simplicity in this demo, we just * get it as a App key. */ string strUTRoot = ConfigurationManager.AppSettings["DataScriptsPath"].ToString(); string strFullScriptPath = strUTRoot + strRelativeScriptPath; _RunScript( strFullScriptPath ); } private static void _RunScript( string strFullScriptPath ) { SqlConnection conn = new SqlConnection( ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString ); DBHelper.ExecuteScript( strFullScriptPath, conn ); Console.WriteLine( "Ran script " + strFullScriptPath ); } #endregion } internal struct SqlAdmin { public SqlAdmin( string strUserId, string strPassword, string strServer, string database ) { _strUserId = strUserId; _strPassword = strPassword; _strServer = strServer; _database = database; } private string _strUserId; public string UserId { get { return _strUserId; } } private string _strPassword; public string Password { get { return _strPassword; } } private string _strServer; public string Server { get { return _strServer; } } private string _database; public string Database { get { return _database; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; /// <summary> /// GetAbbreviatedMonthName(System.Int32) /// </summary> public class DateTimeFormatInfoGetAbbreviatedMonthName { #region Private Fields private const int c_MIN_MONTH_VALUE = 1; private const int c_MAX_MONTH_VALUE = 13; #endregion #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call GetAbbreviatedDayName on default invariant DateTimeFormatInfo instance"); try { DateTimeFormatInfo info = CultureInfo.InvariantCulture.DateTimeFormat; string[] expected = new string[] { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "", }; retVal = VerificationHelper(info, expected, "001.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call GetAbbreviatedDayName on en-us culture DateTimeFormatInfo instance"); try { DateTimeFormatInfo info = new CultureInfo("en-us").DateTimeFormat; string[] expected = new string[] { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "", }; retVal = VerificationHelper(info, expected, "002.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call GetAbbreviatedDayName on fr-FR culture DateTimeFormatInfo instance"); try { DateTimeFormatInfo info = new CultureInfo("fr-FR").DateTimeFormat; string[] expected = new string[] { "", "janv.", "f\u00e9vr.", "mars", "avr.", "mai", "juin", "juil.", "ao\u00fbt", "sept.", "oct.", "nov.", "d\u00e9c.", "", }; retVal = VerificationHelper(info, expected, "003.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Call GetAbbreviatedDayName on DateTimeFormatInfo instance created from ctor"); try { DateTimeFormatInfo info = new DateTimeFormatInfo(); string[] expected = new string[] { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "", }; retVal = VerificationHelper(info, expected, "004.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: ArgumentOutOfRangeException should be thrown when dayofweek is not a valid System.DayOfWeek value. "); try { DateTimeFormatInfo info = new DateTimeFormatInfo(); info.GetAbbreviatedMonthName(c_MIN_MONTH_VALUE - 1); TestLibrary.TestFramework.LogError("101.1", "ArgumentOutOfRangeException is not thrown"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.2", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } try { DateTimeFormatInfo info = new DateTimeFormatInfo(); info.GetAbbreviatedMonthName(c_MAX_MONTH_VALUE + 1); TestLibrary.TestFramework.LogError("101.3", "ArgumentOutOfRangeException is not thrown"); retVal = false; } catch (ArgumentOutOfRangeException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("101.4", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { DateTimeFormatInfoGetAbbreviatedMonthName test = new DateTimeFormatInfoGetAbbreviatedMonthName(); TestLibrary.TestFramework.BeginTestCase("DateTimeFormatInfoGetAbbreviatedMonthName"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private bool VerificationHelper(DateTimeFormatInfo info, string[] expected, string errorno) { bool retval = true; for (int i = c_MIN_MONTH_VALUE; i <= c_MAX_MONTH_VALUE; ++i) { string actual = info.GetAbbreviatedMonthName(i); if (actual != expected[i]) { TestLibrary.TestFramework.LogError(errorno, "GetAbbreviatedDayName returns wrong value"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] i = " + i + ", expected[i] = " + expected[i] + ", actual = " + actual); retval = false; } } return retval; } #endregion }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; namespace System.Management.Automation.Runspaces { internal sealed class DotNetTypes_Format_Ps1Xml { internal static IEnumerable<ExtendedTypeDefinition> GetFormatData() { yield return new ExtendedTypeDefinition( "System.CodeDom.Compiler.CompilerError", ViewsOf_System_CodeDom_Compiler_CompilerError()); yield return new ExtendedTypeDefinition( "System.Reflection.Assembly", ViewsOf_System_Reflection_Assembly()); yield return new ExtendedTypeDefinition( "System.Reflection.AssemblyName", ViewsOf_System_Reflection_AssemblyName()); yield return new ExtendedTypeDefinition( "System.Globalization.CultureInfo", ViewsOf_System_Globalization_CultureInfo()); yield return new ExtendedTypeDefinition( "System.Diagnostics.FileVersionInfo", ViewsOf_System_Diagnostics_FileVersionInfo()); yield return new ExtendedTypeDefinition( "System.Diagnostics.EventLogEntry", ViewsOf_System_Diagnostics_EventLogEntry()); yield return new ExtendedTypeDefinition( "System.Diagnostics.EventLog", ViewsOf_System_Diagnostics_EventLog()); yield return new ExtendedTypeDefinition( "System.Version", ViewsOf_System_Version()); yield return new ExtendedTypeDefinition( "System.Version#IncludeLabel", ViewsOf_System_Version_With_Label()); yield return new ExtendedTypeDefinition( "System.Management.Automation.SemanticVersion", ViewsOf_Semantic_Version_With_Label()); yield return new ExtendedTypeDefinition( "System.Drawing.Printing.PrintDocument", ViewsOf_System_Drawing_Printing_PrintDocument()); yield return new ExtendedTypeDefinition( "System.Collections.DictionaryEntry", ViewsOf_System_Collections_DictionaryEntry()); yield return new ExtendedTypeDefinition( "System.Diagnostics.ProcessModule", ViewsOf_System_Diagnostics_ProcessModule()); yield return new ExtendedTypeDefinition( "System.Diagnostics.Process", ViewsOf_System_Diagnostics_Process()); yield return new ExtendedTypeDefinition( "System.Diagnostics.Process#IncludeUserName", ViewsOf_System_Diagnostics_Process_IncludeUserName()); yield return new ExtendedTypeDefinition( "System.DirectoryServices.DirectoryEntry", ViewsOf_System_DirectoryServices_DirectoryEntry()); yield return new ExtendedTypeDefinition( "System.Management.Automation.PSSnapInInfo", ViewsOf_System_Management_Automation_PSSnapInInfo()); yield return new ExtendedTypeDefinition( "System.ServiceProcess.ServiceController", ViewsOf_System_ServiceProcess_ServiceController()); yield return new ExtendedTypeDefinition( "System.TimeSpan", ViewsOf_System_TimeSpan()); yield return new ExtendedTypeDefinition( "System.AppDomain", ViewsOf_System_AppDomain()); yield return new ExtendedTypeDefinition( "System.DateTime", ViewsOf_System_DateTime()); yield return new ExtendedTypeDefinition( "System.Security.AccessControl.ObjectSecurity", ViewsOf_System_Security_AccessControl_ObjectSecurity()); yield return new ExtendedTypeDefinition( "System.Management.ManagementClass", ViewsOf_System_Management_ManagementClass()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimClass", ViewsOf_Microsoft_Management_Infrastructure_CimClass()); yield return new ExtendedTypeDefinition( "System.Guid", ViewsOf_System_Guid()); yield return new ExtendedTypeDefinition( @"System.Management.ManagementObject#root\cimv2\Win32_PingStatus", ViewsOf_System_Management_ManagementObject_root_cimv2_Win32_PingStatus()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PingStatus", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_PingStatus()); yield return new ExtendedTypeDefinition( @"System.Management.ManagementObject#root\default\SystemRestore", ViewsOf_System_Management_ManagementObject_root_default_SystemRestore()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/default/SystemRestore", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_default_SystemRestore()); yield return new ExtendedTypeDefinition( @"System.Management.ManagementObject#root\cimv2\Win32_QuickFixEngineering", ViewsOf_System_Management_ManagementObject_root_cimv2_Win32_QuickFixEngineering()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_QuickFixEngineering", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_QuickFixEngineering()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Process", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Process()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_ComputerSystem", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_ComputerSystem()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/WIN32_PROCESSOR", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_WIN32_PROCESSOR()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/WIN32_DCOMApplication", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_WIN32_DCOMApplication()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/WIN32_DESKTOP", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_WIN32_DESKTOP()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/WIN32_DESKTOPMONITOR", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_WIN32_DESKTOPMONITOR()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_DeviceMemoryAddress", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_DeviceMemoryAddress()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_DiskDrive", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_DiskDrive()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_DiskQuota", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_DiskQuota()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Environment", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Environment()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Directory", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Directory()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Group", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Group()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_IDEController", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_IDEController()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_IRQResource", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_IRQResource()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_ScheduledJob", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_ScheduledJob()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_LoadOrderGroup", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_LoadOrderGroup()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_LogicalDisk", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_LogicalDisk()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_LogonSession", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_LogonSession()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PhysicalMemoryArray", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_PhysicalMemoryArray()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_OnBoardDevice", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_OnBoardDevice()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_OperatingSystem", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_OperatingSystem()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_DiskPartition", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_DiskPartition()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PortConnector", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_PortConnector()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_QuotaSetting", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_QuotaSetting()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_SCSIController", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_SCSIController()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Service", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Service()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_UserAccount", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_UserAccount()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_NetworkProtocol", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_NetworkProtocol()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_NetworkAdapter", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_NetworkAdapter()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_NetworkAdapterConfiguration", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_NetworkAdapterConfiguration()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_NTDomain", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_NTDomain()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Printer", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Printer()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PrintJob", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_PrintJob()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Product", ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Product()); yield return new ExtendedTypeDefinition( "System.Net.NetworkCredential", ViewsOf_System_Net_NetworkCredential()); yield return new ExtendedTypeDefinition( "System.Management.Automation.PSMethod", ViewsOf_System_Management_Automation_PSMethod()); yield return new ExtendedTypeDefinition( "Microsoft.Management.Infrastructure.CimInstance#__PartialCIMInstance", ViewsOf_Microsoft_Management_Infrastructure_CimInstance___PartialCIMInstance()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_CodeDom_Compiler_CompilerError() { yield return new FormatViewDefinition("System.CodeDom.Compiler.CompilerError", ListControl.Create() .StartEntry() .AddItemProperty(@"ErrorText") .AddItemProperty(@"Line") .AddItemProperty(@"Column") .AddItemProperty(@"ErrorNumber") .AddItemProperty(@"LineSource") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Reflection_Assembly() { yield return new FormatViewDefinition("System.Reflection.Assembly", TableControl.Create() .AddHeader(label: "GAC", width: 6) .AddHeader(label: "Version", width: 14) .AddHeader() .StartRowDefinition() .AddPropertyColumn("GlobalAssemblyCache") .AddPropertyColumn("ImageRuntimeVersion") .AddPropertyColumn("Location") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("System.Reflection.Assembly", ListControl.Create() .StartEntry() .AddItemProperty(@"CodeBase") .AddItemProperty(@"EntryPoint") .AddItemProperty(@"EscapedCodeBase") .AddItemProperty(@"FullName") .AddItemProperty(@"GlobalAssemblyCache") .AddItemProperty(@"HostContext") .AddItemProperty(@"ImageFileMachine") .AddItemProperty(@"ImageRuntimeVersion") .AddItemProperty(@"Location") .AddItemProperty(@"ManifestModule") .AddItemProperty(@"MetadataToken") .AddItemProperty(@"PortableExecutableKind") .AddItemProperty(@"ReflectionOnly") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Reflection_AssemblyName() { yield return new FormatViewDefinition("System.Reflection.AssemblyName", TableControl.Create() .AddHeader(width: 14) .AddHeader() .StartRowDefinition() .AddPropertyColumn("Version") .AddPropertyColumn("Name") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Globalization_CultureInfo() { yield return new FormatViewDefinition("System.Globalization.CultureInfo", TableControl.Create() .AddHeader(width: 16) .AddHeader(width: 16) .AddHeader() .StartRowDefinition() .AddPropertyColumn("LCID") .AddPropertyColumn("Name") .AddPropertyColumn("DisplayName") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Diagnostics_FileVersionInfo() { yield return new FormatViewDefinition("System.Diagnostics.FileVersionInfo", TableControl.Create() .AddHeader(width: 16) .AddHeader(width: 16) .AddHeader() .StartRowDefinition() .AddPropertyColumn("ProductVersion") .AddPropertyColumn("FileVersion") .AddPropertyColumn("FileName") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("System.Diagnostics.FileVersionInfo", ListControl.Create() .StartEntry() .AddItemProperty(@"OriginalFileName") .AddItemProperty(@"FileDescription") .AddItemProperty(@"ProductName") .AddItemProperty(@"Comments") .AddItemProperty(@"CompanyName") .AddItemProperty(@"FileName") .AddItemProperty(@"FileVersion") .AddItemProperty(@"ProductVersion") .AddItemProperty(@"IsDebug") .AddItemProperty(@"IsPatched") .AddItemProperty(@"IsPreRelease") .AddItemProperty(@"IsPrivateBuild") .AddItemProperty(@"IsSpecialBuild") .AddItemProperty(@"Language") .AddItemProperty(@"LegalCopyright") .AddItemProperty(@"LegalTrademarks") .AddItemProperty(@"PrivateBuild") .AddItemProperty(@"SpecialBuild") .AddItemProperty(@"FileVersionRaw") .AddItemProperty(@"ProductVersionRaw") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Diagnostics_EventLogEntry() { yield return new FormatViewDefinition("System.Diagnostics.EventLogEntry", TableControl.Create() .AddHeader(Alignment.Right, label: "Index", width: 8) .AddHeader(label: "Time", width: 13) .AddHeader(label: "EntryType", width: 11) .AddHeader(label: "Source", width: 20) .AddHeader(Alignment.Right, label: "InstanceID", width: 12) .AddHeader(label: "Message") .StartRowDefinition() .AddPropertyColumn("Index") .AddPropertyColumn("TimeGenerated", format: "{0:MMM} {0:dd} {0:HH}:{0:mm}") .AddScriptBlockColumn("$_.EntryType") .AddPropertyColumn("Source") .AddPropertyColumn("InstanceID") .AddPropertyColumn("Message") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("System.Diagnostics.EventLogEntry", ListControl.Create() .StartEntry() .AddItemProperty(@"Index") .AddItemProperty(@"EntryType") .AddItemProperty(@"InstanceID") .AddItemProperty(@"Message") .AddItemProperty(@"Category") .AddItemProperty(@"CategoryNumber") .AddItemProperty(@"ReplacementStrings") .AddItemProperty(@"Source") .AddItemProperty(@"TimeGenerated") .AddItemProperty(@"TimeWritten") .AddItemProperty(@"UserName") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Diagnostics_EventLog() { yield return new FormatViewDefinition("System.Diagnostics.EventLog", TableControl.Create() .AddHeader(Alignment.Right, label: "Max(K)", width: 8) .AddHeader(Alignment.Right, label: "Retain", width: 6) .AddHeader(label: "OverflowAction", width: 18) .AddHeader(Alignment.Right, label: "Entries", width: 10) .AddHeader(label: "Log") .StartRowDefinition() .AddScriptBlockColumn("$_.MaximumKilobytes.ToString('N0')") .AddPropertyColumn("MinimumRetentionDays") .AddPropertyColumn("OverflowAction") .AddScriptBlockColumn("$_.Entries.Count.ToString('N0')") .AddPropertyColumn("Log") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("System.Diagnostics.EventLog", ListControl.Create() .StartEntry() .AddItemProperty(@"Log") .AddItemProperty(@"EnableRaisingEvents") .AddItemProperty(@"MaximumKilobytes") .AddItemProperty(@"MinimumRetentionDays") .AddItemProperty(@"OverflowAction") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Version() { yield return new FormatViewDefinition("System.Version", TableControl.Create() .AddHeader(width: 6) .AddHeader(width: 6) .AddHeader(width: 6) .AddHeader(width: 8) .StartRowDefinition() .AddPropertyColumn("Major") .AddPropertyColumn("Minor") .AddPropertyColumn("Build") .AddPropertyColumn("Revision") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Version_With_Label() { yield return new FormatViewDefinition("System.Version", TableControl.Create() .AddHeader(width: 6) .AddHeader(width: 6) .AddHeader(width: 6) .AddHeader(width: 8) .AddHeader(width: 26) .AddHeader(width: 27) .StartRowDefinition() .AddPropertyColumn("Major") .AddPropertyColumn("Minor") .AddPropertyColumn("Build") .AddPropertyColumn("Revision") .AddPropertyColumn("PSSemVerPreReleaseLabel") .AddPropertyColumn("PSSemVerBuildLabel") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Semantic_Version_With_Label() { yield return new FormatViewDefinition("System.Management.Automation.SemanticVersion", TableControl.Create() .AddHeader(width: 6) .AddHeader(width: 6) .AddHeader(width: 6) .AddHeader(width: 15) .AddHeader(width: 11) .StartRowDefinition() .AddPropertyColumn("Major") .AddPropertyColumn("Minor") .AddPropertyColumn("Patch") .AddPropertyColumn("PreReleaseLabel") .AddPropertyColumn("BuildLabel") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Drawing_Printing_PrintDocument() { yield return new FormatViewDefinition("System.Drawing.Printing.PrintDocument", TableControl.Create() .AddHeader(width: 10) .AddHeader(width: 10) .AddHeader() .StartRowDefinition() .AddPropertyColumn("Color") .AddPropertyColumn("Duplex") .AddPropertyColumn("Name") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Collections_DictionaryEntry() { yield return new FormatViewDefinition("Dictionary", TableControl.Create() .AddHeader(width: 30) .AddHeader() .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("Value") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("System.Collections.DictionaryEntry", ListControl.Create() .StartEntry() .AddItemProperty(@"Name") .AddItemProperty(@"Value") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Diagnostics_ProcessModule() { yield return new FormatViewDefinition("ProcessModule", TableControl.Create() .AddHeader(Alignment.Right, label: "Size(K)", width: 10) .AddHeader(width: 50) .AddHeader() .StartRowDefinition() .AddScriptBlockColumn("$_.Size") .AddPropertyColumn("ModuleName") .AddPropertyColumn("FileName") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Diagnostics_Process() { yield return new FormatViewDefinition("process", TableControl.Create() .AddHeader(Alignment.Right, label: "NPM(K)", width: 7) .AddHeader(Alignment.Right, label: "PM(M)", width: 8) .AddHeader(Alignment.Right, label: "WS(M)", width: 10) .AddHeader(Alignment.Right, label: "CPU(s)", width: 10) .AddHeader(Alignment.Right, width: 7) .AddHeader(Alignment.Right, width: 3) .AddHeader() .StartRowDefinition() .AddScriptBlockColumn("[long]($_.NPM / 1024)") .AddScriptBlockColumn("\"{0:N2}\" -f [float]($_.PM / 1MB)") .AddScriptBlockColumn("\"{0:N2}\" -f [float]($_.WS / 1MB)") .AddScriptBlockColumn("\"{0:N2}\" -f [float]($_.CPU)") .AddPropertyColumn("Id") .AddPropertyColumn("SI") .AddPropertyColumn("ProcessName") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("Priority", TableControl.Create() .GroupByProperty("PriorityClass", label: "PriorityClass") .AddHeader(width: 20) .AddHeader(Alignment.Right, width: 10) .AddHeader(Alignment.Right, width: 12) .StartRowDefinition() .AddPropertyColumn("ProcessName") .AddPropertyColumn("Id") .AddPropertyColumn("WorkingSet64") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("StartTime", TableControl.Create() .GroupByScriptBlock("$_.StartTime.ToShortDateString()", label: "StartTime.ToShortDateString()") .AddHeader(width: 20) .AddHeader(Alignment.Right, width: 10) .AddHeader(Alignment.Right, width: 12) .StartRowDefinition() .AddPropertyColumn("ProcessName") .AddPropertyColumn("Id") .AddPropertyColumn("WorkingSet64") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("process", WideControl.Create() .AddPropertyEntry("ProcessName") .EndWideControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Diagnostics_Process_IncludeUserName() { yield return new FormatViewDefinition("ProcessWithUserName", TableControl.Create() .AddHeader(Alignment.Right, label: "WS(M)", width: 10) .AddHeader(Alignment.Right, label: "CPU(s)", width: 8) .AddHeader(Alignment.Right, width: 7) .AddHeader(width: 30) .AddHeader() .StartRowDefinition() .AddScriptBlockColumn("\"{0:N2}\" -f [float]($_.WS / 1MB)") .AddScriptBlockColumn("\"{0:N2}\" -f [float]($_.CPU)") .AddPropertyColumn("Id") .AddPropertyColumn("UserName") .AddPropertyColumn("ProcessName") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_DirectoryServices_DirectoryEntry() { yield return new FormatViewDefinition("DirectoryEntry", ListControl.Create() .StartEntry() .AddItemProperty(@"distinguishedName", label: "distinguishedName") .AddItemProperty(@"path", label: "Path") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Management_Automation_PSSnapInInfo() { yield return new FormatViewDefinition("PSSnapInInfo", ListControl.Create() .StartEntry() .AddItemProperty(@"Name", label: "Name") .AddItemProperty(@"PSVersion", label: "PSVersion") .AddItemProperty(@"Description", label: "Description") .EndEntry() .EndList()); yield return new FormatViewDefinition("PSSnapInInfo", TableControl.Create() .AddHeader(Alignment.Left, label: "Name", width: 30) .AddHeader(Alignment.Left, label: "PSVersion", width: 20) .AddHeader(Alignment.Left, label: "Description", width: 30) .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("PSVersion") .AddPropertyColumn("Description") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_ServiceProcess_ServiceController() { yield return new FormatViewDefinition("service", TableControl.Create() .AddHeader(width: 8) .AddHeader(width: 18) .AddHeader(width: 38) .StartRowDefinition() .AddPropertyColumn("Status") .AddPropertyColumn("Name") .AddPropertyColumn("DisplayName") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("System.ServiceProcess.ServiceController", ListControl.Create() .StartEntry() .AddItemProperty(@"Name") .AddItemProperty(@"DisplayName") .AddItemProperty(@"Status") .AddItemProperty(@"DependentServices") .AddItemProperty(@"ServicesDependedOn") .AddItemProperty(@"CanPauseAndContinue") .AddItemProperty(@"CanShutdown") .AddItemProperty(@"CanStop") .AddItemProperty(@"ServiceType") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_TimeSpan() { yield return new FormatViewDefinition("System.TimeSpan", ListControl.Create() .StartEntry() .AddItemProperty(@"Days") .AddItemProperty(@"Hours") .AddItemProperty(@"Minutes") .AddItemProperty(@"Seconds") .AddItemProperty(@"Milliseconds") .AddItemProperty(@"Ticks") .AddItemProperty(@"TotalDays") .AddItemProperty(@"TotalHours") .AddItemProperty(@"TotalMinutes") .AddItemProperty(@"TotalSeconds") .AddItemProperty(@"TotalMilliseconds") .EndEntry() .EndList()); yield return new FormatViewDefinition("System.TimeSpan", TableControl.Create() .StartRowDefinition() .AddPropertyColumn("Days") .AddPropertyColumn("Hours") .AddPropertyColumn("Minutes") .AddPropertyColumn("Seconds") .AddPropertyColumn("Milliseconds") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("System.TimeSpan", WideControl.Create() .AddPropertyEntry("TotalMilliseconds") .EndWideControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_AppDomain() { yield return new FormatViewDefinition("System.AppDomain", ListControl.Create() .StartEntry() .AddItemProperty(@"FriendlyName") .AddItemProperty(@"Id") .AddItemProperty(@"ApplicationDescription") .AddItemProperty(@"BaseDirectory") .AddItemProperty(@"DynamicDirectory") .AddItemProperty(@"RelativeSearchPath") .AddItemProperty(@"SetupInformation") .AddItemProperty(@"ShadowCopyFiles") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_DateTime() { yield return new FormatViewDefinition("DateTime", CustomControl.Create() .StartEntry() .AddPropertyExpressionBinding(@"DateTime") .EndEntry() .EndControl()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Security_AccessControl_ObjectSecurity() { yield return new FormatViewDefinition("System.Security.AccessControl.ObjectSecurity", TableControl.Create() .AddHeader() .AddHeader() .AddHeader(label: "Access") .StartRowDefinition() .AddPropertyColumn("Path") .AddPropertyColumn("Owner") .AddPropertyColumn("AccessToString") .EndRowDefinition() .EndTable()); yield return new FormatViewDefinition("System.Security.AccessControl.ObjectSecurity", ListControl.Create() .StartEntry() .AddItemProperty(@"Path") .AddItemProperty(@"Owner") .AddItemProperty(@"Group") .AddItemProperty(@"AccessToString", label: "Access") .AddItemProperty(@"AuditToString", label: "Audit") .AddItemProperty(@"Sddl") .EndEntry() .EndList()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Management_ManagementClass() { yield return new FormatViewDefinition("System.Management.ManagementClass", TableControl.Create() .GroupByProperty("__Namespace", label: "NameSpace") .AddHeader(width: 35) .AddHeader(width: 20) .AddHeader() .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("Methods") .AddPropertyColumn("Properties") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimClass() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimClass", TableControl.Create() .GroupByScriptBlock("$_.CimSystemProperties.Namespace", label: "NameSpace") .AddHeader(label: "CimClassName", width: 35) .AddHeader(width: 20) .AddHeader() .StartRowDefinition() .AddPropertyColumn("CimClassName") .AddPropertyColumn("CimClassMethods") .AddPropertyColumn("CimClassProperties") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Guid() { yield return new FormatViewDefinition("System.Guid", TableControl.Create() .StartRowDefinition() .AddPropertyColumn("Guid") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Management_ManagementObject_root_cimv2_Win32_PingStatus() { yield return new FormatViewDefinition(@"System.Management.ManagementObject#root\cimv2\Win32_PingStatus", TableControl.Create() .AddHeader(label: "Source", width: 13) .AddHeader(label: "Destination", width: 15) .AddHeader(label: "IPV4Address", width: 16) .AddHeader(label: "IPV6Address", width: 40) .AddHeader(label: "Bytes", width: 8) .AddHeader(label: "Time(ms)", width: 9) .StartRowDefinition() .AddPropertyColumn("__Server") .AddPropertyColumn("Address") .AddPropertyColumn("IPV4Address") .AddPropertyColumn("IPV6Address") .AddPropertyColumn("BufferSize") .AddPropertyColumn("ResponseTime") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_PingStatus() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PingStatus", TableControl.Create() .AddHeader(label: "Source", width: 13) .AddHeader(label: "Destination", width: 15) .AddHeader(label: "IPV4Address", width: 16) .AddHeader(label: "IPV6Address", width: 40) .AddHeader(label: "Bytes", width: 8) .AddHeader(label: "Time(ms)", width: 9) .StartRowDefinition() .AddScriptBlockColumn(@" $sourceName = $_.PSComputerName; if($sourceName -eq ""."") {$sourceName = $env:COMPUTERNAME;} return $sourceName; ") .AddPropertyColumn("Address") .AddPropertyColumn("IPV4Address") .AddPropertyColumn("IPV6Address") .AddPropertyColumn("BufferSize") .AddPropertyColumn("ResponseTime") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Management_ManagementObject_root_default_SystemRestore() { yield return new FormatViewDefinition(@"System.Management.ManagementObject#root\default\SystemRestore", TableControl.Create() .AddHeader(label: "CreationTime", width: 22) .AddHeader(label: "Description", width: 30) .AddHeader(label: "SequenceNumber", width: 17) .AddHeader(label: "EventType", width: 17) .AddHeader(label: "RestorePointType", width: 22) .StartRowDefinition() .AddScriptBlockColumn(@" return $_.ConvertToDateTime($_.CreationTime) ") .AddPropertyColumn("Description") .AddPropertyColumn("SequenceNumber") .AddScriptBlockColumn(@" $eventType = $_.EventType; if($_.EventType -eq 100) {$eventType = ""BEGIN_SYSTEM_CHANGE"";} if($_.EventType -eq 101) {$eventType = ""END_SYSTEM_CHANGE"";} if($_.EventType -eq 102) {$eventType = ""BEGIN_NESTED_SYSTEM_CHANGE"";} if($_.EventType -eq 103) {$eventType = ""END_NESTED_SYSTEM_CHANGE"";} return $eventType; ") .AddScriptBlockColumn(@" $RestorePointType = $_.RestorePointType; if($_.RestorePointType -eq 0) { $RestorePointType = ""APPLICATION_INSTALL"";} if($_.RestorePointType -eq 1) { $RestorePointType = ""APPLICATION_UNINSTALL"";} if($_.RestorePointType -eq 10) { $RestorePointType = ""DEVICE_DRIVER_INSTALL"";} if($_.RestorePointType -eq 12) { $RestorePointType = ""MODIFY_SETTINGS"";} if($_.RestorePointType -eq 13) { $RestorePointType = ""CANCELLED_OPERATION"";} return $RestorePointType; ") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_default_SystemRestore() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/default/SystemRestore", TableControl.Create() .AddHeader(label: "CreationTime", width: 22) .AddHeader(label: "Description", width: 30) .AddHeader(label: "SequenceNumber", width: 17) .AddHeader(label: "EventType", width: 17) .AddHeader(label: "RestorePointType", width: 22) .StartRowDefinition() .AddScriptBlockColumn(@" return $_.ConvertToDateTime($_.CreationTime) ") .AddPropertyColumn("Description") .AddPropertyColumn("SequenceNumber") .AddScriptBlockColumn(@" $eventType = $_.EventType; if($_.EventType -eq 100) {$eventType = ""BEGIN_SYSTEM_CHANGE"";} if($_.EventType -eq 101) {$eventType = ""END_SYSTEM_CHANGE"";} if($_.EventType -eq 102) {$eventType = ""BEGIN_NESTED_SYSTEM_CHANGE"";} if($_.EventType -eq 103) {$eventType = ""END_NESTED_SYSTEM_CHANGE"";} return $eventType; ") .AddScriptBlockColumn(@" $RestorePointType = $_.RestorePointType; if($_.RestorePointType -eq 0) { $RestorePointType = ""APPLICATION_INSTALL"";} if($_.RestorePointType -eq 1) { $RestorePointType = ""APPLICATION_UNINSTALL"";} if($_.RestorePointType -eq 10) { $RestorePointType = ""DEVICE_DRIVER_INSTALL"";} if($_.RestorePointType -eq 12) { $RestorePointType = ""MODIFY_SETTINGS"";} if($_.RestorePointType -eq 13) { $RestorePointType = ""CANCELLED_OPERATION"";} return $RestorePointType; ") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Management_ManagementObject_root_cimv2_Win32_QuickFixEngineering() { yield return new FormatViewDefinition(@"System.Management.ManagementObject#root\cimv2\Win32_QuickFixEngineering", TableControl.Create() .AddHeader(label: "Source", width: 13) .AddHeader(label: "Description", width: 16) .AddHeader(label: "HotFixID", width: 13) .AddHeader(label: "InstalledBy", width: 20) .AddHeader(label: "InstalledOn", width: 25) .StartRowDefinition() .AddPropertyColumn("__SERVER") .AddPropertyColumn("Description") .AddPropertyColumn("HotFixID") .AddPropertyColumn("InstalledBy") .AddPropertyColumn("InstalledOn") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_QuickFixEngineering() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_QuickFixEngineering", TableControl.Create() .AddHeader(label: "Source", width: 13) .AddHeader(label: "Description", width: 16) .AddHeader(label: "HotFixID", width: 13) .AddHeader(label: "InstalledBy", width: 20) .AddHeader(label: "InstalledOn", width: 25) .StartRowDefinition() .AddPropertyColumn("ComputerName") .AddPropertyColumn("Description") .AddPropertyColumn("HotFixID") .AddPropertyColumn("InstalledBy") .AddPropertyColumn("InstalledOn") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Process() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Process", TableControl.Create() .AddHeader(label: "ProcessId") .AddHeader(label: "Name", width: 16) .AddHeader(label: "HandleCount") .AddHeader(label: "WorkingSetSize") .AddHeader(label: "VirtualSize") .StartRowDefinition() .AddPropertyColumn("ProcessId") .AddPropertyColumn("Name") .AddPropertyColumn("HandleCount") .AddPropertyColumn("WorkingSetSize") .AddPropertyColumn("VirtualSize") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_ComputerSystem() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_ComputerSystem", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "PrimaryOwnerName") .AddHeader(label: "Domain") .AddHeader(label: "TotalPhysicalMemory") .AddHeader(label: "Model") .AddHeader(label: "Manufacturer") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("PrimaryOwnerName") .AddPropertyColumn("Domain") .AddPropertyColumn("TotalPhysicalMemory") .AddPropertyColumn("Model") .AddPropertyColumn("Manufacturer") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_WIN32_PROCESSOR() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/WIN32_PROCESSOR", TableControl.Create() .AddHeader(label: "DeviceID") .AddHeader(label: "Name", width: 16) .AddHeader(label: "Caption") .AddHeader(label: "MaxClockSpeed") .AddHeader(label: "SocketDesignation") .AddHeader(label: "Manufacturer") .StartRowDefinition() .AddPropertyColumn("DeviceID") .AddPropertyColumn("Name") .AddPropertyColumn("Caption") .AddPropertyColumn("MaxClockSpeed") .AddPropertyColumn("SocketDesignation") .AddPropertyColumn("Manufacturer") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_WIN32_DCOMApplication() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/WIN32_DCOMApplication", TableControl.Create() .AddHeader(label: "AppID") .AddHeader(label: "Name", width: 16) .AddHeader(label: "InstallDate") .StartRowDefinition() .AddPropertyColumn("AppID") .AddPropertyColumn("Name") .AddPropertyColumn("InstallDate") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_WIN32_DESKTOP() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/WIN32_DESKTOP", TableControl.Create() .AddHeader(label: "SettingID") .AddHeader(label: "Name", width: 16) .AddHeader(label: "ScreenSaverActive") .AddHeader(label: "ScreenSaverSecure") .AddHeader(label: "ScreenSaverTimeout") .StartRowDefinition() .AddPropertyColumn("SettingID") .AddPropertyColumn("Name") .AddPropertyColumn("ScreenSaverActive") .AddPropertyColumn("ScreenSaverSecure") .AddPropertyColumn("ScreenSaverTimeout") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_WIN32_DESKTOPMONITOR() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/WIN32_DESKTOPMONITOR", TableControl.Create() .AddHeader(label: "DeviceID") .AddHeader(label: "Name", width: 16) .AddHeader(label: "DisplayType") .AddHeader(label: "MonitorManufacturer") .AddHeader(label: "ScreenHeight") .AddHeader(label: "ScreenWidth") .StartRowDefinition() .AddPropertyColumn("DeviceID") .AddPropertyColumn("Name") .AddPropertyColumn("DisplayType") .AddPropertyColumn("MonitorManufacturer") .AddPropertyColumn("ScreenHeight") .AddPropertyColumn("ScreenWidth") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_DeviceMemoryAddress() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_DeviceMemoryAddress", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "MemoryType") .AddHeader(label: "Status") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("MemoryType") .AddPropertyColumn("Status") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_DiskDrive() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_DiskDrive", TableControl.Create() .AddHeader(label: "DeviceID") .AddHeader(label: "Caption") .AddHeader(label: "Partitions") .AddHeader(label: "Size") .AddHeader(label: "Model") .StartRowDefinition() .AddPropertyColumn("DeviceID") .AddPropertyColumn("Caption") .AddPropertyColumn("Partitions") .AddPropertyColumn("Size") .AddPropertyColumn("Model") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_DiskQuota() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_DiskQuota", TableControl.Create() .AddHeader(label: "DiskSpaceUsed") .AddHeader(label: "Limit") .AddHeader(label: "QuotaVolume") .AddHeader(label: "User") .StartRowDefinition() .AddPropertyColumn("DiskSpaceUsed") .AddPropertyColumn("Limit") .AddPropertyColumn("QuotaVolume") .AddPropertyColumn("User") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Environment() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Environment", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "UserName") .AddHeader(label: "VariableValue") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("UserName") .AddPropertyColumn("VariableValue") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Directory() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Directory", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "Hidden") .AddHeader(label: "Archive") .AddHeader(label: "Writeable") .AddHeader(label: "LastModified") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("Hidden") .AddPropertyColumn("Archive") .AddPropertyColumn("Writeable") .AddPropertyColumn("LastModified") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Group() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Group", TableControl.Create() .AddHeader(label: "SID") .AddHeader(label: "Name", width: 16) .AddHeader(label: "Caption") .AddHeader(label: "Domain") .StartRowDefinition() .AddPropertyColumn("SID") .AddPropertyColumn("Name") .AddPropertyColumn("Caption") .AddPropertyColumn("Domain") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_IDEController() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_IDEController", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "Status") .AddHeader(label: "StatusInfo") .AddHeader(label: "ProtocolSupported") .AddHeader(label: "Manufacturer") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("Status") .AddPropertyColumn("StatusInfo") .AddPropertyColumn("ProtocolSupported") .AddPropertyColumn("Manufacturer") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_IRQResource() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_IRQResource", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "IRQNumber") .AddHeader(label: "Hardware") .AddHeader(label: "TriggerLevel") .AddHeader(label: "TriggerType") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("IRQNumber") .AddPropertyColumn("Hardware") .AddPropertyColumn("TriggerLevel") .AddPropertyColumn("TriggerType") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_ScheduledJob() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_ScheduledJob", TableControl.Create() .AddHeader(label: "JobId") .AddHeader(label: "Name", width: 16) .AddHeader(label: "Owner") .AddHeader(label: "Priority") .AddHeader(label: "Command") .StartRowDefinition() .AddPropertyColumn("JobId") .AddPropertyColumn("Name") .AddPropertyColumn("Owner") .AddPropertyColumn("Priority") .AddPropertyColumn("Command") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_LoadOrderGroup() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_LoadOrderGroup", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "GroupOrder") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("GroupOrder") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_LogicalDisk() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_LogicalDisk", TableControl.Create() .AddHeader(label: "DeviceID") .AddHeader(label: "DriveType") .AddHeader(label: "ProviderName", width: 16) .AddHeader(label: "VolumeName", width: 16) .AddHeader(label: "Size") .AddHeader(label: "FreeSpace") .StartRowDefinition() .AddPropertyColumn("DeviceID") .AddPropertyColumn("DriveType") .AddPropertyColumn("ProviderName") .AddPropertyColumn("VolumeName") .AddPropertyColumn("Size") .AddPropertyColumn("FreeSpace") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_LogonSession() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_LogonSession", TableControl.Create() .AddHeader(label: "LogonId") .AddHeader(label: "Name", width: 16) .AddHeader(label: "LogonType") .AddHeader(label: "StartTime") .AddHeader(label: "Status") .AddHeader(label: "AuthenticationPackage") .StartRowDefinition() .AddPropertyColumn("LogonId") .AddPropertyColumn("Name") .AddPropertyColumn("LogonType") .AddPropertyColumn("StartTime") .AddPropertyColumn("Status") .AddPropertyColumn("AuthenticationPackage") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_PhysicalMemoryArray() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PhysicalMemoryArray", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "MemoryDevices") .AddHeader(label: "MaxCapacity") .AddHeader(label: "Model") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("MemoryDevices") .AddPropertyColumn("MaxCapacity") .AddPropertyColumn("Model") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_OnBoardDevice() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_OnBoardDevice", TableControl.Create() .AddHeader(label: "DeviceType") .AddHeader(label: "SerialNumber") .AddHeader(label: "Enabled") .AddHeader(label: "Description") .StartRowDefinition() .AddPropertyColumn("DeviceType") .AddPropertyColumn("SerialNumber") .AddPropertyColumn("Enabled") .AddPropertyColumn("Description") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_OperatingSystem() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_OperatingSystem", TableControl.Create() .AddHeader(label: "SystemDirectory") .AddHeader(label: "Organization") .AddHeader(label: "BuildNumber") .AddHeader(label: "RegisteredUser") .AddHeader(label: "SerialNumber") .AddHeader(label: "Version") .StartRowDefinition() .AddPropertyColumn("SystemDirectory") .AddPropertyColumn("Organization") .AddPropertyColumn("BuildNumber") .AddPropertyColumn("RegisteredUser") .AddPropertyColumn("SerialNumber") .AddPropertyColumn("Version") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_DiskPartition() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_DiskPartition", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "NumberOfBlocks") .AddHeader(label: "BootPartition") .AddHeader(label: "PrimaryPartition") .AddHeader(label: "Size") .AddHeader(label: "Index") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("NumberOfBlocks") .AddPropertyColumn("BootPartition") .AddPropertyColumn("PrimaryPartition") .AddPropertyColumn("Size") .AddPropertyColumn("Index") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_PortConnector() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PortConnector", TableControl.Create() .AddHeader(label: "Tag") .AddHeader(label: "PortType") .AddHeader(label: "ConnectorType") .AddHeader(label: "SerialNumber") .AddHeader(label: "ExternalReferenceDesignator") .StartRowDefinition() .AddPropertyColumn("Tag") .AddPropertyColumn("PortType") .AddPropertyColumn("ConnectorType") .AddPropertyColumn("SerialNumber") .AddPropertyColumn("ExternalReferenceDesignator") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_QuotaSetting() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_QuotaSetting", TableControl.Create() .AddHeader(label: "SettingID") .AddHeader(label: "Caption") .AddHeader(label: "State") .AddHeader(label: "VolumePath") .AddHeader(label: "DefaultLimit") .AddHeader(label: "DefaultWarningLimit") .StartRowDefinition() .AddPropertyColumn("SettingID") .AddPropertyColumn("Caption") .AddPropertyColumn("State") .AddPropertyColumn("VolumePath") .AddPropertyColumn("DefaultLimit") .AddPropertyColumn("DefaultWarningLimit") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_SCSIController() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_SCSIController", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "DriverName", width: 16) .AddHeader(label: "Status") .AddHeader(label: "StatusInfo") .AddHeader(label: "ProtocolSupported") .AddHeader(label: "Manufacturer") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("DriverName") .AddPropertyColumn("Status") .AddPropertyColumn("StatusInfo") .AddPropertyColumn("ProtocolSupported") .AddPropertyColumn("Manufacturer") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Service() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Service", TableControl.Create() .AddHeader(label: "ProcessId") .AddHeader(label: "Name", width: 16) .AddHeader(label: "StartMode") .AddHeader(label: "State") .AddHeader(label: "Status") .AddHeader(label: "ExitCode") .StartRowDefinition() .AddPropertyColumn("ProcessId") .AddPropertyColumn("Name") .AddPropertyColumn("StartMode") .AddPropertyColumn("State") .AddPropertyColumn("Status") .AddPropertyColumn("ExitCode") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_UserAccount() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_UserAccount", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "Caption") .AddHeader(label: "AccountType") .AddHeader(label: "SID") .AddHeader(label: "Domain") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("Caption") .AddPropertyColumn("AccountType") .AddPropertyColumn("SID") .AddPropertyColumn("Domain") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_NetworkProtocol() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_NetworkProtocol", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "Caption") .AddHeader(label: "Status") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("Caption") .AddPropertyColumn("Status") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_NetworkAdapter() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_NetworkAdapter", TableControl.Create() .AddHeader(label: "DeviceID") .AddHeader(label: "Name", width: 16) .AddHeader(label: "AdapterType") .AddHeader(label: "ServiceName") .StartRowDefinition() .AddPropertyColumn("DeviceID") .AddPropertyColumn("Name") .AddPropertyColumn("AdapterType") .AddPropertyColumn("ServiceName") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_NetworkAdapterConfiguration() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_NetworkAdapterConfiguration", TableControl.Create() .AddHeader(label: "ServiceName", width: 16) .AddHeader(label: "DHCPEnabled") .AddHeader(label: "Index") .AddHeader(label: "Description") .StartRowDefinition() .AddPropertyColumn("ServiceName") .AddPropertyColumn("DHCPEnabled") .AddPropertyColumn("Index") .AddPropertyColumn("Description") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_NTDomain() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_NTDomain", TableControl.Create() .AddHeader(label: "DomainName", width: 16) .AddHeader(label: "DnsForestName") .AddHeader(label: "DomainControllerName") .StartRowDefinition() .AddPropertyColumn("DomainName") .AddPropertyColumn("DnsForestName") .AddPropertyColumn("DomainControllerName") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Printer() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Printer", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "ShareName") .AddHeader(label: "SystemName") .AddHeader(label: "PrinterState") .AddHeader(label: "PrinterStatus") .AddHeader(label: "Location") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("ShareName") .AddPropertyColumn("SystemName") .AddPropertyColumn("PrinterState") .AddPropertyColumn("PrinterStatus") .AddPropertyColumn("Location") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_PrintJob() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_PrintJob", TableControl.Create() .AddHeader(label: "JobId") .AddHeader(label: "Name", width: 16) .AddHeader(label: "JobStatus") .AddHeader(label: "Owner") .AddHeader(label: "Priority") .AddHeader(label: "Size") .AddHeader(label: "Document") .StartRowDefinition() .AddPropertyColumn("JobId") .AddPropertyColumn("Name") .AddPropertyColumn("JobStatus") .AddPropertyColumn("Owner") .AddPropertyColumn("Priority") .AddPropertyColumn("Size") .AddPropertyColumn("Document") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance_root_cimv2_Win32_Product() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#root/cimv2/Win32_Product", TableControl.Create() .AddHeader(label: "Name", width: 16) .AddHeader(label: "Caption") .AddHeader(label: "Vendor") .AddHeader(label: "Version") .AddHeader(label: "IdentifyingNumber") .StartRowDefinition() .AddPropertyColumn("Name") .AddPropertyColumn("Caption") .AddPropertyColumn("Vendor") .AddPropertyColumn("Version") .AddPropertyColumn("IdentifyingNumber") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Net_NetworkCredential() { yield return new FormatViewDefinition("System.Net.NetworkCredential", TableControl.Create() .AddHeader(label: "UserName", width: 50) .AddHeader(label: "Domain", width: 50) .StartRowDefinition() .AddPropertyColumn("UserName") .AddPropertyColumn("Domain") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_System_Management_Automation_PSMethod() { yield return new FormatViewDefinition("System.Management.Automation.PSMethod", TableControl.Create() .AddHeader(label: "OverloadDefinitions") .StartRowDefinition(wrap: true) .AddScriptBlockColumn(@" $_.OverloadDefinitions | Out-String ") .EndRowDefinition() .EndTable()); } private static IEnumerable<FormatViewDefinition> ViewsOf_Microsoft_Management_Infrastructure_CimInstance___PartialCIMInstance() { yield return new FormatViewDefinition("Microsoft.Management.Infrastructure.CimInstance#__PartialCIMInstance", CustomControl.Create() .StartEntry() .StartFrame() .AddScriptBlockExpressionBinding(@" $str = $_ | Microsoft.PowerShell.Utility\Format-List -Property * | Microsoft.PowerShell.Utility\Out-String $str ") .EndFrame() .EndEntry() .EndControl()); } } }
using System; using System.Linq; using System.Drawing; using System.ComponentModel; #if __UNIFIED__ using UIKit; #else using MonoTouch.UIKit; #endif #if __UNIFIED__ using RectangleF = CoreGraphics.CGRect; using SizeF = CoreGraphics.CGSize; using PointF = CoreGraphics.CGPoint; #else using nfloat=System.Single; using nint=System.Int32; using nuint=System.UInt32; #endif namespace Xamarin.Forms.Platform.iOS { public class PhoneMasterDetailRenderer : UIViewController, IVisualElementRenderer, IEffectControlProvider { UIView _clickOffView; UIViewController _detailController; bool _disposed; EventTracker _events; UIViewController _masterController; UIPanGestureRecognizer _panGesture; bool _presented; UIGestureRecognizer _tapGesture; VisualElementTracker _tracker; public PhoneMasterDetailRenderer() { if (!Forms.IsiOS7OrNewer) WantsFullScreenLayout = true; } IMasterDetailPageController MasterDetailPageController => Element as IMasterDetailPageController; bool Presented { get { return _presented; } set { if (_presented == value) return; _presented = value; LayoutChildren(true); if (value) AddClickOffView(); else RemoveClickOffView(); ((IElementController)Element).SetValueFromRenderer(MasterDetailPage.IsPresentedProperty, value); } } public VisualElement Element { get; private set; } public event EventHandler<VisualElementChangedEventArgs> ElementChanged; public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) { return NativeView.GetSizeRequest(widthConstraint, heightConstraint); } public UIView NativeView { get { return View; } } public void SetElement(VisualElement element) { var oldElement = Element; Element = element; Element.SizeChanged += PageOnSizeChanged; _masterController = new ChildViewController(); _detailController = new ChildViewController(); _clickOffView = new UIView(); _clickOffView.BackgroundColor = new Color(0, 0, 0, 0).ToUIColor(); Presented = ((MasterDetailPage)Element).IsPresented; OnElementChanged(new VisualElementChangedEventArgs(oldElement, element)); EffectUtilities.RegisterEffectControlProvider(this, oldElement, element); if (element != null) element.SendViewInitialized(NativeView); } public void SetElementSize(Size size) { Element.Layout(new Rectangle(Element.X, Element.Y, size.Width, size.Height)); } public UIViewController ViewController { get { return this; } } public override void ViewDidAppear(bool animated) { base.ViewDidAppear(animated); ((Page)Element).SendAppearing(); } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); ((Page)Element).SendDisappearing(); } public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); LayoutChildren(false); } public override void ViewDidLoad() { base.ViewDidLoad(); _tracker = new VisualElementTracker(this); _events = new EventTracker(this); _events.LoadEvents(View); ((MasterDetailPage)Element).PropertyChanged += HandlePropertyChanged; _tapGesture = new UITapGestureRecognizer(() => { if (Presented) Presented = false; }); _clickOffView.AddGestureRecognizer(_tapGesture); PackContainers(); UpdateMasterDetailContainers(); UpdateBackground(); UpdatePanGesture(); } public override void WillRotate(UIInterfaceOrientation toInterfaceOrientation, double duration) { if (!MasterDetailPageController.ShouldShowSplitMode && _presented) Presented = false; base.WillRotate(toInterfaceOrientation, duration); } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { Element.SizeChanged -= PageOnSizeChanged; Element.PropertyChanged -= HandlePropertyChanged; if (_tracker != null) { _tracker.Dispose(); _tracker = null; } if (_events != null) { _events.Dispose(); _events = null; } if (_tapGesture != null) { if (_clickOffView != null && _clickOffView.GestureRecognizers.Contains(_panGesture)) { _clickOffView.GestureRecognizers.Remove(_tapGesture); _clickOffView.Dispose(); } _tapGesture.Dispose(); } if (_panGesture != null) { if (View != null && View.GestureRecognizers.Contains(_panGesture)) View.GestureRecognizers.Remove(_panGesture); _panGesture.Dispose(); } EmptyContainers(); ((Page)Element).SendDisappearing(); _disposed = true; } base.Dispose(disposing); } protected virtual void OnElementChanged(VisualElementChangedEventArgs e) { var changed = ElementChanged; if (changed != null) changed(this, e); } void AddClickOffView() { View.Add(_clickOffView); _clickOffView.Frame = _detailController.View.Frame; } void EmptyContainers() { foreach (var child in _detailController.View.Subviews.Concat(_masterController.View.Subviews)) child.RemoveFromSuperview(); foreach (var vc in _detailController.ChildViewControllers.Concat(_masterController.ChildViewControllers)) vc.RemoveFromParentViewController(); } void HandleMasterPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == Page.IconProperty.PropertyName || e.PropertyName == Page.TitleProperty.PropertyName) MessagingCenter.Send<IVisualElementRenderer>(this, NavigationRenderer.UpdateToolbarButtons); } void HandlePropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Master" || e.PropertyName == "Detail") UpdateMasterDetailContainers(); else if (e.PropertyName == MasterDetailPage.IsPresentedProperty.PropertyName) Presented = ((MasterDetailPage)Element).IsPresented; else if (e.PropertyName == MasterDetailPage.IsGestureEnabledProperty.PropertyName) UpdatePanGesture(); else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName) UpdateBackground(); else if (e.PropertyName == Page.BackgroundImageProperty.PropertyName) UpdateBackground(); } void LayoutChildren(bool animated) { var frame = Element.Bounds.ToRectangleF(); var masterFrame = frame; masterFrame.Width = (int)(Math.Min(masterFrame.Width, masterFrame.Height) * 0.8); _masterController.View.Frame = masterFrame; var target = frame; if (Presented) target.X += masterFrame.Width; if (animated) { UIView.BeginAnimations("Flyout"); var view = _detailController.View; view.Frame = target; UIView.SetAnimationCurve(UIViewAnimationCurve.EaseOut); UIView.SetAnimationDuration(250); UIView.CommitAnimations(); } else _detailController.View.Frame = target; MasterDetailPageController.MasterBounds = new Rectangle(0, 0, masterFrame.Width, masterFrame.Height); MasterDetailPageController.DetailBounds = new Rectangle(0, 0, frame.Width, frame.Height); if (Presented) _clickOffView.Frame = _detailController.View.Frame; } void PackContainers() { _detailController.View.BackgroundColor = new UIColor(1, 1, 1, 1); View.AddSubview(_masterController.View); View.AddSubview(_detailController.View); AddChildViewController(_masterController); AddChildViewController(_detailController); } void PageOnSizeChanged(object sender, EventArgs eventArgs) { LayoutChildren(false); } void RemoveClickOffView() { _clickOffView.RemoveFromSuperview(); } void UpdateBackground() { if (!string.IsNullOrEmpty(((Page)Element).BackgroundImage)) View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle(((Page)Element).BackgroundImage)); else if (Element.BackgroundColor == Color.Default) View.BackgroundColor = UIColor.White; else View.BackgroundColor = Element.BackgroundColor.ToUIColor(); } void UpdateMasterDetailContainers() { ((MasterDetailPage)Element).Master.PropertyChanged -= HandleMasterPropertyChanged; EmptyContainers(); if (Platform.GetRenderer(((MasterDetailPage)Element).Master) == null) Platform.SetRenderer(((MasterDetailPage)Element).Master, Platform.CreateRenderer(((MasterDetailPage)Element).Master)); if (Platform.GetRenderer(((MasterDetailPage)Element).Detail) == null) Platform.SetRenderer(((MasterDetailPage)Element).Detail, Platform.CreateRenderer(((MasterDetailPage)Element).Detail)); var masterRenderer = Platform.GetRenderer(((MasterDetailPage)Element).Master); var detailRenderer = Platform.GetRenderer(((MasterDetailPage)Element).Detail); ((MasterDetailPage)Element).Master.PropertyChanged += HandleMasterPropertyChanged; _masterController.View.AddSubview(masterRenderer.NativeView); _masterController.AddChildViewController(masterRenderer.ViewController); _detailController.View.AddSubview(detailRenderer.NativeView); _detailController.AddChildViewController(detailRenderer.ViewController); } void UpdatePanGesture() { var model = (MasterDetailPage)Element; if (!model.IsGestureEnabled) { if (_panGesture != null) View.RemoveGestureRecognizer(_panGesture); return; } if (_panGesture != null) { View.AddGestureRecognizer(_panGesture); return; } UITouchEventArgs shouldRecieve = (g, t) => !(t.View is UISlider); var center = new PointF(); _panGesture = new UIPanGestureRecognizer(g => { switch (g.State) { case UIGestureRecognizerState.Began: center = g.LocationInView(g.View); break; case UIGestureRecognizerState.Changed: var currentPosition = g.LocationInView(g.View); var motion = currentPosition.X - center.X; var detailView = _detailController.View; var targetFrame = detailView.Frame; if (Presented) targetFrame.X = (nfloat)Math.Max(0, _masterController.View.Frame.Width + Math.Min(0, motion)); else targetFrame.X = (nfloat)Math.Min(_masterController.View.Frame.Width, Math.Max(0, motion)); detailView.Frame = targetFrame; break; case UIGestureRecognizerState.Ended: var detailFrame = _detailController.View.Frame; var masterFrame = _masterController.View.Frame; if (Presented) { if (detailFrame.X < masterFrame.Width * .75) Presented = false; else LayoutChildren(true); } else { if (detailFrame.X > masterFrame.Width * .25) Presented = true; else LayoutChildren(true); } break; } }); _panGesture.ShouldReceiveTouch = shouldRecieve; _panGesture.MaximumNumberOfTouches = 2; View.AddGestureRecognizer(_panGesture); } class ChildViewController : UIViewController { public override void ViewDidLayoutSubviews() { foreach (var vc in ChildViewControllers) vc.View.Frame = View.Bounds; } } void IEffectControlProvider.RegisterEffect(Effect effect) { var platformEffect = effect as PlatformEffect; if (platformEffect != null) platformEffect.Container = View; } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.CryptoPro; using Org.BouncyCastle.Asn1.Oiw; using Org.BouncyCastle.Asn1.Pkcs; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Asn1.X9; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Generators; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Math.EC; namespace Org.BouncyCastle.Security { public sealed class PublicKeyFactory { private PublicKeyFactory() { } public static AsymmetricKeyParameter CreateKey( byte[] keyInfoData) { return CreateKey( SubjectPublicKeyInfo.GetInstance( Asn1Object.FromByteArray(keyInfoData))); } public static AsymmetricKeyParameter CreateKey( Stream inStr) { return CreateKey( SubjectPublicKeyInfo.GetInstance( Asn1Object.FromStream(inStr))); } public static AsymmetricKeyParameter CreateKey( SubjectPublicKeyInfo keyInfo) { AlgorithmIdentifier algID = keyInfo.AlgorithmID; DerObjectIdentifier algOid = algID.ObjectID; // TODO See RSAUtil.isRsaOid in Java build if (algOid.Equals(PkcsObjectIdentifiers.RsaEncryption) || algOid.Equals(X509ObjectIdentifiers.IdEARsa) || algOid.Equals(PkcsObjectIdentifiers.IdRsassaPss) || algOid.Equals(PkcsObjectIdentifiers.IdRsaesOaep)) { RsaPublicKeyStructure pubKey = RsaPublicKeyStructure.GetInstance( keyInfo.GetPublicKey()); return new RsaKeyParameters(false, pubKey.Modulus, pubKey.PublicExponent); } else if (algOid.Equals(X9ObjectIdentifiers.DHPublicNumber)) { Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); DHPublicKey dhPublicKey = DHPublicKey.GetInstance(keyInfo.GetPublicKey()); BigInteger y = dhPublicKey.Y.Value; if (IsPkcsDHParam(seq)) return ReadPkcsDHParam(algOid, y, seq); DHDomainParameters dhParams = DHDomainParameters.GetInstance(seq); BigInteger p = dhParams.P.Value; BigInteger g = dhParams.G.Value; BigInteger q = dhParams.Q.Value; BigInteger j = null; if (dhParams.J != null) { j = dhParams.J.Value; } DHValidationParameters validation = null; DHValidationParms dhValidationParms = dhParams.ValidationParms; if (dhValidationParms != null) { byte[] seed = dhValidationParms.Seed.GetBytes(); BigInteger pgenCounter = dhValidationParms.PgenCounter.Value; // TODO Check pgenCounter size? validation = new DHValidationParameters(seed, pgenCounter.IntValue); } return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation)); } else if (algOid.Equals(PkcsObjectIdentifiers.DhKeyAgreement)) { Asn1Sequence seq = Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object()); DerInteger derY = (DerInteger) keyInfo.GetPublicKey(); return ReadPkcsDHParam(algOid, derY.Value, seq); } else if (algOid.Equals(OiwObjectIdentifiers.ElGamalAlgorithm)) { ElGamalParameter para = new ElGamalParameter( Asn1Sequence.GetInstance(algID.Parameters.ToAsn1Object())); DerInteger derY = (DerInteger) keyInfo.GetPublicKey(); return new ElGamalPublicKeyParameters( derY.Value, new ElGamalParameters(para.P, para.G)); } else if (algOid.Equals(X9ObjectIdentifiers.IdDsa) || algOid.Equals(OiwObjectIdentifiers.DsaWithSha1)) { DerInteger derY = (DerInteger) keyInfo.GetPublicKey(); Asn1Encodable ae = algID.Parameters; DsaParameters parameters = null; if (ae != null) { DsaParameter para = DsaParameter.GetInstance(ae.ToAsn1Object()); parameters = new DsaParameters(para.P, para.Q, para.G); } return new DsaPublicKeyParameters(derY.Value, parameters); } else if (algOid.Equals(X9ObjectIdentifiers.IdECPublicKey)) { X962Parameters para = new X962Parameters(algID.Parameters.ToAsn1Object()); X9ECParameters x9; if (para.IsNamedCurve) { x9 = ECKeyPairGenerator.FindECCurveByOid((DerObjectIdentifier)para.Parameters); } else { x9 = new X9ECParameters((Asn1Sequence)para.Parameters); } Asn1OctetString key = new DerOctetString(keyInfo.PublicKeyData.GetBytes()); X9ECPoint derQ = new X9ECPoint(x9.Curve, key); ECPoint q = derQ.Point; if (para.IsNamedCurve) { return new ECPublicKeyParameters("EC", q, (DerObjectIdentifier)para.Parameters); } ECDomainParameters dParams = new ECDomainParameters(x9.Curve, x9.G, x9.N, x9.H, x9.GetSeed()); return new ECPublicKeyParameters(q, dParams); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x2001)) { Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence) algID.Parameters); Asn1OctetString key; try { key = (Asn1OctetString) keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } byte[] keyEnc = key.GetOctets(); byte[] x = new byte[32]; byte[] y = new byte[32]; for (int i = 0; i != y.Length; i++) { x[i] = keyEnc[32 - 1 - i]; } for (int i = 0; i != x.Length; i++) { y[i] = keyEnc[64 - 1 - i]; } ECDomainParameters ecP = ECGost3410NamedCurves.GetByOid(gostParams.PublicKeyParamSet); if (ecP == null) return null; ECPoint q = ecP.Curve.CreatePoint(new BigInteger(1, x), new BigInteger(1, y)); return new ECPublicKeyParameters("ECGOST3410", q, gostParams.PublicKeyParamSet); } else if (algOid.Equals(CryptoProObjectIdentifiers.GostR3410x94)) { Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters( (Asn1Sequence) algID.Parameters); DerOctetString derY; try { derY = (DerOctetString) keyInfo.GetPublicKey(); } catch (IOException) { throw new ArgumentException("invalid info structure in GOST3410 public key"); } byte[] keyEnc = derY.GetOctets(); byte[] keyBytes = new byte[keyEnc.Length]; for (int i = 0; i != keyEnc.Length; i++) { keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // was little endian } BigInteger y = new BigInteger(1, keyBytes); return new Gost3410PublicKeyParameters(y, algParams.PublicKeyParamSet); } else { throw new SecurityUtilityException("algorithm identifier in key not recognised: " + algOid); } } private static bool IsPkcsDHParam(Asn1Sequence seq) { if (seq.Count == 2) return true; if (seq.Count > 3) return false; DerInteger l = DerInteger.GetInstance(seq[2]); DerInteger p = DerInteger.GetInstance(seq[0]); return l.Value.CompareTo(BigInteger.ValueOf(p.Value.BitLength)) <= 0; } private static DHPublicKeyParameters ReadPkcsDHParam(DerObjectIdentifier algOid, BigInteger y, Asn1Sequence seq) { DHParameter para = new DHParameter(seq); BigInteger lVal = para.L; int l = lVal == null ? 0 : lVal.IntValue; DHParameters dhParams = new DHParameters(para.P, para.G, null, l); return new DHPublicKeyParameters(y, dhParams, algOid); } } } #endif
using Lucene.Net.Index; using Lucene.Net.Util; using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace Lucene.Net.Documents { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Documents are the unit of indexing and search. /// <para/> /// A Document is a set of fields. Each field has a name and a textual value. /// A field may be stored (<see cref="IIndexableFieldType.IsStored"/>) with the document, in which /// case it is returned with search hits on the document. Thus each document /// should typically contain one or more stored fields which uniquely identify /// it. /// <para/> /// Note that fields which are <i>not</i> <see cref="Lucene.Net.Index.IIndexableFieldType.IsStored"/> are /// <i>not</i> available in documents retrieved from the index, e.g. with /// <see cref="Search.ScoreDoc.Doc"/> or <see cref="IndexReader.Document(int)"/>. /// </summary> public sealed class Document : IEnumerable<IIndexableField> { private readonly List<IIndexableField> fields = new List<IIndexableField>(); /// <summary> /// Constructs a new document with no fields. </summary> public Document() { } public IEnumerator<IIndexableField> GetEnumerator() { return fields.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// <para>Adds a field to a document. Several fields may be added with /// the same name. In this case, if the fields are indexed, their text is /// treated as though appended for the purposes of search.</para> /// <para> Note that add like the <see cref="RemoveField(string)"/> and <see cref="RemoveFields(string)"/> methods only makes sense /// prior to adding a document to an index. These methods cannot /// be used to change the content of an existing index! In order to achieve this, /// a document has to be deleted from an index and a new changed version of that /// document has to be added.</para> /// </summary> public void Add(IIndexableField field) { fields.Add(field); } /// <summary> /// <para>Removes field with the specified name from the document. /// If multiple fields exist with this name, this method removes the first field that has been added. /// If there is no field with the specified name, the document remains unchanged.</para> /// <para> Note that the <see cref="RemoveField(string)"/> and <see cref="RemoveFields(string)"/> methods like the add method only make sense /// prior to adding a document to an index. These methods cannot /// be used to change the content of an existing index! In order to achieve this, /// a document has to be deleted from an index and a new changed version of that /// document has to be added.</para> /// </summary> public void RemoveField(string name) { for (int i = 0; i < fields.Count; i++) { IIndexableField field = fields[i]; if (field.Name.Equals(name, StringComparison.Ordinal)) { fields.Remove(field); return; } } } /// <summary> /// <para>Removes all fields with the given name from the document. /// If there is no field with the specified name, the document remains unchanged.</para> /// <para> Note that the <see cref="RemoveField(string)"/> and <see cref="RemoveFields(string)"/> methods like the add method only make sense /// prior to adding a document to an index. These methods cannot /// be used to change the content of an existing index! In order to achieve this, /// a document has to be deleted from an index and a new changed version of that /// document has to be added.</para> /// </summary> public void RemoveFields(string name) { for (int i = fields.Count - 1; i >= 0; i--) { IIndexableField field = fields[i]; if (field.Name.Equals(name, StringComparison.Ordinal)) { fields.Remove(field); } } } /// <summary> /// Returns an array of byte arrays for of the fields that have the name specified /// as the method parameter. This method returns an empty /// array when there are no matching fields. It never /// returns <c>null</c>. /// </summary> /// <param name="name"> the name of the field </param> /// <returns> a <see cref="T:BytesRef[]"/> of binary field values </returns> public BytesRef[] GetBinaryValues(string name) { var result = new List<BytesRef>(); foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal)) { BytesRef bytes = field.GetBinaryValue(); if (bytes != null) { result.Add(bytes); } } } return result.ToArray(); } /// <summary> /// Returns an array of bytes for the first (or only) field that has the name /// specified as the method parameter. this method will return <c>null</c> /// if no binary fields with the specified name are available. /// There may be non-binary fields with the same name. /// </summary> /// <param name="name"> the name of the field. </param> /// <returns> a <see cref="BytesRef"/> containing the binary field value or <c>null</c> </returns> public BytesRef GetBinaryValue(string name) { foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal)) { BytesRef bytes = field.GetBinaryValue(); if (bytes != null) { return bytes; } } } return null; } /// <summary> /// Returns a field with the given name if any exist in this document, or /// <c>null</c>. If multiple fields exists with this name, this method returns the /// first value added. /// </summary> public IIndexableField GetField(string name) { foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal)) { return field; } } return null; } /// <summary> /// Returns an array of <see cref="IIndexableField"/>s with the given name. /// This method returns an empty array when there are no /// matching fields. It never returns <c>null</c>. /// </summary> /// <param name="name"> the name of the field </param> /// <returns> a <see cref="T:IndexableField[]"/> array </returns> public IIndexableField[] GetFields(string name) { var result = new List<IIndexableField>(); foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal)) { result.Add(field); } } return result.ToArray(); } /// <summary> /// Returns a List of all the fields in a document. /// <para>Note that fields which are <i>not</i> stored are /// <i>not</i> available in documents retrieved from the /// index, e.g. <see cref="Search.IndexSearcher.Doc(int)"/> or /// <see cref="IndexReader.Document(int)"/>. /// </para> /// </summary> public IList<IIndexableField> Fields => fields; private static readonly string[] NO_STRINGS = #if FEATURE_ARRAYEMPTY Array.Empty<string>(); #else new string[0]; #endif /// <summary> /// Returns an array of values of the field specified as the method parameter. /// This method returns an empty array when there are no /// matching fields. It never returns <c>null</c>. /// For <see cref="Int32Field"/>, <see cref="Int64Field"/>, /// <see cref="SingleField"/> and <seealso cref="DoubleField"/> it returns the string value of the number. If you want /// the actual numeric field instances back, use <see cref="GetFields(string)"/>. </summary> /// <param name="name"> the name of the field </param> /// <returns> a <see cref="T:string[]"/> of field values </returns> public string[] GetValues(string name) { var result = new List<string>(); foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal) && field.GetStringValue() != null) { result.Add(field.GetStringValue()); } } if (result.Count == 0) { return NO_STRINGS; } return result.ToArray(); } /// <summary> /// Returns the string value of the field with the given name if any exist in /// this document, or <c>null</c>. If multiple fields exist with this name, this /// method returns the first value added. If only binary fields with this name /// exist, returns <c>null</c>. /// For <see cref="Int32Field"/>, <see cref="Int64Field"/>, /// <see cref="SingleField"/> and <seealso cref="DoubleField"/> it returns the string value of the number. If you want /// the actual numeric field instance back, use <see cref="GetField(string)"/>. /// </summary> public string Get(string name) { foreach (IIndexableField field in fields) { if (field.Name.Equals(name, StringComparison.Ordinal) && field.GetStringValue() != null) { return field.GetStringValue(); } } return null; } /// <summary> /// Prints the fields of a document for human consumption. </summary> public override string ToString() { var buffer = new StringBuilder(); buffer.Append("Document<"); for (int i = 0; i < fields.Count; i++) { IIndexableField field = fields[i]; buffer.Append(field.ToString()); if (i != fields.Count - 1) { buffer.Append(" "); } } buffer.Append(">"); return buffer.ToString(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace TechAndWingsApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using Moq; using NUnit.Framework; using SqlCE4Umbraco; using umbraco; using umbraco.businesslogic; using umbraco.cms.businesslogic; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Core.Profiling; using Umbraco.Core.PropertyEditors; using umbraco.DataLayer; using umbraco.editorControls; using umbraco.interfaces; using umbraco.MacroEngines; using umbraco.uicontrols; using Umbraco.Web; using Umbraco.Web.PropertyEditors; namespace Umbraco.Tests.Plugins { [TestFixture] public class PluginManagerTests { private PluginManager _manager; [SetUp] public void Initialize() { //this ensures its reset _manager = new PluginManager(new ActivatorServiceProvider(), new NullCacheProvider(), new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); //for testing, we'll specify which assemblies are scanned for the PluginTypeResolver //TODO: Should probably update this so it only searches this assembly and add custom types to be found _manager.AssembliesToScan = new[] { this.GetType().Assembly, typeof(ApplicationStartupHandler).Assembly, typeof(SqlCEHelper).Assembly, typeof(CMSNode).Assembly, typeof(System.Guid).Assembly, typeof(NUnit.Framework.Assert).Assembly, typeof(Microsoft.CSharp.CSharpCodeProvider).Assembly, typeof(System.Xml.NameTable).Assembly, typeof(System.Configuration.GenericEnumConverter).Assembly, typeof(System.Web.SiteMap).Assembly, typeof(TabPage).Assembly, typeof(System.Web.Mvc.ActionResult).Assembly, typeof(TypeFinder).Assembly, typeof(ISqlHelper).Assembly, typeof(ICultureDictionary).Assembly, typeof(UmbracoContext).Assembly, typeof(BaseDataType).Assembly }; } [TearDown] public void TearDown() { _manager = null; } private DirectoryInfo PrepareFolder() { var assDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory; var dir = Directory.CreateDirectory(Path.Combine(assDir.FullName, "PluginManager", Guid.NewGuid().ToString("N"))); foreach (var f in dir.GetFiles()) { f.Delete(); } return dir; } //[Test] //public void Scan_Vs_Load_Benchmark() //{ // var pluginManager = new PluginManager(false); // var watch = new Stopwatch(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = Type.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type3 = Type.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type4 = Type.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type5 = Type.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = BuildManager.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type3 = BuildManager.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type4 = BuildManager.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type5 = BuildManager.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); // watch.Reset(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var refreshers = pluginManager.ResolveTypes<ICacheRefresher>(false); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (2nd round): " + watch.ElapsedMilliseconds); //} ////NOTE: This test shows that Type.GetType is 100% faster than Assembly.Load(..).GetType(...) so we'll use that :) //[Test] //public void Load_Type_Benchmark() //{ // var watch = new Stopwatch(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = Type.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type3 = Type.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type4 = Type.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // var type5 = Type.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null"); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); // watch.Reset(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null") // .GetType("umbraco.macroCacheRefresh"); // var type3 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null") // .GetType("umbraco.templateCacheRefresh"); // var type4 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null") // .GetType("umbraco.presentation.cache.MediaLibraryRefreshers"); // var type5 = Assembly.Load("umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null") // .GetType("umbraco.presentation.cache.pageRefresher"); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (2nd round): " + watch.ElapsedMilliseconds); // watch.Reset(); // watch.Start(); // for (var i = 0; i < 1000; i++) // { // var type2 = BuildManager.GetType("umbraco.macroCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type3 = BuildManager.GetType("umbraco.templateCacheRefresh, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type4 = BuildManager.GetType("umbraco.presentation.cache.MediaLibraryRefreshers, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // var type5 = BuildManager.GetType("umbraco.presentation.cache.pageRefresher, umbraco, Version=1.0.4698.259, Culture=neutral, PublicKeyToken=null", true); // } // watch.Stop(); // Debug.WriteLine("TOTAL TIME (1st round): " + watch.ElapsedMilliseconds); //} [Test] public void Detect_Legacy_Plugin_File_List() { var tempFolder = IOHelper.MapPath("~/App_Data/TEMP/PluginCache"); var filePath= Path.Combine(tempFolder, string.Format("umbraco-plugins.{0}.list", NetworkHelper.FileSafeMachineName)); File.WriteAllText(filePath, @"<?xml version=""1.0"" encoding=""utf-8""?> <plugins> <baseType type=""umbraco.interfaces.ICacheRefresher""> <add type=""umbraco.macroCacheRefresh, umbraco, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"" /> </baseType> </plugins>"); Assert.IsEmpty(_manager.ReadCache()); // uber-legacy cannot be read File.Delete(filePath); File.WriteAllText(filePath, @"<?xml version=""1.0"" encoding=""utf-8""?> <plugins> <baseType type=""umbraco.interfaces.ICacheRefresher"" resolutionType=""FindAllTypes""> <add type=""umbraco.macroCacheRefresh, umbraco, Version=6.0.0.0, Culture=neutral, PublicKeyToken=null"" /> </baseType> </plugins>"); Assert.IsEmpty(_manager.ReadCache()); // legacy cannot be read File.Delete(filePath); File.WriteAllText(filePath, @"IContentFinder MyContentFinder AnotherContentFinder "); Assert.IsNotNull(_manager.ReadCache()); // works } [Test] public void Create_Cached_Plugin_File() { var types = new[] { typeof (PluginManager), typeof (PluginManagerTests), typeof (UmbracoContext) }; var typeList1 = new PluginManager.TypeList(typeof (object), null); foreach (var type in types) typeList1.Add(type); _manager.AddTypeList(typeList1); _manager.WriteCache(); var plugins = _manager.TryGetCached(typeof (object), null); var diffType = _manager.TryGetCached(typeof (object), typeof (ObsoleteAttribute)); Assert.IsTrue(plugins.Success); //this will be false since there is no cache of that type resolution kind Assert.IsFalse(diffType.Success); Assert.AreEqual(3, plugins.Result.Count()); var shouldContain = types.Select(x => x.AssemblyQualifiedName); //ensure they are all found Assert.IsTrue(plugins.Result.ContainsAll(shouldContain)); } [Test] public void Get_Plugins_Hash() { //Arrange var dir = PrepareFolder(); var d1 = dir.CreateSubdirectory("1"); var d2 = dir.CreateSubdirectory("2"); var d3 = dir.CreateSubdirectory("3"); var d4 = dir.CreateSubdirectory("4"); var f1 = new FileInfo(Path.Combine(d1.FullName, "test1.dll")); var f2 = new FileInfo(Path.Combine(d1.FullName, "test2.dll")); var f3 = new FileInfo(Path.Combine(d2.FullName, "test1.dll")); var f4 = new FileInfo(Path.Combine(d2.FullName, "test2.dll")); var f5 = new FileInfo(Path.Combine(d3.FullName, "test1.dll")); var f6 = new FileInfo(Path.Combine(d3.FullName, "test2.dll")); var f7 = new FileInfo(Path.Combine(d4.FullName, "test1.dll")); f1.CreateText().Close(); f2.CreateText().Close(); f3.CreateText().Close(); f4.CreateText().Close(); f5.CreateText().Close(); f6.CreateText().Close(); f7.CreateText().Close(); var list1 = new[] { f1, f2, f3, f4, f5, f6 }; var list2 = new[] { f1, f3, f5 }; var list3 = new[] { f1, f3, f5, f7 }; //Act var hash1 = PluginManager.GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); var hash2 = PluginManager.GetFileHash(list2, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); var hash3 = PluginManager.GetFileHash(list3, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>())); //Assert Assert.AreNotEqual(hash1, hash2); Assert.AreNotEqual(hash1, hash3); Assert.AreNotEqual(hash2, hash3); Assert.AreEqual(hash1, PluginManager.GetFileHash(list1, new ProfilingLogger(Mock.Of<ILogger>(), Mock.Of<IProfiler>()))); } [Test] public void Ensure_Only_One_Type_List_Created() { var foundTypes1 = _manager.ResolveFindMeTypes(); var foundTypes2 = _manager.ResolveFindMeTypes(); Assert.AreEqual(1, _manager.TypeLists.Count(x => x.BaseType == typeof(IFindMe) && x.AttributeType == null)); } [Test] public void Resolves_Assigned_Mappers() { var foundTypes1 = _manager.ResolveAssignedMapperTypes(); Assert.AreEqual(31, foundTypes1.Count()); } [Test] public void Resolves_Types() { var foundTypes1 = _manager.ResolveFindMeTypes(); Assert.AreEqual(2, foundTypes1.Count()); } [Test] public void Resolves_Attributed_Trees() { var trees = _manager.ResolveAttributedTrees(); // commit 6c5e35ec2cbfa31be6790d1228e0c2faf5f55bc8 brings the count down to 14 Assert.AreEqual(6, trees.Count()); } [Test] public void Resolves_Actions() { var actions = _manager.ResolveActions(); Assert.AreEqual(38, actions.Count()); } [Test] public void Resolves_Trees() { var trees = _manager.ResolveTrees(); Assert.AreEqual(34, trees.Count()); } [Test] public void Resolves_Applications() { var apps = _manager.ResolveApplications(); Assert.AreEqual(7, apps.Count()); } [Test] public void Resolves_DataTypes() { var types = _manager.ResolveDataTypes(); Assert.AreEqual(35, types.Count()); } [Test] public void Resolves_RazorDataTypeModels() { var types = _manager.ResolveRazorDataTypeModels(); Assert.AreEqual(2, types.Count()); } [Test] public void Resolves_RestExtensions() { var types = _manager.ResolveRestExtensions(); Assert.AreEqual(3, types.Count()); } [Test] public void Resolves_XsltExtensions() { var types = _manager.ResolveXsltExtensions(); Assert.AreEqual(3, types.Count()); } /// <summary> /// This demonstrates this issue: http://issues.umbraco.org/issue/U4-3505 - the TypeList was returning a list of assignable types /// not explicit types which is sort of ideal but is confusing so we'll do it the less confusing way. /// </summary> [Test] public void TypeList_Resolves_Explicit_Types() { var types = new HashSet<PluginManager.TypeList>(); var propEditors = new PluginManager.TypeList(typeof (PropertyEditor), null); propEditors.Add(typeof(LabelPropertyEditor)); types.Add(propEditors); var found = types.SingleOrDefault(x => x.BaseType == typeof (PropertyEditor) && x.AttributeType == null); Assert.IsNotNull(found); //This should not find a type list of this type var shouldNotFind = types.SingleOrDefault(x => x.BaseType == typeof (IParameterEditor) && x.AttributeType == null); Assert.IsNull(shouldNotFind); } [XsltExtension("Blah.Blah")] public class MyXsltExtension { } [Umbraco.Web.BaseRest.RestExtension("Blah")] public class MyRestExtesion { } public interface IFindMe : IDiscoverable { } public class FindMe1 : IFindMe { } public class FindMe2 : IFindMe { } } }
//////////////////////////////////////////////////////////////////////////////// // Gtk GLWidget Sharp - Gtk OpenGL Widget for CSharp using OpenTK //////////////////////////////////////////////////////////////////////////////// /* Usage: To render either override OnRenderFrame() or hook to the RenderFrame event. When GraphicsContext.ShareContexts == True (Default) To setup OpenGL state hook to the following events: GLWidget.GraphicsContextInitialized GLWidget.GraphicsContextShuttingDown When GraphicsContext.ShareContexts == False To setup OpenGL state hook to the following events: GLWidget.Initialized GLWidget.ShuttingDown */ //////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.InteropServices; using System.Security; using System.Threading; using Eto.Drawing; using Eto.GtkSharp; using Gtk; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; using OpenTK.Platform; namespace Eto.Gl.Gtk { [ToolboxItem(true)] public class GLDrawingArea : DrawingArea, IDisposable { IGraphicsContext graphicsContext; static int graphicsContextCount; const string linux_libx11_name = "libX11.so.6"; const string linux_libgdk_x11_name = "libgdk-x11-2.0.so.0"; const string linux_libgl_name = "libGL.so.1"; const string libgdk_name = "libgdk-win32-2.0-0.dll"; const string libX11_name = "libX11"; /// <summary>Use a single buffer versus a double buffer.</summary> [Browsable(true)] public bool SingleBuffer { get; set; } /// <summary>Color Buffer Bits-Per-Pixel</summary> public int ColorBPP { get; set; } /// <summary>Accumulation Buffer Bits-Per-Pixel</summary> public int AccumulatorBPP { get; set; } /// <summary>Depth Buffer Bits-Per-Pixel</summary> public int DepthBPP { get; set; } /// <summary>Stencil Buffer Bits-Per-Pixel</summary> public int StencilBPP { get; set; } /// <summary>Number of samples</summary> public int Samples { get; set; } /// <summary>Indicates if steropic renderering is enabled</summary> public bool Stereo { get; set; } IWindowInfo windowInfo; /// <summary>The major version of OpenGL to use.</summary> public int GlVersionMajor { get; set; } /// <summary>The minor version of OpenGL to use.</summary> public int GlVersionMinor { get; set; } private Size size; /// <summary> /// Gets or sets the context size. /// </summary> /// <value>The width.</value> public virtual Size GLSize { get { return Visible ? Allocation.Size.ToEto() : size; } set { if (size != value) { size = value; var alloc = Allocation; alloc.Size = value.ToGdk(); SetSizeRequest(size.Width, size.Height); } } } bool initialized = false; public virtual bool IsInitialized { get { return initialized; } } public GraphicsContextFlags GraphicsContextFlags { get { return graphicsContextFlags; } set { graphicsContextFlags = value; } } GraphicsContextFlags graphicsContextFlags; /// <summary>Constructs a new GLWidget.</summary> public GLDrawingArea() : this(GraphicsMode.Default) { } /// <summary>Constructs a new GLWidget using a given GraphicsMode</summary> public GLDrawingArea(GraphicsMode graphicsMode) : this(graphicsMode, 3, 0, GraphicsContextFlags.Default) { } /// <summary>Constructs a new GLWidget</summary> public GLDrawingArea(GraphicsMode graphicsMode, int glVersionMajor, int glVersionMinor, GraphicsContextFlags graphicsContextFlags) { this.DoubleBuffered = false; CanFocus = true; SingleBuffer = graphicsMode.Buffers == 1; ColorBPP = graphicsMode.ColorFormat.BitsPerPixel; AccumulatorBPP = graphicsMode.AccumulatorFormat.BitsPerPixel; DepthBPP = graphicsMode.Depth; StencilBPP = graphicsMode.Stencil; Samples = graphicsMode.Samples; Stereo = graphicsMode.Stereo; GlVersionMajor = glVersionMajor; GlVersionMinor = glVersionMinor; GraphicsContextFlags = graphicsContextFlags; } ~GLDrawingArea() { Dispose(false); } public override void Dispose() { GC.SuppressFinalize(this); Dispose(true); base.Dispose(); } public virtual void Dispose(bool disposing) { if (disposing) { graphicsContext.MakeCurrent(windowInfo); OnShuttingDown(); if (GraphicsContext.ShareContexts && (Interlocked.Decrement(ref graphicsContextCount) == 0)) { OnGraphicsContextShuttingDown(); sharedContextInitialized = false; } graphicsContext.Dispose(); } } public virtual void MakeCurrent() { if (!initialized) { return; } graphicsContext.MakeCurrent(windowInfo); } public virtual void SwapBuffers() { if (!initialized) { return; } Display.Flush (); graphicsContext.SwapBuffers (); Display.Sync (); } // Called when the first GraphicsContext is created in the case of GraphicsContext.ShareContexts == True; public static event EventHandler GraphicsContextInitialized; static void OnGraphicsContextInitialized() { if (GraphicsContextInitialized != null) GraphicsContextInitialized(null, EventArgs.Empty); } // Called when the first GraphicsContext is being destroyed in the case of GraphicsContext.ShareContexts == True; public static event EventHandler GraphicsContextShuttingDown; static void OnGraphicsContextShuttingDown() { if (GraphicsContextShuttingDown != null) GraphicsContextShuttingDown(null, EventArgs.Empty); } // Called when this GLWidget has a valid GraphicsContext public event EventHandler Initialized = delegate {}; protected virtual void OnInitialized() { Initialized(this, EventArgs.Empty); } // Called when this GLWidget needs to render a frame public event EventHandler Resize = delegate {}; protected virtual void OnResize() { Resize (this, EventArgs.Empty); } // Called when this GLWidget is being Disposed public event EventHandler ShuttingDown; protected virtual void OnShuttingDown() { if (ShuttingDown != null) ShuttingDown(this, EventArgs.Empty); } static bool sharedContextInitialized = false; // Called when the widget needs to be (fully or partially) redrawn. protected override bool OnExposeEvent(Gdk.EventExpose eventExpose) { if (!initialized) { initialized = true; // If this looks uninitialized... initialize. if( ColorBPP == 0 ) { ColorBPP = 24; if( DepthBPP == 0 ) DepthBPP = 16; } ColorFormat colorBufferColorFormat = new ColorFormat(ColorBPP); ColorFormat accumulationColorFormat = new ColorFormat(AccumulatorBPP); int buffers = 2; if( SingleBuffer ) buffers--; GraphicsMode graphicsMode = new GraphicsMode(colorBufferColorFormat, DepthBPP, StencilBPP, Samples, accumulationColorFormat, buffers, Stereo); // IWindowInfo if (Configuration.RunningOnWindows) { IntPtr windowHandle = gdk_win32_drawable_get_handle(GdkWindow.Handle); windowInfo = OpenTK.Platform.Utilities.CreateWindowsWindowInfo(windowHandle); } else if (Configuration.RunningOnMacOS) { IntPtr windowHandle = gdk_x11_drawable_get_xid(GdkWindow.Handle); bool ownHandle = true; bool isControl = true; windowInfo = OpenTK.Platform.Utilities.CreateMacOSCarbonWindowInfo(windowHandle, ownHandle, isControl); } else if (Configuration.RunningOnX11) { IntPtr display = gdk_x11_display_get_xdisplay(Display.Handle); int screen = Screen.Number; IntPtr windowHandle = gdk_x11_drawable_get_xid(GdkWindow.Handle); IntPtr rootWindow = gdk_x11_drawable_get_xid(RootWindow.Handle); IntPtr visualInfo; if (graphicsMode.Index.HasValue) { XVisualInfo info = new XVisualInfo(); info.VisualID = graphicsMode.Index.Value; int dummy; visualInfo = XGetVisualInfo(display, XVisualInfoMask.ID, ref info, out dummy); } else { visualInfo = GetVisualInfo(display); } windowInfo = OpenTK.Platform.Utilities.CreateX11WindowInfo(display, screen, windowHandle, rootWindow, visualInfo); XFree(visualInfo); } else throw new PlatformNotSupportedException(); // GraphicsContext graphicsContext = new GraphicsContext(graphicsMode, windowInfo, GlVersionMajor, GlVersionMinor, graphicsContextFlags); MakeCurrent(); if (GraphicsContext.ShareContexts) { Interlocked.Increment(ref graphicsContextCount); if (!sharedContextInitialized) { sharedContextInitialized = true; ((IGraphicsContextInternal)graphicsContext).LoadAll(); OnGraphicsContextInitialized(); } } else { ((IGraphicsContextInternal)graphicsContext).LoadAll(); OnGraphicsContextInitialized(); } OnInitialized(); } else { graphicsContext.MakeCurrent(windowInfo); } bool result = base.OnExposeEvent(eventExpose); GL.Viewport( 0, 0, GLSize.Width, GLSize.Height ); GL.MatrixMode( MatrixMode.Projection ); GL.LoadIdentity(); GL.Ortho( -1.0, 1.0, -1.0, 1.0, 0.0, 4.0 ); OnResize(); eventExpose.Window.Display.Sync(); // Add Sync call to fix resize rendering problem (Jay L. T. Cornwall) - How does this affect VSync? return result; } protected override bool OnConfigureEvent(Gdk.EventConfigure evnt) { bool result = base.OnConfigureEvent(evnt); if (graphicsContext != null) graphicsContext.Update(windowInfo); return result; } public enum XVisualClass : int { StaticGray = 0, GrayScale = 1, StaticColor = 2, PseudoColor = 3, TrueColor = 4, DirectColor = 5, } [StructLayout(LayoutKind.Sequential)] struct XVisualInfo { public IntPtr Visual; public IntPtr VisualID; public int Screen; public int Depth; public XVisualClass Class; public long RedMask; public long GreenMask; public long blueMask; public int ColormapSize; public int BitsPerRgb; public override string ToString() { return String.Format("id ({0}), screen ({1}), depth ({2}), class ({3})", VisualID, Screen, Depth, Class); } } [Flags] internal enum XVisualInfoMask { No = 0x0, ID = 0x1, Screen = 0x2, Depth = 0x4, Class = 0x8, Red = 0x10, Green = 0x20, Blue = 0x40, ColormapSize = 0x80, BitsPerRGB = 0x100, All = 0x1FF, } [DllImport(libX11_name, EntryPoint = "XGetVisualInfo")] static extern IntPtr XGetVisualInfoInternal(IntPtr display, IntPtr vinfo_mask, ref XVisualInfo template, out int nitems); static IntPtr XGetVisualInfo(IntPtr display, XVisualInfoMask vinfo_mask, ref XVisualInfo template, out int nitems) { return XGetVisualInfoInternal(display, (IntPtr)(int)vinfo_mask, ref template, out nitems); } [SuppressUnmanagedCodeSecurity, DllImport(libgdk_name)] public static extern IntPtr gdk_win32_drawable_get_handle(IntPtr d); [SuppressUnmanagedCodeSecurity, DllImport(linux_libx11_name)] static extern void XFree(IntPtr handle); /// <summary> Returns the X resource (window or pixmap) belonging to a GdkDrawable. </summary> /// <remarks> XID gdk_x11_drawable_get_xid(GdkDrawable *drawable); </remarks> /// <param name="gdkDisplay"> The GdkDrawable. </param> /// <returns> The ID of drawable's X resource. </returns> [SuppressUnmanagedCodeSecurity, DllImport(linux_libgdk_x11_name)] static extern IntPtr gdk_x11_drawable_get_xid(IntPtr gdkDisplay); /// <summary> Returns the X display of a GdkDisplay. </summary> /// <remarks> Display* gdk_x11_display_get_xdisplay(GdkDisplay *display); </remarks> /// <param name="gdkDisplay"> The GdkDrawable. </param> /// <returns> The X Display of the GdkDisplay. </returns> [SuppressUnmanagedCodeSecurity, DllImport(linux_libgdk_x11_name)] static extern IntPtr gdk_x11_display_get_xdisplay(IntPtr gdkDisplay); [SuppressUnmanagedCodeSecurity, DllImport(linux_libgl_name)] static extern IntPtr glXChooseVisual(IntPtr display, int screen, int[] attr); IntPtr GetVisualInfo(IntPtr display) { try { int[] attributes = AttributeList.ToArray(); return glXChooseVisual(display, Screen.Number, attributes); } catch (DllNotFoundException e) { throw new DllNotFoundException("OpenGL dll not found!", e); } catch (EntryPointNotFoundException enf) { throw new EntryPointNotFoundException("Glx entry point not found!", enf); } } const int GLX_NONE = 0; const int GLX_USE_GL = 1; const int GLX_BUFFER_SIZE = 2; const int GLX_LEVEL = 3; const int GLX_RGBA = 4; const int GLX_DOUBLEBUFFER = 5; const int GLX_STEREO = 6; const int GLX_AUX_BUFFERS = 7; const int GLX_RED_SIZE = 8; const int GLX_GREEN_SIZE = 9; const int GLX_BLUE_SIZE = 10; const int GLX_ALPHA_SIZE = 11; const int GLX_DEPTH_SIZE = 12; const int GLX_STENCIL_SIZE = 13; const int GLX_ACCUM_RED_SIZE = 14; const int GLX_ACCUM_GREEN_SIZE = 15; const int GLX_ACCUM_BLUE_SIZE = 16; const int GLX_ACCUM_ALPHA_SIZE = 17; List<int> AttributeList { get { List<int> attributeList = new List<int>(24); attributeList.Add(GLX_RGBA); if (!SingleBuffer) attributeList.Add(GLX_DOUBLEBUFFER); if (Stereo) attributeList.Add(GLX_STEREO); attributeList.Add(GLX_RED_SIZE); attributeList.Add(ColorBPP/4); // TODO support 16-bit attributeList.Add(GLX_GREEN_SIZE); attributeList.Add(ColorBPP/4); // TODO support 16-bit attributeList.Add(GLX_BLUE_SIZE); attributeList.Add(ColorBPP/4); // TODO support 16-bit attributeList.Add(GLX_ALPHA_SIZE); attributeList.Add(ColorBPP/4); // TODO support 16-bit attributeList.Add(GLX_DEPTH_SIZE); attributeList.Add(DepthBPP); attributeList.Add(GLX_STENCIL_SIZE); attributeList.Add(StencilBPP); //attributeList.Add(GLX_AUX_BUFFERS); //attributeList.Add(Buffers); attributeList.Add(GLX_ACCUM_RED_SIZE); attributeList.Add(AccumulatorBPP/4);// TODO support 16-bit attributeList.Add(GLX_ACCUM_GREEN_SIZE); attributeList.Add(AccumulatorBPP/4);// TODO support 16-bit attributeList.Add(GLX_ACCUM_BLUE_SIZE); attributeList.Add(AccumulatorBPP/4);// TODO support 16-bit attributeList.Add(GLX_ACCUM_ALPHA_SIZE); attributeList.Add(AccumulatorBPP/4);// TODO support 16-bit attributeList.Add(GLX_NONE); return attributeList; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Text; using Banshee.Base; using Banshee.Sources; using Banshee.MediaEngine; using Banshee.Winforms; using Banshee.Winforms.Controls; using System.Windows.Forms; namespace Banshee { public enum RepeatMode { None, All, Single, ErrorHalt } public class PlaylistModel { public event EventHandler Updated; public event EventHandler Stopped; public event EventHandler Cleared; protected SortableBindingList<TrackInfo> _tracks = new SortableBindingList<TrackInfo>(); public int Count() { return _tracks.Count; } public TimeSpan TotalDuration { get { return totalDuration; } } private TimeSpan totalDuration = new TimeSpan(0); public void AddTrack(TrackInfo track) { AddTrack(track, true); } public void AddTrack(TrackInfo track,bool raiseUpdate) { totalDuration += track.Duration; _tracks.Add(track); if (raiseUpdate) { RaiseUpdated(this, new EventArgs()); } } public SortableBindingList<TrackInfo> Tracks { get { return _tracks; } set { _tracks = value; } } public void Clear() { _tracks.Clear(); } public PlaylistModel() { SourceManager.ActiveSourceChanged += delegate(SourceEventArgs args) { ReloadSource(); }; PlayerEngineCore.EventChanged += delegate(object o, PlayerEngineEventArgs args) { switch (args.Event) { case PlayerEngineEvent.StartOfStream: return; } }; } public void ClearModel() { totalDuration = new TimeSpan(0); _tracks.Clear(); RaiseUpdated(this, new EventArgs()); } private bool can_save_sort_id = true; bool reloading = false; TrackSource source = new TrackSource(); public TrackSource Source { get { return source; } set { source = value; } } void reloadthread() { if (InterfaceElements.MainWindow != null) { InterfaceElements.MainWindow.BeginInvoke((MethodInvoker)delegate() { if (!reloading) { //_tracks.Clear(); RaiseCleared(this, new EventArgs()); totalDuration = new TimeSpan(0); lock (SourceManager.ActiveSource.TracksMutex) { source.Reload(); totalDuration = source.TotalDuration; this.Tracks = source.Tracks; } } total_count = _tracks.Count; RaiseUpdated(this, new EventArgs()); }); } } public void ReloadSource() { ThreadAssist.Spawn(new System.Threading.ThreadStart(reloadthread), true); } private int total_count; private int scan_ref_count = 0; private static System.Drawing.Icon user_event_icon = IconThemeUtils.LoadIcon(ConfigureDefines.ICON_THEME_DIR + @"\user-home.png"); private static readonly object user_event_mutex = new object(); private void RaiseCleared(object sender, EventArgs e) { EventHandler handler = Cleared; if (handler != null) handler(sender, e); } private void RaiseUpdated(object o, EventArgs args) { EventHandler handler = Updated; if (handler != null) handler(o, args); } private DataGridViewRow currentRow; private DataGridViewRow nextRow; private TrackInfo currentTrack; public void PlayIter(string uri) { TrackInfo track = PathTreeInfo(uri); current_index = currentIndex(uri); currentTrack = track; PlayerEngineCore.OpenPlay(track); } public TrackInfo PathTreeInfo(string path) { TrackInfo pathtrackinfo = null; foreach (TrackInfo track in SourceManager.ActiveSource.Tracks) { if (track.Uri.ToString() == path) { pathtrackinfo = track; break; } } return pathtrackinfo; } TrackInfo selected_track; public TrackInfo SelectedTrack { get { return selected_track; } set { selected_track = value; } } int current_index = 0; private int currentIndex(string uri) { int rtn = 0; for (int i = 0; i < _tracks.Count; i++) { if (_tracks[i].Uri.ToString() == uri) rtn = i; } return rtn; } private void ChangeDirection(bool forward) { //Cornel - Okay so now i need to get this working if (forward) { if (repeat == RepeatMode.All) { TrackInfo track = _tracks[current_index+1]; selected_track = track; //PlayerEngineCore.OpenPlay(track); PlayIter(track.Uri.ToString()); } } else { if (repeat == RepeatMode.All) { int index = current_index - 1; if (index >= 0) { TrackInfo track = _tracks[index]; selected_track = track; //PlayerEngineCore.OpenPlay(track); PlayIter(track.Uri.ToString()); } } } } DataGridViewRow playingIter; public void Advance() { ChangeDirection(true); } public void Regress() { ChangeDirection(false); } public void Continue() { Advance(); } private RepeatMode repeat = RepeatMode.None; private bool shuffle = false; public RepeatMode Repeat { set { repeat = value; } get { return repeat; } } public bool Shuffle { set { shuffle = value; } get { return shuffle; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: Image.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; /// <summary>Holder for reflection information generated from Image.proto</summary> public static partial class ImageReflection { #region Descriptor /// <summary>File descriptor for Image.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ImageReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CgtJbWFnZS5wcm90bxoMSGVhZGVyLnByb3RvIk0KBUltYWdlEhcKBmhlYWRl", "chgBIAEoCzIHLkhlYWRlchIOCgZoZWlnaHQYAiABKAUSDQoFd2lkdGgYAyAB", "KAUSDAoEZGF0YRgEIAEoDGIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HeaderReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Image), global::Image.Parser, new[]{ "Header", "Height", "Width", "Data" }, null, null, null) })); } #endregion } #region Messages public sealed partial class Image : pb::IMessage<Image> { private static readonly pb::MessageParser<Image> _parser = new pb::MessageParser<Image>(() => new Image()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Image> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::ImageReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Image() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Image(Image other) : this() { Header = other.header_ != null ? other.Header.Clone() : null; height_ = other.height_; width_ = other.width_; data_ = other.data_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Image Clone() { return new Image(this); } /// <summary>Field number for the "header" field.</summary> public const int HeaderFieldNumber = 1; private global::Header header_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Header Header { get { return header_; } set { header_ = value; } } /// <summary>Field number for the "height" field.</summary> public const int HeightFieldNumber = 2; private int height_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Height { get { return height_; } set { height_ = value; } } /// <summary>Field number for the "width" field.</summary> public const int WidthFieldNumber = 3; private int width_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Width { get { return width_; } set { width_ = value; } } /// <summary>Field number for the "data" field.</summary> public const int DataFieldNumber = 4; private pb::ByteString data_ = pb::ByteString.Empty; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pb::ByteString Data { get { return data_; } set { data_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Image); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Image other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Header, other.Header)) return false; if (Height != other.Height) return false; if (Width != other.Width) return false; if (Data != other.Data) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (header_ != null) hash ^= Header.GetHashCode(); if (Height != 0) hash ^= Height.GetHashCode(); if (Width != 0) hash ^= Width.GetHashCode(); if (Data.Length != 0) hash ^= Data.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 (header_ != null) { output.WriteRawTag(10); output.WriteMessage(Header); } if (Height != 0) { output.WriteRawTag(16); output.WriteInt32(Height); } if (Width != 0) { output.WriteRawTag(24); output.WriteInt32(Width); } if (Data.Length != 0) { output.WriteRawTag(34); output.WriteBytes(Data); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (header_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Header); } if (Height != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Height); } if (Width != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Width); } if (Data.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Image other) { if (other == null) { return; } if (other.header_ != null) { if (header_ == null) { header_ = new global::Header(); } Header.MergeFrom(other.Header); } if (other.Height != 0) { Height = other.Height; } if (other.Width != 0) { Width = other.Width; } if (other.Data.Length != 0) { Data = other.Data; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (header_ == null) { header_ = new global::Header(); } input.ReadMessage(header_); break; } case 16: { Height = input.ReadInt32(); break; } case 24: { Width = input.ReadInt32(); break; } case 34: { Data = input.ReadBytes(); break; } } } } } #endregion #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Threading; interface IGen<T> { void Target<U>(object p); T Dummy(T t); } class GenInt : IGen<int> { public int Dummy(int t) { return t; } public virtual void Target<U>(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest<U>() { ManualResetEvent evt = new ManualResetEvent(false); IGen<int> obj = new GenInt(); TimerCallback tcb = new TimerCallback(obj.Target<U>); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } class GenDouble : IGen<double> { public double Dummy(double t) { return t; } public virtual void Target<U>(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest<U>() { ManualResetEvent evt = new ManualResetEvent(false); IGen<double> obj = new GenDouble(); TimerCallback tcb = new TimerCallback(obj.Target<U>); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } class GenString : IGen<string> { public string Dummy(string t) { return t; } public virtual void Target<U>(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest<U>() { ManualResetEvent evt = new ManualResetEvent(false); IGen<string> obj = new GenString(); TimerCallback tcb = new TimerCallback(obj.Target<U>); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } class GenObject : IGen<object> { public object Dummy(object t) { return t; } public virtual void Target<U>(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest<U>() { ManualResetEvent evt = new ManualResetEvent(false); IGen<object> obj = new GenObject(); TimerCallback tcb = new TimerCallback(obj.Target<U>); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } class GenGuid : IGen<Guid> { public Guid Dummy(Guid t) { return t; } public virtual void Target<U>(object p) { if (Test.Xcounter>=Test.nThreads) { ManualResetEvent evt = (ManualResetEvent) p; evt.Set(); } else { Interlocked.Increment(ref Test.Xcounter); } } public static void ThreadPoolTest<U>() { ManualResetEvent evt = new ManualResetEvent(false); IGen<Guid> obj = new GenGuid(); TimerCallback tcb = new TimerCallback(obj.Target<U>); Timer timer = new Timer(tcb,evt,Test.delay,Test.period); evt.WaitOne(); timer.Dispose(); Test.Eval(Test.Xcounter>=Test.nThreads); Test.Xcounter = 0; } } public class Test { public static int delay = 0; public static int period = 2; public static int nThreads = 5; public static int counter = 0; public static int Xcounter = 0; public static bool result = true; public static void Eval(bool exp) { counter++; if (!exp) { result = exp; Console.WriteLine("Test Failed at location: " + counter); } } public static int Main() { GenInt.ThreadPoolTest<int>(); GenDouble.ThreadPoolTest<int>(); GenString.ThreadPoolTest<int>(); GenObject.ThreadPoolTest<int>(); GenGuid.ThreadPoolTest<int>(); GenInt.ThreadPoolTest<double>(); GenDouble.ThreadPoolTest<double>(); GenString.ThreadPoolTest<double>(); GenObject.ThreadPoolTest<double>(); GenGuid.ThreadPoolTest<double>(); GenInt.ThreadPoolTest<string>(); GenDouble.ThreadPoolTest<string>(); GenString.ThreadPoolTest<string>(); GenObject.ThreadPoolTest<string>(); GenGuid.ThreadPoolTest<string>(); GenInt.ThreadPoolTest<object>(); GenDouble.ThreadPoolTest<object>(); GenString.ThreadPoolTest<object>(); GenObject.ThreadPoolTest<object>(); GenGuid.ThreadPoolTest<object>(); GenInt.ThreadPoolTest<Guid>(); GenDouble.ThreadPoolTest<Guid>(); GenString.ThreadPoolTest<Guid>(); GenObject.ThreadPoolTest<Guid>(); GenGuid.ThreadPoolTest<Guid>(); if (result) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * 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.Runtime.InteropServices; using System.Windows.Forms; namespace Microsoft.DirectX.Direct3D { public sealed class PresentParameters : ICloneable { [StructLayout(LayoutKind.Sequential)] internal struct D3DPRESENT_PARAMETERS { public int BackBufferWidth; public int BackBufferHeight; public int BackBufferFormat; public int BackBufferCount; public int MultiSampleType; public int MultiSampleQuality; public int SwapEffect; public IntPtr hDeviceWindow; public bool Windowed; public bool EnableAutoDepthStencil; public int AutoDepthStencilFormat; public int Flags; public int FullScreen_RefreshRateInHz; public int PresentationInterval; } internal D3DPRESENT_PARAMETERS _params; private Control deviceWindowControl; public int MultiSampleQuality { get { return _params.MultiSampleQuality; } set { _params.MultiSampleQuality = value; } } public PresentInterval PresentationInterval { get { return (PresentInterval)_params.PresentationInterval; } set { _params.PresentationInterval = (int)value; } } public int FullScreenRefreshRateInHz { get { return _params.FullScreen_RefreshRateInHz; } set { _params.FullScreen_RefreshRateInHz = value; } } public PresentFlag PresentFlag { get { return (PresentFlag)_params.Flags; } set { _params.Flags = (int)value; } } public DepthFormat AutoDepthStencilFormat { get { return (DepthFormat)_params.AutoDepthStencilFormat; } set { _params.AutoDepthStencilFormat = (int)value; } } public bool EnableAutoDepthStencil { get { return _params.EnableAutoDepthStencil; } set { _params.EnableAutoDepthStencil = value; } } public bool Windowed { get { return _params.Windowed; } set { _params.Windowed = value; } } public IntPtr DeviceWindowHandle { get { return _params.hDeviceWindow; } set { _params.hDeviceWindow = value; deviceWindowControl = null; } } public Control DeviceWindow { get { return deviceWindowControl; } set { if (value != null) { DeviceWindowHandle = value.Handle; deviceWindowControl = value; } else DeviceWindowHandle = IntPtr.Zero; } } public SwapEffect SwapEffect { get { return (SwapEffect)_params.SwapEffect; } set { _params.SwapEffect = (int)value; } } public MultiSampleType MultiSample { get { return (MultiSampleType)_params.MultiSampleType; } set { _params.MultiSampleType = (int)value; } } public int BackBufferCount { get { return _params.BackBufferCount; } set { _params.BackBufferCount = value; } } public Format BackBufferFormat { get { return (Format)_params.BackBufferFormat; } set { _params.BackBufferFormat = (int)value; } } public int BackBufferHeight { get { return _params.BackBufferHeight; } set { _params.BackBufferHeight = value; } } public int BackBufferWidth { get { return _params.BackBufferWidth; } set { _params.BackBufferWidth = value; } } public bool ForceNoMultiThreadedFlag { get; set; } public PresentParameters () { } public PresentParameters (PresentParameters original) { _params = original._params; deviceWindowControl = original.deviceWindowControl; } public object Clone () { return new PresentParameters(this); } public override string ToString () { throw new NotImplementedException (); } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- function MaterialEditorTools::createUndo(%this, %class, %desc) { pushInstantGroup(); %action = new UndoScriptAction() { class = %class; superClass = BaseMaterialEdAction; actionName = %desc; }; popInstantGroup(); return %action; } function MaterialEditorTools::submitUndo(%this, %action) { if(!%this.preventUndo) %action.addToManager(Editor.getUndoManager()); } function BaseMaterialEdAction::redo(%this) { %this.redo(); } function BaseMaterialEdAction::undo(%this) { } // Generic updateActiveMaterial redo/undo function ActionUpdateActiveMaterial::redo(%this) { if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { /* if( MaterialEditorTools.currentMaterial != %this.material ) { MaterialEditorTools.currentObject = %this.object; MaterialEditorTools.setMode(); MaterialEditorTools.setActiveMaterial(%this.material); } */ eval("materialEd_previewMaterial." @ %this.field @ " = " @ %this.newValue @ ";"); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); if (MaterialEditorTools.livePreview == true) { eval("%this.material." @ %this.field @ " = " @ %this.newValue @ ";"); MaterialEditorTools.currentMaterial.flush(); MaterialEditorTools.currentMaterial.reload(); } MaterialEditorTools.preventUndo = true; MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialDirty(); MaterialEditorTools.preventUndo = false; } else { eval("%this.material." @ %this.field @ " = " @ %this.newValue @ ";"); %this.material.flush(); %this.material.reload(); } } function ActionUpdateActiveMaterial::undo(%this) { MaterialEditorTools.preventUndo = true; if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { /* if( MaterialEditorTools.currentMaterial != %this.material ) { MaterialEditorTools.currentObject = %this.object; MaterialEditorTools.setMode(); MaterialEditorTools.setActiveMaterial(%this.material); } */ eval("materialEd_previewMaterial." @ %this.field @ " = " @ %this.oldValue @ ";"); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); if (MaterialEditorTools.livePreview == true) { eval("%this.material." @ %this.field @ " = " @ %this.oldValue @ ";"); MaterialEditorTools.currentMaterial.flush(); MaterialEditorTools.currentMaterial.reload(); } MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialDirty(); } else { eval("%this.material." @ %this.field @ " = " @ %this.oldValue @ ";"); %this.material.flush(); %this.material.reload(); } MaterialEditorTools.preventUndo = false; } // Special case updateActiveMaterial redo/undo function ActionUpdateActiveMaterialAnimationFlags::redo(%this) { if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { /* if( MaterialEditorTools.currentMaterial != %this.material ) { MaterialEditorTools.currentObject = %this.object; MaterialEditorTools.setMode(); MaterialEditorTools.setActiveMaterial(%this.material); } */ eval("materialEd_previewMaterial.animFlags[" @ %this.layer @ "] = " @ %this.newValue @ ";"); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); if (MaterialEditorTools.livePreview == true) { eval("%this.material.animFlags[" @ %this.layer @ "] = " @ %this.newValue @ ";"); MaterialEditorTools.currentMaterial.flush(); MaterialEditorTools.currentMaterial.reload(); } MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialDirty(); } else { eval("%this.material.animFlags[" @ %this.layer @ "] = " @ %this.newValue @ ";"); %this.material.flush(); %this.material.reload(); } } function ActionUpdateActiveMaterialAnimationFlags::undo(%this) { if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { eval("materialEd_previewMaterial.animFlags[" @ %this.layer @ "] = " @ %this.oldValue @ ";"); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); if (MaterialEditorTools.livePreview == true) { eval("%this.material.animFlags[" @ %this.layer @ "] = " @ %this.oldValue @ ";"); MaterialEditorTools.currentMaterial.flush(); MaterialEditorTools.currentMaterial.reload(); } MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialDirty(); } else { eval("%this.material.animFlags[" @ %this.layer @ "] = " @ %this.oldValue @ ";"); %this.material.flush(); %this.material.reload(); } } function ActionUpdateActiveMaterialName::redo(%this) { %this.material.setName(%this.newName); MaterialEditorTools.updateMaterialReferences( MissionGroup, %this.oldName, %this.newName ); if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialDirty(); } } function ActionUpdateActiveMaterialName::undo(%this) { %this.material.setName(%this.oldName); MaterialEditorTools.updateMaterialReferences( MissionGroup, %this.newName, %this.oldName ); if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialDirty(); } } function ActionRefreshMaterial::redo(%this) { if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { %this.material.setName( %this.newName ); MaterialEditorTools.copyMaterials( %this.newMaterial, materialEd_previewMaterial ); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); if (MaterialEditorTools.livePreview == true) { MaterialEditorTools.copyMaterials( %this.newMaterial , %this.material ); %this.material.flush(); %this.material.reload(); } MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialNotDirty(); } else { MaterialEditorTools.copyMaterials( %this.newMaterial, %this.material ); %this.material.flush(); %this.material.reload(); } } function ActionRefreshMaterial::undo(%this) { if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { %this.material.setName( %this.oldName ); MaterialEditorTools.copyMaterials( %this.oldMaterial, materialEd_previewMaterial ); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); if (MaterialEditorTools.livePreview == true) { MaterialEditorTools.copyMaterials( %this.oldMaterial, %this.material ); %this.material.flush(); %this.material.reload(); } MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialDirty(); } else { MaterialEditorTools.copyMaterials( %this.oldMaterial, %this.material ); %this.material.flush(); %this.material.reload(); } } function ActionClearMaterial::redo(%this) { if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { MaterialEditorTools.copyMaterials( %this.newMaterial, materialEd_previewMaterial ); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); if (MaterialEditorTools.livePreview == true) { MaterialEditorTools.copyMaterials( %this.newMaterial, %this.material ); %this.material.flush(); %this.material.reload(); } MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialDirty(); } else { MaterialEditorTools.copyMaterials( %this.newMaterial, %this.material ); %this.material.flush(); %this.material.reload(); } } function ActionClearMaterial::undo(%this) { if( MaterialEditorPreviewWindow.isVisible() && MaterialEditorTools.currentMaterial == %this.material ) { MaterialEditorTools.copyMaterials( %this.oldMaterial, materialEd_previewMaterial ); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); if (MaterialEditorTools.livePreview == true) { MaterialEditorTools.copyMaterials( %this.oldMaterial, %this.material ); %this.material.flush(); %this.material.reload(); } MaterialEditorTools.guiSync( materialEd_previewMaterial ); MaterialEditorTools.setMaterialDirty(); } else { MaterialEditorTools.copyMaterials( %this.oldMaterial, %this.material ); %this.material.flush(); %this.material.reload(); } } function ActionChangeMaterial::redo(%this) { if( %this.mode $= "model" ) { %this.object.changeMaterial( %this.materialTarget, %this.fromMaterial.getName(), %this.toMaterial.getName() ); MaterialEditorTools.currentObject = %this.object; if( %this.toMaterial.getFilename() !$= "tlab/gui/oldmatSelector.ed.gui" || %this.toMaterial.getFilename() !$= "tlab/materialEditor/scripts/materialEditor.ed.cs") { matEd_PersistMan.removeObjectFromFile(%this.toMaterial); } matEd_PersistMan.setDirty(%this.fromMaterial); matEd_PersistMan.setDirty(%this.toMaterial, %this.toMaterialNewFname); matEd_PersistMan.saveDirty(); matEd_PersistMan.removeDirty(%this.fromMaterial); matEd_PersistMan.removeDirty(%this.toMaterial); } else { eval("%this.object." @ %this.materialTarget @ " = " @ %this.toMaterial.getName() @ ";"); MaterialEditorTools.currentObject.postApply(); } if( MaterialEditorPreviewWindow.isVisible() ) MaterialEditorTools.setActiveMaterial( %this.toMaterial ); } function ActionChangeMaterial::undo(%this) { if( %this.mode $= "model" ) { %this.object.changeMaterial( %this.materialTarget, %this.toMaterial.getName(), %this.fromMaterial.getName() ); MaterialEditorTools.currentObject = %this.object; if( %this.toMaterial.getFilename() !$= "tlab/gui/oldmatSelector.ed.gui" || %this.toMaterial.getFilename() !$= "tlab/materialEditor/scripts/materialEditor.ed.cs") { matEd_PersistMan.removeObjectFromFile(%this.toMaterial); } matEd_PersistMan.setDirty(%this.fromMaterial); matEd_PersistMan.setDirty(%this.toMaterial, %this.toMaterialOldFname); matEd_PersistMan.saveDirty(); matEd_PersistMan.removeDirty(%this.fromMaterial); matEd_PersistMan.removeDirty(%this.toMaterial); } else { eval("%this.object." @ %this.materialTarget @ " = " @ %this.fromMaterial.getName() @ ";"); MaterialEditorTools.currentObject.postApply(); } if( MaterialEditorPreviewWindow.isVisible() ) MaterialEditorTools.setActiveMaterial( %this.fromMaterial ); } function ActionCreateNewMaterial::redo(%this) { if( MaterialEditorPreviewWindow.isVisible() ) { if( MaterialEditorTools.currentMaterial != %this.newMaterial ) { MaterialEditorTools.currentObject = ""; MaterialEditorTools.setMode(); MaterialEditorTools.setActiveMaterial(%this.newMaterial); } MaterialEditorTools.copyMaterials( %this.newMaterial, materialEd_previewMaterial ); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); MaterialEditorTools.guiSync( materialEd_previewMaterial ); } %idx = UnlistedMaterials.getIndexFromValue( %this.newMaterial.getName() ); UnlistedMaterials.erase( %idx ); } function ActionCreateNewMaterial::undo(%this) { if( MaterialEditorPreviewWindow.isVisible() ) { if( MaterialEditorTools.currentMaterial != %this.oldMaterial ) { MaterialEditorTools.currentObject = ""; MaterialEditorTools.setMode(); MaterialEditorTools.setActiveMaterial(%this.oldMaterial); } MaterialEditorTools.copyMaterials( %this.oldMaterial, materialEd_previewMaterial ); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); MaterialEditorTools.guiSync( materialEd_previewMaterial ); } UnlistedMaterials.add( "unlistedMaterials", %this.newMaterial.getName() ); } function ActionDeleteMaterial::redo(%this) { if( MaterialEditorPreviewWindow.isVisible() ) { if( MaterialEditorTools.currentMaterial != %this.newMaterial ) { MaterialEditorTools.currentObject = ""; MaterialEditorTools.setMode(); MaterialEditorTools.setActiveMaterial(%this.newMaterial); } MaterialEditorTools.copyMaterials( %this.newMaterial, materialEd_previewMaterial ); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); MaterialEditorTools.guiSync( materialEd_previewMaterial ); } if( %this.oldMaterial.getFilename() !$= "tlab/gui/oldmatSelector.ed.gui" || %this.oldMaterial.getFilename() !$= "tlab/materialEditor/scripts/materialEditor.ed.cs") { matEd_PersistMan.removeObjectFromFile(%this.oldMaterial); } UnlistedMaterials.add( "unlistedMaterials", %this.oldMaterial.getName() ); } function ActionDeleteMaterial::undo(%this) { if( MaterialEditorPreviewWindow.isVisible() ) { if( MaterialEditorTools.currentMaterial != %this.oldMaterial ) { MaterialEditorTools.currentObject = ""; MaterialEditorTools.setMode(); MaterialEditorTools.setActiveMaterial(%this.oldMaterial); } MaterialEditorTools.copyMaterials( %this.oldMaterial, materialEd_previewMaterial ); materialEd_previewMaterial.flush(); materialEd_previewMaterial.reload(); MaterialEditorTools.guiSync( materialEd_previewMaterial ); } matEd_PersistMan.setDirty(%this.oldMaterial, %this.oldMaterialFname); matEd_PersistMan.saveDirty(); matEd_PersistMan.removeDirty(%this.oldMaterial); %idx = UnlistedMaterials.getIndexFromValue( %this.oldMaterial.getName() ); UnlistedMaterials.erase( %idx ); }