context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ByteTest.cs - NUnit Test Cases for the System.Byte struct // // Mario Martinez (mariom925@home.om) // // (C) Ximian, Inc. http://www.ximian.com // using NUnit.Framework; using System; using System.Globalization; using System.Threading; namespace MonoTests.System { [TestFixture] public class ByteTest : Assertion { private const Byte MyByte1 = 42; private const Byte MyByte2 = 0; private const Byte MyByte3 = 255; private const string MyString1 = "42"; private const string MyString2 = "0"; private const string MyString3 = "255"; private string[] Formats1 = {"c", "d", "e", "f", "g", "n", "p", "x" }; private string[] Formats2 = {"c5", "d5", "e5", "f5", "g5", "n5", "p5", "x5" }; private string[] Results1 = { "", "0", "0.000000e+000", "0.00", "0", "0.00", "0.00 %", "0"}; private string[] Results1_Nfi = {NumberFormatInfo.InvariantInfo.CurrencySymbol+"0.00", "0", "0.000000e+000", "0.00", "0", "0.00", "0.00 %", "0"}; private string[] Results2 = { "", "00255", "2.55000e+002", "255.00000", "255", "255.00000", "25,500.00000 %", "000ff"}; private string[] Results2_Nfi = {NumberFormatInfo.InvariantInfo.CurrencySymbol+"255.00000", "00255", "2.55000e+002", "255.00000", "255", "255.00000", "25,500.00000 %", "000ff"}; private NumberFormatInfo Nfi = NumberFormatInfo.InvariantInfo; public ByteTest() {} [SetUp] public void SetUp() { CultureInfo EnUs = new CultureInfo ("en-us", false); EnUs.NumberFormat.NumberDecimalDigits = 2; Thread.CurrentThread.CurrentCulture = EnUs; int cdd = NumberFormatInfo.CurrentInfo.CurrencyDecimalDigits; string sep = NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator; string csym = NumberFormatInfo.CurrentInfo.CurrencySymbol; string csuffix = (cdd > 0 ? sep : "").PadRight(cdd + (cdd > 0 ? 1 : 0), '0'); switch (NumberFormatInfo.CurrentInfo.CurrencyPositivePattern) { case 0: // $n Results1[0] = csym + "0" + csuffix; Results2[0] = csym + "255" + sep + "00000"; break; case 1: // n$ Results1[0] = "0" + csuffix + csym; Results2[0] = "255" + sep + "00000" + csym; break; case 2: // $ n Results1[0] = csym + " 0" + csuffix; Results2[0] = csym + " 255" + sep + "00000"; break; case 3: // n $ Results1[0] = "0" + csuffix + " " + csym; Results2[0] = "255" + sep + "00000 " + csym; break; } sep = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator; string decimals = new String ('0', NumberFormatInfo.CurrentInfo.NumberDecimalDigits); string perPattern = new string[] {"n %","n%","%n"} [NumberFormatInfo.CurrentInfo.PercentPositivePattern]; Results1[2] = "0" + sep + "000000e+000"; Results1[3] = "0" + sep + decimals; Results1[5] = "0" + sep + decimals; Results1[6] = perPattern.Replace ("n","0" + sep + "00"); Results2[2] = "2" + sep + "55000e+002"; Results2[3] = "255" + sep + "00000"; Results2[3] = "255" + sep + "00000"; Results2[5] = "255" + sep + "00000"; string gsep = NumberFormatInfo.CurrentInfo.NumberGroupSeparator; Results2[6] = perPattern.Replace ("n","25" + gsep + "500" + sep + "00000"); } public void TestMinMax() { AssertEquals(Byte.MinValue, MyByte2); AssertEquals(Byte.MaxValue, MyByte3); } public void TestCompareTo() { Assert(MyByte3.CompareTo(MyByte2) > 0); Assert(MyByte2.CompareTo(MyByte2) == 0); Assert(MyByte1.CompareTo((object)(Byte)42) == 0); Assert(MyByte2.CompareTo(MyByte3) < 0); try { MyByte2.CompareTo((object)100); Fail("Should raise a System.ArgumentException"); } catch (Exception e) { Assert(typeof(ArgumentException) == e.GetType()); } } public void TestEquals() { Assert(MyByte1.Equals(MyByte1)); Assert(MyByte1.Equals((object)(Byte)42)); Assert(MyByte1.Equals((object)(Int16)42) == false); Assert(MyByte1.Equals(MyByte2) == false); } public void TestGetHashCode() { try { MyByte1.GetHashCode(); MyByte2.GetHashCode(); MyByte3.GetHashCode(); } catch { Fail("GetHashCode should not raise an exception here"); } } public void TestParse() { //test Parse(string s) Assert("MyByte1="+MyByte1+", MyString1="+MyString1+", Parse="+Byte.Parse(MyString1) , MyByte1 == Byte.Parse(MyString1)); Assert("MyByte2", MyByte2 == Byte.Parse(MyString2)); Assert("MyByte3", MyByte3 == Byte.Parse(MyString3)); try { Byte.Parse(null); Fail("Should raise a System.ArgumentNullException"); } catch (Exception e) { Assert("Should get ArgumentNullException", typeof(ArgumentNullException) == e.GetType()); } try { Byte.Parse("not-a-number"); Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert("not-a-number", typeof(FormatException) == e.GetType()); } //test Parse(string s, NumberStyles style) AssertEquals(" "+NumberFormatInfo.CurrentInfo.CurrencySymbol+"42 ", (byte)42, Byte.Parse(" "+NumberFormatInfo.CurrentInfo.CurrencySymbol+"42 ", NumberStyles.Currency)); try { Byte.Parse(NumberFormatInfo.CurrentInfo.CurrencySymbol+"42", NumberStyles.Integer); Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert(NumberFormatInfo.CurrentInfo.CurrencySymbol+"42 and NumberStyles.Integer", typeof(FormatException) == e.GetType()); } //test Parse(string s, IFormatProvider provider) Assert(" 42 and Nfi", 42 == Byte.Parse(" 42 ", Nfi)); try { Byte.Parse("%42", Nfi); Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert("%42 and Nfi", typeof(FormatException) == e.GetType()); } //test Parse(string s, NumberStyles style, IFormatProvider provider) Assert("NumberStyles.HexNumber", 16 == Byte.Parse(" 10 ", NumberStyles.HexNumber, Nfi)); try { Byte.Parse(NumberFormatInfo.CurrentInfo.CurrencySymbol+"42", NumberStyles.Integer, Nfi); Fail("Should raise a System.FormatException"); } catch (Exception e) { Assert(NumberFormatInfo.CurrentInfo.CurrencySymbol+"42, NumberStyles.Integer, Nfi", typeof(FormatException) == e.GetType()); } } [Test] [ExpectedException (typeof(OverflowException))] public void ParseOverflow() { int OverInt = Byte.MaxValue + 1; Byte.Parse(OverInt.ToString()); } public void TestToString() { //test ToString() AssertEquals("Compare failed for MyString1 and MyByte1", MyString1, MyByte1.ToString()); AssertEquals("Compare failed for MyString2 and MyByte2", MyString2, MyByte2.ToString()); AssertEquals("Compare failed for MyString3 and MyByte3", MyString3, MyByte3.ToString()); //test ToString(string format) for (int i=0; i < Formats1.Length; i++) { AssertEquals("Compare failed for Formats1["+i.ToString()+"]", Results1[i], MyByte2.ToString(Formats1[i])); AssertEquals("Compare failed for Formats2["+i.ToString()+"]", Results2[i], MyByte3.ToString(Formats2[i])); } //test ToString(string format, IFormatProvider provider); for (int i=0; i < Formats1.Length; i++) { AssertEquals("Compare failed for Formats1["+i.ToString()+"] with Nfi", Results1_Nfi[i], MyByte2.ToString(Formats1[i], Nfi)); AssertEquals("Compare failed for Formats2["+i.ToString()+"] with Nfi", Results2_Nfi[i], MyByte3.ToString(Formats2[i], Nfi)); } try { MyByte1.ToString("z"); Fail("Should raise a System.FormatException"); } catch (Exception e) { AssertEquals("Exception is the wrong type", typeof(FormatException), e.GetType()); } } [Test] public void ToString_Defaults () { byte i = 254; // everything defaults to "G" string def = i.ToString ("G"); AssertEquals ("ToString()", def, i.ToString ()); AssertEquals ("ToString((IFormatProvider)null)", def, i.ToString ((IFormatProvider)null)); AssertEquals ("ToString((string)null)", def, i.ToString ((string)null)); AssertEquals ("ToString(empty)", def, i.ToString (String.Empty)); AssertEquals ("ToString(null,null)", def, i.ToString (null, null)); AssertEquals ("ToString(empty,null)", def, i.ToString (String.Empty, null)); AssertEquals ("ToString(G)", "254", def); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.DDF { using System; using System.Text; using System.Collections; using NPOI.Util; /// <summary> /// Escher array properties are the most wierd construction ever invented /// with all sorts of special cases. I'm hopeful I've got them all. /// @author Glen Stampoultzis (glens at superlinksoftware.com) /// </summary> internal class EscherArrayProperty : EscherComplexProperty { /** * The size of the header that goes at the * start of the array, before the data */ private const int FIXED_SIZE = 3 * 2; /** * Normally, the size recorded in the simple data (for the complex * data) includes the size of the header. * There are a few cases when it doesn't though... */ private bool sizeIncludesHeaderSize = true; /** * When Reading a property from data stream remeber if the complex part is empty and Set this flag. */ private bool emptyComplexPart = false; public EscherArrayProperty(short id, byte[] complexData) : base(id, CheckComplexData(complexData)) { emptyComplexPart = complexData.Length == 0; } public EscherArrayProperty(short propertyNumber, bool isBlipId, byte[] complexData) : base(propertyNumber, isBlipId, CheckComplexData(complexData)) { } private static byte[] CheckComplexData(byte[] complexData) { if (complexData == null || complexData.Length == 0) complexData = new byte[6]; return complexData; } public int NumberOfElementsInArray { get { return LittleEndian.GetUShort(complexData, 0); } set { int expectedArraySize = value * GetActualSizeOfElements(SizeOfElements) + FIXED_SIZE; if (expectedArraySize != complexData.Length) { byte[] newArray = new byte[expectedArraySize]; Array.Copy(complexData, 0, newArray, 0, complexData.Length); complexData = newArray; } LittleEndian.PutShort(complexData, 0, (short)value); } } public int NumberOfElementsInMemory { get { return LittleEndian.GetUShort(complexData, 2); } set { int expectedArraySize = value * GetActualSizeOfElements(this.SizeOfElements) + FIXED_SIZE; if (expectedArraySize != complexData.Length) { byte[] newArray = new byte[expectedArraySize]; Array.Copy(complexData, 0, newArray, 0, expectedArraySize); complexData = newArray; } LittleEndian.PutShort(complexData, 2, (short)value); } } public short SizeOfElements { get { return LittleEndian.GetShort(complexData, 4); } set { LittleEndian.PutShort(complexData, 4, (short)value); int expectedArraySize = NumberOfElementsInArray * GetActualSizeOfElements(SizeOfElements) + FIXED_SIZE; if (expectedArraySize != complexData.Length) { // Keep just the first 6 bytes. The rest is no good to us anyway. byte[] newArray = new byte[expectedArraySize]; Array.Copy(complexData, 0, newArray, 0, 6); complexData = newArray; } } } /// <summary> /// Gets the element. /// </summary> /// <param name="index">The index.</param> /// <returns></returns> public byte[] GetElement(int index) { int actualSize = GetActualSizeOfElements(SizeOfElements); byte[] result = new byte[actualSize]; Array.Copy(complexData, FIXED_SIZE + index * actualSize, result, 0, result.Length); return result; } /// <summary> /// Sets the element. /// </summary> /// <param name="index">The index.</param> /// <param name="element">The element.</param> public void SetElement(int index, byte[] element) { int actualSize = GetActualSizeOfElements(SizeOfElements); Array.Copy(element, 0, complexData, FIXED_SIZE + index * actualSize, actualSize); } /// <summary> /// Retrieves the string representation for this property. /// </summary> /// <returns></returns> public override String ToString() { String nl = Environment.NewLine; StringBuilder results = new StringBuilder(); results.Append(" {EscherArrayProperty:" + nl); results.Append(" Num Elements: " + NumberOfElementsInArray + nl); results.Append(" Num Elements In Memory: " + NumberOfElementsInMemory + nl); results.Append(" Size of elements: " + SizeOfElements + nl); for (int i = 0; i < NumberOfElementsInArray; i++) { results.Append(" Element " + i + ": " + HexDump.ToHex(GetElement(i)) + nl); } results.Append("}" + nl); return "propNum: " + PropertyNumber + ", propName: " + EscherProperties.GetPropertyName(PropertyNumber) + ", complex: " + IsComplex + ", blipId: " + IsBlipId + ", data: " + nl + results.ToString(); } /// <summary> /// We have this method because the way in which arrays in escher works /// is screwed for seemly arbitary reasons. While most properties are /// fairly consistent and have a predictable array size, escher arrays /// have special cases. /// </summary> /// <param name="data">The data array containing the escher array information</param> /// <param name="offset">The offset into the array to start Reading from.</param> /// <returns>the number of bytes used by this complex property.</returns> public int SetArrayData(byte[] data, int offset) { if (emptyComplexPart) { complexData = new byte[0]; } else { short numElements = LittleEndian.GetShort(data, offset); short numReserved = LittleEndian.GetShort(data, offset + 2); short sizeOfElements = LittleEndian.GetShort(data, offset + 4); int arraySize = GetActualSizeOfElements(sizeOfElements) * numElements; if (arraySize == complexData.Length) { // The stored data size in the simple block excludes the header size complexData = new byte[arraySize + 6]; sizeIncludesHeaderSize = false; } Array.Copy(data, offset, complexData, 0, complexData.Length); } return complexData.Length; } /// <summary> /// Serializes the simple part of this property. ie the first 6 bytes. /// Needs special code to handle the case when the size doesn't /// include the size of the header block /// </summary> /// <param name="data"></param> /// <param name="pos"></param> /// <returns></returns> public override int SerializeSimplePart(byte[] data, int pos) { LittleEndian.PutShort(data, pos, Id); int recordSize = complexData.Length; if (!sizeIncludesHeaderSize) { recordSize -= 6; } LittleEndian.PutInt(data, pos + 2, recordSize); return 6; } /// <summary> /// Sometimes the element size is stored as a negative number. We /// negate it and shift it to Get the real value. /// </summary> /// <param name="sizeOfElements">The size of elements.</param> /// <returns></returns> public static int GetActualSizeOfElements(short sizeOfElements) { if (sizeOfElements < 0) return (short)((-sizeOfElements) >> 2); else return sizeOfElements; } } }
using System; using System.Collections.Generic; using CamBam.Geom; using CamBam.CAD; using Geom; namespace Matmill { public enum Sliced_path_item_type { SLICE, SPIRAL, CHORD, SMOOTH_CHORD, GUIDE, SLICE_SHORTCUT, RETURN_TO_BASE, DEBUG_MEDIAL_AXIS, } public class Sliced_path : List<Sliced_path_item> { public object Extension; } public class Sliced_path_item: Polyline { public readonly Sliced_path_item_type Item_type; public Sliced_path_item(Sliced_path_item_type type) : base() { Item_type = type; } public Sliced_path_item(Sliced_path_item_type type, int i) : base(i) { Item_type = type; } public Sliced_path_item(Sliced_path_item_type type, Polyline p) : base(p) { Item_type = type; } public void Add(Point2F pt) { base.Add(new Point3F(pt.X, pt.Y, 0)); } public void Add(Curve2d curve) { foreach (Point2F pt in curve.Points) this.Add(pt); } public void Add(Biarc2d biarc, double tolerance) { if (biarc.Seg1 is Arc2F) this.Add((Arc2F)biarc.Seg1, tolerance); else this.Add((Line2F)biarc.Seg1, tolerance); if (biarc.Seg2 is Arc2F) this.Add((Arc2F)biarc.Seg2, tolerance); else this.Add((Line2F)biarc.Seg2, tolerance); } } class Sliced_path_generator { protected double _general_tolerance; public Sliced_path Path = new Sliced_path(); protected Slice _last_slice = null; protected void append_slice(Slice slice) { // emit segments for (int segidx = 0; segidx < slice.Segments.Count; segidx++) { // connect segments if (segidx > 0) { Sliced_path_item shortcut = new Sliced_path_item(Sliced_path_item_type.SLICE_SHORTCUT); shortcut.Add(slice.Segments[segidx - 1].P2); shortcut.Add(slice.Segments[segidx].P1); Path.Add(shortcut); } Sliced_path_item arc = new Sliced_path_item(Sliced_path_item_type.SLICE); arc.Add(slice.Segments[segidx], _general_tolerance); Path.Add(arc); } _last_slice = slice; } protected Sliced_path_item connect_slices(Slice dst, Slice src) { Sliced_path_item path = new Sliced_path_item(Sliced_path_item_type.CHORD); path.Add(src.End); path.Add(dst.Start); return path; } public void Append_spiral(Point2F start, Point2F end, Vector2d start_tangent, double ted, double tool_r, RotationDirection dir) { Sliced_path_item spiral = new Sliced_path_item(Sliced_path_item_type.SPIRAL); double spacing = Spiral_generator.Calc_reverse_spacing(end.DistanceTo(start), tool_r, ted, _general_tolerance); foreach (Biarc2d biarc in Spiral_generator.Gen_archimedean_spiral(start, end, start_tangent, spacing, dir)) spiral.Add(biarc, _general_tolerance); Path.Add(spiral); } public void Append_root_slice(Slice slice) { append_slice(slice); } public virtual void Append_slice(Slice slice, List<Point2F> guide) { if (_last_slice == null) throw new Exception("attempt to install slice without the root slice"); if (guide == null) { Path.Add(connect_slices(slice, _last_slice)); } else { Sliced_path_item p = new Sliced_path_item(Sliced_path_item_type.GUIDE); p.Add(_last_slice.End); foreach (Point2F pt in guide) p.Add(pt); p.Add(slice.Start); Path.Add(p); } append_slice(slice); } public void Append_return_to_base(List<Point2F> exit) { Sliced_path_item p = new Sliced_path_item(Sliced_path_item_type.RETURN_TO_BASE); p.Add(_last_slice.End); foreach (Point2F pt in exit) p.Add(pt); Path.Add(p); } public void Append_slice_sequence(Slice_sequence sequence) { this.Append_root_slice(sequence.Root_slice); for (int i = 1; i < sequence.Slices.Count; i++) { Slice s = sequence.Slices[i]; this.Append_slice(s, s.Guide); } } public Sliced_path_generator(double general_tolerance) { _general_tolerance = general_tolerance; } } class Sliced_path_smooth_generator : Sliced_path_generator { double _min_arc_len; private bool is_biarc_inside_ball(Biarc2d biarc, Circle2F ball) { if (biarc.Pm.DistanceTo(ball.Center) > ball.Radius) return false; Point2F start = biarc.P1; Point2F end = biarc.P2; Line2F insects; if (biarc.Seg1 is Line2F) insects = ball.LineIntersect((Line2F)biarc.Seg1); else insects = ((Arc2F)biarc.Seg1).CircleIntersect(ball); if ((!insects.p1.IsUndefined) && insects.p1.DistanceTo(start) < _general_tolerance) insects.p1 = Point2F.Undefined; if ((!insects.p2.IsUndefined) && insects.p2.DistanceTo(start) < _general_tolerance) insects.p2 = Point2F.Undefined; if (!(insects.p1.IsUndefined && insects.p2.IsUndefined)) return false; if (biarc.Seg2 is Line2F) insects = ball.LineIntersect((Line2F)biarc.Seg2); else insects = ((Arc2F)biarc.Seg2).CircleIntersect(ball); if ((!insects.p1.IsUndefined) && insects.p1.DistanceTo(end) < _general_tolerance) insects.p1 = Point2F.Undefined; if ((!insects.p2.IsUndefined) && insects.p2.DistanceTo(end) < _general_tolerance) insects.p2 = Point2F.Undefined; if (!(insects.p1.IsUndefined && insects.p2.IsUndefined)) return false; return true; } private Sliced_path_item connect_slices_with_biarc(Slice dst, Slice src) { Point2F start = src.End; Point2F end = dst.Start; // unit normals to points Vector2d vn_start = new Vector2d(src.Center, start).Unit(); Vector2d vn_end = new Vector2d(dst.Center, end).Unit(); // tangents to points Vector2d vt_start; Vector2d vt_end; if (src.Dir == RotationDirection.CW) vt_start = new Vector2d(vn_start.Y, -vn_start.X); else vt_start = new Vector2d(-vn_start.Y, vn_start.X); if (dst.Dir == RotationDirection.CW) vt_end = new Vector2d(vn_end.Y, -vn_end.X); else vt_end = new Vector2d(-vn_end.Y, vn_end.X); Biarc2d biarc = new Biarc2d(start, vt_start, end, vt_end); if (!is_biarc_inside_ball(biarc, src.Ball)) return null; Sliced_path_item path = new Sliced_path_item(Sliced_path_item_type.SMOOTH_CHORD); path.Add(biarc, _general_tolerance); return path; } private Sliced_path_item smooth_connect_slices(Slice dst, Slice src) { Sliced_path_item path = null; // do not emit biarcs if distance is too small if (src.End.DistanceTo(dst.Start) > _min_arc_len) { path = connect_slices_with_biarc(dst, src); if (path == null) Logger.warn("biarc is outside the slice, replacing with chord"); } return path; } public override void Append_slice(Slice slice, List<Point2F> guide) { if (guide == null) { Sliced_path_item biarc = smooth_connect_slices(slice, _last_slice); if (biarc != null) { Path.Add(biarc); append_slice(slice); return; } } base.Append_slice(slice, guide); } public Sliced_path_smooth_generator(double general_tolerance, double min_arc_len) : base(general_tolerance) { _min_arc_len = min_arc_len; } } }
/* Copyright (c) 2010-2015 by Genstein and Jason Lautzenheiser. This file is (or was originally) part of Trizbort, the Interactive Fiction Mapper. 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.Text; namespace Trizbort { public struct LineSegment { public LineSegment(Vector start, Vector end) { Start = start; End = end; } public float Length { get { return Delta.Length; } } public Vector Delta { get { return End - Start; } } /// <summary> /// Shorten this line segment, moving the end point towards the start point. /// </summary> /// <param name="amount">The amount by which to shorten.</param> public bool Shorten(float amount) { var delta = Delta; var length = delta.Length; delta.Normalize(); if (length > amount) { length -= amount; End = Start + delta * length; return true; } else { // don't shorten past zero length End = Start; return false; } } /// <summary> /// Shorten this line segment, moving the start point towards the end point. /// </summary> /// <param name="amount">The amount by which to shorten.</param> public bool Forshorten(float amount) { Reverse(); var result = Shorten(amount); Reverse(); return result; } /// <summary> /// Reverse the direction of this line segment. /// </summary> public void Reverse() { var temp = End; End = Start; Start = temp; } /// <summary> /// Find the intersection point(s) between two line segments, if any. /// </summary> /// <param name="other">The other line segment.</param> /// <returns>A list of one or more intersections, or null if the line segments do not intersect.</returns> public bool Intersect(LineSegment other, bool ignoreEndPointIntersects, out List<LineSegmentIntersect> intersects) { return Intersect(this, other, ignoreEndPointIntersects, out intersects); } public bool Intersect(LineSegment a, LineSegment b, bool ignoreEndPointIntersects, out List<LineSegmentIntersect> intersects) { float ua = (b.End.X - b.Start.X) * (a.Start.Y - b.Start.Y) - (b.End.Y - b.Start.Y) * (a.Start.X - b.Start.X); float ub = (a.End.X - a.Start.X) * (a.Start.Y - b.Start.Y) - (a.End.Y - a.Start.Y) * (a.Start.X - b.Start.X); float denominator = (b.End.Y - b.Start.Y) * (a.End.X - a.Start.X) - (b.End.X - b.Start.X) * (a.End.Y - a.Start.Y); intersects = null; const float small = 0.01f; if (Math.Abs(denominator) <= small) { if (Math.Abs(ua) <= small && Math.Abs(ub) <= small) { // lines are coincident: // lacking other algorithms which actually work, // roll some expensive distance tests to find intersection points if (a.Start.DistanceFromLineSegment(b) <= small) { intersects = new List<LineSegmentIntersect>(); intersects.Add(new LineSegmentIntersect(LineSegmentIntersectType.StartA, a.Start)); } if (a.End.DistanceFromLineSegment(b) <= small) { if (intersects == null) intersects = new List<LineSegmentIntersect>(); intersects.Add(new LineSegmentIntersect(LineSegmentIntersectType.EndA, a.End)); } if (b.Start.DistanceFromLineSegment(a) <= small) { if (intersects == null) intersects = new List<LineSegmentIntersect>(); intersects.Add(new LineSegmentIntersect(LineSegmentIntersectType.MidPointA, b.Start)); } if (b.End.DistanceFromLineSegment(a) <= small) { if (intersects == null) intersects = new List<LineSegmentIntersect>(); intersects.Add(new LineSegmentIntersect(LineSegmentIntersectType.MidPointA, b.End)); } } } else { ua /= denominator; ub /= denominator; if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) { LineSegmentIntersectType type = LineSegmentIntersectType.MidPointA; if (ua <= small) { type = LineSegmentIntersectType.StartA; } else if (1 - ua <= small) { type = LineSegmentIntersectType.EndA; } intersects = new List<LineSegmentIntersect>(); intersects.Add(new LineSegmentIntersect(type, a.Start + new Vector(ua * (a.End.X - a.Start.X), ua * (a.End.Y - a.Start.Y)))); } } if (intersects != null && ignoreEndPointIntersects) { for (int index = 0; index < intersects.Count; ++index) { var intersect = intersects[index]; if (intersect.Position.Distance(a.Start) <= small || intersect.Position.Distance(b.Start) <= small || intersect.Position.Distance(a.End) <= small || intersect.Position.Distance(b.End) <= small) { intersects.RemoveAt(index); --index; } } } return intersects != null; } public bool IntersectsWith(Rect rect) { if (rect.Contains(Start) || rect.Contains(End)) { return true; } var a = new LineSegment(new Vector(rect.Left, rect.Top), new Vector(rect.Right, rect.Top)); var b = new LineSegment(new Vector(rect.Right, rect.Top), new Vector(rect.Right, rect.Bottom)); var c = new LineSegment(new Vector(rect.Right, rect.Bottom), new Vector(rect.Left, rect.Bottom)); var d = new LineSegment(new Vector(rect.Left, rect.Bottom), new Vector(rect.Left, rect.Top)); List<LineSegmentIntersect> intersects; if (Intersect(a, false, out intersects) || Intersect(b, false, out intersects) || Intersect(c, false, out intersects) || Intersect(d, false, out intersects)) { return true; } return false; } public Vector Start; public Vector End; public Vector Mid { get { return (Start + End) / 2; } } } /// <summary> /// The type of a line segment intersection. /// </summary> public enum LineSegmentIntersectType { MidPointA, StartA, EndA, } /// <summary> /// A line segment intersection. /// </summary> public struct LineSegmentIntersect { public LineSegmentIntersect(LineSegmentIntersectType type, Vector pos) { Type = type; Position = pos; } public LineSegmentIntersectType Type; public Vector Position; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Internal.Resources { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// To manage and control access to your resources, you can define /// customized policies and assign them at a scope. /// </summary> public partial class PolicyClient : ServiceClient<PolicyClient>, IPolicyClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The ID of the target subscription. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The API version to use for the operation. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IPolicyAssignmentsOperations. /// </summary> public virtual IPolicyAssignmentsOperations PolicyAssignments { get; private set; } /// <summary> /// Gets the IPolicyDefinitionsOperations. /// </summary> public virtual IPolicyDefinitionsOperations PolicyDefinitions { get; private set; } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected PolicyClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected PolicyClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected PolicyClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected PolicyClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolicyClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolicyClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolicyClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the PolicyClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public PolicyClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.PolicyAssignments = new PolicyAssignmentsOperations(this); this.PolicyDefinitions = new PolicyDefinitionsOperations(this); this.BaseUri = new Uri("https://management.azure.com"); this.ApiVersion = "2016-04-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// // Util.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin 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 Xwt.Drawing; using Xwt.Backends; using System.Collections.Generic; using System.Linq; namespace Xwt.GtkBackend { public static class Util { static uint targetIdCounter = 0; static Dictionary<TransferDataType, Gtk.TargetEntry[]> dragTargets = new Dictionary<TransferDataType, Gtk.TargetEntry[]> (); static Dictionary<string, TransferDataType> atomToType = new Dictionary<string, TransferDataType> (); static Size[] iconSizes = new Size[7]; static Util () { for (int i = 0; i < iconSizes.Length; i++) { int w, h; if (!Gtk.Icon.SizeLookup ((Gtk.IconSize)i, out w, out h)) w = h = -1; iconSizes[i].Width = w; iconSizes[i].Height = h; } if (Platform.IsWindows) { // Workaround for an issue in GTK for Windows. In windows Menu-sized icons are not 16x16, but 14x14 iconSizes[(int)Gtk.IconSize.Menu].Width = 16; iconSizes[(int)Gtk.IconSize.Menu].Height = 16; } } public static void SetDragData (TransferDataSource data, Gtk.DragDataGetArgs args) { foreach (var t in data.DataTypes) { object val = data.GetValue (t); SetSelectionData (args.SelectionData, t.Id, val); } } public static void SetSelectionData (Gtk.SelectionData data, string atomType, object val) { if (val == null) return; if (val is string) data.Text = (string)val; else if (val is Xwt.Drawing.Image) { var bmp = ((Image)val).ToBitmap (); data.SetPixbuf (((GtkImage)Toolkit.GetBackend (bmp)).Frames[0].Pixbuf); } else { var at = Gdk.Atom.Intern (atomType, false); data.Set (at, 0, TransferDataSource.SerializeValue (val)); } } public static bool GetSelectionData (ApplicationContext context, Gtk.SelectionData data, TransferDataStore target) { TransferDataType type = Util.AtomToType (data.Target.Name); if (type == null || data.Length <= 0) return false; if (type == TransferDataType.Text) target.AddText (data.Text); else if (data.TargetsIncludeImage (false)) target.AddImage (context.Toolkit.WrapImage (data.Pixbuf)); else if (type == TransferDataType.Uri) { var uris = System.Text.Encoding.UTF8.GetString (data.Data).Split ('\n').Where (u => !string.IsNullOrEmpty(u)).Select (u => new Uri (u)).ToArray (); target.AddUris (uris); } else target.AddValue (type, data.Data); return true; } internal static TransferDataType AtomToType (string targetName) { TransferDataType type; atomToType.TryGetValue (targetName, out type); return type; } internal static TransferDataType[] GetDragTypes (Gdk.Atom[] dropTypes) { List<TransferDataType> types = new List<TransferDataType> (); foreach (var dt in dropTypes) { TransferDataType type; if (atomToType.TryGetValue (dt.Name, out type)) types.Add (type); } return types.ToArray (); } public static Gtk.TargetList BuildTargetTable (TransferDataType[] types) { var tl = new Gtk.TargetList (); foreach (var tt in types) tl.AddTable (CreateTargetEntries (tt)); return tl; } static Gtk.TargetEntry[] CreateTargetEntries (TransferDataType type) { lock (dragTargets) { Gtk.TargetEntry[] entries; if (dragTargets.TryGetValue (type, out entries)) return entries; uint id = targetIdCounter++; if (type == TransferDataType.Uri) { Gtk.TargetList list = new Gtk.TargetList (); list.AddUriTargets (id); entries = (Gtk.TargetEntry[])list; } else if (type == TransferDataType.Text) { Gtk.TargetList list = new Gtk.TargetList (); list.AddTextTargets (id); //HACK: work around gtk_selection_data_set_text causing crashes on Mac w/ QuickSilver, Clipbard History etc. if (Platform.IsMac) { list.Remove ("COMPOUND_TEXT"); list.Remove ("TEXT"); list.Remove ("STRING"); } entries = (Gtk.TargetEntry[])list; } else if (type == TransferDataType.Rtf) { Gdk.Atom atom; if (Platform.IsMac) { atom = Gdk.Atom.Intern ("NSRTFPboardType", false); //TODO: use public.rtf when dep on MacOS 10.6 } else if (Platform.IsWindows) { atom = Gdk.Atom.Intern ("Rich Text Format", false); } else { atom = Gdk.Atom.Intern ("text/rtf", false); } entries = new Gtk.TargetEntry[] { new Gtk.TargetEntry (atom, 0, id) }; } else if (type == TransferDataType.Html) { Gdk.Atom atom; if (Platform.IsMac) { atom = Gdk.Atom.Intern ("Apple HTML pasteboard type", false); //TODO: use public.rtf when dep on MacOS 10.6 } else if (Platform.IsWindows) { atom = Gdk.Atom.Intern ("HTML Format", false); } else { atom = Gdk.Atom.Intern ("text/html", false); } entries = new Gtk.TargetEntry[] { new Gtk.TargetEntry (atom, 0, id) }; } else { entries = new Gtk.TargetEntry[] { new Gtk.TargetEntry (Gdk.Atom.Intern ("application/" + type.Id, false), 0, id) }; } foreach (var a in entries.Select (e => e.Target)) atomToType [a] = type; return dragTargets [type] = entries; } } static Dictionary<string,string> icons; public static GtkImage ToGtkStock (string id) { if (icons == null) { icons = new Dictionary<string, string> (); icons [StockIconId.ZoomIn] = Gtk.Stock.ZoomIn; icons [StockIconId.ZoomOut] = Gtk.Stock.ZoomOut; icons [StockIconId.Zoom100] = Gtk.Stock.Zoom100; icons [StockIconId.ZoomFit] = Gtk.Stock.ZoomFit; icons [StockIconId.OrientationPortrait] = Gtk.Stock.OrientationPortrait; icons [StockIconId.OrientationLandscape] = Gtk.Stock.OrientationLandscape; icons [StockIconId.Add] = Gtk.Stock.Add; icons [StockIconId.Remove] = Gtk.Stock.Remove; icons [StockIconId.Warning] = Gtk.Stock.DialogWarning; icons [StockIconId.Error] = Gtk.Stock.DialogError; icons [StockIconId.Information] = Gtk.Stock.DialogInfo; icons [StockIconId.Question] = Gtk.Stock.DialogQuestion; } string res; if (!icons.TryGetValue (id, out res)) throw new NotSupportedException ("Unknown image: " + id); return new GtkImage (res); } public static Gtk.IconSize GetBestSizeFit (double size, Gtk.IconSize[] availablesizes = null) { // Find the size that better fits the requested size for (int n=0; n<iconSizes.Length; n++) { if (availablesizes != null && !availablesizes.Contains ((Gtk.IconSize)n)) continue; if (size <= iconSizes [n].Width) return (Gtk.IconSize)n; } if (availablesizes == null || availablesizes.Contains (Gtk.IconSize.Dialog)) return Gtk.IconSize.Dialog; else return Gtk.IconSize.Invalid; } public static double GetBestSizeFitSize (double size) { var s = GetBestSizeFit (size); return iconSizes [(int)s].Width; } public static ImageDescription WithDefaultSize (this ImageDescription image, Gtk.IconSize defaultIconSize) { var s = iconSizes [(int)defaultIconSize]; if (!s.IsZero) image.Size = s; return image; } public static double GetScaleFactor (Gtk.Widget w) { return GtkWorkarounds.GetScaleFactor (w); } public static double GetDefaultScaleFactor () { return 1; } internal static void SetSourceColor (this Cairo.Context cr, Cairo.Color color) { cr.SetSourceRGBA (color.R, color.G, color.B, color.A); } //this is needed for building against old Mono.Cairo versions [Obsolete] internal static void SetSource (this Cairo.Context cr, Cairo.Pattern pattern) { cr.Pattern = pattern; } [Obsolete] internal static Cairo.Surface GetTarget (this Cairo.Context cr) { return cr.Target; } [Obsolete] internal static void Dispose (this Cairo.Context cr) { ((IDisposable)cr).Dispose (); } } }
#region Copyright (c) 2002-2003, James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole, Philip A. Craig /************************************************************************************ ' ' Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole ' Copyright 2000-2002 Philip A. Craig ' ' This software is provided 'as-is', without any express or implied warranty. In no ' event will the authors be held liable for any damages arising from the use of this ' software. ' ' Permission is granted to anyone to use this software for any purpose, including ' commercial applications, and to alter it and redistribute it freely, subject to the ' following restrictions: ' ' 1. The origin of this software must not be misrepresented; you must not claim that ' you wrote the original software. If you use this software in a product, an ' acknowledgment (see the following) in the product documentation is required. ' ' Portions Copyright 2002-2003 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov, Charlie Poole ' or Copyright 2000-2002 Philip A. Craig ' ' 2. Altered source versions must be plainly marked as such, and must not be ' misrepresented as being the original software. ' ' 3. This notice may not be removed or altered from any source distribution. ' '***********************************************************************************/ #endregion namespace NUnit.Util { using System; using System.IO; using System.Collections; using System.Configuration; using System.Threading; using NUnit.Core; /// <summary> /// TestLoader handles interactions between a test runner and a /// client program - typically the user interface - for the /// purpose of loading, unloading and running tests. /// /// It implemements the EventListener interface which is used by /// the test runner and repackages those events, along with /// others as individual events that clients may subscribe to /// in collaboration with a TestEventDispatcher helper object. /// /// TestLoader is quite handy for use with a gui client because /// of the large number of events it supports. However, it has /// no dependencies on ui components and can be used independently. /// </summary> public class TestLoader : LongLivingMarshalByRefObject, NUnit.Core.EventListener, ITestLoader { #region Instance Variables /// <summary> /// StdOut stream for use by the TestRunner /// </summary> private TextWriter stdOutWriter; /// <summary> /// StdErr stream for use by the TestRunner /// </summary> private TextWriter stdErrWriter; /// <summary> /// Our event dispatiching helper object /// </summary> private ProjectEventDispatcher events; /// <summary> /// Loads and executes tests. Non-null when /// we have loaded a test. /// </summary> private TestDomain testDomain = null; /// <summary> /// Our current test project, if we have one. /// </summary> private NUnitProject testProject = null; /// <summary> /// The currently loaded test, returned by the testrunner /// </summary> private Test loadedTest = null; /// <summary> /// The test name that was specified when loading /// </summary> private string loadedTestName = null; /// <summary> /// The tests that are running /// </summary> private ITest[] runningTests = null; /// <summary> /// Result of the last test run /// </summary> private TestResult[] results = null; /// <summary> /// The last exception received when trying to load, unload or run a test /// </summary> private Exception lastException = null; /// <summary> /// Watcher fires when the assembly changes /// </summary> private AssemblyWatcher watcher; /// <summary> /// Assembly changed during a test and /// needs to be reloaded later /// </summary> private bool reloadPending = false; /// <summary> /// Indicates whether to watch for changes /// and reload the tests when a change occurs. /// </summary> private bool reloadOnChange = false; /// <summary> /// Indicates whether to reload the tests /// before each run. /// </summary> private bool reloadOnRun = false; private IFilter filter; #endregion #region Constructor public TestLoader(TextWriter stdOutWriter, TextWriter stdErrWriter ) { this.stdOutWriter = stdOutWriter; this.stdErrWriter = stdErrWriter; this.events = new ProjectEventDispatcher(); } #endregion #region Properties public bool IsProjectLoaded { get { return testProject != null; } } public bool IsTestLoaded { get { return loadedTest != null; } } public bool IsTestRunning { get { return runningTests != null; } } public NUnitProject TestProject { get { return testProject; } set { OnProjectLoad( value ); } } public IProjectEvents Events { get { return events; } } public string TestFileName { get { return testProject.ProjectPath; } } public TestResult[] Results { get { return results; } } public Exception LastException { get { return lastException; } } public bool ReloadOnChange { get { return reloadOnChange; } set { reloadOnChange = value; } } public bool ReloadOnRun { get { return reloadOnRun; } set { reloadOnRun = value; } } public Version FrameworkVersion { get { return this.testDomain.FrameworkVersion; } } #endregion #region EventListener Handlers void EventListener.RunStarted(Test[] tests) { int count = 0; foreach( Test test in tests ) count += filter == null ? test.CountTestCases() : test.CountTestCases( filter ); events.FireRunStarting( tests, count ); } void EventListener.RunFinished(NUnit.Core.TestResult[] results) { this.results = results; events.FireRunFinished( results ); runningTests = null; } void EventListener.RunFinished(Exception exception) { this.lastException = exception; events.FireRunFinished( exception ); runningTests = null; } /// <summary> /// Trigger event when each test starts /// </summary> /// <param name="testCase">TestCase that is starting</param> void EventListener.TestStarted(NUnit.Core.TestCase testCase) { events.FireTestStarting( testCase ); } /// <summary> /// Trigger event when each test finishes /// </summary> /// <param name="result">Result of the case that finished</param> void EventListener.TestFinished(TestCaseResult result) { events.FireTestFinished( result ); } /// <summary> /// Trigger event when each suite starts /// </summary> /// <param name="suite">Suite that is starting</param> void EventListener.SuiteStarted(TestSuite suite) { events.FireSuiteStarting( suite ); } /// <summary> /// Trigger event when each suite finishes /// </summary> /// <param name="result">Result of the suite that finished</param> void EventListener.SuiteFinished(TestSuiteResult result) { events.FireSuiteFinished( result ); } /// <summary> /// Trigger event when an unhandled exception occurs during a test /// </summary> /// <param name="exception">The unhandled exception</param> void EventListener.UnhandledException(Exception exception) { events.FireTestException( exception ); } #endregion #region Methods for Loading and Unloading Projects /// <summary> /// Create a new project with default naming /// </summary> public void NewProject() { try { events.FireProjectLoading( "New Project" ); OnProjectLoad( NUnitProject.NewProject() ); } catch( Exception exception ) { lastException = exception; events.FireProjectLoadFailed( "New Project", exception ); } } /// <summary> /// Create a new project using a given path /// </summary> public void NewProject( string filePath ) { try { events.FireProjectLoading( filePath ); NUnitProject project = new NUnitProject( filePath ); project.Configs.Add( "Debug" ); project.Configs.Add( "Release" ); project.IsDirty = false; OnProjectLoad( project ); } catch( Exception exception ) { lastException = exception; events.FireProjectLoadFailed( filePath, exception ); } } /// <summary> /// Load a new project, optionally selecting the config and fire events /// </summary> public void LoadProject( string filePath, string configName ) { try { events.FireProjectLoading( filePath ); NUnitProject newProject = NUnitProject.LoadProject( filePath ); if ( configName != null ) { newProject.SetActiveConfig( configName ); newProject.IsDirty = false; } OnProjectLoad( newProject ); // return true; } catch( Exception exception ) { lastException = exception; events.FireProjectLoadFailed( filePath, exception ); // return false; } } /// <summary> /// Load a new project using the default config and fire events /// </summary> public void LoadProject( string filePath ) { LoadProject( filePath, null ); } /// <summary> /// Load a project from a list of assemblies and fire events /// </summary> public void LoadProject( string[] assemblies ) { try { events.FireProjectLoading( "New Project" ); NUnitProject newProject = NUnitProject.FromAssemblies( assemblies ); OnProjectLoad( newProject ); // return true; } catch( Exception exception ) { lastException = exception; events.FireProjectLoadFailed( "New Project", exception ); // return false; } } /// <summary> /// Unload the current project and fire events /// </summary> public void UnloadProject() { string testFileName = TestFileName; try { events.FireProjectUnloading( testFileName ); // if ( testFileName != null && File.Exists( testFileName ) ) // UserSettings.RecentProjects.RecentFile = testFileName; if ( IsTestLoaded ) UnloadTest(); testProject.Changed -= new ProjectEventHandler( OnProjectChanged ); testProject = null; events.FireProjectUnloaded( testFileName ); } catch (Exception exception ) { lastException = exception; events.FireProjectUnloadFailed( testFileName, exception ); } } /// <summary> /// Common operations done each time a project is loaded /// </summary> /// <param name="testProject">The newly loaded project</param> private void OnProjectLoad( NUnitProject testProject ) { if ( IsProjectLoaded ) UnloadProject(); this.testProject = testProject; testProject.Changed += new ProjectEventHandler( OnProjectChanged ); events.FireProjectLoaded( TestFileName ); } private void OnProjectChanged( object sender, ProjectEventArgs e ) { switch ( e.type ) { case ProjectChangeType.ActiveConfig: if( TestProject.IsLoadable ) LoadTest(); break; case ProjectChangeType.AddConfig: case ProjectChangeType.UpdateConfig: if ( e.configName == TestProject.ActiveConfigName && TestProject.IsLoadable ) LoadTest(); break; case ProjectChangeType.RemoveConfig: if ( IsTestLoaded && TestProject.Configs.Count == 0 ) UnloadTest(); break; default: break; } } #endregion #region Methods for Loading and Unloading Tests public void LoadTest() { LoadTest( null ); } public void LoadTest( string testName ) { try { events.FireTestLoading( TestFileName ); testDomain = new TestDomain( stdOutWriter, stdErrWriter ); Test test = testDomain.Load( TestProject, testName ); TestSuite suite = test as TestSuite; if ( suite != null ) suite.Sort(); loadedTest = test; loadedTestName = testName; results = null; reloadPending = false; if ( ReloadOnChange ) InstallWatcher( ); if ( suite != null ) events.FireTestLoaded( TestFileName, this.loadedTest ); else { lastException = new ApplicationException( string.Format ( "Unable to find test {0} in assembly", testName ) ); events.FireTestLoadFailed( TestFileName, lastException ); } } catch( FileNotFoundException exception ) { lastException = exception; foreach( string assembly in TestProject.ActiveConfig.AbsolutePaths ) { if ( Path.GetFileNameWithoutExtension( assembly ) == exception.FileName && !ProjectPath.SamePathOrUnder( testProject.ActiveConfig.BasePath, assembly ) ) { lastException = new ApplicationException( string.Format( "Unable to load {0} because it is not located under the AppBase", exception.FileName ), exception ); break; } } events.FireTestLoadFailed( TestFileName, lastException ); } catch( Exception exception ) { lastException = exception; events.FireTestLoadFailed( TestFileName, exception ); } } /// <summary> /// Unload the current test suite and fire the Unloaded event /// </summary> public void UnloadTest( ) { if( IsTestLoaded ) { // Hold the name for notifications after unload string fileName = TestFileName; try { events.FireTestUnloading( TestFileName, this.loadedTest ); RemoveWatcher(); testDomain.Unload(); testDomain = null; loadedTest = null; loadedTestName = null; results = null; reloadPending = false; events.FireTestUnloaded( fileName, this.loadedTest ); } catch( Exception exception ) { lastException = exception; events.FireTestUnloadFailed( fileName, exception ); } } } /// <summary> /// Reload the current test on command /// </summary> public void ReloadTest() { OnTestChanged( TestFileName ); } /// <summary> /// Handle watcher event that signals when the loaded assembly /// file has changed. Make sure it's a real change before /// firing the SuiteChangedEvent. Since this all happens /// asynchronously, we use an event to let ui components /// know that the failure happened. /// </summary> /// <param name="assemblyFileName">Assembly file that changed</param> public void OnTestChanged( string testFileName ) { if ( IsTestRunning ) reloadPending = true; else try { events.FireTestReloading( testFileName, this.loadedTest ); // Don't unload the old domain till after the event // handlers get a chance to compare the trees. TestDomain newDomain = new TestDomain( stdOutWriter, stdErrWriter ); Test newTest = newDomain.Load( testProject, loadedTestName ); TestSuite suite = newTest as TestSuite; if ( suite != null ) suite.Sort(); testDomain.Unload(); testDomain = newDomain; loadedTest = newTest; reloadPending = false; events.FireTestReloaded( testFileName, newTest ); } catch( Exception exception ) { lastException = exception; events.FireTestReloadFailed( testFileName, exception ); } } #endregion #region Methods for Running Tests public void SetFilter( IFilter filter ) { this.filter = filter; } /// <summary> /// Run the currently loaded top level test suite /// </summary> public void RunLoadedTest() { RunTest( loadedTest ); } /// <summary> /// Run a testcase or testsuite from the currrent tree /// firing the RunStarting and RunFinished events. /// Silently ignore the call if a test is running /// to allow for latency in the UI. /// </summary> /// <param name="testName">The test to be run</param> public void RunTest( ITest test ) { RunTests( new ITest[] { test } ); } public void RunTests( ITest[] tests ) { if ( !IsTestRunning ) { if ( reloadPending || ReloadOnRun ) ReloadTest(); runningTests = tests; //kind of silly string[] testNames = new string[ runningTests.Length ]; int index = 0; foreach (ITest node in runningTests) testNames[index++] = node.UniqueName; testDomain.SetFilter( filter ); // testDomain.DisplayTestLabels = UserSettings.Options.TestLabels; testDomain.RunTest( this, testNames ); } } /// <summary> /// Cancel the currently running test. /// Fail silently if there is none to /// allow for latency in the UI. /// </summary> public void CancelTestRun() { if ( IsTestRunning ) testDomain.CancelRun(); } public IList GetCategories() { ArrayList list = new ArrayList(); list.AddRange(testDomain.GetCategories()); return list; } #endregion #region Helper Methods /// <summary> /// Install our watcher object so as to get notifications /// about changes to a test. /// </summary> /// <param name="assemblyFileName">Full path of the assembly to watch</param> private void InstallWatcher() { if(watcher!=null) watcher.Stop(); watcher = new AssemblyWatcher( 1000, TestProject.ActiveConfig.AbsolutePaths ); watcher.AssemblyChangedEvent += new AssemblyWatcher.AssemblyChangedHandler( OnTestChanged ); watcher.Start(); } /// <summary> /// Stop and remove our current watcher object. /// </summary> private void RemoveWatcher() { if ( watcher != null ) { watcher.Stop(); watcher = null; } } #endregion } }
using System; using NUnit.Framework; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Utilities.Encoders; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Crypto.Tests { /** * Salsa20 Test */ [TestFixture] public class Salsa20Test : SimpleTest { private static readonly byte[] zeroes = Hex.Decode( "00000000000000000000000000000000" + "00000000000000000000000000000000" + "00000000000000000000000000000000" + "00000000000000000000000000000000"); private static readonly string set1v0_0 = "4DFA5E481DA23EA09A31022050859936" + "DA52FCEE218005164F267CB65F5CFD7F" + "2B4F97E0FF16924A52DF269515110A07" + "F9E460BC65EF95DA58F740B7D1DBB0AA"; private static readonly string set1v0_192 = "DA9C1581F429E0A00F7D67E23B730676" + "783B262E8EB43A25F55FB90B3E753AEF" + "8C6713EC66C51881111593CCB3E8CB8F" + "8DE124080501EEEB389C4BCB6977CF95"; private static readonly string set1v0_256 = "7D5789631EB4554400E1E025935DFA7B" + "3E9039D61BDC58A8697D36815BF1985C" + "EFDF7AE112E5BB81E37ECF0616CE7147" + "FC08A93A367E08631F23C03B00A8DA2F"; private static readonly string set1v0_448 = "B375703739DACED4DD4059FD71C3C47F" + "C2F9939670FAD4A46066ADCC6A564578" + "3308B90FFB72BE04A6B147CBE38CC0C3" + "B9267C296A92A7C69873F9F263BE9703"; private static readonly string set1v9_0 = "0471076057830FB99202291177FBFE5D" + "38C888944DF8917CAB82788B91B53D1C" + "FB06D07A304B18BB763F888A61BB6B75" + "5CD58BEC9C4CFB7569CB91862E79C459"; private static readonly string set1v9_192 = "D1D7E97556426E6CFC21312AE3811425" + "9E5A6FB10DACBD88E4354B0472556935" + "2B6DA5ACAFACD5E266F9575C2ED8E6F2" + "EFE4B4D36114C3A623DD49F4794F865B"; private static readonly string set1v9_256 = "AF06FAA82C73291231E1BD916A773DE1" + "52FD2126C40A10C3A6EB40F22834B8CC" + "68BD5C6DBD7FC1EC8F34165C517C0B63" + "9DB0C60506D3606906B8463AA0D0EC2F"; private static readonly string set1v9_448 = "AB3216F1216379EFD5EC589510B8FD35" + "014D0AA0B613040BAE63ECAB90A9AF79" + "661F8DA2F853A5204B0F8E72E9D9EB4D" + "BA5A4690E73A4D25F61EE7295215140C"; private static readonly string set6v0_0 = "F5FAD53F79F9DF58C4AEA0D0ED9A9601" + "F278112CA7180D565B420A48019670EA" + "F24CE493A86263F677B46ACE1924773D" + "2BB25571E1AA8593758FC382B1280B71"; private static readonly string set6v0_65472 = "B70C50139C63332EF6E77AC54338A407" + "9B82BEC9F9A403DFEA821B83F7860791" + "650EF1B2489D0590B1DE772EEDA4E3BC" + "D60FA7CE9CD623D9D2FD5758B8653E70"; private static readonly string set6v0_65536 = "81582C65D7562B80AEC2F1A673A9D01C" + "9F892A23D4919F6AB47B9154E08E699B" + "4117D7C666477B60F8391481682F5D95" + "D96623DBC489D88DAA6956B9F0646B6E"; private static readonly string set6v1_0 = "3944F6DC9F85B128083879FDF190F7DE" + "E4053A07BC09896D51D0690BD4DA4AC1" + "062F1E47D3D0716F80A9B4D85E6D6085" + "EE06947601C85F1A27A2F76E45A6AA87"; private static readonly string set6v1_65472 = "36E03B4B54B0B2E04D069E690082C8C5" + "92DF56E633F5D8C7682A02A65ECD1371" + "8CA4352AACCB0DA20ED6BBBA62E177F2" + "10E3560E63BB822C4158CAA806A88C82"; private static readonly string set6v1_65536 = "1B779E7A917C8C26039FFB23CF0EF8E0" + "8A1A13B43ACDD9402CF5DF38501098DF" + "C945A6CC69A6A17367BC03431A86B3ED" + "04B0245B56379BF997E25800AD837D7D"; public override string Name { get { return "Salsa20"; } } public override void PerformTest() { salsa20Test1(new ParametersWithIV(new KeyParameter(Hex.Decode("80000000000000000000000000000000")), Hex.Decode("0000000000000000")), set1v0_0, set1v0_192, set1v0_256, set1v0_448); salsa20Test1(new ParametersWithIV(new KeyParameter(Hex.Decode("00400000000000000000000000000000")), Hex.Decode("0000000000000000")), set1v9_0, set1v9_192, set1v9_256, set1v9_448); salsa20Test2(new ParametersWithIV(new KeyParameter(Hex.Decode("0053A6F94C9FF24598EB3E91E4378ADD3083D6297CCF2275C81B6EC11467BA0D")), Hex.Decode("0D74DB42A91077DE")), set6v0_0, set6v0_65472, set6v0_65536); salsa20Test2(new ParametersWithIV(new KeyParameter(Hex.Decode("0558ABFE51A4F74A9DF04396E93C8FE23588DB2E81D4277ACD2073C6196CBF12")), Hex.Decode("167DE44BB21980E7")), set6v1_0, set6v1_65472, set6v1_65536); reinitBug(); } private void salsa20Test1( ICipherParameters parameters, string v0, string v192, string v256, string v448) { IStreamCipher salsa = new Salsa20Engine(); byte[] buf = new byte[64]; salsa.Init(true, parameters); for (int i = 0; i != 7; i++) { salsa.ProcessBytes(zeroes, 0, 64, buf, 0); switch (i) { case 0: if (!AreEqual(buf, Hex.Decode(v0))) { mismatch("v0", v0, buf); } break; case 3: if (!AreEqual(buf, Hex.Decode(v192))) { mismatch("v192", v192, buf); } break; case 4: if (!AreEqual(buf, Hex.Decode(v256))) { mismatch("v256", v256, buf); } break; default: // ignore break; } } for (int i = 0; i != 64; i++) { buf[i] = salsa.ReturnByte(zeroes[i]); } if (!AreEqual(buf, Hex.Decode(v448))) { mismatch("v448", v448, buf); } } private void salsa20Test2( ICipherParameters parameters, string v0, string v65472, string v65536) { IStreamCipher salsa = new Salsa20Engine(); byte[] buf = new byte[64]; salsa.Init(true, parameters); for (int i = 0; i != 1025; i++) { salsa.ProcessBytes(zeroes, 0, 64, buf, 0); switch (i) { case 0: if (!AreEqual(buf, Hex.Decode(v0))) { mismatch("v0", v0, buf); } break; case 1023: if (!AreEqual(buf, Hex.Decode(v65472))) { mismatch("v65472", v65472, buf); } break; case 1024: if (!AreEqual(buf, Hex.Decode(v65536))) { mismatch("v65536", v65536, buf); } break; default: // ignore break; } } } private void mismatch( string name, string expected, byte[] found) { Fail("mismatch on " + name, expected, Hex.ToHexString(found)); } private void reinitBug() { KeyParameter key = new KeyParameter(Hex.Decode("80000000000000000000000000000000")); ParametersWithIV parameters = new ParametersWithIV(key, Hex.Decode("0000000000000000")); IStreamCipher salsa = new Salsa20Engine(); salsa.Init(true, parameters); try { salsa.Init(true, key); Fail("Salsa20 should throw exception if no IV in Init"); } catch (ArgumentException) { } } public static void Main( string[] args) { RunTest(new Salsa20Test()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { using Microsoft.CodeAnalysis.ErrorLogger; using DiagnosticId = String; using LanguageKind = String; [Export(typeof(ICodeFixService))] internal partial class CodeFixService : ICodeFixService { private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> _workspaceFixersMap; private readonly ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>> _projectFixersMap; // Shared by project fixers and workspace fixers. private ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>> _fixerToFixableIdsMap = ImmutableDictionary<CodeFixProvider, ImmutableArray<DiagnosticId>>.Empty; private readonly ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> _fixerPriorityMap; private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider> _analyzerReferenceToFixersMap; private readonly ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback _createProjectCodeFixProvider; private readonly ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> _suppressionProvidersMap; private readonly IEnumerable<Lazy<IErrorLoggerService>> _errorLoggers; private ImmutableDictionary<CodeFixProvider, FixAllProviderInfo> _fixAllProviderMap; [ImportingConstructor] public CodeFixService( IDiagnosticAnalyzerService service, [ImportMany]IEnumerable<Lazy<IErrorLoggerService>> loggers, [ImportMany]IEnumerable<Lazy<CodeFixProvider, CodeChangeProviderMetadata>> fixers, [ImportMany]IEnumerable<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>> suppressionProviders) { _errorLoggers = loggers; _diagnosticService = service; var fixersPerLanguageMap = fixers.ToPerLanguageMapWithMultipleLanguages(); var suppressionProvidersPerLanguageMap = suppressionProviders.ToPerLanguageMapWithMultipleLanguages(); _workspaceFixersMap = GetFixerPerLanguageMap(fixersPerLanguageMap, null); _suppressionProvidersMap = GetSuppressionProvidersPerLanguageMap(suppressionProvidersPerLanguageMap); // REVIEW: currently, fixer's priority is statically defined by the fixer itself. might considering making it more dynamic or configurable. _fixerPriorityMap = GetFixerPriorityPerLanguageMap(fixersPerLanguageMap); // Per-project fixers _projectFixersMap = new ConditionalWeakTable<IReadOnlyList<AnalyzerReference>, ImmutableDictionary<string, List<CodeFixProvider>>>(); _analyzerReferenceToFixersMap = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>(); _createProjectCodeFixProvider = new ConditionalWeakTable<AnalyzerReference, ProjectCodeFixProvider>.CreateValueCallback(r => new ProjectCodeFixProvider(r)); _fixAllProviderMap = ImmutableDictionary<CodeFixProvider, FixAllProviderInfo>.Empty; } public async Task<FirstDiagnosticResult> GetFirstDiagnosticWithFixAsync(Document document, TextSpan range, bool considerSuppressionFixes, CancellationToken cancellationToken) { if (document == null || !document.IsOpen()) { return default(FirstDiagnosticResult); } using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject()) { var fullResult = await _diagnosticService.TryAppendDiagnosticsForSpanAsync(document, range, diagnostics.Object, cancellationToken).ConfigureAwait(false); foreach (var diagnostic in diagnostics.Object) { cancellationToken.ThrowIfCancellationRequested(); if (!range.IntersectsWith(diagnostic.TextSpan)) { continue; } // REVIEW: 2 possible designs. // 1. find the first fix and then return right away. if the lightbulb is actually expanded, find all fixes for the line synchronously. or // 2. kick off a task that finds all fixes for the given range here but return once we find the first one. // at the same time, let the task to run to finish. if the lightbulb is expanded, we just simply use the task to get all fixes. // // first approach is simpler, so I will implement that first. if the first approach turns out to be not good enough, then // I will try the second approach which will be more complex but quicker var hasFix = await ContainsAnyFix(document, diagnostic, considerSuppressionFixes, cancellationToken).ConfigureAwait(false); if (hasFix) { return new FirstDiagnosticResult(!fullResult, hasFix, diagnostic); } } return new FirstDiagnosticResult(!fullResult, false, default(DiagnosticData)); } } public async Task<IEnumerable<CodeFixCollection>> GetFixesAsync(Document document, TextSpan range, bool includeSuppressionFixes, CancellationToken cancellationToken) { // REVIEW: this is the first and simplest design. basically, when ctrl+. is pressed, it asks diagnostic service to give back // current diagnostics for the given span, and it will use that to get fixes. internally diagnostic service will either return cached information // (if it is up-to-date) or synchronously do the work at the spot. // // this design's weakness is that each side don't have enough information to narrow down works to do. it will most likely always do more works than needed. // sometimes way more than it is needed. (compilation) Dictionary<TextSpan, List<DiagnosticData>> aggregatedDiagnostics = null; foreach (var diagnostic in await _diagnosticService.GetDiagnosticsForSpanAsync(document, range, cancellationToken).ConfigureAwait(false)) { cancellationToken.ThrowIfCancellationRequested(); aggregatedDiagnostics = aggregatedDiagnostics ?? new Dictionary<TextSpan, List<DiagnosticData>>(); aggregatedDiagnostics.GetOrAdd(diagnostic.TextSpan, _ => new List<DiagnosticData>()).Add(diagnostic); } var result = new List<CodeFixCollection>(); if (aggregatedDiagnostics == null) { return result; } foreach (var spanAndDiagnostic in aggregatedDiagnostics) { result = await AppendFixesAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } if (result.Any()) { // sort the result to the order defined by the fixers var priorityMap = _fixerPriorityMap[document.Project.Language].Value; result.Sort((d1, d2) => priorityMap.ContainsKey((CodeFixProvider)d1.Provider) ? (priorityMap.ContainsKey((CodeFixProvider)d2.Provider) ? priorityMap[(CodeFixProvider)d1.Provider] - priorityMap[(CodeFixProvider)d2.Provider] : -1) : 1); } if (includeSuppressionFixes) { foreach (var spanAndDiagnostic in aggregatedDiagnostics) { result = await AppendSuppressionsAsync(document, spanAndDiagnostic.Key, spanAndDiagnostic.Value, result, cancellationToken).ConfigureAwait(false); } } return result; } private async Task<List<CodeFixCollection>> AppendFixesAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnosticDataCollection, List<CodeFixCollection> result, CancellationToken cancellationToken) { Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap); var projectFixersMap = GetProjectFixers(document.Project); var hasAnyProjectFixer = projectFixersMap.Any(); if (!hasAnySharedFixer && !hasAnyProjectFixer) { return result; } ImmutableArray<CodeFixProvider> workspaceFixers; List<CodeFixProvider> projectFixers; var allFixers = new List<CodeFixProvider>(); foreach (var diagnosticId in diagnosticDataCollection.Select(d => d.Id).Distinct()) { cancellationToken.ThrowIfCancellationRequested(); if (hasAnySharedFixer && fixerMap.Value.TryGetValue(diagnosticId, out workspaceFixers)) { allFixers.AddRange(workspaceFixers); } if (hasAnyProjectFixer && projectFixersMap.TryGetValue(diagnosticId, out projectFixers)) { allFixers.AddRange(projectFixers); } } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var diagnostics = diagnosticDataCollection.Select(data => data.ToDiagnostic(tree)).ToImmutableArray(); var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); foreach (var fixer in allFixers.Distinct()) { cancellationToken.ThrowIfCancellationRequested(); Func<Diagnostic, bool> hasFix = (d) => this.GetFixableDiagnosticIds(fixer, extensionManager).Contains(d.Id); Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = async (dxs) => { var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, span, dxs, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (a, d) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(a, d)); } }, verifyArguments: false, cancellationToken: cancellationToken); var task = fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask; await task.ConfigureAwait(false); return fixes; }; await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, fixer, hasFix, getFixes, cancellationToken).ConfigureAwait(false); } return result; } private async Task<List<CodeFixCollection>> AppendSuppressionsAsync( Document document, TextSpan span, IEnumerable<DiagnosticData> diagnosticDataCollection, List<CodeFixCollection> result, CancellationToken cancellationToken) { Lazy<ISuppressionFixProvider> lazySuppressionProvider; if (!_suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) || lazySuppressionProvider.Value == null) { return result; } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var diagnostics = diagnosticDataCollection.Select(data => data.ToDiagnostic(tree)); Func<Diagnostic, bool> hasFix = (d) => lazySuppressionProvider.Value.CanBeSuppressed(d); Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes = (dxs) => lazySuppressionProvider.Value.GetSuppressionsAsync(document, span, dxs, cancellationToken); await AppendFixesOrSuppressionsAsync(document, span, diagnostics, result, lazySuppressionProvider.Value, hasFix, getFixes, cancellationToken).ConfigureAwait(false); return result; } private async Task<List<CodeFixCollection>> AppendFixesOrSuppressionsAsync( Document document, TextSpan span, IEnumerable<Diagnostic> diagnosticsWithSameSpan, List<CodeFixCollection> result, object fixer, Func<Diagnostic, bool> hasFix, Func<ImmutableArray<Diagnostic>, Task<IEnumerable<CodeFix>>> getFixes, CancellationToken cancellationToken) { var diagnostics = diagnosticsWithSameSpan.Where(d => hasFix(d)).OrderByDescending(d => d.Severity).ToImmutableArray(); if (diagnostics.Length <= 0) { // this can happen for suppression case where all diagnostics can't be suppressed return result; } var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); var fixes = await extensionManager.PerformFunctionAsync(fixer, () => getFixes(diagnostics), defaultValue: SpecializedCollections.EmptyEnumerable<CodeFix>()).ConfigureAwait(false); if (fixes != null && fixes.Any()) { FixAllCodeActionContext fixAllContext = null; var codeFixProvider = fixer as CodeFixProvider; if (codeFixProvider != null) { // If the codeFixProvider supports fix all occurrences, then get the corresponding FixAllProviderInfo and fix all context. var fixAllProviderInfo = extensionManager.PerformFunction(codeFixProvider, () => ImmutableInterlocked.GetOrAdd(ref _fixAllProviderMap, codeFixProvider, FixAllProviderInfo.Create), defaultValue: null); if (fixAllProviderInfo != null) { fixAllContext = FixAllCodeActionContext.Create(document, fixAllProviderInfo, codeFixProvider, diagnostics, this.GetDocumentDiagnosticsAsync, this.GetProjectDiagnosticsAsync, cancellationToken); } } result = result ?? new List<CodeFixCollection>(); var codeFix = new CodeFixCollection(fixer, span, fixes, fixAllContext); result.Add(codeFix); } return result; } private async Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(document); var solution = document.Project.Solution; var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(solution, null, document.Id, diagnosticIds, cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId != null)); return diagnostics.Select(d => d.ToDiagnostic(tree)); } private async Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, bool includeAllDocumentDiagnostics, ImmutableHashSet<string> diagnosticIds, CancellationToken cancellationToken) { Contract.ThrowIfNull(project); if (includeAllDocumentDiagnostics) { // Get all diagnostics for the entire project, including document diagnostics. var diagnostics = await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); var documentIdsToTreeMap = await GetDocumentIdsToTreeMapAsync(project, cancellationToken).ConfigureAwait(false); return diagnostics.Select(d => d.DocumentId != null ? d.ToDiagnostic(documentIdsToTreeMap[d.DocumentId]) : d.ToDiagnostic(null)); } else { // Get all no-location diagnostics for the project, doesn't include document diagnostics. var diagnostics = await _diagnosticService.GetProjectDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds, cancellationToken: cancellationToken).ConfigureAwait(false); Contract.ThrowIfFalse(diagnostics.All(d => d.DocumentId == null)); return diagnostics.Select(d => d.ToDiagnostic(null)); } } private static async Task<ImmutableDictionary<DocumentId, SyntaxTree>> GetDocumentIdsToTreeMapAsync(Project project, CancellationToken cancellationToken) { var builder = ImmutableDictionary.CreateBuilder<DocumentId, SyntaxTree>(); foreach (var document in project.Documents) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); builder.Add(document.Id, tree); } return builder.ToImmutable(); } private async Task<bool> ContainsAnyFix(Document document, DiagnosticData diagnostic, bool considerSuppressionFixes, CancellationToken cancellationToken) { ImmutableArray<CodeFixProvider> workspaceFixers = ImmutableArray<CodeFixProvider>.Empty; List<CodeFixProvider> projectFixers = null; Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>> fixerMap; bool hasAnySharedFixer = _workspaceFixersMap.TryGetValue(document.Project.Language, out fixerMap) && fixerMap.Value.TryGetValue(diagnostic.Id, out workspaceFixers); var hasAnyProjectFixer = GetProjectFixers(document.Project).TryGetValue(diagnostic.Id, out projectFixers); Lazy<ISuppressionFixProvider> lazySuppressionProvider = null; var hasSuppressionFixer = considerSuppressionFixes && _suppressionProvidersMap.TryGetValue(document.Project.Language, out lazySuppressionProvider) && lazySuppressionProvider.Value != null; if (!hasAnySharedFixer && !hasAnyProjectFixer && !hasSuppressionFixer) { return false; } var allFixers = ImmutableArray<CodeFixProvider>.Empty; if (hasAnySharedFixer) { allFixers = workspaceFixers; } if (hasAnyProjectFixer) { allFixers = allFixers.AddRange(projectFixers); } var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var dx = diagnostic.ToDiagnostic(tree); if (hasSuppressionFixer && lazySuppressionProvider.Value.CanBeSuppressed(dx)) { return true; } var fixes = new List<CodeFix>(); var context = new CodeFixContext(document, dx, // TODO: Can we share code between similar lambdas that we pass to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs? (a, d) => { // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from. lock (fixes) { fixes.Add(new CodeFix(a, d)); } }, verifyArguments: false, cancellationToken: cancellationToken); var extensionManager = document.Project.Solution.Workspace.Services.GetService<IExtensionManager>(); // we do have fixer. now let's see whether it actually can fix it foreach (var fixer in allFixers) { await extensionManager.PerformActionAsync(fixer, () => fixer.RegisterCodeFixesAsync(context) ?? SpecializedTasks.EmptyTask).ConfigureAwait(false); if (!fixes.Any()) { continue; } return true; } return false; } private static readonly Func<DiagnosticId, List<CodeFixProvider>> s_createList = _ => new List<CodeFixProvider>(); private ImmutableArray<DiagnosticId> GetFixableDiagnosticIds(CodeFixProvider fixer, IExtensionManager extensionManager) { // If we are passed a null extension manager it means we do not have access to a document so there is nothing to // show the user. In this case we will log any exceptions that occur, but the user will not see them. if (extensionManager != null) { return extensionManager.PerformFunction( fixer, () => ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => f.FixableDiagnosticIds), defaultValue: ImmutableArray<DiagnosticId>.Empty); } try { return ImmutableInterlocked.GetOrAdd(ref _fixerToFixableIdsMap, fixer, f => f.FixableDiagnosticIds); } catch (OperationCanceledException) { throw; } catch (Exception e) { foreach (var logger in _errorLoggers) { logger.Value.LogException(fixer, e); } return ImmutableArray<DiagnosticId>.Empty; } } private ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>> GetFixerPerLanguageMap( Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage, IExtensionManager extensionManager) { var fixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>>(); foreach (var languageKindAndFixers in fixersPerLanguage) { var lazyMap = new Lazy<ImmutableDictionary<DiagnosticId, ImmutableArray<CodeFixProvider>>>(() => { var mutableMap = new Dictionary<DiagnosticId, List<CodeFixProvider>>(); foreach (var fixer in languageKindAndFixers.Value) { foreach (var id in this.GetFixableDiagnosticIds(fixer.Value, extensionManager)) { if (string.IsNullOrWhiteSpace(id)) { continue; } var list = mutableMap.GetOrAdd(id, s_createList); list.Add(fixer.Value); } } var immutableMap = ImmutableDictionary.CreateBuilder<DiagnosticId, ImmutableArray<CodeFixProvider>>(); foreach (var diagnosticIdAndFixers in mutableMap) { immutableMap.Add(diagnosticIdAndFixers.Key, diagnosticIdAndFixers.Value.AsImmutableOrEmpty()); } return immutableMap.ToImmutable(); }, isThreadSafe: true); fixerMap = fixerMap.Add(languageKindAndFixers.Key, lazyMap); } return fixerMap; } private static ImmutableDictionary<LanguageKind, Lazy<ISuppressionFixProvider>> GetSuppressionProvidersPerLanguageMap( Dictionary<LanguageKind, List<Lazy<ISuppressionFixProvider, CodeChangeProviderMetadata>>> suppressionProvidersPerLanguage) { var suppressionFixerMap = ImmutableDictionary.Create<LanguageKind, Lazy<ISuppressionFixProvider>>(); foreach (var languageKindAndFixers in suppressionProvidersPerLanguage) { var suppressionFixerLazyMap = new Lazy<ISuppressionFixProvider>(() => languageKindAndFixers.Value.SingleOrDefault().Value); suppressionFixerMap = suppressionFixerMap.Add(languageKindAndFixers.Key, suppressionFixerLazyMap); } return suppressionFixerMap; } private static ImmutableDictionary<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>> GetFixerPriorityPerLanguageMap( Dictionary<LanguageKind, List<Lazy<CodeFixProvider, CodeChangeProviderMetadata>>> fixersPerLanguage) { var languageMap = ImmutableDictionary.CreateBuilder<LanguageKind, Lazy<ImmutableDictionary<CodeFixProvider, int>>>(); foreach (var languageAndFixers in fixersPerLanguage) { var lazyMap = new Lazy<ImmutableDictionary<CodeFixProvider, int>>(() => { var priorityMap = ImmutableDictionary.CreateBuilder<CodeFixProvider, int>(); var fixers = ExtensionOrderer.Order(languageAndFixers.Value); for (var i = 0; i < fixers.Count; i++) { priorityMap.Add(fixers[i].Value, i); } return priorityMap.ToImmutable(); }, isThreadSafe: true); languageMap.Add(languageAndFixers.Key, lazyMap); } return languageMap.ToImmutable(); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> GetProjectFixers(Project project) { return _projectFixersMap.GetValue(project.AnalyzerReferences, pId => ComputeProjectFixers(project)); } private ImmutableDictionary<DiagnosticId, List<CodeFixProvider>> ComputeProjectFixers(Project project) { var extensionManager = project.Solution.Workspace.Services.GetService<IExtensionManager>(); ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Builder builder = null; foreach (var reference in project.AnalyzerReferences) { var projectCodeFixerProvider = _analyzerReferenceToFixersMap.GetValue(reference, _createProjectCodeFixProvider); foreach (var fixer in projectCodeFixerProvider.GetFixers(project.Language)) { var fixableIds = this.GetFixableDiagnosticIds(fixer, extensionManager); foreach (var id in fixableIds) { if (string.IsNullOrWhiteSpace(id)) { continue; } builder = builder ?? ImmutableDictionary.CreateBuilder<DiagnosticId, List<CodeFixProvider>>(); var list = builder.GetOrAdd(id, s_createList); list.Add(fixer); } } } if (builder == null) { return ImmutableDictionary<DiagnosticId, List<CodeFixProvider>>.Empty; } return builder.ToImmutable(); } } }
// *********************************************************************** // Copyright (c) 2015 Charlie Poole // // 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.Globalization; using System.IO; using System.Reflection; using NUnit.Common; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnitLite { public class TextUI { public ExtendedTextWriter Writer { get; private set; } private TextReader _reader; private NUnitLiteOptions _options; #region Constructors public TextUI(ExtendedTextWriter writer, TextReader reader, NUnitLiteOptions options) { Writer = writer; _reader = reader; _options = options; } public TextUI(ExtendedTextWriter writer, TextReader reader) : this(writer, reader, new NUnitLiteOptions()) { } public TextUI(ExtendedTextWriter writer) #if SILVERLIGHT || PORTABLE : this(writer, null, new NUnitLiteOptions()) { } #else : this(writer, Console.In, new NUnitLiteOptions()) { } #endif #endregion #region Public Methods #region DisplayHeader /// <summary> /// Writes the header. /// </summary> public void DisplayHeader() { Assembly executingAssembly = GetType().GetTypeInfo().Assembly; AssemblyName assemblyName = AssemblyHelper.GetAssemblyName(executingAssembly); Version version = assemblyName.Version; string copyright = "Copyright (C) 2016, Charlie Poole"; string build = ""; var copyrightAttr = executingAssembly.GetCustomAttribute<AssemblyCopyrightAttribute>(); if (copyrightAttr != null) copyright = copyrightAttr.Copyright; var configAttr = executingAssembly.GetCustomAttribute<AssemblyConfigurationAttribute>(); if (configAttr != null) build = string.Format("({0})", configAttr.Configuration); WriteHeader(String.Format("NUnitLite {0} {1}", version.ToString(3), build)); WriteSubHeader(copyright); Writer.WriteLine(); } #endregion #region DisplayTestFiles public void DisplayTestFiles(IEnumerable<string> testFiles) { WriteSectionHeader("Test Files"); foreach (string testFile in testFiles) Writer.WriteLine(ColorStyle.Default, " " + testFile); Writer.WriteLine(); } #endregion #region DisplayHelp public void DisplayHelp() { WriteHeader("Usage: NUNITLITE [assembly] [options]"); Writer.WriteLine(); WriteHelpLine("Runs a set of NUnitLite tests from the console."); Writer.WriteLine(); WriteSectionHeader("Assembly:"); WriteHelpLine(" An alternate assembly from which to execute tests. Normally, the tests"); WriteHelpLine(" contained in the executable test assembly itself are run. An alternate"); WriteHelpLine(" assembly is specified using the assembly name, without any path or."); WriteHelpLine(" extension. It must be in the same in the same directory as the executable"); WriteHelpLine(" or on the probing path."); Writer.WriteLine(); WriteSectionHeader("Options:"); using (var sw = new StringWriter()) { _options.WriteOptionDescriptions(sw); Writer.Write(ColorStyle.Help, sw.ToString()); } WriteSectionHeader("Notes:"); WriteHelpLine(" * File names may be listed by themselves, with a relative path or "); WriteHelpLine(" using an absolute path. Any relative path is based on the current "); WriteHelpLine(" directory or on the Documents folder if running on a under the "); WriteHelpLine(" compact framework."); Writer.WriteLine(); WriteHelpLine(" * On Windows, options may be prefixed by a '/' character if desired"); Writer.WriteLine(); WriteHelpLine(" * Options that take values may use an equal sign or a colon"); WriteHelpLine(" to separate the option from its value."); Writer.WriteLine(); WriteHelpLine(" * Several options that specify processing of XML output take"); WriteHelpLine(" an output specification as a value. A SPEC may take one of"); WriteHelpLine(" the following forms:"); WriteHelpLine(" --OPTION:filename"); WriteHelpLine(" --OPTION:filename;format=formatname"); WriteHelpLine(" --OPTION:filename;transform=xsltfile"); Writer.WriteLine(); WriteHelpLine(" The --result option may use any of the following formats:"); WriteHelpLine(" nunit3 - the native XML format for NUnit 3.0"); WriteHelpLine(" nunit2 - legacy XML format used by earlier releases of NUnit"); Writer.WriteLine(); WriteHelpLine(" The --explore option may use any of the following formats:"); WriteHelpLine(" nunit3 - the native XML format for NUnit 3.0"); WriteHelpLine(" cases - a text file listing the full names of all test cases."); WriteHelpLine(" If --explore is used without any specification following, a list of"); WriteHelpLine(" test cases is output to the console."); Writer.WriteLine(); } #endregion #region DisplayRuntimeEnvironment /// <summary> /// Displays info about the runtime environment. /// </summary> public void DisplayRuntimeEnvironment() { #if !PORTABLE WriteSectionHeader("Runtime Environment"); Writer.WriteLabelLine(" OS Version: ", Environment.OSVersion); Writer.WriteLabelLine(" CLR Version: ", Environment.Version); Writer.WriteLine(); #endif } #endregion #region DisplayTestFilters public void DisplayTestFilters() { if (_options.TestList.Count > 0 || _options.WhereClauseSpecified) { WriteSectionHeader("Test Filters"); if (_options.TestList.Count > 0) foreach (string testName in _options.TestList) Writer.WriteLabelLine(" Test: ", testName); if (_options.WhereClauseSpecified) Writer.WriteLabelLine(" Where: ", _options.WhereClause.Trim()); Writer.WriteLine(); } } #endregion #region DisplayRunSettings public void DisplayRunSettings() { WriteSectionHeader("Run Settings"); if (_options.DefaultTimeout >= 0) Writer.WriteLabelLine(" Default timeout: ", _options.DefaultTimeout); #if PARALLEL Writer.WriteLabelLine( " Number of Test Workers: ", _options.NumberOfTestWorkers >= 0 ? _options.NumberOfTestWorkers #if NETCF : 2); #else : Math.Max(Environment.ProcessorCount, 2)); #endif #endif #if !PORTABLE Writer.WriteLabelLine(" Work Directory: ", _options.WorkDirectory ?? NUnit.Env.DefaultWorkDirectory); #endif Writer.WriteLabelLine(" Internal Trace: ", _options.InternalTraceLevel ?? "Off"); if (_options.TeamCity) Writer.WriteLine(ColorStyle.Value, " Display TeamCity Service Messages"); Writer.WriteLine(); } #endregion #region TestFinished private bool _testCreatedOutput = false; public void TestFinished(ITestResult result) { bool isSuite = result.Test.IsSuite; var labels = "ON"; #if !SILVERLIGHT if (_options.DisplayTestLabels != null) labels = _options.DisplayTestLabels.ToUpperInvariant(); #endif if (!isSuite && labels == "ALL" || !isSuite && labels == "ON" && result.Output.Length > 0) { WriteLabelLine(result.Test.FullName); } if (result.Output.Length > 0) { WriteOutputLine(result.Output); if (!result.Output.EndsWith("\n")) Writer.WriteLine(); } if (result.Test is TestAssembly && _testCreatedOutput) { Writer.WriteLine(); _testCreatedOutput = false; } } #endregion #region TestOutput public void TestOutput(TestOutput output) { var labels = "ON"; #if !SILVERLIGHT if (_options.DisplayTestLabels != null) labels = _options.DisplayTestLabels.ToUpperInvariant(); #endif if (labels == "ON" || labels == "All") if (output.TestName != null) WriteLabelLine(output.TestName); WriteOutputLine(output.Stream == "Error" ? ColorStyle.Error : ColorStyle.Output, output.Text); } #endregion #region WaitForUser public void WaitForUser(string message) { // Ignore if we don't have a TextReader if (_reader != null) { Writer.WriteLine(ColorStyle.Label, message); _reader.ReadLine(); } } #endregion #region Test Result Reports #region DisplaySummaryReport public void DisplaySummaryReport(ResultSummary summary) { var status = summary.ResultState.Status; var overallResult = status.ToString(); if (overallResult == "Skipped") overallResult = "Warning"; ColorStyle overallStyle = status == TestStatus.Passed ? ColorStyle.Pass : status == TestStatus.Failed ? ColorStyle.Failure : status == TestStatus.Skipped ? ColorStyle.Warning : ColorStyle.Output; if (_testCreatedOutput) Writer.WriteLine(); WriteSectionHeader("Test Run Summary"); Writer.WriteLabelLine(" Overall result: ", overallResult, overallStyle); WriteSummaryCount(" Test Count: ", summary.TestCount); WriteSummaryCount(", Passed: ", summary.PassCount); WriteSummaryCount(", Failed: ", summary.FailedCount, ColorStyle.Failure); WriteSummaryCount(", Inconclusive: ", summary.InconclusiveCount); WriteSummaryCount(", Skipped: ", summary.TotalSkipCount); Writer.WriteLine(); if (summary.FailedCount > 0) { WriteSummaryCount(" Failed Tests - Failures: ", summary.FailureCount, ColorStyle.Failure); WriteSummaryCount(", Errors: ", summary.ErrorCount, ColorStyle.Error); WriteSummaryCount(", Invalid: ", summary.InvalidCount, ColorStyle.Error); Writer.WriteLine(); } if (summary.TotalSkipCount > 0) { WriteSummaryCount(" Skipped Tests - Ignored: ", summary.IgnoreCount, ColorStyle.Warning); WriteSummaryCount(", Explicit: ", summary.ExplicitCount); WriteSummaryCount(", Other: ", summary.SkipCount); Writer.WriteLine(); } Writer.WriteLabelLine(" Start time: ", summary.StartTime.ToString("u")); Writer.WriteLabelLine(" End time: ", summary.EndTime.ToString("u")); Writer.WriteLabelLine(" Duration: ", string.Format(NumberFormatInfo.InvariantInfo, "{0:0.000} seconds", summary.Duration)); Writer.WriteLine(); } private void WriteSummaryCount(string label, int count) { Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture)); } private void WriteSummaryCount(string label, int count, ColorStyle color) { Writer.WriteLabel(label, count.ToString(CultureInfo.CurrentUICulture), count > 0 ? color : ColorStyle.Value); } #endregion #region DisplayErrorsAndFailuresReport public void DisplayErrorsAndFailuresReport(ITestResult result) { _reportIndex = 0; WriteSectionHeader("Errors and Failures"); DisplayErrorsAndFailures(result); Writer.WriteLine(); #if !SILVERLIGHT if (_options.StopOnError) { Writer.WriteLine(ColorStyle.Failure, "Execution terminated after first error"); Writer.WriteLine(); } #endif } #endregion #region DisplayNotRunReport public void DisplayNotRunReport(ITestResult result) { _reportIndex = 0; WriteSectionHeader("Tests Not Run"); DisplayNotRunResults(result); Writer.WriteLine(); } #endregion #region DisplayFullReport #if FULL // Not currently used, but may be reactivated /// <summary> /// Prints a full report of all results /// </summary> public void DisplayFullReport(ITestResult result) { WriteLine(ColorStyle.SectionHeader, "All Test Results -"); _writer.WriteLine(); DisplayAllResults(result, " "); _writer.WriteLine(); } #endif #endregion #endregion #region DisplayWarning public void DisplayWarning(string text) { Writer.WriteLine(ColorStyle.Warning, text); } #endregion #region DisplayError public void DisplayError(string text) { Writer.WriteLine(ColorStyle.Error, text); } #endregion #region DisplayErrors public void DisplayErrors(IList<string> messages) { foreach (string message in messages) DisplayError(message); } #endregion #endregion #region Helper Methods private void DisplayErrorsAndFailures(ITestResult result) { if (result.Test.IsSuite) { if (result.ResultState.Status == TestStatus.Failed) { var suite = result.Test as TestSuite; var site = result.ResultState.Site; if (suite.TestType == "Theory" || site == FailureSite.SetUp || site == FailureSite.TearDown) DisplayTestResult(result); if (site == FailureSite.SetUp) return; } foreach (ITestResult childResult in result.Children) DisplayErrorsAndFailures(childResult); } else if (result.ResultState.Status == TestStatus.Failed) DisplayTestResult(result); } private void DisplayNotRunResults(ITestResult result) { if (result.HasChildren) foreach (ITestResult childResult in result.Children) DisplayNotRunResults(childResult); else if (result.ResultState.Status == TestStatus.Skipped) DisplayTestResult(result); } private static readonly char[] TRIM_CHARS = new char[] { '\r', '\n' }; private int _reportIndex; private void DisplayTestResult(ITestResult result) { string status = result.ResultState.Label; if (string.IsNullOrEmpty(status)) status = result.ResultState.Status.ToString(); if (status == "Failed" || status == "Error") { var site = result.ResultState.Site.ToString(); if (site == "SetUp" || site == "TearDown") status = site + " " + status; } ColorStyle style = ColorStyle.Output; switch (result.ResultState.Status) { case TestStatus.Failed: style = ColorStyle.Failure; break; case TestStatus.Skipped: style = status == "Ignored" ? ColorStyle.Warning : ColorStyle.Output; break; case TestStatus.Passed: style = ColorStyle.Pass; break; } Writer.WriteLine(); Writer.WriteLine( style, string.Format("{0}) {1} : {2}", ++_reportIndex, status, result.FullName)); if (!string.IsNullOrEmpty(result.Message)) Writer.WriteLine(style, result.Message.TrimEnd(TRIM_CHARS)); if (!string.IsNullOrEmpty(result.StackTrace)) Writer.WriteLine(style, result.StackTrace.TrimEnd(TRIM_CHARS)); } #if FULL private void DisplayAllResults(ITestResult result, string indent) { string status = null; ColorStyle style = ColorStyle.Output; switch (result.ResultState.Status) { case TestStatus.Failed: status = "FAIL"; style = ColorStyle.Failure; break; case TestStatus.Skipped: if (result.ResultState.Label == "Ignored") { status = "IGN "; style = ColorStyle.Warning; } else { status = "SKIP"; style = ColorStyle.Output; } break; case TestStatus.Inconclusive: status = "INC "; style = ColorStyle.Output; break; case TestStatus.Passed: status = "OK "; style = ColorStyle.Pass; break; } WriteLine(style, status + indent + result.Name); if (result.HasChildren) foreach (ITestResult childResult in result.Children) PrintAllResults(childResult, indent + " "); } #endif private void WriteHeader(string text) { Writer.WriteLine(ColorStyle.Header, text); } private void WriteSubHeader(string text) { Writer.WriteLine(ColorStyle.SubHeader, text); } private void WriteSectionHeader(string text) { Writer.WriteLine(ColorStyle.SectionHeader, text); } private void WriteHelpLine(string text) { Writer.WriteLine(ColorStyle.Help, text); } private string _currentLabel; private void WriteLabelLine(string label) { if (label != _currentLabel) { Writer.WriteLine(ColorStyle.SectionHeader, "=> " + label); _testCreatedOutput = true; _currentLabel = label; } } private void WriteOutputLine(string text) { WriteOutputLine(ColorStyle.Output, text); } private void WriteOutputLine(ColorStyle color, string text) { Writer.Write(color, text); if (!text.EndsWith(Environment.NewLine)) Writer.WriteLine(); _testCreatedOutput = true; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Fonlow.TraceHub.Areas.HelpPage.ModelDescriptions; using Fonlow.TraceHub.Areas.HelpPage.Models; namespace Fonlow.TraceHub.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ // #define SHOW_DK2_VARIABLES // Use the Unity new GUI with Unity 4.6 or above. #if UNITY_4_6 || UNITY_5_0 #define USE_NEW_GUI #endif using System; using System.Collections; using UnityEngine; #if USE_NEW_GUI using UnityEngine.UI; # endif //------------------------------------------------------------------------------------- // ***** OVRMainMenu // /// <summary> /// OVRMainMenu is used to control the loading of different scenes. It also renders out /// a menu that allows a user to modify various Rift settings, and allow for storing /// these settings for recall later. /// /// A user of this component can add as many scenes that they would like to be able to /// have access to. /// /// OVRMainMenu is currently attached to the OVRPlayerController prefab for convenience, /// but can safely removed from it and added to another GameObject that is used for general /// Unity logic. /// /// </summary> public class OVRMainMenu : MonoBehaviour { /// <summary> /// The amount of time in seconds that it takes for the menu to fade in. /// </summary> public float FadeInTime = 2.0f; /// <summary> /// An optional texture that appears before the menu fades in. /// </summary> public UnityEngine.Texture FadeInTexture = null; /// <summary> /// An optional font that replaces Unity's default Arial. /// </summary> public Font FontReplace = null; /// <summary> /// The key that toggles the menu. /// </summary> public KeyCode MenuKey = KeyCode.Space; /// <summary> /// The key that quits the application. /// </summary> public KeyCode QuitKey = KeyCode.Escape; /// <summary> /// Scene names to show on-screen for each of the scenes in Scenes. /// </summary> public string [] SceneNames; /// <summary> /// The set of scenes that the user can jump to. /// </summary> public string [] Scenes; private bool ScenesVisible = false; // Spacing for scenes menu private int StartX = 490; private int StartY = 250; private int WidthX = 300; private int WidthY = 23; // Spacing for variables that users can change private int VRVarsSX = 553; private int VRVarsSY = 250; private int VRVarsWidthX = 175; private int VRVarsWidthY = 23; private int StepY = 25; // Handle to OVRCameraRig private OVRCameraRig CameraController = null; // Handle to OVRPlayerController private OVRPlayerController PlayerController = null; // Controller buttons private bool PrevStartDown; private bool PrevHatDown; private bool PrevHatUp; private bool ShowVRVars; private bool OldSpaceHit; // FPS private float UpdateInterval = 0.5f; private float Accum = 0; private int Frames = 0; private float TimeLeft = 0; private string strFPS = "FPS: 0"; private string strIPD = "IPD: 0.000"; /// <summary> /// Prediction (in ms) /// </summary> public float PredictionIncrement = 0.001f; // 1 ms private string strPrediction = "Pred: OFF"; private string strFOV = "FOV: 0.0f"; private string strHeight = "Height: 0.0f"; /// <summary> /// Controls how quickly the player's speed and rotation change based on input. /// </summary> public float SpeedRotationIncrement = 0.05f; private string strSpeedRotationMultipler = "Spd. X: 0.0f Rot. X: 0.0f"; private bool LoadingLevel = false; private float AlphaFadeValue = 1.0f; private int CurrentLevel = 0; // Rift detection private bool HMDPresent = false; private float RiftPresentTimeout = 0.0f; private string strRiftPresent = ""; // Replace the GUI with our own texture and 3D plane that // is attached to the rendder camera for true 3D placement private OVRGUI GuiHelper = new OVRGUI(); private GameObject GUIRenderObject = null; private RenderTexture GUIRenderTexture = null; // We want to use new Unity GUI built in 4.6 for OVRMainMenu GUI // Enable the UsingNewGUI option in the editor, // if you want to use new GUI and Unity version is higher than 4.6 #if USE_NEW_GUI private GameObject NewGUIObject = null; private GameObject RiftPresentGUIObject = null; #endif /// <summary> /// We can set the layer to be anything we want to, this allows /// a specific camera to render it. /// </summary> public string LayerName = "Default"; /// <summary> /// Crosshair rendered onto 3D plane. /// </summary> public UnityEngine.Texture CrosshairImage = null; private OVRCrosshair Crosshair = new OVRCrosshair(); // Resolution Eye Texture private string strResolutionEyeTexture = "Resolution: 0 x 0"; // Latency values private string strLatencies = "Ren: 0.0f TWrp: 0.0f PostPresent: 0.0f"; // Vision mode on/off private bool VisionMode = true; #if SHOW_DK2_VARIABLES private string strVisionMode = "Vision Enabled: ON"; #endif // We want to hold onto GridCube, for potential sharing // of the menu RenderTarget OVRGridCube GridCube = null; // We want to hold onto the VisionGuide so we can share // the menu RenderTarget OVRVisionGuide VisionGuide = null; #region MonoBehaviour Message Handlers /// <summary> /// Awake this instance. /// </summary> void Awake() { // Find camera controller OVRCameraRig[] CameraControllers; CameraControllers = gameObject.GetComponentsInChildren<OVRCameraRig>(); if(CameraControllers.Length == 0) Debug.LogWarning("OVRMainMenu: No OVRCameraRig attached."); else if (CameraControllers.Length > 1) Debug.LogWarning("OVRMainMenu: More then 1 OVRCameraRig attached."); else{ CameraController = CameraControllers[0]; #if USE_NEW_GUI OVRUGUI.CameraController = CameraController; #endif } // Find player controller OVRPlayerController[] PlayerControllers; PlayerControllers = gameObject.GetComponentsInChildren<OVRPlayerController>(); if(PlayerControllers.Length == 0) Debug.LogWarning("OVRMainMenu: No OVRPlayerController attached."); else if (PlayerControllers.Length > 1) Debug.LogWarning("OVRMainMenu: More then 1 OVRPlayerController attached."); else{ PlayerController = PlayerControllers[0]; #if USE_NEW_GUI OVRUGUI.PlayerController = PlayerController; #endif } #if USE_NEW_GUI // Create canvas for using new GUI NewGUIObject = new GameObject(); NewGUIObject.name = "OVRGUIMain"; NewGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = NewGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localScale = new Vector3(0.001f, 0.001f, 0.001f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; Canvas c = NewGUIObject.AddComponent<Canvas>(); #if (UNITY_5_0) // TODO: Unity 5.0b11 has an older version of the new GUI being developed in Unity 4.6. // Remove this once Unity 5 has a more recent merge of Unity 4.6. c.renderMode = RenderMode.WorldSpace; #else c.renderMode = RenderMode.WorldSpace; #endif c.pixelPerfect = false; #endif } /// <summary> /// Start this instance. /// </summary> void Start() { AlphaFadeValue = 1.0f; CurrentLevel = 0; PrevStartDown = false; PrevHatDown = false; PrevHatUp = false; ShowVRVars = false; OldSpaceHit = false; strFPS = "FPS: 0"; LoadingLevel = false; ScenesVisible = false; // Set the GUI target GUIRenderObject = GameObject.Instantiate(Resources.Load("OVRGUIObjectMain")) as GameObject; if(GUIRenderObject != null) { // Chnge the layer GUIRenderObject.layer = LayerMask.NameToLayer(LayerName); if(GUIRenderTexture == null) { int w = Screen.width; int h = Screen.height; // We don't need a depth buffer on this texture GUIRenderTexture = new RenderTexture(w, h, 0); GuiHelper.SetPixelResolution(w, h); // NOTE: All GUI elements are being written with pixel values based // from DK1 (1280x800). These should change to normalized locations so // that we can scale more cleanly with varying resolutions GuiHelper.SetDisplayResolution(1280.0f, 800.0f); } } // Attach GUI texture to GUI object and GUI object to Camera if(GUIRenderTexture != null && GUIRenderObject != null) { GUIRenderObject.GetComponent<Renderer>().material.mainTexture = GUIRenderTexture; if(CameraController != null) { // Grab transform of GUI object Vector3 ls = GUIRenderObject.transform.localScale; Vector3 lp = GUIRenderObject.transform.localPosition; Quaternion lr = GUIRenderObject.transform.localRotation; // Attach the GUI object to the camera GUIRenderObject.transform.parent = CameraController.centerEyeAnchor; // Reset the transform values (we will be maintaining state of the GUI object // in local state) GUIRenderObject.transform.localScale = ls; GUIRenderObject.transform.localPosition = lp; GUIRenderObject.transform.localRotation = lr; // Deactivate object until we have completed the fade-in // Also, we may want to deactive the render object if there is nothing being rendered // into the UI GUIRenderObject.SetActive(false); } } // Make sure to hide cursor if(Application.isEditor == false) { #if UNITY_5_0 Cursor.visible = false; Cursor.lockState = CursorLockMode.Locked; #else Screen.showCursor = false; Screen.lockCursor = true; #endif } // CameraController updates if(CameraController != null) { // Add a GridCube component to this object GridCube = gameObject.AddComponent<OVRGridCube>(); GridCube.SetOVRCameraController(ref CameraController); // Add a VisionGuide component to this object VisionGuide = gameObject.AddComponent<OVRVisionGuide>(); VisionGuide.SetOVRCameraController(ref CameraController); VisionGuide.SetFadeTexture(ref FadeInTexture); VisionGuide.SetVisionGuideLayer(ref LayerName); } // Crosshair functionality Crosshair.Init(); Crosshair.SetCrosshairTexture(ref CrosshairImage); Crosshair.SetOVRCameraController (ref CameraController); Crosshair.SetOVRPlayerController(ref PlayerController); // Check for HMD and sensor CheckIfRiftPresent(); #if USE_NEW_GUI if (!string.IsNullOrEmpty(strRiftPresent)){ ShowRiftPresentGUI(); } #endif } /// <summary> /// Update this instance. /// </summary> void Update() { if(LoadingLevel == true) return; // Main update UpdateFPS(); // CameraController updates if(CameraController != null) { UpdateIPD(); UpdateRecenterPose(); UpdateVisionMode(); UpdateFOV(); UpdateEyeHeightOffset(); UpdateResolutionEyeTexture(); UpdateLatencyValues(); } // PlayerController updates if(PlayerController != null) { UpdateSpeedAndRotationScaleMultiplier(); UpdatePlayerControllerMovement(); } // MainMenu updates UpdateSelectCurrentLevel(); // Device updates UpdateDeviceDetection(); // Crosshair functionality Crosshair.UpdateCrosshair(); #if USE_NEW_GUI if (ShowVRVars && RiftPresentTimeout <= 0.0f) { NewGUIObject.SetActive(true); UpdateNewGUIVars(); OVRUGUI.UpdateGUI(); } else { NewGUIObject.SetActive(false); } #endif // Toggle Fullscreen if(Input.GetKeyDown(KeyCode.F11)) Screen.fullScreen = !Screen.fullScreen; if (Input.GetKeyDown(KeyCode.M)) OVRManager.display.mirrorMode = !OVRManager.display.mirrorMode; // Escape Application if (Input.GetKeyDown(QuitKey)) Application.Quit(); } /// <summary> /// Updates Variables for new GUI. /// </summary> #if USE_NEW_GUI void UpdateNewGUIVars() { #if SHOW_DK2_VARIABLES // Print out Vision Mode OVRUGUI.strVisionMode = strVisionMode; #endif // Print out FPS OVRUGUI.strFPS = strFPS; // Don't draw these vars if CameraController is not present if (CameraController != null) { OVRUGUI.strPrediction = strPrediction; OVRUGUI.strIPD = strIPD; OVRUGUI.strFOV = strFOV; OVRUGUI.strResolutionEyeTexture = strResolutionEyeTexture; OVRUGUI.strLatencies = strLatencies; } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { OVRUGUI.strHeight = strHeight; OVRUGUI.strSpeedRotationMultipler = strSpeedRotationMultipler; } OVRUGUI.strRiftPresent = strRiftPresent; } #endif void OnGUI() { // Important to keep from skipping render events if (Event.current.type != EventType.Repaint) return; #if !USE_NEW_GUI // Fade in screen if(AlphaFadeValue > 0.0f) { AlphaFadeValue -= Mathf.Clamp01(Time.deltaTime / FadeInTime); if(AlphaFadeValue < 0.0f) { AlphaFadeValue = 0.0f; } else { GUI.color = new Color(0, 0, 0, AlphaFadeValue); GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture ); return; } } #endif // We can turn on the render object so we can render the on-screen menu if(GUIRenderObject != null) { if (ScenesVisible || ShowVRVars || Crosshair.IsCrosshairVisible() || RiftPresentTimeout > 0.0f || VisionGuide.GetFadeAlphaValue() > 0.0f) { GUIRenderObject.SetActive(true); } else { GUIRenderObject.SetActive(false); } } //*** // Set the GUI matrix to deal with portrait mode Vector3 scale = Vector3.one; Matrix4x4 svMat = GUI.matrix; // save current matrix // substitute matrix - only scale is altered from standard GUI.matrix = Matrix4x4.TRS(Vector3.zero, Quaternion.identity, scale); // Cache current active render texture RenderTexture previousActive = RenderTexture.active; // if set, we will render to this texture if(GUIRenderTexture != null && GUIRenderObject.activeSelf) { RenderTexture.active = GUIRenderTexture; GL.Clear (false, true, new Color (0.0f, 0.0f, 0.0f, 0.0f)); } // Update OVRGUI functions (will be deprecated eventually when 2D renderingc // is removed from GUI) GuiHelper.SetFontReplace(FontReplace); // If true, we are displaying information about the Rift not being detected // So do not show anything else if(GUIShowRiftDetected() != true) { GUIShowLevels(); GUIShowVRVariables(); } // The cross-hair may need to go away at some point, unless someone finds it // useful Crosshair.OnGUICrosshair(); // Since we want to draw into the main GUI that is shared within the MainMenu, // we call the OVRVisionGuide GUI function here VisionGuide.OnGUIVisionGuide(); // Restore active render texture if (GUIRenderObject.activeSelf) { RenderTexture.active = previousActive; } // *** // Restore previous GUI matrix GUI.matrix = svMat; } #endregion #region Internal State Management Functions /// <summary> /// Updates the FPS. /// </summary> void UpdateFPS() { TimeLeft -= Time.deltaTime; Accum += Time.timeScale/Time.deltaTime; ++Frames; // Interval ended - update GUI text and start new interval if( TimeLeft <= 0.0 ) { // display two fractional digits (f2 format) float fps = Accum / Frames; if(ShowVRVars == true)// limit gc strFPS = System.String.Format("FPS: {0:F2}",fps); TimeLeft += UpdateInterval; Accum = 0.0f; Frames = 0; } } /// <summary> /// Updates the IPD. /// </summary> void UpdateIPD() { if(ShowVRVars == true) // limit gc { strIPD = System.String.Format("IPD (mm): {0:F4}", OVRManager.profile.ipd * 1000.0f); } } void UpdateRecenterPose() { if(Input.GetKeyDown(KeyCode.R)) { OVRManager.display.RecenterPose(); } } /// <summary> /// Updates the vision mode. /// </summary> void UpdateVisionMode() { if (Input.GetKeyDown(KeyCode.F2)) { VisionMode = !VisionMode; OVRManager.tracker.isEnabled = VisionMode; #if SHOW_DK2_VARIABLES strVisionMode = VisionMode ? "Vision Enabled: ON" : "Vision Enabled: OFF"; #endif } } /// <summary> /// Updates the FOV. /// </summary> void UpdateFOV() { if(ShowVRVars == true)// limit gc { OVRDisplay.EyeRenderDesc eyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); strFOV = System.String.Format ("FOV (deg): {0:F3}", eyeDesc.fov.y); } } /// <summary> /// Updates resolution of eye texture /// </summary> void UpdateResolutionEyeTexture() { if (ShowVRVars == true) // limit gc { OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); OVRDisplay.EyeRenderDesc rightEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Right); float scale = OVRManager.instance.nativeTextureScale * OVRManager.instance.virtualTextureScale; float w = (int)(scale * (float)(leftEyeDesc.resolution.x + rightEyeDesc.resolution.x)); float h = (int)(scale * (float)Mathf.Max(leftEyeDesc.resolution.y, rightEyeDesc.resolution.y)); strResolutionEyeTexture = System.String.Format("Resolution : {0} x {1}", w, h); } } /// <summary> /// Updates latency values /// </summary> void UpdateLatencyValues() { #if !UNITY_ANDROID || UNITY_EDITOR if (ShowVRVars == true) // limit gc { OVRDisplay.LatencyData latency = OVRManager.display.latency; if (latency.render < 0.000001f && latency.timeWarp < 0.000001f && latency.postPresent < 0.000001f) strLatencies = System.String.Format("Ren : N/A TWrp: N/A PostPresent: N/A"); else strLatencies = System.String.Format("Ren : {0:F3} TWrp: {1:F3} PostPresent: {2:F3}", latency.render, latency.timeWarp, latency.postPresent); } #endif } /// <summary> /// Updates the eye height offset. /// </summary> void UpdateEyeHeightOffset() { if(ShowVRVars == true)// limit gc { float eyeHeight = OVRManager.profile.eyeHeight; strHeight = System.String.Format ("Eye Height (m): {0:F3}", eyeHeight); } } /// <summary> /// Updates the speed and rotation scale multiplier. /// </summary> void UpdateSpeedAndRotationScaleMultiplier() { float moveScaleMultiplier = 0.0f; PlayerController.GetMoveScaleMultiplier(ref moveScaleMultiplier); if(Input.GetKeyDown(KeyCode.Alpha7)) moveScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown(KeyCode.Alpha8)) moveScaleMultiplier += SpeedRotationIncrement; PlayerController.SetMoveScaleMultiplier(moveScaleMultiplier); float rotationScaleMultiplier = 0.0f; PlayerController.GetRotationScaleMultiplier(ref rotationScaleMultiplier); if(Input.GetKeyDown(KeyCode.Alpha9)) rotationScaleMultiplier -= SpeedRotationIncrement; else if (Input.GetKeyDown(KeyCode.Alpha0)) rotationScaleMultiplier += SpeedRotationIncrement; PlayerController.SetRotationScaleMultiplier(rotationScaleMultiplier); if(ShowVRVars == true)// limit gc strSpeedRotationMultipler = System.String.Format ("Spd.X: {0:F2} Rot.X: {1:F2}", moveScaleMultiplier, rotationScaleMultiplier); } /// <summary> /// Updates the player controller movement. /// </summary> void UpdatePlayerControllerMovement() { if(PlayerController != null) PlayerController.SetHaltUpdateMovement(ScenesVisible); } /// <summary> /// Updates the select current level. /// </summary> void UpdateSelectCurrentLevel() { ShowLevels(); if (!ScenesVisible) return; CurrentLevel = GetCurrentLevel(); if (Scenes.Length != 0 && (OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.A) || Input.GetKeyDown(KeyCode.Return))) { LoadingLevel = true; Application.LoadLevelAsync(Scenes[CurrentLevel]); } } /// <summary> /// Shows the levels. /// </summary> /// <returns><c>true</c>, if levels was shown, <c>false</c> otherwise.</returns> bool ShowLevels() { if (Scenes.Length == 0) { ScenesVisible = false; return ScenesVisible; } bool curStartDown = OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Start); bool startPressed = (curStartDown && !PrevStartDown) || Input.GetKeyDown(KeyCode.RightShift); PrevStartDown = curStartDown; if (startPressed) { ScenesVisible = !ScenesVisible; } return ScenesVisible; } /// <summary> /// Gets the current level. /// </summary> /// <returns>The current level.</returns> int GetCurrentLevel() { bool curHatDown = false; if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true) curHatDown = true; bool curHatUp = false; if(OVRGamepadController.GPC_GetButton(OVRGamepadController.Button.Down) == true) curHatUp = true; if((PrevHatDown == false) && (curHatDown == true) || Input.GetKeyDown(KeyCode.DownArrow)) { CurrentLevel = (CurrentLevel + 1) % SceneNames.Length; } else if((PrevHatUp == false) && (curHatUp == true) || Input.GetKeyDown(KeyCode.UpArrow)) { CurrentLevel--; if(CurrentLevel < 0) CurrentLevel = SceneNames.Length - 1; } PrevHatDown = curHatDown; PrevHatUp = curHatUp; return CurrentLevel; } #endregion #region Internal GUI Functions /// <summary> /// Show the GUI levels. /// </summary> void GUIShowLevels() { if(ScenesVisible == true) { // Darken the background by rendering fade texture GUI.color = new Color(0, 0, 0, 0.5f); GUI.DrawTexture( new Rect(0, 0, Screen.width, Screen.height ), FadeInTexture ); GUI.color = Color.white; if(LoadingLevel == true) { string loading = "LOADING..."; GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref loading, Color.yellow); return; } for (int i = 0; i < SceneNames.Length; i++) { Color c; if(i == CurrentLevel) c = Color.yellow; else c = Color.black; int y = StartY + (i * StepY); GuiHelper.StereoBox (StartX, y, WidthX, WidthY, ref SceneNames[i], c); } } } /// <summary> /// Show the VR variables. /// </summary> void GUIShowVRVariables() { bool SpaceHit = Input.GetKey(MenuKey); if ((OldSpaceHit == false) && (SpaceHit == true)) { if (ShowVRVars == true) { ShowVRVars = false; } else { ShowVRVars = true; #if USE_NEW_GUI OVRUGUI.InitUIComponent = ShowVRVars; #endif } } OldSpaceHit = SpaceHit; // Do not render if we are not showing if (ShowVRVars == false) return; #if !USE_NEW_GUI int y = VRVarsSY; #if SHOW_DK2_VARIABLES // Print out Vision Mode GuiHelper.StereoBox (VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strVisionMode, Color.green); #endif // Draw FPS GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFPS, Color.green); // Don't draw these vars if CameraController is not present if (CameraController != null) { GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strPrediction, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strIPD, Color.yellow); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strFOV, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strResolutionEyeTexture, Color.white); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strLatencies, Color.white); } // Don't draw these vars if PlayerController is not present if (PlayerController != null) { GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strHeight, Color.yellow); GuiHelper.StereoBox(VRVarsSX, y += StepY, VRVarsWidthX, VRVarsWidthY, ref strSpeedRotationMultipler, Color.white); } #endif } // RIFT DETECTION /// <summary> /// Checks to see if HMD and / or sensor is available, and displays a /// message if it is not. /// </summary> void CheckIfRiftPresent() { HMDPresent = OVRManager.display.isPresent; if (!HMDPresent) { RiftPresentTimeout = 15.0f; if (!HMDPresent) strRiftPresent = "NO HMD DETECTED"; #if USE_NEW_GUI OVRUGUI.strRiftPresent = strRiftPresent; #endif } } /// <summary> /// Show if Rift is detected. /// </summary> /// <returns><c>true</c>, if show rift detected was GUIed, <c>false</c> otherwise.</returns> bool GUIShowRiftDetected() { #if !USE_NEW_GUI if(RiftPresentTimeout > 0.0f) { GuiHelper.StereoBox (StartX, StartY, WidthX, WidthY, ref strRiftPresent, Color.white); return true; } #else if(RiftPresentTimeout < 0.0f) DestroyImmediate(RiftPresentGUIObject); #endif return false; } /// <summary> /// Updates the device detection. /// </summary> void UpdateDeviceDetection() { if(RiftPresentTimeout > 0.0f) RiftPresentTimeout -= Time.deltaTime; } /// <summary> /// Show rift present GUI with new GUI /// </summary> void ShowRiftPresentGUI() { #if USE_NEW_GUI RiftPresentGUIObject = new GameObject(); RiftPresentGUIObject.name = "RiftPresentGUIMain"; RiftPresentGUIObject.transform.parent = GameObject.Find("LeftEyeAnchor").transform; RectTransform r = RiftPresentGUIObject.AddComponent<RectTransform>(); r.sizeDelta = new Vector2(100f, 100f); r.localPosition = new Vector3(0.01f, 0.17f, 0.53f); r.localEulerAngles = Vector3.zero; r.localScale = new Vector3(0.001f, 0.001f, 0.001f); Canvas c = RiftPresentGUIObject.AddComponent<Canvas>(); #if UNITY_5_0 // TODO: Unity 5.0b11 has an older version of the new GUI being developed in Unity 4.6. // Remove this once Unity 5 has a more recent merge of Unity 4.6. c.renderMode = RenderMode.WorldSpace; #else c.renderMode = RenderMode.WorldSpace; #endif c.pixelPerfect = false; OVRUGUI.RiftPresentGUI(RiftPresentGUIObject); #endif } #endregion }
using System.Collections.Generic; using DevExpress.XtraReports.UI; using EIDSS.FlexibleForms.Helpers; using EIDSS.FlexibleForms.Helpers.ReportHelper.Tree; using EIDSS.Reports.Flexible.Visitors; using bv.winclient.Core; namespace EIDSS.Reports.Flexible { public class FlexFactory { #region Human public static void CreateHumanClinicalSignsReport(SubreportBase parentSubreport, long id, long diagnosis) { CreateFlexReport(parentSubreport, id, diagnosis, FFType.HumanClinicalSigns); } public static void CreateHumanEpiObservationsReport(SubreportBase parentSubreport, long id, long diagnosis) { CreateFlexReport(parentSubreport, id, diagnosis, FFType.HumanEpiInvestigations); } #endregion #region Lim public static void CreateLimBatchReport(SubreportBase parentSubreport, long id, long type) { CreateFlexReport(parentSubreport, id, type, FFType.TestRun); } public static void CreateLimTestReport(SubreportBase parentSubreport, long id, long? type) { CreateFlexReport(parentSubreport, id, type, FFType.TestDetails); } #endregion #region Vet public static void CreateControlMeasuresReport(SubreportBase parentSubreport, long id, long diagnosis) { CreateFlexReport(parentSubreport, id, diagnosis, FFType.LivestockControlMeasures); } public static void CreateLivestockEpiReport(SubreportBase parentSubreport, long id, long diagnosis) { CreateFlexReport(parentSubreport, id, diagnosis, FFType.LivestockFarmEPI); } public static void CreateAvianEpiReport(SubreportBase parentSubreport, long id, long diagnosis) { CreateFlexReport(parentSubreport, id, diagnosis, FFType.AvianFarmEPI); } public static void CreateLivestockClinicalReport(SubreportBase parentSubreport, long id, long diagnosis) { CreateFlexReport(parentSubreport, id, diagnosis, FFType.LivestockSpeciesCS); } public static void CreateAvianClinicalReport(SubreportBase parentSubreport, long id, long diagnosis) { CreateFlexReport(parentSubreport, id, diagnosis, FFType.AvianSpeciesCS); } #endregion #region Human Aggregate public static void CreateHumanAggregateReport(SubreportBase parentSubreport, long idFormTemplate, long id, int? tableMaxSize) { var dictionary = new Dictionary<int, int> {{3, 3}}; CreateFlexAggregateReport(parentSubreport, idFormTemplate, AggregateCaseSection.HumanCase, id, FFType.HumanAggregateCase, tableMaxSize, dictionary); } public static void CreateHumanAggregateSummaryReport (SubreportBase parentSubreport, List<long> ids, int? tableMaxSize) { var dictionary = new Dictionary<int, int> {{3, 3}}; CreateFlexAggregateSummaryReport(parentSubreport, ids, FFType.HumanAggregateCase, tableMaxSize, dictionary); } #endregion #region Vet Aggregate public static void CreateVetAggregateReport(SubreportBase parentSubreport, long idFormTemplate, long id, int? tableMaxSize) { CreateFlexAggregateReport(parentSubreport,idFormTemplate, AggregateCaseSection.VetCase, id, FFType.VetAggregateCase, tableMaxSize); } public static void CreateVetAggregateActionsReport (SubreportBase parentSubreport, long idFormTemplate, long id, int? tableMaxSize, string header) { CreateFlexAggregateReport(parentSubreport,idFormTemplate, AggregateCaseSection.DiagnosticAction, id, FFType.VetEpizooticActionDiagnosisInv, tableMaxSize, header); } public static void CreateVetAggregateActionsProReport (SubreportBase parentSubreport, long idFormTemplate, long id, int? tableMaxSize, string header) { CreateFlexAggregateReport(parentSubreport, idFormTemplate, AggregateCaseSection.ProphylacticAction, id, FFType.VetEpizooticActionTreatment, tableMaxSize, header); } public static void CreateVetAggregateActionsSanReport (SubreportBase parentSubreport, long idFormTemplate, long id, int? tableMaxSize, string header) { CreateFlexAggregateReport(parentSubreport, idFormTemplate, AggregateCaseSection.SanitaryAction, id, FFType.VetEpizooticAction, tableMaxSize, header); } public static void CreateVetAggregateSummaryReport (SubreportBase parentSubreport, List<long> ids, int? tableMaxSize) { CreateFlexAggregateSummaryReport(parentSubreport, ids, FFType.VetAggregateCase, tableMaxSize); } public static void CreateVetAggregateActionsSummaryReport (SubreportBase parentSubreport, List<long> ids, int? tableMaxSize, string header) { CreateFlexAggregateSummaryReport(parentSubreport, ids, FFType.VetEpizooticActionDiagnosisInv, tableMaxSize, header); } public static void CreateVetAggregateActionsSummaryProReport (SubreportBase parentSubreport, List<long> ids, int? tableMaxSize, string header) { CreateFlexAggregateSummaryReport(parentSubreport, ids, FFType.VetEpizooticActionTreatment, tableMaxSize, header); } public static void CreateVetAggregateActionsSummarySanReport (SubreportBase parentSubreport, List<long> ids, int? tableMaxSize, string header) { CreateFlexAggregateSummaryReport(parentSubreport, ids, FFType.VetEpizooticAction, tableMaxSize, header); } #endregion private static void CreateFlexAggregateSummaryReport (SubreportBase parentSubreport, List<long> ids, FFType formType, int? tableMaxSize, Dictionary<int, int> levelFont = null) { CreateFlexAggregateSummaryReport(parentSubreport, ids, formType, tableMaxSize, string.Empty, levelFont); } private static void CreateFlexAggregateSummaryReport (SubreportBase parentSubreport, List<long> ids, FFType formType, int? tableMaxSize, string header, Dictionary<int, int> levelFont = null) { var templateHelper = new TemplateHelper(); templateHelper.LoadSummary(ids, formType); FlexNode flexNode = templateHelper.GetFlexNodeFromTemplateSummary(); flexNode.ProcessAsTable = true; parentSubreport.ReportSource = CreateFlexReport(flexNode, header, tableMaxSize, levelFont); } private static void CreateFlexAggregateReport (SubreportBase parentSubreport, long idFormTemplate, AggregateCaseSection presetStub, long id, FFType formType, int? tableMaxSize, Dictionary<int, int> levelFont = null) { CreateFlexAggregateReport(parentSubreport, idFormTemplate, presetStub, id, formType, tableMaxSize, string.Empty, levelFont); } private static void CreateFlexAggregateReport (SubreportBase parentSubreport, long idFormTemplate, AggregateCaseSection presetStub, long id, FFType formType, int? tableMaxSize, string reportHeader, Dictionary<int, int> levelFont = null) { var templateHelper = new TemplateHelper(); //templateHelper.LoadAggregateTemplate(presetStub, id, formType); templateHelper.LoadAggregateTemplate(idFormTemplate, presetStub, id, formType); FlexNode flexNode = templateHelper.GetFlexNodeFromTemplate(id); flexNode.ProcessAsTable = true; parentSubreport.ReportSource = CreateFlexReport(flexNode, reportHeader, tableMaxSize, levelFont); } private static void CreateFlexReport(SubreportBase parentSubreport, long id, long? determinant,FFType formType) { var templateHelper = new TemplateHelper(); templateHelper.LoadTemplate(new List<long> {id}, determinant, formType); FlexNode flexNode = templateHelper.GetFlexNodeFromTemplate(id); parentSubreport.ReportSource = CreateFlexReport(flexNode, string.Empty, null); } public static FlexReport CreateFlexReport (FlexNode root, string tableHeader, int? tableMaxSize, Dictionary<int, int> levelFont = null) { root.AcceptForward(new AuditVisitor()); root.AcceptForward(new ShouldProcessAsTableVisitor()); var levelVisitor = new LevelVisitor(); root.AcceptForward(levelVisitor); var auditWidthVisitor = new AuditWidthVisitor(); for (int i = levelVisitor.MaxLevel; i > 0; i--) { auditWidthVisitor.LevelToVisit = i; root.AcceptBackword(auditWidthVisitor); } if (!string.IsNullOrEmpty(auditWidthVisitor.ErrorMessage)) { MessageForm.Show(auditWidthVisitor.ErrorMessage, "Flexible Form Error"); } var reportVisitor = new ReportVisitor {LevelFont = levelFont}; root.AcceptForward(reportVisitor); var tableVisitor = new TableVisitor {TableMaxWidth = tableMaxSize, TableHeader = tableHeader}; root.AcceptForward(tableVisitor); var report = (FlexReport) root.AssignedControl; EndInitChildren(report); // note[ivan]: no need to set header for whole report, just set it for main table report.Text = string.Empty; return report; } private static void EndInitChildren(XRControl parent) { foreach (XRControl child in parent.Controls) { EndInitChildren(child); } if (parent is XRSubreport) { EndInitChildren(((XRSubreport) (parent)).ReportSource); } var flexTable = parent as FlexTable; if (flexTable != null) { (flexTable).EndInit(); } } } }
using System; public static class FF9BattleDBHeightAndRadius { public const Int32 GeoCount = 661; public static readonly Int32[,] Data; static FF9BattleDBHeightAndRadius() { Data = LoadHeightRadiusData(); } public static Boolean TryFindHeightAndRadius(Int32 geoId, ref Int32 height, ref Int32 radius) { Int32 index; if (BinarySearch(geoId, out index)) { height = Data[index, 1]; radius = Data[index, 2]; return true; } return false; } public static Boolean TryFindNeckBoneIndex(Int32 geoId, ref Int32 boneIndex) { Int32 index; if (BinarySearch(geoId, out index)) { boneIndex = Data[index, 3]; return true; } return false; } private static Boolean BinarySearch(Int32 geoId, out Int32 index) { Int32 first = 0; Int32 last = GeoCount; if (Data[0, 0] > geoId) { index = -1; return false; } if (Data[GeoCount - 1, 0] < geoId) { index = -1; return false; } while (first < last) { Int32 mid = first + ((last - first) >> 1); Int32 value = Data[mid, 0]; if (value == geoId) { index = mid; return true; } if (geoId < value) last = mid; else first = mid + 1; } index = -1; return false; } private static Int32[,] LoadHeightRadiusData() { return new Int32[661, 4] { {0, 4693, 2026, 34}, {1, 2351, 1175, 0}, {2, 1751, 813, 11}, {3, 400, 715, 0}, {4, 671, 2321, 44}, {5, 573, 251, 20}, {6, 38, 787, 0}, {7, 0, 25, 0}, {8, 395, 156, 19}, {9, 252, 420, 5}, {10, 407, 219, 3}, {11, 444, 227, 7}, {12, 407, 219, 3}, {13, 407, 219, 3}, {14, 540, 454, 0}, {15, 21, 394, 0}, {16, 616, 971, 0}, {17, 470, 190, 16}, {18, 451, 215, 7}, {19, 518, 202, 7}, {20, 441, 200, 7}, {21, 435, 190, 7}, {22, 749, 117, 0}, {23, 203, 177, 0}, {24, 441, 177, 7}, {25, 465, 189, 7}, {26, 475, 186, 7}, {27, 318, 93, 3}, {28, 449, 426, 2}, {31, 113, 46, 4}, {32, 318, 93, 3}, {33, 566, 2075, 0}, {34, 318, 93, 3}, {35, 142, 78, 6}, {36, 671, 2321, 44}, {37, 41, 167, 0}, {38, 3083, 796, 48}, {39, 415, 189, 12}, {40, 318, 93, 3}, {41, 283, 206, 0}, {42, 456, 166, 3}, {43, 52, 195, 0}, {44, 39, 149, 0}, {45, 470, 215, 8}, {46, 440, 355, 8}, {47, 107, 391, 0}, {48, 462, 157, 3}, {49, 303, 98, 3}, {50, 455, 183, 16}, {51, 437, 181, 7}, {52, 377, 164, 7}, {53, 603, 219, 7}, {54, 598, 324, 3}, {55, 300, 98, 3}, {56, 465, 189, 7}, {57, 150, 143, 7}, {58, 635, 594, 9}, {59, 376, 270, 12}, {60, 102, 719, 11}, {61, 318, 93, 3}, {62, 473, 270, 21}, {63, 127, 135, 7}, {64, 457, 178, 7}, {65, 525, 268, 19}, {66, 490, 309, 18}, {67, 472, 183, 7}, {68, 456, 224, 11}, {69, 207, 155, 6}, {70, 479, 189, 7}, {71, 476, 187, 7}, {72, 402, 160, 14}, {73, 468, 209, 3}, {74, 453, 176, 7}, {75, 257, 149, 0}, {76, 445, 160, 19}, {77, 1153, 559, 0}, {78, 947, 3060, 12}, {79, 470, 2230, 0}, {80, 848, 1418, 2}, {81, 430, 1301, 3}, {82, 533, 447, 2}, {83, 1205, 590, 9}, {84, 716, 763, 3}, {85, 1035, 1936, 15}, {86, 428, 921, 3}, {87, 2343, 1666, 11}, {88, 910, 1670, 5}, {89, 656, 1207, 3}, {90, 602, 1243, 3}, {91, 261, 144, 0}, {92, 650, 524, 33}, {93, 808, 1433, 7}, {94, 614, 272, 2}, {95, 1202, 2023, 1}, {96, 933, 1031, 1}, {97, 854, 707, 28}, {98, 458, 364, 8}, {99, 437, 181, 7}, {100, 571, 353, 5}, {101, 470, 190, 16}, {102, 441, 203, 11}, {103, 407, 225, 3}, {104, 554, 243, 7}, {105, 702, 502, 3}, {106, 555, 400, 15}, {107, 415, 232, 12}, {108, 457, 197, 7}, {109, 470, 249, 8}, {110, 457, 197, 7}, {111, 470, 190, 16}, {112, 407, 219, 3}, {113, 449, 283, 3}, {114, 78, 59, 2}, {115, 212, 252, 8}, {116, 502, 202, 3}, {117, 441, 203, 11}, {118, 441, 200, 7}, {119, 535, 170, 7}, {120, 516, 185, 3}, {121, 323, 277, 7}, {122, 444, 227, 7}, {123, 518, 202, 7}, {124, 451, 215, 7}, {125, 593, 337, 11}, {126, 407, 225, 3}, {127, 435, 284, 3}, {128, 43, 57, 0}, {129, 406, 151, 11}, {130, 460, 222, 3}, {131, 389, 227, 3}, {132, 450, 249, 3}, {133, 46, 293, 0}, {134, 319, 36, 0}, {135, 599, 365, 29}, {136, 384, 550, 2}, {137, 489, 609, 2}, {138, 559, 616, 12}, {141, 765, 796, 1}, {142, 1301, 2026, 4}, {143, 673, 511, 5}, {144, 199, 103, 2}, {145, 773, 726, 3}, {146, 1959, 4226, 3}, {147, 1178, 506, 32}, {148, 571, 630, 2}, {149, 511, 474, 2}, {150, 225, 1043, 0}, {151, 398, 256, 13}, {152, 458, 297, 8}, {153, 281, 505, 0}, {154, 258, 166, 0}, {155, 334, 340, 0}, {156, 245, 405, 2}, {157, 598, 593, 25}, {158, 294, 698, 2}, {159, 205, 1730, 38}, {160, 705, 773, 17}, {161, 220, 607, 0}, {162, 512, 462, 27}, {163, 851, 886, 2}, {164, 475, 938, 25}, {165, 880, 3074, 14}, {166, 901, 602, 11}, {167, 573, 412, 28}, {168, 593, 337, 11}, {169, 631, 660, 28}, {170, 454, 248, 3}, {171, 436, 188, 14}, {172, 463, 183, 12}, {173, 459, 175, 3}, {174, 133, 87, 11}, {175, 133, 87, 11}, {176, 133, 87, 11}, {177, 486, 233, 20}, {178, 25, 113, 1}, {179, 472, 192, 14}, {180, 303, 98, 3}, {181, 490, 309, 18}, {182, 528, 366, 3}, {183, 470, 190, 16}, {184, 388, 345, 22}, {185, 445, 160, 19}, {186, 750, 371, 19}, {187, 435, 190, 7}, {188, 434, 207, 3}, {189, 501, 214, 3}, {190, 438, 162, 3}, {191, 151, 84, 13}, {192, 583, 334, 8}, {193, 218, 212, 2}, {194, 441, 210, 16}, {195, 435, 261, 2}, {196, 342, 125, 20}, {197, 370, 206, 3}, {198, 287, 105, 11}, {199, 406, 151, 11}, {200, 1841, 1915, 0}, {201, 1160, 2087, 0}, {202, 443, 181, 22}, {203, 458, 207, 21}, {204, 472, 178, 18}, {205, 443, 181, 22}, {206, 334, 277, 7}, {207, 507, 412, 11}, {208, 467, 210, 12}, {209, 531, 209, 18}, {210, 500, 184, 7}, {211, 449, 179, 7}, {212, 406, 178, 10}, {213, 475, 186, 7}, {214, 568, 266, 2}, {215, 568, 250, 2}, {216, 490, 193, 7}, {217, 528, 366, 3}, {218, 464, 386, 3}, {219, 484, 222, 3}, {220, 406, 151, 11}, {221, 618, 467, 0}, {222, 121, 37, 0}, {223, 79, 24, 0}, {224, 15, 585, 0}, {225, 570, 313, 0}, {226, 299, 53, 0}, {227, 64, 28, 0}, {228, 67, 22, 0}, {229, 672, 553, 0}, {230, 455, 611, 0}, {231, 833, 656, 0}, {232, 564, 782, 0}, {233, 61, 90, 0}, {234, 31, 43, 0}, {235, 91, 78, 0}, {236, 14, 87, 0}, {237, 11, 34, 0}, {238, 310, 145, 0}, {239, 102, 80, 1}, {240, 412, 451, 0}, {241, 376, 193, 0}, {242, 628, 195, 0}, {243, 63, 326, 0}, {244, 357, 95, 8}, {245, 851, 886, 2}, {246, 773, 726, 3}, {247, 398, 256, 13}, {248, 294, 698, 2}, {249, 252, 420, 5}, {250, 220, 4887, 9}, {251, 342, 4841, 9}, {252, 1308, 1112, 8}, {253, 441, 177, 7}, {254, 602, 1243, 3}, {255, 808, 1433, 7}, {256, 1061, 2883, 3}, {257, 443, 181, 14}, {258, 34, 91, 0}, {259, 571, 353, 5}, {260, 336, 142, 4}, {261, 1240, 1333, 13}, {262, 496, 1536, 0}, {264, 50, 168, 0}, {265, 618, 499, 24}, {266, 848, 581, 0}, {267, 573, 251, 20}, {268, 490, 209, 3}, {269, 513, 244, 14}, {270, 493, 223, 3}, {272, 572, 291, 15}, {273, 502, 254, 6}, {274, 463, 183, 12}, {275, 94, 34, 0}, {277, 192, 111, 0}, {278, 573, 412, 28}, {279, 1297, 1394, 0}, {281, 445, 160, 19}, {282, 434, 207, 3}, {283, 445, 160, 19}, {284, 356, 154, 19}, {285, 458, 364, 8}, {286, 603, 272, 20}, {287, 445, 160, 19}, {288, 445, 160, 19}, {289, 502, 254, 6}, {290, 583, 334, 8}, {291, 356, 154, 19}, {294, 1659, 1113, 17}, {295, 502, 306, 6}, {296, 603, 373, 20}, {297, 583, 544, 23}, {298, 603, 373, 20}, {299, 410, 243, 8}, {300, 463, 183, 12}, {301, 574, 449, 19}, {302, 463, 183, 12}, {303, 603, 219, 7}, {304, 551, 249, 2}, {305, 598, 324, 3}, {306, 831, 958, 12}, {307, 336, 152, 2}, {308, 578, 351, 12}, {309, 445, 156, 20}, {310, 453, 361, 7}, {311, 489, 284, 0}, {312, 853, 704, 0}, {313, 727, 464, 0}, {314, 327, 553, 0}, {315, 455, 611, 0}, {316, 833, 656, 0}, {317, 829, 1164, 0}, {318, 455, 611, 0}, {319, 833, 656, 0}, {320, 660, 830, 0}, {321, 699, 703, 0}, {322, 67, 170, 0}, {323, 525, 199, 37}, {324, 1595, 2140, 2}, {325, 1016, 1368, 43}, {326, 748, 1223, 2}, {327, 1286, 729, 2}, {328, 872, 431, 12}, {329, 922, 856, 6}, {330, 349, 750, 8}, {331, 759, 778, 3}, {332, 934, 802, 5}, {333, 444, 408, 0}, {334, 1029, 702, 0}, {335, 701, 536, 2}, {336, 1061, 2883, 3}, {337, 1351, 1691, 5}, {338, 2573, 1944, 4}, {339, 1682, 1814, 2}, {340, 559, 1239, 0}, {341, 992, 1190, 2}, {342, 348, 1605, 37}, {343, 1176, 855, 4}, {344, 1308, 1112, 8}, {345, 242, 466, 2}, {346, 1420, 871, 7}, {347, 1160, 2087, 0}, {348, 220, 4887, 9}, {349, 2533, 1940, 11}, {350, 775, 1205, 10}, {351, 1409, 1419, 46}, {352, 342, 4841, 38}, {353, 995, 2438, 12}, {354, 1940, 563, 0}, {355, 2497, 3162, 7}, {356, 98, 98, 0}, {357, 85, 85, 0}, {358, 472, 178, 18}, {359, 574, 486, 21}, {360, 501, 214, 3}, {362, 1554, 1328, 4}, {363, 1751, 813, 11}, {364, 1404, 1137, 46}, {365, 140, 425, 0}, {366, 61, 324, 0}, {367, 89, 431, 0}, {368, 517, 182, 21}, {369, 866, 510, 7}, {370, 3236, 3753, 0}, {371, 872, 2697, 5}, {376, 441, 203, 11}, {377, 191, 393, 0}, {378, 1121, 1942, 78}, {379, 695, 447, 0}, {380, 586, 603, 23}, {381, 369, 138, 7}, {382, 672, 341, 17}, {383, 58, 446, 0}, {384, 61, 324, 0}, {385, 61, 324, 0}, {386, 81, 324, 0}, {387, 61, 324, 0}, {388, 51, 315, 0}, {389, 56, 311, 0}, {390, 47, 353, 0}, {391, 54, 327, 0}, {392, 56, 311, 0}, {395, 0, 625, 0}, {398, 294, 698, 2}, {399, 511, 474, 2}, {400, 245, 405, 2}, {401, 199, 103, 2}, {402, 922, 856, 6}, {403, 150, 143, 7}, {404, 533, 447, 2}, {405, 384, 550, 2}, {406, 831, 278, 0}, {407, 533, 865, 0}, {408, 476, 75, 0}, {409, 134, 142, 0}, {410, 517, 387, 21}, {411, 6, 79, 0}, {412, 554, 243, 7}, {413, 67, 585, 0}, {414, 1012, 245, 0}, {415, 1127, 541, 0}, {416, 1380, 1137, 0}, {417, 494, 271, 7}, {418, 318, 93, 3}, {419, 445, 346, 16}, {420, 343, 185, 7}, {421, 389, 202, 3}, {422, 385, 190, 3}, {423, 133, 87, 11}, {424, 318, 93, 3}, {425, 176, 100, 3}, {426, 449, 191, 7}, {427, 472, 371, 18}, {428, 750, 449, 19}, {429, 750, 264, 3}, {430, 750, 371, 2}, {431, 534, 340, 7}, {432, 497, 271, 18}, {433, 33, 170, 0}, {434, 78, 71, 0}, {435, 95, 171, 0}, {436, 1107, 825, 0}, {437, 459, 160, 0}, {438, 8, 8, 0}, {439, 17, 25, 0}, {440, 73, 208, 0}, {441, 67, 201, 0}, {442, 775, 1205, 10}, {443, 356, 154, 19}, {444, 622, 350, 18}, {445, 568, 306, 2}, {446, 751, 383, 51}, {447, 492, 346, 7}, {450, 631, 660, 28}, {451, 580, 2604, 2}, {452, 0, 992, 0}, {453, 108, 281, 0}, {454, 108, 281, 0}, {455, 112, 261, 0}, {456, 86, 193, 0}, {457, 89, 305, 0}, {458, 108, 287, 0}, {459, 127, 286, 0}, {460, 139, 304, 0}, {461, 37, 183, 0}, {462, 45, 183, 0}, {463, 49, 202, 0}, {464, 30, 222, 0}, {465, 86, 524, 0}, {466, 54, 540, 0}, {467, 64, 446, 0}, {468, 173, 483, 0}, {469, 115, 520, 0}, {470, 39, 522, 0}, {471, 56, 258, 0}, {472, 103, 264, 0}, {473, 56, 158, 0}, {474, 107, 240, 0}, {475, 81, 198, 0}, {476, 38, 200, 0}, {477, 74, 200, 0}, {478, 71, 176, 0}, {479, 20, 184, 0}, {480, 34, 183, 0}, {481, 58, 185, 0}, {482, 48, 176, 0}, {483, 34, 201, 0}, {484, 49, 227, 0}, {485, 90, 240, 0}, {486, 55, 229, 0}, {487, 221, 97, 0}, {488, 620, 1630, 0}, {489, 162, 145, 0}, {490, 373, 522, 0}, {491, 37, 183, 0}, {492, 37, 183, 0}, {493, 37, 183, 0}, {494, 39, 149, 0}, {495, 39, 149, 0}, {496, 86, 524, 0}, {497, 86, 524, 0}, {498, 56, 258, 0}, {499, 56, 258, 0}, {500, 56, 258, 0}, {501, 38, 200, 0}, {502, 71, 176, 0}, {503, 71, 176, 0}, {504, 71, 176, 0}, {505, 49, 227, 0}, {506, 49, 227, 0}, {507, 49, 227, 0}, {508, 497, 160, 16}, {509, 622, 350, 18}, {512, 1956, 2835, 0}, {514, 124, 396, 0}, {515, 87, 395, 0}, {516, 20, 380, 0}, {517, 83, 377, 0}, {518, 81, 377, 0}, {519, 129, 375, 0}, {520, 22, 383, 0}, {521, 72, 386, 0}, {522, 30, 386, 0}, {523, 1027, 422, 0}, {524, 242, 466, 2}, {526, 603, 419, 49}, {527, 31, 200, 0}, {528, 2533, 1940, 11}, {529, 1404, 1137, 46}, {530, 2694, 304, 16}, {531, 643, 345, 23}, {532, 458, 419, 50}, {533, 872, 2697, 5}, {534, 609, 477, 42}, {535, 1045, 3617, 42}, {536, 247, 119, 0}, {537, 321, 167, 0}, {538, 247, 119, 0}, {539, 444, 242, 20}, {540, 460, 250, 20}, {541, 404, 214, 20}, {542, 803, 489, 19}, {543, 465, 189, 7}, {544, 435, 190, 7}, {545, 1100, 3916, 29}, {546, 405, 337, 39}, {547, 554, 243, 7}, {548, 525, 199, 37}, {549, 343, 185, 7}, {550, 389, 202, 3}, {551, 385, 190, 3}, {553, 934, 802, 5}, {555, 47, 353, 0}, {556, 763, 1228, 53}, {557, 445, 160, 19}, {558, 395, 156, 7}, {559, 470, 190, 16}, {564, 490, 209, 3}, {566, 943, 487, 42}, {567, 723, 401, 37}, {569, 458, 364, 21}, {570, 356, 204, 19}, {571, 395, 211, 19}, {572, 622, 445, 18}, {573, 622, 445, 18}, {574, 763, 1063, 29}, {575, 376, 270, 12}, {576, 2286, 849, 63}, {577, 299, 53, 0}, {578, 299, 53, 0}, {579, 299, 53, 0}, {580, 458, 364, 8}, {581, 458, 364, 8}, {582, 445, 160, 19}, {583, 445, 160, 19}, {584, 481, 156, 7}, {585, 583, 334, 8}, {586, 1625, 413, 0}, {587, 1138, 600, 0}, {588, 37, 182, 6}, {589, 51, 122, 6}, {590, 97, 185, 6}, {591, 441, 337, 18}, {592, 449, 333, 16}, {593, 507, 412, 11}, {594, 77, 413, 0}, {595, 77, 413, 0}, {596, 106, 2105, 0}, {597, 437, 181, 7}, {598, 435, 261, 2}, {599, 441, 203, 11}, {600, 467, 210, 12}, {601, 445, 160, 19}, {602, 445, 160, 19}, {603, 472, 192, 14}, {604, 300, 98, 3}, {605, 81, 648, 0}, {606, 603, 272, 20}, {607, 530, 254, 6}, {608, 438, 162, 3}, {609, 412, 36, 0}, {610, 711, 1163, 34}, {612, 475, 186, 7}, {613, 571, 353, 5}, {614, 571, 353, 5}, {615, 571, 353, 5}, {616, 711, 1163, 34}, {617, 1016, 1368, 43}, {618, 1121, 1942, 78}, {619, 3083, 796, 48}, {620, 1409, 1419, 46}, {621, 3236, 3753, 0}, {622, 1000, 287, 0}, {624, 212, 252, 8}, {625, 454, 263, 0}, {626, 108, 21, 0}, {627, 74, 469, 0}, {628, 23, 438, 0}, {629, 82, 324, 0}, {630, 108, 21, 0}, {631, 108, 21, 0}, {632, 108, 21, 0}, {633, 78, 71, 0}, {634, 78, 71, 0}, {635, 78, 71, 0}, {636, 3292, 563, 0}, {637, 264, 272, 0}, {638, 27, 18, 0}, {639, 456, 350, 3}, {640, 86, 524, 0}, {641, 86, 76, 0}, {642, 37, 214, 0}, {643, 303, 98, 3}, {644, 360, 154, 19}, {645, 360, 154, 19}, {646, 441, 177, 7}, {647, 441, 203, 11}, {648, 645, 350, 18}, {655, 603, 272, 20}, {658, 603, 272, 20}, {659, 456, 166, 3}, {660, 470, 249, 8}, {661, 415, 232, 12}, {662, 395, 156, 19}, {663, 489, 609, 2}, {664, 410, 243, 8}, {665, 461, 247, 26}, {666, 356, 172, 26}, {667, 573, 251, 20}, {668, 458, 364, 8}, {669, 458, 364, 8}, {670, 458, 364, 8}, {671, 445, 235, 19}, {672, 3236, 2426, 0}, {673, 1310, 11, 3}, {674, 479, 189, 7}, {675, 449, 179, 7}, {676, 759, 778, 3}, {677, 377, 164, 7}, {678, 377, 164, 7}, {679, 319, 36, 0}, {680, 34, 91, 0}, {681, 63, 326, 0}, {701, 257, 149, 0}, {702, 261, 144, 0}, {5414, 458, 364, 8}, {5415, 395, 156, 7}, {5458, 401, 687, 2}, {5459, 769, 1133, 14}, {5460, 540, 344, 2}, {5461, 566, 2075, 0}, {5464, 574, 259, 8}, {5467, 456, 166, 3}, {5468, 551, 249, 2}, {5474, 401, 168, 3}, {5476, 439, 175, 20}, {5478, 457, 197, 7}, {5488, 449, 191, 7}, {5489, 603, 272, 20}, {5492, 318, 93, 3}, {5500, 410, 243, 8}, {5501, 574, 293, 8}, {5505, 458, 171, 7}, {5509, 417, 193, 7}, {5511, 406, 192, 7} }; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Helpers; namespace BrillTown { /// <summary> /// Helps manage the coding-world-cup API. /// /// You can derive from this class and implement its abstract /// functions in your API. /// </summary> public abstract class CodingWorldCupAPI { #region Public and protected methods /// <summary> /// Constructor. /// </summary> public CodingWorldCupAPI() { // Uncomment this line to launch the debugger when the AI starts up. // you can then set breakpoints in the rest of your code. //System.Diagnostics.Debugger.Launch(); // We run the game loop... Logger.log("Starting game loop", Logger.LogLevel.INFO); for (; ; ) { // We "listen" to game messages on stdin, and process them... var message = Console.ReadLine(); processMessage(message); } } /// <summary> /// Sends a reply back to the game. /// </summary> public void sendReply(JSObject reply) { string strReply = reply.toJSON(); Logger.log("Sending reply: " + strReply, Logger.LogLevel.DEBUG); Console.WriteLine(strReply); } /// <summary> /// Returns a Position for the centre of the requested goal. /// </summary> protected Position getGoalCentre(GoalType goal) { double x = 0.0; if ((goal == GoalType.OUR_GOAL && this.playingDirection == DirectionType.LEFT) || (goal == GoalType.THEIR_GOAL && this.playingDirection == DirectionType.RIGHT)) { x = this.pitch.width; } double y = this.pitch.goalCentre; return new Position(x, y); } #endregion #region Abstract and virtual methods /// <summary> /// Default implementation for the CONFIGURE_ABLITIES request. /// </summary><remarks> /// We give all players an average level of ability in all areas. /// </remarks> protected virtual void processRequest_ConfigureAbilities(dynamic data) { // As a default, we give all players equal abilities... double totalKickingAbility = data.totalKickingAbility; double totalRunningAbility = data.totalRunningAbility; double totalBallControlAbility = data.totalBallControlAbility; double totalTacklingAbility = data.totalTacklingAbility; int numberOfPlayers = this.teamPlayers.Count + 1; // +1 for the goalkeeper // We create the reply... var reply = new JSObject(); reply.add("requestType", "CONFIGURE_ABILITIES"); // We give each player an average ability in all categories... var playerInfos = new List<JSObject>(); foreach(var playerNumber in this.allTeamPlayers.Keys) { var playerInfo = new JSObject(); playerInfo.add("playerNumber", playerNumber); playerInfo.add("kickingAbility", totalKickingAbility / numberOfPlayers); playerInfo.add("runningAbility", totalRunningAbility / numberOfPlayers); playerInfo.add("ballControlAbility", totalBallControlAbility / numberOfPlayers); playerInfo.add("tacklingAbility", totalTacklingAbility / numberOfPlayers); playerInfos.Add(playerInfo); } reply.add("players", playerInfos); sendReply(reply); } /// <summary> /// Default implementation for the kickoff request. /// </summary><remarks> /// Returns a minimal response (which results in default positions /// being allocated). /// </remarks> protected virtual void processRequest_Kickoff() { // We create the reply... var reply = new JSObject(); reply.add("requestType", "KICKOFF"); reply.add("players", new List<JSObject>()); sendReply(reply); } /// <summary> /// Default implementation for the PLAY request. /// </summary><remarks> /// We send back an empty list of actions, which means that /// the players do nothing. /// </remarks> protected virtual void processRequest_Play() { // We create the reply... var reply = new JSObject(); reply.add("requestType", "PLAY"); reply.add("actions", new List<JSObject>()); sendReply(reply); } /// <summary> /// Called after the TEAM_INFO event has been processed. /// (If the implementation in this class has been called.) /// </summary> protected virtual void onTeamInfoUpdated() { } /// <summary> /// Called after the GOAL event has been processed. /// (If the implementation in this class has been called.) /// </summary> protected virtual void onGoal() { } #endregion #region Private functions /// <summary> /// Called when we have received a new message from the game-engine. /// </summary> private void processMessage(string message) { Logger.log("Received message: " + message, Logger.LogLevel.DEBUG); // We decode the JSON message, and process it depending // on its message type... var data = Json.Decode(message); string messageType = data.messageType; switch(messageType) { case "EVENT": processEvent(data); break; case "REQUEST": processRequest(data); break; default: //throw new Exception("Unexpected messageType :" + messageType + " [" + message + "]"); Logger.log("Unexpected messageType :" + messageType + " [" + message + "]", Logger.LogLevel.DEBUG); var reply = new JSObject(); reply.add("requestType", "PLAY"); var actions = new List<JSObject>(); reply.add("actions", actions); sendReply(reply); break; } } /// <summary> /// Called when we receive an EVENT. /// </summary> private void processEvent(dynamic data) { string eventType = data.eventType; switch(eventType) { case "GAME_START": processEvent_GameStart(data); break; case "TEAM_INFO": processEvent_TeamInfo(data); break; case "START_OF_TURN": processEvent_StartOfTurn(data); break; case "GOAL": processEvent_Goal(data); break; case "KICKOFF": processEvent_Kickoff(data); break; case "HALF_TIME": processEvent_HalfTime(data); break; default: throw new Exception("Unexpected eventType: " + eventType); } } /// <summary> /// Called when we receive a REQUEST. /// </summary> private void processRequest(dynamic data) { string requestType = data.requestType; switch(requestType) { case "CONFIGURE_ABILITIES": processRequest_ConfigureAbilities(data); break; case "KICKOFF": processRequest_Kickoff(); break; case "PLAY": processRequest_Play(); break; default: throw new Exception("Unexpected requestType"); } } /// <summary> /// Called when we receive a GAME_START event. /// </summary> private void processEvent_GameStart(dynamic data) { this.pitch = data.pitch; this.gameLengthSeconds = data.gameLengthSeconds; } /// <summary> /// Called when we receive a TEAM_INFO event. /// </summary> private void processEvent_TeamInfo(dynamic data) { this.teamNumber = data.teamNumber; // We keep a collection of all the player-numbers in out team // as well as the information sorted by player vs. goalkeeper... foreach(var player in data.players) { int playerNumber = player.playerNumber; // We set up the all-players collection... this.allTeamPlayers[playerNumber] = new { }; // And the player / goalkeeper split... if(player.playerType == "P") { // This is a player... this.teamPlayers[playerNumber] = new { }; } else { // This is the goalkeeper... this.goalkeeperPlayerNumber = playerNumber; } } // We notify that team inf has been updated... onTeamInfoUpdated(); } /// <summary> /// Called when we receive a START_OF_TURN event. /// </summary> private void processEvent_StartOfTurn(dynamic data) { // We store the whole game-state... this.gameState = data; // And we split up parts of it. // The time... this.gameTimeSeconds = (double)data.game.currentTimeSeconds; // The ball... this.ball = data.ball; // The teams... if(this.teamNumber == 1) { // We are team 1... storeTeamInfo(data.team1); storeOpposingTeamInfo(data.team2); } else { // We are team 2... storeTeamInfo(data.team2); storeOpposingTeamInfo(data.team1); } if (this.gameTimeSeconds > this.gameLengthSeconds) { // Game is about to end log score to summary file string message; if (this.teamNumber == 1) { // We are team 1... message = String.Format("{0} {1} - {2} {3}", this.teamInfo.name, this.teamScore.ToString(), this.otherScore.ToString(), this.opposingTeamInfo.name); } else { // We are team 2... message = String.Format("{0} {1} - {2} {3}", this.opposingTeamInfo.name, this.otherScore.ToString(), this.teamScore.ToString(), this.teamInfo.Name); } var staticState1 = " {"; foreach (var player in this.gameState.team1.players) { var staticState = player.staticState; staticState1 += "(" + staticState.playerNumber + "," + staticState.ballControlAbility.ToString("F") + "," + staticState.kickingAbility.ToString("F") + "," + staticState.runningAbility.ToString("F") + "," + staticState.tacklingAbility.ToString("F") + ") "; } staticState1 += "} "; var staticState2 = " {"; foreach (var player in this.gameState.team2.players) { var staticState = player.staticState; staticState2 += "(" + staticState.playerNumber + "," + staticState.ballControlAbility.ToString("F") + "," + staticState.kickingAbility.ToString("F") + "," + staticState.runningAbility.ToString("F") + "," + staticState.tacklingAbility.ToString("F") + ") "; } staticState2 += "} "; message += staticState1 + staticState2; Logger.summary(message); } } /// <summary> /// Stores info about our team in our internal collections. /// </summary> private void storeTeamInfo(dynamic teamInfo) { // We store info about each player in the team in a map // by player-number, and we also split out the player info // from the goalkeeper info... foreach (var playerInfo in teamInfo.players) { var staticState = playerInfo.staticState; int playerNumber = staticState.playerNumber; // We store all the players in one collection... this.allTeamPlayers[playerNumber] = playerInfo; // And split by player vs. goalkeeper... string playerType = staticState.playerType; if(playerType == "P") { // This is a player... this.teamPlayers[playerNumber] = playerInfo; } else { // This is the goalkeeper... this.goalkeeper = playerInfo; } } } /// <summary> /// Stores info about the opposing team in our internal collections. /// </summary> private void storeOpposingTeamInfo(dynamic teamInfo) { // We store info about each player in the opposing team // in a map by player-number... foreach(var playerInfo in teamInfo.players) { int playerNumber = playerInfo.staticState.playerNumber; this.allOpposingTeamPlayers[playerNumber] = playerInfo; } } /// <summary> /// Called when a goal is scored. /// </summary> private void processEvent_Goal(dynamic data) { if (this.teamNumber == 1) { // We are team 1... this.teamScore = data.team1.score; this.otherScore = data.team2.score; } else { // We are team 2... this.teamScore = data.team2.score; this.otherScore = data.team1.score; } // We notify the derived class... onGoal(); } /// <summary> /// Called at half-time. /// </summary> private void processEvent_HalfTime(dynamic data) { } /// <summary> /// Called when we receive a KICKOFF event. /// </summary> private void processEvent_Kickoff(dynamic data) { // We store the team info (including playing direction and score)... if(this.teamNumber == 1) { // We are team 1... this.teamInfo = data.team1; this.opposingTeamInfo = data.team2; } else { // We are team 2... this.teamInfo = data.team2; this.opposingTeamInfo = data.team1; } // We find the direction we are playing... if(this.teamInfo.direction == "LEFT") { this.playingDirection = DirectionType.LEFT; } else { this.playingDirection = DirectionType.RIGHT; } // Are we the team kicking off? this.weAreKickingOff = (data.teamKickingOff == this.teamNumber); } #endregion #region Protected data // The dimensions of the pitch... protected dynamic pitch = new { }; // The lngth of the game in seconds... protected int gameLengthSeconds = -1; // Our team number... protected int teamNumber = -1; protected int teamScore = 0; protected int otherScore = 0; // The collection of all players in our team... // This is a map of player-number to information about the player. protected Dictionary<int, dynamic> allTeamPlayers = new Dictionary<int, dynamic>(); // The collection of players, not including the goalkeeper. // This is a map of player-number to information about the player. protected Dictionary<int, dynamic> teamPlayers = new Dictionary<int, dynamic>(); // Information about the goalkeeper... protected int goalkeeperPlayerNumber = -1; protected dynamic goalkeeper = new { }; // The collection of all players in the opposing team... // This is a map of player-number to information about the player. protected Dictionary<int, dynamic> allOpposingTeamPlayers = new Dictionary<int, dynamic>(); // The game start at the start of each turn. // Some of this data is split up into the 'ball' info and the // 'players' info... protected dynamic gameState = new { }; // Information about the ball, including its position, direction and speed... protected dynamic ball = new { }; // Info about our team. Includes the score and the direction of play... protected dynamic teamInfo = new { }; // Info about the opposing team. Includes the score and the direction of play... protected dynamic opposingTeamInfo = new { }; // True if we are kicking off. // (Only valid during a KICKOFF event and request.) protected bool weAreKickingOff = false; // The direction we are playing... protected enum DirectionType { // We don't yet know the playing direction... DONT_KNOW, // We are shooting at the left goal... LEFT, // We are shooting at the right goal... RIGHT } protected DirectionType playingDirection; // An enum for the two goals... protected enum GoalType { OUR_GOAL, THEIR_GOAL } // The current 'game-time' in seconds from the start of the match... protected double gameTimeSeconds; #endregion } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MindTouch.Deki.Search { internal class QueryTermParser { //--- Class Fields --- private static readonly HashSet<string> _knownFields = new HashSet<string> { "author", "comments", "content", "description", "filename", "id.file", "id.page", "id.parent", "namespace", "path", "path.parent", "path.title", "property", "rating.count", "rating.score", "tag", "title", "title.page", "title.parent", "type", }; private static readonly HashSet<string> _reservedWords = new HashSet<string>() { "AND", "NOT", "OR" }; //--- Fields --- private readonly HashSet<QueryTerm> _terms = new HashSet<QueryTerm>(); private readonly StringBuilder _escapedTerm = new StringBuilder(); private readonly StringBuilder _normalizedTerm = new StringBuilder(); private string _escapedField; private string _normalizedField; private bool _abortOnLuceneConstruct; private bool _inQuote; private bool _escaping; private char _leadingOperator; //--- Properties --- private bool IsTermStart { get { return _escapedTerm.Length == 0; } } private bool HasFieldPrefix { get { return !string.IsNullOrEmpty(_escapedField); } } //--- Methods --- // Note (arnec): this call is not threadsafe, since QueryTermParser keeps state in the instance, which is why // it is not used by itself but embedded in SearchQueryParser public IEnumerable<QueryTerm> GetQueryTerms(string rawQuery, bool abortOnLuceneConstruct) { _abortOnLuceneConstruct = abortOnLuceneConstruct; _inQuote = _escaping = false; _escapedTerm.Length = 0; _normalizedTerm.Length = 0; _leadingOperator = char.MinValue; _terms.Clear(); for(var i = 0; i < rawQuery.Length; i++) { var c = rawQuery[i]; if(_escaping) { _escaping = false; } else { switch(c) { // quote case '"': if(!_inQuote) { if(IsTermStart) { // start of quoted term _inQuote = true; continue; } // quote in middle of unquoted term, throw throw new FormatException(string.Format("Quote in middle of unquoted term: {0}", _escapedTerm)); } if(i < rawQuery.Length - 1) { i++; var c2 = rawQuery[i]; if(!char.IsWhiteSpace(c2)) { if(_abortOnLuceneConstruct) { // might be legal in lucene, i.e. term followed by range, boost, etc. return null; } // badly ended quoted term throw new FormatException(string.Format("Unescaped quote in middle of quoted term: \"{0}", _escapedTerm)); } } if(!BuildTerm()) { return null; } continue; // possible inclusion or exclusion operator case '+': case '-': if(_inQuote) { EscapeCharacter(); break; } if(_leadingOperator == char.MinValue && IsTermStart && !HasFieldPrefix) { // capture operator _leadingOperator = c; continue; } EscapeCharacter(); break; // special characters case '!': case '(': case ')': case '{': case '}': case '[': case ']': case '^': case '~': if(!_inQuote && abortOnLuceneConstruct) { return null; } EscapeCharacter(); break; // wild cards case '*': case '?': if(_inQuote) { EscapeCharacter(); } break; // possible field separator case ':': if(_inQuote) { EscapeCharacter(); } else if(HasFieldPrefix) { EscapeCharacter(); } else if(IsTermStart) { if(abortOnLuceneConstruct) { return null; } EscapeCharacter(); } else { _escapedField = _escapedTerm.ToString(); _normalizedField = _normalizedTerm.ToString(); if(_knownFields.Contains(_escapedField) || _escapedField.Contains("#")) { _escapedTerm.Length = 0; _normalizedTerm.Length = 0; continue; } _escapedField = _normalizedField = null; EscapeCharacter(); } break; // possible escaped sequence case '\\': _escapedTerm.Append('\\'); _escaping = true; continue; // everything else default: if(!_inQuote && char.IsWhiteSpace(c)) { if(!BuildTerm()) { return null; } continue; } if(_inQuote && char.IsWhiteSpace(c)) { EscapeCharacter(); } break; } } _escapedTerm.Append(c); _normalizedTerm.Append(c); } if(_inQuote) { throw new FormatException(string.Format("Unclosed quote on quoted term term: \"{0}", _escapedTerm)); } return !BuildTerm() ? null : _terms.ToArray(); } private void EscapeCharacter() { _escapedTerm.Append('\\'); } private bool BuildTerm() { if(_escapedTerm.Length != 0) { if(_escaping) { throw new FormatException(string.Format("Incomplete escape sequence at end of term: {0}", _escapedTerm)); } var escaped = HasFieldPrefix ? _escapedField + ":" + _escapedTerm : _escapedTerm.ToString(); var normalized = HasFieldPrefix ? _normalizedField + ":" + _normalizedTerm : _normalizedTerm.ToString(); if(!_inQuote && _reservedWords.Contains(escaped)) { if(_abortOnLuceneConstruct) { return false; } escaped = "\"" + escaped + "\""; } switch(_leadingOperator) { case '-': escaped = "-" + escaped; normalized = "-" + normalized; break; case '+': escaped = "+" + escaped; break; } _terms.Add(new QueryTerm(escaped, normalized, HasFieldPrefix, _inQuote)); } _escapedField = _normalizedField = null; _normalizedTerm.Length = 0; _escapedTerm.Length = 0; _inQuote = false; _leadingOperator = char.MinValue; return true; } } }
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2020 // // 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. // This file was automatically generated and should not be edited directly. using System; namespace SharpVk.Khronos { /// <summary> /// /// </summary> public static class QueueExtensions { /// <summary> /// Queue an image for presentation. /// </summary> /// <param name="extendedHandle"> /// The Queue handle to extend. /// </param> /// <param name="waitSemaphores"> /// </param> /// <param name="swapchains"> /// </param> /// <param name="imageIndices"> /// </param> /// <param name="results"> /// </param> /// <param name="displayPresentInfoKhr"> /// Extension struct /// </param> /// <param name="presentRegionsKhr"> /// Extension struct /// </param> /// <param name="deviceGroupPresentInfoKhr"> /// Extension struct /// </param> /// <param name="presentTimesInfoGoogle"> /// Extension struct /// </param> /// <param name="presentFrameTokenGgp"> /// Extension struct /// </param> public static unsafe Result Present(this SharpVk.Queue extendedHandle, ArrayProxy<SharpVk.Semaphore>? waitSemaphores, ArrayProxy<SharpVk.Khronos.Swapchain>? swapchains, ArrayProxy<uint>? imageIndices, ArrayProxy<SharpVk.Result>? results = null, SharpVk.Khronos.DisplayPresentInfo? displayPresentInfoKhr = null, SharpVk.Khronos.PresentRegions? presentRegionsKhr = null, SharpVk.Khronos.DeviceGroupPresentInfo? deviceGroupPresentInfoKhr = null, SharpVk.Google.PresentTimesInfo? presentTimesInfoGoogle = null, SharpVk.Ggp.PresentFrameToken? presentFrameTokenGgp = null) { try { Result result = default(Result); CommandCache commandCache = default(CommandCache); SharpVk.Interop.Khronos.PresentInfo* marshalledPresentInfo = default(SharpVk.Interop.Khronos.PresentInfo*); void* vkPresentInfoKHRNextPointer = default(void*); if (displayPresentInfoKhr != null) { SharpVk.Interop.Khronos.DisplayPresentInfo* extensionPointer = default(SharpVk.Interop.Khronos.DisplayPresentInfo*); extensionPointer = (SharpVk.Interop.Khronos.DisplayPresentInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Khronos.DisplayPresentInfo>()); displayPresentInfoKhr.Value.MarshalTo(extensionPointer); extensionPointer->Next = vkPresentInfoKHRNextPointer; vkPresentInfoKHRNextPointer = extensionPointer; } if (presentRegionsKhr != null) { SharpVk.Interop.Khronos.PresentRegions* extensionPointer = default(SharpVk.Interop.Khronos.PresentRegions*); extensionPointer = (SharpVk.Interop.Khronos.PresentRegions*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Khronos.PresentRegions>()); presentRegionsKhr.Value.MarshalTo(extensionPointer); extensionPointer->Next = vkPresentInfoKHRNextPointer; vkPresentInfoKHRNextPointer = extensionPointer; } if (deviceGroupPresentInfoKhr != null) { SharpVk.Interop.Khronos.DeviceGroupPresentInfo* extensionPointer = default(SharpVk.Interop.Khronos.DeviceGroupPresentInfo*); extensionPointer = (SharpVk.Interop.Khronos.DeviceGroupPresentInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Khronos.DeviceGroupPresentInfo>()); deviceGroupPresentInfoKhr.Value.MarshalTo(extensionPointer); extensionPointer->Next = vkPresentInfoKHRNextPointer; vkPresentInfoKHRNextPointer = extensionPointer; } if (presentTimesInfoGoogle != null) { SharpVk.Interop.Google.PresentTimesInfo* extensionPointer = default(SharpVk.Interop.Google.PresentTimesInfo*); extensionPointer = (SharpVk.Interop.Google.PresentTimesInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Google.PresentTimesInfo>()); presentTimesInfoGoogle.Value.MarshalTo(extensionPointer); extensionPointer->Next = vkPresentInfoKHRNextPointer; vkPresentInfoKHRNextPointer = extensionPointer; } if (presentFrameTokenGgp != null) { SharpVk.Interop.Ggp.PresentFrameToken* extensionPointer = default(SharpVk.Interop.Ggp.PresentFrameToken*); extensionPointer = (SharpVk.Interop.Ggp.PresentFrameToken*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Ggp.PresentFrameToken>()); presentFrameTokenGgp.Value.MarshalTo(extensionPointer); extensionPointer->Next = vkPresentInfoKHRNextPointer; vkPresentInfoKHRNextPointer = extensionPointer; } commandCache = extendedHandle.commandCache; marshalledPresentInfo = (SharpVk.Interop.Khronos.PresentInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Khronos.PresentInfo>()); marshalledPresentInfo->SType = StructureType.PresentInfo; marshalledPresentInfo->Next = vkPresentInfoKHRNextPointer; marshalledPresentInfo->WaitSemaphoreCount = (uint)(Interop.HeapUtil.GetLength(waitSemaphores)); if (waitSemaphores.IsNull()) { marshalledPresentInfo->WaitSemaphores = null; } else { if (waitSemaphores.Value.Contents == ProxyContents.Single) { marshalledPresentInfo->WaitSemaphores = (SharpVk.Interop.Semaphore*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Semaphore>()); *(SharpVk.Interop.Semaphore*)(marshalledPresentInfo->WaitSemaphores) = waitSemaphores.Value.GetSingleValue()?.handle ?? default(SharpVk.Interop.Semaphore); } else { var fieldPointer = (SharpVk.Interop.Semaphore*)(Interop.HeapUtil.AllocateAndClear<SharpVk.Interop.Semaphore>(Interop.HeapUtil.GetLength(waitSemaphores.Value)).ToPointer()); for(int index = 0; index < (uint)(Interop.HeapUtil.GetLength(waitSemaphores.Value)); index++) { fieldPointer[index] = waitSemaphores.Value[index]?.handle ?? default(SharpVk.Interop.Semaphore); } marshalledPresentInfo->WaitSemaphores = fieldPointer; } } marshalledPresentInfo->SwapchainCount = (uint)(Interop.HeapUtil.GetLength(swapchains)); if (swapchains.IsNull()) { marshalledPresentInfo->Swapchains = null; } else { if (swapchains.Value.Contents == ProxyContents.Single) { marshalledPresentInfo->Swapchains = (SharpVk.Interop.Khronos.Swapchain*)(Interop.HeapUtil.Allocate<SharpVk.Interop.Khronos.Swapchain>()); *(SharpVk.Interop.Khronos.Swapchain*)(marshalledPresentInfo->Swapchains) = swapchains.Value.GetSingleValue()?.handle ?? default(SharpVk.Interop.Khronos.Swapchain); } else { var fieldPointer = (SharpVk.Interop.Khronos.Swapchain*)(Interop.HeapUtil.AllocateAndClear<SharpVk.Interop.Khronos.Swapchain>(Interop.HeapUtil.GetLength(swapchains.Value)).ToPointer()); for(int index = 0; index < (uint)(Interop.HeapUtil.GetLength(swapchains.Value)); index++) { fieldPointer[index] = swapchains.Value[index]?.handle ?? default(SharpVk.Interop.Khronos.Swapchain); } marshalledPresentInfo->Swapchains = fieldPointer; } } if (imageIndices.IsNull()) { marshalledPresentInfo->ImageIndices = null; } else { if (imageIndices.Value.Contents == ProxyContents.Single) { marshalledPresentInfo->ImageIndices = (uint*)(Interop.HeapUtil.Allocate<uint>()); *(uint*)(marshalledPresentInfo->ImageIndices) = imageIndices.Value.GetSingleValue(); } else { var fieldPointer = (uint*)(Interop.HeapUtil.AllocateAndClear<uint>(Interop.HeapUtil.GetLength(imageIndices.Value)).ToPointer()); for(int index = 0; index < (uint)(Interop.HeapUtil.GetLength(imageIndices.Value)); index++) { fieldPointer[index] = imageIndices.Value[index]; } marshalledPresentInfo->ImageIndices = fieldPointer; } } if (results.IsNull()) { marshalledPresentInfo->Results = null; } else { if (results.Value.Contents == ProxyContents.Single) { marshalledPresentInfo->Results = (SharpVk.Result*)(Interop.HeapUtil.Allocate<SharpVk.Result>()); *(SharpVk.Result*)(marshalledPresentInfo->Results) = results.Value.GetSingleValue(); } else { var fieldPointer = (SharpVk.Result*)(Interop.HeapUtil.AllocateAndClear<SharpVk.Result>(Interop.HeapUtil.GetLength(results.Value)).ToPointer()); for(int index = 0; index < (uint)(Interop.HeapUtil.GetLength(results.Value)); index++) { fieldPointer[index] = results.Value[index]; } marshalledPresentInfo->Results = fieldPointer; } } SharpVk.Interop.Khronos.VkQueuePresentDelegate commandDelegate = commandCache.Cache.vkQueuePresentKHR; result = commandDelegate(extendedHandle.handle, marshalledPresentInfo); if (SharpVkException.IsError(result)) { throw SharpVkException.Create(result); } return result; } finally { Interop.HeapUtil.FreeAll(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { /// <summary> /// A synthesized instance method used for binding /// expressions outside of a method - specifically, binding /// DebuggerDisplayAttribute expressions. /// </summary> internal sealed class SynthesizedContextMethodSymbol : SynthesizedInstanceMethodSymbol { private readonly NamedTypeSymbol _container; public SynthesizedContextMethodSymbol(NamedTypeSymbol container) { _container = container; } public override int Arity { get { return 0; } } public override Symbol AssociatedSymbol { get { return null; } } public override Symbol ContainingSymbol { get { return _container; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override bool HidesBaseMethodsByName { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsAsync { get { return false; } } public override bool IsExtensionMethod { get { return false; } } public override bool IsExtern { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsSealed { get { return true; } } public override bool IsStatic { get { return false; } } public override bool IsVararg { get { return false; } } public override bool IsVirtual { get { return false; } } public override ImmutableArray<Location> Locations { get { throw ExceptionUtilities.Unreachable; } } public override MethodKind MethodKind { get { return MethodKind.Ordinary; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return ImmutableArray<ParameterSymbol>.Empty; } } public override bool ReturnsVoid { get { return true; } } internal override RefKind RefKind { get { return RefKind.None; } } public override TypeSymbol ReturnType { get { throw ExceptionUtilities.Unreachable; } } public override ImmutableArray<CustomModifier> ReturnTypeCustomModifiers { get { throw ExceptionUtilities.Unreachable; } } internal override ushort CountOfCustomModifiersPrecedingByRef { get { throw ExceptionUtilities.Unreachable; } } public override ImmutableArray<TypeSymbol> TypeArguments { get { return ImmutableArray<TypeSymbol>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } internal override Microsoft.Cci.CallingConvention CallingConvention { get { throw ExceptionUtilities.Unreachable; } } internal override bool GenerateDebugInfo { get { throw ExceptionUtilities.Unreachable; } } internal override bool HasDeclarativeSecurity { get { throw ExceptionUtilities.Unreachable; } } internal override bool HasSpecialName { get { throw ExceptionUtilities.Unreachable; } } internal override MethodImplAttributes ImplementationAttributes { get { throw ExceptionUtilities.Unreachable; } } internal override bool RequiresSecurityObject { get { throw ExceptionUtilities.Unreachable; } } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { throw ExceptionUtilities.Unreachable; } } public override DllImportData GetDllImportData() { throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { throw ExceptionUtilities.Unreachable; } internal override IEnumerable<Microsoft.Cci.SecurityAttribute> GetSecurityInformation() { throw ExceptionUtilities.Unreachable; } internal override bool IsMetadataFinal { get { return false; } } internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { throw ExceptionUtilities.Unreachable; } internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { throw ExceptionUtilities.Unreachable; } } }
#pragma warning disable SA1633 // File should have header - This is an imported file, // original header with license shall remain the same /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /* * The following part was imported from https://gitlab.freedesktop.org/uchardet/uchardet * The implementation of this feature was originally done on https://gitlab.freedesktop.org/uchardet/uchardet/blob/master/src/LangModels/LangSwedishModel.cpp * and adjusted to language specific support. */ namespace UtfUnknown.Core.Models.SingleByte.Swedish; internal class Iso_8859_15_SwedishModel : SwedishModel { // Generated by BuildLangModel.py // On: 2016-09-28 22:29:21.480940 // Character Mapping Table: // ILL: illegal character. // CTR: control character specific to the charset. // RET: carriage/return. // SYM: symbol (punctuation) that does not belong to word. // NUM: 0 - 9. // Other characters are ordered by probabilities // (0 is the most common character in the language). // Orders are generic to a language. So the codepoint with order X in // CHARSET1 maps to the same character as the codepoint with the same // order X in CHARSET2 for the same language. // As such, it is possible to get missing order. For instance the // ligature of 'o' and 'e' exists in ISO-8859-15 but not in ISO-8859-1 // even though they are both used for French. Same for the euro sign. private static byte[] CHAR_TO_ORDER_MAP = { CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, RET, CTR, CTR, RET, CTR, CTR, /* 0X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 1X */ SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, SYM, /* 2X */ NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, NUM, SYM, SYM, SYM, SYM, SYM, SYM, /* 3X */ SYM, 0, 22, 20, 9, 1, 14, 12, 18, 6, 23, 10, 7, 11, 3, 8, /* 4X */ 15, 30, 2, 5, 4, 16, 13, 26, 25, 24, 27, SYM, SYM, SYM, SYM, SYM, /* 5X */ SYM, 0, 22, 20, 9, 1, 14, 12, 18, 6, 23, 10, 7, 11, 3, 8, /* 6X */ 15, 30, 2, 5, 4, 16, 13, 26, 25, 24, 27, SYM, SYM, SYM, SYM, CTR, /* 7X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 8X */ CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, CTR, /* 9X */ SYM, SYM, SYM, SYM, SYM, SYM, 213, SYM, 214, SYM, SYM, SYM, SYM, SYM, SYM, SYM, /* AX */ SYM, SYM, SYM, SYM, 215, 216, SYM, SYM, 217, SYM, SYM, SYM, 218, 219, 220, SYM, /* BX */ 221, 44, 222, 223, 17, 19, 38, 40, 32, 28, 45, 224, 225, 226, 47, 227, /* CX */ 228, 229, 230, 231, 35, 232, 21, SYM, 37, 233, 234, 235, 31, 236, 237, 238, /* DX */ 239, 44, 240, 241, 17, 19, 38, 40, 32, 28, 45, 242, 243, 244, 47, 245, /* EX */ 246, 247, 248, 249, 35, 249, 21, SYM, 37, 249, 249, 249, 31, 249, 249, 249 /* FX */ }; /*X0 X1 X2 X3 X4 X5 X6 X7 X8 X9 XA XB XC XD XE XF */ public Iso_8859_15_SwedishModel() : base( CHAR_TO_ORDER_MAP, CodepageName.ISO_8859_15) { } }
using AjaxControlToolkit.Design; using System; using System.ComponentModel; using System.Drawing; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// PopupControl is an ASP.NET AJAX extender that can be attached to any control to open a popup /// window that displays additional content. This popup window will probably be interactive and /// located within an ASP.NET AJAX UpdatePanel. So, it will perform complex server-based processing /// (including postbacks) without affecting the rest of the page. The popup window can contain any /// content including ASP.NET server controls, HTML elements, etc. Once work of the popup window is /// done, a simple server-side call dismisses it and triggers any relevant script on the client to /// run and update the page dynamically. /// </summary> [ClientScriptResource("Sys.Extended.UI.PopupControlBehavior", Constants.PopupControlName)] [RequiredScript(typeof(PopupExtender))] [RequiredScript(typeof(CommonToolkitScripts))] [TargetControlType(typeof(WebControl))] [TargetControlType(typeof(HtmlControl))] [Designer(typeof(PopupControlExtenderDesigner))] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.PopupControlName + Constants.IconPostfix)] public class PopupControlExtender : DynamicPopulateExtenderControlBase { bool _shouldClose; string _closeString; Page _proxyForCurrentPopup; EventHandler _pagePreRenderHandler; public PopupControlExtender() { } // Constructor with a page - Used to initialize proxy controls only. private PopupControlExtender(Page page) { _proxyForCurrentPopup = page; // In this case, the control acts as a proxy // It is not actually added to control collections and does not participate in the page cycle // Attach the Page.PreRender event _pagePreRenderHandler = new EventHandler(Page_PreRender); _proxyForCurrentPopup.PreRender += _pagePreRenderHandler; } /// <summary> /// Returns a proxy PopupControlExtender representing the currently active popup on the specified page /// </summary> /// <remarks> /// Only the Cancel and Commit methods should be called on the proxy /// </remarks> /// <param name="page" type="Page">Page</param> /// <returns>Popup control extender</returns> public static PopupControlExtender GetProxyForCurrentPopup(Page page) { var popupControlExtender = new PopupControlExtender(page); return popupControlExtender; } /// <summary> /// Cancels the popup control and hides it abandoning results /// </summary> public void Cancel() { // It is possible for Cancel() to be called numerous times during the same postback so we just remember the desired state // Pass the magic cancel string as the result _closeString = "$$CANCEL$$"; _shouldClose = true; } /// <summary> /// Commits the popup control and hides it applying the specified result /// </summary> /// <param name="result" type="String">Result</param> public void Commit(string result) { // It is possible for Commit() to be called numerous times during the same postback so we just remember the desired state _closeString = result; _shouldClose = true; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Attach the Page.PreRender event - Make sure we hook up only once if(_pagePreRenderHandler == null) { _pagePreRenderHandler = new EventHandler(Page_PreRender); Page.PreRender += _pagePreRenderHandler; } } protected void Page_PreRender(object sender, EventArgs e) { // If Cancel()/Commit() were called, close the popup now if(_shouldClose) Close(_closeString); } // Closes the popup control, applying the specified result or abandoning it void Close(string result) { if(_proxyForCurrentPopup == null) { // Normal call - Simply register the relevant data item for the TargetControl ScriptManager.GetCurrent(Page).RegisterDataItem(TargetControl, result); } else { // Proxy call - Add a LiteralControl to pass the information down to the interested PopupControlExtender var literalControl = new LiteralControl(); literalControl.ID = "_PopupControl_Proxy_ID_"; _proxyForCurrentPopup.Controls.Add(literalControl); ScriptManager.GetCurrent(_proxyForCurrentPopup).RegisterDataItem(literalControl, result); } } /// <summary> /// The ID of the extender control /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [ClientPropertyName("extenderControlID")] public string ExtenderControlID { get { return GetPropertyValue("ExtenderControlID", String.Empty); } set { SetPropertyValue("ExtenderControlID", value); } } /// <summary> /// The ID of the control to display /// </summary> [ExtenderControlProperty] [IDReferenceProperty(typeof(WebControl))] [RequiredProperty] [DefaultValue("")] [ClientPropertyName("popupControlID")] public string PopupControlID { get { return GetPropertyValue("PopupControlID", String.Empty); } set { SetPropertyValue("PopupControlID", value); } } /// <summary> /// Optional setting specifying a property of the control being extended that /// should be set with the result of the popup /// </summary> /// <remarks> /// If the property value is missing (an empty line), the default "value" property will be used /// </remarks> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("commitProperty")] public string CommitProperty { get { return GetPropertyValue("CommitProperty", String.Empty); } set { SetPropertyValue("CommitProperty", value); } } /// <summary> /// Optional setting specifying an additional script to run after the result of the popup is set /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("commitScript")] public string CommitScript { get { return GetPropertyValue("CommitScript", String.Empty); } set { SetPropertyValue("CommitScript", value); } } /// <summary> /// Optional setting specifying where the popup should be positioned relative to the target /// control (Left, Right, Top, Bottom, or Center) /// </summary> [ExtenderControlProperty] [DefaultValue(PopupControlPopupPosition.Center)] [ClientPropertyName("position")] public PopupControlPopupPosition Position { get { return GetPropertyValue("Position", PopupControlPopupPosition.Center); } set { SetPropertyValue("Position", value); } } /// <summary> /// The number of pixels to offset the Popup from its default position, as specified by Position /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("offsetX")] public int OffsetX { get { return GetPropertyValue("OffsetX", 0); } set { SetPropertyValue("OffsetX", value); } } /// <summary> /// The number of pixels to offset the Popup from its default position, as specified by Position /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("offsetY")] public int OffsetY { get { return GetPropertyValue("OffsetY", 0); } set { SetPropertyValue("OffsetY", value); } } /// <summary> /// OnShow animation will be played each time the popup is displayed. The /// popup will be positioned correctly but hidden. Animation can be used /// to display the popup with other visual effects /// </summary> [ExtenderControlProperty] [ClientPropertyName("onShow")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnShow { get { return GetAnimation(ref _onShow, "OnShow"); } set { SetAnimation(ref _onShow, "OnShow", value); } } Animation _onShow; /// <summary> /// OnHide animation will be played each time the popup is hidden /// </summary> [ExtenderControlProperty] [ClientPropertyName("onHide")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnHide { get { return GetAnimation(ref _onHide, "OnHide"); } set { SetAnimation(ref _onHide, "OnHide", value); } } Animation _onHide; // Convert server IDs into ClientIDs for animations protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); ResolveControlIDs(_onShow); ResolveControlIDs(_onHide); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using DotVVM.Framework.Controls; using DotVVM.Framework.Utils; using System.Diagnostics; using DotVVM.Framework.Compilation; using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Compilation.ControlTree; using DotVVM.Framework.Compilation.ControlTree.Resolved; using Newtonsoft.Json; using System.Diagnostics.CodeAnalysis; using System.Collections.Immutable; using DotVVM.Framework.Runtime; namespace DotVVM.Framework.Binding { /// <summary> /// Represents a property of DotVVM controls. /// </summary> [DebuggerDisplay("{FullName}")] public class DotvvmProperty : IPropertyDescriptor { /// <summary> /// Gets or sets the name of the property. /// </summary> public string Name { get; protected set; } [JsonIgnore] ITypeDescriptor IControlAttributeDescriptor.DeclaringType => new ResolvedTypeDescriptor(DeclaringType); [JsonIgnore] ITypeDescriptor IControlAttributeDescriptor.PropertyType => new ResolvedTypeDescriptor(PropertyType); /// <summary> /// Gets the default value of the property. /// </summary> public object? DefaultValue { get; protected set; } /// <summary> /// Gets the type of the property. /// </summary> public Type PropertyType { get; protected set; } /// <summary> /// Gets the type of the class where the property is registered. /// </summary> public Type DeclaringType { get; protected set; } /// <summary> /// Gets whether the value can be inherited from the parent controls. /// </summary> public bool IsValueInherited { get; protected set; } /// <summary> /// Gets or sets the Reflection property information. /// </summary> [JsonIgnore] public PropertyInfo? PropertyInfo { get; private set; } /// <summary> /// Provider of custom attributes for this property. /// </summary> internal ICustomAttributeProvider AttributeProvider { get; set; } /// <summary> /// Gets or sets the markup options. /// </summary> public MarkupOptionsAttribute MarkupOptions { get; set; } /// <summary> /// Determines if property type inherits from IBinding /// </summary> public bool IsBindingProperty { get; protected set; } /// <summary> /// Gets the full name of the descriptor. /// </summary> public string DescriptorFullName { get { return DeclaringType.FullName + "." + Name + "Property"; } } /// <summary> /// Gets the full name of the property. /// </summary> public string FullName { get { return DeclaringType.Name + "." + Name; } } [JsonIgnore] public DataContextChangeAttribute[] DataContextChangeAttributes { get; protected set; } [JsonIgnore] public DataContextStackManipulationAttribute? DataContextManipulationAttribute { get; protected set; } public ObsoleteAttribute? ObsoleteAttribute { get; protected set; } /// <summary> The capability which declared this property. When the property is declared by an capability, it can only be used by this capability. </summary> public DotvvmCapabilityProperty? OwningCapability { get; internal set; } /// <summary> The capabilities which use this property. </summary> public ImmutableArray<DotvvmCapabilityProperty> UsedInCapabilities { get; internal set; } = ImmutableArray<DotvvmCapabilityProperty>.Empty; internal void AddUsedInCapability(DotvvmCapabilityProperty? p) { if (p is object) lock(this) { UsedInCapabilities = UsedInCapabilities.Add(p); } } /// <summary> /// Prevents a default instance of the <see cref="DotvvmProperty"/> class from being created. /// </summary> #pragma warning disable CS8618 // DotvvmProperty is usually initialized by InitializeProperty internal DotvvmProperty() { } internal DotvvmProperty( #pragma warning restore CS8618 string name, Type type, Type declaringType, object? defaultValue, bool isValueInherited, ICustomAttributeProvider attributeProvider ) { this.Name = name; this.PropertyType = type; this.DeclaringType = declaringType; this.DefaultValue = defaultValue; this.IsValueInherited = isValueInherited; this.AttributeProvider = attributeProvider; InitializeProperty(this); } public T[] GetAttributes<T>() { if (PropertyInfo == null) return AttributeProvider.GetCustomAttributes<T>(); if (object.ReferenceEquals(AttributeProvider, PropertyInfo)) return PropertyInfo.GetCustomAttributes<T>(); var attrA = AttributeProvider.GetCustomAttributes<T>(); var attrB = PropertyInfo.GetCustomAttributes<T>(); if (attrA.Length == 0) return attrB; if (attrB.Length == 0) return attrA; return attrA.Concat(attrB).ToArray(); } public bool IsOwnedByCapability(Type capability) => (this is DotvvmCapabilityProperty && this.PropertyType == capability) || OwningCapability?.IsOwnedByCapability(capability) == true; public bool IsOwnedByCapability(DotvvmCapabilityProperty capability) => this == capability || OwningCapability?.IsOwnedByCapability(capability) == true; private object? GetInheritedValue(DotvvmBindableObject control) { for (var p = control.Parent; p is not null; p = p.Parent) { if (p.properties.TryGet(this, out var v)) return v; } return DefaultValue; } /// <summary> /// Gets the value of the property. /// </summary> public virtual object? GetValue(DotvvmBindableObject control, bool inherit = true) { if (control.properties.TryGet(this, out var value)) { return value; } if (IsValueInherited & inherit) { return GetInheritedValue(control); } return DefaultValue; } /// <summary> /// Gets whether the value of the property is set /// </summary> public virtual bool IsSet(DotvvmBindableObject control, bool inherit = true) { if (control.properties.Contains(this)) { return true; } if (IsValueInherited && inherit && control.Parent != null) { return IsSet(control.Parent); } return false; } /// <summary> /// Sets the value of the property. /// </summary> public virtual void SetValue(DotvvmBindableObject control, object? value) { control.properties.Set(this, value); } /// <summary> /// Registers the specified DotVVM property. /// </summary> public static DotvvmProperty Register<TPropertyType, TDeclaringType>(Expression<Func<DotvvmProperty?>> fieldAccessor, [AllowNull] TPropertyType defaultValue = default(TPropertyType), bool isValueInherited = false) { var field = ReflectionUtils.GetMemberFromExpression(fieldAccessor) as FieldInfo; if (field == null || !field.IsStatic) throw new ArgumentException("The expression should be simple static field access", nameof(fieldAccessor)); if (!field.Name.EndsWith("Property", StringComparison.Ordinal)) throw new ArgumentException($"DotVVM property backing field's '{field.Name}' name should end with 'Property'"); return Register<TPropertyType, TDeclaringType>(field.Name.Remove(field.Name.Length - "Property".Length).DotvvmInternString(trySystemIntern: true), defaultValue, isValueInherited); } /// <summary> /// Registers the specified DotVVM property. /// </summary> public static DotvvmProperty Register<TPropertyType, TDeclaringType>(Expression<Func<TDeclaringType, object?>> propertyAccessor, [AllowNull] TPropertyType defaultValue = default(TPropertyType), bool isValueInherited = false) { var property = ReflectionUtils.GetMemberFromExpression(propertyAccessor) as PropertyInfo; if (property == null) throw new ArgumentException("The expression should be simple property access", nameof(propertyAccessor)); return Register<TPropertyType, TDeclaringType>(property.Name.DotvvmInternString(trySystemIntern: true), defaultValue, isValueInherited); } /// <summary> /// Registers the specified DotVVM property. /// </summary> public static DotvvmProperty Register<TPropertyType, TDeclaringType>(string propertyName, [AllowNull] TPropertyType defaultValue = default(TPropertyType), bool isValueInherited = false, DotvvmProperty? property = null) { var field = typeof(TDeclaringType).GetField(propertyName + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) throw new ArgumentException($"'{typeof(TDeclaringType).Name}' does not contain static field '{propertyName}Property'."); return Register(propertyName, typeof(TPropertyType), typeof(TDeclaringType), BoxingUtils.BoxGeneric(defaultValue), isValueInherited, property, field); } public static DotvvmProperty Register(string propertyName, Type propertyType, Type declaringType, object? defaultValue, bool isValueInherited, DotvvmProperty? property, ICustomAttributeProvider attributeProvider, bool throwOnDuplicateRegistration = true) { if (property == null) property = new DotvvmProperty(); property.Name = propertyName; property.IsValueInherited = isValueInherited; property.DeclaringType = declaringType; property.PropertyType = propertyType; property.DefaultValue = defaultValue; property.AttributeProvider = attributeProvider; return Register(property, throwOnDuplicateRegistration); } public record PropertyAlreadyExistsException( DotvvmProperty OldProperty, DotvvmProperty NewProperty ) : DotvvmExceptionBase(RelatedProperty: OldProperty) { public override string Message { get { var capabilityHelp = OldProperty.OwningCapability is {} ownerOld ? $" The existing property is declared by capability {ownerOld.Name}." : ""; var capabilityHelpNew = NewProperty.OwningCapability is {} ownerNew ? $" The new property is declared by capability {ownerNew.Name}." : ""; var message = NewProperty is DotvvmCapabilityProperty ? $"Capability {NewProperty.Name} conflicts with existing property. Consider giving the capability a different name." : $"DotVVM property is already registered: {NewProperty.FullName}"; return message + capabilityHelp + capabilityHelpNew; } } } internal static DotvvmProperty Register(DotvvmProperty property, bool throwOnDuplicateRegistration = true) { InitializeProperty(property); var key = (property.DeclaringType, property.Name); if (!registeredProperties.TryAdd(key, property)) { if (throwOnDuplicateRegistration) throw new PropertyAlreadyExistsException(registeredProperties[key], property); else property = registeredProperties[key]; } return property; } /// <summary> /// Registers an alias with a property accessor for another DotvvmProperty given by the PropertyAlias attribute. /// </summary> public static DotvvmPropertyAlias RegisterAlias<TDeclaringType>( Expression<Func<TDeclaringType, object?>> propertyAccessor) { var property = ReflectionUtils.GetMemberFromExpression(propertyAccessor.Body) as PropertyInfo; if (property == null) { throw new ArgumentException("The expression should be simple property access", nameof(propertyAccessor)); } return RegisterAlias<TDeclaringType>(property.Name); } /// <summary> /// Registers an alias for another DotvvmProperty given by the PropertyAlias attribute. /// </summary> public static DotvvmPropertyAlias RegisterAlias<TDeclaringType>( Expression<Func<DotvvmProperty?>> fieldAccessor) { var field = ReflectionUtils.GetMemberFromExpression(fieldAccessor) as FieldInfo; if (field == null || !field.IsStatic) { throw new ArgumentException("The expression should be simple static field access", nameof(fieldAccessor)); } if (!field.Name.EndsWith("Property", StringComparison.Ordinal)) { throw new ArgumentException($"DotVVM property backing field's '{field.Name}' " + "name should end with 'Property'"); } return RegisterAlias<TDeclaringType>(field.Name.Remove(field.Name.Length - "Property".Length)); } /// <summary> /// Registers an alias for another DotvvmProperty given by the PropertyAlias attribute. /// </summary> public static DotvvmPropertyAlias RegisterAlias<TDeclaringType>(string aliasName) { var field = typeof(TDeclaringType).GetField( aliasName + "Property", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field == null) { throw new ArgumentException($"'{typeof(TDeclaringType).Name}' does not contain static field '{aliasName}Property'."); } return RegisterAlias(aliasName, typeof(TDeclaringType), field); } /// <summary> /// Registers an alias for a DotvvmProperty. /// </summary> public static DotvvmPropertyAlias RegisterAlias( string aliasName, Type declaringType, ICustomAttributeProvider attributeProvider, bool throwOnDuplicitRegistration = true) { var propertyInfo = declaringType.GetProperty(aliasName); attributeProvider = propertyInfo ?? attributeProvider; var aliasAttribute = attributeProvider.GetCustomAttribute<PropertyAliasAttribute>(); if (aliasAttribute is null) { throw new ArgumentException($"A property alias must have a {nameof(PropertyAliasAttribute)}."); } var propertyAlias = new DotvvmPropertyAlias( aliasName, declaringType, aliasAttribute.AliasedPropertyName, aliasAttribute.AliasedPropertyDeclaringType ?? declaringType); propertyAlias.AttributeProvider = attributeProvider; propertyAlias.ObsoleteAttribute = attributeProvider.GetCustomAttribute<ObsoleteAttribute>(); var key = (propertyAlias.DeclaringType, propertyAlias.Name); if (!registeredProperties.TryAdd(key, propertyAlias)) { if (throwOnDuplicitRegistration) throw new PropertyAlreadyExistsException(registeredProperties[key], propertyAlias); } if (!registeredAliases.TryAdd(key, propertyAlias)) { if (throwOnDuplicitRegistration) throw new ArgumentException($"Property alias is already registered: {propertyAlias.FullName}"); else return registeredAliases[key]; } return propertyAlias; } public static void InitializeProperty(DotvvmProperty property, ICustomAttributeProvider? attributeProvider = null) { if (string.IsNullOrWhiteSpace(property.Name)) throw new Exception("DotvvmProperty must not have empty name."); if (property.DeclaringType is null || property.PropertyType is null) throw new Exception($"DotvvmProperty {property.DeclaringType?.Name}.{property.Name} must have PropertyType and DeclaringType."); property.PropertyInfo ??= property.DeclaringType.GetProperty(property.Name); property.AttributeProvider ??= attributeProvider ?? property.PropertyInfo ?? throw new ArgumentNullException(nameof(attributeProvider)); property.MarkupOptions ??= property.GetAttributes<MarkupOptionsAttribute>().SingleOrDefault() ?? new MarkupOptionsAttribute(); if (string.IsNullOrEmpty(property.MarkupOptions.Name)) property.MarkupOptions.Name = property.Name; property.DataContextChangeAttributes ??= property.GetAttributes<DataContextChangeAttribute>().ToArray(); property.DataContextManipulationAttribute ??= property.GetAttributes<DataContextStackManipulationAttribute>().SingleOrDefault(); if (property.DataContextManipulationAttribute != null && property.DataContextChangeAttributes.Any()) throw new ArgumentException($"{nameof(DataContextChangeAttributes)} and {nameof(DataContextManipulationAttribute)} cannot be set both at property '{property.FullName}'."); property.IsBindingProperty = typeof(IBinding).IsAssignableFrom(property.PropertyType); property.ObsoleteAttribute = property.AttributeProvider.GetCustomAttribute<ObsoleteAttribute>(); } public static void CheckAllPropertiesAreRegistered(Type controlType) { var properties = (from p in controlType.GetProperties(BindingFlags.Public | BindingFlags.Instance) where !registeredProperties.ContainsKey((p.DeclaringType!, p.Name)) where !p.IsDefined(typeof(PropertyGroupAttribute)) let markupOptions = p.GetCustomAttribute<MarkupOptionsAttribute>() where markupOptions != null && markupOptions.MappingMode != MappingMode.Exclude select p).ToArray(); if (properties.Any()) { var controlHasOtherProperties = registeredProperties.Values.Any(p => p.DeclaringType == controlType); var explicitLoadingHelp = !controlHasOtherProperties ? $" The control does not have any other properties registered. It could indicate that DotVVM did not register properties from this assembly - it is common with ExplicitAssemblyLoading enabled, try to register {controlType.Assembly.GetName().Name} into config.Markup.Assemblies." : ""; var deprecationHelp = " DotVVM version <= 3.x did support this, but this feature was removed as it lead to many issues. Please register the property using DotvvmProperty.Register. If you find this annoyingly verbose, you could use control capabilities instead (using DotvvmCapabilityProperty.Register)."; throw new NotSupportedException($"Control '{controlType.Name}' has properties that are not registered as a DotvvmProperty but have a MarkupOptionsAttribute: {string.Join(", ", properties.Select(p => p.Name))}." + explicitLoadingHelp + deprecationHelp); } } // TODO: figure out how to refresh on hot reload private static readonly ConcurrentDictionary<(Type, string), DotvvmProperty> registeredProperties = new(); private static readonly ConcurrentDictionary<(Type, string), DotvvmPropertyAlias> registeredAliases = new(); /// <summary> /// Resolves the <see cref="DotvvmProperty"/> by the declaring type and name. /// </summary> public static DotvvmProperty? ResolveProperty(Type type, string name) { DotvvmProperty? property; while (!registeredProperties.TryGetValue((type, name), out property) && type.BaseType != null) { type = type.BaseType; } return property; } /// <summary> /// Resolves the <see cref="DotvvmProperty"/> from the full name (DeclaringTypeName.PropertyName). /// </summary> public static DotvvmProperty? ResolveProperty(string fullName, bool caseSensitive = true) { return registeredProperties.Values.LastOrDefault(p => p.FullName.Equals(fullName, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase)); } /// <summary> /// Resolves all properties of specified type. /// </summary> public static DotvvmProperty[] ResolveProperties(Type type) { var types = new HashSet<Type>(); while (type.BaseType != null) { types.Add(type); type = type.BaseType; } return registeredProperties.Values.Where(p => types.Contains(p.DeclaringType)).ToArray(); } public static IEnumerable<DotvvmProperty> AllProperties => registeredProperties.Values; public static IEnumerable<DotvvmPropertyAlias> AllAliases => registeredAliases.Values; public override string ToString() { return $"{this.FullName}"; } } }
/** * Easing * Animates the value of a float property between two target values using * Robert Penner's easing equations for interpolation over a specified Duration. * * Original Author: Darren David darren-code@lookorfeel.com * * Ported to be easily used in Unity by Marco Mastropaolo * * Credit/Thanks: * Robert Penner - The easing equations we all know and love * (http://robertpenner.com/easing/) [See License.txt for license info] * * Lee Brimelow - initial port of Penner's equations to WPF * (http://thewpfblog.com/?p=12) * * Zeh Fernando - additional equations (out/in) from * caurina.transitions.Tweener (http://code.google.com/p/tweener/) * [See License.txt for license info] */ using UnityEngine; /// <summary> /// Animates the value of a float property between two target values using /// Robert Penner's easing equations for interpolation over a specified Duration. /// </summary> /// <example> /// <code> /// // C# /// PennerDoubleAnimation anim = new PennerDoubleAnimation(); /// anim.Type = PennerDoubleAnimation.Equations.Linear; /// anim.From = 1; /// anim.To = 0; /// myControl.BeginAnimation( OpacityProperty, anim ); /// /// // XAML /// <Storyboard x:Key="AnimateXamlRect"> /// <animation:PennerDoubleAnimation /// Storyboard.TargetName="myControl" /// Storyboard.TargetProperty="(Canvas.Left)" /// From="0" /// To="600" /// Equation="BackEaseOut" /// Duration="00:00:05" /> /// </Storyboard> /// /// <Control.Triggers> /// <EventTrigger RoutedEvent="FrameworkElement.Loaded"> /// <BeginStoryboard Storyboard="{StaticResource AnimateXamlRect}"/> /// </EventTrigger> /// </Control.Triggers> /// </code> /// </example> public static class Easing { #region Equations // These methods are all public to enable reflection in GetCurrentValueCore. #region Linear /// <summary> /// Easing equation function for a simple linear tweening, with no easing. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float Linear(float t, float b, float c, float d) { return c * t / d + b; } #endregion #region Expo /// <summary> /// Easing equation function for an exponential (2^t) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float ExpoEaseOut(float t, float b, float c, float d) { return (t == d) ? b + c : c * (-Mathf.Pow(2, -10 * t / d) + 1) + b; } /// <summary> /// Easing equation function for an exponential (2^t) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float ExpoEaseIn(float t, float b, float c, float d) { return (t == 0) ? b : c * Mathf.Pow(2, 10 * (t / d - 1)) + b; } /// <summary> /// Easing equation function for an exponential (2^t) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float ExpoEaseInOut(float t, float b, float c, float d) { if (t == 0) return b; if (t == d) return b + c; if ((t /= d / 2) < 1) return c / 2 * Mathf.Pow(2, 10 * (t - 1)) + b; return c / 2 * (-Mathf.Pow(2, -10 * --t) + 2) + b; } /// <summary> /// Easing equation function for an exponential (2^t) easing out/in: /// deceleration until halfway, then acceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float ExpoEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return ExpoEaseOut(t * 2, b, c / 2, d); return ExpoEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #region Circular /// <summary> /// Easing equation function for a circular (sqrt(1-t^2)) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float CircEaseOut(float t, float b, float c, float d) { return c * Mathf.Sqrt(1 - (t = t / d - 1) * t) + b; } /// <summary> /// Easing equation function for a circular (sqrt(1-t^2)) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float CircEaseIn(float t, float b, float c, float d) { return -c * (Mathf.Sqrt(1 - (t /= d) * t) - 1) + b; } /// <summary> /// Easing equation function for a circular (sqrt(1-t^2)) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float CircEaseInOut(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return -c / 2 * (Mathf.Sqrt(1 - t * t) - 1) + b; return c / 2 * (Mathf.Sqrt(1 - (t -= 2) * t) + 1) + b; } /// <summary> /// Easing equation function for a circular (sqrt(1-t^2)) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float CircEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return CircEaseOut(t * 2, b, c / 2, d); return CircEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #region Quad /// <summary> /// Easing equation function for a quadratic (t^2) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuadEaseOut(float t, float b, float c, float d) { return -c * (t /= d) * (t - 2) + b; } /// <summary> /// Easing equation function for a quadratic (t^2) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuadEaseIn(float t, float b, float c, float d) { return c * (t /= d) * t + b; } /// <summary> /// Easing equation function for a quadratic (t^2) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuadEaseInOut(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * t * t + b; return -c / 2 * ((--t) * (t - 2) - 1) + b; } /// <summary> /// Easing equation function for a quadratic (t^2) easing out/in: /// deceleration until halfway, then acceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuadEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return QuadEaseOut(t * 2, b, c / 2, d); return QuadEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #region Sine /// <summary> /// Easing equation function for a sinusoidal (sin(t)) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float SineEaseOut(float t, float b, float c, float d) { return c * Mathf.Sin(t / d * (Mathf.PI / 2)) + b; } /// <summary> /// Easing equation function for a sinusoidal (sin(t)) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float SineEaseIn(float t, float b, float c, float d) { return -c * Mathf.Cos(t / d * (Mathf.PI / 2)) + c + b; } /// <summary> /// Easing equation function for a sinusoidal (sin(t)) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float SineEaseInOut(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * (Mathf.Sin(Mathf.PI * t / 2)) + b; return -c / 2 * (Mathf.Cos(Mathf.PI * --t / 2) - 2) + b; } /// <summary> /// Easing equation function for a sinusoidal (sin(t)) easing in/out: /// deceleration until halfway, then acceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float SineEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return SineEaseOut(t * 2, b, c / 2, d); return SineEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #region Cubic /// <summary> /// Easing equation function for a cubic (t^3) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float CubicEaseOut(float t, float b, float c, float d) { return c * ((t = t / d - 1) * t * t + 1) + b; } /// <summary> /// Easing equation function for a cubic (t^3) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float CubicEaseIn(float t, float b, float c, float d) { return c * (t /= d) * t * t + b; } /// <summary> /// Easing equation function for a cubic (t^3) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float CubicEaseInOut(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t + b; return c / 2 * ((t -= 2) * t * t + 2) + b; } /// <summary> /// Easing equation function for a cubic (t^3) easing out/in: /// deceleration until halfway, then acceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float CubicEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return CubicEaseOut(t * 2, b, c / 2, d); return CubicEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #region Quartic /// <summary> /// Easing equation function for a quartic (t^4) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuartEaseOut(float t, float b, float c, float d) { return -c * ((t = t / d - 1) * t * t * t - 1) + b; } /// <summary> /// Easing equation function for a quartic (t^4) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuartEaseIn(float t, float b, float c, float d) { return c * (t /= d) * t * t * t + b; } /// <summary> /// Easing equation function for a quartic (t^4) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuartEaseInOut(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b; return -c / 2 * ((t -= 2) * t * t * t - 2) + b; } /// <summary> /// Easing equation function for a quartic (t^4) easing out/in: /// deceleration until halfway, then acceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuartEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return QuartEaseOut(t * 2, b, c / 2, d); return QuartEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #region Quintic /// <summary> /// Easing equation function for a quintic (t^5) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuintEaseOut(float t, float b, float c, float d) { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; } /// <summary> /// Easing equation function for a quintic (t^5) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuintEaseIn(float t, float b, float c, float d) { return c * (t /= d) * t * t * t * t + b; } /// <summary> /// Easing equation function for a quintic (t^5) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuintEaseInOut(float t, float b, float c, float d) { if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b; return c / 2 * ((t -= 2) * t * t * t * t + 2) + b; } /// <summary> /// Easing equation function for a quintic (t^5) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float QuintEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return QuintEaseOut(t * 2, b, c / 2, d); return QuintEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #region Elastic /// <summary> /// Easing equation function for an elastic (exponentially decaying sine wave) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float ElasticEaseOut(float t, float b, float c, float d) { if ((t /= d) == 1) return b + c; float p = d * .3f; float s = p / 4; return (c * Mathf.Pow(2, -10 * t) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p) + c + b); } /// <summary> /// Easing equation function for an elastic (exponentially decaying sine wave) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float ElasticEaseIn(float t, float b, float c, float d) { if ((t /= d) == 1) return b + c; float p = d * .3f; float s = p / 4; return -(c * Mathf.Pow(2, 10 * (t -= 1)) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p)) + b; } /// <summary> /// Easing equation function for an elastic (exponentially decaying sine wave) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float ElasticEaseInOut(float t, float b, float c, float d) { if ((t /= d / 2) == 2) return b + c; float p = d * (.3f * 1.5f); float s = p / 4; if (t < 1) return -.5f * (c * Mathf.Pow(2, 10 * (t -= 1)) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p)) + b; return c * Mathf.Pow(2, -10 * (t -= 1)) * Mathf.Sin((t * d - s) * (2 * Mathf.PI) / p) * .5f + c + b; } /// <summary> /// Easing equation function for an elastic (exponentially decaying sine wave) easing out/in: /// deceleration until halfway, then acceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float ElasticEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return ElasticEaseOut(t * 2, b, c / 2, d); return ElasticEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #region Bounce /// <summary> /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float BounceEaseOut(float t, float b, float c, float d) { if ((t /= d) < (1f / 2.75f)) return c * (7.5625f * t * t) + b; else if (t < (2f / 2.75f)) return c * (7.5625f * (t -= (1.5f / 2.75f)) * t + .75f) + b; else if (t < (2.5f / 2.75f)) return c * (7.5625f * (t -= (2.25f / 2.75f)) * t + .9375f) + b; else return c * (7.5625f * (t -= (2.625f / 2.75f)) * t + .984375f) + b; } /// <summary> /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float BounceEaseIn(float t, float b, float c, float d) { return c - BounceEaseOut(d - t, 0, c, d) + b; } /// <summary> /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float BounceEaseInOut(float t, float b, float c, float d) { if (t < d / 2) return BounceEaseIn(t * 2, 0, c, d) * .5f + b; else return BounceEaseOut(t * 2 - d, 0, c, d) * .5f + c * .5f + b; } /// <summary> /// Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out/in: /// deceleration until halfway, then acceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float BounceEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return BounceEaseOut(t * 2, b, c / 2, d); return BounceEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #region Back /// <summary> /// Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out: /// decelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float BackEaseOut(float t, float b, float c, float d) { return c * ((t = t / d - 1) * t * ((1.70158f + 1) * t + 1.70158f) + 1) + b; } /// <summary> /// Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in: /// accelerating from zero velocity. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float BackEaseIn(float t, float b, float c, float d) { return c * (t /= d) * t * ((1.70158f + 1) * t - 1.70158f) + b; } /// <summary> /// Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in/out: /// acceleration until halfway, then deceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float BackEaseInOut(float t, float b, float c, float d) { float s = 1.70158f; if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b; return c / 2 * ((t -= 2) * t * (((s *= (1.525f)) + 1) * t + s) + 2) + b; } /// <summary> /// Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out/in: /// deceleration until halfway, then acceleration. /// </summary> /// <param name="t">Current time in seconds.</param> /// <param name="b">Starting value.</param> /// <param name="c">Final value.</param> /// <param name="d">Duration of animation.</param> /// <returns>The correct value.</returns> public static float BackEaseOutIn(float t, float b, float c, float d) { if (t < d / 2) return BackEaseOut(t * 2, b, c / 2, d); return BackEaseIn((t * 2) - d, b + c / 2, c / 2, d); } #endregion #endregion }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Xml; using System.Xml.Serialization; using AgenaTrader.API; using AgenaTrader.Custom; using AgenaTrader.Plugins; using AgenaTrader.Helper; /// <summary> /// Version: in progress /// ------------------------------------------------------------------------- /// Simon Pucher 2016 /// Christian Kovar 2016 /// ------------------------------------------------------------------------- /// Golden & Death cross: http://www.investopedia.com/ask/answers/121114/what-difference-between-golden-cross-and-death-cross-pattern.asp /// ------------------------------------------------------------------------- /// ****** Important ****** /// To compile this script without any error you also need access to the utility indicator to use these global source code elements. /// You will find this indicator on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs /// ------------------------------------------------------------------------- /// Namespace holds all indicators and is required. Do not change it. /// </summary> namespace AgenaTrader.UserCode { [Category("Script-Trading")] [Description("Use SMA or EMA crosses to find trends.")] [IsEntryAttribute(true)] [IsStopAttribute(false)] [IsTargetAttribute(false)] [OverrulePreviousStopPrice(false)] public class RunningWithTheWolves_Condition : UserScriptedCondition { #region Variables //input private Enum_RunningWithTheWolves_Indicator_MA _MA_Selected = Enum_RunningWithTheWolves_Indicator_MA.SMA; private int _ma_slow = 200; private int _ma_medium = 100; private int _ma_fast = 20; private bool _IsShortEnabled = true; private bool _IsLongEnabled = true; //output //internal private RunningWithTheWolves_Indicator _RunningWithTheWolves_Indicator = null; #endregion protected override void OnInit() { IsEntry = true; IsStop = false; IsTarget = false; Add(new OutputDescriptor(Const.DefaultIndicatorColor, "Occurred")); Add(new OutputDescriptor(Const.DefaultIndicatorColor, "Entry")); IsOverlay = false; CalculateOnClosedBar = true; //For SMA200 we need at least 200 Bars. this.RequiredBarsCount = 200; } protected override void OnBarsRequirements() { base.OnBarsRequirements(); } protected override void OnStart() { base.OnStart(); //Init our indicator to get code access this._RunningWithTheWolves_Indicator = new RunningWithTheWolves_Indicator(); } protected override void OnCalculate() { //calculate data OrderDirection_Enum? resultdata = this._RunningWithTheWolves_Indicator.calculate(InSeries, this.MA_Selected, this.MA_Fast, this.MA_Medium, this.MA_Slow); if (resultdata.HasValue) { switch (resultdata) { case OrderDirection_Enum.OpenLong: Occurred.Set(1); //Entry.Set(InSeries[0]); break; case OrderDirection_Enum.OpenShort: Occurred.Set(-1); //Entry.Set(InSeries[0]); break; //case OrderDirection.Buy: // break; //case OrderDirection.Sell: // break; default: //nothing to do Occurred.Set(0); //Entry.Set(InSeries[0]); break; } } else { Occurred.Set(0); } } public override string ToString() { return "Running with the wolves (C)"; } public override string DisplayName { get { return "Running with the wolves (C)"; } } #region Properties #region InSeries /// <summary> /// </summary> [Description("Select the type of MA you would like to use")] [InputParameter] [DisplayName("Type of MA")] public Enum_RunningWithTheWolves_Indicator_MA MA_Selected { get { return _MA_Selected; } set { _MA_Selected = value; } } /// <summary> /// </summary> [Description("Period for the slow mean average")] [InputParameter] [DisplayName("MA Slow")] public int MA_Slow { get { return _ma_slow; } set { _ma_slow = value; } } /// <summary> /// </summary> [Description("Period for the medium mean average")] [InputParameter] [DisplayName("MA Medium")] public int MA_Medium { get { return _ma_medium; } set { _ma_medium = value; } } /// <summary> /// </summary> [Description("Period for the fast mean average")] [InputParameter] [DisplayName("MA Fast")] public int MA_Fast { get { return _ma_fast; } set { _ma_fast = value; } } /// <summary> /// </summary> [Description("If true it is allowed to go long")] [InputParameter] [DisplayName("Allow Long")] public bool IsLongEnabled { get { return _IsLongEnabled; } set { _IsLongEnabled = value; } } /// <summary> /// </summary> [Description("If true it is allowed to go short")] [InputParameter] [DisplayName("Allow Short")] public bool IsShortEnabled { get { return _IsShortEnabled; } set { _IsShortEnabled = value; } } #endregion #region Output [Browsable(false)] [XmlIgnore()] public DataSeries Occurred { get { return Outputs[0]; } } [Browsable(false)] [XmlIgnore()] public DataSeries Entry { get { return Outputs[1]; } } public override IList<DataSeries> GetEntries() { return new[] { Entry }; } #endregion #region Internals #endregion #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Dynamic.Utils; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Dynamic { /// <summary> /// Provides a simple class that can be inherited from to create an object with dynamic behavior /// at runtime. Subclasses can override the various binder methods (GetMember, SetMember, Call, etc...) /// to provide custom behavior that will be invoked at runtime. /// /// If a method is not overridden then the DynamicObject does not directly support that behavior and /// the call site will determine how the binding should be performed. /// </summary> public class DynamicObject : IDynamicMetaObjectProvider { /// <summary> /// Enables derived types to create a new instance of DynamicObject. DynamicObject instances cannot be /// directly instantiated because they have no implementation of dynamic behavior. /// </summary> protected DynamicObject() { } #region Public Virtual APIs /// <summary> /// Provides the implementation of getting a member. Derived classes can override /// this method to customize behavior. When not overridden the call site requesting the /// binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="result">The result of the get operation.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] public virtual bool TryGetMember(GetMemberBinder binder, out object result) { result = null; return false; } /// <summary> /// Provides the implementation of setting a member. Derived classes can override /// this method to customize behavior. When not overridden the call site requesting the /// binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="value">The value to set.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> public virtual bool TrySetMember(SetMemberBinder binder, object value) { return false; } /// <summary> /// Provides the implementation of deleting a member. Derived classes can override /// this method to customize behavior. When not overridden the call site requesting the /// binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> public virtual bool TryDeleteMember(DeleteMemberBinder binder) { return false; } /// <summary> /// Provides the implementation of calling a member. Derived classes can override /// this method to customize behavior. When not overridden the call site requesting the /// binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="args">The arguments to be used for the invocation.</param> /// <param name="result">The result of the invocation.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] public virtual bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { result = null; return false; } /// <summary> /// Provides the implementation of converting the DynamicObject to another type. Derived classes /// can override this method to customize behavior. When not overridden the call site /// requesting the binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="result">The result of the conversion.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] public virtual bool TryConvert(ConvertBinder binder, out object result) { result = null; return false; } /// <summary> /// Provides the implementation of creating an instance of the DynamicObject. Derived classes /// can override this method to customize behavior. When not overridden the call site requesting /// the binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="args">The arguments used for creation.</param> /// <param name="result">The created instance.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] public virtual bool TryCreateInstance(CreateInstanceBinder binder, object[] args, out object result) { result = null; return false; } /// <summary> /// Provides the implementation of invoking the DynamicObject. Derived classes can /// override this method to customize behavior. When not overridden the call site requesting /// the binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="args">The arguments to be used for the invocation.</param> /// <param name="result">The result of the invocation.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] public virtual bool TryInvoke(InvokeBinder binder, object[] args, out object result) { result = null; return false; } /// <summary> /// Provides the implementation of performing a binary operation. Derived classes can /// override this method to customize behavior. When not overridden the call site requesting /// the binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="arg">The right operand for the operation.</param> /// <param name="result">The result of the operation.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] public virtual bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result) { result = null; return false; } /// <summary> /// Provides the implementation of performing a unary operation. Derived classes can /// override this method to customize behavior. When not overridden the call site requesting /// the binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="result">The result of the operation.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] public virtual bool TryUnaryOperation(UnaryOperationBinder binder, out object result) { result = null; return false; } /// <summary> /// Provides the implementation of performing a get index operation. Derived classes can /// override this method to customize behavior. When not overridden the call site requesting /// the binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="indexes">The indexes to be used.</param> /// <param name="result">The result of the operation.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] public virtual bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { result = null; return false; } /// <summary> /// Provides the implementation of performing a set index operation. Derived classes can /// override this method to custmize behavior. When not overridden the call site requesting /// the binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="indexes">The indexes to be used.</param> /// <param name="value">The value to set.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")] public virtual bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value) { return false; } /// <summary> /// Provides the implementation of performing a delete index operation. Derived classes /// can override this method to custmize behavior. When not overridden the call site /// requesting the binder determines the behavior. /// </summary> /// <param name="binder">The binder provided by the call site.</param> /// <param name="indexes">The indexes to be deleted.</param> /// <returns>true if the operation is complete, false if the call site should determine behavior.</returns> public virtual bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes) { return false; } /// <summary> /// Returns the enumeration of all dynamic member names. /// </summary> /// <returns>The list of dynamic member names.</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public virtual System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() { return Array.Empty<string>(); } #endregion #region MetaDynamic private sealed class MetaDynamic : DynamicMetaObject { internal MetaDynamic(Expression expression, DynamicObject value) : base(expression, BindingRestrictions.Empty, value) { } public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames() { return Value.GetDynamicMemberNames(); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { if (IsOverridden("TryGetMember")) { return CallMethodWithResult("TryGetMember", binder, s_noArgs, (e) => binder.FallbackGetMember(this, e)); } return base.BindGetMember(binder); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { if (IsOverridden("TrySetMember")) { return CallMethodReturnLast("TrySetMember", binder, s_noArgs, value.Expression, (e) => binder.FallbackSetMember(this, value, e)); } return base.BindSetMember(binder, value); } public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder) { if (IsOverridden("TryDeleteMember")) { return CallMethodNoResult("TryDeleteMember", binder, s_noArgs, (e) => binder.FallbackDeleteMember(this, e)); } return base.BindDeleteMember(binder); } public override DynamicMetaObject BindConvert(ConvertBinder binder) { if (IsOverridden("TryConvert")) { return CallMethodWithResult("TryConvert", binder, s_noArgs, (e) => binder.FallbackConvert(this, e)); } return base.BindConvert(binder); } public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { // Generate a tree like: // // { // object result; // TryInvokeMember(payload, out result) // ? result // : TryGetMember(payload, out result) // ? FallbackInvoke(result) // : fallbackResult // } // // Then it calls FallbackInvokeMember with this tree as the // "error", giving the language the option of using this // tree or doing .NET binding. // Fallback fallback = e => binder.FallbackInvokeMember(this, args, e); var call = BuildCallMethodWithResult( "TryInvokeMember", binder, DynamicMetaObject.GetExpressions(args), BuildCallMethodWithResult<GetMemberBinder>( "TryGetMember", new GetBinderAdapter(binder), s_noArgs, fallback(null), (e) => binder.FallbackInvoke(e, args, null) ), null ); return fallback(call); } public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args) { if (IsOverridden("TryCreateInstance")) { return CallMethodWithResult("TryCreateInstance", binder, DynamicMetaObject.GetExpressions(args), (e) => binder.FallbackCreateInstance(this, args, e)); } return base.BindCreateInstance(binder, args); } public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { if (IsOverridden("TryInvoke")) { return CallMethodWithResult("TryInvoke", binder, DynamicMetaObject.GetExpressions(args), (e) => binder.FallbackInvoke(this, args, e)); } return base.BindInvoke(binder, args); } public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg) { if (IsOverridden("TryBinaryOperation")) { return CallMethodWithResult("TryBinaryOperation", binder, DynamicMetaObject.GetExpressions(new DynamicMetaObject[] { arg }), (e) => binder.FallbackBinaryOperation(this, arg, e)); } return base.BindBinaryOperation(binder, arg); } public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder) { if (IsOverridden("TryUnaryOperation")) { return CallMethodWithResult("TryUnaryOperation", binder, s_noArgs, (e) => binder.FallbackUnaryOperation(this, e)); } return base.BindUnaryOperation(binder); } public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { if (IsOverridden("TryGetIndex")) { return CallMethodWithResult("TryGetIndex", binder, DynamicMetaObject.GetExpressions(indexes), (e) => binder.FallbackGetIndex(this, indexes, e)); } return base.BindGetIndex(binder, indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { if (IsOverridden("TrySetIndex")) { return CallMethodReturnLast("TrySetIndex", binder, DynamicMetaObject.GetExpressions(indexes), value.Expression, (e) => binder.FallbackSetIndex(this, indexes, value, e)); } return base.BindSetIndex(binder, indexes, value); } public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes) { if (IsOverridden("TryDeleteIndex")) { return CallMethodNoResult("TryDeleteIndex", binder, DynamicMetaObject.GetExpressions(indexes), (e) => binder.FallbackDeleteIndex(this, indexes, e)); } return base.BindDeleteIndex(binder, indexes); } private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion); private readonly static Expression[] s_noArgs = new Expression[0]; // used in reference comparison, requires unique object identity private static Expression[] GetConvertedArgs(params Expression[] args) { ReadOnlyCollectionBuilder<Expression> paramArgs = new ReadOnlyCollectionBuilder<Expression>(args.Length); for (int i = 0; i < args.Length; i++) { paramArgs.Add(Expression.Convert(args[i], typeof(object))); } return paramArgs.ToArray(); } /// <summary> /// Helper method for generating expressions that assign byRef call /// parameters back to their original variables /// </summary> private static Expression ReferenceArgAssign(Expression callArgs, Expression[] args) { ReadOnlyCollectionBuilder<Expression> block = null; for (int i = 0; i < args.Length; i++) { ContractUtils.Requires(args[i] is ParameterExpression); if (((ParameterExpression)args[i]).IsByRef) { if (block == null) block = new ReadOnlyCollectionBuilder<Expression>(); block.Add( Expression.Assign( args[i], Expression.Convert( Expression.ArrayIndex( callArgs, Expression.Constant(i) ), args[i].Type ) ) ); } } if (block != null) return Expression.Block(block); else return Expression.Empty(); } /// <summary> /// Helper method for generating arguments for calling methods /// on DynamicObject. parameters is either a list of ParameterExpressions /// to be passed to the method as an object[], or NoArgs to signify that /// the target method takes no object[] parameter. /// </summary> private static Expression[] BuildCallArgs<TBinder>(TBinder binder, Expression[] parameters, Expression arg0, Expression arg1) where TBinder : DynamicMetaObjectBinder { if (!object.ReferenceEquals(parameters, s_noArgs)) return arg1 != null ? new Expression[] { Constant(binder), arg0, arg1 } : new Expression[] { Constant(binder), arg0 }; else return arg1 != null ? new Expression[] { Constant(binder), arg1 } : new Expression[] { Constant(binder) }; } private static ConstantExpression Constant<TBinder>(TBinder binder) { return Expression.Constant(binder, typeof(TBinder)); } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic that returns a result /// </summary> private DynamicMetaObject CallMethodWithResult<TBinder>(string methodName, TBinder binder, Expression[] args, Fallback fallback) where TBinder : DynamicMetaObjectBinder { return CallMethodWithResult(methodName, binder, args, fallback, null); } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic that returns a result /// </summary> private DynamicMetaObject CallMethodWithResult<TBinder>(string methodName, TBinder binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke) where TBinder : DynamicMetaObjectBinder { // // First, call fallback to do default binding // This produces either an error or a call to a .NET member // DynamicMetaObject fallbackResult = fallback(null); var callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke); // // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. // return fallback(callDynamic); } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on DynamicObject that returns a result. /// /// args is either an array of arguments to be passed /// to the method as an object[] or NoArgs to signify that /// the target method takes no parameters. /// </summary> private DynamicMetaObject BuildCallMethodWithResult<TBinder>(string methodName, TBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke) where TBinder : DynamicMetaObjectBinder { if (!IsOverridden(methodName)) { return fallbackResult; } // // Build a new expression like: // { // object result; // TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult // } // var result = Expression.Parameter(typeof(object), null); ParameterExpression callArgs = methodName != "TryBinaryOperation" ? Expression.Parameter(typeof(object[]), null) : Expression.Parameter(typeof(object), null); var callArgsValue = GetConvertedArgs(args); var resultMO = new DynamicMetaObject(result, BindingRestrictions.Empty); // Need to add a conversion if calling TryConvert if (binder.ReturnType != typeof(object)) { Debug.Assert(binder is ConvertBinder && fallbackInvoke == null); var convert = Expression.Convert(resultMO.Expression, binder.ReturnType); // will always be a cast or unbox Debug.Assert(convert.Method == null); // Prepare a good exception message in case the convert will fail string convertFailed = Strings.DynamicObjectResultNotAssignable( "{0}", this.Value.GetType(), binder.GetType(), binder.ReturnType ); Expression condition; // If the return type can not be assigned null then just check for type assignablity otherwise allow null. if (binder.ReturnType.GetTypeInfo().IsValueType && Nullable.GetUnderlyingType(binder.ReturnType) == null) { condition = Expression.TypeIs(resultMO.Expression, binder.ReturnType); } else { condition = Expression.OrElse( Expression.Equal(resultMO.Expression, Expression.Constant(null)), Expression.TypeIs(resultMO.Expression, binder.ReturnType)); } var checkedConvert = Expression.Condition( condition, convert, Expression.Throw( Expression.New(typeof(InvalidCastException).GetConstructor(new Type[] { typeof(string) }), Expression.Call( typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) }), Expression.Constant(convertFailed), Expression.NewArrayInit(typeof(object), Expression.Condition( Expression.Equal(resultMO.Expression, Expression.Constant(null)), Expression.Constant("null"), Expression.Call( resultMO.Expression, typeof(object).GetMethod("GetType") ), typeof(object) ) ) ) ), binder.ReturnType ), binder.ReturnType ); resultMO = new DynamicMetaObject(checkedConvert, resultMO.Restrictions); } if (fallbackInvoke != null) { resultMO = fallbackInvoke(resultMO); } var callDynamic = new DynamicMetaObject( Expression.Block( new[] { result, callArgs }, methodName != "TryBinaryOperation" ? Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)) : Expression.Assign(callArgs, callArgsValue[0]), Expression.Condition( Expression.Call( GetLimitedSelf(), typeof(DynamicObject).GetMethod(methodName), BuildCallArgs( binder, args, callArgs, result ) ), Expression.Block( methodName != "TryBinaryOperation" ? ReferenceArgAssign(callArgs, args) : Expression.Empty(), resultMO.Expression ), fallbackResult.Expression, binder.ReturnType ) ), GetRestrictions().Merge(resultMO.Restrictions).Merge(fallbackResult.Restrictions) ); return callDynamic; } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic, but uses one of the arguments for /// the result. /// /// args is either an array of arguments to be passed /// to the method as an object[] or NoArgs to signify that /// the target method takes no parameters. /// </summary> private DynamicMetaObject CallMethodReturnLast<TBinder>(string methodName, TBinder binder, Expression[] args, Expression value, Fallback fallback) where TBinder : DynamicMetaObjectBinder { // // First, call fallback to do default binding // This produces either an error or a call to a .NET member // DynamicMetaObject fallbackResult = fallback(null); // // Build a new expression like: // { // object result; // TrySetMember(payload, result = value) ? result : fallbackResult // } // var result = Expression.Parameter(typeof(object), null); var callArgs = Expression.Parameter(typeof(object[]), null); var callArgsValue = GetConvertedArgs(args); var callDynamic = new DynamicMetaObject( Expression.Block( new[] { result, callArgs }, Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)), Expression.Condition( Expression.Call( GetLimitedSelf(), typeof(DynamicObject).GetMethod(methodName), BuildCallArgs( binder, args, callArgs, Expression.Assign(result, Expression.Convert(value, typeof(object))) ) ), Expression.Block( ReferenceArgAssign(callArgs, args), result ), fallbackResult.Expression, typeof(object) ) ), GetRestrictions().Merge(fallbackResult.Restrictions) ); // // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. // return fallback(callDynamic); } /// <summary> /// Helper method for generating a MetaObject which calls a /// specific method on Dynamic, but uses one of the arguments for /// the result. /// /// args is either an array of arguments to be passed /// to the method as an object[] or NoArgs to signify that /// the target method takes no parameters. /// </summary> private DynamicMetaObject CallMethodNoResult<TBinder>(string methodName, TBinder binder, Expression[] args, Fallback fallback) where TBinder : DynamicMetaObjectBinder { // // First, call fallback to do default binding // This produces either an error or a call to a .NET member // DynamicMetaObject fallbackResult = fallback(null); var callArgs = Expression.Parameter(typeof(object[]), null); var callArgsValue = GetConvertedArgs(args); // // Build a new expression like: // if (TryDeleteMember(payload)) { } else { fallbackResult } // var callDynamic = new DynamicMetaObject( Expression.Block( new[] { callArgs }, Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)), Expression.Condition( Expression.Call( GetLimitedSelf(), typeof(DynamicObject).GetMethod(methodName), BuildCallArgs( binder, args, callArgs, null ) ), Expression.Block( ReferenceArgAssign(callArgs, args), Expression.Empty() ), fallbackResult.Expression, typeof(void) ) ), GetRestrictions().Merge(fallbackResult.Restrictions) ); // // Now, call fallback again using our new MO as the error // When we do this, one of two things can happen: // 1. Binding will succeed, and it will ignore our call to // the dynamic method, OR // 2. Binding will fail, and it will use the MO we created // above. // return fallback(callDynamic); } /// <summary> /// Checks if the derived type has overridden the specified method. If there is no /// implementation for the method provided then Dynamic falls back to the base class /// behavior which lets the call site determine how the binder is performed. /// </summary> private bool IsOverridden(string method) { var methods = Value.GetType().GetMember(method, BindingFlags.Public | BindingFlags.Instance).OfType<MethodInfo>(); foreach (MethodInfo mi in methods) { if (mi.DeclaringType != typeof(DynamicObject)) { var baseMethods = typeof(DynamicObject).GetMember(method, BindingFlags.Public | BindingFlags.Instance).OfType<MethodInfo>(); foreach (MethodInfo baseMethod in baseMethods) { var baseParams = baseMethod.GetParameters(); var miParams = mi.GetParameters(); if (baseParams.Length == miParams.Length) { bool mismatch = false; for (int i = 0; i < baseParams.Length; i++) { if (baseParams[i].ParameterType != miParams[i].ParameterType) { mismatch = true; } } if (!mismatch) { return true; } } } } } return false; } /// <summary> /// Returns a Restrictions object which includes our current restrictions merged /// with a restriction limiting our type /// </summary> private BindingRestrictions GetRestrictions() { Debug.Assert(Restrictions == BindingRestrictions.Empty, "We don't merge, restrictions are always empty"); return BindingRestrictions.GetTypeRestriction(this); } /// <summary> /// Returns our Expression converted to DynamicObject /// </summary> private Expression GetLimitedSelf() { // Convert to DynamicObject rather than LimitType, because // the limit type might be non-public. if (TypeUtils.AreEquivalent(Expression.Type, typeof(DynamicObject))) { return Expression; } return Expression.Convert(Expression, typeof(DynamicObject)); } private new DynamicObject Value { get { return (DynamicObject)base.Value; } } // It is okay to throw NotSupported from this binder. This object // is only used by DynamicObject.GetMember--it is not expected to // (and cannot) implement binding semantics. It is just so the DO // can use the Name and IgnoreCase properties. private sealed class GetBinderAdapter : GetMemberBinder { internal GetBinderAdapter(InvokeMemberBinder binder) : base(binder.Name, binder.IgnoreCase) { } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) { throw new NotSupportedException(); } } } #endregion #region IDynamicMetaObjectProvider Members /// <summary> /// The provided MetaObject will dispatch to the Dynamic virtual methods. /// The object can be encapsulated inside of another MetaObject to /// provide custom behavior for individual actions. /// </summary> public virtual DynamicMetaObject GetMetaObject(Expression parameter) { return new MetaDynamic(parameter, this); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace MusicLife.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 Stephen M. McKamey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*---------------------------------------------------------------------------------*/ #endregion License using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace Pathfinding.Serialization.JsonFx { /// <summary> /// Writes data as full ECMAScript objects, rather than the limited set of JSON objects. /// </summary> public class EcmaScriptWriter : JsonWriter { #region Constants private static readonly DateTime EcmaScriptEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); private const string EcmaScriptDateCtor1 = "new Date({0})"; private const string EcmaScriptDateCtor7 = "new Date({0:0000},{1},{2},{3},{4},{5},{6})"; private const string EmptyRegExpLiteral = "(?:)"; private const char RegExpLiteralDelim = '/'; private const char OperatorCharEscape = '\\'; private const string NamespaceDelim = "."; private static readonly char[] NamespaceDelims = { '.' }; private const string RootDeclarationDebug = @" /* namespace {1} */ var {0};"; private const string RootDeclaration = @"var {0};"; private const string NamespaceCheck = @"if(""undefined""===typeof {0}){{{0}={{}};}}"; private const string NamespaceCheckDebug = @" if (""undefined"" === typeof {0}) {{ {0} = {{}}; }}"; private static readonly IList<string> BrowserObjects = new List<string>(new string[] { "console", "document", "event", "frames", "history", "location", "navigator", "opera", "screen", "window" }); #endregion Constants #region Init /// <summary> /// Ctor /// </summary> /// <param name="output">TextWriter for writing</param> public EcmaScriptWriter(TextWriter output) : base(output) { } /// <summary> /// Ctor /// </summary> /// <param name="output">Stream for writing</param> public EcmaScriptWriter(Stream output) : base(output) { } /// <summary> /// Ctor /// </summary> /// <param name="output">File name for writing</param> public EcmaScriptWriter(string outputFileName) : base(outputFileName) { } /// <summary> /// Ctor /// </summary> /// <param name="output">StringBuilder for appending</param> public EcmaScriptWriter(StringBuilder output) : base(output) { } #endregion Init #region Static Methods /// <summary> /// A helper method for serializing an object to EcmaScript /// </summary> /// <param name="value"></param> /// <returns></returns> public static new string Serialize(object value) { StringBuilder output = new StringBuilder(); using (EcmaScriptWriter writer = new EcmaScriptWriter(output)) { writer.Write(value); } return output.ToString(); } /// <summary> /// Returns a block of script for ensuring that a namespace is declared. /// </summary> /// <param name="writer">the output writer</param> /// <param name="ident">the namespace to ensure</param> /// <param name="namespaces">list of namespaces already emitted</param> /// <param name="debug">determines if should emit pretty-printed</param> /// <returns>if was a nested identifier</returns> public static bool WriteNamespaceDeclaration(TextWriter writer, string ident, List<string> namespaces, bool isDebug) { if (String.IsNullOrEmpty(ident)) { return false; } if (namespaces == null) { namespaces = new List<string>(); } string[] nsParts = ident.Split(EcmaScriptWriter.NamespaceDelims, StringSplitOptions.RemoveEmptyEntries); string ns = nsParts[0]; bool isNested = false; for (int i=0; i<nsParts.Length-1; i++) { isNested = true; if (i > 0) { ns += EcmaScriptWriter.NamespaceDelim; ns += nsParts[i]; } if (namespaces.Contains(ns) || EcmaScriptWriter.BrowserObjects.Contains(ns)) { // don't emit multiple checks for same namespace continue; } // make note that we've emitted this namespace before namespaces.Add(ns); if (i == 0) { if (isDebug) { writer.Write(EcmaScriptWriter.RootDeclarationDebug, ns, String.Join(NamespaceDelim, nsParts, 0, nsParts.Length-1)); } else { writer.Write(EcmaScriptWriter.RootDeclaration, ns); } } if (isDebug) { writer.WriteLine(EcmaScriptWriter.NamespaceCheckDebug, ns); } else { writer.Write(EcmaScriptWriter.NamespaceCheck, ns); } } if (isDebug && isNested) { writer.WriteLine(); } return isNested; } #endregion Static Methods #region Writer Methods /// <summary> /// Writes dates as ECMAScript Date constructors /// </summary> /// <param name="value"></param> public override void Write(DateTime value) { EcmaScriptWriter.WriteEcmaScriptDate(this, value); } /// <summary> /// Writes out all Single values including NaN, Infinity, -Infinity /// </summary> /// <param name="value">Single</param> public override void Write(float value) { this.TextWriter.Write(value.ToString("r")); } /// <summary> /// Writes out all Double values including NaN, Infinity, -Infinity /// </summary> /// <param name="value">Double</param> public override void Write(double value) { this.TextWriter.Write(value.ToString("r")); } protected override void Write(object value, bool isProperty) { if (value is Regex) { if (isProperty && this.Settings.PrettyPrint) { this.TextWriter.Write(' '); } EcmaScriptWriter.WriteEcmaScriptRegExp(this, (Regex)value); return; } base.Write(value, isProperty); } protected override void WriteObjectPropertyName(string name) { if (EcmaScriptIdentifier.IsValidIdentifier(name, false)) { // write out without quoting this.TextWriter.Write(name); } else { // write out as an escaped string base.WriteObjectPropertyName(name); } } public static void WriteEcmaScriptDate(JsonWriter writer, DateTime value) { if (value.Kind == DateTimeKind.Unspecified) { // unknown timezones serialize directly to become browser-local writer.TextWriter.Write( EcmaScriptWriter.EcmaScriptDateCtor7, value.Year, // yyyy value.Month-1, // 0-11 value.Day, // 1-31 value.Hour, // 0-23 value.Minute, // 0-60 value.Second, // 0-60 value.Millisecond); // 0-999 return; } if (value.Kind == DateTimeKind.Local) { // convert server-local to UTC value = value.ToUniversalTime(); } // find the time since Jan 1, 1970 TimeSpan duration = value.Subtract(EcmaScriptWriter.EcmaScriptEpoch); // get the total milliseconds long ticks = (long)duration.TotalMilliseconds; // write out as a Date constructor writer.TextWriter.Write( EcmaScriptWriter.EcmaScriptDateCtor1, ticks); } /// <summary> /// Outputs a .NET Regex as an ECMAScript RegExp literal. /// Defaults to global matching off. /// </summary> /// <param name="writer"></param> /// <param name="regex"></param> /// <remarks> /// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf /// </remarks> public static void WriteEcmaScriptRegExp(JsonWriter writer, Regex regex) { EcmaScriptWriter.WriteEcmaScriptRegExp(writer, regex, false); } /// <summary> /// Outputs a .NET Regex as an ECMAScript RegExp literal. /// </summary> /// <param name="writer"></param> /// <param name="regex"></param> /// <param name="isGlobal"></param> /// <remarks> /// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf /// </remarks> public static void WriteEcmaScriptRegExp(JsonWriter writer, Regex regex, bool isGlobal) { if (regex == null) { writer.TextWriter.Write(JsonReader.LiteralNull); return; } // Regex.ToString() returns the original pattern string pattern = regex.ToString(); if (String.IsNullOrEmpty(pattern)) { // must output something otherwise becomes a code comment pattern = EcmaScriptWriter.EmptyRegExpLiteral; } string modifiers = isGlobal ? "g" : ""; switch (regex.Options & (RegexOptions.IgnoreCase|RegexOptions.Multiline)) { case RegexOptions.IgnoreCase: { modifiers += "i"; break; } case RegexOptions.Multiline: { modifiers += "m"; break; } case RegexOptions.IgnoreCase|RegexOptions.Multiline: { modifiers += "im"; break; } } writer.TextWriter.Write(EcmaScriptWriter.RegExpLiteralDelim); int length = pattern.Length; int start = 0; for (int i = start; i < length; i++) { switch (pattern[i]) { case EcmaScriptWriter.RegExpLiteralDelim: { writer.TextWriter.Write(pattern.Substring(start, i - start)); start = i + 1; writer.TextWriter.Write(EcmaScriptWriter.OperatorCharEscape); writer.TextWriter.Write(pattern[i]); break; } } } writer.TextWriter.Write(pattern.Substring(start, length - start)); writer.TextWriter.Write(EcmaScriptWriter.RegExpLiteralDelim); writer.TextWriter.Write(modifiers); } #endregion Writer Methods } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Linq; using Xunit; namespace Moq.Tests.Linq { public class SupportedQuerying { public class GivenABooleanProperty { [Fact] public void WhenImplicitlyQueryingTrueOneOf_ThenSetsPropertyToTrue() { var target = Mock.Of<IFoo>(x => x.IsValid); Assert.True(target.IsValid); } [Fact] public void WhenImplicitlyQueryingTrueWhere_ThenSetsPropertyToTrue() { var target = Mocks.Of<IFoo>().Where(x => x.IsValid); Assert.True(target.First().IsValid); } [Fact] public void WhenImplicitlyQueryingTrueFirst_ThenSetsPropertyToTrue() { var target = Mocks.Of<IFoo>().First(x => x.IsValid); Assert.True(target.IsValid); } [Fact] public void WhenImplicitlyQueryingTrueFirstOrDefault_ThenSetsPropertyToTrue() { var target = Mocks.Of<IFoo>().FirstOrDefault(x => x.IsValid); Assert.True(target.IsValid); } [Fact] public void WhenExplicitlyQueryingTrueOneOf_ThenSetsPropertyToTrue() { var target = Mock.Of<IFoo>(x => x.IsValid == true); Assert.True(target.IsValid); } [Fact] public void WhenExplicitlyQueryingTrueWhere_ThenSetsPropertyToTrue() { var target = Mocks.Of<IFoo>().Where(x => x.IsValid == true); Assert.True(target.First().IsValid); } [Fact] public void WhenExplicitlyQueryingTrueFirst_ThenSetsPropertyToTrue() { var target = Mocks.Of<IFoo>().First(x => x.IsValid == true); Assert.True(target.IsValid); } [Fact] public void WhenExplicitlyQueryingTrueFirstOrDefault_ThenSetsPropertyToTrue() { var target = Mocks.Of<IFoo>().FirstOrDefault(x => x.IsValid == true); Assert.True(target.IsValid); } [Fact] public void WhenQueryingOnFluent_ThenSetsPropertyToTrue() { var target = Mocks.Of<IFluent>().FirstOrDefault(x => x.Foo.IsValid == true); Assert.True(target.Foo.IsValid); } [Fact] public void WhenQueryingWithFalse_ThenSetsProperty() { var target = Mock.Of<FooDefaultIsValid>(x => x.IsValid == false); Assert.False(target.IsValid); } [Fact] public void WhenQueryingTrueEquals_ThenSetsProperty() { var target = Mock.Of<IFoo>(x => true == x.IsValid); Assert.True(target.IsValid); } [Fact] public void WhenQueryingFalseEquals_ThenSetsProperty() { var target = Mock.Of<FooDefaultIsValid>(x => false == x.IsValid); Assert.False(target.IsValid); } [Fact] public void WhenQueryingNegatedProperty_ThenSetsProperty() { var target = Mock.Of<FooDefaultIsValid>(x => !x.IsValid); Assert.False(target.IsValid); } [Fact] public void WhenQueryingWithNoValue_ThenAlwaysHasPropertyStubBehavior() { var foo = Mock.Of<IFoo>(); foo.IsValid = true; Assert.True(foo.IsValid); foo.IsValid = false; Assert.False(foo.IsValid); } public class FooDefaultIsValid : IFoo { public FooDefaultIsValid() { this.IsValid = true; } public virtual bool IsValid { get; set; } } public interface IFoo { bool IsValid { get; set; } } public interface IFluent { IFoo Foo { get; set; } } } public class GivenAnEnumProperty { [Fact] public void WhenQueryingWithEnumValue_ThenSetsPropertyValue() { var target = Mocks.Of<IFoo>().First(f => f.Targets == AttributeTargets.Class); Assert.Equal(AttributeTargets.Class, target.Targets); } //[Fact(Skip = "Not implemented yet. Need to refactor old matcher stuff to the new one, require the MatcherAttribute on matchers, and verify it.")] //public void WhenQueryingWithItIsAny_ThenThrowsNotSupportedException() //{ // var target = Mocks.Of<IFoo>().First(f => f.Targets == It.IsAny<AttributeTargets>()); // // Assert.Equal(AttributeTargets.Class, target.Targets); //} public interface IFoo { AttributeTargets Targets { get; set; } } } public class GivenTwoProperties { [Fact] public void WhenCombiningQueryingWithImplicitBoolean_ThenSetsBothProperties() { var target = Mock.Of<IFoo>(x => x.IsValid && x.Value == "foo"); Assert.True(target.IsValid); Assert.Equal("foo", target.Value); } [Fact] public void WhenCombiningQueryingWithExplicitBoolean_ThenSetsBothProperties() { var target = Mock.Of<IFoo>(x => x.IsValid == true && x.Value == "foo"); Assert.True(target.IsValid); Assert.Equal("foo", target.Value); } public interface IFoo { string Value { get; set; } bool IsValid { get; set; } } } public class GivenAMethodWithOneParameter { [Fact] public void WhenUsingSpecificArgumentValue_ThenSetsReturnValue() { var foo = Mock.Of<IFoo>(x => x.Do(5) == "foo"); Assert.Equal("foo", foo.Do(5)); } [Fact] public void WhenUsingItIsAnyForArgument_ThenSetsReturnValue() { var foo = Mock.Of<IFoo>(x => x.Do(It.IsAny<int>()) == "foo"); Assert.Equal("foo", foo.Do(5)); } [Fact] public void WhenUsingItIsForArgument_ThenSetsReturnValue() { var foo = Mock.Of<IFoo>(x => x.Do(It.Is<int>(i => i > 0)) == "foo"); Assert.Equal("foo", foo.Do(5)); Assert.Equal(default(string), foo.Do(-5)); } [Fact] public void WhenUsingCustomMatcherForArgument_ThenSetsReturnValue() { var foo = Mock.Of<IFoo>(x => x.Do(Any<int>()) == "foo"); Assert.Equal("foo", foo.Do(5)); } public TValue Any<TValue>() { return Match.Create<TValue>(v => true); } public interface IFoo { string Do(int value); } } public class GivenAClassWithNonVirtualProperties { [Fact] public void WhenQueryingByProperties_ThenSetsThemDirectly() { var foo = Mock.Of<Foo>(x => x.Id == 1 && x.Value == "hello"); Assert.Equal(1, foo.Id); Assert.Equal("hello", foo.Value); } public class Foo { public int Id { get; set; } public string Value { get; set; } } } public class GivenAReadonlyProperty { [Fact] public void WhenQueryingByProperties_ThenSetsThemDirectly() { var foo = Mock.Of<Foo>(x => x.Id == 1); Assert.Equal(1, foo.Id); } public class Foo { public virtual int Id { get { return 0; } } } } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System.Text; using System.IO; using System.Collections; using Ctrip.Util; using Ctrip.Repository; namespace Ctrip.Util { /// <summary> /// Abstract class that provides the formatting functionality that /// derived classes need. /// </summary> /// <remarks> /// <para> /// Conversion specifiers in a conversion patterns are parsed to /// individual PatternConverters. Each of which is responsible for /// converting a logging event in a converter specific manner. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public abstract class PatternConverter { #region Protected Instance Constructors /// <summary> /// Protected constructor /// </summary> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="PatternConverter" /> class. /// </para> /// </remarks> protected PatternConverter() { } #endregion Protected Instance Constructors #region Public Instance Properties /// <summary> /// Get the next pattern converter in the chain /// </summary> /// <value> /// the next pattern converter in the chain /// </value> /// <remarks> /// <para> /// Get the next pattern converter in the chain /// </para> /// </remarks> public virtual PatternConverter Next { get { return m_next; } } /// <summary> /// Gets or sets the formatting info for this converter /// </summary> /// <value> /// The formatting info for this converter /// </value> /// <remarks> /// <para> /// Gets or sets the formatting info for this converter /// </para> /// </remarks> public virtual FormattingInfo FormattingInfo { get { return new FormattingInfo(m_min, m_max, m_leftAlign); } set { m_min = value.Min; m_max = value.Max; m_leftAlign = value.LeftAlign; } } /// <summary> /// Gets or sets the option value for this converter /// </summary> /// <summary> /// The option for this converter /// </summary> /// <remarks> /// <para> /// Gets or sets the option value for this converter /// </para> /// </remarks> public virtual string Option { get { return m_option; } set { m_option = value; } } #endregion Public Instance Properties #region Protected Abstract Methods /// <summary> /// Evaluate this pattern converter and write the output to a writer. /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="state">The state object on which the pattern converter should be executed.</param> /// <remarks> /// <para> /// Derived pattern converters must override this method in order to /// convert conversion specifiers in the appropriate way. /// </para> /// </remarks> abstract protected void Convert(TextWriter writer, object state); #endregion Protected Abstract Methods #region Public Instance Methods /// <summary> /// Set the next pattern converter in the chains /// </summary> /// <param name="patternConverter">the pattern converter that should follow this converter in the chain</param> /// <returns>the next converter</returns> /// <remarks> /// <para> /// The PatternConverter can merge with its neighbor during this method (or a sub class). /// Therefore the return value may or may not be the value of the argument passed in. /// </para> /// </remarks> public virtual PatternConverter SetNext(PatternConverter patternConverter) { m_next = patternConverter; return m_next; } /// <summary> /// Write the pattern converter to the writer with appropriate formatting /// </summary> /// <param name="writer"><see cref="TextWriter" /> that will receive the formatted result.</param> /// <param name="state">The state object on which the pattern converter should be executed.</param> /// <remarks> /// <para> /// This method calls <see cref="Convert"/> to allow the subclass to perform /// appropriate conversion of the pattern converter. If formatting options have /// been specified via the <see cref="FormattingInfo"/> then this method will /// apply those formattings before writing the output. /// </para> /// </remarks> virtual public void Format(TextWriter writer, object state) { if (m_min < 0 && m_max == int.MaxValue) { // Formatting options are not in use Convert(writer, state); } else { string msg = null; int len; lock (m_formatWriter) { m_formatWriter.Reset(c_renderBufferMaxCapacity, c_renderBufferSize); Convert(m_formatWriter, state); StringBuilder buf = m_formatWriter.GetStringBuilder(); len = buf.Length; if (len > m_max) { msg = buf.ToString(len - m_max, m_max); len = m_max; } else { msg = buf.ToString(); } } if (len < m_min) { if (m_leftAlign) { writer.Write(msg); SpacePad(writer, m_min - len); } else { SpacePad(writer, m_min - len); writer.Write(msg); } } else { writer.Write(msg); } } } private static readonly string[] SPACES = { " ", " ", " ", " ", // 1,2,4,8 spaces " ", // 16 spaces " " }; // 32 spaces /// <summary> /// Fast space padding method. /// </summary> /// <param name="writer"><see cref="TextWriter" /> to which the spaces will be appended.</param> /// <param name="length">The number of spaces to be padded.</param> /// <remarks> /// <para> /// Fast space padding method. /// </para> /// </remarks> protected static void SpacePad(TextWriter writer, int length) { while(length >= 32) { writer.Write(SPACES[5]); length -= 32; } for(int i = 4; i >= 0; i--) { if ((length & (1<<i)) != 0) { writer.Write(SPACES[i]); } } } #endregion Public Instance Methods #region Private Instance Fields private PatternConverter m_next; private int m_min = -1; private int m_max = int.MaxValue; private bool m_leftAlign = false; /// <summary> /// The option string to the converter /// </summary> private string m_option = null; private ReusableStringWriter m_formatWriter = new ReusableStringWriter(System.Globalization.CultureInfo.InvariantCulture); #endregion Private Instance Fields #region Constants /// <summary> /// Initial buffer size /// </summary> private const int c_renderBufferSize = 256; /// <summary> /// Maximum buffer size before it is recycled /// </summary> private const int c_renderBufferMaxCapacity = 1024; #endregion #region Static Methods /// <summary> /// Write an dictionary to a <see cref="TextWriter"/> /// </summary> /// <param name="writer">the writer to write to</param> /// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param> /// <param name="value">the value to write to the writer</param> /// <remarks> /// <para> /// Writes the <see cref="IDictionary"/> to a writer in the form: /// </para> /// <code> /// {key1=value1, key2=value2, key3=value3} /// </code> /// <para> /// If the <see cref="ILoggerRepository"/> specified /// is not null then it is used to render the key and value to text, otherwise /// the object's ToString method is called. /// </para> /// </remarks> protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionary value) { WriteDictionary(writer, repository, value.GetEnumerator()); } /// <summary> /// Write an dictionary to a <see cref="TextWriter"/> /// </summary> /// <param name="writer">the writer to write to</param> /// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param> /// <param name="value">the value to write to the writer</param> /// <remarks> /// <para> /// Writes the <see cref="IDictionaryEnumerator"/> to a writer in the form: /// </para> /// <code> /// {key1=value1, key2=value2, key3=value3} /// </code> /// <para> /// If the <see cref="ILoggerRepository"/> specified /// is not null then it is used to render the key and value to text, otherwise /// the object's ToString method is called. /// </para> /// </remarks> protected static void WriteDictionary(TextWriter writer, ILoggerRepository repository, IDictionaryEnumerator value) { writer.Write("{"); bool first = true; // Write out all the dictionary key value pairs while (value.MoveNext()) { if (first) { first = false; } else { writer.Write(", "); } WriteObject(writer, repository, value.Key); writer.Write("="); WriteObject(writer, repository, value.Value); } writer.Write("}"); } /// <summary> /// Write an object to a <see cref="TextWriter"/> /// </summary> /// <param name="writer">the writer to write to</param> /// <param name="repository">a <see cref="ILoggerRepository"/> to use for object conversion</param> /// <param name="value">the value to write to the writer</param> /// <remarks> /// <para> /// Writes the Object to a writer. If the <see cref="ILoggerRepository"/> specified /// is not null then it is used to render the object to text, otherwise /// the object's ToString method is called. /// </para> /// </remarks> protected static void WriteObject(TextWriter writer, ILoggerRepository repository, object value) { if (repository != null) { repository.RendererMap.FindAndRender(value, writer); } else { // Don't have a repository to render with so just have to rely on ToString if (value == null) { writer.Write( SystemInfo.NullText ); } else { writer.Write( value.ToString() ); } } } #endregion private PropertiesDictionary properties; /// <summary> /// /// </summary> public PropertiesDictionary Properties { get { return properties; } set { properties = value; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Threading.Tasks; using System.Threading; using Xunit; #if USE_MDT_EVENTSOURCE using Microsoft.Diagnostics.Tracing; #else using System.Diagnostics.Tracing; #endif using System.Text.RegularExpressions; using System.Diagnostics; using SdtEventSources; namespace BasicEventSourceTests { public class TestsWriteEvent { #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. /// <summary> /// Tests WriteEvent using the manifest based mechanism. /// Tests the ETW path. /// </summary> [Fact] public void Test_WriteEvent_Manifest_ETW() { using (var listener = new EtwListener()) { Test_WriteEvent(listener, false); } } #endif // USE_ETW /// <summary> /// Tests WriteEvent using the manifest based mechanism. /// Tests bTraceListener path. /// </summary> [Fact] [ActiveIssue("dotnet/corefx #18806", TargetFrameworkMonikers.NetFramework)] public void Test_WriteEvent_Manifest_EventListener() { using (var listener = new EventListenerListener()) { Test_WriteEvent(listener, false); } } /// <summary> /// Tests WriteEvent using the manifest based mechanism. /// Tests bTraceListener path using events instead of virtual callbacks. /// </summary> [Fact] [ActiveIssue("dotnet/corefx #18806", TargetFrameworkMonikers.NetFramework)] public void Test_WriteEvent_Manifest_EventListener_UseEvents() { Test_WriteEvent(new EventListenerListener(true), false); } #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. /// <summary> /// Tests WriteEvent using the self-describing mechanism. /// Tests both the ETW and TraceListener paths. /// </summary> [Fact] public void Test_WriteEvent_SelfDescribing_ETW() { using (var listener = new EtwListener()) { Test_WriteEvent(listener, true); } } #endif /// <summary> /// Tests WriteEvent using the self-describing mechanism. /// Tests both the ETW and TraceListener paths. /// </summary> [Fact] [ActiveIssue("dotnet/corefx #18806", TargetFrameworkMonikers.NetFramework)] public void Test_WriteEvent_SelfDescribing_EventListener() { using (var listener = new EventListenerListener()) { Test_WriteEvent(listener, true); } } /// <summary> /// Tests WriteEvent using the self-describing mechanism. /// Tests both the ETW and TraceListener paths using events /// instead of virtual callbacks. /// </summary> [Fact] [ActiveIssue("dotnet/corefx #18806", TargetFrameworkMonikers.NetFramework)] public void Test_WriteEvent_SelfDescribing_EventListener_UseEvents() { Test_WriteEvent(new EventListenerListener(true), true); } [Fact] public void Test_WriteEvent_NoAttribute() { using (EventSourceNoAttribute es = new EventSourceNoAttribute()) { Listener el = new EventListenerListener(true); var tests = new List<SubTest>(); string arg = "a sample string"; tests.Add(new SubTest("Write/Basic/EventWith9Strings", delegate () { es.EventNoAttributes(arg); }, delegate (Event evt) { Assert.Equal(es.Name, evt.ProviderName); Assert.Equal("EventNoAttributes", evt.EventName); Assert.Equal(arg, (string)evt.PayloadValue(0, null)); })); EventTestHarness.RunTests(tests, el, es); } } /// <summary> /// Helper method for the two tests above. /// </summary> private void Test_WriteEvent(Listener listener, bool useSelfDescribingEvents) { using (var logger = new SdtEventSources.EventSourceTest(useSelfDescribingEvents)) { var tests = new List<SubTest>(); /*************************************************************************/ tests.Add(new SubTest("WriteEvent/Basic/EventII", delegate () { logger.EventII(10, 11); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventII", evt.EventName); Assert.Equal(evt.PayloadValue(0, "arg1"), 10); Assert.Equal(evt.PayloadValue(1, "arg2"), 11); })); /*************************************************************************/ tests.Add(new SubTest("WriteEvent/Basic/EventSS", delegate () { logger.EventSS("one", "two"); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventSS", evt.EventName); Assert.Equal(evt.PayloadValue(0, "arg1"), "one"); Assert.Equal(evt.PayloadValue(1, "arg2"), "two"); })); #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. /*************************************************************************/ tests.Add(new SubTest("Write/Basic/EventWithManyTypeArgs", delegate () { logger.EventWithManyTypeArgs("Hello", 1, 2, 3, 'a', 4, 5, 6, 7, (float)10.0, (double)11.0, logger.Guid); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithManyTypeArgs", evt.EventName); Assert.Equal("Hello", evt.PayloadValue(0, "msg")); Assert.Equal((float)10.0, evt.PayloadValue(9, "f")); Assert.Equal((double)11.0, evt.PayloadValue(10, "d")); Assert.Equal(logger.Guid, evt.PayloadValue(11, "guid")); })); #endif // USE_ETW /*************************************************************************/ tests.Add(new SubTest("Write/Basic/EventWith7Strings", delegate () { logger.EventWith7Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6"); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWith7Strings", evt.EventName); Assert.Equal("s0", (string)evt.PayloadValue(0, "s0")); Assert.Equal("s6", (string)evt.PayloadValue(6, "s6")); })); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/EventWith9Strings", delegate () { logger.EventWith9Strings("s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8"); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWith9Strings", evt.EventName); Assert.Equal("s0", (string)evt.PayloadValue(0, "s0")); Assert.Equal("s8", (string)evt.PayloadValue(8, "s8")); })); #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. /*************************************************************************/ tests.Add(new SubTest("Write/Activity/EventWithXferWeirdArgs", delegate () { var actid = Guid.NewGuid(); logger.EventWithXferWeirdArgs(actid, (IntPtr)128, true, SdtEventSources.MyLongEnum.LongVal1); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); // We log EventWithXferWeirdArgs in one case and // WorkWeirdArgs/Send in the other Assert.True(evt.EventName.Contains("WeirdArgs")); Assert.Equal("128", evt.PayloadValue(0, "iptr").ToString()); Assert.Equal(true, (bool)evt.PayloadValue(1, "b")); Assert.Equal((long)SdtEventSources.MyLongEnum.LongVal1, (long)evt.PayloadValue(2, "le")); })); #endif // USE_ETW /*************************************************************************/ /*************************** ENUM TESTING *******************************/ /*************************************************************************/ /*************************************************************************/ tests.Add(new SubTest("WriteEvent/Enum/EventEnum", delegate () { logger.EventEnum(SdtEventSources.MyColor.Blue); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventEnum", evt.EventName); Assert.Equal(1, (int)evt.PayloadValue(0, "x")); if (evt.IsEtw && !useSelfDescribingEvents) Assert.Equal("Blue", evt.PayloadString(0, "x")); })); tests.Add(new SubTest("WriteEvent/Enum/EventEnum1", delegate () { logger.EventEnum1(SdtEventSources.MyColor.Blue); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventEnum1", evt.EventName); Assert.Equal(1, (int)evt.PayloadValue(0, "x")); if (evt.IsEtw && !useSelfDescribingEvents) Assert.Equal("Blue", evt.PayloadString(0, "x")); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithIntIntString", delegate () { logger.EventWithIntIntString(10, 11, "test"); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithIntIntString", evt.EventName); Assert.Equal(evt.PayloadValue(0, "i1"), 10); Assert.Equal(evt.PayloadValue(1, "i2"), 11); Assert.Equal(evt.PayloadValue(2, "str"), "test"); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithIntLongString", delegate () { logger.EventWithIntLongString(10, (long)11, "test"); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithIntLongString", evt.EventName); Assert.Equal(evt.PayloadValue(0, "i1"), 10); Assert.Equal(evt.PayloadValue(1, "l1"), (long)11); Assert.Equal(evt.PayloadValue(2, "str"), "test"); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithString", delegate () { logger.EventWithString(null); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal(1, evt.PayloadCount); Assert.Equal("", evt.PayloadValue(0, null)); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithIntAndString", delegate () { logger.EventWithIntAndString(12, null); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal(2, evt.PayloadCount); Assert.Equal(12, evt.PayloadValue(0, null)); Assert.Equal("", evt.PayloadValue(1, null)); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithLongAndString", delegate () { logger.EventWithLongAndString(120L, null); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal(2, evt.PayloadCount); Assert.Equal(120L, evt.PayloadValue(0, null)); Assert.Equal("", evt.PayloadValue(1, null)); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndInt", delegate () { logger.EventWithStringAndInt(null, 12); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal(2, evt.PayloadCount); Assert.Equal("", evt.PayloadValue(0, null)); Assert.Equal(12, evt.PayloadValue(1, null)); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndIntAndInt", delegate () { logger.EventWithStringAndIntAndInt(null, 12, 13); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal(3, evt.PayloadCount); Assert.Equal("", evt.PayloadValue(0, null)); Assert.Equal(12, evt.PayloadValue(1, null)); Assert.Equal(13, evt.PayloadValue(2, null)); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndLong", delegate () { logger.EventWithStringAndLong(null, 120L); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal(2, evt.PayloadCount); Assert.Equal("", evt.PayloadValue(0, null)); Assert.Equal(120L, evt.PayloadValue(1, null)); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndString", delegate () { logger.EventWithStringAndString(null, null); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal(2, evt.PayloadCount); Assert.Equal("", evt.PayloadValue(0, null)); Assert.Equal("", evt.PayloadValue(1, null)); })); tests.Add(new SubTest("WriteEvent/Basic/EventWithStringAndStringAndString", delegate () { logger.EventWithStringAndStringAndString(null, null, null); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal(3, evt.PayloadCount); Assert.Equal("", evt.PayloadValue(0, null)); Assert.Equal("", evt.PayloadValue(1, null)); Assert.Equal("", evt.PayloadValue(2, null)); })); if (useSelfDescribingEvents) { tests.Add(new SubTest("WriteEvent/Basic/EventVarArgsWithString", delegate () { logger.EventVarArgsWithString(1, 2, 12, null); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal(4, evt.PayloadCount); Assert.Equal(1, evt.PayloadValue(0, null)); Assert.Equal(2, evt.PayloadValue(1, null)); Assert.Equal(12, evt.PayloadValue(2, null)); Assert.Equal("", evt.PayloadValue(3, null)); })); } // Probably belongs in the user TestUsersErrors.cs. if (!useSelfDescribingEvents) { tests.Add(new SubTest("WriteEvent/Basic/EventWithIncorrectNumberOfParameters", delegate () { logger.EventWithIncorrectNumberOfParameters("TestMessage", "TestPath", 10); }, delegate (List<Event> evts) { Assert.True(0 < evts.Count); // We give an error message in EventListener case but not the ETW case. if (1 < evts.Count) { Assert.Equal(2, evts.Count); Assert.Equal(logger.Name, evts[0].ProviderName); Assert.Equal("EventSourceMessage", evts[0].EventName); string errorMsg = evts[0].PayloadString(0, "message"); Assert.True(Regex.IsMatch(errorMsg, "called with 1.*defined with 3")); } int eventIdx = evts.Count - 1; Assert.Equal(logger.Name, evts[eventIdx].ProviderName); Assert.Equal("EventWithIncorrectNumberOfParameters", evts[eventIdx].EventName); Assert.Equal("{TestPath:10}TestMessage", evts[eventIdx].PayloadString(0, "message")); })); } // If you only wish to run one or several of the tests you can filter them here by // Uncommenting the following line. // tests = tests.FindAll(test => Regex.IsMatch(test.Name, "ventWithByteArray")); // Next run the same tests with the TraceLogging path. EventTestHarness.RunTests(tests, listener, logger); } } /**********************************************************************/ /// <summary> /// Tests sending complex data (class, arrays etc) from WriteEvent /// Tests the EventListener case /// </summary> [Fact] public void Test_WriteEvent_ComplexData_SelfDescribing_EventListener() { using (var listener = new EventListenerListener()) { Test_WriteEvent_ComplexData_SelfDescribing(listener); } } #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. /// <summary> /// Tests sending complex data (class, arrays etc) from WriteEvent /// Tests the EventListener case /// </summary> [Fact] public void Test_WriteEvent_ComplexData_SelfDescribing_ETW() { using (var listener = new EtwListener()) { Test_WriteEvent_ComplexData_SelfDescribing(listener); } } #endif // USE_ETW private void Test_WriteEvent_ComplexData_SelfDescribing(Listener listener) { using (var logger = new EventSourceTestSelfDescribingOnly()) { var tests = new List<SubTest>(); byte[] byteArray = { 0, 1, 2, 3 }; tests.Add(new SubTest("WriteEvent/SelfDescribingOnly/Byte[]", delegate () { logger.EventByteArrayInt(byteArray, 5); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventByteArrayInt", evt.EventName); var eventArray = evt.PayloadValue(0, "array"); Array.Equals(eventArray, byteArray); Assert.Equal(5, evt.PayloadValue(1, "anInt")); })); tests.Add(new SubTest("WriteEvent/SelfDescribingOnly/UserData", delegate () { logger.EventUserDataInt(new UserData() { x = 3, y = 8 }, 5); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventUserDataInt", evt.EventName); var aClass = (IDictionary<string, object>)evt.PayloadValue(0, "aClass"); Assert.Equal(3, (int)aClass["x"]); Assert.Equal(8, (int)aClass["y"]); Assert.Equal(5, evt.PayloadValue(1, "anInt")); })); // If you only wish to run one or several of the tests you can filter them here by // Uncommenting the following line. // tests = tests.FindAll(test => Regex.IsMatch(test.Name, "ventWithByteArray")); // Next run the same tests with the TraceLogging path. EventTestHarness.RunTests(tests, listener, logger); } } /**********************************************************************/ /// <summary> /// Tests sending complex data (class, arrays etc) from WriteEvent /// Uses Manifest format /// Tests the EventListener case /// </summary> [Fact] public void Test_WriteEvent_ByteArray_Manifest_EventListener() { using (var listener = new EventListenerListener()) { Test_WriteEvent_ByteArray(false, listener); } } /// <summary> /// Tests sending complex data (class, arrays etc) from WriteEvent /// Uses Manifest format /// Tests the EventListener case using events instead of virtual /// callbacks. /// </summary> [Fact] public void Test_WriteEvent_ByteArray_Manifest_EventListener_UseEvents() { Test_WriteEvent_ByteArray(false, new EventListenerListener(true)); } #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. /// <summary> /// Tests sending complex data (class, arrays etc) from WriteEvent /// Uses Manifest format /// Tests the EventListener case /// </summary> [Fact] public void Test_WriteEvent_ByteArray_Manifest_ETW() { using (var listener = new EtwListener()) { Test_WriteEvent_ByteArray(false, listener); } } #endif // USE_ETW /// <summary> /// Tests sending complex data (class, arrays etc) from WriteEvent /// Uses Self-Describing format /// Tests the EventListener case /// </summary> [Fact] public void Test_WriteEvent_ByteArray_SelfDescribing_EventListener() { using (var listener = new EventListenerListener()) { Test_WriteEvent_ByteArray(true, listener); } } #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. /// <summary> /// Tests sending complex data (class, arrays etc) from WriteEvent /// Uses Self-Describing format /// Tests the EventListener case /// </summary> [Fact] public void Test_WriteEvent_ByteArray_SelfDescribing_ETW() { using (var listener = new EtwListener()) { Test_WriteEvent_ByteArray(true, listener); } } #endif // USE_ETW private void Test_WriteEvent_ByteArray(bool useSelfDescribingEvents, Listener listener) { EventSourceSettings settings = EventSourceSettings.EtwManifestEventFormat; if (useSelfDescribingEvents) settings = EventSourceSettings.EtwSelfDescribingEventFormat; using (var logger = new EventSourceTestByteArray(settings)) { var tests = new List<SubTest>(); /*************************************************************************/ /**************************** byte[] TESTING *****************************/ /*************************************************************************/ // We only support arrays of any type with the SelfDescribing case. /*************************************************************************/ byte[] blob = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; tests.Add(new SubTest("Write/Array/EventWithByteArrayArg", delegate () { logger.EventWithByteArrayArg(blob, 1000); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithByteArrayArg", evt.EventName); if (evt.IsEventListener) { byte[] retBlob = (byte[])evt.PayloadValue(0, "blob"); Assert.NotNull(retBlob); Assert.True(Equal(blob, retBlob)); Assert.Equal(1000, (int)evt.PayloadValue(1, "n")); } })); if (!useSelfDescribingEvents) { /*************************************************************************/ tests.Add(new SubTest("Write/Array/NonEventCallingEventWithBytePtrArg", delegate () { logger.NonEventCallingEventWithBytePtrArg(blob, 2, 4, 1001); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithBytePtrArg", evt.EventName); if (evt.IsEtw) { Assert.Equal(2, evt.PayloadCount); byte[] retBlob = (byte[])evt.PayloadValue(0, "blob"); Assert.Equal(4, retBlob.Length); Assert.Equal(retBlob[0], blob[2]); Assert.Equal(retBlob[3], blob[2 + 3]); Assert.Equal(1001, (int)evt.PayloadValue(1, "n")); } else { Assert.Equal(3, evt.PayloadCount); byte[] retBlob = (byte[])evt.PayloadValue(1, "blob"); Assert.Equal(1001, (int)evt.PayloadValue(2, "n")); } })); } tests.Add(new SubTest("Write/Array/EventWithLongByteArray", delegate () { logger.EventWithLongByteArray(blob, 1000); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithLongByteArray", evt.EventName); Assert.Equal(2, evt.PayloadCount); byte[] retBlob = (byte[])evt.PayloadValue(0, "blob"); Assert.True(Equal(blob, retBlob)); Assert.Equal(1000, (long)evt.PayloadValue(1, "lng")); })); tests.Add(new SubTest("Write/Array/EventWithNullByteArray", delegate () { logger.EventWithByteArrayArg(null, 0); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithByteArrayArg", evt.EventName); if (evt.IsEventListener) { byte[] retBlob = (byte[])evt.PayloadValue(0, "blob"); Assert.Null(retBlob); Assert.Equal(0, (int)evt.PayloadValue(1, "n")); } })); tests.Add(new SubTest("Write/Array/EventWithEmptyByteArray", delegate () { logger.EventWithByteArrayArg(Array.Empty<byte>(), 0); }, delegate (Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithByteArrayArg", evt.EventName); Assert.Equal(2, evt.PayloadCount); byte[] retBlob = (byte[])evt.PayloadValue(0, "blob"); Assert.True(Equal(Array.Empty<byte>(), retBlob)); Assert.Equal(0, (int)evt.PayloadValue(1, "n")); })); // If you only wish to run one or several of the tests you can filter them here by // Uncommenting the following line. // tests = tests.FindAll(test => Regex.IsMatch(test.Name, "ventWithByteArray")); // Next run the same tests with the TraceLogging path. EventTestHarness.RunTests(tests, listener, logger); } } /**********************************************************************/ // Helper that compares two arrays for equality. private static bool Equal(byte[] blob1, byte[] blob2) { if (blob1.Length != blob2.Length) return false; for (int i = 0; i < blob1.Length; i++) if (blob1[i] != blob2[i]) return false; return true; } } [EventData] public class UserData { public int x { get; set; } public int y { get; set; } } /// <summary> /// Used to show the more complex data type that /// </summary> public sealed class EventSourceTestSelfDescribingOnly : EventSource { public EventSourceTestSelfDescribingOnly() : base(EventSourceSettings.EtwSelfDescribingEventFormat) { } public void EventByteArrayInt(byte[] array, int anInt) { WriteEvent(1, array, anInt); } public void EventUserDataInt(UserData aClass, int anInt) { WriteEvent(2, aClass, anInt); } } public sealed class EventSourceTestByteArray : EventSource { public EventSourceTestByteArray(EventSourceSettings settings) : base(settings) { } // byte[] args not supported on 4.5 [Event(1, Level = EventLevel.Informational, Message = "Int arg after byte array: {1}")] public void EventWithByteArrayArg(byte[] blob, int n) { WriteEvent(1, blob, n); } [NonEvent] public unsafe void NonEventCallingEventWithBytePtrArg(byte[] blob, int start, uint size, int n) { if (blob == null || start + size > blob.Length) throw new ArgumentException("start + size must be smaller than blob.Length"); fixed (byte* p = blob) EventWithBytePtrArg(size, p + start, n); } [Event(2, Level = EventLevel.Informational, Message = "Int arg after byte ptr: {2}")] public unsafe void EventWithBytePtrArg(uint blobSize, byte* blob, int n) { if (IsEnabled()) { { EventSource.EventData* descrs = stackalloc EventSource.EventData[3]; descrs[0].DataPointer = (IntPtr)(&blobSize); descrs[0].Size = 4; descrs[1].DataPointer = (IntPtr)blob; descrs[1].Size = (int)blobSize; descrs[2].Size = 4; descrs[2].DataPointer = (IntPtr)(&n); WriteEventCore(2, 3, descrs); } } } [Event(3, Level = EventLevel.Informational, Message = "long after byte array: {1}")] public void EventWithLongByteArray(byte[] blob, long lng) { WriteEvent(3, blob, lng); } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.IO; using System.Xml; using System.Xml.Serialization; using Hydra.Framework; using Hydra.Framework.Helpers; using Hydra.Framework.Java; using Hydra.Framework.Mapping.CoordinateSystems; using Hydra.Framework.Conversions; namespace Hydra.DomainModel { // //********************************************************************** /// <summary> /// Telemetry Details /// </summary> //********************************************************************** // [Serializable] [DataContract(Namespace = CommonConstants.DATA_NAMESPACE)] public class InternalTelemetry : AbstractInternalData { #region Member Variables // //********************************************************************** /// <summary> /// Measurement Class StateName (Java Class StateName - use MeasurementClassType) /// </summary> //********************************************************************** // [DataMember(Name = "MeasurementClass")] public string MeasurementClass { get; set; } // //********************************************************************** /// <summary> /// Type of Telemetry /// </summary> //********************************************************************** // [DataMember(Name = "Type")] public string Type { get; set; } // // ********************************************************************** /// <summary> /// Unit of Measurement /// </summary> // ********************************************************************** // [DataMember(Name = "Units")] public string Units { get; set; } // // ********************************************************************** /// <summary> /// Last Received Date Time /// </summary> // ********************************************************************** // [DataMember(Name = "LastReceivedTime")] public DateTime LastReceivedTime { get; set; } // // ********************************************************************** /// <summary> /// Last Received Sequence Number /// </summary> // ********************************************************************** // [DataMember(Name = "LastReceivedSequence")] public int LastReceivedSequence { get; set; } // // ********************************************************************** /// <summary> /// List of Telemetry Items /// </summary> // ********************************************************************** // [DataMember(Name = "TelemetryList")] public List<ITelemetry> TelemetryList { get; set; } // //********************************************************************** /// <summary> /// Measurement Class Type (This is dependant on the Measurement Class /// </summary> //********************************************************************** // [DataMember(Name = "Measurement")] public InternalDefaultTelemetryMeasurement Measurement { get; set; } // // ********************************************************************** /// <summary> /// Temperature /// </summary> // ********************************************************************** // [DataMember(Name = "Temperature")] public float Temperature { get; set; } // // ********************************************************************** /// <summary> /// Temperature Type /// </summary> // ********************************************************************** // [DataMember(Name = "TemperatureType")] public TemperatureType TemperatureType { get; set; } #endregion #region Constructors // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="InternalTelemetry"/> class. /// </summary> // ********************************************************************** // public InternalTelemetry() : base(InternalLocationServiceType.Internal) { } // //********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="T:InternalTelemetry"/> class. /// </summary> /// <param name="changedOn">The changed on.</param> /// <param name="objectId">The object id.</param> /// <param name="parentId">The parent id.</param> /// <param name="measurementClass">The measurement class.</param> /// <param name="type">The type.</param> /// <param name="measurement">The measurement.</param> /// <param name="units">The units.</param> /// <param name="lastReceivedTime">The last received time.</param> /// <param name="lastReceivedSequence">The last received sequence.</param> //********************************************************************** // public InternalTelemetry(DateTime changedOn, int objectId, int parentId, string measurementClass, string type, InternalDefaultTelemetryMeasurement measurement, string units, DateTime lastReceivedTime, int lastReceivedSequence) : base(InternalLocationServiceType.Internal, objectId, parentId, changedOn) { MeasurementClass = measurementClass; Type = type; Units = units; Measurement = measurement; LastReceivedTime = lastReceivedTime; LastReceivedSequence = lastReceivedSequence; } // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="InternalTelemetry"/> class. /// </summary> /// <param name="changedOn">The changed on.</param> /// <param name="objectId">The object id.</param> /// <param name="parentId">The parent id.</param> /// <param name="temperature">The temperature.</param> /// <param name="temperatureType">Type of the temperature.</param> // ********************************************************************** // public InternalTelemetry(DateTime changedOn, int objectId, int parentId, float temperature, TemperatureType temperatureType) : base(InternalLocationServiceType.Internal, objectId, parentId, changedOn) { MeasurementClass = string.Empty; Type = string.Empty; Units = string.Empty; Measurement = null; LastReceivedTime = changedOn; LastReceivedSequence = -1; Temperature = temperature; TemperatureType = temperatureType; } #endregion #region Properties #endregion #region Private Methods #endregion #region Public Methods // // ********************************************************************** /// <summary> /// Adds the telemetry. /// </summary> /// <param name="item">The item.</param> // ********************************************************************** // public void AddTelemetry(ITelemetry item) { try { Check.That(item, Is.Not.Null); // // Check and/or create the telemetry list // if (TelemetryList == null) TelemetryList = new List<ITelemetry>(); // // Add the item // TelemetryList.Add(item); } catch (Exception ex) { Log.Exception(ex); } } #endregion } }
using EdiEngine.Common.Enums; using EdiEngine.Common.Definitions; using EdiEngine.Standards.X12_004010.Segments; namespace EdiEngine.Standards.X12_004010.Maps { public class M_842 : MapLoop { public M_842() : base(null) { Content.AddRange(new MapBaseEntity[] { new BNR() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_MEA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PWK(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_HL(this) { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 999999 }, }); } //1000 public class L_MEA : MapLoop { public L_MEA(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new MEA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //2000 public class L_PWK : MapLoop { public L_PWK(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PWK() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //3000 public class L_N1 : MapLoop { public L_N1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4000 public class L_HL : MapLoop { public L_HL(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new HL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PRS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new CS() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new TMD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PSD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new PWK() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LM(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_MEA_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_FA1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_SPS(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NCD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4100 public class L_LM : MapLoop { public L_LM(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4200 public class L_MEA_1 : MapLoop { public L_MEA_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new MEA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4300 public class L_FA1 : MapLoop { public L_FA1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new FA1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new FA2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4400 public class L_SPS : MapLoop { public L_SPS(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new SPS() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PSD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new L_MEA_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_STA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4410 public class L_MEA_2 : MapLoop { public L_MEA_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new MEA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4420 public class L_STA : MapLoop { public L_STA(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new STA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4500 public class L_NCD : MapLoop { public L_NCD(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NCD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new MEA() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new RC() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_EFI(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LM_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_NCA(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_FA1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4510 public class L_EFI : MapLoop { public L_EFI(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new EFI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new BIN() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, }); } } //4520 public class L_N1_1 : MapLoop { public L_N1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4530 public class L_LM_1 : MapLoop { public L_LM_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4540 public class L_NCA : MapLoop { public L_NCA(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new NCA() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_PWK_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_N1_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new L_LM_2(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4541 public class L_PWK_1 : MapLoop { public L_PWK_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new PWK() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4542 public class L_N1_2 : MapLoop { public L_N1_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 }, new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 }, new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, new PER() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4543 public class L_LM_2 : MapLoop { public L_LM_2(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new LM() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new LQ() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } //4550 public class L_FA1_1 : MapLoop { public L_FA1_1(MapLoop parentLoop) : base(parentLoop) { Content.AddRange(new MapBaseEntity[] { new FA1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 }, new FA2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 }, }); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Security; using System.Text; using System.Threading; using System.Web; using System.Web.Compilation; using NUnit.Framework; using SqlCE4Umbraco; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Tests; using Umbraco.Tests.TestHelpers; using Umbraco.Web.BaseRest; using umbraco; using umbraco.DataLayer; using umbraco.MacroEngines; using umbraco.businesslogic; using umbraco.cms.businesslogic; using umbraco.editorControls.tags; using umbraco.interfaces; using umbraco.uicontrols; namespace Umbraco.Tests { /// <summary> /// Tests for typefinder /// </summary> [TestFixture] public class TypeFinderTests { /// <summary> /// List of assemblies to scan /// </summary> private Assembly[] _assemblies; [SetUp] public void Initialize() { TestHelper.SetupLog4NetForTests(); _assemblies = 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(Tag).Assembly, typeof(global::UmbracoExamine.BaseUmbracoIndexer).Assembly }; } [Test] public void Find_Class_Of_Type_With_Attribute() { var typesFound = TypeFinder.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies); Assert.AreEqual(2, typesFound.Count()); } [Test] public void Find_Classes_Of_Type() { var typesFound = TypeFinder.FindClassesOfType<IApplicationStartupHandler>(_assemblies); var originalTypesFound = TypeFinderOriginal.FindClassesOfType<IApplicationStartupHandler>(_assemblies); Assert.AreEqual(originalTypesFound.Count(), typesFound.Count()); Assert.AreEqual(5, typesFound.Count()); Assert.AreEqual(5, originalTypesFound.Count()); } [Test] public void Find_Classes_With_Attribute() { var typesFound = TypeFinder.FindClassesWithAttribute<RestExtensionAttribute>(_assemblies); Assert.AreEqual(1, typesFound.Count()); } [Ignore] [Test] public void Benchmark_Original_Finder() { using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting test", "Finished test")) { using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfType", "Finished FindClassesOfType")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinderOriginal.FindClassesOfType<DisposableObject>(_assemblies).Count(), 0); } } using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinderOriginal.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies).Count(), 0); } } using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinderOriginal.FindClassesWithAttribute<XsltExtensionAttribute>(_assemblies).Count(), 0); } } } } [Ignore] [Test] public void Benchmark_New_Finder() { using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting test", "Finished test")) { using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfType", "Finished FindClassesOfType")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinder.FindClassesOfType<DisposableObject>(_assemblies).Count(), 0); } } using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesOfTypeWithAttribute", "Finished FindClassesOfTypeWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinder.FindClassesOfTypeWithAttribute<TestEditor, MyTestAttribute>(_assemblies).Count(), 0); } } using (DisposableTimer.TraceDuration<TypeFinderTests>("Starting FindClassesWithAttribute", "Finished FindClassesWithAttribute")) { for (var i = 0; i < 1000; i++) { Assert.Greater(TypeFinder.FindClassesWithAttribute<XsltExtensionAttribute>(_assemblies).Count(), 0); } } } } public class MyTag : ITag { public int Id { get; private set; } public string TagCaption { get; private set; } public string Group { get; private set; } } public class MySuperTag : MyTag { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class MyTestAttribute : Attribute { } public abstract class TestEditor { } [MyTestAttribute] public class BenchmarkTestEditor : TestEditor { } [MyTestAttribute] public class MyOtherTestEditor : TestEditor { } //USED FOR THE ABOVE TESTS // see this issue for details: http://issues.umbraco.org/issue/U4-1187 internal static class TypeFinderOriginal { private static readonly ConcurrentBag<Assembly> LocalFilteredAssemblyCache = new ConcurrentBag<Assembly>(); private static readonly ReaderWriterLockSlim LocalFilteredAssemblyCacheLocker = new ReaderWriterLockSlim(); private static ReadOnlyCollection<Assembly> _allAssemblies = null; private static ReadOnlyCollection<Assembly> _binFolderAssemblies = null; private static readonly ReaderWriterLockSlim Locker = new ReaderWriterLockSlim(); /// <summary> /// lazily load a reference to all assemblies and only local assemblies. /// This is a modified version of: http://www.dominicpettifer.co.uk/Blog/44/how-to-get-a-reference-to-all-assemblies-in-the--bin-folder /// </summary> /// <remarks> /// We do this because we cannot use AppDomain.Current.GetAssemblies() as this will return only assemblies that have been /// loaded in the CLR, not all assemblies. /// See these threads: /// http://issues.umbraco.org/issue/U5-198 /// http://stackoverflow.com/questions/3552223/asp-net-appdomain-currentdomain-getassemblies-assemblies-missing-after-app /// http://stackoverflow.com/questions/2477787/difference-between-appdomain-getassemblies-and-buildmanager-getreferencedassembl /// </remarks> internal static IEnumerable<Assembly> GetAllAssemblies() { if (_allAssemblies == null) { using (new WriteLock(Locker)) { List<Assembly> assemblies = null; try { var isHosted = HttpContext.Current != null; try { if (isHosted) { assemblies = new List<Assembly>(BuildManager.GetReferencedAssemblies().Cast<Assembly>()); } } catch (InvalidOperationException e) { if (!(e.InnerException is SecurityException)) throw; } if (assemblies == null) { //NOTE: we cannot use AppDomain.CurrentDomain.GetAssemblies() because this only returns assemblies that have // already been loaded in to the app domain, instead we will look directly into the bin folder and load each one. var binFolder = Assembly.GetExecutingAssembly().GetAssemblyFile().Directory; var binAssemblyFiles = Directory.GetFiles(binFolder.FullName, "*.dll", SearchOption.TopDirectoryOnly).ToList(); assemblies = new List<Assembly>(); foreach (var a in binAssemblyFiles) { try { var assName = AssemblyName.GetAssemblyName(a); var ass = Assembly.Load(assName); assemblies.Add(ass); } catch (Exception e) { if (e is SecurityException || e is BadImageFormatException) { //swallow these exceptions } else { throw; } } } } //if for some reason they are still no assemblies, then use the AppDomain to load in already loaded assemblies. if (!assemblies.Any()) { assemblies.AddRange(AppDomain.CurrentDomain.GetAssemblies().ToList()); } //here we are trying to get the App_Code assembly var fileExtensions = new[] { ".cs", ".vb" }; //only vb and cs files are supported var appCodeFolder = new DirectoryInfo(IOHelper.MapPath(IOHelper.ResolveUrl("~/App_code"))); //check if the folder exists and if there are any files in it with the supported file extensions if (appCodeFolder.Exists && (fileExtensions.Any(x => appCodeFolder.GetFiles("*" + x).Any()))) { var appCodeAssembly = Assembly.Load("App_Code"); if (!assemblies.Contains(appCodeAssembly)) // BuildManager will find App_Code already assemblies.Add(appCodeAssembly); } //now set the _allAssemblies _allAssemblies = new ReadOnlyCollection<Assembly>(assemblies); } catch (InvalidOperationException e) { if (!(e.InnerException is SecurityException)) throw; _binFolderAssemblies = _allAssemblies; } } } return _allAssemblies; } /// <summary> /// Returns only assemblies found in the bin folder that have been loaded into the app domain. /// </summary> /// <returns></returns> /// <remarks> /// This will be used if we implement App_Plugins from Umbraco v5 but currently it is not used. /// </remarks> internal static IEnumerable<Assembly> GetBinAssemblies() { if (_binFolderAssemblies == null) { using (new WriteLock(Locker)) { var assemblies = GetAssembliesWithKnownExclusions().ToArray(); var binFolder = Assembly.GetExecutingAssembly().GetAssemblyFile().Directory; var binAssemblyFiles = Directory.GetFiles(binFolder.FullName, "*.dll", SearchOption.TopDirectoryOnly).ToList(); var domainAssemblyNames = binAssemblyFiles.Select(AssemblyName.GetAssemblyName); var safeDomainAssemblies = new List<Assembly>(); var binFolderAssemblies = new List<Assembly>(); foreach (var a in assemblies) { try { //do a test to see if its queryable in med trust var assemblyFile = a.GetAssemblyFile(); safeDomainAssemblies.Add(a); } catch (SecurityException) { //we will just ignore this because this will fail //in medium trust for system assemblies, we get an exception but we just want to continue until we get to //an assembly that is ok. } } foreach (var assemblyName in domainAssemblyNames) { try { var foundAssembly = safeDomainAssemblies.FirstOrDefault(a => a.GetAssemblyFile() == assemblyName.GetAssemblyFile()); if (foundAssembly != null) { binFolderAssemblies.Add(foundAssembly); } } catch (SecurityException) { //we will just ignore this because if we are trying to do a call to: // AssemblyName.ReferenceMatchesDefinition(a.GetName(), assemblyName))) //in medium trust for system assemblies, we get an exception but we just want to continue until we get to //an assembly that is ok. } } _binFolderAssemblies = new ReadOnlyCollection<Assembly>(binFolderAssemblies); } } return _binFolderAssemblies; } /// <summary> /// Return a list of found local Assemblies excluding the known assemblies we don't want to scan /// and exluding the ones passed in and excluding the exclusion list filter, the results of this are /// cached for perforance reasons. /// </summary> /// <param name="excludeFromResults"></param> /// <returns></returns> internal static IEnumerable<Assembly> GetAssembliesWithKnownExclusions( IEnumerable<Assembly> excludeFromResults = null) { if (LocalFilteredAssemblyCache.Any()) return LocalFilteredAssemblyCache; using (new WriteLock(LocalFilteredAssemblyCacheLocker)) { var assemblies = GetFilteredAssemblies(excludeFromResults, KnownAssemblyExclusionFilter); assemblies.ForEach(LocalFilteredAssemblyCache.Add); } return LocalFilteredAssemblyCache; } /// <summary> /// Return a list of found local Assemblies and exluding the ones passed in and excluding the exclusion list filter /// </summary> /// <param name="excludeFromResults"></param> /// <param name="exclusionFilter"></param> /// <returns></returns> private static IEnumerable<Assembly> GetFilteredAssemblies( IEnumerable<Assembly> excludeFromResults = null, string[] exclusionFilter = null) { if (excludeFromResults == null) excludeFromResults = new List<Assembly>(); if (exclusionFilter == null) exclusionFilter = new string[] { }; return GetAllAssemblies() .Where(x => !excludeFromResults.Contains(x) && !x.GlobalAssemblyCache && !exclusionFilter.Any(f => x.FullName.StartsWith(f))); } /// <summary> /// this is our assembly filter to filter out known types that def dont contain types we'd like to find or plugins /// </summary> /// <remarks> /// NOTE the comma vs period... comma delimits the name in an Assembly FullName property so if it ends with comma then its an exact name match /// </remarks> internal static readonly string[] KnownAssemblyExclusionFilter = new[] { "mscorlib,", "System.", "Antlr3.", "Autofac.", "Autofac,", "Castle.", "ClientDependency.", "DataAnnotationsExtensions.", "DataAnnotationsExtensions,", "Dynamic,", "HtmlDiff,", "Iesi.Collections,", "log4net,", "Microsoft.", "Newtonsoft.", "NHibernate.", "NHibernate,", "NuGet.", "RouteDebugger,", "SqlCE4Umbraco,", "umbraco.datalayer,", "umbraco.interfaces,", "umbraco.providers,", "Umbraco.Web.UI,", "umbraco.webservices", "Lucene.", "Examine,", "Examine.", "ServiceStack.", "MySql.", "HtmlAgilityPack.", "TidyNet.", "ICSharpCode.", "CookComputing.", /* Mono */ "MonoDevelop.NUnit" }; public static IEnumerable<Type> FindClassesOfTypeWithAttribute<T, TAttribute>() where TAttribute : Attribute { return FindClassesOfTypeWithAttribute<T, TAttribute>(GetAssembliesWithKnownExclusions(), true); } public static IEnumerable<Type> FindClassesOfTypeWithAttribute<T, TAttribute>(IEnumerable<Assembly> assemblies) where TAttribute : Attribute { return FindClassesOfTypeWithAttribute<T, TAttribute>(assemblies, true); } public static IEnumerable<Type> FindClassesOfTypeWithAttribute<T, TAttribute>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) where TAttribute : Attribute { if (assemblies == null) throw new ArgumentNullException("assemblies"); var l = new List<Type>(); foreach (var a in assemblies) { var types = from t in GetTypesWithFormattedException(a) where !t.IsInterface && typeof(T).IsAssignableFrom(t) && t.GetCustomAttributes<TAttribute>(false).Any() && (!onlyConcreteClasses || (t.IsClass && !t.IsAbstract)) select t; l.AddRange(types); } return l; } /// <summary> /// Searches all filtered local assemblies specified for classes of the type passed in. /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IEnumerable<Type> FindClassesOfType<T>() { return FindClassesOfType<T>(GetAssembliesWithKnownExclusions(), true); } /// <summary> /// Returns all types found of in the assemblies specified of type T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies"></param> /// <param name="onlyConcreteClasses"></param> /// <returns></returns> public static IEnumerable<Type> FindClassesOfType<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) { if (assemblies == null) throw new ArgumentNullException("assemblies"); return GetAssignablesFromType<T>(assemblies, onlyConcreteClasses); } /// <summary> /// Returns all types found of in the assemblies specified of type T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies"></param> /// <returns></returns> public static IEnumerable<Type> FindClassesOfType<T>(IEnumerable<Assembly> assemblies) { return FindClassesOfType<T>(assemblies, true); } /// <summary> /// Finds the classes with attribute. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies">The assemblies.</param> /// <param name="onlyConcreteClasses">if set to <c>true</c> only concrete classes.</param> /// <returns></returns> public static IEnumerable<Type> FindClassesWithAttribute<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) where T : Attribute { return FindClassesWithAttribute(typeof(T), assemblies, onlyConcreteClasses); } /// <summary> /// Finds the classes with attribute. /// </summary> /// <param name="type">The attribute type </param> /// <param name="assemblies">The assemblies.</param> /// <param name="onlyConcreteClasses">if set to <c>true</c> only concrete classes.</param> /// <returns></returns> public static IEnumerable<Type> FindClassesWithAttribute(Type type, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) { if (assemblies == null) throw new ArgumentNullException("assemblies"); if (!TypeHelper.IsTypeAssignableFrom<Attribute>(type)) throw new ArgumentException("The type specified: " + type + " is not an Attribute type"); var l = new List<Type>(); foreach (var a in assemblies) { var types = from t in GetTypesWithFormattedException(a) where !t.IsInterface && t.GetCustomAttributes(type, false).Any() && (!onlyConcreteClasses || (t.IsClass && !t.IsAbstract)) select t; l.AddRange(types); } return l; } /// <summary> /// Finds the classes with attribute. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies">The assemblies.</param> /// <returns></returns> public static IEnumerable<Type> FindClassesWithAttribute<T>(IEnumerable<Assembly> assemblies) where T : Attribute { return FindClassesWithAttribute<T>(assemblies, true); } /// <summary> /// Finds the classes with attribute in filtered local assemblies /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static IEnumerable<Type> FindClassesWithAttribute<T>() where T : Attribute { return FindClassesWithAttribute<T>(GetAssembliesWithKnownExclusions()); } #region Private methods /// <summary> /// Gets a collection of assignables of type T from a collection of assemblies /// </summary> /// <typeparam name="T"></typeparam> /// <param name="assemblies"></param> /// <param name="onlyConcreteClasses"></param> /// <returns></returns> private static IEnumerable<Type> GetAssignablesFromType<T>(IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) { return GetTypes(typeof(T), assemblies, onlyConcreteClasses); } private static IEnumerable<Type> GetTypes(Type assignTypeFrom, IEnumerable<Assembly> assemblies, bool onlyConcreteClasses) { var l = new List<Type>(); foreach (var a in assemblies) { var types = from t in GetTypesWithFormattedException(a) where !t.IsInterface && assignTypeFrom.IsAssignableFrom(t) && (!onlyConcreteClasses || (t.IsClass && !t.IsAbstract)) select t; l.AddRange(types); } return l; } private static IEnumerable<Type> GetTypesWithFormattedException(Assembly a) { //if the assembly is dynamic, do not try to scan it if (a.IsDynamic) return Enumerable.Empty<Type>(); try { return a.GetExportedTypes(); } catch (ReflectionTypeLoadException ex) { var sb = new StringBuilder(); sb.AppendLine("Could not load types from assembly " + a.FullName + ", errors:"); foreach (var loaderException in ex.LoaderExceptions.WhereNotNull()) { sb.AppendLine("Exception: " + loaderException.ToString()); } throw new ReflectionTypeLoadException(ex.Types, ex.LoaderExceptions, sb.ToString()); } } #endregion } } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. namespace AutoReporter { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.button1 = new System.Windows.Forms.Button(); this.checkbox1 = new System.Windows.Forms.CheckBox(); this.checkbox2 = new System.Windows.Forms.CheckBox(); this.checkbox3 = new System.Windows.Forms.CheckBox(); this.checkbox4 = new System.Windows.Forms.CheckBox(); this.checkbox5 = new System.Windows.Forms.CheckBox(); this.checkbox6 = new System.Windows.Forms.CheckBox(); this.checkbox7 = new System.Windows.Forms.CheckBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.textBox2 = new System.Windows.Forms.TextBox(); this.AppErrorNotifyInfo = new System.Windows.Forms.NotifyIcon(this.components); this.textBox3 = new System.Windows.Forms.TextBox(); this.ButtonPanel = new System.Windows.Forms.Panel(); this.MainPanel = new System.Windows.Forms.Panel(); this.ButtonPanel.SuspendLayout(); this.MainPanel.SuspendLayout(); this.SuspendLayout(); // // button1 // this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.button1.Location = new System.Drawing.Point(602, 3); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 2; this.button1.Text = "OK"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // checkbox1 // this.checkbox1.Checked = true; this.checkbox1.CheckState = System.Windows.Forms.CheckState.Checked; this.checkbox1.Location = new System.Drawing.Point(91, 164); this.checkbox1.Name = "checkbox1"; this.checkbox1.Size = new System.Drawing.Size(85, 18); this.checkbox1.TabIndex = 3; this.checkbox1.Text = "Functions"; this.checkbox1.Click += new System.EventHandler(this.checkbox_Click); // // checkbox2 // this.checkbox2.Location = new System.Drawing.Point(176, 164); this.checkbox2.Name = "checkbox2"; this.checkbox2.Size = new System.Drawing.Size(85, 18); this.checkbox2.TabIndex = 4; this.checkbox2.Text = "Addresses"; this.checkbox2.Click += new System.EventHandler(this.checkbox_Click); // // checkbox3 // this.checkbox3.Checked = true; this.checkbox3.CheckState = System.Windows.Forms.CheckState.Checked; this.checkbox3.Location = new System.Drawing.Point(267, 164); this.checkbox3.Name = "checkbox3"; this.checkbox3.Size = new System.Drawing.Size(85, 18); this.checkbox3.TabIndex = 5; this.checkbox3.Text = "Files:Lines"; this.checkbox3.Click += new System.EventHandler(this.checkbox_Click); // // checkbox4 // this.checkbox4.Location = new System.Drawing.Point(358, 164); this.checkbox4.Name = "checkbox4"; this.checkbox4.Size = new System.Drawing.Size(85, 18); this.checkbox4.TabIndex = 6; this.checkbox4.Text = "Modules"; this.checkbox4.Click += new System.EventHandler(this.checkbox_Click); // // checkbox5 // this.checkbox5.Checked = true; this.checkbox5.CheckState = System.Windows.Forms.CheckState.Checked; this.checkbox5.Location = new System.Drawing.Point(431, 164); this.checkbox5.Name = "checkbox5"; this.checkbox5.Size = new System.Drawing.Size(85, 18); this.checkbox5.TabIndex = 7; this.checkbox5.Text = "Shortnames"; this.checkbox5.Click += new System.EventHandler(this.checkbox_Click); // // checkbox6 // this.checkbox6.Location = new System.Drawing.Point(516, 164); this.checkbox6.Name = "checkbox6"; this.checkbox6.Size = new System.Drawing.Size(85, 18); this.checkbox6.TabIndex = 8; this.checkbox6.Text = "Unknowns"; this.checkbox6.Click += new System.EventHandler(this.checkbox_Click); // // checkbox7 // this.checkbox7.Location = new System.Drawing.Point(607, 164); this.checkbox7.Name = "checkbox7"; this.checkbox7.Size = new System.Drawing.Size(85, 18); this.checkbox7.TabIndex = 9; this.checkbox7.Text = "Original"; this.checkbox7.Click += new System.EventHandler(this.checkbox_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(12, 86); this.textBox1.MaxLength = 1024; this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(665, 57); this.textBox1.TabIndex = 1; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(12, 70); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(416, 13); this.label1.TabIndex = 13; this.label1.Text = "Please describe in detail what you were doing when the crash occurred:"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(12, 166); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(65, 13); this.label2.TabIndex = 12; this.label2.Text = "CallStack:"; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(12, 11); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(236, 13); this.label4.TabIndex = 11; this.label4.Text = "Please provide a summary for this crash:"; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(12, 27); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(371, 20); this.textBox2.TabIndex = 0; // // AppErrorNotifyInfo // this.AppErrorNotifyInfo.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Warning; this.AppErrorNotifyInfo.BalloonTipTitle = "Unreal AutoReporter"; this.AppErrorNotifyInfo.Icon = ((System.Drawing.Icon)(resources.GetObject("AppErrorNotifyInfo.Icon"))); this.AppErrorNotifyInfo.Visible = true; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(12, 182); this.textBox3.Multiline = true; this.textBox3.Name = "textBox3"; this.textBox3.ReadOnly = true; this.textBox3.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.textBox3.Size = new System.Drawing.Size(665, 38); this.textBox3.TabIndex = 10; this.textBox3.Text = "hello worldhello worldhello worldhello worldhello worldhello world"; this.textBox3.WordWrap = false; // // ButtonPanel // this.ButtonPanel.BackColor = System.Drawing.SystemColors.Control; this.ButtonPanel.Controls.Add(this.button1); this.ButtonPanel.Dock = System.Windows.Forms.DockStyle.Bottom; this.ButtonPanel.Location = new System.Drawing.Point(0, 226); this.ButtonPanel.Name = "ButtonPanel"; this.ButtonPanel.Size = new System.Drawing.Size(689, 31); this.ButtonPanel.TabIndex = 14; // // MainPanel // this.MainPanel.Controls.Add(this.checkbox7); this.MainPanel.Controls.Add(this.textBox1); this.MainPanel.Controls.Add(this.textBox2); this.MainPanel.Controls.Add(this.label1); this.MainPanel.Controls.Add(this.label4); this.MainPanel.Controls.Add(this.checkbox5); this.MainPanel.Controls.Add(this.checkbox6); this.MainPanel.Controls.Add(this.checkbox4); this.MainPanel.Controls.Add(this.checkbox3); this.MainPanel.Controls.Add(this.checkbox2); this.MainPanel.Controls.Add(this.checkbox1); this.MainPanel.Controls.Add(this.textBox3); this.MainPanel.Controls.Add(this.label2); this.MainPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.MainPanel.Location = new System.Drawing.Point(0, 0); this.MainPanel.Name = "MainPanel"; this.MainPanel.Size = new System.Drawing.Size(689, 257); this.MainPanel.TabIndex = 15; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(689, 257); this.ControlBox = false; this.Controls.Add(this.ButtonPanel); this.Controls.Add(this.MainPanel); this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "."; this.TopMost = true; this.Resize += new System.EventHandler(this.form1_Resize); this.ButtonPanel.ResumeLayout(false); this.MainPanel.ResumeLayout(false); this.MainPanel.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.CheckBox checkbox1; private System.Windows.Forms.CheckBox checkbox2; private System.Windows.Forms.CheckBox checkbox3; private System.Windows.Forms.CheckBox checkbox4; private System.Windows.Forms.CheckBox checkbox5; private System.Windows.Forms.CheckBox checkbox6; private System.Windows.Forms.CheckBox checkbox7; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.NotifyIcon AppErrorNotifyInfo; private System.Windows.Forms.Panel ButtonPanel; private System.Windows.Forms.Panel MainPanel; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using Apache.Ignite.Core.Discovery; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Static; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Tests.Process; using NUnit.Framework; /// <summary> /// Test utility methods. /// </summary> public static class TestUtils { /** Indicates long running and/or memory/cpu intensive test. */ public const string CategoryIntensive = "LONG_TEST"; /** */ public const int DfltBusywaitSleepInterval = 200; /** */ private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess ? new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms1g", "-Xmx4g", "-ea" } : new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms512m", "-Xmx512m", "-ea", "-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000" }; /** */ private static readonly IList<string> JvmDebugOpts = new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005" }; /** */ public static bool JvmDebug = true; /** */ [ThreadStatic] private static Random _random; /** */ private static int _seed = Environment.TickCount; /// <summary> /// Kill Ignite processes. /// </summary> public static void KillProcesses() { IgniteProcess.KillAll(); } /// <summary> /// /// </summary> public static Random Random { get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); } } /// <summary> /// /// </summary> /// <returns></returns> public static IList<string> TestJavaOptions() { IList<string> ops = new List<string>(TestJvmOpts); if (JvmDebug) { foreach (string opt in JvmDebugOpts) ops.Add(opt); } return ops; } /// <summary> /// /// </summary> /// <returns></returns> public static string CreateTestClasspath() { return Classpath.CreateClasspath(forceTestClasspath: true); } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> public static void RunMultiThreaded(Action action, int threadNum) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { action(); } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> /// <param name="duration">Duration of test execution in seconds</param> public static void RunMultiThreaded(Action action, int threadNum, int duration) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); bool stop = false; for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { while (true) { Thread.MemoryBarrier(); // ReSharper disable once AccessToModifiedClosure if (stop) break; action(); } } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); Thread.Sleep(duration * 1000); stop = true; Thread.MemoryBarrier(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// Wait for particular topology size. /// </summary> /// <param name="grid">Grid.</param> /// <param name="size">Size.</param> /// <param name="timeout">Timeout.</param> /// <returns> /// <c>True</c> if topology took required size. /// </returns> public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000) { int left = timeout; while (true) { if (grid.GetCluster().GetNodes().Count != size) { if (left > 0) { Thread.Sleep(100); left -= 100; } else break; } else return true; } return false; } /// <summary> /// Asserts that the handle registry is empty. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, 0, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, expectedCount, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="grid">The grid to check.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="timeout">Timeout, in milliseconds.</param> public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout) { var handleRegistry = ((Ignite)grid).HandleRegistry; if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout)) return; var items = handleRegistry.GetItems(); if (items.Any()) Assert.Fail("HandleRegistry is not empty in grid '{0}':\n '{1}'", grid.Name, items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y)); } /// <summary> /// Waits for condition, polling in busy wait loop. /// </summary> /// <param name="cond">Condition.</param> /// <param name="timeout">Timeout, in milliseconds.</param> /// <returns>True if condition predicate returned true within interval; false otherwise.</returns> public static bool WaitForCondition(Func<bool> cond, int timeout) { if (timeout <= 0) return cond(); var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval); while (DateTime.Now < maxTime) { if (cond()) return true; Thread.Sleep(DfltBusywaitSleepInterval); } return false; } /// <summary> /// Gets the static discovery. /// </summary> public static IDiscoverySpi GetStaticDiscovery() { return new TcpDiscoverySpi { IpFinder = new TcpDiscoveryStaticIpFinder { Endpoints = new[] { "127.0.0.1:47500" } }, SocketTimeout = TimeSpan.FromSeconds(0.3) }; } /// <summary> /// Gets the default code-based test configuration. /// </summary> public static IgniteConfiguration GetTestConfiguration() { return new IgniteConfiguration { DiscoverySpi = GetStaticDiscovery(), Localhost = "127.0.0.1", JvmOptions = TestJavaOptions(), JvmClasspath = CreateTestClasspath() }; } } }
using NUnit.Framework; using GoldAddin; using MonoDevelop.Ide.CodeCompletion; namespace UnitTests { [TestFixture] public class CompletionProviderTest { [Test] public void NonTerminalListTest() { string text = "<s-Expression> ::= <Quote> Atom\r\n" + //index: 0-32 "\t| <Quote> '(' <Series> ')'\r\n" + //index: 33-61 "errorline<Value\r\n"+ //index: 62- 78 "<"; var target = new CompletionProvider (text); int nonTermCount = 3; //<s-Expression>, <Quote>, and <Series> //case 1: < at new line var completionList = target.GetCompletionList (79); Assert.AreEqual (nonTermCount, completionList.Count); //case 2: < inside rule declaration (first line) completionList = target.GetCompletionList (19); Assert.AreEqual(nonTermCount+1, completionList.Count); //+1 for <> //case 3: < inside rule declaration (continuation line) completionList = target.GetCompletionList (36); Assert.AreEqual(nonTermCount+1, completionList.Count); //+1 for <> //case 4: < inside bad syntax line completionList = target.GetCompletionList (71); Assert.AreEqual(null, completionList); } [Test] public void InCommentsTest() { string text = "!*<*!\"\r\n" + "!*{*!{<value>::=<expr>\r\n" + "\t <\r\n"; var target = new CompletionProvider (text); //completion should not show up while inside a comment var completionList = target.GetCompletionList (2); Assert.IsNull (completionList); completionList = target.GetCompletionList (10); Assert.IsNull (completionList); text = "<A>::=a !<A>"; target = new CompletionProvider (text); completionList = target.GetCompletionList (9); Assert.IsNull (completionList); } [Test] public void TerminalListTest() { string text = "while = 'while'\n"+ //index 0-15 "integer = {Digit}+\n"+ //16-34 "<expr>::= !*..*! integer\n"+ //35-59 "integer = integer'.'integer"; //60-86 ICompletionDataList completionList; int expectedTermCount = 2; //while, integer //case 1: on a new line, no completion var target = new CompletionProvider (text); completionList = target.GetCompletionList (16); Assert.IsNull (completionList); //case 2: in terminal literal, no completion completionList = target.GetCompletionList (9); Assert.IsNull (completionList); //case 3: alpha in a rule declaration completionList = target.GetCompletionList (52); Assert.NotNull(completionList); //list should only have "while" and "integer", but NOT "'while'" (terminal literal) Assert.AreEqual(expectedTermCount,completionList.Count); //case 4: alpha in a terminal declaration completionList = target.GetCompletionList (72); Assert.AreEqual (expectedTermCount, completionList.Count); //verify what's in the list Assert.AreEqual ("while", completionList [0].DisplayText); Assert.AreEqual ("integer", completionList [1].DisplayText); } [Test] public void SetNameListTest() { string text = "{set}=[xyz]\n" + //0-11 "int = {digit}+\n" + //12-26 "{digit} = {set}\n"; //27-42 var target = new CompletionProvider (text); ICompletionDataList completionList; int predefinedSetCount = 29; //the list will return several others that are defined in the meta language int expectedSetCount = predefinedSetCount + 2; //include {set} and {digit} //case 1: no completion for lhs of assignment completionList = target.GetCompletionList (0); Assert.IsNull (completionList); //case 2: { in a terminal declaration completionList = target.GetCompletionList (18); Assert.AreEqual (expectedSetCount, completionList.Count); //case 3: { in a set declaration completionList = target.GetCompletionList (37); Assert.AreEqual (expectedSetCount, completionList.Count); //verify what's in the list Assert.IsTrue(completionListContains(completionList,"{set}")); Assert.IsTrue (completionListContains (completionList, "{digit}")); } [Test] public void NoListInLiteralTest() { //A list should not be created when typing in a // terminal literal string text; ICompletionDataList completionList; //start of a terminal literal - should be no list text = "keyword = !*'*!'inaliteral"; var target = new CompletionProvider (text); completionList = target.GetCompletionList (16); //at the 'i' Assert.IsNull (completionList); } [Test] public void NoListInBlockCommentTest() { //A list should not be created when the context is a // block comment string text; ICompletionDataList completionList; text="!* start of block\r\n"+ "<expr"; var target = new CompletionProvider (text); completionList = target.GetCompletionList (19); //at the '<' Assert.IsNull (completionList); } [Test] public void NonTerminalDeclarationTest() { //Typing a < on a new line should bring up a non-terminal list string text = "int = {Digit}+\r\n" + //0-15 "<\r\n" + //16-18 "<value>::=int"; var target = new CompletionProvider (text); var list = target.GetCompletionList (16); Assert.IsNotNull (list); //list should contain <value> Assert.AreEqual (1, list.Count); Assert.AreEqual ("<value>", list [0].DisplayText); } [Test] public void OnlyDefinedTerminalTest() { //the list of terminals should contain only what has been defined // in the grammar string text = "int = {Digit}+\r\n" + //0-15 "<value>::=i"; //16-26 var target = new CompletionProvider (text); var list = target.GetCompletionList (26); Assert.IsNotNull (list); //list should contain int, and only int. 'i' should not be there Assert.AreEqual (1, list.Count); Assert.AreEqual ("int", list [0].DisplayText); } [Test] public void OnlyDefinedSetsTest() { //the list of sets should contain only what has been defined // in the grammar string text = "{hex ch}= {Digit}+[abcdef]\r\n" + //0-27 "hexnum = {\r\n" + //28-39 "{notdefined}"; var target = new CompletionProvider (text); var list = target.GetCompletionList (37); Assert.IsNotNull (list); //The list of sets will contained built-in sets also, so // we can't just check the count.. //The list should NOT contain {notdefined} Assert.IsTrue(completionListContains(list,"{hex ch}")); Assert.IsFalse(completionListContains(list,"{notdefined}")); } [Test] public void NullableInRuleDeclarationTest() { //<> should show up in a rule declaration string text = "int = {Digit}+\r\n" + //0-15 "<value>::=<"; //16-26 var target = new CompletionProvider (text); var list = target.GetCompletionList (26); Assert.IsNotNull (list); Assert.IsTrue (completionListContains (list, "<>")); } [Test] public void NullableInNewLineTest() { //<> should NOT show up when starting a new line string text = "int = {Digit}+\r\n" + //0-15 "<\r\n" + "<value>::=<x>"; var target = new CompletionProvider (text); var list = target.GetCompletionList (16); Assert.IsNotNull (list); Assert.IsFalse (completionListContains (list, "<>")); } static bool completionListContains(ICompletionDataList completionList, string expected) { foreach (CompletionData completionItem in completionList) { if (completionItem.DisplayText == expected) return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using System.Linq; using Xunit; using Xunit.Abstractions; namespace Microsoft.DotNet.Build.Tasks.Packaging.Tests { public class CreateTrimDependencyGroupsTests { private Log _log; private TestBuildEngine _engine; private ITaskItem[] packageIndexes; private const string FrameworkListsPath = "FrameworkLists"; public CreateTrimDependencyGroupsTests(ITestOutputHelper output) { _log = new Log(output); _engine = new TestBuildEngine(_log); var packageIndexPath = $"packageIndex.{Guid.NewGuid()}.json"; PackageIndex index = new PackageIndex(); index.MergeFrameworkLists(FrameworkListsPath); index.Save(packageIndexPath); packageIndexes = new[] { new TaskItem(packageIndexPath) }; } [Fact] public void NoAdditionalDependenciesForPlaceholders() { ITaskItem[] files = new[] { CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoAndroid10", "MonoAndroid10"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoTouch10", "MonoTouch10"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/net45", "net45"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/win8", "win8"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/wp8", "wp8"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/wpa81", "wpa81"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinios10", "xamarinios10"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinmac20", "xamarinmac20"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarintvos10", "xamarintvos10"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinwatchos10", "xamarinwatchos10"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\NETCore\Libraries\System.Collections.Immutable.dll", "lib/netstandard1.0", "netstandard1.0"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\Open\CoreFx\Windows_NT.x86.Release\System.Collections.Immutable\System.Collections.Immutable.xml", "lib/netstandard1.0", "netstandard1.0"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\Open\CoreFx\Windows_NT.x86.Release\System.Collections.Immutable\System.Collections.Immutable.xml", "lib/portable-net45+win8+wp8+wpa81", "portable-net45+win8+wp8+wpa81"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\NETCore\Libraries\System.Collections.Immutable.dll", "lib/portable-net45+win8+wp8+wpa81", "portable-net45+win8+wp8+wpa81"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/MonoAndroid10", "MonoAndroid10"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/MonoTouch10", "MonoTouch10"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/net45", "net45"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/win8", "win8"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/wp8", "wp8"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/wpa81", "wpa81"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinios10", "xamarinios10"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarintvos10", "xamarintvos10"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinwatchos10", "xamarinwatchos10"), CreateFileItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinmac20", "xamarinmac20") }; ITaskItem[] dependencies = new[] { CreateDependencyItem(@"_._", null, "MonoAndroid10"), CreateDependencyItem(@"_._", null, "MonoTouch10"), CreateDependencyItem(@"_._", null, "net45"), CreateDependencyItem(@"_._", null, "win8"), CreateDependencyItem(@"_._", null, "wp8"), CreateDependencyItem(@"_._", null, "wpa81"), CreateDependencyItem(@"_._", null, "portable45-net45+win8+wp8+wpa81"), CreateDependencyItem(@"_._", null, "xamarinios10"), CreateDependencyItem(@"_._", null, "xamarinmac20"), CreateDependencyItem(@"_._", null, "xamarintvos10"), CreateDependencyItem(@"_._", null, "xamarinwatchos10"), CreateDependencyItem(@"System.Runtime", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Resources.ResourceManager", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Collections", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Diagnostics.Debug", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Linq", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Runtime.Extensions", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Globalization", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Threading", "4.0.0", "netstandard1.0") }; CreateTrimDependencyGroups task = new CreateTrimDependencyGroups() { BuildEngine = _engine, Files = files, Dependencies = dependencies, PackageIndexes = packageIndexes }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); // Assert that we're not adding any new trimmed inbox dependencies, we have placeholders for all inbox frameworks. Assert.Equal(0, task.TrimmedDependencies.Length); } [Fact] public void NoPlaceholders() { ITaskItem[] files = new[] { CreateFileItem(@"E:\ProjectK\binaries\x86ret\NETCore\Libraries\System.Collections.Immutable.dll", "lib/netstandard1.0", "netstandard1.0"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\Open\CoreFx\Windows_NT.x86.Release\System.Collections.Immutable\System.Collections.Immutable.xml", "lib/netstandard1.0", "netstandard1.0"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\Open\CoreFx\Windows_NT.x86.Release\System.Collections.Immutable\System.Collections.Immutable.xml", "lib/portable-net45+win8+wp8+wpa81", "portable-net45+win8+wp8+wpa81"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\NETCore\Libraries\System.Collections.Immutable.dll", "lib/portable-net45+win8+wp8+wpa81", "portable-net45+win8+wp8+wpa81"), }; ITaskItem[] dependencies = new[] { CreateDependencyItem(@"System.Runtime", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Resources.ResourceManager", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Collections", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Diagnostics.Debug", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Linq", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Runtime.Extensions", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Globalization", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Threading", "4.0.0", "netstandard1.0") }; CreateTrimDependencyGroups task = new CreateTrimDependencyGroups() { BuildEngine = _engine, Files = files, Dependencies = dependencies, PackageIndexes = packageIndexes }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); // Assert that we're adding dependency groups that cover all inbox TFMs Assert.Equal(1, task.TrimmedDependencies.Length); Assert.Equal(1, task.TrimmedDependencies.Where(f => f.GetMetadata("TargetFramework").Equals("portable45-net45+win8+wp8+wpa81")).Count()); // Assert these are empty dependencygroups. Assert.All(task.TrimmedDependencies, f => f.ToString().Equals("_._")); } [Fact] public void MultiGeneration() { ITaskItem[] files = new[] { CreateFileItem(@"C:\bin\System.ComponentModel.dll", "lib/netstandard1.3", "netstandard1.3"), CreateFileItem(@"C:\bin\System.ComponentModel.dll", "lib/netcore50/System.ComponentModel.dll", "netcore50"), CreateFileItem(@"C:\bin\ns10\System.ComponentModel.dll", "lib/netstandard1.0", "netstandard1.0"), CreateFileItem(@"C:\bin\_._", "lib/MonoAndroid10", "MonoAndroid10"), CreateFileItem(@"C:\bin\_._", "lib/MonoTouch10", "MonoTouch10"), CreateFileItem(@"C:\bin\_._", "lib/win8", "win8"), CreateFileItem(@"C:\bin\_._", "lib/wp80", "wp80"), CreateFileItem(@"C:\bin\_._", "lib/wpa81", "wpa81"), CreateFileItem(@"C:\bin\_._", "lib/xamarinios10", "xamarinios10"), CreateFileItem(@"C:\bin\_._", "lib/xamarinmac20", "xamarinmac20"), CreateFileItem(@"C:\bin\_._", "lib/xamarintvos10", "xamarintvos10"), CreateFileItem(@"C:\bin\_._", "lib/xamarinwatchos10", "xamarinwatchos10"), CreateFileItem(@"C:\bin\ref\System.ComponentModel.dll", "ref/netstandard1.3", "netstandard1.3"), CreateFileItem(@"C:\bin\ref\System.ComponentModel.dll", "ref/netcore50/System.ComponentModel.dll", "netcore50"), CreateFileItem(@"C:\bin\ref\ns10\System.ComponentModel.dll", "ref/netstandard1.0", "netstandard1.0"), CreateFileItem(@"C:\bin\_._", "ref/MonoAndroid10", "MonoAndroid10"), CreateFileItem(@"C:\bin\_._", "ref/MonoTouch10", "MonoTouch10"), CreateFileItem(@"C:\bin\_._", "ref/win8", "win8"), CreateFileItem(@"C:\bin\_._", "ref/wp80", "wp80"), CreateFileItem(@"C:\bin\_._", "ref/wpa81", "wpa81"), CreateFileItem(@"C:\bin\_._", "ref/xamarinios10", "xamarinios10"), CreateFileItem(@"C:\bin\_._", "ref/xamarintvos10", "xamarintvos10"), CreateFileItem(@"C:\bin\_._", "ref/xamarinwatchos10", "xamarinwatchos10"), CreateFileItem(@"C:\bin\_._", "ref/xamarinmac20", "xamarinmac20"), }; ITaskItem[] dependencies = new[] { CreateDependencyItem(@"_._", null, "MonoAndroid10"), CreateDependencyItem(@"_._", null, "MonoTouch10"), CreateDependencyItem(@"_._", null, "win8"), CreateDependencyItem(@"_._", null, "wp8"), CreateDependencyItem(@"_._", null, "wpa81"), CreateDependencyItem(@"_._", null, "xamarinios10"), CreateDependencyItem(@"_._", null, "xamarinmac20"), CreateDependencyItem(@"_._", null, "xamarintvos10"), CreateDependencyItem(@"_._", null, "xamarinwatchos10"), CreateDependencyItem(@"System.Runtime", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Runtime", "4.0.20", "netstandard1.3"), // Make up some dependencies which are not inbox on net45, net451, net46 CreateDependencyItem(@"System.Collections.Immutable", "4.0.0", "netstandard1.0"), CreateDependencyItem(@"System.Collections.Immutable", "4.0.20", "netstandard1.2"), CreateDependencyItem(@"System.Collections.Immutable", "4.0.20", "netstandard1.3"), CreateDependencyItem(@"System.Runtime", "4.0.20", ".NETCore50") }; CreateTrimDependencyGroups task = new CreateTrimDependencyGroups() { BuildEngine = _engine, Files = files, Dependencies = dependencies, PackageIndexes = packageIndexes }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); // System.Collections.Immutable is not inbox and we've specified different versions for netstandard1.0 and netstandard1.3, so // we're expecting those dependencies to both be present for the net45 and net46 target frameworks. Assert.Equal(3, task.TrimmedDependencies.Length); Assert.Equal(1, task.TrimmedDependencies.Where(f => f.GetMetadata("TargetFramework").Equals("portable45-net45+win8+wp8+wpa81") && f.ItemSpec.Equals("System.Collections.Immutable", StringComparison.OrdinalIgnoreCase)).Count()); Assert.Equal(1, task.TrimmedDependencies.Where(f => f.GetMetadata("TargetFramework").Equals("portable46-net451+win81+wpa81") && f.ItemSpec.Equals("System.Collections.Immutable", StringComparison.OrdinalIgnoreCase)).Count()); } [Fact] public void NotSupported() { ITaskItem[] files = new[] { CreateFileItem(@"E:\ProjectK\binaries\x86ret\NETCore\Libraries\System.Threading.AccessControl.dll", "lib/netcoreapp1.0", "netcoreapp1.0"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\NETCore\Libraries\net\System.Threading.AccessControl.dll", "lib/net46", "net46"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\Contracts\System.Threading.AccessControl\4.0.0.0\System.Threading.AccessControl.dll", "ref/netstandard1.3", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1033\System.Threading.AccessControl.xml", "ref/netstandard1.3", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1028\System.Threading.AccessControl.xml", "ref/netstandard1.3/zh-hant", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1031\System.Threading.AccessControl.xml", "ref/netstandard1.3/de", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1036\System.Threading.AccessControl.xml", "ref/netstandard1.3/fr", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1040\System.Threading.AccessControl.xml", "ref/netstandard1.3/it", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1041\System.Threading.AccessControl.xml", "ref/netstandard1.3/ja", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1042\System.Threading.AccessControl.xml", "ref/netstandard1.3/ko", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1049\System.Threading.AccessControl.xml", "ref/netstandard1.3/ru", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\2052\System.Threading.AccessControl.xml", "ref/netstandard1.3/zh-hans", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\3082\System.Threading.AccessControl.xml", "ref/netstandard1.3/es", "netstandard1.3"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\NETCore\Libraries\net\System.Threading.AccessControl.dll", "ref/net46", "netstandard1.3") }; ITaskItem[] dependencies = new[] { CreateDependencyItem(@"System.Runtime", "4.0.20", "netcoreapp1.0"), CreateDependencyItem(@"System.Resources.ResourceManager", "4.0.0", "netcoreapp1.0"), CreateDependencyItem(@"System.Security.AccessControl", "4.0.0-rc2-23516", "netcoreapp1.0"), CreateDependencyItem(@"System.Security.Principal.Windows", "4.0.0-rc2-23516", "netcoreapp1.0"), CreateDependencyItem(@"System.Runtime.Handles", "4.0.0", "netcoreapp1.0"), CreateDependencyItem(@"System.Threading", "4.0.10", "netcoreapp1.0") }; CreateTrimDependencyGroups task = new CreateTrimDependencyGroups() { BuildEngine = _engine, Files = files, Dependencies = dependencies, PackageIndexes = packageIndexes }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); // Assert that we're not adding any new trimmed inbox dependencies, for unsupported inbox frameworks. Assert.Equal(0, task.TrimmedDependencies.Length); } [Fact] public void AddInboxFrameworkGroupsAndDependencies() { ITaskItem[] files = new[] { CreateFileItem(@"E:\ProjectK\binaries\x86ret\NETCore\Libraries\System.Reflection.Metadata.dll", "lib/netstandard1.1", "netstandard1.1"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\Open\CoreFx\Windows_NT.x86.Release\System.Reflection.Metadata\System.Reflection.Metadata.xml", "lib/netstandard1.1", "netstandard1.1"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\Open\CoreFx\Windows_NT.x86.Release\System.Reflection.Metadata\System.Reflection.Metadata.xml", "lib/portable-net45+win8", "portable-net45+win8"), CreateFileItem(@"E:\ProjectK\binaries\x86ret\NETCore\Libraries\System.Reflection.Metadata.dll", "lib/portable-net45+win8", "portable-net45+win8"), }; ITaskItem[] dependencies = new[] { CreateDependencyItem(@"System.Runtime", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Resources.ResourceManager", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Reflection.Primitives", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.IO", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Collections", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Diagnostics.Debug", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Text.Encoding", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Runtime.InteropServices", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Reflection", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Runtime.Extensions", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Threading", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Text.Encoding.Extensions", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Reflection.Extensions", "4.0.0", "netstandard1.1"), CreateDependencyItem(@"System.Collections.Immutable", "1.1.37", "netstandard1.1"), CreateDependencyItem(@"System.Collections.Immutable", "1.1.37", "portable-net45+win80") }; CreateTrimDependencyGroups task = new CreateTrimDependencyGroups() { BuildEngine = _engine, Files = files, Dependencies = dependencies, PackageIndexes = packageIndexes }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); IEnumerable<string> tmp = task.TrimmedDependencies.Select(f => f.GetMetadata("TargetFramework")); // Assert that we're creating new dependency groups Assert.Equal(1, task.TrimmedDependencies.Length); // The only added dependency in portable45-net45+win8+wpa81 is System.Collections.Immutable Assert.Equal("System.Collections.Immutable", task.TrimmedDependencies.Where(f => f.GetMetadata("TargetFramework").Equals("portable45-net45+win8+wpa81")).Single().ItemSpec); } public static ITaskItem CreateFileItem(string sourcePath, string targetPath, string targetFramework) { TaskItem item = new TaskItem(sourcePath); item.SetMetadata("TargetPath", targetPath); item.SetMetadata("TargetFramework", targetFramework); return item; } public static ITaskItem CreateDependencyItem(string sourcePath, string version, string targetFramework) { TaskItem item = new TaskItem(sourcePath); if (version != null) { item.SetMetadata("Version", version); } item.SetMetadata("TargetFramework", targetFramework); return item; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.GamerServices; using TLSA.Engine; using TLSA.Engine.Tools; using System.IO; using System.Xml.Serialization; namespace WhiteAndWorld.GameObjects { /// <summary> /// Funciones para entrada y salida de archivos del juego. /// </summary> /// <remarks>Permite guardar y cargar archivos desde el dispositivo seleccionado.</remarks> public static class StorageSession { private static IAsyncResult result; private static StorageDevice device; public static bool IsDeviceInitialize { get; internal set; } public static void Initialize() { IsDeviceInitialize = false; StorageDevice.DeviceChanged += new EventHandler<EventArgs>(DeviceChanged); } /// <summary> /// Evento para detectar si se ha desconectado el dispositivo de almacenamiento. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private static void DeviceChanged(object sender, EventArgs e) { if (device != null) { if (!device.IsConnected) { IsDeviceInitialize = false; // Activamos el componente de error de dispositivo desconectado: Manager.Scene.AddEntity(new WhiteAndWorld.GameObjects.Entities.StorageDeviceLost()); } } } /// <summary> /// Muestra el selector de dispositivos. /// </summary> /// <remarks>Indice de jugador que realiza la peticion.</remarks> public static void SelectDevice(PlayerIndex player) { if (!Guide.IsVisible) { IsDeviceInitialize = false; try { result = StorageDevice.BeginShowSelector(player, GetDevice, null); } catch (Exception) { return; } } } public static void SelectDevice() { SelectDevice(Manager.UIInput.Player); } /// <summary> /// En conjunto con SelectDevice, se encarga de enlazar con el dispositivo elegido. /// </summary> /// <param name="result"></param> private static void GetDevice(IAsyncResult result) { device = StorageDevice.EndShowSelector(result); // Si se selecciono dispositivo lo asociamos a la sesion: if (device != null && device.IsConnected) { IsDeviceInitialize = true; } else // Si no se selecciono volvemos a la ventana de splash: { if (Manager.GameStates.CurrerntState != "gametitle") Manager.GameStates.ChangeState("gametitle"); } } /// <summary> /// Guarda la estructura en un archivo XML en el dispositivo. /// </summary> /// <param name="filename">Nombre del archivo a guardar.</param> /// <param name="data">Datos a guardar.</param> public static void SaveData(string filename, object data) { try { // Open a storage container. IAsyncResult result = device.BeginOpenContainer("GreyInfection", null, null); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); StorageContainer container = device.EndOpenContainer(result); // Close the wait handle. result.AsyncWaitHandle.Close(); // Check to see whether the save exists. if (container.FileExists(filename)) // Delete it so that we can create one fresh. container.DeleteFile(filename); // Create the file. Stream stream = container.CreateFile(filename); // Convert the object to XML data and put it in the stream. XmlSerializer serializer = new XmlSerializer(data.GetType()); serializer.Serialize(stream, data); // Close the file. stream.Close(); // Dispose the container, to commit changes. container.Dispose(); } catch (Exception) { } } /// <summary> /// Lee el contenido de un archivo en el dispositivo. /// </summary> public static T LoadData<T>(string filename) { try { // Open a storage container. IAsyncResult result = device.BeginOpenContainer("GreyInfection", null, null); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); StorageContainer container = device.EndOpenContainer(result); // Close the wait handle. result.AsyncWaitHandle.Close(); // Check to see whether the save exists. if (!container.FileExists(filename)) { // If not, dispose of the container and return. container.Dispose(); return default(T); } // Open the file. Stream stream = container.OpenFile(filename, FileMode.Open); // Read the data from the file. XmlSerializer serializer = new XmlSerializer(typeof(T)); T data = (T)serializer.Deserialize(stream); // Close the file. stream.Close(); // Dispose the container. container.Dispose(); // Devolvemos el contenido del archivo: return data; } catch (Exception) { return default(T); } } public static bool FileExists(string filename) { try { // Open a storage container. IAsyncResult result = device.BeginOpenContainer("GreyInfection", null, null); // Wait for the WaitHandle to become signaled. result.AsyncWaitHandle.WaitOne(); StorageContainer container = device.EndOpenContainer(result); // Close the wait handle. result.AsyncWaitHandle.Close(); // Check to see whether the save exists. bool ret = container.FileExists(filename); container.Dispose(); return ret; } catch (Exception) { return false; } } public static void Release() { device = null; IsDeviceInitialize = false; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using UnityEditor; using UnityEngine; using System.IO; namespace Microsoft.MixedReality.Toolkit.Editor { public class TextureCombinerWindow : EditorWindow { private enum Channel { Red = 0, Green = 1, Blue = 2, Alpha = 3, RGBAverage = 4 } private enum TextureFormat { TGA = 0, PNG = 1, JPG = 2 } private static readonly string[] textureExtensions = new string[] { "tga", "png", "jpg" }; private const float defaultUniformValue = -0.01f; private Texture2D metallicMap; private Channel metallicMapChannel = Channel.Red; private float metallicUniform = defaultUniformValue; private Texture2D occlusionMap; private Channel occlusionMapChannel = Channel.Green; private float occlusionUniform = defaultUniformValue; private Texture2D emissionMap; private Channel emissionMapChannel = Channel.RGBAverage; private float emissionUniform = defaultUniformValue; private Texture2D smoothnessMap; private Channel smoothnessMapChannel = Channel.Alpha; private float smoothnessUniform = defaultUniformValue; private Material standardMaterial; private TextureFormat textureFormat = TextureFormat.TGA; private const string StandardShaderName = "Standard"; private const string StandardRoughnessShaderName = "Standard (Roughness setup)"; private const string StandardSpecularShaderName = "Standard (Specular setup)"; [MenuItem("Mixed Reality Toolkit/Utilities/Texture Combiner")] private static void ShowWindow() { TextureCombinerWindow window = GetWindow<TextureCombinerWindow>(); window.titleContent = new GUIContent("Texture Combiner"); window.minSize = new Vector2(380.0f, 700.0f); window.Show(); } private void OnGUI() { GUILayout.Label("Import", EditorStyles.boldLabel); GUI.enabled = metallicUniform < 0.0f; metallicMap = (Texture2D)EditorGUILayout.ObjectField("Metallic Map", metallicMap, typeof(Texture2D), false); metallicMapChannel = (Channel)EditorGUILayout.EnumPopup("Input Channel", metallicMapChannel); GUI.enabled = true; metallicUniform = EditorGUILayout.Slider(new GUIContent("Metallic Uniform"), metallicUniform, defaultUniformValue, 1.0f); GUILayout.Box("Output Channel: Red", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); EditorGUILayout.Separator(); GUI.enabled = occlusionUniform < 0.0f; occlusionMap = (Texture2D)EditorGUILayout.ObjectField("Occlusion Map", occlusionMap, typeof(Texture2D), false); occlusionMapChannel = (Channel)EditorGUILayout.EnumPopup("Input Channel", occlusionMapChannel); GUI.enabled = true; occlusionUniform = EditorGUILayout.Slider(new GUIContent("Occlusion Uniform"), occlusionUniform, defaultUniformValue, 1.0f); GUILayout.Box("Output Channel: Green", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); EditorGUILayout.Separator(); GUI.enabled = emissionUniform < 0.0f; emissionMap = (Texture2D)EditorGUILayout.ObjectField("Emission Map", emissionMap, typeof(Texture2D), false); emissionMapChannel = (Channel)EditorGUILayout.EnumPopup("Input Channel", emissionMapChannel); GUI.enabled = true; emissionUniform = EditorGUILayout.Slider(new GUIContent("Emission Uniform"), emissionUniform, defaultUniformValue, 1.0f); GUILayout.Box("Output Channel: Blue", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); EditorGUILayout.Separator(); GUI.enabled = smoothnessUniform < 0.0f; smoothnessMap = (Texture2D)EditorGUILayout.ObjectField("Smoothness Map", smoothnessMap, typeof(Texture2D), false); smoothnessMapChannel = (Channel)EditorGUILayout.EnumPopup("Input Channel", smoothnessMapChannel); GUI.enabled = true; smoothnessUniform = EditorGUILayout.Slider(new GUIContent("Smoothness Uniform"), smoothnessUniform, defaultUniformValue, 1.0f); GUILayout.Box("Output Channel: Alpha", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); EditorGUILayout.Separator(); standardMaterial = (Material)EditorGUILayout.ObjectField("Standard Material", standardMaterial, typeof(Material), false); GUI.enabled = standardMaterial != null && IsUnityStandardMaterial(standardMaterial); if (GUILayout.Button("Autopopulate from Standard Material")) { Autopopulate(); } GUI.enabled = CanSave(); EditorGUILayout.Separator(); GUILayout.Label("Export", EditorStyles.boldLabel); textureFormat = (TextureFormat)EditorGUILayout.EnumPopup("Texture Format", textureFormat); if (GUILayout.Button("Save Channel Map")) { Save(); } GUILayout.Box("Metallic (Red), Occlusion (Green), Emission (Blue), Smoothness (Alpha)", EditorStyles.helpBox, System.Array.Empty<GUILayoutOption>()); } private void Autopopulate() { metallicUniform = defaultUniformValue; occlusionUniform = defaultUniformValue; emissionUniform = defaultUniformValue; smoothnessUniform = defaultUniformValue; occlusionMap = (Texture2D)standardMaterial.GetTexture("_OcclusionMap"); occlusionMapChannel = occlusionMap != null ? Channel.Green : occlusionMapChannel; emissionMap = (Texture2D)standardMaterial.GetTexture("_EmissionMap"); emissionMapChannel = emissionMap != null ? Channel.RGBAverage : emissionMapChannel; if (standardMaterial.shader.name == StandardShaderName) { metallicMap = (Texture2D)standardMaterial.GetTexture("_MetallicGlossMap"); metallicMapChannel = metallicMap != null ? Channel.Red : metallicMapChannel; smoothnessMap = ((int)standardMaterial.GetFloat("_SmoothnessTextureChannel") == 0) ? metallicMap : (Texture2D)standardMaterial.GetTexture("_MainTex"); smoothnessMapChannel = smoothnessMap != null ? Channel.Alpha : smoothnessMapChannel; } else if (standardMaterial.shader.name == StandardRoughnessShaderName) { metallicMap = (Texture2D)standardMaterial.GetTexture("_MetallicGlossMap"); metallicMapChannel = metallicMap != null ? Channel.Red : metallicMapChannel; smoothnessMap = (Texture2D)standardMaterial.GetTexture("_SpecGlossMap"); smoothnessMapChannel = smoothnessMap != null ? Channel.Red : smoothnessMapChannel; } else { smoothnessMap = ((int)standardMaterial.GetFloat("_SmoothnessTextureChannel") == 0) ? (Texture2D)standardMaterial.GetTexture("_SpecGlossMap") : (Texture2D)standardMaterial.GetTexture("_MainTex"); smoothnessMapChannel = smoothnessMap != null ? Channel.Alpha : smoothnessMapChannel; } } private void Save() { int width; int height; Texture[] textures = new Texture[] { metallicMap, occlusionMap, emissionMap, smoothnessMap }; CalculateChannelMapSize(textures, out width, out height); Texture2D channelMap = new Texture2D(width, height); RenderTexture renderTexture = RenderTexture.GetTemporary(width, height, 0, RenderTextureFormat.Default, RenderTextureReadWrite.Linear); // Use the GPU to pack the various texture maps into a single texture. Material channelPacker = new Material(Shader.Find("Hidden/ChannelPacker")); channelPacker.SetTexture("_MetallicMap", metallicMap); channelPacker.SetInt("_MetallicMapChannel", (int)metallicMapChannel); channelPacker.SetFloat("_MetallicUniform", metallicUniform); channelPacker.SetTexture("_OcclusionMap", occlusionMap); channelPacker.SetInt("_OcclusionMapChannel", (int)occlusionMapChannel); channelPacker.SetFloat("_OcclusionUniform", occlusionUniform); channelPacker.SetTexture("_EmissionMap", emissionMap); channelPacker.SetInt("_EmissionMapChannel", (int)emissionMapChannel); channelPacker.SetFloat("_EmissionUniform", emissionUniform); channelPacker.SetTexture("_SmoothnessMap", smoothnessMap); channelPacker.SetInt("_SmoothnessMapChannel", (int)smoothnessMapChannel); channelPacker.SetFloat("_SmoothnessUniform", smoothnessUniform); Graphics.Blit(null, renderTexture, channelPacker); DestroyImmediate(channelPacker); // Save the last render texture to a texture. RenderTexture previous = RenderTexture.active; RenderTexture.active = renderTexture; channelMap.ReadPixels(new Rect(0.0f, 0.0f, width, height), 0, 0); channelMap.Apply(); RenderTexture.active = previous; RenderTexture.ReleaseTemporary(renderTexture); // Save the texture to disk. string filename = string.Format("{0}{1}.{2}", GetChannelMapName(textures), "_Channel", textureExtensions[(int)textureFormat]); string path = EditorUtility.SaveFilePanel("Save Channel Map", "", filename, textureExtensions[(int)textureFormat]); if (path.Length != 0) { byte[] textureData = null; switch (textureFormat) { case TextureFormat.TGA: textureData = channelMap.EncodeToTGA(); break; case TextureFormat.PNG: textureData = channelMap.EncodeToPNG(); break; case TextureFormat.JPG: textureData = channelMap.EncodeToJPG(); break; } if (textureData != null) { File.WriteAllBytes(path, textureData); Debug.LogFormat("Saved channel map to: {0}", path); AssetDatabase.Refresh(); } } } private bool CanSave() { return metallicMap != null || occlusionMap != null || emissionMap != null || smoothnessMap != null || metallicUniform >= 0.0f || occlusionUniform >= 0.0f || emissionUniform >= 0.0f || smoothnessUniform >= 0.0f; } private static bool IsUnityStandardMaterial(Material material) { if (material != null) { if (material.shader.name == StandardShaderName || material.shader.name == StandardRoughnessShaderName || material.shader.name == StandardSpecularShaderName) { return true; } } return false; } private static string GetChannelMapName(Texture[] textures) { // Use the first named texture as the channel map name. foreach (Texture texture in textures) { if (texture != null && !string.IsNullOrEmpty(texture.name)) { return texture.name; } } return string.Empty; } private static void CalculateChannelMapSize(Texture[] textures, out int width, out int height) { width = 4; height = 4; // Find the max extents of all texture maps. foreach (Texture texture in textures) { width = texture != null ? Mathf.Max(texture.width, width) : width; height = texture != null ? Mathf.Max(texture.height, height) : height; } } } }
#region Using Directives using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; #endregion namespace System.CommandLine.ValueConverters { /// <summary> /// Represents a helper, which makes it easy to create collections of many different kinds via one, simple API. /// </summary> public static class CollectionHelper { #region Private Static Fields /// <summary> /// Contains a list of all the collection types that are supported by the collection helper. /// </summary> private static List<Type> supportedTypes = new List<Type> { // System.Collections typeof(ArrayList), typeof(Queue), typeof(Stack), typeof(ICollection), typeof(IEnumerable), typeof(IList), // System.Collections.Generic typeof(HashSet<>), typeof(LinkedList<>), typeof(List<>), typeof(Queue<>), typeof(SortedSet<>), typeof(Stack<>), typeof(ICollection<>), typeof(IEnumerable<>), typeof(IList<>), typeof(IReadOnlyCollection<>), typeof(IReadOnlyList<>), typeof(ISet<>), // System.Collections.ObjectModel typeof(Collection<>), typeof(ObservableCollection<>), typeof(ReadOnlyCollection<>), typeof(ReadOnlyObservableCollection<>) }; #endregion #region Public Static Methods /// <summary> /// Determines if a given type is one of the supported collection types. /// </summary> /// <param name="type">The type that is to be checked for support.</param> /// <returns>Returns <c>true</c> if the specified type is one of the supported collection types and <c>false</c> otherwise.</returns> public static bool IsSupportedCollectionType(Type type) { if (type.IsArray) { if (type.GetElementType().IsArray) return false; return type.GetArrayRank() == 1; } if (type.IsConstructedGenericType) type = type.GetGenericTypeDefinition(); return CollectionHelper.supportedTypes.Contains(type); } /// <summary> /// Retrieves the element type of the specified collection. /// </summary> /// <param name="type">The collection type for which the element type is to be determined.</param> /// <returns>Returns the type of the elements of the specified collection type. If the collection type is not generic <c>typeof(object)</c> is returned.</returns> public static Type GetCollectionElementType(Type type) { if (!CollectionHelper.IsSupportedCollectionType(type)) throw new InvalidOperationException("The specified type is not a supported collection type."); if (type.IsArray) return type.GetElementType(); if (type.IsConstructedGenericType) return type.GetGenericArguments()[0]; return typeof(object); } /// <summary> /// Merges two collections into one collection of the same type. /// </summary> /// <param name="resultType">The type of collection into which the result is to be converted.</param> /// <param name="firstCollection">The first collection.</param> /// <param name="secondCollection">The second collection.</param> /// <returns>Returns a collection that contains the elements of both collections, which is of the same type as the input collections.</returns> public static object Merge(Type resultType, object firstCollection, object secondCollection) { // Validates that the two collections are of a supported collection type if (!CollectionHelper.IsSupportedCollectionType(firstCollection.GetType())) throw new InvalidOperationException("The type of the first collection is not a supported collection type."); if (!CollectionHelper.IsSupportedCollectionType(secondCollection.GetType())) throw new InvalidOperationException("The type of the second collection is not a supported collection type."); if (!CollectionHelper.IsSupportedCollectionType(resultType)) throw new InvalidOperationException("The result type is not a supported collection type."); // Converts the two collections to arrays first Array firstArray = CollectionHelper.ToArray(firstCollection); Array secondArray = CollectionHelper.ToArray(secondCollection); // Combines the two arrays into a single array object[] mergedArray = new object[firstArray.Length + secondArray.Length]; Array.Copy(firstArray, mergedArray, firstArray.Length); Array.Copy(secondArray, 0, mergedArray, firstArray.Length, secondArray.Length); // Converts the merged array back to the collection type and returns it return CollectionHelper.To(resultType, mergedArray); } /// <summary> /// Converts the specified collection to a collection of another containing the same elements. /// </summary> /// <param name="resultType">The type of collection into which the result is to be converted.</param> /// <param name="inputCollection">The collection, that is to be converted to another collection type.</param> /// <returns>Returns the converted collection.</returns> public static object To(Type resultType, object inputCollection) { // Checks if both collection types are supported if (!CollectionHelper.IsSupportedCollectionType(inputCollection.GetType())) throw new InvalidOperationException("The type of the input collection is not a supported collection type."); if (!CollectionHelper.IsSupportedCollectionType(resultType)) throw new InvalidOperationException("The result type is not a supported collection type."); // First the input collection is converted to an array and then the array is converted to the result collection type Array array = CollectionHelper.ToArray(inputCollection); return CollectionHelper.FromArray(resultType, array); } /// <summary> /// Converts the specified collection into an array with the same elements. /// </summary> /// <param name="inputCollection">The collection that is to be converted into an array.</param> /// <returns>Returns an array that contains the same elements of the specified input collection.</returns> public static Array ToArray(object inputCollection) { // Checks if the type of the input collection is supported Type type = inputCollection.GetType(); if (!CollectionHelper.IsSupportedCollectionType(type)) throw new InvalidOperationException("The type of the input collection is not a supported collection type."); // Checks if the collection already is an array, then nothing needs to be done if (type.IsArray) return inputCollection as Array; // Creates a new array int arraySize = CollectionHelper.GetCount(inputCollection); object[] array = new object[arraySize]; // Checks if the input collection implements ICollection, in that case there is a way to copy its contents to an array ICollection collection = inputCollection as ICollection; if (collection != null) { collection.CopyTo(array, 0); return array; } // Checks if the input collection implements the IEnumerable interface, in that case the enumerator can be used to copy its contents to an array IEnumerable enumerable = inputCollection as IEnumerable; if (enumerable != null) { IEnumerator enumerator = enumerable.GetEnumerator(); int currentIndex = 0; while (enumerator.MoveNext()) { array[currentIndex] = enumerator.Current; currentIndex += 1; } return array; } // Since some weird error must have occurred (all supported collection types either implement ICollection or IEnumerator one or the other way), an exception is thrown throw new InvalidOperationException("The input collection type neither implements ICollection nor IEnumerable."); } /// <summary> /// Converts the specified array into another collection type with the same elements. /// </summary> /// <param name="resultType">The type of collection into which the result is to be converted.</param> /// <param name="inputArray">The array that is to be converted into another collection type.</param> /// <returns>Returns a collection that contains the same elements of the specified input array.</returns> public static object FromArray(Type resultType, Array inputArray) { // Checks if the type of the input collection is supported if (!CollectionHelper.IsSupportedCollectionType(resultType)) throw new InvalidOperationException("The result type is not a supported collection type."); // Determines which type the elements will have in the result collection Type elementType; if (resultType.IsGenericType) elementType = resultType.GenericTypeArguments[0]; else if (resultType.IsArray) elementType = resultType.GetElementType(); else elementType = typeof(object); if (resultType.IsConstructedGenericType) resultType = resultType.GetGenericTypeDefinition(); // Checks if the result collection is an array and performs the necessary conversions if (resultType.IsArray) { Array resultArray = Array.CreateInstance(elementType, inputArray.Length); Array.Copy(inputArray, resultArray, inputArray.Length); return resultArray; } // Checks if the result collection is ICollection, IEnumerable, or IList, in that case nothing needs to be done, because Array already implements all three of them if (resultType == typeof(ICollection) || resultType == typeof(IEnumerable) || resultType == typeof(IList)) return inputArray; // Checks if the result collection is a non-generic collection type, all non-generic collection types implement a constructor that takes an ICollection as a parameter, // so reflection can be used to instantiated instances of them if (resultType == typeof(ArrayList) || resultType == typeof(Queue) || resultType == typeof(Stack)) { ConstructorInfo collectionConstructor = resultType.GetConstructor(new Type[] { typeof(ICollection) }); object newCollection = collectionConstructor.Invoke(new object[] { inputArray }); return newCollection; } // Since all of the following types are generic types, the input array is first cast into a generic IEnumerable IEnumerable enumerable = inputArray as IEnumerable; MethodInfo castMethod = typeof(Enumerable).GetMethod(nameof(Enumerable.Cast)).MakeGenericMethod( new System.Type[]{ elementType } ); object genericEnumerable = castMethod.Invoke(null, new object[] { enumerable }); // Many of the generic collection types have a constructor that takes a generic IEnumerable as a parameter, so reflection can be used to instantiated instances of them if (resultType == typeof(HashSet<>) || resultType == typeof(LinkedList<>) || resultType == typeof(List<>) || resultType == typeof(Queue<>) || resultType == typeof(SortedSet<>) || resultType == typeof(Stack<>) || resultType == typeof(ObservableCollection<>) || resultType == typeof(IEnumerable<>) || resultType == typeof(IList<>) || resultType == typeof(ISet<>)) { if (resultType == typeof(IEnumerable<>) || resultType == typeof(IList<>)) resultType = typeof(List<>); if (resultType == typeof(ISet<>)) resultType = typeof(SortedSet<>); Type collectionType = resultType.MakeGenericType(new Type[] { elementType }); ConstructorInfo collectionConstructor = collectionType.GetConstructor(new Type[] { genericEnumerable.GetType() }); object newCollection = collectionConstructor.Invoke(new object[] { genericEnumerable }); return newCollection; } // The ReadOnlyObservableCollection<> is a special case, as it only has one constructor, which takes a ObservableCollection<> as parameter, so reflection can be used to instantiated instances of it if (resultType == typeof(ReadOnlyObservableCollection<>)) { Type observableCollectionType = typeof(ObservableCollection<>).MakeGenericType(new Type[] { elementType }); ConstructorInfo observableCollectionConstructor = observableCollectionType.GetConstructor(new Type[] { genericEnumerable.GetType() }); object observableCollection = observableCollectionConstructor.Invoke(new object[] { genericEnumerable }); Type collectionType = typeof(ReadOnlyObservableCollection<>).MakeGenericType(new Type[] { elementType }); ConstructorInfo collectionConstructor = collectionType.GetConstructor(new Type[] { observableCollectionType }); object newCollection = collectionConstructor.Invoke(new object[] { observableCollection }); return newCollection; } // The Collection<> and ReadOnlyCollection<> are special cases, as they have constructors, which take generic IList values as parameters, so reflection can be used to instantiated instances of them if (resultType == typeof(Collection<>) || resultType == typeof(ReadOnlyCollection<>) || resultType == typeof(ICollection<>) || resultType == typeof(IReadOnlyCollection<>) || resultType == typeof(IReadOnlyList<>)) { if (resultType == typeof(ICollection<>)) resultType = typeof(Collection<>); if (resultType == typeof(IReadOnlyCollection<>) || resultType == typeof(IReadOnlyList<>)) resultType = typeof(ReadOnlyCollection<>); Type listType = typeof(List<>).MakeGenericType(new Type[] { elementType }); ConstructorInfo listConstructor = listType.GetConstructor(new Type[] { genericEnumerable.GetType() }); object newList = listConstructor.Invoke(new object[] { genericEnumerable }); Type collectionType = resultType.MakeGenericType(new Type[] { elementType }); ConstructorInfo collectionConstructor = collectionType.GetConstructor(new Type[] { listType }); object newCollection = collectionConstructor.Invoke(new object[] { newList }); return newCollection; } throw new InvalidOperationException("The array could not be converted."); } /// <summary> /// Gets the number of elements in the specified collection. /// </summary> /// <param name="inputCollection">The collection for which the number of elements is to be determined.</param> /// <returns>Returns the number of elements that are in the specified collection.</returns> public static int GetCount(object inputCollection) { // Determines if the specified collection is of a supported type if (!CollectionHelper.IsSupportedCollectionType(inputCollection.GetType())) throw new InvalidOperationException("The type of the input collection is not a supported collection type."); // Checks if the collection implements ICollection, in that case, the length of the collection can directly be accessed ICollection collection = inputCollection as ICollection; if (collection != null) return collection.Count; // Since the collection does not implement ICollection, the other way to retrieve length is via IEnumerable and IEnumerator IEnumerable enumerable = inputCollection as IEnumerable; if (enumerable != null) { int count = 0; IEnumerator enumerator = enumerable.GetEnumerator(); while (enumerator.MoveNext()) count += 1; return count; } // Since some weird error must have occurred (all supported collection types either implement ICollection or IEnumerator one or the other way), an exception is thrown throw new InvalidOperationException("The input collection type neither implements ICollection nor IEnumerable."); } #endregion } }
using System; using System.Linq; using System.ComponentModel.DataAnnotations; using Csla; using System.ComponentModel; namespace ProjectTracker.Library { [Serializable()] public class ProjectEdit : CslaBaseTypes.BusinessBase<ProjectEdit> { public static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(c => c.TimeStamp); [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public byte[] TimeStamp { get { return GetProperty(TimeStampProperty); } set { SetProperty(TimeStampProperty, value); } } public static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(c => c.Id); [Display(Name = "Project id")] public int Id { get { return GetProperty(IdProperty); } private set { LoadProperty(IdProperty, value); } } public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(c => c.Name); [Display(Name = "Project name")] [Required] [StringLength(50)] public string Name { get { return GetProperty(NameProperty); } set { SetProperty(NameProperty, value); } } public static readonly PropertyInfo<string> CoolPropertyProperty = RegisterProperty<string>(c => c.CoolProperty); public string CoolProperty { get { return GetProperty(CoolPropertyProperty); } set { SetProperty(CoolPropertyProperty, value); } } public static readonly PropertyInfo<DateTime?> StartedProperty = RegisterProperty<DateTime?>(c => c.Started); public DateTime? Started { get { return GetProperty(StartedProperty); } set { SetProperty(StartedProperty, value); } } public static readonly PropertyInfo<DateTime?> EndedProperty = RegisterProperty<DateTime?>(c => c.Ended); public DateTime? Ended { get { return GetProperty(EndedProperty); } set { SetProperty(EndedProperty, value); } } public static readonly PropertyInfo<string> DescriptionProperty = RegisterProperty<string>(c => c.Description); public string Description { get { return GetProperty(DescriptionProperty); } set { SetProperty(DescriptionProperty, value); } } public static readonly PropertyInfo<ProjectResources> ResourcesProperty = RegisterProperty<ProjectResources>(p => p.Resources, RelationshipTypes.Child); public ProjectResources Resources { get { return GetProperty(ResourcesProperty); } private set { LoadProperty(ResourcesProperty, value); } } public override string ToString() { return Id.ToString(); } protected override void AddBusinessRules() { base.AddBusinessRules(); BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty)); BusinessRules.AddRule( new StartDateGTEndDate { PrimaryProperty = StartedProperty, AffectedProperties = { EndedProperty } }); BusinessRules.AddRule( new StartDateGTEndDate { PrimaryProperty = EndedProperty, AffectedProperties = { StartedProperty } }); BusinessRules.AddRule( new Csla.Rules.CommonRules.IsInRole( Csla.Rules.AuthorizationActions.WriteProperty, NameProperty, "ProjectManager")); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, StartedProperty, "ProjectManager")); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, EndedProperty, "ProjectManager")); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.WriteProperty, DescriptionProperty, "ProjectManager")); BusinessRules.AddRule(new NoDuplicateResource { PrimaryProperty = ResourcesProperty }); } [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public static void AddObjectAuthorizationRules() { Csla.Rules.BusinessRules.AddRule( typeof(ProjectEdit), new Csla.Rules.CommonRules.IsInRole( Csla.Rules.AuthorizationActions.CreateObject, "ProjectManager")); Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.EditObject, "ProjectManager")); Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.DeleteObject, "ProjectManager", "Administrator")); } protected override void OnChildChanged(Csla.Core.ChildChangedEventArgs e) { if (e.ChildObject is ProjectResources) { BusinessRules.CheckRules(ResourcesProperty); OnPropertyChanged(ResourcesProperty); } base.OnChildChanged(e); } private class NoDuplicateResource : Csla.Rules.BusinessRule { protected override void Execute(Csla.Rules.IRuleContext context) { var target = (ProjectEdit)context.Target; foreach (var item in target.Resources) { var count = target.Resources.Count(r => r.ResourceId == item.ResourceId); if (count > 1) { context.AddErrorResult("Duplicate resources not allowed"); return; } } } } private class StartDateGTEndDate : Csla.Rules.BusinessRule { protected override void Execute(Csla.Rules.IRuleContext context) { var target = (ProjectEdit)context.Target; var started = target.ReadProperty(StartedProperty); var ended = target.ReadProperty(EndedProperty); if (started.HasValue && ended.HasValue && started > ended || !started.HasValue && ended.HasValue) context.AddErrorResult("Start date can't be after end date"); } } #if FULL_DOTNET public static void NewProject(EventHandler<DataPortalResult<ProjectEdit>> callback) { ProjectGetter.CreateNewProject((o, e) => { callback(o, new DataPortalResult<ProjectEdit>(e.Object.Project, e.Error, null)); }); } public static void GetProject(int id, EventHandler<DataPortalResult<ProjectEdit>> callback) { ProjectGetter.GetExistingProject(id, (o, e) => { callback(o, new DataPortalResult<ProjectEdit>(e.Object.Project, e.Error, null)); }); } public static void Exists(int id, Action<bool> result) { var cmd = new ProjectExistsCommand(id); DataPortal.BeginExecute<ProjectExistsCommand>(cmd, (o, e) => { if (e.Error != null) throw e.Error; else result(e.Object.ProjectExists); }); } public static void DeleteProject(int id, EventHandler<DataPortalResult<ProjectEdit>> callback) { DataPortal.BeginDelete<ProjectEdit>(id, callback); } #endif public async static System.Threading.Tasks.Task<ProjectEdit> NewProjectAsync() { return await DataPortal.CreateAsync<ProjectEdit>(); } public async static System.Threading.Tasks.Task<ProjectEdit> GetProjectAsync(int id) { return await DataPortal.FetchAsync<ProjectEdit>(id); } #if FULL_DOTNET public static ProjectEdit NewProject() { return DataPortal.Create<ProjectEdit>(); } public static ProjectEdit GetProject(int id) { return DataPortal.Fetch<ProjectEdit>(id); } public static void DeleteProject(int id) { DataPortal.Delete<ProjectEdit>(id); } public static bool Exists(int id) { var cmd = new ProjectExistsCommand(id); cmd = DataPortal.Execute<ProjectExistsCommand>(cmd); return cmd.ProjectExists; } #endif [RunLocal] protected override void DataPortal_Create() { LoadProperty(ResourcesProperty, DataPortal.CreateChild<ProjectResources>()); base.DataPortal_Create(); } private void DataPortal_Fetch(int id) { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>(); var data = dal.Fetch(id); using (BypassPropertyChecks) { Id = data.Id; Name = data.Name; Description = data.Description; Started = data.Started; Ended = data.Ended; TimeStamp = data.LastChanged; Resources = DataPortal.FetchChild<ProjectResources>(id); } } } protected override void DataPortal_Insert() { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>(); using (BypassPropertyChecks) { var item = new ProjectTracker.Dal.ProjectDto { Name = this.Name, Description = this.Description, Started = this.Started, Ended = this.Ended }; dal.Insert(item); Id = item.Id; TimeStamp = item.LastChanged; } FieldManager.UpdateChildren(this); } } protected override void DataPortal_Update() { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>(); using (BypassPropertyChecks) { var item = new ProjectTracker.Dal.ProjectDto { Id = this.Id, Name = this.Name, Description = this.Description, Started = this.Started, Ended = this.Ended, LastChanged = this.TimeStamp }; dal.Update(item); TimeStamp = item.LastChanged; } FieldManager.UpdateChildren(this); } } protected override void DataPortal_DeleteSelf() { using (BypassPropertyChecks) DataPortal_Delete(this.Id); } private void DataPortal_Delete(int id) { using (var ctx = ProjectTracker.Dal.DalFactory.GetManager()) { Resources.Clear(); FieldManager.UpdateChildren(this); var dal = ctx.GetProvider<ProjectTracker.Dal.IProjectDal>(); dal.Delete(id); } } } }
/* Copyright 2012 Michael Edwards Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //-CRE- using System; using System.Collections.Generic; using System.Text; using Sitecore.Web.UI.Pages; using System.Collections.Specialized; using System.IO; using Sitecore.Web.UI.HtmlControls; using Sitecore.Web.UI.WebControls; using Sitecore.Data.Items; using Sitecore; using Sitecore.Web.UI.Sheer; using Sitecore.IO; using Sitecore.Diagnostics; using Sitecore.Shell.Framework; using Glass.Mapper.Sc.Razor.Model; using Sitecore.Web; using Sitecore.Data; namespace Glass.Mapper.Sc.Razor.Shell { /// <summary> /// Class AbtractFileCreateWizard /// </summary> /// <typeparam name="T"></typeparam> public abstract class AbtractFileCreateWizard<T> : WizardForm where T:class { /// <summary> /// Gets or sets the extension. /// </summary> /// <value>The extension.</value> public string Extension { get; set; } /// <summary> /// Gets or sets the default file location. /// </summary> /// <value>The default file location.</value> public string DefaultFileLocation { get; set; } /// <summary> /// Gets or sets the database. /// </summary> /// <value>The database.</value> public string Database { get; set; } /// <summary> /// Gets or sets the item root. /// </summary> /// <value>The item root.</value> public string ItemRoot { get; set; } /// <summary> /// The file name /// </summary> protected Edit FileName; /// <summary> /// The file location treeview /// </summary> protected TreeviewEx FileLocationTreeview; /// <summary> /// The file data context /// </summary> protected DataContext FileDataContext; /// <summary> /// The item data context /// </summary> protected DataContext ItemDataContext; /// <summary> /// The item tree view /// </summary> protected TreeviewEx ItemTreeView; /// <summary> /// The master /// </summary> protected ISitecoreService Master; /// <summary> /// Initializes a new instance of the <see cref="AbtractFileCreateWizard{T}"/> class. /// </summary> /// <exception cref="Glass.Mapper.Sc.Razor.RazorException">Exception creating Sitecore Service, have you called the method GlassRazorModuleLoader.Load()?</exception> public AbtractFileCreateWizard() { Extension = "cshtml"; DefaultFileLocation = "/layouts/razor"; ItemRoot = "/sitecore/layout/Glass Razor"; Database = "master"; try { Master = new SitecoreService(Database, GlassRazorSettings.ContextName); } catch (KeyNotFoundException) { throw new RazorException( "Exception creating Sitecore Service, have you called the method GlassRazorModuleLoader.Load()?"); } } /// <summary> /// Raises the load event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs" /> instance containing the event data.</param> /// <remarks>This method notifies the server control that it should perform actions common to each HTTP /// request for the page it is associated with, such as setting up a database query. At this /// stage in the page lifecycle, server controls in the hierarchy are created and initialized, /// view state is restored, and form controls reflect client-side data. Use the IsPostBack /// property to determine whether the page is being loaded in response to a client postback, /// or if it is being loaded and accessed for the first time.</remarks> protected override void OnLoad(EventArgs e) { FileDataContext.Folder = DefaultFileLocation; ItemDataContext.Root = ItemRoot; ItemDataContext.Filter = "@@templateId = '{A4F60160-BD14-4471-B362-CB56905E9564}'"; string locationId = WebUtil.GetQueryString("locationId"); var master = Sitecore.Configuration.Factory.GetDatabase("master"); Item location = master.GetItem(ID.Parse(locationId)); ItemUri folderUri = new ItemUri(location); ItemDataContext.SetFolder(folderUri); base.OnLoad(e); } /// <summary> /// Handles the message. /// </summary> /// <param name="message">The message.</param> public override void HandleMessage(Message message) { Assert.ArgumentNotNull(message, "message"); base.HandleMessage(message); if (!(message.Name == "newfile:refresh")) { Item item; if (!string.IsNullOrEmpty(message["id"])) { item = ItemDataContext.GetItem(message["id"]); } else { item = ItemDataContext.GetFolder(); } Dispatcher.Dispatch(message, item); } } /// <summary> /// Gets the relative file path. /// </summary> /// <returns>System.String.</returns> /// <exception cref="System.NullReferenceException">File location item was null</exception> public string GetRelativeFilePath() { Item fileLocationItem = FileLocationTreeview.GetSelectionItem(); if (fileLocationItem != null) { string directory = StringUtil.GetString(new[] { fileLocationItem["Path"] }); string fileName = FileName.Value; string ext = fileName.EndsWith(".cshtml") ? "" : Extension; return FileUtil.MakePath(directory, "{0}.{1}".Formatted(fileName, ext)); } throw new NullReferenceException("File location item was null"); } /// <summary> /// Files the exists. /// </summary> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns> protected bool FileExists() { string fullPath = FileUtil.MapPath(GetRelativeFilePath()); if (File.Exists(fullPath)) { SheerResponse.Alert("A file already exists at {0}. Please choose another name.".Formatted(fullPath)); return true; } return false; } /// <summary> /// Items the can write. /// </summary> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns> protected bool ItemCanWrite() { Item item = ItemTreeView.GetSelectionItem(); if (item != null && !item.Access.CanCreate()) { SheerResponse.Alert("You don't have permissions to write to {0}".Formatted(item.Paths.FullPath)); return false; } return true; } /// <summary> /// Creates the cs HTML file. /// </summary> /// <param name="collection">The collection.</param> /// <param name="templatePath">The template path.</param> public void CreateCsHtmlFile(NameValueCollection collection, string templatePath) { string path = FileUtil.MapPath(GetRelativeFilePath()); CreateFile(collection, templatePath, path); } /// <summary> /// Creates the file. /// </summary> /// <param name="collection">The collection.</param> /// <param name="templatePath">The template path.</param> /// <param name="targetPath">The target path.</param> public void CreateFile(NameValueCollection collection, string templatePath, string targetPath){ string fullTemplatePath = FileUtil.MapPath(templatePath); string template = File.ReadAllText(fullTemplatePath); StringBuilder sb = new StringBuilder(template); foreach(var key in collection.AllKeys){ sb.Replace("{{"+key+"}}", collection[key]); } File.WriteAllText(targetPath, sb.ToString()); } /// <summary> /// Creates the item. /// </summary> /// <param name="item">The item.</param> public void CreateItem(T item) { Item parent = ItemTreeView.GetSelectionItem(); var folder = Master.CreateType<GlassRazorFolder>(parent); Master.Create(folder, item); } } }
// 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 System.Runtime; using System.ServiceModel.Channels; namespace System.ServiceModel.Dispatcher { internal class ImmutableClientRuntime { private int _correlationCount; private bool _addTransactionFlowProperties; private IInteractiveChannelInitializer[] _interactiveChannelInitializers; private IClientOperationSelector _operationSelector; private IChannelInitializer[] _channelInitializers; private IClientMessageInspector[] _messageInspectors; private Dictionary<string, ProxyOperationRuntime> _operations; private ProxyOperationRuntime _unhandled; private bool _useSynchronizationContext; private bool _validateMustUnderstand; internal ImmutableClientRuntime(ClientRuntime behavior) { _channelInitializers = EmptyArray<IChannelInitializer>.ToArray(behavior.ChannelInitializers); _interactiveChannelInitializers = EmptyArray<IInteractiveChannelInitializer>.ToArray(behavior.InteractiveChannelInitializers); _messageInspectors = EmptyArray<IClientMessageInspector>.ToArray(behavior.MessageInspectors); _operationSelector = behavior.OperationSelector; _useSynchronizationContext = behavior.UseSynchronizationContext; _validateMustUnderstand = behavior.ValidateMustUnderstand; _unhandled = new ProxyOperationRuntime(behavior.UnhandledClientOperation, this); _addTransactionFlowProperties = behavior.AddTransactionFlowProperties; _operations = new Dictionary<string, ProxyOperationRuntime>(); for (int i = 0; i < behavior.Operations.Count; i++) { ClientOperation operation = behavior.Operations[i]; ProxyOperationRuntime operationRuntime = new ProxyOperationRuntime(operation, this); _operations.Add(operation.Name, operationRuntime); } _correlationCount = _messageInspectors.Length + behavior.MaxParameterInspectors; } internal int MessageInspectorCorrelationOffset { get { return 0; } } internal int ParameterInspectorCorrelationOffset { get { return _messageInspectors.Length; } } internal int CorrelationCount { get { return _correlationCount; } } internal IClientOperationSelector OperationSelector { get { return _operationSelector; } } internal ProxyOperationRuntime UnhandledProxyOperation { get { return _unhandled; } } internal bool UseSynchronizationContext { get { return _useSynchronizationContext; } } internal bool ValidateMustUnderstand { get { return _validateMustUnderstand; } set { _validateMustUnderstand = value; } } internal void AfterReceiveReply(ref ProxyRpc rpc) { int offset = this.MessageInspectorCorrelationOffset; try { for (int i = 0; i < _messageInspectors.Length; i++) { _messageInspectors[i].AfterReceiveReply(ref rpc.Reply, rpc.Correlation[offset + i]); if (WcfEventSource.Instance.ClientMessageInspectorAfterReceiveInvokedIsEnabled()) { WcfEventSource.Instance.ClientMessageInspectorAfterReceiveInvoked(rpc.EventTraceActivity, _messageInspectors[i].GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal void BeforeSendRequest(ref ProxyRpc rpc) { int offset = this.MessageInspectorCorrelationOffset; try { for (int i = 0; i < _messageInspectors.Length; i++) { ServiceChannel clientChannel = ServiceChannelFactory.GetServiceChannel(rpc.Channel.Proxy); rpc.Correlation[offset + i] = _messageInspectors[i].BeforeSendRequest(ref rpc.Request, clientChannel); if (WcfEventSource.Instance.ClientMessageInspectorBeforeSendInvokedIsEnabled()) { WcfEventSource.Instance.ClientMessageInspectorBeforeSendInvoked(rpc.EventTraceActivity, _messageInspectors[i].GetType().FullName); } } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal void DisplayInitializationUI(ServiceChannel channel) { EndDisplayInitializationUI(BeginDisplayInitializationUI(channel, null, null)); } internal IAsyncResult BeginDisplayInitializationUI(ServiceChannel channel, AsyncCallback callback, object state) { return new DisplayInitializationUIAsyncResult(channel, _interactiveChannelInitializers, callback, state); } internal void EndDisplayInitializationUI(IAsyncResult result) { DisplayInitializationUIAsyncResult.End(result); } internal void InitializeChannel(IClientChannel channel) { try { for (int i = 0; i < _channelInitializers.Length; ++i) { _channelInitializers[i].Initialize(channel); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal ProxyOperationRuntime GetOperation(MethodBase methodBase, object[] args, out bool canCacheResult) { if (_operationSelector == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException (SR.Format(SR.SFxNeedProxyBehaviorOperationSelector2, methodBase.Name, methodBase.DeclaringType.Name))); } try { if (_operationSelector.AreParametersRequiredForSelection) { canCacheResult = false; } else { args = null; canCacheResult = true; } string operationName = _operationSelector.SelectOperation(methodBase, args); ProxyOperationRuntime operation; if ((operationName != null) && _operations.TryGetValue(operationName, out operation)) { return operation; } else { // did not find the right operation, will not know how // to invoke the method. return null; } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (ErrorBehavior.ShouldRethrowClientSideExceptionAsIs(e)) { throw; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperCallback(e); } } internal ProxyOperationRuntime GetOperationByName(string operationName) { ProxyOperationRuntime operation = null; if (_operations.TryGetValue(operationName, out operation)) return operation; else return null; } internal class DisplayInitializationUIAsyncResult : System.Runtime.AsyncResult { private ServiceChannel _channel; private int _index = -1; private IInteractiveChannelInitializer[] _initializers; private IClientChannel _proxy; private static AsyncCallback s_callback = Fx.ThunkCallback(new AsyncCallback(DisplayInitializationUIAsyncResult.Callback)); internal DisplayInitializationUIAsyncResult(ServiceChannel channel, IInteractiveChannelInitializer[] initializers, AsyncCallback callback, object state) : base(callback, state) { _channel = channel; _initializers = initializers; _proxy = ServiceChannelFactory.GetServiceChannel(channel.Proxy); this.CallBegin(true); } private void CallBegin(bool completedSynchronously) { while (++_index < _initializers.Length) { IAsyncResult result = null; Exception exception = null; try { result = _initializers[_index].BeginDisplayInitializationUI( _proxy, DisplayInitializationUIAsyncResult.s_callback, this ); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } if (exception == null) { if (!result.CompletedSynchronously) { return; } this.CallEnd(result, out exception); } if (exception != null) { this.CallComplete(completedSynchronously, exception); return; } } this.CallComplete(completedSynchronously, null); } private static void Callback(IAsyncResult result) { if (result.CompletedSynchronously) { return; } DisplayInitializationUIAsyncResult outer = (DisplayInitializationUIAsyncResult)result.AsyncState; Exception exception = null; outer.CallEnd(result, out exception); if (exception != null) { outer.CallComplete(false, exception); return; } outer.CallBegin(false); } private void CallEnd(IAsyncResult result, out Exception exception) { try { _initializers[_index].EndDisplayInitializationUI(result); exception = null; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } exception = e; } } private void CallComplete(bool completedSynchronously, Exception exception) { this.Complete(completedSynchronously, exception); } internal static void End(IAsyncResult result) { System.Runtime.AsyncResult.End<DisplayInitializationUIAsyncResult>(result); } } } }
// WARNING // // This file has been generated automatically by MonoDevelop to store outlets and // actions made in the Xcode designer. If it is removed, they will be lost. // Manual changes to this file may not be handled correctly. // using MonoMac.Foundation; namespace NBTExplorer { [Register ("AppDelegate")] partial class AppDelegate { [Outlet] MonoMac.AppKit.NSMenuItem _menuAbout { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuQuit { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuOpen { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuOpenFolder { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuOpenMinecraft { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuSave { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuCut { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuCopy { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuPaste { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuRename { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuEditValue { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuDelete { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuMoveUp { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuMoveDown { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuFind { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuFindNext { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertByte { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertShort { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertInt { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertLong { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertFloat { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertDouble { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertByteArray { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertIntArray { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertString { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertList { get; set; } [Outlet] MonoMac.AppKit.NSMenuItem _menuInsertCompound { get; set; } [Action ("ActionOpen:")] partial void ActionOpen (MonoMac.Foundation.NSObject sender); [Action ("ActionOpenFolder:")] partial void ActionOpenFolder (MonoMac.Foundation.NSObject sender); [Action ("ActionOpenMinecraft:")] partial void ActionOpenMinecraft (MonoMac.Foundation.NSObject sender); [Action ("ActionSave:")] partial void ActionSave (MonoMac.Foundation.NSObject sender); [Action ("ActionCut:")] partial void ActionCut (MonoMac.Foundation.NSObject sender); [Action ("ActionCopy:")] partial void ActionCopy (MonoMac.Foundation.NSObject sender); [Action ("ActionPaste:")] partial void ActionPaste (MonoMac.Foundation.NSObject sender); [Action ("ActionRename:")] partial void ActionRename (MonoMac.Foundation.NSObject sender); [Action ("ActionEditValue:")] partial void ActionEditValue (MonoMac.Foundation.NSObject sender); [Action ("ActionDelete:")] partial void ActionDelete (MonoMac.Foundation.NSObject sender); [Action ("ActionMoveUp:")] partial void ActionMoveUp (MonoMac.Foundation.NSObject sender); [Action ("ActionMoveDown:")] partial void ActionMoveDown (MonoMac.Foundation.NSObject sender); [Action ("ActionFind:")] partial void ActionFind (MonoMac.Foundation.NSObject sender); [Action ("ActionFindNext:")] partial void ActionFindNext (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertByte:")] partial void ActionInsertByte (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertShort:")] partial void ActionInsertShort (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertInt:")] partial void ActionInsertInt (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertLong:")] partial void ActionInsertLong (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertFloat:")] partial void ActionInsertFloat (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertDouble:")] partial void ActionInsertDouble (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertByteArray:")] partial void ActionInsertByteArray (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertIntArray:")] partial void ActionInsertIntArray (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertString:")] partial void ActionInsertString (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertList:")] partial void ActionInsertList (MonoMac.Foundation.NSObject sender); [Action ("ActionInsertCompound:")] partial void ActionInsertCompound (MonoMac.Foundation.NSObject sender); void ReleaseDesignerOutlets () { if (_menuAbout != null) { _menuAbout.Dispose (); _menuAbout = null; } if (_menuQuit != null) { _menuQuit.Dispose (); _menuQuit = null; } if (_menuOpen != null) { _menuOpen.Dispose (); _menuOpen = null; } if (_menuOpenFolder != null) { _menuOpenFolder.Dispose (); _menuOpenFolder = null; } if (_menuOpenMinecraft != null) { _menuOpenMinecraft.Dispose (); _menuOpenMinecraft = null; } if (_menuSave != null) { _menuSave.Dispose (); _menuSave = null; } if (_menuCut != null) { _menuCut.Dispose (); _menuCut = null; } if (_menuCopy != null) { _menuCopy.Dispose (); _menuCopy = null; } if (_menuPaste != null) { _menuPaste.Dispose (); _menuPaste = null; } if (_menuRename != null) { _menuRename.Dispose (); _menuRename = null; } if (_menuEditValue != null) { _menuEditValue.Dispose (); _menuEditValue = null; } if (_menuDelete != null) { _menuDelete.Dispose (); _menuDelete = null; } if (_menuMoveUp != null) { _menuMoveUp.Dispose (); _menuMoveUp = null; } if (_menuMoveDown != null) { _menuMoveDown.Dispose (); _menuMoveDown = null; } if (_menuFind != null) { _menuFind.Dispose (); _menuFind = null; } if (_menuFindNext != null) { _menuFindNext.Dispose (); _menuFindNext = null; } if (_menuInsertByte != null) { _menuInsertByte.Dispose (); _menuInsertByte = null; } if (_menuInsertShort != null) { _menuInsertShort.Dispose (); _menuInsertShort = null; } if (_menuInsertInt != null) { _menuInsertInt.Dispose (); _menuInsertInt = null; } if (_menuInsertLong != null) { _menuInsertLong.Dispose (); _menuInsertLong = null; } if (_menuInsertFloat != null) { _menuInsertFloat.Dispose (); _menuInsertFloat = null; } if (_menuInsertDouble != null) { _menuInsertDouble.Dispose (); _menuInsertDouble = null; } if (_menuInsertByteArray != null) { _menuInsertByteArray.Dispose (); _menuInsertByteArray = null; } if (_menuInsertIntArray != null) { _menuInsertIntArray.Dispose (); _menuInsertIntArray = null; } if (_menuInsertString != null) { _menuInsertString.Dispose (); _menuInsertString = null; } if (_menuInsertList != null) { _menuInsertList.Dispose (); _menuInsertList = null; } if (_menuInsertCompound != null) { _menuInsertCompound.Dispose (); _menuInsertCompound = null; } } } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; namespace dnlib.DotNet { /// <summary> /// A custom attribute /// </summary> public sealed class CustomAttribute : ICustomAttribute { ICustomAttributeType ctor; byte[] rawData; readonly IList<CAArgument> arguments; readonly IList<CANamedArgument> namedArguments; uint caBlobOffset; /// <summary> /// Gets/sets the custom attribute constructor /// </summary> public ICustomAttributeType Constructor { get => ctor; set => ctor = value; } /// <summary> /// Gets the attribute type /// </summary> public ITypeDefOrRef AttributeType => ctor?.DeclaringType; /// <summary> /// Gets the full name of the attribute type /// </summary> public string TypeFullName { get { if (ctor is MemberRef mrCtor) return mrCtor.GetDeclaringTypeFullName() ?? string.Empty; if (ctor is MethodDef mdCtor) { var declType = mdCtor.DeclaringType; if (declType is not null) return declType.FullName; } return string.Empty; } } /// <summary> /// <c>true</c> if the raw custom attribute blob hasn't been parsed /// </summary> public bool IsRawBlob => rawData is not null; /// <summary> /// Gets the raw custom attribute blob or <c>null</c> if the CA was successfully parsed. /// </summary> public byte[] RawData => rawData; /// <summary> /// Gets all constructor arguments /// </summary> public IList<CAArgument> ConstructorArguments => arguments; /// <summary> /// <c>true</c> if <see cref="ConstructorArguments"/> is not empty /// </summary> public bool HasConstructorArguments => arguments.Count > 0; /// <summary> /// Gets all named arguments (field and property values) /// </summary> public IList<CANamedArgument> NamedArguments => namedArguments; /// <summary> /// <c>true</c> if <see cref="NamedArguments"/> is not empty /// </summary> public bool HasNamedArguments => namedArguments.Count > 0; /// <summary> /// Gets all <see cref="CANamedArgument"/>s that are field arguments /// </summary> public IEnumerable<CANamedArgument> Fields { get { var namedArguments = this.namedArguments; int count = namedArguments.Count; for (int i = 0; i < count; i++) { var namedArg = namedArguments[i]; if (namedArg.IsField) yield return namedArg; } } } /// <summary> /// Gets all <see cref="CANamedArgument"/>s that are property arguments /// </summary> public IEnumerable<CANamedArgument> Properties { get { var namedArguments = this.namedArguments; int count = namedArguments.Count; for (int i = 0; i < count; i++) { var namedArg = namedArguments[i]; if (namedArg.IsProperty) yield return namedArg; } } } /// <summary> /// Gets the #Blob offset or 0 if unknown /// </summary> public uint BlobOffset => caBlobOffset; /// <summary> /// Constructor /// </summary> /// <param name="ctor">Custom attribute constructor</param> /// <param name="rawData">Raw custom attribute blob</param> public CustomAttribute(ICustomAttributeType ctor, byte[] rawData) : this(ctor, null, null, 0) => this.rawData = rawData; /// <summary> /// Constructor /// </summary> /// <param name="ctor">Custom attribute constructor</param> public CustomAttribute(ICustomAttributeType ctor) : this(ctor, null, null, 0) { } /// <summary> /// Constructor /// </summary> /// <param name="ctor">Custom attribute constructor</param> /// <param name="arguments">Constructor arguments or <c>null</c> if none</param> public CustomAttribute(ICustomAttributeType ctor, IEnumerable<CAArgument> arguments) : this(ctor, arguments, null) { } /// <summary> /// Constructor /// </summary> /// <param name="ctor">Custom attribute constructor</param> /// <param name="namedArguments">Named arguments or <c>null</c> if none</param> public CustomAttribute(ICustomAttributeType ctor, IEnumerable<CANamedArgument> namedArguments) : this(ctor, null, namedArguments) { } /// <summary> /// Constructor /// </summary> /// <param name="ctor">Custom attribute constructor</param> /// <param name="arguments">Constructor arguments or <c>null</c> if none</param> /// <param name="namedArguments">Named arguments or <c>null</c> if none</param> public CustomAttribute(ICustomAttributeType ctor, IEnumerable<CAArgument> arguments, IEnumerable<CANamedArgument> namedArguments) : this(ctor, arguments, namedArguments, 0) { } /// <summary> /// Constructor /// </summary> /// <param name="ctor">Custom attribute constructor</param> /// <param name="arguments">Constructor arguments or <c>null</c> if none</param> /// <param name="namedArguments">Named arguments or <c>null</c> if none</param> /// <param name="caBlobOffset">Original custom attribute #Blob offset or 0</param> public CustomAttribute(ICustomAttributeType ctor, IEnumerable<CAArgument> arguments, IEnumerable<CANamedArgument> namedArguments, uint caBlobOffset) { this.ctor = ctor; this.arguments = arguments is null ? new List<CAArgument>() : new List<CAArgument>(arguments); this.namedArguments = namedArguments is null ? new List<CANamedArgument>() : new List<CANamedArgument>(namedArguments); this.caBlobOffset = caBlobOffset; } /// <summary> /// Constructor /// </summary> /// <param name="ctor">Custom attribute constructor</param> /// <param name="arguments">Constructor arguments. The list is now owned by this instance.</param> /// <param name="namedArguments">Named arguments. The list is now owned by this instance.</param> /// <param name="caBlobOffset">Original custom attribute #Blob offset or 0</param> internal CustomAttribute(ICustomAttributeType ctor, List<CAArgument> arguments, List<CANamedArgument> namedArguments, uint caBlobOffset) { this.ctor = ctor; this.arguments = arguments ?? new List<CAArgument>(); this.namedArguments = namedArguments ?? new List<CANamedArgument>(); this.caBlobOffset = caBlobOffset; } /// <summary> /// Gets the field named <paramref name="name"/> /// </summary> /// <param name="name">Name of field</param> /// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns> public CANamedArgument GetField(string name) => GetNamedArgument(name, true); /// <summary> /// Gets the field named <paramref name="name"/> /// </summary> /// <param name="name">Name of field</param> /// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns> public CANamedArgument GetField(UTF8String name) => GetNamedArgument(name, true); /// <summary> /// Gets the property named <paramref name="name"/> /// </summary> /// <param name="name">Name of property</param> /// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns> public CANamedArgument GetProperty(string name) => GetNamedArgument(name, false); /// <summary> /// Gets the property named <paramref name="name"/> /// </summary> /// <param name="name">Name of property</param> /// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns> public CANamedArgument GetProperty(UTF8String name) => GetNamedArgument(name, false); /// <summary> /// Gets the property/field named <paramref name="name"/> /// </summary> /// <param name="name">Name of property/field</param> /// <param name="isField"><c>true</c> if it's a field, <c>false</c> if it's a property</param> /// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns> public CANamedArgument GetNamedArgument(string name, bool isField) { var namedArguments = this.namedArguments; int count = namedArguments.Count; for (int i = 0; i < count; i++) { var namedArg = namedArguments[i]; if (namedArg.IsField == isField && UTF8String.ToSystemStringOrEmpty(namedArg.Name) == name) return namedArg; } return null; } /// <summary> /// Gets the property/field named <paramref name="name"/> /// </summary> /// <param name="name">Name of property/field</param> /// <param name="isField"><c>true</c> if it's a field, <c>false</c> if it's a property</param> /// <returns>A <see cref="CANamedArgument"/> instance or <c>null</c> if not found</returns> public CANamedArgument GetNamedArgument(UTF8String name, bool isField) { var namedArguments = this.namedArguments; int count = namedArguments.Count; for (int i = 0; i < count; i++) { var namedArg = namedArguments[i]; if (namedArg.IsField == isField && UTF8String.Equals(namedArg.Name, name)) return namedArg; } return null; } /// <inheritdoc/> public override string ToString() => TypeFullName; } /// <summary> /// A custom attribute constructor argument /// </summary> public struct CAArgument : ICloneable { TypeSig type; object value; /// <summary> /// Gets/sets the argument type /// </summary> public TypeSig Type { readonly get => type; set => type = value; } /// <summary> /// Gets/sets the argument value /// </summary> public object Value { readonly get => value; set => this.value = value; } /// <summary> /// Constructor /// </summary> /// <param name="type">Argument type</param> public CAArgument(TypeSig type) { this.type = type; value = null; } /// <summary> /// Constructor /// </summary> /// <param name="type">Argument type</param> /// <param name="value">Argument value</param> public CAArgument(TypeSig type, object value) { this.type = type; this.value = value; } readonly object ICloneable.Clone() => Clone(); /// <summary> /// Clones this instance and any <see cref="CAArgument"/>s and <see cref="CANamedArgument"/>s /// referenced from this instance. /// </summary> /// <returns></returns> public readonly CAArgument Clone() { var value = this.value; if (value is CAArgument) value = ((CAArgument)value).Clone(); else if (value is IList<CAArgument> args) { var newArgs = new List<CAArgument>(args.Count); int count = args.Count; for (int i = 0; i < count; i++) { var arg = args[i]; newArgs.Add(arg.Clone()); } value = newArgs; } return new CAArgument(type, value); } /// <inheritdoc/> public override readonly string ToString() => $"{value ?? "null"} ({type})"; } /// <summary> /// A custom attribute field/property argument /// </summary> public sealed class CANamedArgument : ICloneable { bool isField; TypeSig type; UTF8String name; CAArgument argument; /// <summary> /// <c>true</c> if it's a field /// </summary> public bool IsField { get => isField; set => isField = value; } /// <summary> /// <c>true</c> if it's a property /// </summary> public bool IsProperty { get => !isField; set => isField = !value; } /// <summary> /// Gets/sets the field/property type /// </summary> public TypeSig Type { get => type; set => type = value; } /// <summary> /// Gets/sets the property/field name /// </summary> public UTF8String Name { get => name; set => name = value; } /// <summary> /// Gets/sets the argument /// </summary> public CAArgument Argument { get => argument; set => argument = value; } /// <summary> /// Gets/sets the argument type /// </summary> public TypeSig ArgumentType { get => argument.Type; set => argument.Type = value; } /// <summary> /// Gets/sets the argument value /// </summary> public object Value { get => argument.Value; set => argument.Value = value; } /// <summary> /// Default constructor /// </summary> public CANamedArgument() { } /// <summary> /// Constructor /// </summary> /// <param name="isField"><c>true</c> if field, <c>false</c> if property</param> public CANamedArgument(bool isField) => this.isField = isField; /// <summary> /// Constructor /// </summary> /// <param name="isField"><c>true</c> if field, <c>false</c> if property</param> /// <param name="type">Field/property type</param> public CANamedArgument(bool isField, TypeSig type) { this.isField = isField; this.type = type; } /// <summary> /// Constructor /// </summary> /// <param name="isField"><c>true</c> if field, <c>false</c> if property</param> /// <param name="type">Field/property type</param> /// <param name="name">Name of field/property</param> public CANamedArgument(bool isField, TypeSig type, UTF8String name) { this.isField = isField; this.type = type; this.name = name; } /// <summary> /// Constructor /// </summary> /// <param name="isField"><c>true</c> if field, <c>false</c> if property</param> /// <param name="type">Field/property type</param> /// <param name="name">Name of field/property</param> /// <param name="argument">Field/property argument</param> public CANamedArgument(bool isField, TypeSig type, UTF8String name, CAArgument argument) { this.isField = isField; this.type = type; this.name = name; this.argument = argument; } object ICloneable.Clone() => Clone(); /// <summary> /// Clones this instance and any <see cref="CAArgument"/>s referenced from this instance. /// </summary> /// <returns></returns> public CANamedArgument Clone() => new CANamedArgument(isField, type, name, argument.Clone()); /// <inheritdoc/> public override string ToString() => $"({(isField ? "field" : "property")}) {type} {name} = {Value ?? "null"} ({ArgumentType})"; } }
using System; using System.Collections.Generic; using System.Linq; using Foundation; using HomeKit; using UIKit; namespace HomeKitCatalog { public partial class RoomViewController : HMCatalogViewController, IHMAccessoryDelegate { static readonly NSString AccessoryCell = (NSString)"AccessoryCell"; static readonly NSString UnreachableAccessoryCell = (NSString)"UnreachableAccessoryCell"; static readonly string ModifyAccessorySegue = "Modify Accessory"; HMRoom room; public HMRoom Room { get { return room; } set { room = value; NavigationItem.Title = room.Name; } } List<HMAccessory> Accessories { get; set; } public RoomViewController (IntPtr handle) : base (handle) { } [Export ("initWithCoder:")] public RoomViewController (NSCoder coder) : base (coder) { } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); ReloadData (); } #region Table View Methods public override nint RowsInSection (UITableView tableView, nint section) { var rows = Accessories.Count; TableView.SetBackgroundMessage (rows == 0 ? "No Accessories" : null); return rows; } // returns: `true` if the current room is not the home's roomForEntireHome; `false` otherwise. public override bool CanEditRow (UITableView tableView, NSIndexPath indexPath) { return Room != Home.GetRoomForEntireHome (); } public override string TitleForDeleteConfirmation (UITableView tableView, NSIndexPath indexPath) { return "Unassign"; } public override void CommitEditingStyle (UITableView tableView, UITableViewCellEditingStyle editingStyle, NSIndexPath indexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) UnassignAccessory (Accessories [indexPath.Row]); } // returns: A cell representing an accessory. public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var accessory = Accessories [indexPath.Row]; var reuseIdentifier = AccessoryCell; if (!accessory.Reachable) reuseIdentifier = UnreachableAccessoryCell; var cell = tableView.DequeueReusableCell (reuseIdentifier, indexPath); cell.TextLabel.Text = accessory.Name; return cell; } public override string TitleForHeader (UITableView tableView, nint section) { return Accessories.Any () ? "Accessories" : null; } #endregion #region Helpers // Updates the internal array of accessories and reloads the table view. void ReloadData () { if (Accessories == null) Accessories = new List<HMAccessory> (); Accessories.Clear (); Accessories.AddRange (Room.Accessories); Accessories.SortByLocalizedName (a => a.Name); } // Sorts the internal list of accessories by localized name. void SortAccessories () { Accessories.SortByLocalizedName (a => a.Name); } // Registers as the delegate for the current home and all accessories in our room. protected override void RegisterAsDelegate () { base.RegisterAsDelegate (); foreach (var accessory in Room.Accessories) accessory.Delegate = this; } // Sets the accessory and home of the modifyAccessoryViewController that will be presented. public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender) { base.PrepareForSegue (segue, sender); var indexPath = TableView.IndexPathForCell ((UITableViewCell)sender); if (segue.Identifier == ModifyAccessorySegue) { var modifyViewController = (ModifyAccessoryViewController)segue.IntendedDestinationViewController (); modifyViewController.Accessory = Room.Accessories [indexPath.Row]; } } // Adds an accessory into the internal list of accessories and inserts the row into the table view. void DidAssignAccessory (HMAccessory accessory) { Accessories.Add (accessory); SortAccessories (); var newAccessoryIndex = Accessories.IndexOf (accessory); if (newAccessoryIndex >= 0) { var newAccessoryIndexPath = NSIndexPath.FromRowSection (newAccessoryIndex, 0); TableView.InsertRows (new []{ newAccessoryIndexPath }, UITableViewRowAnimation.Automatic); } } // Removes an accessory from the internal list of accessory (if it exists) and deletes the row from the table view. void DidUnassignAccessory (HMAccessory accessory) { var accessoryIndex = Accessories.IndexOf (accessory); if (accessoryIndex >= 0) { Accessories.RemoveAt (accessoryIndex); var accessoryIndexPath = NSIndexPath.FromRowSection (accessoryIndex, 0); TableView.DeleteRows (new [] { accessoryIndexPath }, UITableViewRowAnimation.Automatic); } } // Assigns an accessory to the current room. void AssignAccessory (HMAccessory accessory) { DidAssignAccessory (accessory); Home.AssignAccessory (accessory, room, error => { if (error != null) { DisplayError (error); DidUnassignAccessory (accessory); } }); } // Assigns the current room back into `roomForEntireHome`. void UnassignAccessory (HMAccessory accessory) { DidUnassignAccessory (accessory); Home.AssignAccessory (accessory, Home.GetRoomForEntireHome (), error => { if (error != null) { DisplayError (error); DidAssignAccessory (accessory); } }); } // Finds an accessory in the internal array of accessories and updates its row in the table view. void DidModifyAccessory (HMAccessory accessory) { var index = Accessories.IndexOf (accessory); if (index >= 0) TableView.ReloadRows (new []{ NSIndexPath.FromRowSection (index, 0) }, UITableViewRowAnimation.Automatic); } #endregion #region HMHomeDelegate Methods // If the accessory was added to this room, insert it. [Export ("home:didAddAccessory:")] public void DidAddAccessory (HMHome home, HMAccessory accessory) { if (accessory.Room == room) { accessory.Delegate = this; DidAssignAccessory (accessory); } } // Remove the accessory from our room, if required. [Export ("home:didRemoveAccessory:")] public void DidRemoveAccessory (HMHome home, HMAccessory accessory) { DidUnassignAccessory (accessory); } // Handles the update. // // We act based on one of three options: // // 1. A new accessory is being added to this room. // 2. An accessory is being assigned from this room to another room. // 3. We can ignore this message. [Export ("home:didUpdateRoom:forAccessory:")] public void DidUpdateRoom (HMHome home, HMRoom room, HMAccessory accessory) { if (room == Room) DidAssignAccessory (accessory); else if (Accessories.Contains (accessory)) DidUnassignAccessory (accessory); } // If our room was removed, pop back. [Export ("home:didRemoveRoom:")] public void DidRemoveRoom (HMHome home, HMRoom room) { if (room == Room) NavigationController.PopViewController (true); } // If our room was renamed, reload our title. [Export ("home:didUpdateNameForRoom:")] public void DidUpdateNameForRoom (HMHome home, HMRoom room) { if (room == Room) NavigationItem.Title = room.Name; } #endregion #region HMAccessoryDelegate Methods // Accessory updates will reload the cell for the accessory. [Export ("accessoryDidUpdateReachability:")] public void DidUpdateReachability (HMAccessory accessory) { DidModifyAccessory (accessory); } [Export ("accessoryDidUpdateName:")] public void DidUpdateName (HMAccessory accessory) { DidModifyAccessory (accessory); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using Nop.Core; using Nop.Core.Domain.Catalog; using Nop.Core.Domain.Common; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Directory; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Tax; using Nop.Core.Plugins; using Nop.Services.Common; using Nop.Services.Directory; namespace Nop.Services.Tax { /// <summary> /// Tax service /// </summary> public partial class TaxService : ITaxService { #region Fields private readonly IAddressService _addressService; private readonly IWorkContext _workContext; private readonly TaxSettings _taxSettings; private readonly IPluginFinder _pluginFinder; private readonly IGeoLookupService _geoLookupService; private readonly ICountryService _countryService; private readonly CustomerSettings _customerSettings; private readonly AddressSettings _addressSettings; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="addressService">Address service</param> /// <param name="workContext">Work context</param> /// <param name="taxSettings">Tax settings</param> /// <param name="pluginFinder">Plugin finder</param> /// <param name="geoLookupService">GEO lookup service</param> /// <param name="countryService">Country service</param> /// <param name="customerSettings">Customer settings</param> /// <param name="addressSettings">Address settings</param> public TaxService(IAddressService addressService, IWorkContext workContext, TaxSettings taxSettings, IPluginFinder pluginFinder, IGeoLookupService geoLookupService, ICountryService countryService, CustomerSettings customerSettings, AddressSettings addressSettings) { this._addressService = addressService; this._workContext = workContext; this._taxSettings = taxSettings; this._pluginFinder = pluginFinder; this._geoLookupService = geoLookupService; this._countryService = countryService; this._customerSettings = customerSettings; this._addressSettings = addressSettings; } #endregion #region Utilities /// <summary> /// Get a value indicating whether a customer is consumer (a person, not a company) located in Europe Union /// </summary> /// <param name="customer">Customer</param> /// <returns>Result</returns> protected virtual bool IsEuConsumer(Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); Country country = null; //get country from billing address if (_addressSettings.CountryEnabled && customer.BillingAddress != null) country = customer.BillingAddress.Country; //get country specified during registration? if (country == null && _customerSettings.CountryEnabled) { var countryId = customer.GetAttribute<int>(SystemCustomerAttributeNames.CountryId); country = _countryService.GetCountryById(countryId); } //get country by IP address if (country == null) { var ipAddress = customer.LastIpAddress; //ipAddress = _webHelper.GetCurrentIpAddress(); var countryIsoCode = _geoLookupService.LookupCountryIsoCode(ipAddress); country = _countryService.GetCountryByTwoLetterIsoCode(countryIsoCode); } //we cannot detect country if (country == null) return false; //outside EU if (!country.SubjectToVat) return false; //company (business) or consumer? var customerVatStatus = (VatNumberStatus)customer.GetAttribute<int>(SystemCustomerAttributeNames.VatNumberStatusId); if (customerVatStatus == VatNumberStatus.Valid) return false; //TODO: use specified company name? (both address and registration one) //consumer return true; } /// <summary> /// Create request for tax calculation /// </summary> /// <param name="product">Product</param> /// <param name="taxCategoryId">Tax category identifier</param> /// <param name="customer">Customer</param> /// <returns>Package for tax calculation</returns> protected virtual CalculateTaxRequest CreateCalculateTaxRequest(Product product, int taxCategoryId, Customer customer) { if (customer == null) throw new ArgumentNullException("customer"); var calculateTaxRequest = new CalculateTaxRequest(); calculateTaxRequest.Customer = customer; if (taxCategoryId > 0) { calculateTaxRequest.TaxCategoryId = taxCategoryId; } else { if (product != null) calculateTaxRequest.TaxCategoryId = product.TaxCategoryId; } var basedOn = _taxSettings.TaxBasedOn; //new EU VAT rules starting January 1st 2015 //find more info at http://ec.europa.eu/taxation_customs/taxation/vat/how_vat_works/telecom/index_en.htm#new_rules //EU VAT enabled? if (_taxSettings.EuVatEnabled) { //telecommunications, broadcasting and electronic services? if (product != null && product.IsTelecommunicationsOrBroadcastingOrElectronicServices) { //January 1st 2015 passed? if (DateTime.UtcNow > new DateTime(2015, 1, 1, 0, 0, 0, DateTimeKind.Utc)) { //Europe Union consumer? if (IsEuConsumer(customer)) { //We must charge VAT in the EU country where the customer belongs (not where the business is based) basedOn = TaxBasedOn.BillingAddress; } } } } if (basedOn == TaxBasedOn.BillingAddress && customer.BillingAddress == null) basedOn = TaxBasedOn.DefaultAddress; if (basedOn == TaxBasedOn.ShippingAddress && customer.ShippingAddress == null) basedOn = TaxBasedOn.DefaultAddress; Address address = null; switch (basedOn) { case TaxBasedOn.BillingAddress: { address = customer.BillingAddress; } break; case TaxBasedOn.ShippingAddress: { address = customer.ShippingAddress; } break; case TaxBasedOn.DefaultAddress: default: { address = _addressService.GetAddressById(_taxSettings.DefaultTaxAddressId); } break; } calculateTaxRequest.Address = address; return calculateTaxRequest; } /// <summary> /// Calculated price /// </summary> /// <param name="price">Price</param> /// <param name="percent">Percent</param> /// <param name="increase">Increase</param> /// <returns>New price</returns> protected virtual decimal CalculatePrice(decimal price, decimal percent, bool increase) { if (percent == decimal.Zero) return price; decimal result; if (increase) { result = price * (1 + percent / 100); } else { result = price - (price) / (100 + percent) * percent; } return result; } /// <summary> /// Gets tax rate /// </summary> /// <param name="product">Product</param> /// <param name="taxCategoryId">Tax category identifier</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Calculated tax rate</param> /// <param name="isTaxable">A value indicating whether a request is taxable</param> protected virtual void GetTaxRate(Product product, int taxCategoryId, Customer customer, out decimal taxRate, out bool isTaxable) { taxRate = decimal.Zero; isTaxable = true; //active tax provider var activeTaxProvider = LoadActiveTaxProvider(); if (activeTaxProvider == null) { //throw new NopException("Active tax provider cannot be loaded. Please select at least one in admin area."); return; } //tax exempt if (IsTaxExempt(product, customer)) { isTaxable = false; } //tax request var calculateTaxRequest = CreateCalculateTaxRequest(product, taxCategoryId, customer); //make EU VAT exempt validation (the European Union Value Added Tax) if (_taxSettings.EuVatEnabled) { if (IsVatExempt(calculateTaxRequest.Address, calculateTaxRequest.Customer)) { //VAT is not chargeable isTaxable = false; } } //get tax rate var calculateTaxResult = activeTaxProvider.GetTaxRate(calculateTaxRequest); if (calculateTaxResult.Success) { //ensure that tax is equal or greater than zero if (calculateTaxResult.TaxRate < decimal.Zero) calculateTaxResult.TaxRate = decimal.Zero; taxRate = calculateTaxResult.TaxRate; } } #endregion #region Methods /// <summary> /// Load active tax provider /// </summary> /// <returns>Active tax provider</returns> public virtual ITaxProvider LoadActiveTaxProvider() { var taxProvider = LoadTaxProviderBySystemName(_taxSettings.ActiveTaxProviderSystemName); if (taxProvider == null) taxProvider = LoadAllTaxProviders().FirstOrDefault(); return taxProvider; } /// <summary> /// Load tax provider by system name /// </summary> /// <param name="systemName">System name</param> /// <returns>Found tax provider</returns> public virtual ITaxProvider LoadTaxProviderBySystemName(string systemName) { var descriptor = _pluginFinder.GetPluginDescriptorBySystemName<ITaxProvider>(systemName); if (descriptor != null) return descriptor.Instance<ITaxProvider>(); return null; } /// <summary> /// Load all tax providers /// </summary> /// <returns>Tax providers</returns> public virtual IList<ITaxProvider> LoadAllTaxProviders() { return _pluginFinder.GetPlugins<ITaxProvider>().ToList(); } /// <summary> /// Gets price /// </summary> /// <param name="product">Product</param> /// <param name="price">Price</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetProductPrice(Product product, decimal price, out decimal taxRate) { var customer = _workContext.CurrentCustomer; return GetProductPrice(product, price, customer, out taxRate); } /// <summary> /// Gets price /// </summary> /// <param name="product">Product</param> /// <param name="price">Price</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetProductPrice(Product product, decimal price, Customer customer, out decimal taxRate) { bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax; return GetProductPrice(product, price, includingTax, customer, out taxRate); } /// <summary> /// Gets price /// </summary> /// <param name="product">Product</param> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetProductPrice(Product product, decimal price, bool includingTax, Customer customer, out decimal taxRate) { bool priceIncludesTax = _taxSettings.PricesIncludeTax; int taxCategoryId = 0; return GetProductPrice(product, taxCategoryId, price, includingTax, customer, priceIncludesTax, out taxRate); } /// <summary> /// Gets price /// </summary> /// <param name="product">Product</param> /// <param name="taxCategoryId">Tax category identifier</param> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="priceIncludesTax">A value indicating whether price already includes tax</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetProductPrice(Product product, int taxCategoryId, decimal price, bool includingTax, Customer customer, bool priceIncludesTax, out decimal taxRate) { //no need to calculate tax rate if passed "price" is 0 if (price == decimal.Zero) { taxRate = decimal.Zero; return taxRate; } bool isTaxable; GetTaxRate(product, taxCategoryId, customer, out taxRate, out isTaxable); if (priceIncludesTax) { //"price" already includes tax if (!includingTax) { //we should calculated price WITHOUT tax price = CalculatePrice(price, taxRate, false); } else { //we should calculated price WITH tax if (!isTaxable) { //but our request is not taxable //hence we should calculated price WITHOUT tax price = CalculatePrice(price, taxRate, false); } } } else { //"price" doesn't include tax if (includingTax) { //we should calculated price WITH tax //do it only when price is taxable if (isTaxable) { price = CalculatePrice(price, taxRate, true); } } } if (!isTaxable) { //we return 0% tax rate in case a request is not taxable taxRate = decimal.Zero; } //allowed to support negative price adjustments //if (price < decimal.Zero) // price = decimal.Zero; return price; } /// <summary> /// Gets shipping price /// </summary> /// <param name="price">Price</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetShippingPrice(decimal price, Customer customer) { bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax; return GetShippingPrice(price, includingTax, customer); } /// <summary> /// Gets shipping price /// </summary> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetShippingPrice(decimal price, bool includingTax, Customer customer) { decimal taxRate; return GetShippingPrice(price, includingTax, customer, out taxRate); } /// <summary> /// Gets shipping price /// </summary> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetShippingPrice(decimal price, bool includingTax, Customer customer, out decimal taxRate) { taxRate = decimal.Zero; if (!_taxSettings.ShippingIsTaxable) { return price; } int taxClassId = _taxSettings.ShippingTaxClassId; bool priceIncludesTax = _taxSettings.ShippingPriceIncludesTax; return GetProductPrice(null, taxClassId, price, includingTax, customer, priceIncludesTax, out taxRate); } /// <summary> /// Gets payment method additional handling fee /// </summary> /// <param name="price">Price</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetPaymentMethodAdditionalFee(decimal price, Customer customer) { bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax; return GetPaymentMethodAdditionalFee(price, includingTax, customer); } /// <summary> /// Gets payment method additional handling fee /// </summary> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetPaymentMethodAdditionalFee(decimal price, bool includingTax, Customer customer) { decimal taxRate; return GetPaymentMethodAdditionalFee(price, includingTax, customer, out taxRate); } /// <summary> /// Gets payment method additional handling fee /// </summary> /// <param name="price">Price</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetPaymentMethodAdditionalFee(decimal price, bool includingTax, Customer customer, out decimal taxRate) { taxRate = decimal.Zero; if (!_taxSettings.PaymentMethodAdditionalFeeIsTaxable) { return price; } int taxClassId = _taxSettings.PaymentMethodAdditionalFeeTaxClassId; bool priceIncludesTax = _taxSettings.PaymentMethodAdditionalFeeIncludesTax; return GetProductPrice(null, taxClassId, price, includingTax, customer, priceIncludesTax, out taxRate); } /// <summary> /// Gets checkout attribute value price /// </summary> /// <param name="cav">Checkout attribute value</param> /// <returns>Price</returns> public virtual decimal GetCheckoutAttributePrice(CheckoutAttributeValue cav) { var customer = _workContext.CurrentCustomer; return GetCheckoutAttributePrice(cav, customer); } /// <summary> /// Gets checkout attribute value price /// </summary> /// <param name="cav">Checkout attribute value</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetCheckoutAttributePrice(CheckoutAttributeValue cav, Customer customer) { bool includingTax = _workContext.TaxDisplayType == TaxDisplayType.IncludingTax; return GetCheckoutAttributePrice(cav, includingTax, customer); } /// <summary> /// Gets checkout attribute value price /// </summary> /// <param name="cav">Checkout attribute value</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <returns>Price</returns> public virtual decimal GetCheckoutAttributePrice(CheckoutAttributeValue cav, bool includingTax, Customer customer) { decimal taxRate; return GetCheckoutAttributePrice(cav, includingTax, customer, out taxRate); } /// <summary> /// Gets checkout attribute value price /// </summary> /// <param name="cav">Checkout attribute value</param> /// <param name="includingTax">A value indicating whether calculated price should include tax</param> /// <param name="customer">Customer</param> /// <param name="taxRate">Tax rate</param> /// <returns>Price</returns> public virtual decimal GetCheckoutAttributePrice(CheckoutAttributeValue cav, bool includingTax, Customer customer, out decimal taxRate) { if (cav == null) throw new ArgumentNullException("cav"); taxRate = decimal.Zero; decimal price = cav.PriceAdjustment; if (cav.CheckoutAttribute.IsTaxExempt) { return price; } bool priceIncludesTax = _taxSettings.PricesIncludeTax; int taxClassId = cav.CheckoutAttribute.TaxCategoryId; return GetProductPrice(null, taxClassId, price, includingTax, customer, priceIncludesTax, out taxRate); } /// <summary> /// Gets VAT Number status /// </summary> /// <param name="fullVatNumber">Two letter ISO code of a country and VAT number (e.g. GB 111 1111 111)</param> /// <returns>VAT Number status</returns> public virtual VatNumberStatus GetVatNumberStatus(string fullVatNumber) { string name, address; return GetVatNumberStatus(fullVatNumber, out name, out address); } /// <summary> /// Gets VAT Number status /// </summary> /// <param name="fullVatNumber">Two letter ISO code of a country and VAT number (e.g. GB 111 1111 111)</param> /// <param name="name">Name (if received)</param> /// <param name="address">Address (if received)</param> /// <returns>VAT Number status</returns> public virtual VatNumberStatus GetVatNumberStatus(string fullVatNumber, out string name, out string address) { name = string.Empty; address = string.Empty; if (String.IsNullOrWhiteSpace(fullVatNumber)) return VatNumberStatus.Empty; fullVatNumber = fullVatNumber.Trim(); //GB 111 1111 111 or GB 1111111111 //more advanced regex - http://codeigniter.com/wiki/European_Vat_Checker var r = new Regex(@"^(\w{2})(.*)"); var match = r.Match(fullVatNumber); if (!match.Success) return VatNumberStatus.Invalid; var twoLetterIsoCode = match.Groups[1].Value; var vatNumber = match.Groups[2].Value; return GetVatNumberStatus(twoLetterIsoCode, vatNumber, out name, out address); } /// <summary> /// Gets VAT Number status /// </summary> /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param> /// <param name="vatNumber">VAT number</param> /// <returns>VAT Number status</returns> public virtual VatNumberStatus GetVatNumberStatus(string twoLetterIsoCode, string vatNumber) { string name, address; return GetVatNumberStatus(twoLetterIsoCode, vatNumber, out name, out address); } /// <summary> /// Gets VAT Number status /// </summary> /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param> /// <param name="vatNumber">VAT number</param> /// <param name="name">Name (if received)</param> /// <param name="address">Address (if received)</param> /// <returns>VAT Number status</returns> public virtual VatNumberStatus GetVatNumberStatus(string twoLetterIsoCode, string vatNumber, out string name, out string address) { name = string.Empty; address = string.Empty; if (String.IsNullOrEmpty(twoLetterIsoCode)) return VatNumberStatus.Empty; if (String.IsNullOrEmpty(vatNumber)) return VatNumberStatus.Empty; if (_taxSettings.EuVatAssumeValid) return VatNumberStatus.Valid; if (!_taxSettings.EuVatUseWebService) return VatNumberStatus.Unknown; Exception exception; return DoVatCheck(twoLetterIsoCode, vatNumber, out name, out address, out exception); } /// <summary> /// Performs a basic check of a VAT number for validity /// </summary> /// <param name="twoLetterIsoCode">Two letter ISO code of a country</param> /// <param name="vatNumber">VAT number</param> /// <param name="name">Company name</param> /// <param name="address">Address</param> /// <param name="exception">Exception</param> /// <returns>VAT number status</returns> public virtual VatNumberStatus DoVatCheck(string twoLetterIsoCode, string vatNumber, out string name, out string address, out Exception exception) { name = string.Empty; address = string.Empty; if (vatNumber == null) vatNumber = string.Empty; vatNumber = vatNumber.Trim().Replace(" ", ""); if (twoLetterIsoCode == null) twoLetterIsoCode = string.Empty; if (!String.IsNullOrEmpty(twoLetterIsoCode)) //The service returns INVALID_INPUT for country codes that are not uppercase. twoLetterIsoCode = twoLetterIsoCode.ToUpper(); EuropaCheckVatService.checkVatService s = null; try { bool valid; s = new EuropaCheckVatService.checkVatService(); s.checkVat(ref twoLetterIsoCode, ref vatNumber, out valid, out name, out address); exception = null; return valid ? VatNumberStatus.Valid : VatNumberStatus.Invalid; } catch (Exception ex) { name = address = string.Empty; exception = ex; return VatNumberStatus.Unknown; } finally { if (name == null) name = string.Empty; if (address == null) address = string.Empty; if (s != null) s.Dispose(); } } /// <summary> /// Gets a value indicating whether a product is tax exempt /// </summary> /// <param name="product">Product</param> /// <param name="customer">Customer</param> /// <returns>A value indicating whether a product is tax exempt</returns> public virtual bool IsTaxExempt(Product product, Customer customer) { if (customer != null) { if (customer.IsTaxExempt) return true; if (customer.CustomerRoles.Where(cr => cr.Active).Any(cr => cr.TaxExempt)) return true; } if (product == null) { return false; } if (product.IsTaxExempt) { return true; } return false; } /// <summary> /// Gets a value indicating whether EU VAT exempt (the European Union Value Added Tax) /// </summary> /// <param name="address">Address</param> /// <param name="customer">Customer</param> /// <returns>Result</returns> public virtual bool IsVatExempt(Address address, Customer customer) { if (!_taxSettings.EuVatEnabled) return false; if (address == null || address.Country == null || customer == null) return false; if (!address.Country.SubjectToVat) // VAT not chargeable if shipping outside VAT zone return true; // VAT not chargeable if address, customer and config meet our VAT exemption requirements: // returns true if this customer is VAT exempt because they are shipping within the EU but outside our shop country, they have supplied a validated VAT number, and the shop is configured to allow VAT exemption var customerVatStatus = (VatNumberStatus) customer.GetAttribute<int>(SystemCustomerAttributeNames.VatNumberStatusId); return address.CountryId != _taxSettings.EuVatShopCountryId && customerVatStatus == VatNumberStatus.Valid && _taxSettings.EuVatAllowVatExemption; } #endregion } }
using System; using System.Collections.Generic; //Epsilon 2011 class Solution { #region Private Structs & Classes //Represents cartesian coordinates in two dimensions private struct CartesianCoordinates { #region Properties public double X { get; private set; } public double Y { get; private set; } #endregion #region Constructor public CartesianCoordinates(double x, double y) : this() { X = x; Y = y; } #endregion } //Represents linear function private class LinearFunction : IComparable<LinearFunction>, IComparable { #region Properties public int Slope { get; private set; } public int Intercept { get; private set; } #endregion #region Constructor public LinearFunction(int slope, int intercept) { Slope = slope; Intercept = intercept; } #endregion #region Methods public double Evaluate(double x) { return Slope * x + Intercept; } public CartesianCoordinates? Intersect(LinearFunction other) { if (this.Slope == other.Slope) return null; double x = (double)(this.Intercept - other.Intercept) / (double)(other.Slope - this.Slope); return new CartesianCoordinates(x, this.Evaluate(x)); } #endregion #region IComparable Members public int CompareTo(LinearFunction other) { //If slope and intercept are equal we treat the functions as equal if (this.Slope == other.Slope && this.Intercept == other.Intercept) return 0; //Functions with smaller slope first, if slope is equal the larger intercept goes first else if (this.Slope < other.Slope || (this.Slope == other.Slope && this.Intercept > other.Intercept)) return -1; else return 1; } public int CompareTo(object obj) { if (obj == null) throw new ArgumentNullException("obj"); if (!(obj is LinearFunction)) throw new ArgumentException("Object must be of type LinearFunction", "obj"); return CompareTo((LinearFunction)obj); } #endregion } //Represents envelope for collection of linear functions (envelope consist of lines and intersection points at which those lines connect) private class Envelope { #region Properties public LinearFunction[] Lines { get; private set; } public CartesianCoordinates[] Intersections { get; private set; } #endregion #region Constructor public Envelope(LinearFunction[] lines, CartesianCoordinates[] intersections) { Lines = lines; Intersections = intersections; } #endregion } #endregion #region Private Enums private enum EnvelopeKind { Upper, Lower } #endregion #region Fields private int _leftBorder = -10000000; private int _rightBorder = 10000000; #endregion #region Public Methods public double solution(int[] A, int[] B) { //This is where result will be stored double result = Double.MaxValue; //Sanity check if (A != null && A.Length > 0 && B != null && B.Length > 0) { int N = A.Length; //We will treat every A[K]*X+B as linear function LinearFunction[] functions = new LinearFunction[N]; for (int i = 0; i < N; i++) functions[i] = new LinearFunction(A[i], B[i]); //We sort the functions by slope and intercept Array.Sort<LinearFunction>(functions); //We get the upper and lower envelopes for the functions collection Envelope upperEnvelope = GetEnvelope(functions, EnvelopeKind.Upper); Envelope lowerEnvelope = GetEnvelope(functions, EnvelopeKind.Lower); int upperEnvelopePointIndex = 1; int lowerEnvelopePointIndex = 1; //We need to minimaze the distance between envelopes, we will start by going through upper envelope while (upperEnvelopePointIndex < upperEnvelope.Intersections.Length) { double distance = Double.MaxValue; //If current intersection in upper envelope lies before the current intersection in lower envelope (or there are no more intersections in lower envelope) if (upperEnvelope.Intersections[upperEnvelopePointIndex].X < lowerEnvelope.Intersections[lowerEnvelopePointIndex].X || lowerEnvelopePointIndex == lowerEnvelope.Intersections.Length - 1) { //The distance is equal to value at current intersection from upper envelope minus the value of current function from lower envelope in this point distance = upperEnvelope.Intersections[upperEnvelopePointIndex].Y - lowerEnvelope.Lines[lowerEnvelopePointIndex - 1].Evaluate(upperEnvelope.Intersections[upperEnvelopePointIndex].X); //We move to next intersection in upper envelope upperEnvelopePointIndex++; } //Otherwise (the current intersection in upper envelope lies further than current intersection in lower envelope and there are still other intersection in lower envelope) else { //The distance is equal to the value of current function from upper envelope in this point minus value at current intersection from lower envelope distance = upperEnvelope.Lines[upperEnvelopePointIndex - 1].Evaluate(lowerEnvelope.Intersections[lowerEnvelopePointIndex].X) - lowerEnvelope.Intersections[lowerEnvelopePointIndex].Y; //We move to next intersection in lower envelope lowerEnvelopePointIndex++; } //If new distance is smaller than result which we laready have if (distance < result) //We update the result result = distance; } } //Return the result return result; } #endregion #region Private methods private Envelope GetEnvelope(LinearFunction[] functions, EnvelopeKind kind) { Envelope envelope = null; if (functions != null && functions.Length > 0) { int firstFunctionIndex, lastFunctionIndex, functionsIterationStep; //While looking for upper envelope we will go from first to last function if (kind == EnvelopeKind.Upper) { firstFunctionIndex = 0; lastFunctionIndex = functions.Length - 1; functionsIterationStep = 1; } //While looking for lower envelope we will go from last to first function else { firstFunctionIndex = functions.Length - 1; lastFunctionIndex = 0; functionsIterationStep = -1; } List<LinearFunction> lines = new List<LinearFunction>(); List<CartesianCoordinates> points = new List<CartesianCoordinates>(); //We set the first line in the envelope LinearFunction previousLine = functions[firstFunctionIndex]; lines.Add(previousLine); //And calculate "theoretical" furthest to left point points.Add(new CartesianCoordinates(_leftBorder, previousLine.Evaluate(_leftBorder))); //We will look for intersection points between the functions for (int i = firstFunctionIndex + functionsIterationStep; (kind == EnvelopeKind.Upper && i <= lastFunctionIndex) || (kind == EnvelopeKind.Lower && i >= lastFunctionIndex); i += functionsIterationStep) { LinearFunction currentLine = functions[i]; //Because we have taken intercept into consideration while sorting we can skip parallel lines if (currentLine.Slope != previousLine.Slope) { //We add an intersection between previous and current line to the points collection points.Add(previousLine.Intersect(currentLine).Value); //If the latest intersection point lies before any of the previous one, we need to update those intersections to find the actual last intersection int lastIntersectionIndex = points.Count - 1; while (points[lastIntersectionIndex].X < points[lastIntersectionIndex - 1].X) { //Calculate the intersection between current on previous line points[lastIntersectionIndex - 1] = lines[lastIntersectionIndex - 2].Intersect(currentLine).Value; //Remove the no longer valid intersection and line points.RemoveAt(lastIntersectionIndex); lines.RemoveAt(lastIntersectionIndex - 1); lastIntersectionIndex--; } //We add current line to the lines collection previousLine = currentLine; lines.Add(previousLine); } } //We calculate "theoretical" furthest to right point points.Add(new CartesianCoordinates(_rightBorder, previousLine.Evaluate(_rightBorder))); envelope = new Envelope(lines.ToArray(), points.ToArray()); } return envelope; } #endregion }
// The MIT License (MIT) // // CoreTweet - A .NET Twitter Library supporting Twitter API 1.1 // Copyright (c) 2014 lambdalice // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq.Expressions; using CoreTweet.Core; namespace CoreTweet.Rest { /// <summary>GET/POST users</summary> public partial class Users : ApiProviderBase { internal Users(TokensBase e) : base(e) { } #if !PCL //GET Methods /// <summary> /// <para>Returns a collection of users that the specified user can "contribute" to.</para> /// <para>Note: A user_id or screen_name is required.</para> /// <para>Avaliable parameters: </para> /// <para><paramref name="long user_id (optional)"/> : The ID of the user for whom to return results for. Helpful for disambiguating when a valid user ID is also a valid screen name.</para> /// <para><paramref name="string screen_name (optional)"/> : The screen name of the user for whom to return results for.</para> /// <para><paramref name="bool include_entities (optional)"/> : The entities node will be disincluded when set to false.</para> /// <para><paramref name="bool skip_status (optional)"/> : When set to either true, t or 1 statuses will not be included in the returned user objects.</para> /// </summary> /// <returns>Users.</returns> /// <param name='parameters'> /// Parameters. /// </param> public IEnumerable<User> Contributees(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessApiArray<User>(MethodType.Get, "users/contributees", parameters); } public IEnumerable<User> Contributees(IDictionary<string, object> parameters) { return this.Tokens.AccessApiArray<User>(MethodType.Get, "users/contributees", parameters); } public IEnumerable<User> Contributees<T>(T parameters) { return this.Tokens.AccessApiArray<User, T>(MethodType.Get, "users/contributees", parameters); } /// <summary> /// <para>Returns a collection of users who can contribute to the specified account.</para> /// <para>Note: A user_id or screen_name is required.</para> /// <para>Avaliable parameters: </para> /// <para><paramref name="long user_id (optional)"/> : The ID of the user for whom to return results for.</para> /// <para><paramref name="string screen_name (optional)"/> : The screen name of the user for whom to return results for.</para> /// <para><paramref name="bool include_entities (optional)"/> : The entities node will be disincluded when set to false.</para> /// <para><paramref name="bool skip_status (optional)"/> : When set to either true, t or 1 statuses will not be included in the returned user objects.</para> /// </summary> /// <returns>Users.</returns> /// <param name='parameters'> /// Parameters. /// </param> public IEnumerable<User> Contributors(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessApiArray<User>(MethodType.Get, "users/contributors", parameters); } public IEnumerable<User> Contributors(IDictionary<string, object> parameters) { return this.Tokens.AccessApiArray<User>(MethodType.Get, "users/contributors", parameters); } public IEnumerable<User> Contributors<T>(T parameters) { return this.Tokens.AccessApiArray<User, T>(MethodType.Get, "users/contributors", parameters); } /// <summary> /// <para>Returns fully-hydrated user objects for up to 100 users per request, as specified by comma-separated values passed to the user_id and/or screen_name parameters.</para> /// <para>This method is especially useful when used in conjunction with collections of user IDs returned from GET friends/ids and GET followers/ids.</para> /// <para>GET users/show is used to retrieve a single user object.</para> /// <para>Avaliable parameters: </para> /// <para><paramref name="string, IEnumerable<long> user_id (optional)"/> : A list of user IDs or comma separated string of ones, up to 100 are allowed in a single request. You are strongly encouraged to use a POST for larger requests.</para> /// <para><paramref name="string, IEnumerable<string> screen_name (optional)"/> : A list of screen names or comma separated string of ones, up to 100 are allowed in a single request. You are strongly encouraged to use a POST for larger (up to 100 screen names) requests.</para> /// <para><paramref name="bool include_entities (optional)"/> : The entities node that may appear within embedded statuses will be disincluded when set to false.</para> /// </summary> /// <returns>Users.</returns> /// <param name='parameters'> /// Parameters. /// </param> public IEnumerable<User> Lookup(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessApiArray<User>(MethodType.Get, "users/lookup", parameters); } public IEnumerable<User> Lookup(IDictionary<string, object> parameters) { return this.Tokens.AccessApiArray<User>(MethodType.Get, "users/lookup", parameters); } public IEnumerable<User> Lookup<T>(T parameters) { return this.Tokens.AccessApiArray<User, T>(MethodType.Get, "users/lookup", parameters); } /// <summary> /// <para>Returns the size of the specified user's profile banner. If the user has not uploaded a profile banner, a HTTP 404 will be served instead. This method can be used instead of string manipulation on the profile_banner_url returned in user objects as described in User Profile Images and Banners.</para> /// <para>Note: Always specify either an user_id or screen_name when requesting this method.</para> /// <para>Avaliable parameters: </para> /// <para><paramref name="long id (optional)"/> : The ID of the user for whom to return results for. Helpful for disambiguating when a valid user ID is also a valid screen name.</para> /// <para><paramref name="string screen_name (optional)"/> : The screen name of the user for whom to return results for. Helpful for disambiguating when a valid screen name is also a user ID.</para> /// </summary> /// <returns>The size.</returns> /// <param name='parameters'> /// Parameters. /// </param> public ProfileBannerSizes ProfileBanner(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessApi<ProfileBannerSizes>(MethodType.Get, "users/profile_banner", parameters, "sizes"); } public ProfileBannerSizes ProfileBanner(IDictionary<string, object> parameters) { return this.Tokens.AccessApi<ProfileBannerSizes>(MethodType.Get, "users/profile_banner", parameters, "sizes"); } public ProfileBannerSizes ProfileBanner<T>(T parameters) { return this.Tokens.AccessApi<ProfileBannerSizes, T>(MethodType.Get, "users/profile_banner", parameters, "sizes"); } /// <summary> /// <para>Provides a simple, relevance-based search interface to public user accounts on Twitter. Try querying by topical interest, full name, company name, location, or other criteria. Exact match searches are not supported.</para> /// <para>Only the first 1,000 matching results are available.</para> /// <para>Avaliable parameters: </para> /// <para><paramref name="string q (required)"/> : The search query to run against people search.</para> /// <para><paramref name="int page (optional)"/> : Specifies the page of results to retrieve.</para> /// <para><paramref name="int count (optional)"/> : The number of potential user results to retrieve per page. This value has a maximum of 20.</para> /// <para><paramref name="bool include_entities (optional)"/> : The entities node will be disincluded from embedded tweet objects when set to false.</para> /// </summary> /// <returns>Users.</returns> /// <param name='parameters'> /// Parameters. /// </param> public IEnumerable<User> Search(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessApiArray<User>(MethodType.Get, "users/search", parameters); } public IEnumerable<User> Search(IDictionary<string, object> parameters) { return this.Tokens.AccessApiArray<User>(MethodType.Get, "users/search", parameters); } public IEnumerable<User> Search<T>(T parameters) { return this.Tokens.AccessApiArray<User, T>(MethodType.Get, "users/search", parameters); } /// <summary> /// <para>Returns a variety of information about the user specified by the required user_id or screen_name parameter. The author's most recent Tweet will be returned inline when possible.</para> /// <para>GET users/lookup is used to retrieve a bulk collection of user objects.</para> /// <para>Avaliable parameters: </para> /// <para><paramref name="long user_id (required)"/> : The ID of the user for whom to return results for. Either an id or screen_name is required for this method.</para> /// <para><paramref name="string screen_name (required)"/> : The screen name of the user for whom to return results for. Either a id or screen_name is required for this method.</para> /// <para><paramref name="bool include_entities (optional)"/> : The entities node will be disincluded when set to false.</para> /// </summary> /// <returns>The user.</returns> /// <param name='parameters'> /// Parameters. /// </param> public User Show(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessApi<User>(MethodType.Get, "users/show", parameters); } public User Show(IDictionary<string, object> parameters) { return this.Tokens.AccessApi<User>(MethodType.Get, "users/show", parameters); } public User Show<T>(T parameters) { return this.Tokens.AccessApi<User, T>(MethodType.Get, "users/show", parameters); } /// <summary> /// <para>Access to Twitter's suggested user list. This returns the list of suggested user categories. The category can be used in GET users/suggestions/:slug to get the users in that category.</para> /// <para>Avaliable parameters: </para> /// <para><paramref name="string lang (optional)"/> : Restricts the suggested categories to the requested language. The language must be specified by the appropriate two letter ISO 639-1 representation. Currently supported languages are provided by the GET help/languages API request. Unsupported language codes will receive English (en) results. If you use lang in this request, ensure you also include it when requesting the GET users/suggestions/:slug list.</para> /// </summary> /// <returns>Catgories.</returns> /// <param name='parameters'> /// Parameters. /// </param> public IEnumerable<Category> Suggestions(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessApiArray<Category>(MethodType.Get, "users/suggestions", parameters); } public IEnumerable<Category> Suggestions(IDictionary<string, object> parameters) { return this.Tokens.AccessApiArray<Category>(MethodType.Get, "users/suggestions", parameters); } public IEnumerable<Category> Suggestions<T>(T parameters) { return this.Tokens.AccessApiArray<Category, T>(MethodType.Get, "users/suggestions", parameters); } /// <summary> /// <para>Access the users in a given category of the Twitter suggested user list.</para> /// <para>It is recommended that applications cache this data for no more than one hour.</para> /// <para><paramref name="string slug (required)"/> : The short name of list or a category</para> /// <para><paramref name="string lang (optional)"/> : Restricts the suggested categories to the requested language. The language must be specified by the appropriate two letter ISO 639-1 representation. Currently supported languages are provided by the GET help/languages API request. Unsupported language codes will receive English (en) results. If you use lang in this request, ensure you also include it when requesting the GET users/suggestions/:slug list.</para> /// </summary> /// <returns>The category.</returns> /// <param name="parameters"> /// Parameters. /// </param> public Category Suggestion(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessParameterReservedApi<Category>(MethodType.Get, "users/suggestions/{slug}", "slug", InternalUtils.ExpressionsToDictionary(parameters)); } public Category Suggestion(IDictionary<string, object> parameters) { return this.Tokens.AccessParameterReservedApi<Category>(MethodType.Get, "users/suggestions/{slug}", "slug", parameters); } public Category Suggestion<T>(T parameters) { return this.Tokens.AccessParameterReservedApi<Category>(MethodType.Get, "users/suggestions/{slug}", "slug", InternalUtils.ResolveObject(parameters)); } /// <summary> /// <para>Access the users in a given category of the Twitter suggested user list and return their most recent status if they are not a protected user.</para> /// <para>Avaliable parameters: </para> /// <para><paramref name="string slug (required)"/> : The short name of list or a category</para> /// </summary> /// <returns>Users.</returns> /// <param name='parameters'> /// Parameters. /// </param> public IEnumerable<User> SuggestedMembers(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessParameterReservedApiArray<User>(MethodType.Get, "users/suggestions/{slug}/members", "slug", InternalUtils.ExpressionsToDictionary(parameters)); } public IEnumerable<User> SuggestedMembers(IDictionary<string, object> parameters) { return this.Tokens.AccessParameterReservedApiArray<User>(MethodType.Get, "users/suggestions/{slug}/members", "slug", parameters); } public IEnumerable<User> SuggestedMembers<T>(T parameters) { return this.Tokens.AccessParameterReservedApiArray<User>(MethodType.Get, "users/suggestions/{slug}/members", "slug", InternalUtils.ResolveObject(parameters)); } //POST Method /// <summary> /// <para>Report the specified user as a spam account to Twitter. Additionally performs the equivalent of POST blocks/create on behalf of the authenticated user.</para> /// <para>Note: One of these parameters must be provided.</para> /// <para>Avaliable parameters: </para> /// <para><paramref name="string screen_name (optional)"/> : The ID or screen_name of the user you want to report as a spammer. Helpful for disambiguating when a valid screen name is also a user ID.</para> /// <para><paramref name="long user_id (optional)"/> : The ID of the user you want to report as a spammer. Helpful for disambiguating when a valid user ID is also a valid screen name.</para> /// </summary> /// <returns>The User.</returns> /// <param name='parameters'> /// Parameters. /// </param> public User ReportSpam(params Expression<Func<string, object>>[] parameters) { return this.Tokens.AccessApi<User>(MethodType.Post, "users/report_spam", parameters); } public User ReportSpam(IDictionary<string, object> parameters) { return this.Tokens.AccessApi<User>(MethodType.Post, "users/report_spam", parameters); } public User ReportSpam<T>(T parameters) { return this.Tokens.AccessApi<User, T>(MethodType.Post, "users/report_spam", parameters); } #endif } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Autodesk.Revit.DB; using Revit.SDK.Samples.CurtainSystem.CS.Data; namespace Revit.SDK.Samples.CurtainSystem.CS.UI { /// <summary> /// the main window form for UI operations /// </summary> public partial class CurtainForm : System.Windows.Forms.Form { // the document containing all the data used in the sample MyDocument m_mydocument; /// <summary> /// constructor /// </summary> /// <param name="mydoc"> /// the data used in the sample /// </param> public CurtainForm(MyDocument mydoc) { m_mydocument = mydoc; InitializeComponent(); // initialize some controls manually InitializeCustomComponent(); // register the customized events RegisterEvents(); } /// <summary> /// initialize some controls manually /// </summary> private void InitializeCustomComponent() { this.deleteCSButton.Enabled = false; this.addCGButton.Enabled = false; this.removeCGButton.Enabled = false; } /// <summary> /// register the customized events /// </summary> private void RegisterEvents() { m_mydocument.FatalErrorEvent += new MyDocument.FatalErrorHandler(m_document_FatalErrorEvent); m_mydocument.SystemData.CurtainSystemChanged += new CurtainSystem.SystemData.CurtainSystemChangedHandler(m_document_SystemData_CurtainSystemChanged); // moniter the sample message change status m_mydocument.MessageChanged += new MyDocument.MessageChangedHandler(m_document_MessageChanged); } /// <summary> /// Fatal error occurs, close the sample dialog directly /// </summary> /// <param name="errorMsg"> /// the error hint shown to user /// </param> void m_document_FatalErrorEvent(string errorMsg) { // hang the sample and shown the error hint to users DialogResult result = MessageBox.Show(errorMsg, Properties.Resources.TXT_DialogTitle, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly); // the user has read the hint and clicked the "OK" button, close the dialog if (DialogResult.OK == result) { this.Close(); } } /// <summary> /// curtain system changed(added/removed), refresh the lists /// </summary> void m_document_SystemData_CurtainSystemChanged() { // clear the out-of-date values csListBox.Items.Clear(); facesCheckedListBox.Items.Clear(); cgCheckedListBox.Items.Clear(); List<CurtainSystem.SystemInfo> csInfos = m_mydocument.SystemData.CurtainSystemInfos; // no curtain system available, disable the "Delete Curtain System" // "Add curtain grid" and "remove curtain grid" buttons if (null == csInfos || 0 == csInfos.Count) { this.deleteCSButton.Enabled = false; this.addCGButton.Enabled = false; this.removeCGButton.Enabled = false; this.Show(); return; } foreach (CurtainSystem.SystemInfo info in csInfos) { csListBox.Items.Add(info); } // activate the last one CurtainSystem.SystemInfo csInfo = csInfos[csInfos.Count - 1]; // this will invoke the selectedIndexChanged event, then to update the other 2 list boxes csListBox.SetSelected(csInfos.Count - 1, true); // enable the buttons and show the dialog this.deleteCSButton.Enabled = true; // only curtain system which created by reference array supports curtain grid operations if (false == csInfo.ByFaceArray) { this.addCGButton.Enabled = true; this.removeCGButton.Enabled = true; } this.Show(); } /// <summary> /// update the status hints in the status strip /// </summary> void m_document_MessageChanged() { //if it's an error / warning message, set the color of the text to red KeyValuePair<string, bool> message = m_mydocument.Message; if (true == message.Value) { this.operationStatusLabel.ForeColor = System.Drawing.Color.Red; } // it's a common hint message, set the color to black else { this.operationStatusLabel.ForeColor = System.Drawing.Color.Black; } this.operationStatusLabel.Text = message.Key; this.statusStrip.Refresh(); } /// <summary> /// "Create curtain system" button clicked, hide the main form, /// pop up the create curtain system dialog to let user add a new curtain system. /// After the curtain system created, close the dialog and show the main form again /// </summary> /// <param name="sender"> /// object who sent this event /// </param> /// <param name="e"> /// event args /// </param> private void createCSButton_Click(object sender, EventArgs e) { this.Hide(); // show the "create curtain system" dialog using (CreateCurtainSystemDialog dlg = new CreateCurtainSystemDialog(m_mydocument)) { dlg.ShowDialog(this); } } /// <summary> /// delete the checked curtain systems in the curtain system list box /// </summary> /// <param name="sender"> /// object who sent this event /// </param> /// <param name="e"> /// event args /// </param> private void deleteCSButton_Click(object sender, EventArgs e) { // no curtain system available, ask sample user to create some curtain systems first if (null == csListBox.Items || 0 == csListBox.Items.Count) { string hint = Properties.Resources.HINT_CreateCSFirst; m_mydocument.Message = new KeyValuePair<string, bool>(hint, true); return; } // get the checked curtain sytems List<int> checkedIndices = new List<int>(); for (int i = 0; i < csListBox.Items.Count; i++) { bool itemChecked = csListBox.GetItemChecked(i); if (true == itemChecked) { checkedIndices.Add(i); } } // no curtain system available or no curtain system selected for deletion // update the status hints if (null == checkedIndices || 0 == checkedIndices.Count) { string hint = Properties.Resources.HINT_SelectCSFirst; m_mydocument.Message = new KeyValuePair<string, bool>(hint, true); return; } // delete them m_mydocument.SystemData.DeleteCurtainSystem(checkedIndices); } /// <summary> /// the selected curtain system changed, update the "Curtain grid" and /// "Uncovered faces" list boxes of the selected curtain system /// </summary> /// <param name="sender"> /// object who sent this event /// </param> /// <param name="e"> /// event args /// </param> private void csListBox_SelectedIndexChanged(object sender, EventArgs e) { List<CurtainSystem.SystemInfo> csInfos = m_mydocument.SystemData.CurtainSystemInfos; // data verification if (null == csInfos || 0 == csInfos.Count) { return; } // // step 1: activate the selected one // CurtainSystem.SystemInfo csInfo = csInfos[csListBox.SelectedIndex]; // update the curtain grid list box cgCheckedListBox.Items.Clear(); foreach (int index in csInfo.GridFacesIndices) { CurtainSystem.GridFaceInfo gridFaceInfo = new CurtainSystem.GridFaceInfo(index); cgCheckedListBox.Items.Add(gridFaceInfo); } // update the uncovered face list box facesCheckedListBox.Items.Clear(); foreach (int index in csInfo.UncoverFacesIndices) { CurtainSystem.UncoverFaceInfo uncoverFaceInfo = new CurtainSystem.UncoverFaceInfo(index); facesCheckedListBox.Items.Add(uncoverFaceInfo); } // // step 2: enable/disable some buttons and refresh the status hints // // the selected curtain system is created by face array // it's not allowed to modify its curtain grids data if (true == csInfo.ByFaceArray) { // disable the buttons this.addCGButton.Enabled = false; this.removeCGButton.Enabled = false; this.facesCheckedListBox.Enabled = false; this.cgCheckedListBox.Enabled = false; // update the status hints string hint = Properties.Resources.HINT_CSIsByFaceArray; m_mydocument.Message = new KeyValuePair<string, bool>(hint, false); } // the selected curtain system is created by references of the faces // it's allowed to modify its curtain grids data else { // enable the buttons if (null == facesCheckedListBox.Items || 0 == facesCheckedListBox.Items.Count) { this.addCGButton.Enabled = false; } else { this.addCGButton.Enabled = true; } // at least one curtain grid must be kept if (null == cgCheckedListBox.Items || 2 > cgCheckedListBox.Items.Count) { this.removeCGButton.Enabled = false; } else { this.removeCGButton.Enabled = true; } this.facesCheckedListBox.Enabled = true; this.cgCheckedListBox.Enabled = true; // update the status hints string hint = ""; m_mydocument.Message = new KeyValuePair<string, bool>(hint, false); } } /// <summary> /// add curtain grids to the checked faces /// </summary> /// <param name="sender"> /// object who sent this event /// </param> /// <param name="e"> /// event args /// </param> private void addCGButton_Click(object sender, EventArgs e) { // step 1: get the curtain system List<CurtainSystem.SystemInfo> csInfos = m_mydocument.SystemData.CurtainSystemInfos; // no curtain system available, ask sample user to create some curtain systems first if (null == csInfos || 0 == csInfos.Count) { string hint = Properties.Resources.HINT_CreateCSFirst; m_mydocument.Message = new KeyValuePair<string, bool>(hint, true); return; } CurtainSystem.SystemInfo csInfo = csInfos[csListBox.SelectedIndex]; // if the curtain system is created by face array, it's forbidden to make other operations on it if (true == csInfo.ByFaceArray) { return; } // step 2: find out the faces to be covered List<int> faceIndices = new List<int>(); for (int i = 0; i < facesCheckedListBox.Items.Count; i++) { bool itemChecked = facesCheckedListBox.GetItemChecked(i); if (true == itemChecked) { CurtainSystem.UncoverFaceInfo info = facesCheckedListBox.Items[i] as CurtainSystem.UncoverFaceInfo; faceIndices.Add(info.Index); } } // no uncovered faces selected, warn the sample user if (null == faceIndices || 0 == faceIndices.Count) { string hint = Properties.Resources.HINT_SelectFaceFirst; m_mydocument.Message = new KeyValuePair<string, bool>(hint, true); return; } // step 3: cover the selected faces with curtain grids csInfo.AddCurtainGrids(faceIndices); // step 4: update the UI list boxes csListBox_SelectedIndexChanged(null, null); } /// <summary> /// remove the checked curtain grids from the curtain system /// Note: curtain system must have at least one curtain grid /// so sample users can't remove all the curtain grids away /// </summary> /// <param name="sender"> /// object who sent this event /// </param> /// <param name="e"> /// event args /// </param> private void removeCGButton_Click(object sender, EventArgs e) { // step 1: get the curtain system List<CurtainSystem.SystemInfo> csInfos = m_mydocument.SystemData.CurtainSystemInfos; // no curtain system available, ask sample user to create some curtain systems first if (null == csInfos || 0 == csInfos.Count) { string hint = Properties.Resources.HINT_CreateCSFirst; m_mydocument.Message = new KeyValuePair<string, bool>(hint, true); return; } CurtainSystem.SystemInfo csInfo = csInfos[csListBox.SelectedIndex]; // if the curtain system is created by face array, it's forbidden to make other operations on it if (true == csInfo.ByFaceArray) { return; } // step 2: find out the curtain grids to be removed List<int> faceIndices = new List<int>(); for (int i = 0; i < cgCheckedListBox.Items.Count; i++) { bool itemChecked = cgCheckedListBox.GetItemChecked(i); if (true == itemChecked) { CurtainSystem.GridFaceInfo info = cgCheckedListBox.Items[i] as CurtainSystem.GridFaceInfo; faceIndices.Add(info.FaceIndex); } } // no curtain grids selected, warn the sample user if (null == faceIndices || 0 == faceIndices.Count) { string hint = Properties.Resources.HINT_SelectCGFirst; m_mydocument.Message = new KeyValuePair<string, bool>(hint, true); return; } // step 3: remove the selected curtain grids csInfo.RemoveCurtainGrids(faceIndices); // step 4: update the UI list boxes csListBox_SelectedIndexChanged(null, null); } /// <summary> /// check the curtain grids to delete them, if user wants to check all the curtain /// grids for deletion, prohibit it (must keep at least one curtain grid) /// </summary> /// <param name="sender"> /// object who sent this event /// </param> /// <param name="e"> /// event args /// </param> private void cgCheckedListBox_ItemCheck(object sender, ItemCheckEventArgs e) { List<int> indices = new List<int>(); // get all the unchecked curtain grids for (int i = 0; i < cgCheckedListBox.Items.Count; i++) { bool itemChecked = cgCheckedListBox.GetItemChecked(i); if (false == itemChecked) { indices.Add(i); } } // for curtain system, we must keep at least one curtain grid // so it's not allowed to select all the curtain grids to remove if (indices.Count <= 1 && CheckState.Unchecked == e.CurrentValue) { e.NewValue = CheckState.Unchecked; // update the status hints string hint = Properties.Resources.HINT_KeepOneCG; m_mydocument.Message = new KeyValuePair<string, bool>(hint, true); } else { // update the status hints string hint = ""; m_mydocument.Message = new KeyValuePair<string, bool>(hint, false); } } private void facesCheckedListBox_SelectedIndexChanged(object sender, EventArgs e) { } private void mainPanel_Paint(object sender, PaintEventArgs e) { } private void csLabel_Click(object sender, EventArgs e) { } } // end of class }
// Copyright 2016 Renaud Paquay All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Text; namespace mtsuite.CoreFileSystem.Utils { /// <summary> /// An abstraction over a sequence of bytes allocated from the Native HEAP. /// </summary> public class ByteBuffer : IDisposable { private readonly SafeHGlobalHandle _memoryHandle = new SafeHGlobalHandle(); private int _capacity; public ByteBuffer(int capacity) { Allocate(capacity); } private void Allocate(int capacity) { if (capacity <= 0) { throw new ArgumentException("Capacity must be positive", "capacity"); } _memoryHandle.Realloc(capacity); _capacity = capacity; } public int Capacity { get { return _capacity; } set { Allocate(value); } } public IntPtr Pointer { get { return _memoryHandle.Pointer; } } public void Dispose() { _memoryHandle.Dispose(); } public override string ToString() { var sb = new StringBuilder(); sb.AppendFormat("Capacity={0}, [", Capacity); for (var i = 0; i < Capacity; i++) { sb.AppendFormat("0x{0:X2}, ", (byte)ReadFromMemory(i, 1)); } sb.AppendFormat("]"); return sb.ToString(); } public string ReadString(int offset, int count) { CheckRange(offset, count); var sb = new StringBuffer(); ReadString(offset, count, sb); return sb.Text; } public unsafe void ReadString(int offset, int count, StringBuffer stringBuffer) { CheckRange(offset, count); var bufferStart = (char*)(Pointer + offset).ToPointer(); for (var i = 0; i < count; i++) { stringBuffer.Append(bufferStart[i]); } } public void WriteString(int offset, string value) { WriteString(offset, value, value.Length + 1); } public void WriteString(int offset, StringBuffer stringBuffer) { WriteString(offset, stringBuffer, stringBuffer.Length + 1); } public unsafe void WriteString(int offset, string value, int count) { count = Math.Min(count, value.Length + 1); fixed (char* valuePtr = value) { WriteCharacters(offset, count, valuePtr); } } public unsafe void WriteString(int offset, StringBuffer stringBuffer, int count) { count = Math.Min(count, stringBuffer.Length + 1); fixed (char* valuePtr = stringBuffer.Data) { WriteCharacters(offset, count, valuePtr); } } public unsafe void WriteCharacters(int offset, int count, char* source) { EnsureCapacity(offset, count * sizeof(char)); char* bufferStart = (char*)(Pointer + offset).ToPointer(); while (count > 0) { *bufferStart = *source; bufferStart++; source++; count--; } } public void WriteInt8(int offset, sbyte value) { WriteToMemory(offset, sizeof(sbyte), AsUInt64(value)); } public void WriteUInt8(int offset, byte value) { WriteToMemory(offset, sizeof(byte), AsUInt64(value)); } public void WriteInt16(int offset, short value) { WriteToMemory(offset, sizeof(short), AsUInt64(value)); } public void WriteUInt16(int offset, ushort value) { WriteToMemory(offset, sizeof(ushort), AsUInt64(value)); } public void WriteInt32(int offset, int value) { WriteToMemory(offset, sizeof(int), AsUInt64(value)); } public void WriteUInt32(int offset, uint value) { WriteToMemory(offset, sizeof(uint), AsUInt64(value)); } public void WriteInt64(int offset, long value) { WriteToMemory(offset, sizeof(long), AsUInt64(value)); } public void WriteUInt64(int offset, ulong value) { WriteToMemory(offset, sizeof(ulong), AsUInt64(value)); } public unsafe UInt64 ReadFromMemory(int offset, int size) { CheckRange(offset, size); void* bufferStart = (Pointer + offset).ToPointer(); switch (size) { case 1: return *(byte*)bufferStart; case 2: return *(ushort*)bufferStart; case 4: return *(uint*)bufferStart; case 8: return *(ulong*)bufferStart; } throw new InvalidOperationException("Invalid field size (must be 1, 2, 4 or 8)"); } public unsafe void WriteToMemory(int offset, int size, UInt64 value) { EnsureCapacity(offset, size); void* bufferStart = (Pointer + offset).ToPointer(); switch (size) { case 1: *(byte*)bufferStart = AsUInt8(value); break; case 2: *(ushort*)bufferStart = AsUInt16(value); break; case 4: *(uint*)bufferStart = AsUInt32(value); break; case 8: *(ulong*)bufferStart = AsUInt64(value); break; default: throw new ArgumentException("Invalid size (must be 1, 2, 4 or 8)", "size"); } } public static byte AsUInt8(ulong value) { return unchecked((byte)value); } public static ushort AsUInt16(ulong value) { return unchecked((ushort)value); } public static uint AsUInt32(ulong value) { return unchecked((uint)value); } public static ulong AsUInt64(byte value) { return value; } public static ulong AsUInt64(short value) { return unchecked((ulong)value); } public static ulong AsUInt64(int value) { return unchecked((ulong)value); } public static ulong AsUInt64(long value) { return unchecked((ulong)value); } public static ulong AsUInt64(ulong value) { return value; } private void CheckRange(int offset, int size) { if (offset < 0) ThrowInvalidRange(offset, size); if (size < 0) ThrowInvalidRange(offset, size); if (checked(offset + size) > Capacity) ThrowInvalidRange(offset, size); } private void EnsureCapacity(int offset, int size) { if (offset < 0) ThrowInvalidRange(offset, size); if (size < 0) ThrowInvalidRange(offset, size); checked { if (_capacity >= offset + size) return; var newCapacity = _capacity; while (newCapacity < offset + size) { newCapacity *= 2; } Allocate(newCapacity); } } private void ThrowInvalidRange(int offset, int size) { throw new InvalidOperationException(string.Format("Trying to read past end of buffer (Offset={0}, Size={1}, Capacity={2}", offset, size, Capacity)); } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // MONO 1.0 Beta mcs does not like #if !A && !B && !C syntax // .NET Compact Framework 1.0 has no support for EventLog #if !NETCF // SSCLI 1.0 has no support for EventLog #if !SSCLI using System; using System.Diagnostics; using System.Globalization; using log4net.Util; using log4net.Layout; using log4net.Core; namespace log4net.Appender { /// <summary> /// Writes events to the system event log. /// </summary> /// <remarks> /// <para> /// The appender will fail if you try to write using an event source that doesn't exist unless it is running with local administrator privileges. /// See also http://logging.apache.org/log4net/release/faq.html#trouble-EventLog /// </para> /// <para> /// The <c>EventID</c> of the event log entry can be /// set using the <c>EventID</c> property (<see cref="LoggingEvent.Properties"/>) /// on the <see cref="LoggingEvent"/>. /// </para> /// <para> /// The <c>Category</c> of the event log entry can be /// set using the <c>Category</c> property (<see cref="LoggingEvent.Properties"/>) /// on the <see cref="LoggingEvent"/>. /// </para> /// <para> /// There is a limit of 32K characters for an event log message /// </para> /// <para> /// When configuring the EventLogAppender a mapping can be /// specified to map a logging level to an event log entry type. For example: /// </para> /// <code lang="XML"> /// &lt;mapping&gt; /// &lt;level value="ERROR" /&gt; /// &lt;eventLogEntryType value="Error" /&gt; /// &lt;/mapping&gt; /// &lt;mapping&gt; /// &lt;level value="DEBUG" /&gt; /// &lt;eventLogEntryType value="Information" /&gt; /// &lt;/mapping&gt; /// </code> /// <para> /// The Level is the standard log4net logging level and eventLogEntryType can be any value /// from the <see cref="EventLogEntryType"/> enum, i.e.: /// <list type="bullet"> /// <item><term>Error</term><description>an error event</description></item> /// <item><term>Warning</term><description>a warning event</description></item> /// <item><term>Information</term><description>an informational event</description></item> /// </list> /// </para> /// </remarks> /// <author>Aspi Havewala</author> /// <author>Douglas de la Torre</author> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Thomas Voss</author> public class EventLogAppender : AppenderSkeleton { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="EventLogAppender" /> class. /// </summary> /// <remarks> /// <para> /// Default constructor. /// </para> /// </remarks> public EventLogAppender() { m_applicationName = System.Threading.Thread.GetDomain().FriendlyName; m_logName = "Application"; // Defaults to application log m_machineName = "."; // Only log on the local machine } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// The name of the log where messages will be stored. /// </summary> /// <value> /// The string name of the log where messages will be stored. /// </value> /// <remarks> /// <para>This is the name of the log as it appears in the Event Viewer /// tree. The default value is to log into the <c>Application</c> /// log, this is where most applications write their events. However /// if you need a separate log for your application (or applications) /// then you should set the <see cref="LogName"/> appropriately.</para> /// <para>This should not be used to distinguish your event log messages /// from those of other applications, the <see cref="ApplicationName"/> /// property should be used to distinguish events. This property should be /// used to group together events into a single log. /// </para> /// </remarks> public string LogName { get { return m_logName; } set { m_logName = value; } } /// <summary> /// Property used to set the Application name. This appears in the /// event logs when logging. /// </summary> /// <value> /// The string used to distinguish events from different sources. /// </value> /// <remarks> /// Sets the event log source property. /// </remarks> public string ApplicationName { get { return m_applicationName; } set { m_applicationName = value; } } /// <summary> /// This property is used to return the name of the computer to use /// when accessing the event logs. Currently, this is the current /// computer, denoted by a dot "." /// </summary> /// <value> /// The string name of the machine holding the event log that /// will be logged into. /// </value> /// <remarks> /// This property cannot be changed. It is currently set to '.' /// i.e. the local machine. This may be changed in future. /// </remarks> public string MachineName { get { return m_machineName; } set { /* Currently we do not allow the machine name to be changed */; } } /// <summary> /// Add a mapping of level to <see cref="EventLogEntryType"/> - done by the config file /// </summary> /// <param name="mapping">The mapping to add</param> /// <remarks> /// <para> /// Add a <see cref="Level2EventLogEntryType"/> mapping to this appender. /// Each mapping defines the event log entry type for a level. /// </para> /// </remarks> public void AddMapping(Level2EventLogEntryType mapping) { m_levelMapping.Add(mapping); } /// <summary> /// Gets or sets the <see cref="SecurityContext"/> used to write to the EventLog. /// </summary> /// <value> /// The <see cref="SecurityContext"/> used to write to the EventLog. /// </value> /// <remarks> /// <para> /// The system security context used to write to the EventLog. /// </para> /// <para> /// Unless a <see cref="SecurityContext"/> specified here for this appender /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the /// security context to use. The default behavior is to use the security context /// of the current thread. /// </para> /// </remarks> public SecurityContext SecurityContext { get { return m_securityContext; } set { m_securityContext = value; } } /// <summary> /// Gets or sets the <c>EventId</c> to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties. /// </summary> /// <remarks> /// <para> /// The <c>EventID</c> of the event log entry will normally be /// set using the <c>EventID</c> property (<see cref="LoggingEvent.Properties"/>) /// on the <see cref="LoggingEvent"/>. /// This property provides the fallback value which defaults to 0. /// </para> /// </remarks> public int EventId { get { return m_eventId; } set { m_eventId = value; } } /// <summary> /// Gets or sets the <c>Category</c> to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties. /// </summary> /// <remarks> /// <para> /// The <c>Category</c> of the event log entry will normally be /// set using the <c>Category</c> property (<see cref="LoggingEvent.Properties"/>) /// on the <see cref="LoggingEvent"/>. /// This property provides the fallback value which defaults to 0. /// </para> /// </remarks> public short Category { get { return m_category; } set { m_category = value; } } #endregion // Public Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> override public void ActivateOptions() { try { base.ActivateOptions(); if (m_securityContext == null) { m_securityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } bool sourceAlreadyExists = false; string currentLogName = null; using (SecurityContext.Impersonate(this)) { sourceAlreadyExists = EventLog.SourceExists(m_applicationName); if (sourceAlreadyExists) { currentLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); } } if (sourceAlreadyExists && currentLogName != m_logName) { LogLog.Debug(declaringType, "Changing event source [" + m_applicationName + "] from log [" + currentLogName + "] to log [" + m_logName + "]"); } else if (!sourceAlreadyExists) { LogLog.Debug(declaringType, "Creating event source Source [" + m_applicationName + "] in log " + m_logName + "]"); } string registeredLogName = null; using (SecurityContext.Impersonate(this)) { if (sourceAlreadyExists && currentLogName != m_logName) { // // Re-register this to the current application if the user has changed // the application / logfile association // EventLog.DeleteEventSource(m_applicationName, m_machineName); CreateEventSource(m_applicationName, m_logName, m_machineName); registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); } else if (!sourceAlreadyExists) { CreateEventSource(m_applicationName, m_logName, m_machineName); registeredLogName = EventLog.LogNameFromSourceName(m_applicationName, m_machineName); } } m_levelMapping.ActivateOptions(); LogLog.Debug(declaringType, "Source [" + m_applicationName + "] is registered to log [" + registeredLogName + "]"); } catch (System.Security.SecurityException ex) { ErrorHandler.Error("Caught a SecurityException trying to access the EventLog. Most likely the event source " + m_applicationName + " doesn't exist and must be created by a local administrator. Will disable EventLogAppender." + " See http://logging.apache.org/log4net/release/faq.html#trouble-EventLog", ex); Threshold = Level.Off; } } #endregion // Implementation of IOptionHandler /// <summary> /// Create an event log source /// </summary> /// <remarks> /// Uses different API calls under NET_2_0 /// </remarks> private static void CreateEventSource(string source, string logName, string machineName) { #if NET_2_0 EventSourceCreationData eventSourceCreationData = new EventSourceCreationData(source, logName); eventSourceCreationData.MachineName = machineName; EventLog.CreateEventSource(eventSourceCreationData); #else EventLog.CreateEventSource(source, logName, machineName); #endif } #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> /// method. /// </summary> /// <param name="loggingEvent">the event to log</param> /// <remarks> /// <para>Writes the event to the system event log using the /// <see cref="ApplicationName"/>.</para> /// /// <para>If the event has an <c>EventID</c> property (see <see cref="LoggingEvent.Properties"/>) /// set then this integer will be used as the event log event id.</para> /// /// <para> /// There is a limit of 32K characters for an event log message /// </para> /// </remarks> override protected void Append(LoggingEvent loggingEvent) { // // Write the resulting string to the event log system // int eventID = m_eventId; // Look for the EventID property object eventIDPropertyObj = loggingEvent.LookupProperty("EventID"); if (eventIDPropertyObj != null) { if (eventIDPropertyObj is int) { eventID = (int)eventIDPropertyObj; } else { string eventIDPropertyString = eventIDPropertyObj as string; if (eventIDPropertyString == null) { eventIDPropertyString = eventIDPropertyObj.ToString(); } if (eventIDPropertyString != null && eventIDPropertyString.Length > 0) { // Read the string property into a number int intVal; if (SystemInfo.TryParse(eventIDPropertyString, out intVal)) { eventID = intVal; } else { ErrorHandler.Error("Unable to parse event ID property [" + eventIDPropertyString + "]."); } } } } short category = m_category; // Look for the Category property object categoryPropertyObj = loggingEvent.LookupProperty("Category"); if (categoryPropertyObj != null) { if (categoryPropertyObj is short) { category = (short) categoryPropertyObj; } else { string categoryPropertyString = categoryPropertyObj as string; if (categoryPropertyString == null) { categoryPropertyString = categoryPropertyObj.ToString(); } if (categoryPropertyString != null && categoryPropertyString.Length > 0) { // Read the string property into a number short shortVal; if (SystemInfo.TryParse(categoryPropertyString, out shortVal)) { category = shortVal; } else { ErrorHandler.Error("Unable to parse event category property [" + categoryPropertyString + "]."); } } } } // Write to the event log try { string eventTxt = RenderLoggingEvent(loggingEvent); // There is a limit of about 32K characters for an event log message if (eventTxt.Length > MAX_EVENTLOG_MESSAGE_SIZE) { eventTxt = eventTxt.Substring(0, MAX_EVENTLOG_MESSAGE_SIZE); } EventLogEntryType entryType = GetEntryType(loggingEvent.Level); using(SecurityContext.Impersonate(this)) { EventLog.WriteEntry(m_applicationName, eventTxt, entryType, eventID, category); } } catch(Exception ex) { ErrorHandler.Error("Unable to write to event log [" + m_logName + "] using source [" + m_applicationName + "]", ex); } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } #endregion // Override implementation of AppenderSkeleton #region Protected Instance Methods /// <summary> /// Get the equivalent <see cref="EventLogEntryType"/> for a <see cref="Level"/> <paramref name="level"/> /// </summary> /// <param name="level">the Level to convert to an EventLogEntryType</param> /// <returns>The equivalent <see cref="EventLogEntryType"/> for a <see cref="Level"/> <paramref name="level"/></returns> /// <remarks> /// Because there are fewer applicable <see cref="EventLogEntryType"/> /// values to use in logging levels than there are in the /// <see cref="Level"/> this is a one way mapping. There is /// a loss of information during the conversion. /// </remarks> virtual protected EventLogEntryType GetEntryType(Level level) { // see if there is a specified lookup. Level2EventLogEntryType entryType = m_levelMapping.Lookup(level) as Level2EventLogEntryType; if (entryType != null) { return entryType.EventLogEntryType; } // Use default behavior if (level >= Level.Error) { return EventLogEntryType.Error; } else if (level == Level.Warn) { return EventLogEntryType.Warning; } // Default setting return EventLogEntryType.Information; } #endregion // Protected Instance Methods #region Private Instance Fields /// <summary> /// The log name is the section in the event logs where the messages /// are stored. /// </summary> private string m_logName; /// <summary> /// Name of the application to use when logging. This appears in the /// application column of the event log named by <see cref="m_logName"/>. /// </summary> private string m_applicationName; /// <summary> /// The name of the machine which holds the event log. This is /// currently only allowed to be '.' i.e. the current machine. /// </summary> private string m_machineName; /// <summary> /// Mapping from level object to EventLogEntryType /// </summary> private LevelMapping m_levelMapping = new LevelMapping(); /// <summary> /// The security context to use for privileged calls /// </summary> private SecurityContext m_securityContext; /// <summary> /// The event ID to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties. /// </summary> private int m_eventId = 0; /// <summary> /// The event category to use unless one is explicitly specified via the <c>LoggingEvent</c>'s properties. /// </summary> private short m_category = 0; #endregion // Private Instance Fields #region Level2EventLogEntryType LevelMapping Entry /// <summary> /// A class to act as a mapping between the level that a logging call is made at and /// the color it should be displayed as. /// </summary> /// <remarks> /// <para> /// Defines the mapping between a level and its event log entry type. /// </para> /// </remarks> public class Level2EventLogEntryType : LevelMappingEntry { private EventLogEntryType m_entryType; /// <summary> /// The <see cref="EventLogEntryType"/> for this entry /// </summary> /// <remarks> /// <para> /// Required property. /// The <see cref="EventLogEntryType"/> for this entry /// </para> /// </remarks> public EventLogEntryType EventLogEntryType { get { return m_entryType; } set { m_entryType = value; } } } #endregion // LevelColors LevelMapping Entry #region Private Static Fields /// <summary> /// The fully qualified type of the EventLogAppender class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(EventLogAppender); /// <summary> /// The maximum size supported by default. /// </summary> /// <remarks> /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx /// The 32766 documented max size is two bytes shy of 32K (I'm assuming 32766 /// may leave space for a two byte null terminator of #0#0). The 32766 max /// length is what the .NET 4.0 source code checks for, but this is WRONG! /// Strings with a length > 31839 on Windows Vista or higher can CORRUPT /// the event log! See: System.Diagnostics.EventLogInternal.InternalWriteEvent() /// for the use of the 32766 max size. /// </remarks> private readonly static int MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT = 32766; /// <summary> /// The maximum size supported by a windows operating system that is vista /// or newer. /// </summary> /// <remarks> /// See ReportEvent API: /// http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx /// ReportEvent's lpStrings parameter: /// "A pointer to a buffer containing an array of /// null-terminated strings that are merged into the message before Event Viewer /// displays the string to the user. This parameter must be a valid pointer /// (or NULL), even if wNumStrings is zero. Each string is limited to 31,839 characters." /// /// Going beyond the size of 31839 will (at some point) corrupt the event log on Windows /// Vista or higher! It may succeed for a while...but you will eventually run into the /// error: "System.ComponentModel.Win32Exception : A device attached to the system is /// not functioning", and the event log will then be corrupt (I was able to corrupt /// an event log using a length of 31877 on Windows 7). /// /// The max size for Windows Vista or higher is documented here: /// http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.100).aspx. /// Going over this size may succeed a few times but the buffer will overrun and /// eventually corrupt the log (based on testing). /// /// The maxEventMsgSize size is based on the max buffer size of the lpStrings parameter of the ReportEvent API. /// The documented max size for EventLog.WriteEntry for Windows Vista and higher is 31839, but I'm leaving room for a /// terminator of #0#0, as we cannot see the source of ReportEvent (though we could use an API monitor to examine the /// buffer, given enough time). /// </remarks> private readonly static int MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER = 31839 - 2; /// <summary> /// The maximum size that the operating system supports for /// a event log message. /// </summary> /// <remarks> /// Used to determine the maximum string length that can be written /// to the operating system event log and eventually truncate a string /// that exceeds the limits. /// </remarks> private readonly static int MAX_EVENTLOG_MESSAGE_SIZE = GetMaxEventLogMessageSize(); /// <summary> /// This method determines the maximum event log message size allowed for /// the current environment. /// </summary> /// <returns></returns> private static int GetMaxEventLogMessageSize() { if (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6) return MAX_EVENTLOG_MESSAGE_SIZE_VISTA_OR_NEWER; return MAX_EVENTLOG_MESSAGE_SIZE_DEFAULT; } #endregion Private Static Fields } } #endif // !SSCLI #endif // !NETCF
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Compat; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Holds the meta data of a <see cref = "Tree" />. /// </summary> public class TreeDefinition { private readonly Dictionary<string, TreeEntryDefinition> entries = new Dictionary<string, TreeEntryDefinition>(); private readonly Dictionary<string, TreeDefinition> unwrappedTrees = new Dictionary<string, TreeDefinition>(); /// <summary> /// Builds a <see cref = "TreeDefinition" /> from an existing <see cref = "Tree" />. /// </summary> /// <param name = "tree">The <see cref = "Tree" /> to be processed.</param> /// <returns>A new <see cref = "TreeDefinition" /> holding the meta data of the <paramref name = "tree" />.</returns> public static TreeDefinition From(Tree tree) { Ensure.ArgumentNotNull(tree, "tree"); var td = new TreeDefinition(); foreach (TreeEntry treeEntry in tree) { td.AddEntry(treeEntry.Name, TreeEntryDefinition.From(treeEntry)); } return td; } private void AddEntry(string targetTreeEntryName, TreeEntryDefinition treeEntryDefinition) { if (entries.ContainsKey(targetTreeEntryName)) { WrapTree(targetTreeEntryName, treeEntryDefinition); return; } entries.Add(targetTreeEntryName, treeEntryDefinition); } /// <summary> /// Removes a <see cref="TreeEntryDefinition"/> located the specified <paramref name="treeEntryPath"/> path. /// </summary> /// <param name="treeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Remove(string treeEntryPath) { Ensure.ArgumentNotNullOrEmptyString(treeEntryPath, "treeEntryPath"); if (this[treeEntryPath] == null) { return this; } Tuple<string, string> segments = ExtractPosixLeadingSegment(treeEntryPath); if (segments.Item2 == null) { entries.Remove(segments.Item1); } if (!unwrappedTrees.ContainsKey(segments.Item1)) { return this; } if (segments.Item2 != null) { unwrappedTrees[segments.Item1].Remove(segments.Item2); } if (unwrappedTrees[segments.Item1].entries.Count == 0) { unwrappedTrees.Remove(segments.Item1); entries.Remove(segments.Item1); } return this; } /// <summary> /// Adds or replaces a <see cref="TreeEntryDefinition"/> at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="treeEntryDefinition">The <see cref="TreeEntryDefinition"/> to be stored at the described location.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(string targetTreeEntryPath, TreeEntryDefinition treeEntryDefinition) { Ensure.ArgumentNotNullOrEmptyString(targetTreeEntryPath, "targetTreeEntryPath"); Ensure.ArgumentNotNull(treeEntryDefinition, "treeEntryDefinition"); if (Path.IsPathRooted(targetTreeEntryPath)) { throw new ArgumentException("The provided path is an absolute path."); } if (treeEntryDefinition is TransientTreeTreeEntryDefinition) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "The {0} references a target which hasn't been created in the {1} yet. " + "This situation can occur when the target is a whole new {2} being created, or when an existing {2} is being updated because some of its children were added/removed.", typeof(TreeEntryDefinition).Name, typeof(ObjectDatabase).Name, typeof(Tree).Name)); } Tuple<string, string> segments = ExtractPosixLeadingSegment(targetTreeEntryPath); if (segments.Item2 != null) { TreeDefinition td = RetrieveOrBuildTreeDefinition(segments.Item1, true); td.Add(segments.Item2, treeEntryDefinition); } else { AddEntry(segments.Item1, treeEntryDefinition); } return this; } /// <summary> /// Adds or replaces a <see cref="TreeEntryDefinition"/>, dynamically built from the provided <see cref="Blob"/>, at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="blob">The <see cref="Blob"/> to be stored at the described location.</param> /// <param name="mode">The file related <see cref="Mode"/> attributes.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(string targetTreeEntryPath, Blob blob, Mode mode) { Ensure.ArgumentNotNull(blob, "blob"); Ensure.ArgumentConformsTo(mode, m => m.HasAny(TreeEntryDefinition.BlobModes), "mode"); TreeEntryDefinition ted = TreeEntryDefinition.From(blob, mode); return Add(targetTreeEntryPath, ted); } /// <summary> /// Adds or replaces a <see cref="TreeEntryDefinition"/>, dynamically built from the content of the file, at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="filePath">The path to the file from which a <see cref="Blob"/> will be built and stored at the described location. A relative path is allowed to be passed if the target /// <see cref="Repository" /> is a standard, non-bare, repository. The path will then be considered as a path relative to the root of the working directory.</param> /// <param name="mode">The file related <see cref="Mode"/> attributes.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(string targetTreeEntryPath, string filePath, Mode mode) { Ensure.ArgumentNotNullOrEmptyString(filePath, "filePath"); TreeEntryDefinition ted = TreeEntryDefinition.TransientBlobFrom(filePath, mode); return Add(targetTreeEntryPath, ted); } /// <summary> /// Adds or replaces a <see cref="TreeEntryDefinition"/>, dynamically built from the provided <see cref="Tree"/>, at the specified <paramref name="targetTreeEntryPath"/> location. /// </summary> /// <param name="targetTreeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <param name="tree">The <see cref="Tree"/> to be stored at the described location.</param> /// <returns>The current <see cref="TreeDefinition"/>.</returns> public virtual TreeDefinition Add(string targetTreeEntryPath, Tree tree) { Ensure.ArgumentNotNull(tree, "tree"); TreeEntryDefinition ted = TreeEntryDefinition.From(tree); return Add(targetTreeEntryPath, ted); } private TreeDefinition RetrieveOrBuildTreeDefinition(string treeName, bool shouldOverWrite) { TreeDefinition td; if (unwrappedTrees.TryGetValue(treeName, out td)) { return td; } TreeEntryDefinition treeEntryDefinition; bool hasAnEntryBeenFound = entries.TryGetValue(treeName, out treeEntryDefinition); if (hasAnEntryBeenFound) { switch (treeEntryDefinition.Type) { case GitObjectType.Tree: td = From(treeEntryDefinition.Target as Tree); break; case GitObjectType.Blob: if (shouldOverWrite) { td = new TreeDefinition(); break; } return null; default: throw new NotImplementedException(); } } else { if (!shouldOverWrite) { return null; } td = new TreeDefinition(); } entries[treeName] = new TransientTreeTreeEntryDefinition(); unwrappedTrees.Add(treeName, td); return td; } internal Tree Build(Repository repository) { WrapAllTreeDefinitions(repository); using (var builder = new TreeBuilder()) { var builtTreeEntryDefinitions = new List<Tuple<string, TreeEntryDefinition>>(entries.Count); foreach (KeyValuePair<string, TreeEntryDefinition> kvp in entries) { string name = kvp.Key; TreeEntryDefinition ted = kvp.Value; var transient = ted as TransientBlobTreeEntryDefinition; if (transient == null) { builder.Insert(name, ted); continue; } Blob blob = transient.Builder(repository.ObjectDatabase); TreeEntryDefinition ted2 = TreeEntryDefinition.From(blob, ted.Mode); builtTreeEntryDefinitions.Add(new Tuple<string, TreeEntryDefinition>(name, ted2)); builder.Insert(name, ted2); } builtTreeEntryDefinitions.ForEach(t => entries[t.Item1] = t.Item2); ObjectId treeId = builder.Write(repository); return repository.Lookup<Tree>(treeId); } } private void WrapAllTreeDefinitions(Repository repository) { foreach (KeyValuePair<string, TreeDefinition> pair in unwrappedTrees) { Tree tree = pair.Value.Build(repository); entries[pair.Key] = TreeEntryDefinition.From(tree); } unwrappedTrees.Clear(); } private void WrapTree(string entryName, TreeEntryDefinition treeEntryDefinition) { entries[entryName] = treeEntryDefinition; unwrappedTrees.Remove(entryName); } /// <summary> /// Retrieves the <see cref="TreeEntryDefinition"/> located the specified <paramref name="treeEntryPath"/> path. /// </summary> /// <param name="treeEntryPath">The path within this <see cref="TreeDefinition"/>.</param> /// <returns>The found <see cref="TreeEntryDefinition"/> if any; null otherwise.</returns> public virtual TreeEntryDefinition this[string treeEntryPath] { get { Ensure.ArgumentNotNullOrEmptyString(treeEntryPath, "treeEntryPath"); Tuple<string, string> segments = ExtractPosixLeadingSegment(treeEntryPath); if (segments.Item2 != null) { TreeDefinition td = RetrieveOrBuildTreeDefinition(segments.Item1, false); return td == null ? null : td[segments.Item2]; } TreeEntryDefinition treeEntryDefinition; return !entries.TryGetValue(segments.Item1, out treeEntryDefinition) ? null : treeEntryDefinition; } } private static Tuple<string, string> ExtractPosixLeadingSegment(FilePath targetPath) { string[] segments = targetPath.Posix.Split(new[] { '/' }, 2); if (segments[0] == string.Empty || (segments.Length == 2 && (segments[1] == string.Empty || segments[1].StartsWith("/", StringComparison.Ordinal)))) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "'{0}' is not a valid path.", targetPath)); } return new Tuple<string, string>(segments[0], segments.Length == 2 ? segments[1] : null); } private class TreeBuilder : IDisposable { private readonly TreeBuilderSafeHandle handle; public TreeBuilder() { handle = Proxy.git_treebuilder_create(); } public void Insert(string name, TreeEntryDefinition treeEntryDefinition) { Proxy.git_treebuilder_insert(handle, name, treeEntryDefinition); } public ObjectId Write(Repository repo) { return Proxy.git_treebuilder_write(repo.Handle, handle); } public void Dispose() { handle.SafeDispose(); } } } }
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 GUIOdyssey.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; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //------------------------------------------------------------ //------------------------------------------------------------ using System; using System.Runtime.Serialization; using System.Diagnostics; namespace System.Xml { internal enum PrefixHandleType { Empty, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, Buffer, Max, } internal class PrefixHandle : IEquatable<PrefixHandle> { private XmlBufferReader _bufferReader; private PrefixHandleType _type; private int _offset; private int _length; private static string[] s_prefixStrings = { "", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; private static byte[] s_prefixBuffer = { (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' }; public PrefixHandle(XmlBufferReader bufferReader) { _bufferReader = bufferReader; } public void SetValue(PrefixHandleType type) { DiagnosticUtility.DebugAssert(type != PrefixHandleType.Buffer, ""); _type = type; } public void SetValue(PrefixHandle prefix) { _type = prefix._type; _offset = prefix._offset; _length = prefix._length; } public void SetValue(int offset, int length) { if (length == 0) { SetValue(PrefixHandleType.Empty); return; } if (length == 1) { byte ch = _bufferReader.GetByte(offset); if (ch >= 'a' && ch <= 'z') { SetValue(GetAlphaPrefix(ch - 'a')); return; } } _type = PrefixHandleType.Buffer; _offset = offset; _length = length; } public bool IsEmpty { get { return _type == PrefixHandleType.Empty; } } public bool IsXmlns { get { if (_type != PrefixHandleType.Buffer) return false; if (_length != 5) return false; byte[] buffer = _bufferReader.Buffer; int offset = _offset; return buffer[offset + 0] == 'x' && buffer[offset + 1] == 'm' && buffer[offset + 2] == 'l' && buffer[offset + 3] == 'n' && buffer[offset + 4] == 's'; } } public bool IsXml { get { if (_type != PrefixHandleType.Buffer) return false; if (_length != 3) return false; byte[] buffer = _bufferReader.Buffer; int offset = _offset; return buffer[offset + 0] == 'x' && buffer[offset + 1] == 'm' && buffer[offset + 2] == 'l'; } } public bool TryGetShortPrefix(out PrefixHandleType type) { type = _type; return (type != PrefixHandleType.Buffer); } public static string GetString(PrefixHandleType type) { DiagnosticUtility.DebugAssert(type != PrefixHandleType.Buffer, ""); return s_prefixStrings[(int)type]; } public static PrefixHandleType GetAlphaPrefix(int index) { DiagnosticUtility.DebugAssert(index >= 0 && index < 26, ""); return (PrefixHandleType)(PrefixHandleType.A + index); } public static byte[] GetString(PrefixHandleType type, out int offset, out int length) { DiagnosticUtility.DebugAssert(type != PrefixHandleType.Buffer, ""); if (type == PrefixHandleType.Empty) { offset = 0; length = 0; } else { length = 1; offset = (int)(type - PrefixHandleType.A); } return s_prefixBuffer; } public string GetString(XmlNameTable nameTable) { PrefixHandleType type = _type; if (type != PrefixHandleType.Buffer) return GetString(type); else return _bufferReader.GetString(_offset, _length, nameTable); } public string GetString() { PrefixHandleType type = _type; if (type != PrefixHandleType.Buffer) return GetString(type); else return _bufferReader.GetString(_offset, _length); } public byte[] GetString(out int offset, out int length) { PrefixHandleType type = _type; if (type != PrefixHandleType.Buffer) return GetString(type, out offset, out length); else { offset = _offset; length = _length; return _bufferReader.Buffer; } } public int CompareTo(PrefixHandle that) { return GetString().CompareTo(that.GetString()); } public bool Equals(PrefixHandle prefix2) { if (ReferenceEquals(prefix2, null)) return false; PrefixHandleType type1 = _type; PrefixHandleType type2 = prefix2._type; if (type1 != type2) return false; if (type1 != PrefixHandleType.Buffer) return true; if (_bufferReader == prefix2._bufferReader) return _bufferReader.Equals2(_offset, _length, prefix2._offset, prefix2._length); else return _bufferReader.Equals2(_offset, _length, prefix2._bufferReader, prefix2._offset, prefix2._length); } private bool Equals2(string prefix2) { PrefixHandleType type = _type; if (type != PrefixHandleType.Buffer) return GetString(type) == prefix2; return _bufferReader.Equals2(_offset, _length, prefix2); } private bool Equals2(XmlDictionaryString prefix2) { return Equals2(prefix2.Value); } static public bool operator ==(PrefixHandle prefix1, string prefix2) { return prefix1.Equals2(prefix2); } static public bool operator !=(PrefixHandle prefix1, string prefix2) { return !prefix1.Equals2(prefix2); } static public bool operator ==(PrefixHandle prefix1, XmlDictionaryString prefix2) { return prefix1.Equals2(prefix2); } static public bool operator !=(PrefixHandle prefix1, XmlDictionaryString prefix2) { return !prefix1.Equals2(prefix2); } static public bool operator ==(PrefixHandle prefix1, PrefixHandle prefix2) { return prefix1.Equals(prefix2); } static public bool operator !=(PrefixHandle prefix1, PrefixHandle prefix2) { return !prefix1.Equals(prefix2); } public override bool Equals(object obj) { return Equals(obj as PrefixHandle); } public override string ToString() { return GetString(); } public override int GetHashCode() { return GetString().GetHashCode(); } } }
using System; using System.Collections.Generic; /// <summary> /// System.Collections.Generic.IDictionary.Keys /// </summary> public class IDictionaryKeys { private int c_MINI_STRING_LENGTH = 1; private int c_MAX_STRING_LENGTH = 20; public static int Main(string[] args) { IDictionaryKeys testObj = new IDictionaryKeys(); TestLibrary.TestFramework.BeginTestCase("Testing for Property: System.Collections.Generic.IDictionary.Keys"); if (testObj.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]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Using Dictionary<TKey,TValue> which implemented the Keys property in IDictionay<TKey,TValue> and TKey is int..."; const string c_TEST_ID = "P001"; Dictionary<int, int> dictionary = new Dictionary<int, int>(); int key = TestLibrary.Generator.GetInt32(-55); int value = TestLibrary.Generator.GetInt32(-55); dictionary.Add(key, value); key = key + 1; dictionary.Add(key,value); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ICollection<int> keys = ((IDictionary<int, int>)dictionary).Keys; if (keys.Count != 2) { string errorDesc = "( the count of IDictionary<int, int>.Keys 2 as expected: Actual(" + keys.Count + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!keys.Contains(key)) { string errorDesc = key + "should exist in (IDictionary<int, int>.Keys"; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("003", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Using Dictionary<TKey,TValue> which implemented the Keys property in IDictionay<TKey,TValue> and TKey is String..."; const string c_TEST_ID = "P002"; Dictionary<String, String> dictionary = new Dictionary<String, String>(); String key = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); String value = TestLibrary.Generator.GetString(-55, false, c_MINI_STRING_LENGTH, c_MAX_STRING_LENGTH); dictionary.Add(key, value); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ICollection<String> keys = ((IDictionary<String, String>)dictionary).Keys; if (keys.Count != 1) { string errorDesc = "( the count of IDictionary<int, int>.Keys 1 as expected: Actual(" + keys.Count + ")"; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!keys.Contains(key)) { string errorDesc = key + "should exist in (IDictionary<String, String>.Keys"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: Using Dictionary<TKey,TValue> which implemented the Keys property in IDictionay<TKey,TValue> and TKey is customer class..."; const string c_TEST_ID = "P003"; Dictionary<MyClass, int> dictionary = new Dictionary<MyClass, int>(); MyClass key = new MyClass(); int value = TestLibrary.Generator.GetInt32(-55); dictionary.Add(key, value); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ICollection<MyClass> keys = ((IDictionary<MyClass, int>)dictionary).Keys; if (keys.Count != 1) { string errorDesc = "( the count of IDictionary<int, int>.Keys 1 as expected: Actual(" + keys.Count + ")"; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (!keys.Contains(key)) { string errorDesc = "MyClass object should exist in (IDictionary<String, String>.Keys"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("009", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: Using Dictionary<TKey,TValue> which implemented the Keys property in IDictionay<TKey,TValue> and Keys is empty..."; const string c_TEST_ID = "P004"; Dictionary<int, int> dictionary = new Dictionary<int, int>(); int key = TestLibrary.Generator.GetInt32(-55); TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ICollection<int> keys = ((IDictionary<int, int>)dictionary).Keys; if (keys.Count != 0) { string errorDesc = "( the count of IDictionary<int, int>.Keys 0 as expected: Actual(" + keys.Count + ")"; TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } if (keys.Contains(key)) { string errorDesc = key + "should not exist in (IDictionary<int, int>.Keys"; TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unecpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region Help Class public class MyClass { } #endregion }
//---------------------------------------------------------------------------------------------- // Copyright 2014 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //---------------------------------------------------------------------------------------------- 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 TodoListService.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) 2004 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if NET20 || NET35 || NET40 || NET45 using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Security; using System.Security.Permissions; using System.Security.Policy; namespace NUnit.Framework.Assertions { [TestFixture] [Platform(Exclude = "Mono,MonoTouch", Reason = "Mono does not implement Code Access Security")] public class LowTrustFixture { private TestSandBox _sandBox; [OneTimeSetUp] public void CreateSandBox() { _sandBox = new TestSandBox(); } [OneTimeTearDown] public void DisposeSandBox() { if (_sandBox != null) { _sandBox.Dispose(); _sandBox = null; } } [Test] public void AssertEqualityInLowTrustSandBox() { _sandBox.Run(() => { Assert.That(1, Is.EqualTo(1)); }); } [Test] public void AssertEqualityWithToleranceInLowTrustSandBox() { _sandBox.Run(() => { Assert.That(10.5, Is.EqualTo(10.5)); }); } [Test] public void AssertThrowsInLowTrustSandBox() { _sandBox.Run(() => { Assert.Throws<SecurityException>(() => new SecurityPermission(SecurityPermissionFlag.Infrastructure).Demand()); }); } } /// <summary> /// A facade for an <see cref="AppDomain"/> with partial trust privileges. /// </summary> public class TestSandBox : IDisposable { private AppDomain _appDomain; #region Constructor(s) /// <summary> /// Creates a low trust <see cref="TestSandBox"/> instance. /// </summary> /// <param name="fullTrustAssemblies">Strong named assemblies that will have full trust in the sandbox.</param> public TestSandBox(params Assembly[] fullTrustAssemblies) : this(null, fullTrustAssemblies) { } /// <summary> /// Creates a partial trust <see cref="TestSandBox"/> instance with a given set of permissions. /// </summary> /// <param name="permissions">Optional <see cref="TestSandBox"/> permission set. By default a minimal trust /// permission set is used.</param> /// <param name="fullTrustAssemblies">Strong named assemblies that will have full trust in the sandbox.</param> public TestSandBox(PermissionSet permissions, params Assembly[] fullTrustAssemblies) { var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory }; var strongNames = new HashSet<StrongName>(); // Grant full trust to NUnit.Framework assembly to enable use of NUnit assertions in sandboxed test code. strongNames.Add(GetStrongName(typeof(TestAttribute).Assembly)); if (fullTrustAssemblies != null) { foreach (var assembly in fullTrustAssemblies) { strongNames.Add(GetStrongName(assembly)); } } _appDomain = AppDomain.CreateDomain( "TestSandBox" + DateTime.Now.Ticks, null, setup, permissions ?? GetLowTrustPermissionSet(), strongNames.ToArray()); } #endregion #region Finalizer and Dispose methods /// <summary> /// The <see cref="TestSandBox"/> finalizer. /// </summary> ~TestSandBox() { Dispose(false); } /// <summary> /// Unloads the <see cref="AppDomain"/>. /// </summary> public void Dispose() { Dispose(true); } /// <summary> /// Unloads the <see cref="AppDomain"/>. /// </summary> /// <param name="disposing">Indicates whether this method is called from <see cref="Dispose()"/>.</param> protected virtual void Dispose(bool disposing) { if (_appDomain != null) { AppDomain.Unload(_appDomain); _appDomain = null; } } #endregion #region PermissionSet factory methods public static PermissionSet GetLowTrustPermissionSet() { var permissions = new PermissionSet(PermissionState.None); permissions.AddPermission(new SecurityPermission( SecurityPermissionFlag.Execution | // Required to execute test code SecurityPermissionFlag.SerializationFormatter)); // Required to support cross-appdomain test result formatting by NUnit TestContext permissions.AddPermission(new ReflectionPermission( ReflectionPermissionFlag.MemberAccess)); // Required to instantiate classes that contain test code and to get cross-appdomain communication to work. return permissions; } #endregion #region Run methods public T Run<T>(Func<T> func) { return (T)Run(func.Method); } public void Run(Action action) { Run(action.Method); } public object Run(MethodInfo method, params object[] parameters) { if (method == null) throw new ArgumentNullException("method"); if (_appDomain == null) throw new ObjectDisposedException(null); var methodRunnerType = typeof(MethodRunner); var methodRunnerProxy = (MethodRunner)_appDomain.CreateInstanceAndUnwrap( methodRunnerType.Assembly.FullName, methodRunnerType.FullName); try { return methodRunnerProxy.Run(method, parameters); } catch (Exception e) { throw e is TargetInvocationException ? e.InnerException : e; } } #endregion #region Private methods private static StrongName GetStrongName(Assembly assembly) { AssemblyName assemblyName = assembly.GetName(); byte[] publicKey = assembly.GetName().GetPublicKey(); if (publicKey == null || publicKey.Length == 0) { throw new InvalidOperationException("Assembly is not strongly named"); } return new StrongName(new StrongNamePublicKeyBlob(publicKey), assemblyName.Name, assemblyName.Version); } #endregion #region Inner classes [Serializable] internal class MethodRunner : MarshalByRefObject { public object Run(MethodInfo method, params object[] parameters) { var instance = method.IsStatic ? null : Activator.CreateInstance(method.ReflectedType); try { return method.Invoke(instance, parameters); } catch (TargetInvocationException e) { if (e.InnerException == null) throw; throw e.InnerException; } } } #endregion } } #endif
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Emit; namespace StackExchange.Precompilation { class Compilation { private readonly PrecompilationCommandLineArgs _precompilationCommandLineArgs; internal CSharpCommandLineArguments CscArgs { get; private set; } internal DirectoryInfo CurrentDirectory { get; private set; } internal List<Diagnostic> Diagnostics { get; private set; } internal Encoding Encoding { get; private set; } private readonly Dictionary<string, Lazy<Parser>> _syntaxTreeLoaders; private const string DiagnosticCategory = "StackExchange.Precompilation"; private static DiagnosticDescriptor FailedToCreateModule = new DiagnosticDescriptor("SE001", "Failed to instantiate ICompileModule", "Failed to instantiate ICompileModule '{0}': {1}", DiagnosticCategory, DiagnosticSeverity.Error, true); private static DiagnosticDescriptor UnknownFileType = new DiagnosticDescriptor("SE002", "Unknown file type", "Unknown file type '{0}'", DiagnosticCategory, DiagnosticSeverity.Error, true); internal static DiagnosticDescriptor ViewGenerationFailed = new DiagnosticDescriptor("SE003", "View generation failed", "View generation failed: {0}", DiagnosticCategory, DiagnosticSeverity.Error, true); internal static DiagnosticDescriptor FailedParsingSourceTree = new DiagnosticDescriptor("SE004", "Failed parsing source tree", "Failed parasing source tree: {0}", DiagnosticCategory, DiagnosticSeverity.Error, true); public Compilation(PrecompilationCommandLineArgs precompilationCommandLineArgs) { _precompilationCommandLineArgs = precompilationCommandLineArgs; _syntaxTreeLoaders = new Dictionary<string, Lazy<Parser>> { {".cs", new Lazy<Parser>(CSharp, LazyThreadSafetyMode.PublicationOnly)}, {".cshtml", new Lazy<Parser>(Razor, LazyThreadSafetyMode.PublicationOnly)}, }; CurrentDirectory = new DirectoryInfo(_precompilationCommandLineArgs.BaseDirectory); AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(CurrentDirectory.FullName, "App_Data")); // HACK mocking ASP.NET's ~/App_Data aka. |DataDirectory| } private Parser CSharp() { return new CSharpParser(this); } private Parser Razor() { return new RazorParser(this); } public bool Run() { try { // this parameter was introduced in rc3, all call to it seem to be using RuntimeEnvironment.GetRuntimeDirectory() // https://github.com/dotnet/roslyn/blob/0382e3e3fc543fc483090bff3ab1eaae39dfb4d9/src/Compilers/CSharp/csc/Program.cs#L18 var sdkDirectory = RuntimeEnvironment.GetRuntimeDirectory(); CscArgs = CSharpCommandLineParser.Default.Parse(_precompilationCommandLineArgs.Arguments, _precompilationCommandLineArgs.BaseDirectory, sdkDirectory); Diagnostics = new List<Diagnostic>(CscArgs.Errors); if (Diagnostics.Any()) { return false; } Encoding = CscArgs.Encoding ?? Encoding.UTF8; var references = SetupReferences(); var sources = LoadSources(CscArgs.SourceFiles.Select(x => x.Path).ToArray()); var compilationModules = LoadModules().ToList(); var compilation = CSharpCompilation.Create( options: CscArgs.CompilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default), references: references, syntaxTrees: sources, assemblyName: CscArgs.CompilationName); var context = new CompileContext(compilationModules); context.Before(new BeforeCompileContext { Arguments = CscArgs, Compilation = compilation, Diagnostics = Diagnostics, Resources = CscArgs.ManifestResources.ToList() }); var emitResult = Emit(context); return emitResult.Success; } finally { Diagnostics.ForEach(x => Console.WriteLine(x.ToString())); // strings only, since the Console.Out textwriter is another app domain... } } private IEnumerable<ICompileModule> LoadModules() { var compilationSection = PrecompilerSection.Current; if (compilationSection == null) yield break; foreach(var module in compilationSection.CompileModules.Cast<CompileModuleElement>()) { ICompileModule compileModule = null; try { var type = Type.GetType(module.Type, false); compileModule = Activator.CreateInstance(type, true) as ICompileModule; } catch(Exception ex) { Diagnostics.Add(Diagnostic.Create( FailedToCreateModule, Location.Create(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile, new TextSpan(), new LinePositionSpan()), module.Type, ex.Message)); } if (compileModule != null) { yield return compileModule; } } } private EmitResult Emit(CompileContext context) { var compilation = context.BeforeCompileContext.Compilation; var pdbPath = CscArgs.PdbPath; var outputPath = Path.Combine(CscArgs.OutputDirectory, CscArgs.OutputFileName); if (!CscArgs.EmitPdb) { pdbPath = null; } else if (string.IsNullOrWhiteSpace(pdbPath)) { pdbPath = Path.ChangeExtension(outputPath, ".pdb"); } using (var peStream = File.Create(outputPath)) using (var pdbStream = !string.IsNullOrWhiteSpace(pdbPath) ? File.Create(pdbPath) : null) using (var xmlDocumentationStream = !string.IsNullOrWhiteSpace(CscArgs.DocumentationPath) ? File.Create(CscArgs.DocumentationPath) : null) using (var win32Resources = compilation.CreateDefaultWin32Resources( versionResource: true, noManifest: CscArgs.NoWin32Manifest, manifestContents: !string.IsNullOrWhiteSpace(CscArgs.Win32Manifest) ? new MemoryStream(File.ReadAllBytes(CscArgs.Win32Manifest)) : null, iconInIcoFormat: !string.IsNullOrWhiteSpace(CscArgs.Win32Icon) ? new MemoryStream(File.ReadAllBytes(CscArgs.Win32Icon)) : null)) { var emitResult = compilation.Emit( peStream: peStream, pdbStream: pdbStream, xmlDocumentationStream: xmlDocumentationStream, options: CscArgs.EmitOptions, manifestResources: CscArgs.ManifestResources, win32Resources: win32Resources); Diagnostics.AddRange(emitResult.Diagnostics); context.After(new AfterCompileContext { Arguments = CscArgs, AssemblyStream = peStream, Compilation = compilation, Diagnostics = Diagnostics, SymbolStream = pdbStream, XmlDocStream = xmlDocumentationStream, }); return emitResult; } } class CompileContext { private readonly ICompileModule[] _modules; public BeforeCompileContext BeforeCompileContext { get; private set; } public AfterCompileContext AfterCompileContext { get; private set; } public CompileContext(IEnumerable<ICompileModule> modules) { _modules = modules == null ? new ICompileModule[0] : modules.ToArray(); } public void Before(BeforeCompileContext context) { Apply(context, x => BeforeCompileContext = x, m => m.BeforeCompile); } public void After(AfterCompileContext context) { Apply(context, x => AfterCompileContext = x, m => m.AfterCompile); } private void Apply<TContext>(TContext ctx, Action<TContext> setter, Func<ICompileModule, Action<TContext>> actionGetter) { setter(ctx); foreach(var module in _modules) { var action = actionGetter(module); action(ctx); } } } private ICollection<MetadataReference> SetupReferences() { // really don't care about /addmodule and .netmodule stuff... // https://msdn.microsoft.com/en-us/library/226t7yxe.aspx return _precompilationCommandLineArgs.References.Select(x => (MetadataReference)MetadataReference.CreateFromFile(x, MetadataReferenceProperties.Assembly)).ToArray(); } private IEnumerable<SyntaxTree> LoadSources(ICollection<string> paths) { var trees = new SyntaxTree[paths.Count]; Parallel.ForEach(paths, (file, state, index) => { var ext = Path.GetExtension(file) ?? ""; Lazy<Parser> parser; if(_syntaxTreeLoaders.TryGetValue(ext, out parser)) { using (var sourceStream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read)) { trees[index] = parser.Value.GetSyntaxTree(file, sourceStream); } } else { Diagnostics.Add(Diagnostic.Create(UnknownFileType, AsLocation(file), ext)); } }); return trees.Where(x => x != null).Concat(GeneratedSyntaxTrees()); } private IEnumerable<SyntaxTree> GeneratedSyntaxTrees() { yield return SyntaxFactory.ParseSyntaxTree($"[assembly: {typeof(CompiledFromDirectoryAttribute).FullName}(@\"{CurrentDirectory.FullName}\")]"); } public Location AsLocation(string path) { return Location.Create(path, new TextSpan(), new LinePositionSpan()); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the email-2010-12-01.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.SimpleEmail.Model; namespace Amazon.SimpleEmail { /// <summary> /// Interface for accessing SimpleEmailService /// /// Amazon Simple Email Service /// <para> /// This is the API Reference for Amazon Simple Email Service (Amazon SES). This documentation /// is intended to be used in conjunction with the <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/Welcome.html">Amazon /// SES Developer Guide</a>. /// </para> /// <note>For a list of Amazon SES endpoints to use in service requests, see <a href="http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html">Regions /// and Amazon SES</a> in the Amazon SES Developer Guide. </note> /// </summary> public partial interface IAmazonSimpleEmailService : IDisposable { #region DeleteIdentity /// <summary> /// Initiates the asynchronous execution of the DeleteIdentity operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteIdentity operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteIdentityResponse> DeleteIdentityAsync(DeleteIdentityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteIdentityPolicy /// <summary> /// Initiates the asynchronous execution of the DeleteIdentityPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteIdentityPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteIdentityPolicyResponse> DeleteIdentityPolicyAsync(DeleteIdentityPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeleteVerifiedEmailAddress /// <summary> /// Initiates the asynchronous execution of the DeleteVerifiedEmailAddress operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteVerifiedEmailAddress operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteVerifiedEmailAddressResponse> DeleteVerifiedEmailAddressAsync(DeleteVerifiedEmailAddressRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetIdentityDkimAttributes /// <summary> /// Initiates the asynchronous execution of the GetIdentityDkimAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIdentityDkimAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetIdentityDkimAttributesResponse> GetIdentityDkimAttributesAsync(GetIdentityDkimAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetIdentityNotificationAttributes /// <summary> /// Initiates the asynchronous execution of the GetIdentityNotificationAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIdentityNotificationAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetIdentityNotificationAttributesResponse> GetIdentityNotificationAttributesAsync(GetIdentityNotificationAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetIdentityPolicies /// <summary> /// Initiates the asynchronous execution of the GetIdentityPolicies operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIdentityPolicies operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetIdentityPoliciesResponse> GetIdentityPoliciesAsync(GetIdentityPoliciesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetIdentityVerificationAttributes /// <summary> /// Initiates the asynchronous execution of the GetIdentityVerificationAttributes operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetIdentityVerificationAttributes operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetIdentityVerificationAttributesResponse> GetIdentityVerificationAttributesAsync(GetIdentityVerificationAttributesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetSendQuota /// <summary> /// Returns the user's current sending limits. /// /// /// <para> /// This action is throttled at one request per second. /// </para> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetSendQuota service method, as returned by SimpleEmailService.</returns> Task<GetSendQuotaResponse> GetSendQuotaAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the GetSendQuota operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSendQuota operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetSendQuotaResponse> GetSendQuotaAsync(GetSendQuotaRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetSendStatistics /// <summary> /// Returns the user's sending statistics. The result is a list of data points, representing /// the last two weeks of sending activity. /// /// /// <para> /// Each data point in the list contains statistics for a 15-minute interval. /// </para> /// /// <para> /// This action is throttled at one request per second. /// </para> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the GetSendStatistics service method, as returned by SimpleEmailService.</returns> Task<GetSendStatisticsResponse> GetSendStatisticsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the GetSendStatistics operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetSendStatistics operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetSendStatisticsResponse> GetSendStatisticsAsync(GetSendStatisticsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListIdentities /// <summary> /// Returns a list containing all of the identities (email addresses and domains) for /// a specific AWS Account, regardless of verification status. /// /// /// <para> /// This action is throttled at one request per second. /// </para> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListIdentities service method, as returned by SimpleEmailService.</returns> Task<ListIdentitiesResponse> ListIdentitiesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the ListIdentities operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListIdentities operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListIdentitiesResponse> ListIdentitiesAsync(ListIdentitiesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListIdentityPolicies /// <summary> /// Initiates the asynchronous execution of the ListIdentityPolicies operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListIdentityPolicies operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListIdentityPoliciesResponse> ListIdentityPoliciesAsync(ListIdentityPoliciesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListVerifiedEmailAddresses /// <summary> /// Returns a list containing all of the email addresses that have been verified. /// /// <important>The ListVerifiedEmailAddresses action is deprecated as of the May 15, /// 2012 release of Domain Verification. The ListIdentities action is now preferred.</important> /// /// <para> /// This action is throttled at one request per second. /// </para> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the ListVerifiedEmailAddresses service method, as returned by SimpleEmailService.</returns> Task<ListVerifiedEmailAddressesResponse> ListVerifiedEmailAddressesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the ListVerifiedEmailAddresses operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListVerifiedEmailAddresses operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListVerifiedEmailAddressesResponse> ListVerifiedEmailAddressesAsync(ListVerifiedEmailAddressesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutIdentityPolicy /// <summary> /// Initiates the asynchronous execution of the PutIdentityPolicy operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutIdentityPolicy operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutIdentityPolicyResponse> PutIdentityPolicyAsync(PutIdentityPolicyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SendEmail /// <summary> /// Initiates the asynchronous execution of the SendEmail operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SendEmail operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SendEmailResponse> SendEmailAsync(SendEmailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SendRawEmail /// <summary> /// Initiates the asynchronous execution of the SendRawEmail operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SendRawEmail operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SendRawEmailResponse> SendRawEmailAsync(SendRawEmailRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetIdentityDkimEnabled /// <summary> /// Initiates the asynchronous execution of the SetIdentityDkimEnabled operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetIdentityDkimEnabled operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetIdentityDkimEnabledResponse> SetIdentityDkimEnabledAsync(SetIdentityDkimEnabledRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetIdentityFeedbackForwardingEnabled /// <summary> /// Initiates the asynchronous execution of the SetIdentityFeedbackForwardingEnabled operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetIdentityFeedbackForwardingEnabled operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetIdentityFeedbackForwardingEnabledResponse> SetIdentityFeedbackForwardingEnabledAsync(SetIdentityFeedbackForwardingEnabledRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region SetIdentityNotificationTopic /// <summary> /// Initiates the asynchronous execution of the SetIdentityNotificationTopic operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the SetIdentityNotificationTopic operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<SetIdentityNotificationTopicResponse> SetIdentityNotificationTopicAsync(SetIdentityNotificationTopicRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region VerifyDomainDkim /// <summary> /// Initiates the asynchronous execution of the VerifyDomainDkim operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifyDomainDkim operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<VerifyDomainDkimResponse> VerifyDomainDkimAsync(VerifyDomainDkimRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region VerifyDomainIdentity /// <summary> /// Initiates the asynchronous execution of the VerifyDomainIdentity operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifyDomainIdentity operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<VerifyDomainIdentityResponse> VerifyDomainIdentityAsync(VerifyDomainIdentityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region VerifyEmailAddress /// <summary> /// Initiates the asynchronous execution of the VerifyEmailAddress operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifyEmailAddress operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<VerifyEmailAddressResponse> VerifyEmailAddressAsync(VerifyEmailAddressRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region VerifyEmailIdentity /// <summary> /// Initiates the asynchronous execution of the VerifyEmailIdentity operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the VerifyEmailIdentity operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<VerifyEmailIdentityResponse> VerifyEmailIdentityAsync(VerifyEmailIdentityRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using Microsoft.JScript.Vsa; using System; using System.Reflection; using System.Reflection.Emit; internal sealed class Lookup : Binding{ private int lexLevel; //Keeps track of the number of frames on the explicit scope stack that needs to be searched for a late binding private int evalLexLevel; //Keeps track of the number of frames to GetObject should skip private LocalBuilder fieldLoc; private LocalBuilder refLoc; private LateBinding lateBinding; private bool thereIsAnObjectOnTheStack; // this is the typical Lookup constructor. The context points to the identifier internal Lookup(Context context) : base(context, context.GetCode()){ this.lexLevel = 0; this.evalLexLevel = 0; this.fieldLoc = null; this.refLoc = null; this.lateBinding = null; this.thereIsAnObjectOnTheStack = false; } // this constructor is invoked when there has been a parse error. The typical scenario is a missing identifier. internal Lookup(String name, Context context) : this(context){ this.name = name; } public String Name{ get{ return this.name; } } private void BindName(){ int lexLevel = 0; int evalLexLevel = 0; ScriptObject scope = Globals.ScopeStack.Peek(); BindingFlags flags = BindingFlags.Public|BindingFlags.NonPublic|BindingFlags.Instance|BindingFlags.Static|BindingFlags.DeclaredOnly; bool staticClassFound = false; // is there a static class on the scope chain bool enclosingClassForStaticClassFound = false; // has the class enclosing a static nested class been found while (scope != null){ MemberInfo[] members = null; WithObject withScope = scope as WithObject; if (withScope != null && enclosingClassForStaticClassFound) members = withScope.GetMember(this.name, flags, false); else members = scope.GetMember(this.name, flags); this.members = members; if (members.Length > 0) break; if (scope is WithObject){ this.isFullyResolved = this.isFullyResolved && ((WithObject)scope).isKnownAtCompileTime; lexLevel++; }else if (scope is ActivationObject){ this.isFullyResolved = this.isFullyResolved && ((ActivationObject)scope).isKnownAtCompileTime; if (scope is BlockScope || (scope is FunctionScope && ((FunctionScope)scope).mustSaveStackLocals)) lexLevel++; if (scope is ClassScope){ if (staticClassFound) enclosingClassForStaticClassFound = true; if (((ClassScope)scope).owner.isStatic){ flags &= ~BindingFlags.Instance; staticClassFound = true; } } }else if (scope is StackFrame) lexLevel++; evalLexLevel++; scope = scope.GetParent(); } if (this.members.Length > 0){ this.lexLevel = lexLevel; this.evalLexLevel = evalLexLevel; } } internal bool CanPlaceAppropriateObjectOnStack(Object ob){ if (ob is LenientGlobalObject) return true; ScriptObject scope = Globals.ScopeStack.Peek(); int lexLev = this.lexLevel; while (lexLev > 0 && (scope is WithObject || scope is BlockScope)){ if (scope is WithObject) lexLev--; scope = scope.GetParent(); } return scope is WithObject || scope is GlobalScope; } internal override void CheckIfOKToUseInSuperConstructorCall(){ FieldInfo f = this.member as FieldInfo; if (f != null){ if (!f.IsStatic) this.context.HandleError(JSError.NotAllowedInSuperConstructorCall); return; } MethodInfo m = this.member as MethodInfo; if (m != null){ if (!m.IsStatic) this.context.HandleError(JSError.NotAllowedInSuperConstructorCall); return; } PropertyInfo p = this.member as PropertyInfo; if (p != null){ m = JSProperty.GetGetMethod(p, true); if (m != null && !m.IsStatic) this.context.HandleError(JSError.NotAllowedInSuperConstructorCall); else{ m = JSProperty.GetSetMethod(p, true); if (m != null && !m.IsStatic) this.context.HandleError(JSError.NotAllowedInSuperConstructorCall); } } } internal override Object Evaluate(){ Object result = null; ScriptObject scope = Globals.ScopeStack.Peek(); if (!this.isFullyResolved){ result = ((IActivationObject)scope).GetMemberValue(this.name, this.evalLexLevel); if (!(result is Missing)) return result; } if (this.members == null && !VsaEngine.executeForJSEE){ this.BindName(); this.ResolveRHValue(); } result = base.Evaluate(); if (result is Missing) throw new JScriptException(JSError.UndefinedIdentifier, this.context); return result; } internal override LateBinding EvaluateAsLateBinding(){ if (!this.isFullyResolved){ this.BindName(); //Doing this at runtime. Binding is now final (for this call). Do it here so that scope chain logic works as at compile time. this.isFullyResolved = false; } if (this.defaultMember == this.member) this.defaultMember = null; Object ob = this.GetObject(); LateBinding lb = this.lateBinding; if (lb == null) lb = this.lateBinding = new LateBinding(this.name, ob, VsaEngine.executeForJSEE); lb.obj = ob; lb.last_object = ob; lb.last_members = this.members; lb.last_member = this.member; if (!this.isFullyResolved) this.members = null; return lb; } internal override WrappedNamespace EvaluateAsWrappedNamespace(bool giveErrorIfNameInUse){ Namespace ns = Namespace.GetNamespace(this.name, this.Engine); GlobalScope scope = ((IActivationObject)Globals.ScopeStack.Peek()).GetGlobalScope(); FieldInfo field = giveErrorIfNameInUse ? scope.GetLocalField(this.name) : scope.GetField(this.name, BindingFlags.Public|BindingFlags.Static); if (field != null){ if (giveErrorIfNameInUse && (!field.IsLiteral || !(field.GetValue(null) is Namespace))) this.context.HandleError(JSError.DuplicateName, true); }else{ field = scope.AddNewField(this.name, ns, FieldAttributes.Literal|FieldAttributes.Public); ((JSVariableField)field).type = new TypeExpression(new ConstantWrapper(Typeob.Namespace, this.context)); ((JSVariableField)field).originalContext = this.context; } return new WrappedNamespace(this.name, this.Engine); } protected override Object GetObject(){ Object result; ScriptObject scope = Globals.ScopeStack.Peek(); if (this.member is JSMemberField){ while (scope != null){ StackFrame sf = scope as StackFrame; if (sf != null) {result = sf.closureInstance; goto finish;} scope = scope.GetParent(); } return null; } for (int i = this.evalLexLevel; i > 0; i--) scope = scope.GetParent(); result = scope; finish: if (this.defaultMember != null) switch(this.defaultMember.MemberType){ case MemberTypes.Field: return ((FieldInfo)this.defaultMember).GetValue(result); case MemberTypes.Method: return ((MethodInfo)this.defaultMember).Invoke(result, new Object[0]); case MemberTypes.Property: return ((PropertyInfo)this.defaultMember).GetValue(result, null); case MemberTypes.Event: return null; case MemberTypes.NestedType: return member; } return result; } protected override void HandleNoSuchMemberError(){ if (!this.isFullyResolved) return; this.context.HandleError(JSError.UndeclaredVariable, this.Engine.doFast); } internal override IReflect InferType(JSField inference_target){ if (!this.isFullyResolved) return Typeob.Object; return base.InferType(inference_target); } internal bool InFunctionNestedInsideInstanceMethod(){ ScriptObject scope = this.Globals.ScopeStack.Peek(); while (scope is WithObject || scope is BlockScope) scope = scope.GetParent(); FunctionScope fscope = scope as FunctionScope; while (fscope != null){ if (fscope.owner.isMethod) return !fscope.owner.isStatic; scope = fscope.owner.enclosing_scope; while (scope is WithObject || scope is BlockScope) scope = scope.GetParent(); fscope = scope as FunctionScope; } return false; } internal bool InStaticCode(){ ScriptObject scope = this.Globals.ScopeStack.Peek(); while (scope is WithObject || scope is BlockScope) scope = scope.GetParent(); FunctionScope fscope = scope as FunctionScope; if (fscope != null) return fscope.isStatic; StackFrame sframe = scope as StackFrame; //Might be a StackFrame if called from an eval if (sframe != null) return sframe.thisObject is Type; ClassScope cscope = scope as ClassScope; //Happens when the initializers of variable declarations are partially evaluated if (cscope != null) return cscope.inStaticInitializerCode; return true; } internal override AST PartiallyEvaluate(){ this.BindName(); if (this.members == null || this.members.Length == 0){ //Give a warning, unless inside a with statement ScriptObject scope = Globals.ScopeStack.Peek(); while (scope is FunctionScope) scope = scope.GetParent(); if (!(scope is WithObject) || this.isFullyResolved) this.context.HandleError(JSError.UndeclaredVariable, this.isFullyResolved && this.Engine.doFast); }else{ this.ResolveRHValue(); MemberInfo member = this.member; if (member is FieldInfo){ FieldInfo field = (FieldInfo)member; if (field is JSLocalField && !((JSLocalField)field).isDefined){ ((JSLocalField)field).isUsedBeforeDefinition = true; this.context.HandleError(JSError.VariableMightBeUnitialized); } if (field.IsLiteral){ Object val = field is JSVariableField ? ((JSVariableField)field).value : TypeReferences.GetConstantValue(field); if (val is AST){ AST pval = ((AST)val).PartiallyEvaluate(); if (pval is ConstantWrapper && this.isFullyResolved) return pval; val = null; } if (!(val is FunctionObject) && this.isFullyResolved) return new ConstantWrapper(val, this.context); }else if (field.IsInitOnly && field.IsStatic && field.DeclaringType == Typeob.GlobalObject && this.isFullyResolved) return new ConstantWrapper(field.GetValue(null), this.context); }else if (member is PropertyInfo){ PropertyInfo prop = (PropertyInfo)member; if (!prop.CanWrite && !(prop is JSProperty) && prop.DeclaringType == Typeob.GlobalObject && this.isFullyResolved) return new ConstantWrapper(prop.GetValue(null, null), this.context); } if (member is Type && this.isFullyResolved) return new ConstantWrapper(member, this.context); } return this; } internal override AST PartiallyEvaluateAsCallable(){ this.BindName(); return this; } internal override AST PartiallyEvaluateAsReference(){ this.BindName(); if (this.members == null || this.members.Length == 0){ //Give a warning, unless inside a with statement ScriptObject scope = Globals.ScopeStack.Peek(); if (!(scope is WithObject) || this.isFullyResolved) this.context.HandleError(JSError.UndeclaredVariable, this.isFullyResolved && this.Engine.doFast); }else this.ResolveLHValue(); return this; } internal override Object ResolveCustomAttribute(ASTList args, IReflect[] argIRs, AST target){ if (this.name == "expando") this.members = Typeob.Expando.GetConstructors(BindingFlags.Instance|BindingFlags.Public); else if (this.name == "override") this.members = Typeob.Override.GetConstructors(BindingFlags.Instance|BindingFlags.Public); else if (this.name == "hide") this.members = Typeob.Hide.GetConstructors(BindingFlags.Instance|BindingFlags.Public); else if (this.name == "...") this.members = Typeob.ParamArrayAttribute.GetConstructors(BindingFlags.Instance|BindingFlags.Public); else{ this.name = this.name + "Attribute"; this.BindName(); if (this.members == null || this.members.Length == 0){ this.name = this.name.Substring(0, this.name.Length-9); this.BindName(); } } return base.ResolveCustomAttribute(args, argIRs, target); } internal override void SetPartialValue(AST partial_value){ //ResolveLHValue has already been called and has already checked if the target is accessible and assignable if (this.members == null || this.members.Length == 0) return; //Assignment to an undeclared variable. Nothing further to do. if (this.member is JSLocalField){ //If we are dealing with an assignment to an untyped local variable, we need to tell the type inferencer about the assignment JSLocalField lfield = (JSLocalField)this.member; if (lfield.type == null){ IReflect ir = partial_value.InferType(lfield); if (ir == Typeob.String && partial_value is Plus) lfield.SetInferredType(Typeob.Object, partial_value); else lfield.SetInferredType(ir, partial_value); //but then we are done return; } lfield.isDefined = true; } Binding.AssignmentCompatible(this.InferType(null), partial_value, partial_value.InferType(null), this.isFullyResolved); } internal override void SetValue(Object value){ if (!this.isFullyResolved){ this.EvaluateAsLateBinding().SetValue(value); return; } base.SetValue(value); } internal void SetWithValue(WithObject scope, Object value){ Debug.Assert(!this.isFullyResolved); FieldInfo withField = scope.GetField(this.name, this.lexLevel); if (withField != null){ withField.SetValue(scope, value); return; } } //code in parser relies on this.name being returned from here public override String ToString(){ return this.name; } internal override void TranslateToIL(ILGenerator il, Type rtype){ if (this.isFullyResolved){ base.TranslateToIL(il, rtype); return; } //Need to do a dynamic lookup to see if there is a dynamically introduced (by eval or with) hiding definition. Label done = il.DefineLabel(); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.scriptObjectStackTopMethod); il.Emit(OpCodes.Castclass, Typeob.IActivationObject); il.Emit(OpCodes.Ldstr, this.name); ConstantWrapper.TranslateToILInt(il, this.lexLevel); il.Emit(OpCodes.Callvirt, CompilerGlobals.getMemberValueMethod); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Call, CompilerGlobals.isMissingMethod); il.Emit(OpCodes.Brfalse, done); //dynamic lookup succeeded, do not use the value from the early bound location. il.Emit(OpCodes.Pop); //The dynamic lookup returned Missing.Value, discard it and go on to use the value from the early bound location. base.TranslateToIL(il, Typeob.Object); il.MarkLabel(done); Convert.Emit(this, il, Typeob.Object, rtype); } internal override void TranslateToILCall(ILGenerator il, Type rtype, ASTList argList, bool construct, bool brackets){ if (this.isFullyResolved){ base.TranslateToILCall(il, rtype, argList, construct, brackets); return; } //Need to do a dynamic lookup to see if there is a dynamically introduced (by eval or with) hiding definition. Label lateBoundCall = il.DefineLabel(); Label done = il.DefineLabel(); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.scriptObjectStackTopMethod); il.Emit(OpCodes.Castclass, Typeob.IActivationObject); il.Emit(OpCodes.Ldstr, this.name); ConstantWrapper.TranslateToILInt(il, this.lexLevel); il.Emit(OpCodes.Callvirt, CompilerGlobals.getMemberValueMethod); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Call, CompilerGlobals.isMissingMethod); il.Emit(OpCodes.Brfalse, lateBoundCall); //dynamic lookup succeeded, do not call early bound method il.Emit(OpCodes.Pop); //The dynamic lookup returned Missing.Value, discard it and go on to use the value from the early bound location. base.TranslateToILCall(il, Typeob.Object, argList, construct, brackets); il.Emit(OpCodes.Br, done); //Skip over the latebound call sequence il.MarkLabel(lateBoundCall); this.TranslateToILDefaultThisObject(il); argList.TranslateToIL(il, Typeob.ArrayOfObject); if (construct) il.Emit(OpCodes.Ldc_I4_1); else il.Emit(OpCodes.Ldc_I4_0); if (brackets) il.Emit(OpCodes.Ldc_I4_1); else il.Emit(OpCodes.Ldc_I4_0); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.callValue2Method); il.MarkLabel(done); Convert.Emit(this, il, Typeob.Object, rtype); } internal void TranslateToILDefaultThisObject(ILGenerator il){ this.TranslateToILDefaultThisObject(il, 0); } private void TranslateToILDefaultThisObject(ILGenerator il, int lexLevel){ this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.scriptObjectStackTopMethod); while (lexLevel-- > 0) il.Emit(OpCodes.Call, CompilerGlobals.getParentMethod); il.Emit(OpCodes.Castclass, Typeob.IActivationObject); il.Emit(OpCodes.Callvirt, CompilerGlobals.getDefaultThisObjectMethod); } internal override void TranslateToILInitializer(ILGenerator il){ if (this.defaultMember != null) return; if (this.member != null) switch(this.member.MemberType){ case MemberTypes.Constructor: case MemberTypes.Method: case MemberTypes.NestedType: case MemberTypes.Property: case MemberTypes.TypeInfo: return; case MemberTypes.Field: if (this.member is JSExpandoField){ this.member = null; break; } return; } this.refLoc = il.DeclareLocal(Typeob.LateBinding); il.Emit(OpCodes.Ldstr, this.name); if (this.isFullyResolved && this.member == null && this.IsBoundToMethodInfos()) { MethodInfo method = this.members[0] as MethodInfo; if (method.IsStatic) { il.Emit(OpCodes.Ldtoken, method.DeclaringType); il.Emit(OpCodes.Call, CompilerGlobals.getTypeFromHandleMethod); } else this.TranslateToILObjectForMember(il, method.DeclaringType, false, method); } else { this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.scriptObjectStackTopMethod); } il.Emit(OpCodes.Newobj, CompilerGlobals.lateBindingConstructor2); il.Emit(OpCodes.Stloc, this.refLoc); } private bool IsBoundToMethodInfos() { if (this.members == null || this.members.Length == 0) return false; for (int i = 0; i < this.members.Length; i++) if (!(this.members[i] is MethodInfo)) return false; return true; } protected override void TranslateToILObject(ILGenerator il, Type obType, bool noValue){ this.TranslateToILObjectForMember(il, obType, noValue, this.member); } private void TranslateToILObjectForMember(ILGenerator il, Type obType, bool noValue, MemberInfo mem) { this.thereIsAnObjectOnTheStack = true; if (mem is IWrappedMember){ Object obj = ((IWrappedMember)mem).GetWrappedObject(); if (obj is LenientGlobalObject){ this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.getLenientGlobalObjectMethod); }else if (obj is Type || obj is ClassScope){ if (obType.IsAssignableFrom(Typeob.Type)){ (new ConstantWrapper(obj, null)).TranslateToIL(il, Typeob.Type); return; } //this.name is the name of an instance member of the superclass of the class (or an outer class) in which this expression appears //get class instance on stack ScriptObject scope = Globals.ScopeStack.Peek(); while (scope is WithObject || scope is BlockScope) scope = scope.GetParent(); if (scope is FunctionScope){ FunctionObject func = ((FunctionScope)scope).owner; if (func.isMethod) il.Emit(OpCodes.Ldarg_0); else{ //Need to get the StackFrame.closureInstance on the stack this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.scriptObjectStackTopMethod); scope = this.Globals.ScopeStack.Peek(); while (scope is WithObject || scope is BlockScope){ il.Emit(OpCodes.Call, CompilerGlobals.getParentMethod); scope = scope.GetParent(); } il.Emit(OpCodes.Castclass, Typeob.StackFrame); il.Emit(OpCodes.Ldfld, CompilerGlobals.closureInstanceField); } }else if (scope is ClassScope){ il.Emit(OpCodes.Ldarg_0); //Inside instance initializer } //If dealing with a member of an outer class, get the outer class instance on the stack scope = Globals.ScopeStack.Peek(); while (scope != null){ ClassScope csc = scope as ClassScope; if (csc != null){ //Might be dealing with a reference from within a nested class to an instance member of an outer class if (csc.IsSameOrDerivedFrom(obType)) break; il.Emit(OpCodes.Ldfld, csc.outerClassField); } scope = scope.GetParent(); } }else{ this.TranslateToILDefaultThisObject(il, this.lexLevel); Convert.Emit(this, il, Typeob.Object, obType); } }else{ ScriptObject scope = Globals.ScopeStack.Peek(); while (scope is WithObject || scope is BlockScope) scope = scope.GetParent(); if (scope is FunctionScope){ FunctionObject func = ((FunctionScope)scope).owner; if (!func.isMethod){ //Need to get the StackFrame.closureInstance on the stack this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.scriptObjectStackTopMethod); scope = this.Globals.ScopeStack.Peek(); while (scope is WithObject || scope is BlockScope){ il.Emit(OpCodes.Call, CompilerGlobals.getParentMethod); scope = scope.GetParent(); } il.Emit(OpCodes.Castclass, Typeob.StackFrame); il.Emit(OpCodes.Ldfld, CompilerGlobals.closureInstanceField); while (scope != null){ if (scope is ClassScope){ //Might be dealing with a reference from within a nested class to an instance member of an outer class ClassScope csc = (ClassScope)scope; if (csc.IsSameOrDerivedFrom(obType)) break; il.Emit(OpCodes.Castclass, csc.GetTypeBuilder()); il.Emit(OpCodes.Ldfld, csc.outerClassField); } scope = scope.GetParent(); } il.Emit(OpCodes.Castclass, obType); return; } } il.Emit(OpCodes.Ldarg_0); while (scope != null){ if (scope is ClassScope){ //Might be dealing with a reference from within a nested class to an instance member of an outer class ClassScope csc = (ClassScope)scope; if (csc.IsSameOrDerivedFrom(obType)) break; il.Emit(OpCodes.Ldfld, csc.outerClassField); } scope = scope.GetParent(); } } } internal override void TranslateToILPreSet(ILGenerator il){ this.TranslateToILPreSet(il, false); } internal void TranslateToILPreSet(ILGenerator il, bool doBoth){ if (this.isFullyResolved){ base.TranslateToILPreSet(il); return; } //Need to do a dynamic lookup to see if there is a dynamically introduced (by eval or with) hiding definition. //Leave a FieldInfo on the stack if there is such a member, otherwise leave null on the stack Label done = il.DefineLabel(); LocalBuilder fieldLoc = this.fieldLoc = il.DeclareLocal(Typeob.FieldInfo); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.scriptObjectStackTopMethod); il.Emit(OpCodes.Castclass, Typeob.IActivationObject); il.Emit(OpCodes.Ldstr, this.name); ConstantWrapper.TranslateToILInt(il, this.lexLevel); il.Emit(OpCodes.Callvirt, CompilerGlobals.getFieldMethod); il.Emit(OpCodes.Stloc, fieldLoc); if (!doBoth){ il.Emit(OpCodes.Ldloc, fieldLoc); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Bne_Un_S, done); } base.TranslateToILPreSet(il); if (this.thereIsAnObjectOnTheStack){ Label reallyDone = il.DefineLabel(); il.Emit(OpCodes.Br_S, reallyDone); il.MarkLabel(done); il.Emit(OpCodes.Ldnull); //Push a dummy object so that both latebound and early bound code paths leave an object on the stack il.MarkLabel(reallyDone); }else il.MarkLabel(done); } internal override void TranslateToILPreSetPlusGet(ILGenerator il){ if (this.isFullyResolved){ base.TranslateToILPreSetPlusGet(il); return; } //Need to do a dynamic lookup to see if there is a dynamically introduced (by eval or with) hiding definition. //Leave a FieldInfo on the stack if there is such a member, otherwise leave null on the stack Label done = il.DefineLabel(); Label latebound = il.DefineLabel(); LocalBuilder fieldTok = this.fieldLoc = il.DeclareLocal(Typeob.FieldInfo); this.EmitILToLoadEngine(il); il.Emit(OpCodes.Call, CompilerGlobals.scriptObjectStackTopMethod); il.Emit(OpCodes.Castclass, Typeob.IActivationObject); il.Emit(OpCodes.Ldstr, this.name); ConstantWrapper.TranslateToILInt(il, this.lexLevel); il.Emit(OpCodes.Callvirt, CompilerGlobals.getFieldMethod); il.Emit(OpCodes.Stloc, fieldTok); il.Emit(OpCodes.Ldloc, fieldTok); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Bne_Un_S, latebound); base.TranslateToILPreSetPlusGet(il); il.Emit(OpCodes.Br_S, done); il.MarkLabel(latebound); if (this.thereIsAnObjectOnTheStack) il.Emit(OpCodes.Ldnull); //Push a dummy object so that both latebound and early bound code paths leave an object on the stack il.Emit(OpCodes.Ldloc, this.fieldLoc); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Callvirt, CompilerGlobals.getFieldValueMethod); il.MarkLabel(done); } internal override void TranslateToILSet(ILGenerator il, AST rhvalue){ this.TranslateToILSet(il, false, rhvalue); } internal void TranslateToILSet(ILGenerator il, bool doBoth, AST rhvalue){ if (this.isFullyResolved){ base.TranslateToILSet(il, rhvalue); return; } if (rhvalue != null) rhvalue.TranslateToIL(il, Typeob.Object); if (this.fieldLoc == null){ //There is a callable value plus parameters on the stack il.Emit(OpCodes.Call, CompilerGlobals.setIndexedPropertyValueStaticMethod); return; } LocalBuilder temp = il.DeclareLocal(Typeob.Object); if (doBoth){ //save copy of rh value il.Emit(OpCodes.Dup); il.Emit(OpCodes.Stloc, temp); //store it in early bound location this.isFullyResolved = true; Convert.Emit(this, il, Typeob.Object, Convert.ToType(this.InferType(null))); base.TranslateToILSet(il, null); } //See if there is a late bound field Label earlyBound = il.DefineLabel(); il.Emit(OpCodes.Ldloc, this.fieldLoc); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Beq_S, earlyBound); //No late bound field //store it in the late bound field Label done = il.DefineLabel(); if (!doBoth){ il.Emit(OpCodes.Stloc, temp); if (this.thereIsAnObjectOnTheStack) il.Emit(OpCodes.Pop); } il.Emit(OpCodes.Ldloc, this.fieldLoc); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Ldloc, temp); il.Emit(OpCodes.Callvirt, CompilerGlobals.setFieldValueMethod); il.Emit(OpCodes.Br_S, done); //Alternative store it in the early bound location il.MarkLabel(earlyBound); if (!doBoth){ this.isFullyResolved = true; Convert.Emit(this, il, Typeob.Object, Convert.ToType(this.InferType(null))); base.TranslateToILSet(il, null); } il.MarkLabel(done); } protected override void TranslateToILWithDupOfThisOb(ILGenerator il){ this.TranslateToILDefaultThisObject(il); this.TranslateToIL(il, Typeob.Object); } internal void TranslateToLateBinding(ILGenerator il){ this.thereIsAnObjectOnTheStack = true; il.Emit(OpCodes.Ldloc, this.refLoc); } } }
using System; namespace OpenRiaServices.DomainServices.Hosting.OData { #region Namespace using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Data.Linq; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using OpenRiaServices.DomainServices.Server; using System.Threading; #endregion /// <summary> /// Contains utility methods for inspecting types through Reflection. /// </summary> internal static class TypeUtils { private static char[] xmlWhitespaceChars = new char[] { ' ', '\t', '\n', '\r' }; /// <summary>'binary' constant prefixed to binary literals.</summary> internal const string LiteralPrefixBinary = "binary"; /// <summary>'datetime' constant prefixed to datetime literals.</summary> internal const string LiteralPrefixDateTime = "datetime"; /// <summary>'guid' constant prefixed to guid literals.</summary> internal const string LiteralPrefixGuid = "guid"; /// <summary>'X': Prefix to binary type string representation.</summary> internal const string XmlBinaryPrefix = "X"; /// <summary>'M': Suffix for decimal type's string representation</summary> internal const string XmlDecimalLiteralSuffix = "M"; /// <summary>'L': Suffix for long (int64) type's string representation</summary> internal const string XmlInt64LiteralSuffix = "L"; /// <summary>'f': Suffix for float (single) type's string representation</summary> internal const string XmlSingleLiteralSuffix = "f"; /// <summary>'D': Suffix for double (Real) type's string representation</summary> internal const string XmlDoubleLiteralSuffix = "D"; /// <summary>Type of OutOfMemoryException.</summary> private static readonly Type OutOfMemoryType = typeof(OutOfMemoryException); /// <summary>Type of StackOverflowException.</summary> private static readonly Type StackOverflowType = typeof(StackOverflowException); /// <summary>Type of ThreadAbortException.</summary> private static readonly Type ThreadAbortType = typeof(ThreadAbortException); /// <summary>XML whitespace characters to trim around literals.</summary> internal static char[] XmlWhitespaceChars { get { return TypeUtils.xmlWhitespaceChars; } } /// <summary>Checks if the given property has DataMember attribute.</summary> /// <param name="property">Given property.</param> /// <returns>true if DataMember attribute is set, false otherwise.</returns> internal static bool IsDataMember(PropertyDescriptor property) { return HasAttribute(property, typeof(DataMemberAttribute)); } /// <summary>Checks if the given property represents an association.</summary> /// <param name="property">Given property.</param> /// <returns>true if property is an association, false otherwise.</returns> internal static bool IsAssociation(PropertyDescriptor property) { return HasAttribute(property, typeof(AssociationAttribute)); } /// <summary>Checks if the given property represents a composition.</summary> /// <param name="property">Given property.</param> /// <returns>true if property is a composition, false otherwise.</returns> internal static bool IsComposition(PropertyDescriptor property) { return HasAttribute(property, typeof(CompositionAttribute)); } /// <summary>Checks if the given property represents an external reference.</summary> /// <param name="property">Given property.</param> /// <returns>true if property is an external reference, false otherwise.</returns> internal static bool IsExternalReference(PropertyDescriptor property) { return HasAttribute(property, typeof(ExternalReferenceAttribute)); } /// <summary>Checks if the given property is excluded.</summary> /// <param name="property">Given property.</param> /// <returns>true if property is excluded, false otherwise.</returns> internal static bool IsExcluded(PropertyDescriptor property) { return HasAttribute(property, typeof(ExcludeAttribute)); } /// <summary>Checks if the given property is a key property.</summary> /// <param name="property">Property to check.</param> /// <returns>true if property is a key property, false otherwise.</returns> internal static bool IsKeyProperty(PropertyDescriptor property) { return HasAttribute(property, typeof(KeyAttribute)); } /// <summary> /// Returns true if the specified property is a data member that should be serialized /// </summary> /// <param name="propertyDescriptor">The property to inspect</param> /// <returns>true if the specified property is a data member that should be serialized</returns> internal static bool IsSerializableDataMember(PropertyDescriptor propertyDescriptor) { bool serializable = SerializationUtility.IsSerializableDataMember(propertyDescriptor); Debug.Assert(!TypeUtils.IsKeyProperty(propertyDescriptor) || serializable, "Key property must be serializable."); Debug.Assert(!TypeUtils.IsAssociation(propertyDescriptor) || !serializable, "Association property should not be serializable."); Debug.Assert(!TypeUtils.IsComposition(propertyDescriptor) || !serializable, "Composition property should not be serializable."); Debug.Assert(!TypeUtils.IsExternalReference(propertyDescriptor) || !serializable, "External Reference property should not be serializable."); Debug.Assert(!TypeUtils.IsExcluded(propertyDescriptor) || !serializable, "Excluded property should not be serializable."); return serializable; } /// <summary> /// Returns the type of the IQueryable if the type implements IQueryable interface /// </summary> /// <param name="type">clr type on which IQueryable check needs to be performed.</param> /// <returns>Element type if the property type implements IQueryable, else returns null</returns> internal static Type GetIQueryableElement(Type type) { return GetGenericInterfaceElementType(type, IQueryableTypeFilter); } /// <summary> /// Returns the type of the IEnumerable if the type implements IEnumerable interface; null otherwise. /// </summary> /// <param name="type">type that needs to be checked</param> /// <returns>Element type if the type implements IEnumerable, else returns null</returns> internal static Type GetIEnumerableElement(Type type) { return GetGenericInterfaceElementType(type, IEnumerableTypeFilter); } /// <summary> /// Determines whether the specified exception can be caught and /// handled, or whether it should be allowed to continue unwinding. /// </summary> /// <param name="e"><see cref="Exception"/> to test.</param> /// <returns> /// true if the specified exception can be caught and handled; /// false otherwise. /// </returns> internal static bool IsCatchableExceptionType(Exception e) { // a 'catchable' exception is defined by what it is not. Debug.Assert(e != null, "Unexpected null exception!"); Type type = e.GetType(); return ((type != StackOverflowType) && (type != OutOfMemoryType) && (type != ThreadAbortType)); } /// <summary> /// Gets the type that should be used on the client for the specified type. /// </summary> /// <param name="t">The type to get the client type for.</param> /// <returns>The client type.</returns> internal static Type GetClientType(Type t) { if (t == typeof(Binary)) { return typeof(byte[]); } return t; } /// <summary> /// Gets a value that can be used by the client. /// </summary> /// <param name="targetType">The type used by the client.</param> /// <param name="value">The value on the server.</param> /// <returns>A value that can be used by the client.</returns> internal static object GetClientValue(Type targetType, object value) { if (value == null) { return null; } Binary valueAsBinary = value as Binary; if (targetType == typeof(byte[]) && valueAsBinary != null) { return valueAsBinary.ToArray(); } return value; } /// <summary> /// Gets a value that can be used by the server. /// </summary> /// <param name="targetType">The type used by the server.</param> /// <param name="value">The value from the client.</param> /// <returns>A value that can be used by the server.</returns> internal static object GetServerValue(Type targetType, object value) { if (value == null) { return null; } byte[] valueAsByteArray = value as byte[]; if (targetType == typeof(Binary) && valueAsByteArray != null) { return new Binary(valueAsByteArray); } return value; } /// <summary>Filter callback for finding IQueryable implementations.</summary> /// <param name="m">Type to inspect.</param> /// <param name="filterCriteria">Filter criteria.</param> /// <returns>true if the specified type is an IQueryable of T; false otherwise.</returns> private static bool IQueryableTypeFilter(Type m, object filterCriteria) { Debug.Assert(m != null, "m != null"); return m.IsGenericType && m.GetGenericTypeDefinition() == typeof(IQueryable<>); } /// <summary>Filter callback for finding IEnumerable implementations.</summary> /// <param name="m">Type to inspect.</param> /// <param name="filterCriteria">Filter criteria.</param> /// <returns>true if the specified type is an IEnumerable of T; false otherwise.</returns> private static bool IEnumerableTypeFilter(Type m, object filterCriteria) { Debug.Assert(m != null, "m != null"); return m.IsGenericType && m.GetGenericTypeDefinition() == typeof(IEnumerable<>); } /// <summary> /// Returns the "T" in the IQueryable of T implementation of type. /// </summary> /// <param name="type">Type to check.</param> /// <param name="typeFilter">filter against which the type is checked</param> /// <returns> /// The element type for the generic IQueryable interface of the type, /// or null if it has none or if it's ambiguous. /// </returns> private static Type GetGenericInterfaceElementType(Type type, TypeFilter typeFilter) { Debug.Assert(type != null, "type != null"); Debug.Assert(!type.IsGenericTypeDefinition, "!type.IsGenericTypeDefinition"); if (typeFilter(type, null)) { return type.GetGenericArguments()[0]; } Type[] queriables = type.FindInterfaces(typeFilter, null); if (queriables != null && queriables.Length == 1) { return queriables[0].GetGenericArguments()[0]; } else { return null; } } /// <summary>Checks if given property has the attribute set.</summary> /// <param name="target">Property desriptor.</param> /// <param name="attribute">Attribute to check for.</param> /// <returns>true if attribute is present, false otherwise.</returns> private static bool HasAttribute(PropertyDescriptor target, Type attribute) { return null != target.Attributes[attribute]; } } }
// 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.ComponentModel; using System.Web.Services; using System.Web.Services.Protocols; using WebsitePanel.Providers; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.Providers.OS; using WebsitePanel.Providers.ResultObjects; using WebsitePanel.Server.Utils; namespace WebsitePanel.Server { /// <summary> /// Summary description for Organizations /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class Organizations : HostingServiceProviderWebService { private IOrganization Organization { get { return (IOrganization)Provider; } } [WebMethod, SoapHeader("settings")] public bool OrganizationExists(string organizationId) { try { Log.WriteStart("'{0}' OrganizationExists", ProviderSettings.ProviderName); bool ret = Organization.OrganizationExists(organizationId); Log.WriteEnd("'{0}' OrganizationExists", ProviderSettings.ProviderName); return ret; } catch (Exception ex) { Log.WriteError(String.Format("Can't CreateOrganization '{0}' provider", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public Organization CreateOrganization(string organizationId) { try { Log.WriteStart("'{0}' CreateOrganization", ProviderSettings.ProviderName); Organization ret = Organization.CreateOrganization(organizationId); Log.WriteEnd("'{0}' CreateOrganization", ProviderSettings.ProviderName); return ret; } catch (Exception ex) { Log.WriteError(String.Format("Can't CreateOrganization '{0}' provider", ProviderSettings.ProviderName), ex); throw; } } [WebMethod, SoapHeader("settings")] public void DeleteOrganization(string organizationId) { Organization.DeleteOrganization(organizationId); } [WebMethod, SoapHeader("settings")] public int CreateUser(string organizationId, string loginName, string displayName, string upn, string password, bool enabled) { return Organization.CreateUser(organizationId, loginName, displayName, upn, password, enabled); } [WebMethod, SoapHeader("settings")] public void DisableUser(string loginName, string organizationId) { Organization.DisableUser(loginName, organizationId); } [WebMethod, SoapHeader("settings")] public void DeleteUser(string loginName, string organizationId) { Organization.DeleteUser(loginName, organizationId); } [WebMethod, SoapHeader("settings")] public OrganizationUser GetUserGeneralSettings(string loginName, string organizationId) { return Organization.GetUserGeneralSettings(loginName, organizationId); } [WebMethod, SoapHeader("settings")] public int CreateSecurityGroup(string organizationId, string groupName) { return Organization.CreateSecurityGroup(organizationId, groupName); } [WebMethod, SoapHeader("settings")] public OrganizationSecurityGroup GetSecurityGroupGeneralSettings(string groupName, string organizationId) { return Organization.GetSecurityGroupGeneralSettings(groupName, organizationId); } [WebMethod, SoapHeader("settings")] public void DeleteSecurityGroup(string groupName, string organizationId) { Organization.DeleteSecurityGroup(groupName, organizationId); } [WebMethod, SoapHeader("settings")] public void SetSecurityGroupGeneralSettings(string organizationId, string groupName, string[] memberAccounts, string notes) { Organization.SetSecurityGroupGeneralSettings(organizationId, groupName, memberAccounts, notes); } [WebMethod, SoapHeader("settings")] public void AddObjectToSecurityGroup(string organizationId, string accountName, string groupName) { Organization.AddObjectToSecurityGroup(organizationId, accountName, groupName); } [WebMethod, SoapHeader("settings")] public void DeleteObjectFromSecurityGroup(string organizationId, string accountName, string groupName) { Organization.DeleteObjectFromSecurityGroup(organizationId, accountName, groupName); } [WebMethod, SoapHeader("settings")] public void SetUserGeneralSettings(string organizationId, string accountName, string displayName, string password, bool hideFromAddressBook, bool disabled, bool locked, string firstName, string initials, string lastName, string address, string city, string state, string zip, string country, string jobTitle, string company, string department, string office, string managerAccountName, string businessPhone, string fax, string homePhone, string mobilePhone, string pager, string webPage, string notes, string externalEmail, bool userMustChangePassword) { Organization.SetUserGeneralSettings(organizationId, accountName, displayName, password, hideFromAddressBook, disabled, locked, firstName, initials, lastName, address, city, state, zip, country, jobTitle, company, department, office, managerAccountName, businessPhone, fax, homePhone, mobilePhone, pager, webPage, notes, externalEmail, userMustChangePassword); } [WebMethod, SoapHeader("settings")] public void SetUserPassword(string organizationId, string accountName, string password) { Organization.SetUserPassword(organizationId, accountName, password); } [WebMethod, SoapHeader("settings")] public void SetUserPrincipalName(string organizationId, string accountName, string userPrincipalName) { Organization.SetUserPrincipalName(organizationId, accountName, userPrincipalName); } [WebMethod, SoapHeader("settings")] public void DeleteOrganizationDomain(string organizationDistinguishedName, string domain) { Organization.DeleteOrganizationDomain(organizationDistinguishedName, domain); } [WebMethod, SoapHeader("settings")] public void CreateOrganizationDomain(string organizationDistinguishedName, string domain) { Organization.CreateOrganizationDomain(organizationDistinguishedName, domain); } [WebMethod, SoapHeader("settings")] public PasswordPolicyResult GetPasswordPolicy() { return Organization.GetPasswordPolicy(); } [WebMethod, SoapHeader("settings")] public string GetSamAccountNameByUserPrincipalName(string organizationId, string userPrincipalName) { return Organization.GetSamAccountNameByUserPrincipalName(organizationId, userPrincipalName); } [WebMethod, SoapHeader("settings")] public bool DoesSamAccountNameExist(string accountName) { return Organization.DoesSamAccountNameExist(accountName); } [WebMethod, SoapHeader("settings")] public MappedDrive[] GetDriveMaps(string organizationId) { return Organization.GetDriveMaps(organizationId); } [WebMethod, SoapHeader("settings")] public int CreateMappedDrive(string organizationId, string drive, string labelAs, string path) { return Organization.CreateMappedDrive(organizationId, drive, labelAs, path); } [WebMethod, SoapHeader("settings")] public void DeleteMappedDrive(string organizationId, string drive) { Organization.DeleteMappedDrive(organizationId, drive); } [WebMethod, SoapHeader("settings")] public void DeleteMappedDriveByPath(string organizationId, string path) { Organization.DeleteMappedDriveByPath(organizationId, path); } [WebMethod, SoapHeader("settings")] public void DeleteMappedDrivesGPO(string organizationId) { Organization.DeleteMappedDrivesGPO(organizationId); } [WebMethod, SoapHeader("settings")] public void SetDriveMapsTargetingFilter(string organizationId, ExchangeAccount[] accounts, string folderName) { Organization.SetDriveMapsTargetingFilter(organizationId, accounts, folderName); } [WebMethod, SoapHeader("settings")] public void ChangeDriveMapFolderPath(string organizationId, string oldFolder, string newFolder) { Organization.ChangeDriveMapFolderPath(organizationId, oldFolder, newFolder); } [WebMethod, SoapHeader("settings")] public List<OrganizationUser> GetOrganizationUsersWithExpiredPassword(string organizationId, int daysBeforeExpiration) { return Organization.GetOrganizationUsersWithExpiredPassword(organizationId, daysBeforeExpiration); } [WebMethod, SoapHeader("settings")] public void ApplyPasswordSettings(string organizationId, OrganizationPasswordSettings passwordSettings) { Organization.ApplyPasswordSettings(organizationId, passwordSettings); } [WebMethod, SoapHeader("settings")] public bool CheckPhoneNumberIsInUse(string phoneNumber, string userSamAccountName = null) { return Organization.CheckPhoneNumberIsInUse(phoneNumber, userSamAccountName); } [WebMethod, SoapHeader("settings")] public OrganizationUser GetOrganizationUserWithExtraData(string loginName, string organizationId) { return Organization.GetOrganizationUserWithExtraData(loginName, organizationId); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Runtime.InteropServices; using Xunit; namespace System.Numerics.Tests { public class QuaternionTests { // A test for Dot (Quaternion, Quaternion) [Fact] public void QuaternionDotTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); float expected = 70.0f; float actual; actual = Quaternion.Dot(a, b); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Dot did not return the expected value."); } // A test for Length () [Fact] public void QuaternionLengthTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); float w = 4.0f; Quaternion target = new Quaternion(v, w); float expected = 5.477226f; float actual; actual = target.Length(); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Length did not return the expected value."); } // A test for LengthSquared () [Fact] public void QuaternionLengthSquaredTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); float w = 4.0f; Quaternion target = new Quaternion(v, w); float expected = 30.0f; float actual; actual = target.LengthSquared(); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.LengthSquared did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) [Fact] public void QuaternionLerpTest() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.5f; Quaternion expected = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(20.0f)); Quaternion actual; actual = Quaternion.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); // Case a and b are same. expected = a; actual = Quaternion.Lerp(a, a, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) // Lerp test when t = 0 [Fact] public void QuaternionLerpTest1() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.0f; Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W); Quaternion actual = Quaternion.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) // Lerp test when t = 1 [Fact] public void QuaternionLerpTest2() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 1.0f; Quaternion expected = new Quaternion(b.X, b.Y, b.Z, b.W); Quaternion actual = Quaternion.Lerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) // Lerp test when the two quaternions are more than 90 degree (dot product <0) [Fact] public void QuaternionLerpTest3() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.Negate(a); float t = 1.0f; Quaternion actual = Quaternion.Lerp(a, b, t); // Note that in quaternion world, Q == -Q. In the case of quaternions dot product is zero, // one of the quaternion will be flipped to compute the shortest distance. When t = 1, we // expect the result to be the same as quaternion b but flipped. Assert.True(actual == a, "Quaternion.Lerp did not return the expected value."); } // A test for Conjugate(Quaternion) [Fact] public void QuaternionConjugateTest1() { Quaternion a = new Quaternion(1, 2, 3, 4); Quaternion expected = new Quaternion(-1, -2, -3, 4); Quaternion actual; actual = Quaternion.Conjugate(a); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Conjugate did not return the expected value."); } // A test for Normalize (Quaternion) [Fact] public void QuaternionNormalizeTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion expected = new Quaternion(0.182574168f, 0.365148336f, 0.5477225f, 0.7302967f); Quaternion actual; actual = Quaternion.Normalize(a); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Normalize did not return the expected value."); } // A test for Normalize (Quaternion) // Normalize zero length quaternion [Fact] public void QuaternionNormalizeTest1() { Quaternion a = new Quaternion(0.0f, 0.0f, -0.0f, 0.0f); Quaternion actual = Quaternion.Normalize(a); Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z) && float.IsNaN(actual.W) , "Quaternion.Normalize did not return the expected value."); } // A test for Concatenate(Quaternion, Quaternion) [Fact] public void QuaternionConcatenateTest1() { Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion a = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f); Quaternion actual; actual = Quaternion.Concatenate(a, b); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Concatenate did not return the expected value."); } // A test for operator - (Quaternion, Quaternion) [Fact] public void QuaternionSubtractionTest() { Quaternion a = new Quaternion(1.0f, 6.0f, 7.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 2.0f, 3.0f, 8.0f); Quaternion expected = new Quaternion(-4.0f, 4.0f, 4.0f, -4.0f); Quaternion actual; actual = a - b; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator - did not return the expected value."); } // A test for operator * (Quaternion, float) [Fact] public void QuaternionMultiplyTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); float factor = 0.5f; Quaternion expected = new Quaternion(0.5f, 1.0f, 1.5f, 2.0f); Quaternion actual; actual = a * factor; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator * did not return the expected value."); } // A test for operator * (Quaternion, Quaternion) [Fact] public void QuaternionMultiplyTest1() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f); Quaternion actual; actual = a * b; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator * did not return the expected value."); } // A test for operator / (Quaternion, Quaternion) [Fact] public void QuaternionDivisionTest1() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(-0.045977015f, -0.09195402f, -7.450581E-9f, 0.402298868f); Quaternion actual; actual = a / b; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator / did not return the expected value."); } // A test for operator + (Quaternion, Quaternion) [Fact] public void QuaternionAdditionTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(6.0f, 8.0f, 10.0f, 12.0f); Quaternion actual; actual = a + b; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator + did not return the expected value."); } // A test for Quaternion (float, float, float, float) [Fact] public void QuaternionConstructorTest() { float x = 1.0f; float y = 2.0f; float z = 3.0f; float w = 4.0f; Quaternion target = new Quaternion(x, y, z, w); Assert.True(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y) && MathHelper.Equal(target.Z, z) && MathHelper.Equal(target.W, w), "Quaternion.constructor (x,y,z,w) did not return the expected value."); } // A test for Quaternion (Vector3f, float) [Fact] public void QuaternionConstructorTest1() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); float w = 4.0f; Quaternion target = new Quaternion(v, w); Assert.True(MathHelper.Equal(target.X, v.X) && MathHelper.Equal(target.Y, v.Y) && MathHelper.Equal(target.Z, v.Z) && MathHelper.Equal(target.W, w), "Quaternion.constructor (Vector3f,w) did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3f, float) [Fact] public void QuaternionCreateFromAxisAngleTest() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); float angle = MathHelper.ToRadians(30.0f); Quaternion expected = new Quaternion(0.0691723f, 0.1383446f, 0.207516879f, 0.9659258f); Quaternion actual; actual = Quaternion.CreateFromAxisAngle(axis, angle); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.CreateFromAxisAngle did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3f, float) // CreateFromAxisAngle of zero vector [Fact] public void QuaternionCreateFromAxisAngleTest1() { Vector3 axis = new Vector3(); float angle = MathHelper.ToRadians(-30.0f); float cos = (float)System.Math.Cos(angle / 2.0f); Quaternion actual = Quaternion.CreateFromAxisAngle(axis, angle); Assert.True(actual.X == 0.0f && actual.Y == 0.0f && actual.Z == 0.0f && MathHelper.Equal(cos, actual.W) , "Quaternion.CreateFromAxisAngle did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3f, float) // CreateFromAxisAngle of angle = 30 && 750 [Fact] public void QuaternionCreateFromAxisAngleTest2() { Vector3 axis = new Vector3(1, 0, 0); float angle1 = MathHelper.ToRadians(30.0f); float angle2 = MathHelper.ToRadians(750.0f); Quaternion actual1 = Quaternion.CreateFromAxisAngle(axis, angle1); Quaternion actual2 = Quaternion.CreateFromAxisAngle(axis, angle2); Assert.True(MathHelper.Equal(actual1, actual2), "Quaternion.CreateFromAxisAngle did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3f, float) // CreateFromAxisAngle of angle = 30 && 390 [Fact] public void QuaternionCreateFromAxisAngleTest3() { Vector3 axis = new Vector3(1, 0, 0); float angle1 = MathHelper.ToRadians(30.0f); float angle2 = MathHelper.ToRadians(390.0f); Quaternion actual1 = Quaternion.CreateFromAxisAngle(axis, angle1); Quaternion actual2 = Quaternion.CreateFromAxisAngle(axis, angle2); actual1.X = -actual1.X; actual1.W = -actual1.W; Assert.True(MathHelper.Equal(actual1, actual2), "Quaternion.CreateFromAxisAngle did not return the expected value."); } [Fact] public void QuaternionCreateFromYawPitchRollTest1() { float yawAngle = MathHelper.ToRadians(30.0f); float pitchAngle = MathHelper.ToRadians(40.0f); float rollAngle = MathHelper.ToRadians(50.0f); Quaternion yaw = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawAngle); Quaternion pitch = Quaternion.CreateFromAxisAngle(Vector3.UnitX, pitchAngle); Quaternion roll = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, rollAngle); Quaternion expected = yaw * pitch * roll; Quaternion actual = Quaternion.CreateFromYawPitchRoll(yawAngle, pitchAngle, rollAngle); Assert.True(MathHelper.Equal(expected, actual)); } // Covers more numeric rigions [Fact] public void QuaternionCreateFromYawPitchRollTest2() { const float step = 35.0f; for (float yawAngle = -720.0f; yawAngle <= 720.0f; yawAngle += step) { for (float pitchAngle = -720.0f; pitchAngle <= 720.0f; pitchAngle += step) { for (float rollAngle = -720.0f; rollAngle <= 720.0f; rollAngle += step) { float yawRad = MathHelper.ToRadians(yawAngle); float pitchRad = MathHelper.ToRadians(pitchAngle); float rollRad = MathHelper.ToRadians(rollAngle); Quaternion yaw = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawRad); Quaternion pitch = Quaternion.CreateFromAxisAngle(Vector3.UnitX, pitchRad); Quaternion roll = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, rollRad); Quaternion expected = yaw * pitch * roll; Quaternion actual = Quaternion.CreateFromYawPitchRoll(yawRad, pitchRad, rollRad); Assert.True(MathHelper.Equal(expected, actual), String.Format("Yaw:{0} Pitch:{1} Roll:{2}", yawAngle, pitchAngle, rollAngle)); } } } } // A test for Slerp (Quaternion, Quaternion, float) [Fact] public void QuaternionSlerpTest() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.5f; Quaternion expected = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(20.0f)); Quaternion actual; actual = Quaternion.Slerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); // Case a and b are same. expected = a; actual = Quaternion.Slerp(a, a, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where t = 0 [Fact] public void QuaternionSlerpTest1() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.0f; Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W); Quaternion actual = Quaternion.Slerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where t = 1 [Fact] public void QuaternionSlerpTest2() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 1.0f; Quaternion expected = new Quaternion(b.X, b.Y, b.Z, b.W); Quaternion actual = Quaternion.Slerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where dot product is < 0 [Fact] public void QuaternionSlerpTest3() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = -a; float t = 1.0f; Quaternion expected = a; Quaternion actual = Quaternion.Slerp(a, b, t); // Note that in quaternion world, Q == -Q. In the case of quaternions dot product is zero, // one of the quaternion will be flipped to compute the shortest distance. When t = 1, we // expect the result to be the same as quaternion b but flipped. Assert.True(actual == expected, "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where the quaternion is flipped [Fact] public void QuaternionSlerpTest4() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = -Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.0f; Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W); Quaternion actual = Quaternion.Slerp(a, b, t); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for operator - (Quaternion) [Fact] public void QuaternionUnaryNegationTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion expected = new Quaternion(-1.0f, -2.0f, -3.0f, -4.0f); Quaternion actual; actual = -a; Assert.True(MathHelper.Equal(expected, actual), "Quaternion.operator - did not return the expected value."); } // A test for Inverse (Quaternion) [Fact] public void QuaternionInverseTest() { Quaternion a = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(-0.0287356321f, -0.03448276f, -0.0402298868f, 0.04597701f); Quaternion actual; actual = Quaternion.Inverse(a); Assert.Equal(expected, actual); } // A test for Inverse (Quaternion) // Invert zero length quaternion [Fact] public void QuaternionInverseTest1() { Quaternion a = new Quaternion(); Quaternion actual = Quaternion.Inverse(a); Assert.True(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z) && float.IsNaN(actual.W) ); } // A test for ToString () [Fact] public void QuaternionToStringTest() { Quaternion target = new Quaternion(-1.0f, 2.2f, 3.3f, -4.4f); string expected = string.Format(CultureInfo.CurrentCulture , "{{X:{0} Y:{1} Z:{2} W:{3}}}" , -1.0f, 2.2f, 3.3f, -4.4f); string actual = target.ToString(); Assert.Equal(expected, actual); } // A test for Add (Quaternion, Quaternion) [Fact] public void QuaternionAddTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(6.0f, 8.0f, 10.0f, 12.0f); Quaternion actual; actual = Quaternion.Add(a, b); Assert.Equal(expected, actual); } // A test for Divide (Quaternion, Quaternion) [Fact] public void QuaternionDivideTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(-0.045977015f, -0.09195402f, -7.450581E-9f, 0.402298868f); Quaternion actual; actual = Quaternion.Divide(a, b); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Divide did not return the expected value."); } // A test for Equals (object) [Fact] public void QuaternionEqualsTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values object obj = b; bool expected = true; bool actual = a.Equals(obj); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; obj = b; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare between different types. obj = new Vector4(); expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); // case 3: compare against null. obj = null; expected = false; actual = a.Equals(obj); Assert.Equal(expected, actual); } // A test for GetHashCode () [Fact] public void QuaternionGetHashCodeTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); int expected = a.X.GetHashCode() + a.Y.GetHashCode() + a.Z.GetHashCode() + a.W.GetHashCode(); int actual = a.GetHashCode(); Assert.Equal(expected, actual); } // A test for Multiply (Quaternion, float) [Fact] public void QuaternionMultiplyTest2() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); float factor = 0.5f; Quaternion expected = new Quaternion(0.5f, 1.0f, 1.5f, 2.0f); Quaternion actual; actual = Quaternion.Multiply(a, factor); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Multiply did not return the expected value."); } // A test for Multiply (Quaternion, Quaternion) [Fact] public void QuaternionMultiplyTest3() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f); Quaternion actual; actual = Quaternion.Multiply(a, b); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.Multiply did not return the expected value."); } // A test for Negate (Quaternion) [Fact] public void QuaternionNegateTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion expected = new Quaternion(-1.0f, -2.0f, -3.0f, -4.0f); Quaternion actual; actual = Quaternion.Negate(a); Assert.Equal(expected, actual); } // A test for Subtract (Quaternion, Quaternion) [Fact] public void QuaternionSubtractTest() { Quaternion a = new Quaternion(1.0f, 6.0f, 7.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 2.0f, 3.0f, 8.0f); Quaternion expected = new Quaternion(-4.0f, 4.0f, 4.0f, -4.0f); Quaternion actual; actual = Quaternion.Subtract(a, b); Assert.Equal(expected, actual); } // A test for operator != (Quaternion, Quaternion) [Fact] public void QuaternionInequalityTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = false; bool actual = a != b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = true; actual = a != b; Assert.Equal(expected, actual); } // A test for operator == (Quaternion, Quaternion) [Fact] public void QuaternionEqualityTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = true; bool actual = a == b; Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a == b; Assert.Equal(expected, actual); } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert Identity matrix test [Fact] public void QuaternionFromRotationMatrixTest1() { Matrix4x4 matrix = Matrix4x4.Identity; Quaternion expected = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.Equal(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert X axis rotation matrix [Fact] public void QuaternionFromRotationMatrixTest2() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), expected.ToString(), actual.ToString())); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), matrix.ToString(), m2.ToString())); } } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert Y axis rotation matrix [Fact] public void QuaternionFromRotationMatrixTest3() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationY(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0}", angle.ToString())); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0}", angle.ToString())); } } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert Z axis rotation matrix [Fact] public void QuaternionFromRotationMatrixTest4() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), expected.ToString(), actual.ToString())); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), matrix.ToString(), m2.ToString())); } } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert XYZ axis rotation matrix [Fact] public void QuaternionFromRotationMatrixTest5() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationY(angle) * Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), expected.ToString(), actual.ToString())); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), string.Format("Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), matrix.ToString(), m2.ToString())); } } // A test for CreateFromRotationMatrix (Matrix4x4) // X axis is most large axis case [Fact] public void QuaternionFromRotationMatrixWithScaledMatrixTest1() { float angle = MathHelper.ToRadians(180.0f); Matrix4x4 matrix = Matrix4x4.CreateRotationY(angle) * Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Y axis is most large axis case [Fact] public void QuaternionFromRotationMatrixWithScaledMatrixTest2() { float angle = MathHelper.ToRadians(180.0f); Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Z axis is most large axis case [Fact] public void QuaternionFromRotationMatrixWithScaledMatrixTest3() { float angle = MathHelper.ToRadians(180.0f); Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationY(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.True(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.True(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for Equals (Quaternion) [Fact] public void QuaternionEqualsTest1() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = true; bool actual = a.Equals(b); Assert.Equal(expected, actual); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a.Equals(b); Assert.Equal(expected, actual); } // A test for Identity [Fact] public void QuaternionIdentityTest() { Quaternion val = new Quaternion(0, 0, 0, 1); Assert.Equal(val, Quaternion.Identity); } // A test for IsIdentity [Fact] public void QuaternionIsIdentityTest() { Assert.True(Quaternion.Identity.IsIdentity); Assert.True(new Quaternion(0, 0, 0, 1).IsIdentity); Assert.False(new Quaternion(1, 0, 0, 1).IsIdentity); Assert.False(new Quaternion(0, 1, 0, 1).IsIdentity); Assert.False(new Quaternion(0, 0, 1, 1).IsIdentity); Assert.False(new Quaternion(0, 0, 0, 0).IsIdentity); } // A test for Quaternion comparison involving NaN values [Fact] public void QuaternionEqualsNanTest() { Quaternion a = new Quaternion(float.NaN, 0, 0, 0); Quaternion b = new Quaternion(0, float.NaN, 0, 0); Quaternion c = new Quaternion(0, 0, float.NaN, 0); Quaternion d = new Quaternion(0, 0, 0, float.NaN); Assert.False(a == new Quaternion(0, 0, 0, 0)); Assert.False(b == new Quaternion(0, 0, 0, 0)); Assert.False(c == new Quaternion(0, 0, 0, 0)); Assert.False(d == new Quaternion(0, 0, 0, 0)); Assert.True(a != new Quaternion(0, 0, 0, 0)); Assert.True(b != new Quaternion(0, 0, 0, 0)); Assert.True(c != new Quaternion(0, 0, 0, 0)); Assert.True(d != new Quaternion(0, 0, 0, 0)); Assert.False(a.Equals(new Quaternion(0, 0, 0, 0))); Assert.False(b.Equals(new Quaternion(0, 0, 0, 0))); Assert.False(c.Equals(new Quaternion(0, 0, 0, 0))); Assert.False(d.Equals(new Quaternion(0, 0, 0, 0))); Assert.False(a.IsIdentity); Assert.False(b.IsIdentity); Assert.False(c.IsIdentity); Assert.False(d.IsIdentity); // Counterintuitive result - IEEE rules for NaN comparison are weird! Assert.False(a.Equals(a)); Assert.False(b.Equals(b)); Assert.False(c.Equals(c)); Assert.False(d.Equals(d)); } // A test to make sure these types are blittable directly into GPU buffer memory layouts [Fact] public unsafe void QuaternionSizeofTest() { Assert.Equal(16, sizeof(Quaternion)); Assert.Equal(32, sizeof(Quaternion_2x)); Assert.Equal(20, sizeof(QuaternionPlusFloat)); Assert.Equal(40, sizeof(QuaternionPlusFloat_2x)); } [StructLayout(LayoutKind.Sequential)] struct Quaternion_2x { private Quaternion _a; private Quaternion _b; } [StructLayout(LayoutKind.Sequential)] struct QuaternionPlusFloat { private Quaternion _v; private float _f; } [StructLayout(LayoutKind.Sequential)] struct QuaternionPlusFloat_2x { private QuaternionPlusFloat _a; private QuaternionPlusFloat _b; } // A test to make sure the fields are laid out how we expect [Fact] public unsafe void QuaternionFieldOffsetTest() { Quaternion* ptr = (Quaternion*)0; Assert.Equal(new IntPtr(0), new IntPtr(&ptr->X)); Assert.Equal(new IntPtr(4), new IntPtr(&ptr->Y)); Assert.Equal(new IntPtr(8), new IntPtr(&ptr->Z)); Assert.Equal(new IntPtr(12), new IntPtr(&ptr->W)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using Microsoft.DotNet.InternalAbstractions; using Xunit; namespace Microsoft.DotNet.CoreSetup.Test.HostActivation.MultilevelSDKLookup { public class GivenThatICareAboutMultilevelSDKLookup { private static readonly Mutex id_mutex = new Mutex(); private static IDictionary<string, string> s_DefaultEnvironment = new Dictionary<string, string>() { {"COREHOST_TRACE", "1" }, // The SDK being used may be crossgen'd for a different architecture than we are building for. // Turn off ready to run, so an x64 crossgen'd SDK can be loaded in an x86 process. {"COMPlus_ReadyToRun", "0" }, }; private RepoDirectoriesProvider RepoDirectories; private TestProjectFixture PreviouslyBuiltAndRestoredPortableTestProjectFixture; private string _currentWorkingDir; private string _userDir; private string _executableDir; private string _cwdSdkBaseDir; private string _userSdkBaseDir; private string _exeSdkBaseDir; private string _cwdSelectedMessage; private string _userSelectedMessage; private string _exeSelectedMessage; private string _sdkDir; private const string _dotnetSdkDllMessageTerminator = "dotnet.dll]"; public GivenThatICareAboutMultilevelSDKLookup() { // From the artifacts dir, it's possible to find where the sharedFrameworkPublish folder is. We need // to locate it because we'll copy its contents into other folders string artifactsDir = Environment.GetEnvironmentVariable("TEST_ARTIFACTS"); string builtDotnet = Path.Combine(artifactsDir, "sharedFrameworkPublish"); // The dotnetMultilevelSDKLookup dir will contain some folders and files that will be // necessary to perform the tests string baseMultilevelDir = Path.Combine(artifactsDir, "dotnetMultilevelSDKLookup"); string multilevelDir = CalculateMultilevelDirectory(baseMultilevelDir); // The three tested locations will be the cwd, the user folder and the exe dir. cwd and user are no longer supported. // All dirs will be placed inside the multilevel folder _currentWorkingDir = Path.Combine(multilevelDir, "cwd"); _userDir = Path.Combine(multilevelDir, "user"); _executableDir = Path.Combine(multilevelDir, "exe"); // It's necessary to copy the entire publish folder to the exe dir because // we'll need to build from it. The CopyDirectory method automatically creates the dest dir CopyDirectory(builtDotnet, _executableDir); RepoDirectories = new RepoDirectoriesProvider(builtDotnet: _executableDir); // SdkBaseDirs contain all available version folders _cwdSdkBaseDir = Path.Combine(_currentWorkingDir, "sdk"); _userSdkBaseDir = Path.Combine(_userDir, ".dotnet", RepoDirectories.BuildArchitecture, "sdk"); _exeSdkBaseDir = Path.Combine(_executableDir, "sdk"); // Create directories Directory.CreateDirectory(_cwdSdkBaseDir); Directory.CreateDirectory(_userSdkBaseDir); Directory.CreateDirectory(_exeSdkBaseDir); // Restore and build PortableApp from exe dir PreviouslyBuiltAndRestoredPortableTestProjectFixture = new TestProjectFixture("PortableApp", RepoDirectories) .EnsureRestored(RepoDirectories.CorehostPackages) .BuildProject(); var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture; // Set a dummy framework version (9999.0.0) in the exe sharedFx location. We will // always pick the framework from this to avoid interference with the sharedFxLookup string exeDirDummyFxVersion = Path.Combine(_executableDir, "shared", "Microsoft.NETCore.App", "9999.0.0"); string builtSharedFxDir = fixture.BuiltDotnet.GreatestVersionSharedFxPath; CopyDirectory(builtSharedFxDir, exeDirDummyFxVersion); // The actual SDK version can be obtained from the built fixture. We'll use it to // locate the sdkDir from which we can get the files contained in the version folder string sdkBaseDir = Path.Combine(fixture.SdkDotnet.BinPath, "sdk"); var sdkVersionDirs = Directory.EnumerateDirectories(sdkBaseDir) .Select(p => Path.GetFileName(p)); string greatestVersionSdk = sdkVersionDirs .Where(p => !string.Equals(p, "NuGetFallbackFolder", StringComparison.OrdinalIgnoreCase)) .OrderByDescending(p => p.ToLower()) .First(); _sdkDir = Path.Combine(sdkBaseDir, greatestVersionSdk); // Trace messages used to identify from which folder the SDK was picked _cwdSelectedMessage = $"Using dotnet SDK dll=[{_cwdSdkBaseDir}"; _userSelectedMessage = $"Using dotnet SDK dll=[{_userSdkBaseDir}"; _exeSelectedMessage = $"Using dotnet SDK dll=[{_exeSdkBaseDir}"; } [Fact] public void SdkLookup_Global_Json_Patch_Rollup() { var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Set specified CLI version = 9999.0.0-global-dummy SetGlobalJsonVersion(); // Add some dummy versions AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.1", "9999.0.0-dummy"); // Specified CLI version: 9999.0.0-global-dummy // CWD: empty // User: empty // Exe: 9999.0.1, 9999.0.0-dummy // Expected: 9999.0.1 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.1", _dotnetSdkDllMessageTerminator)); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.4"); // Specified CLI version: 9999.0.0-global-dummy // CWD: empty // User: empty // Exe: 9999.0.1, 9999.0.0-dummy, 9999.0.4 // Expected: 9999.0.4 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.6-dummy"); // Specified CLI version: 9999.0.0-global-dummy // CWD: empty // User: empty // Exe: 9999.0.1, 9999.0.0-dummy, 9999.0.4, 9999.0.6-dummy // Expected: 9999.0.6-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.6-dummy", _dotnetSdkDllMessageTerminator)); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.0-global-dummy"); // Specified CLI version: 9999.0.0-global-dummy // CWD: empty // User: empty // Exe: 9999.0.1, 9999.0.0-dummy, 9999.0.4, 9999.0.6-dummy, 9999.0.0-global-dummy // Expected: 9999.0.0-global-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.0-global-dummy", _dotnetSdkDllMessageTerminator)); // Verify we have the expected sdk versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.0.0-dummy") .And .HaveStdOutContaining("9999.0.0-global-dummy") .And .HaveStdOutContaining("9999.0.1") .And .HaveStdOutContaining("9999.0.4") .And .HaveStdOutContaining("9999.0.6-dummy"); } [Fact] public void SdkLookup_Negative_Version() { var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Add a negative CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "-1.-1.-1"); // Specified CLI version: none // CWD: empty // User: empty // Exe: -1.-1.-1 // Expected: no compatible version and a specific error message dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Fail() .And .HaveStdErrContaining("It was not possible to find any SDK version"); // Add specified CLI version AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.4"); // Specified CLI version: none // CWD: empty // User: empty // Exe: -1.-1.-1, 9999.0.4 // Expected: 9999.0.4 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.4", _dotnetSdkDllMessageTerminator)); // Verify we have the expected sdk versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .EnvironmentVariable("DOTNET_MULTILEVEL_LOOKUP", "0") .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.0.4"); } [Fact] public void SdkLookup_Must_Pick_The_Highest_Semantic_Version() { var fixture = PreviouslyBuiltAndRestoredPortableTestProjectFixture .Copy(); var dotnet = fixture.BuiltDotnet; // Add dummy versions in the exe dir AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.0", "9999.0.1-dummy"); // Specified CLI version: none // CWD: empty // User: empty // Exe: 9999.0.0, 9999.0.1-dummy // Expected: 9999.0.1-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.1-dummy", _dotnetSdkDllMessageTerminator)); // Add dummy versions AddAvailableSdkVersions(_userSdkBaseDir, "9999.0.2"); AddAvailableSdkVersions(_cwdSdkBaseDir, "10000.0.0"); AddAvailableSdkVersions(_exeSdkBaseDir, "9999.0.1"); // Specified CLI version: none // CWD: 10000.0.0 --> should not be picked // User: 9999.0.2 --> should not be picked // Exe: 9999.0.0, 9999.0.1-dummy, 9999.0.1 // Expected: 9999.0.1 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "9999.0.1", _dotnetSdkDllMessageTerminator)); // Add a dummy version in the exe dir AddAvailableSdkVersions(_exeSdkBaseDir, "10000.0.0-dummy"); // Specified CLI version: none // CWD: 10000.0.0 --> should not be picked // User: 9999.0.2 --> should not be picked // Exe: 9999.0.0, 9999.0.1-dummy, 9999.0.1, 10000.0.0-dummy // Expected: 10000.0.0-dummy from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "10000.0.0-dummy", _dotnetSdkDllMessageTerminator)); // Add a dummy version in the user dir AddAvailableSdkVersions(_exeSdkBaseDir, "10000.0.0"); // Specified CLI version: none // CWD: 10000.0.0 --> should not be picked // User: 9999.0.2 --> should not be picked // Exe: 9999.0.0, 9999.0.1-dummy, 9999.0.1, 10000.0.0-dummy, 10000.0.0 // Expected: 10000.0.0 from exe dir dotnet.Exec("help") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .CaptureStdErr() .Execute() .Should() .Pass() .And .HaveStdErrContaining(Path.Combine(_exeSelectedMessage, "10000.0.0", _dotnetSdkDllMessageTerminator)); // Verify we have the expected sdk versions dotnet.Exec("--list-sdks") .WorkingDirectory(_currentWorkingDir) .WithUserProfile(_userDir) .Environment(s_DefaultEnvironment) .CaptureStdOut() .Execute() .Should() .Pass() .And .HaveStdOutContaining("9999.0.0") .And .HaveStdOutContaining("9999.0.1-dummy") .And .HaveStdOutContaining("9999.0.1") .And .HaveStdOutContaining("10000.0.0") .And .HaveStdOutContaining("10000.0.0-dummy"); } // This method adds a list of new sdk version folders in the specified // sdkBaseDir. The files are copied from the _sdkDir. Also, the dotnet.runtimeconfig.json // file is overwritten in order to use a dummy framework version (9999.0.0) // Remarks: // - If the sdkBaseDir does not exist, then a DirectoryNotFoundException // is thrown. // - If a specified version folder already exists, then it is deleted and replaced // with the contents of the _builtSharedFxDir. private void AddAvailableSdkVersions(string sdkBaseDir, params string[] availableVersions) { DirectoryInfo sdkBaseDirInfo = new DirectoryInfo(sdkBaseDir); if (!sdkBaseDirInfo.Exists) { throw new DirectoryNotFoundException(); } string dummyRuntimeConfig = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils", "SDKLookup", "dotnet.runtimeconfig.json"); foreach (string version in availableVersions) { string newSdkDir = Path.Combine(sdkBaseDir, version); CopyDirectory(_sdkDir, newSdkDir); string runtimeConfig = Path.Combine(newSdkDir, "dotnet.runtimeconfig.json"); File.Copy(dummyRuntimeConfig, runtimeConfig, true); } } // This method removes a list of sdk version folders from the specified sdkBaseDir. // Remarks: // - If the sdkBaseDir does not exist, then a DirectoryNotFoundException // is thrown. // - If a specified version folder does not exist, then a DirectoryNotFoundException // is thrown. private void DeleteAvailableSdkVersions(string sdkBaseDir, params string[] availableVersions) { DirectoryInfo sdkBaseDirInfo = new DirectoryInfo(sdkBaseDir); if (!sdkBaseDirInfo.Exists) { throw new DirectoryNotFoundException(); } foreach (string version in availableVersions) { string sdkDir = Path.Combine(sdkBaseDir, version); if (!Directory.Exists(sdkDir)) { throw new DirectoryNotFoundException(); } Directory.Delete(sdkDir, true); } } // CopyDirectory recursively copies a directory. // Remarks: // - If the dest dir does not exist, then it is created. // - If the dest dir exists, then it is substituted with the new one // (original files and subfolders are deleted). // - If the src dir does not exist, then a DirectoryNotFoundException // is thrown. private void CopyDirectory(string srcDir, string dstDir) { DirectoryInfo srcDirInfo = new DirectoryInfo(srcDir); if (!srcDirInfo.Exists) { throw new DirectoryNotFoundException(); } DirectoryInfo dstDirInfo = new DirectoryInfo(dstDir); if (dstDirInfo.Exists) { dstDirInfo.Delete(true); } dstDirInfo.Create(); foreach (FileInfo fileInfo in srcDirInfo.GetFiles()) { string newFile = Path.Combine(dstDir, fileInfo.Name); fileInfo.CopyTo(newFile); } foreach (DirectoryInfo subdirInfo in srcDirInfo.GetDirectories()) { string newDir = Path.Combine(dstDir, subdirInfo.Name); CopyDirectory(subdirInfo.FullName, newDir); } } // Put a global.json file in the cwd in order to specify a CLI // dummy version (9999.0.0-global-dummy) public void SetGlobalJsonVersion() { string destFile = Path.Combine(_currentWorkingDir, "global.json"); string srcFile = Path.Combine(RepoDirectories.RepoRoot, "src", "test", "Assets", "TestUtils", "SDKLookup", "global.json"); File.Copy(srcFile, destFile, true); } // MultilevelDirectory is %TEST_ARTIFACTS%\dotnetMultilevelSDKLookup\id. // We must locate the first non existing id. private string CalculateMultilevelDirectory(string baseMultilevelDir) { id_mutex.WaitOne(); int count = 0; string multilevelDir; do { multilevelDir = Path.Combine(baseMultilevelDir, count.ToString()); count++; } while (Directory.Exists(multilevelDir)); id_mutex.ReleaseMutex(); return multilevelDir; } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData.Atom { #region Namespaces using System; using System.Globalization; using System.Xml; using Microsoft.Data.OData; #endregion Namespaces /// <summary> /// Helper to convert values to strings compliant to the ATOM format /// </summary> internal static class ODataAtomConvert { /// <summary>Used for settings the updated element properly.</summary> private static readonly TimeSpan zeroOffset = new TimeSpan(0, 0, 0); /// <summary> /// Converts a boolean to the corresponding ATOM string representation. /// </summary> /// <param name="b">The boolean value to convert.</param> /// <returns>The ATOM strings representing boolean literals.</returns> internal static string ToString(bool b) { DebugUtils.CheckNoExternalCallers(); return b ? AtomConstants.AtomTrueLiteral : AtomConstants.AtomFalseLiteral; } /// <summary> /// Converts a byte to the corresponding ATOM string representation. /// </summary> /// <param name="b">The byte value to convert.</param> /// <returns>The ATOM strings representing the byte value.</returns> internal static string ToString(byte b) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(b); } /// <summary> /// Converts a decimal to the corresponding ATOM string representation. /// </summary> /// <param name="d">The decimal value to convert.</param> /// <returns>The ATOM strings representing the decimal value.</returns> internal static string ToString(decimal d) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(d); } /// <summary> /// Converts the given date/time value to the string appropriate for Atom format /// </summary> /// <param name="dt">The date/time value to convert.</param> /// <returns>The string version of the date/time value in Atom format.</returns> internal static string ToString(this DateTime dt) { DebugUtils.CheckNoExternalCallers(); return PlatformHelper.ConvertDateTimeToString(dt); } /// <summary> /// Converts the given DateTimeOffset value to string appropriate for Atom format. /// </summary> /// <param name="dateTime">Given DateTimeOffset value.</param> /// <returns>Atom format string representation of <paramref name="dateTime"/>.</returns> internal static string ToString(DateTimeOffset dateTime) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(dateTime); } /// <summary> /// Converts the given DateTimeOffset value to string appropriate for Atom format. /// ToAtomString is used to write values in atom specific elements like updated, etc. /// </summary> /// <param name="dateTime">Given DateTimeOffset value.</param> /// <returns>Atom format string representation of <paramref name="dateTime"/>.</returns> internal static string ToAtomString(DateTimeOffset dateTime) { DebugUtils.CheckNoExternalCallers(); if (dateTime.Offset == zeroOffset) { return dateTime.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture); } return dateTime.ToString("yyyy-MM-ddTHH:mm:sszzz", CultureInfo.InvariantCulture); } /// <summary> /// Converts the given timespan value to the string appropriate for Atom format /// </summary> /// <param name="ts">The timespan value to convert.</param> /// <returns>The string version of the timespan value in Atom format.</returns> internal static string ToString(this TimeSpan ts) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(ts); } /// <summary> /// Converts the given double value to the string appropriate for Atom format /// </summary> /// <param name="d">The double value to convert.</param> /// <returns>The string version of the double value in Atom format.</returns> internal static string ToString(this double d) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(d); } /// <summary> /// Converts the given Int16 value to the string appropriate for Atom format /// </summary> /// <param name="i">The Int16 value to convert.</param> /// <returns>The string version of the Int16 value in Atom format.</returns> internal static string ToString(this Int16 i) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(i); } /// <summary> /// Converts the given Int32 value to the string appropriate for Atom format. /// </summary> /// <param name="i">The Int32 value to convert.</param> /// <returns>The string version of the Int32 in Atom format.</returns> internal static string ToString(this Int32 i) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(i); } /// <summary> /// Converts the given Int64 value to the string appropriate for Atom format. /// </summary> /// <param name="i">The Int64 value to convert.</param> /// <returns>The string version of the Int64 in Atom format.</returns> internal static string ToString(this Int64 i) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(i); } /// <summary> /// Converts the given SByte value to the string appropriate for Atom format. /// </summary> /// <param name="sb">The SByte value to convert.</param> /// <returns>The string version of the SByte in Atom format.</returns> internal static string ToString(this SByte sb) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(sb); } /// <summary> /// Converts the given byte array value to the string appropriate for Atom format. /// </summary> /// <param name="bytes">The byte array to convert.</param> /// <returns>The string version of the byte array in Atom format.</returns> internal static string ToString(this byte[] bytes) { DebugUtils.CheckNoExternalCallers(); return Convert.ToBase64String(bytes); } /// <summary> /// Converts the given Single value to the string appropriate for Atom format. /// </summary> /// <param name="s">The Single value to convert.</param> /// <returns>The string version of the Single in Atom format.</returns> internal static string ToString(this Single s) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(s); } /// <summary> /// Converts the given Guid value to the string appropriate for Atom format. /// </summary> /// <param name="guid">The Guid value to convert.</param> /// <returns>The string version of the Guid in Atom format.</returns> internal static string ToString(this Guid guid) { DebugUtils.CheckNoExternalCallers(); return XmlConvert.ToString(guid); } } }
#if DEBUG //#define GC_DEBUG #endif //#define COSMOSDEBUG using System; using Cosmos.Core.Memory; namespace Cosmos.Core { /// <summary> /// GCImplementation class. Garbage collector. Mostly not implemented. /// </summary> /// <remarks>Most of the class is yet to be implemented.</remarks> [System.Diagnostics.DebuggerStepThrough] public unsafe static class GCImplementation { private unsafe static byte* memPtr = null; private static ulong memLength = 0; private static bool StartedMemoryManager = false; /// <summary> /// /// Acquire lock. Not implemented. /// </summary> /// <exception cref="NotImplementedException">Thrown always.</exception> private static void AcquireLock() { throw new NotImplementedException(); } /// <summary> /// Release lock. Not implemented. /// </summary> /// <exception cref="NotImplementedException">Thrown always.</exception> private static void ReleaseLock() { throw new NotImplementedException(); } /// <summary> /// Alloc new object. /// </summary> public unsafe static uint AllocNewObject(uint aSize) { return (uint)Heap.Alloc(aSize); } /// <summary> /// Free Object from Memory /// </summary> /// <param name="obj">Takes a memory allocated object</param> public unsafe static void Free(object aObj) { Heap.Free(GetPointer(aObj)); } /// <summary> /// Get amount of available Ram /// </summary> /// <returns>Returns amount of available memory to the System in MB</returns> public static ulong GetAvailableRAM() { return memLength / 1024 / 1024; } /// <summary> /// Get a rough estimate of used Memory by the System /// </summary> /// <returns>Returns the used PageSize by the MemoryManager in Bytes.</returns> public static uint GetUsedRAM() { return (RAT.TotalPageCount - RAT.GetPageCount(RAT.PageType.Empty)) * RAT.PageSize; } /// <summary> /// Initialise the Memory Manager, this should not be called anymore since it is done very early during the boot process. /// </summary> public static unsafe void Init() { if (StartedMemoryManager) { return; } StartedMemoryManager = true; var largestBlock = CPU.GetLargestMemoryBlock(); if (largestBlock != null) { memPtr = (byte*)largestBlock->Address; memLength = largestBlock->Length; if ((uint)memPtr < CPU.GetEndOfKernel() + 1024) { memPtr = (byte*)CPU.GetEndOfKernel() + 1024; memPtr += RAT.PageSize - (uint)memPtr % RAT.PageSize; memLength = largestBlock->Length - ((uint)memPtr - (uint)largestBlock->Address); memLength += RAT.PageSize - memLength % RAT.PageSize; } } else { memPtr = (byte*)CPU.GetEndOfKernel() + 1024; memPtr += RAT.PageSize - (uint)memPtr % RAT.PageSize; memLength = (128 * 1024 * 1024); } RAT.Init(memPtr, (uint)memLength); } /// <summary> /// Get the Pointer of any object needed for Free() /// </summary> /// <param name="o">Takes any kind of object</param> /// <returns>Returns a pointer to the area in memory where the object is located</returns> public static unsafe uint* GetPointer(object aObj) => throw null; // this is plugged /// <summary> /// Get the pointer of any object as a uint /// </summary> /// <param name="aObj"></param> /// <returns></returns> public static unsafe uint GetSafePointer(object aObj) { return (uint)GetPointer(aObj); } /// <summary> /// Get cosmos internal type from object /// </summary> /// <param name="aObj"></param> /// <returns></returns> public static unsafe uint GetType(object aObj) { return *GetPointer(aObj); } /// <summary> /// Increments the root count of the object at the pointer by 1 /// </summary> /// <param name="aPtr"></param> public static unsafe void IncRootCount(ushort* aPtr) { if (RAT.GetPageType(aPtr) != 0) { var rootCount = *(aPtr - 1) >> 1; // lowest bit is used to set if hit *(aPtr - 1) = (ushort)((rootCount + 1) << 1); // loest bit can be zero since we shouldnt be doing this while gc is collecting } } /// <summary> /// Decrements the root count of the object at the pointer by 1 /// </summary> /// <param name="aPtr"></param> public static unsafe void DecRootCount(ushort* aPtr) { if (RAT.GetPageType(aPtr) != 0) { var rootCount = *(aPtr - 1) >> 1; // lowest bit is used to set if hit *(aPtr - 1) = (ushort)((rootCount - 1) << 1); // loest bit can be zero since we shouldnt be doing this while gc is collecting } } /// <summary> /// Increments the root count of all object stored in this struct by 1 /// </summary> /// <param name="aPtr"></param> /// <param name="aType">Type of the struct</param> public static unsafe void IncRootCountsInStruct(ushort* aPtr, uint aType) { uint count = VTablesImpl.GetGCFieldCount(aType); uint[] offset = VTablesImpl.GetGCFieldOffsets(aType); uint[] types = VTablesImpl.GetGCFieldTypes(aType); for (int i = 0; i < count; i++) { if (VTablesImpl.IsStruct(types[i])) { IncRootCountsInStruct(aPtr + offset[i] / 2, types[i]); } else { IncRootCount(*(ushort**)(aPtr + offset[i] / 2)); } } } /// <summary> /// Decrements the root count of all object stored in this struct by 1 /// </summary> /// <param name="aPtr"></param> /// <param name="aType">Type of the struct</param> public static unsafe void DecRootCountsInStruct(ushort* aPtr, uint aType) { uint count = VTablesImpl.GetGCFieldCount(aType); uint[] offset = VTablesImpl.GetGCFieldOffsets(aType); uint[] types = VTablesImpl.GetGCFieldTypes(aType); for (int i = 0; i < count; i++) { if (VTablesImpl.IsStruct(types[i])) { DecRootCountsInStruct(aPtr + offset[i] / 2, types[i]); } else { DecRootCount(*(ushort**)(aPtr + offset[i] / 2)); } } } } }
using System; using System.Text; using System.Runtime.InteropServices; //Contains IFilter interface translation //Most translations are from PInvoke.net namespace Inbox2.Platform.Framework.Text.iFilter { [StructLayout(LayoutKind.Sequential)] public struct FULLPROPSPEC { public Guid guidPropSet; public PROPSPEC psProperty; } [StructLayout(LayoutKind.Sequential)] public struct FILTERREGION { public int idChunk; public int cwcStart; public int cwcExtent; } [StructLayout(LayoutKind.Explicit)] public struct PROPSPEC { [FieldOffset(0)] public int ulKind; // 0 - string used; 1 - PROPID [FieldOffset(4)] public int propid; [FieldOffset(4)] public IntPtr lpwstr; } [Flags] public enum IFILTER_FLAGS { /// <summary> /// The caller should use the IPropertySetStorage and IPropertyStorage /// interfaces to locate additional properties. /// When this flag is set, properties available through COM /// enumerators should not be returned from IFilter. /// </summary> IFILTER_FLAGS_OLE_PROPERTIES = 1 } /// <summary> /// Flags controlling the operation of the FileFilter /// instance. /// </summary> [Flags] public enum IFILTER_INIT { NONE = 0, /// <summary> /// Paragraph breaks should be marked with the Unicode PARAGRAPH /// SEPARATOR (0x2029) /// </summary> CANON_PARAGRAPHS = 1, /// <summary> /// Soft returns, such as the newline character in Microsoft Word, should /// be replaced by hard returnsLINE SEPARATOR (0x2028). Existing hard /// returns can be doubled. A carriage return (0x000D), line feed (0x000A), /// or the carriage return and line feed in combination should be considered /// a hard return. The intent is to enable pattern-expression matches that /// match against observed line breaks. /// </summary> HARD_LINE_BREAKS = 2, /// <summary> /// Various word-processing programs have forms of hyphens that are not /// represented in the host character set, such as optional hyphens /// (appearing only at the end of a line) and nonbreaking hyphens. This flag /// indicates that optional hyphens are to be converted to nulls, and /// non-breaking hyphens are to be converted to normal hyphens (0x2010), or /// HYPHEN-MINUSES (0x002D). /// </summary> CANON_HYPHENS = 4, /// <summary> /// Just as the CANON_HYPHENS flag standardizes hyphens, /// this one standardizes spaces. All special space characters, such as /// nonbreaking spaces, are converted to the standard space character /// (0x0020). /// </summary> CANON_SPACES = 8, /// <summary> /// Indicates that the client wants text split into chunks representing /// public value-type properties. /// </summary> APPLY_INDEX_ATTRIBUTES = 16, /// <summary> /// Indicates that the client wants text split into chunks representing /// properties determined during the indexing process. /// </summary> APPLY_CRAWL_ATTRIBUTES = 256, /// <summary> /// Any properties not covered by the APPLY_INDEX_ATTRIBUTES /// and APPLY_CRAWL_ATTRIBUTES flags should be emitted. /// </summary> APPLY_OTHER_ATTRIBUTES = 32, /// <summary> /// Optimizes IFilter for indexing because the client calls the /// IFilter::Init method only once and does not call IFilter::BindRegion. /// This eliminates the possibility of accessing a chunk both before and /// after accessing another chunk. /// </summary> INDEXING_ONLY = 64, /// <summary> /// The text extraction process must recursively search all linked /// objects within the document. If a link is unavailable, the /// IFilter::GetChunk call that would have obtained the first chunk of the /// link should return FILTER_E_LINK_UNAVAILABLE. /// </summary> SEARCH_LINKS = 128, /// <summary> /// The content indexing process can return property values set by the filter. /// </summary> FILTER_OWNED_VALUE_OK = 512 } public struct STAT_CHUNK { /// <summary> /// The chunk identifier. Chunk identifiers must be unique for the /// current instance of the IFilter interface. /// Chunk identifiers must be in ascending order. The order in which /// chunks are numbered should correspond to the order in which they appear /// in the source document. Some search engines can take advantage of the /// proximity of chunks of various properties. If so, the order in which /// chunks with different properties are emitted will be important to the /// search engine. /// </summary> public int idChunk; /// <summary> /// The type of break that separates the previous chunk from the current /// chunk. Values are from the CHUNK_BREAKTYPE enumeration. /// </summary> [MarshalAs(UnmanagedType.U4)] public CHUNK_BREAKTYPE breakType; /// <summary> /// Flags indicate whether this chunk contains a text-type or a /// value-type property. /// Flag values are taken from the CHUNKSTATE enumeration. If the CHUNK_TEXT flag is set, /// IFilter::GetText should be used to retrieve the contents of the chunk /// as a series of words. /// If the CHUNK_VALUE flag is set, IFilter::GetValue should be used to retrieve /// the value and treat it as a single property value. If the filter dictates that the same /// content be treated as both text and as a value, the chunk should be emitted twice in two /// different chunks, each with one flag set. /// </summary> [MarshalAs(UnmanagedType.U4)] public CHUNKSTATE flags; /// <summary> /// The language and sublanguage associated with a chunk of text. Chunk locale is used /// by document indexers to perform proper word breaking of text. If the chunk is /// neither text-type nor a value-type with data type VT_LPWSTR, VT_LPSTR or VT_BSTR, /// this field is ignored. /// </summary> public int locale; /// <summary> /// The property to be applied to the chunk. If a filter requires that the same text /// have more than one property, it needs to emit the text once for each property /// in separate chunks. /// </summary> public FULLPROPSPEC attribute; /// <summary> /// The ID of the source of a chunk. The value of the idChunkSource member depends on the nature of the chunk: /// If the chunk is a text-type property, the value of the idChunkSource member must be the same as the value of the idChunk member. /// If the chunk is an public value-type property derived from textual content, the value of the idChunkSource member is the chunk ID for the /// text-type chunk from which it is derived. /// If the filter attributes specify to return only public value-type /// properties, there is no content chunk from which to derive the current /// public value-type property. In this case, the value of the /// idChunkSource member must be set to zero, which is an invalid chunk. /// </summary> public int idChunkSource; /// <summary> /// The offset from which the source text for a derived chunk starts in /// the source chunk. /// </summary> public int cwcStartSource; /// <summary> /// The length in characters of the source text from which the current /// chunk was derived. /// A zero value signifies character-by-character correspondence between /// the source text and /// the derived text. A nonzero value means that no such direct /// correspondence exists /// </summary> public int cwcLenSource; } /// <summary> /// Enumerates the different breaking types that occur between /// chunks of text read out by the FileFilter. /// </summary> public enum CHUNK_BREAKTYPE { /// <summary> /// No break is placed between the current chunk and the previous chunk. /// The chunks are glued together. /// </summary> CHUNK_NO_BREAK = 0, /// <summary> /// A word break is placed between this chunk and the previous chunk that /// had the same attribute. /// Use of CHUNK_EOW should be minimized because the choice of word /// breaks is language-dependent, /// so determining word breaks is best left to the search engine. /// </summary> CHUNK_EOW = 1, /// <summary> /// A sentence break is placed between this chunk and the previous chunk /// that had the same attribute. /// </summary> CHUNK_EOS = 2, /// <summary> /// A paragraph break is placed between this chunk and the previous chunk /// that had the same attribute. /// </summary> CHUNK_EOP = 3, /// <summary> /// A chapter break is placed between this chunk and the previous chunk /// that had the same attribute. /// </summary> CHUNK_EOC = 4 } public enum CHUNKSTATE { /// <summary> /// The current chunk is a text-type property. /// </summary> CHUNK_TEXT = 0x1, /// <summary> /// The current chunk is a value-type property. /// </summary> CHUNK_VALUE = 0x2, /// <summary> /// Reserved /// </summary> CHUNK_FILTER_OWNED_VALUE = 0x4 } public enum IFilterReturnCode : uint { /// <summary> /// Success /// </summary> S_OK = 0, /// <summary> /// The function was denied access to the filter file. /// </summary> E_ACCESSDENIED = 0x80070005, /// <summary> /// The function encountered an invalid handle, /// probably due to a low-memory situation. /// </summary> E_HANDLE = 0x80070006, /// <summary> /// The function received an invalid parameter. /// </summary> E_INVALIDARG = 0x80070057, /// <summary> /// Out of memory /// </summary> E_OUTOFMEMORY = 0x8007000E, /// <summary> /// Not implemented /// </summary> E_NOTIMPL = 0x80004001, /// <summary> /// Unknown error /// </summary> E_FAIL = 0x80000008, /// <summary> /// File not filtered due to password protection /// </summary> FILTER_E_PASSWORD = 0x8004170B, /// <summary> /// The document format is not recognised by the filter /// </summary> FILTER_E_UNKNOWNFORMAT = 0x8004170C, /// <summary> /// No text in current chunk /// </summary> FILTER_E_NO_TEXT = 0x80041705, /// <summary> /// No more chunks of text available in object /// </summary> FILTER_E_END_OF_CHUNKS = 0x80041700, /// <summary> /// No more text available in chunk /// </summary> FILTER_E_NO_MORE_TEXT = 0x80041701, /// <summary> /// No more property values available in chunk /// </summary> FILTER_E_NO_MORE_VALUES = 0x80041702, /// <summary> /// Unable to access object /// </summary> FILTER_E_ACCESS = 0x80041703, /// <summary> /// Moniker doesn't cover entire region /// </summary> FILTER_W_MONIKER_CLIPPED = 0x00041704, /// <summary> /// Unable to bind IFilter for embedded object /// </summary> FILTER_E_EMBEDDING_UNAVAILABLE = 0x80041707, /// <summary> /// Unable to bind IFilter for linked object /// </summary> FILTER_E_LINK_UNAVAILABLE = 0x80041708, /// <summary> /// This is the last text in the current chunk /// </summary> FILTER_S_LAST_TEXT = 0x00041709, /// <summary> /// This is the last value in the current chunk /// </summary> FILTER_S_LAST_VALUES = 0x0004170A } [ComImport, Guid("89BCB740-6119-101A-BCB7-00DD010655AF")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IFilter { /// <summary> /// The IFilter::Init method initializes a filtering session. /// </summary> [PreserveSig] IFilterReturnCode Init( //[in] Flag settings from the IFILTER_INIT enumeration for // controlling text standardization, property output, embedding // scope, and IFilter access patterns. IFILTER_INIT grfFlags, // [in] The size of the attributes array. When nonzero, cAttributes // takes // precedence over attributes specified in grfFlags. If no // attribute flags // are specified and cAttributes is zero, the default is given by // the // PSGUID_STORAGE storage property set, which contains the date and // time // of the last write to the file, size, and so on; and by the // PID_STG_CONTENTS // 'contents' property, which maps to the main contents of the // file. // For more information about properties and property sets, see // Property Sets. int cAttributes, //[in] Array of pointers to FULLPROPSPEC structures for the // requested properties. // When cAttributes is nonzero, only the properties in aAttributes // are returned. IntPtr aAttributes, // [out] Information about additional properties available to the // caller; from the IFILTER_FLAGS enumeration. out IFILTER_FLAGS pdwFlags); /// <summary> /// The IFilter::GetChunk method positions the filter at the beginning /// of the next chunk, /// or at the first chunk if this is the first call to the GetChunk /// method, and returns a description of the current chunk. /// </summary> [PreserveSig] IFilterReturnCode GetChunk(out STAT_CHUNK pStat); /// <summary> /// The IFilter::GetText method retrieves text (text-type properties) /// from the current chunk, /// which must have a CHUNKSTATE enumeration value of CHUNK_TEXT. /// </summary> [PreserveSig] IFilterReturnCode GetText( // [in/out] On entry, the size of awcBuffer array in wide/Unicode // characters. On exit, the number of Unicode characters written to // awcBuffer. // Note that this value is not the number of bytes in the buffer. ref uint pcwcBuffer, // Text retrieved from the current chunk. Do not terminate the // buffer with a character. [Out(), MarshalAs(UnmanagedType.LPArray)] char[] awcBuffer); /// <summary> /// The IFilter::GetValue method retrieves a value (public /// value-type property) from a chunk, /// which must have a CHUNKSTATE enumeration value of CHUNK_VALUE. /// </summary> [PreserveSig] int GetValue( // Allocate the PROPVARIANT structure with CoTaskMemAlloc. Some // PROPVARIANT // structures contain pointers, which can be freed by calling the // PropVariantClear function. // It is up to the caller of the GetValue method to call the // PropVariantClear method. // ref IntPtr ppPropValue // [MarshalAs(UnmanagedType.Struct)] ref IntPtr PropVal); /// <summary> /// The IFilter::BindRegion method retrieves an interface representing /// the specified portion of the object. /// Currently reserved for future use. /// </summary> [PreserveSig] int BindRegion(ref FILTERREGION origPos, ref Guid riid, ref object ppunk); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Security; using System.Threading; using Windows.Foundation; using Windows.UI.Core; using System.Diagnostics.Tracing; namespace System.Threading { #if FEATURE_APPX #region class WinRTSynchronizationContextFactory [FriendAccessAllowed] internal sealed class WinRTSynchronizationContextFactory : WinRTSynchronizationContextFactoryBase { // // It's important that we always return the same SynchronizationContext object for any particular ICoreDispatcher // object, as long as any existing instance is still reachable. This allows reference equality checks against the // SynchronizationContext to determine if two instances represent the same dispatcher. Async frameworks rely on this. // To accomplish this, we use a ConditionalWeakTable to track which instances of WinRTSynchronizationContext are bound // to each ICoreDispatcher instance. // private static readonly ConditionalWeakTable<CoreDispatcher, WinRTSynchronizationContext> s_contextCache = new ConditionalWeakTable<CoreDispatcher, WinRTSynchronizationContext>(); public override SynchronizationContext Create(object dispatcherObj) { Debug.Assert(dispatcherObj != null); // // Get the RCW for the dispatcher // CoreDispatcher dispatcher = (CoreDispatcher)dispatcherObj; // // The dispatcher is supposed to belong to this thread // Debug.Assert(dispatcher == CoreWindow.GetForCurrentThread().Dispatcher); Debug.Assert(dispatcher.HasThreadAccess); // // Get the WinRTSynchronizationContext instance that represents this CoreDispatcher. // return s_contextCache.GetValue(dispatcher, _dispatcher => new WinRTSynchronizationContext(_dispatcher)); } } #endregion class WinRTSynchronizationContextFactory #region class WinRTSynchronizationContext internal sealed class WinRTSynchronizationContext : SynchronizationContext { private readonly CoreDispatcher _dispatcher; internal WinRTSynchronizationContext(CoreDispatcher dispatcher) { _dispatcher = dispatcher; } #region class WinRTSynchronizationContext.Invoker private class Invoker { private readonly ExecutionContext _executionContext; private readonly SendOrPostCallback _callback; private readonly object _state; private static readonly ContextCallback s_contextCallback = new ContextCallback(InvokeInContext); private delegate void DelEtwFireThreadTransferSendObj(object id, int kind, string info, bool multiDequeues); private delegate void DelEtwFireThreadTransferObj(object id, int kind, string info); private static DelEtwFireThreadTransferSendObj s_EtwFireThreadTransferSendObj; private static DelEtwFireThreadTransferObj s_EtwFireThreadTransferReceiveObj; private static DelEtwFireThreadTransferObj s_EtwFireThreadTransferReceiveHandledObj; private static volatile bool s_TriedGetEtwDelegates; public Invoker(SendOrPostCallback callback, object state) { _executionContext = ExecutionContext.FastCapture(); _callback = callback; _state = state; if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) EtwFireThreadTransferSendObj(this); } public void Invoke() { if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) EtwFireThreadTransferReceiveObj(this); if (_executionContext == null) InvokeCore(); else ExecutionContext.Run(_executionContext, s_contextCallback, this, preserveSyncCtx: true); // If there was an ETW event that fired at the top of the winrt event handling loop, ETW listeners could // use it as a marker of completion of the previous request. Since such an event does not exist we need to // fire the "done handling off-thread request" event in order to enable correct work item assignment. if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer)) EtwFireThreadTransferReceiveHandledObj(this); } private static void InvokeInContext(object thisObj) { ((Invoker)thisObj).InvokeCore(); } private void InvokeCore() { try { _callback(_state); } catch (Exception ex) { // // If we let exceptions propagate to CoreDispatcher, it will swallow them with the idea that someone will // observe them later using the IAsyncInfo returned by CoreDispatcher.RunAsync. However, we ignore // that IAsyncInfo, because there's nothing Post can do with it (since Post returns void). // So, to avoid these exceptions being lost forever, we post them to the ThreadPool. // if (!(ex is ThreadAbortException) && !(ex is AppDomainUnloadedException)) { if (!WindowsRuntimeMarshal.ReportUnhandledError(ex)) { var edi = ExceptionDispatchInfo.Capture(ex); ThreadPool.QueueUserWorkItem(o => ((ExceptionDispatchInfo)o).Throw(), edi); } } } } #region ETW Activity-tracing support private static void InitEtwMethods() { Type fest = typeof(FrameworkEventSource); var mi1 = fest.GetMethod("ThreadTransferSendObj", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var mi2 = fest.GetMethod("ThreadTransferReceiveObj", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); var mi3 = fest.GetMethod("ThreadTransferReceiveHandledObj", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (mi1 != null && mi2 != null && mi3 != null) { s_EtwFireThreadTransferSendObj = (DelEtwFireThreadTransferSendObj)mi1.CreateDelegate(typeof(DelEtwFireThreadTransferSendObj), FrameworkEventSource.Log); s_EtwFireThreadTransferReceiveObj = (DelEtwFireThreadTransferObj)mi2.CreateDelegate(typeof(DelEtwFireThreadTransferObj), FrameworkEventSource.Log); s_EtwFireThreadTransferReceiveHandledObj = (DelEtwFireThreadTransferObj)mi3.CreateDelegate(typeof(DelEtwFireThreadTransferObj), FrameworkEventSource.Log); } s_TriedGetEtwDelegates = true; } private static void EtwFireThreadTransferSendObj(object id) { if (!s_TriedGetEtwDelegates) InitEtwMethods(); if (s_EtwFireThreadTransferSendObj != null) s_EtwFireThreadTransferSendObj(id, 3, string.Empty, false); } private static void EtwFireThreadTransferReceiveObj(object id) { if (!s_TriedGetEtwDelegates) InitEtwMethods(); if (s_EtwFireThreadTransferReceiveObj != null) s_EtwFireThreadTransferReceiveObj(id, 3, string.Empty); } private static void EtwFireThreadTransferReceiveHandledObj(object id) { if (!s_TriedGetEtwDelegates) InitEtwMethods(); if (s_EtwFireThreadTransferReceiveHandledObj != null) s_EtwFireThreadTransferReceiveHandledObj(id, 3, string.Empty); } #endregion ETW Activity-tracing support } #endregion class WinRTSynchronizationContext.Invoker [SecuritySafeCritical] public override void Post(SendOrPostCallback d, object state) { if (d == null) throw new ArgumentNullException("d"); Contract.EndContractBlock(); var ignored = _dispatcher.RunAsync(CoreDispatcherPriority.Normal, new Invoker(d, state).Invoke); } [SecuritySafeCritical] public override void Send(SendOrPostCallback d, object state) { throw new NotSupportedException(SR.InvalidOperation_SendNotSupportedOnWindowsRTSynchronizationContext); } public override SynchronizationContext CreateCopy() { return new WinRTSynchronizationContext(_dispatcher); } } #endregion class WinRTSynchronizationContext #endif //FEATURE_APPX } // namespace
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Diagnostics.Contracts; namespace System.Windows.Forms { // Summary: // Specifies the locations of the tabs in a tab control. public enum TabAlignment { // Summary: // The tabs are located across the top of the control. Top = 0, // // Summary: // The tabs are located across the bottom of the control. Bottom = 1, // // Summary: // The tabs are located along the left edge of the control. Left = 2, // // Summary: // The tabs are located along the right edge of the control. Right = 3, } // Summary: // Specifies the appearance of the tabs in a tab control. public enum TabAppearance { // Summary: // The tabs have the standard appearance of tabs. Normal = 0, // // Summary: // The tabs have the appearance of three-dimensional buttons. Buttons = 1, // // Summary: // The tabs have the appearance of flat buttons. FlatButtons = 2, } // Summary: // Specifies whether the tabs in a tab control are owner-drawn (drawn by the // parent window), or drawn by the operating system. public enum TabDrawMode { // Summary: // The tabs are drawn by the operating system, and are of the same size. Normal = 0, // // Summary: // The tabs are drawn by the parent window, and are of the same size. OwnerDrawFixed = 1, } // Summary: // Specifies how tabs in a tab control are sized. public enum TabSizeMode { // Summary: // The width of each tab is sized to accommodate what is displayed on the tab, // and the size of tabs in a row are not adjusted to fill the entire width of // the container control. Normal = 0, // // Summary: // The width of each tab is sized so that each row of tabs fills the entire // width of the container control. This is only applicable to tab controls with // more than one row. FillToRight = 1, // // Summary: // All tabs in a control are the same width. Fixed = 2, } public class TabControl { // Summary: // Initializes a new instance of the System.Windows.Forms.TabControl class. public TabControl() { } // Summary: // Gets or sets the area of the control (for example, along the top) where the // tabs are aligned. // // Returns: // One of the System.Windows.Forms.TabAlignment values. The default is Top. // // Exceptions: // System.ComponentModel.InvalidEnumArgumentException: // The property value is not a valid System.Windows.Forms.TabAlignment value. public TabAlignment Alignment { get { return default(TabAlignment); } set { // } } // // Summary: // Gets or sets the visual appearance of the control's tabs. // // Returns: // One of the System.Windows.Forms.TabAppearance values. The default is Normal. // // Exceptions: // System.ComponentModel.InvalidEnumArgumentException: // The property value is not a valid System.Windows.Forms.TabAppearance value public TabAppearance Appearance { get { return default(TabAppearance); } set { // } } // // Summary: // This member is not meaningful for this control. // // Returns: // Always System.Drawing.SystemColors.Control. // public override System.Drawing.Color BackColor { get; set; } // Summary: // This member is not meaningful for this control. // // Returns: // An System.Drawing.Image. // public override System.Drawing.Image BackgroundImage { get; set; } // Summary: // This member is not meaningful for this control. // // Returns: // An System.Windows.Forms.ImageLayout. //public override ImageLayout BackgroundImageLayout { get; set; } // // Summary: // This member overrides System.Windows.Forms.Control.CreateParams. // // Returns: // A System.Windows.Forms.CreateParams that contains the required creation parameters // when the handle to the control is created. //protected override CreateParams CreateParams { get; } // // // Returns: // The default System.Drawing.Size of the control. //protected override System.Drawing.Size DefaultSize { get; } // // Summary: // Gets the display area of the control's tab pages. // // Returns: // A System.Drawing.Rectangle that represents the display area of the tab pages. //public override System.Drawing.Rectangle DisplayRectangle { get; } // // Summary: // This member is not meaningful for this control. // // Returns: // A System.Boolean value. //protected override bool DoubleBuffered { get; set; } // // Summary: // Gets or sets the way that the control's tabs are drawn. // // Returns: // One of the System.Windows.Forms.TabDrawMode values. The default is Normal. // // Exceptions: // System.ComponentModel.InvalidEnumArgumentException: // The property value is not a valid System.Windows.Forms.TabDrawMode value. public TabDrawMode DrawMode { get { return default(TabDrawMode); } set { // } } // // Summary: // This member is not meaningful for this control. // // Returns: // A System.Drawing.Color. //public override System.Drawing.Color ForeColor { get; set; } // // Summary: // Gets or sets a value indicating whether the control's tabs change in appearance // when the mouse passes over them. // // Returns: // true if the tabs change in appearance when the mouse passes over them; otherwise, // false. The default is false. public bool HotTrack { get { return default(bool); } set { // } } // // Summary: // Gets or sets the images to display on the control's tabs. // // Returns: // An System.Windows.Forms.ImageList that specifies the images to display on // the tabs. public ImageList ImageList { get { return default(ImageList); } set { // } } // // Summary: // Gets or sets the size of the control's tabs. // // Returns: // A System.Drawing.Size that represents the size of the tabs. The default automatically // sizes the tabs to fit the icons and labels on the tabs. // // Exceptions: // System.ArgumentOutOfRangeException: // The width or height of the System.Drawing.Size is less than 0. //public System.Drawing.Size ItemSize //{ // get // { // return default(System.Drawing.Size); // } // set // { // // // } //} // // Summary: // Gets or sets a value indicating whether more than one row of tabs can be // displayed. // // Returns: // true if more than one row of tabs can be displayed; otherwise, false. The // default is false. public bool Multiline { get { return default(bool); } set { // } } // // Summary: // Gets or sets the amount of space around each item on the control's tab pages. // // Returns: // A System.Drawing.Point that specifies the amount of space around each item. // The default is (6,3). // // Exceptions: // System.ArgumentOutOfRangeException: // The width or height of the System.Drawing.Point is less than 0. //public System.Drawing.Point Padding // { // get // { // return default(System.Drawing.Size); // } // set // { // // // } //} // // Summary: // Gets or sets a value indicating whether right-to-left mirror placement is // turned on. // // Returns: // true if right-to-left mirror placement is turned on; false for standard child // control placement. The default is false. //public virtual bool RightToLeftLayout { get; set; } // // Summary: // Gets the number of rows that are currently being displayed in the control's // tab strip. // // Returns: // The number of rows that are currently being displayed in the tab strip. public int RowCount { get { return default(int); } } // // Summary: // Gets or sets the index of the currently selected tab page. // // Returns: // The zero-based index of the currently selected tab page. The default is -1, // which is also the value if no tab page is selected. // // Exceptions: // System.ArgumentOutOfRangeException: // The value is less than -1 public int SelectedIndex { get { return default(int); } set { Contract.Requires(value >= -1); // } } // // Summary: // Gets or sets the currently selected tab page. // // Returns: // A System.Windows.Forms.TabPage that represents the selected tab page. If // no tab page is selected, the value is null. public TabPage SelectedTab { get { return default(TabPage); } set { // } } // // Summary: // Gets or sets a value indicating whether a tab's ToolTip is shown when the // mouse passes over the tab. // // Returns: // true if ToolTips are shown for the tabs that have them; otherwise, false. // The default is false. public bool ShowToolTips { get { return default(bool); } set { // } } // // Summary: // Gets or sets the way that the control's tabs are sized. // // Returns: // One of the System.Windows.Forms.TabSizeMode values. The default is Normal. // // Exceptions: // System.ComponentModel.InvalidEnumArgumentException: // The property value is not a valid System.Windows.Forms.TabSizeMode value. public TabSizeMode SizeMode { get { return default(TabSizeMode); } set { // } } // // Summary: // Gets the number of tabs in the tab strip. // // Returns: // The number of tabs in the tab strip. public int TabCount { get { return default(int); } } // // Summary: // Gets the collection of tab pages in this tab control. // // Returns: // A System.Windows.Forms.TabControl.TabPageCollection that contains the System.Windows.Forms.TabPage // objects in this System.Windows.Forms.TabControl. // public TabControl.TabPageCollection TabPages { get; } // // Summary: // This member is not meaningful for this control. // // Returns: // A System.String. //public override string Text { get; set; } // Summary: // This event is not meaningful for this control. // public event EventHandler BackColorChanged; // Summary: // Occurs when the value of the System.Windows.Forms.TabControl.BackgroundImage // property changes. // public event EventHandler BackgroundImageChanged; // // Summary: // Occurs when the value of the System.Windows.Forms.TabControl.BackgroundImageLayout // property changes. //public event EventHandler BackgroundImageLayoutChanged; // // Summary: // Occurs when a tab is deselected. //public event TabControlEventHandler Deselected; // // Summary: // Occurs before a tab is deselected, enabling a handler to cancel the tab change. //public event TabControlCancelEventHandler Deselecting; // // Summary: // Occurs when the System.Windows.Forms.TabControl needs to paint each of its // tabs if the System.Windows.Forms.TabControl.DrawMode property is set to System.Windows.Forms.TabDrawMode.OwnerDrawFixed. //public event DrawItemEventHandler DrawItem; // // Summary: // Occurs when the value of the System.Windows.Forms.TabControl.ForeColor property // changes. //public event EventHandler ForeColorChanged; // // Summary: // This event is not meaningful for this control. //public event PaintEventHandler Paint; // // Summary: // Occurs when the value of the System.Windows.Forms.TabControl.RightToLeftLayout // property changes. //public event EventHandler RightToLeftLayoutChanged; // // Summary: // Occurs when a tab is selected. //public event TabControlEventHandler Selected; // // Summary: // Occurs when the System.Windows.Forms.TabControl.SelectedIndex property has // changed. //public event EventHandler SelectedIndexChanged; // // Summary: // Occurs before a tab is selected, enabling a handler to cancel the tab change. //public event TabControlCancelEventHandler Selecting; // // Summary: // Occurs when the value of the System.Windows.Forms.TabControl.Text property // changes. //public event EventHandler TextChanged; // Summary: // This member overrides System.Windows.Forms.Control.CreateControlsInstance(). // // Returns: // A new instance of System.Windows.Forms.Control.ControlCollection assigned // to the control. //protected override Control.ControlCollection CreateControlsInstance(); // // Summary: // This member overrides System.Windows.Forms.Control.CreateHandle(). //protected override void CreateHandle(); // // Summary: // Makes the tab following the tab with the specified index the current tab. // // Parameters: // index: // The index in the System.Windows.Forms.TabControl.TabPages collection of the // tab to deselect. // // Exceptions: // System.ArgumentOutOfRangeException: // index is less than 0 or greater than the number of System.Windows.Forms.TabPage // controls in the System.Windows.Forms.TabControl.TabPages collection minus // 1. public void DeselectTab(int index) { Contract.Requires(index >= 0); } // // Summary: // Makes the tab following the tab with the specified name the current tab. // // Parameters: // tabPageName: // The System.Windows.Forms.Control.Name of the tab to deselect. // // Exceptions: // System.ArgumentNullException: // tabPageName is null.-or-tabPageName does not match the System.Windows.Forms.Control.Name // property of any System.Windows.Forms.TabPage in the System.Windows.Forms.TabControl.TabPages // collection. public void DeselectTab(string tabPageName) { Contract.Requires(tabPageName != null); } // Summary: // Makes the tab following the specified System.Windows.Forms.TabPage the current // tab. // // Parameters: // tabPage: // The System.Windows.Forms.TabPage to deselect. // // Exceptions: // System.ArgumentOutOfRangeException: // index is less than 0 or greater than the number of System.Windows.Forms.TabPage // controls in the System.Windows.Forms.TabControl.TabPages collection minus // 1.-or-tabPage is not in the System.Windows.Forms.TabControl.TabPages collection. // // System.ArgumentNullException: // tabPage is null. public void DeselectTab(TabPage tabPage) { Contract.Requires(tabPage != null); } // // // Parameters: // disposing: // true to release both managed and unmanaged resources; false to release only // unmanaged resources. //protected override void Dispose(bool disposing); // // Summary: // Gets the System.Windows.Forms.TabPage control at the specified location. // // Parameters: // index: // The index of the System.Windows.Forms.TabPage to get. // // Returns: // The System.Windows.Forms.TabPage at the specified location. // // Exceptions: // System.ArgumentOutOfRangeException: // index is less than 0 or greater than the System.Windows.Forms.TabControl.TabCount. public Control GetControl(int index) { Contract.Requires(index >= 0); return default(Control); } // // Summary: // Gets an array of System.Windows.Forms.TabPage controls that belong to the // System.Windows.Forms.TabControl control. // // Returns: // An array of System.Windows.Forms.TabPage controls that belong to the System.Windows.Forms.TabControl. //protected virtual object[] GetItems(); // // Summary: // Copies the System.Windows.Forms.TabPage controls in the System.Windows.Forms.TabControl // to an array of the specified type. // // Parameters: // baseType: // The System.Type of the array to create. // // Returns: // The System.Windows.Forms.TabPage controls that belong to the System.Windows.Forms.TabControl // as an array of the specified type. // // Exceptions: // System.ArrayTypeMismatchException: // The type System.Windows.Forms.TabPage cannot be converted to baseType. //protected virtual object[] GetItems(Type baseType); // // Summary: // Returns the bounding rectangle for a specified tab in this tab control. // // Parameters: // index: // The zero-based index of the tab you want. // // Returns: // A System.Drawing.Rectangle that represents the bounds of the specified tab. // // Exceptions: // System.ArgumentOutOfRangeException: // The index is less than zero.-or- The index is greater than or equal to System.Windows.Forms.TabControl.TabPageCollection.Count. //public System.Drawing.Rectangle GetTabRect(int index); // // Summary: // Makes the tab with the specified index the current tab. // // Parameters: // index: // The index in the System.Windows.Forms.TabControl.TabPages collection of the // tab to select. // // Exceptions: // System.ArgumentOutOfRangeException: // index is less than 0 or greater than the number of System.Windows.Forms.TabPage // controls in the System.Windows.Forms.TabControl.TabPages collection minus // 1. public void SelectTab(int index) { Contract.Requires(index >= 0); } // Summary: // Makes the tab with the specified name the current tab. // // Parameters: // tabPageName: // The System.Windows.Forms.Control.Name of the tab to select. // // Exceptions: // System.ArgumentNullException: // tabPageName is null.-or-tabPageName does not match the System.Windows.Forms.Control.Name // property of any System.Windows.Forms.TabPage in the System.Windows.Forms.TabControl.TabPages // collection. public void SelectTab(string tabPageName) { Contract.Requires(tabPageName != null); } // // Summary: // Makes the specified System.Windows.Forms.TabPage the current tab. // // Parameters: // tabPage: // The System.Windows.Forms.TabPage to select. // // Exceptions: // System.ArgumentOutOfRangeException: // index is less than 0 or greater than the number of System.Windows.Forms.TabPage // controls in the System.Windows.Forms.TabControl.TabPages collection minus // 1.-or-tabPage is not in the System.Windows.Forms.TabControl.TabPages collection. // // System.ArgumentNullException: // tabPage is null. public void SelectTab(TabPage tabPage) { Contract.Requires(tabPage != null); } // // Summary: // Returns a string that represents the System.Windows.Forms.TabControl control. // // Returns: // A string that represents the current System.Windows.Forms.TabControl. //public override string ToString(); public TabPageCollection TabPages { get { // To add: \forall c in result. c != null Contract.Ensures(Contract.Result<TabPageCollection>() != null); return default(TabPageCollection); } } public class TabPageCollection { } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/api/system_parameter.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Api { /// <summary>Holder for reflection information generated from google/api/system_parameter.proto</summary> public static partial class SystemParameterReflection { #region Descriptor /// <summary>File descriptor for google/api/system_parameter.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static SystemParameterReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiFnb29nbGUvYXBpL3N5c3RlbV9wYXJhbWV0ZXIucHJvdG8SCmdvb2dsZS5h", "cGkiQgoQU3lzdGVtUGFyYW1ldGVycxIuCgVydWxlcxgBIAMoCzIfLmdvb2ds", "ZS5hcGkuU3lzdGVtUGFyYW1ldGVyUnVsZSJYChNTeXN0ZW1QYXJhbWV0ZXJS", "dWxlEhAKCHNlbGVjdG9yGAEgASgJEi8KCnBhcmFtZXRlcnMYAiADKAsyGy5n", "b29nbGUuYXBpLlN5c3RlbVBhcmFtZXRlciJRCg9TeXN0ZW1QYXJhbWV0ZXIS", "DAoEbmFtZRgBIAEoCRITCgtodHRwX2hlYWRlchgCIAEoCRIbChN1cmxfcXVl", "cnlfcGFyYW1ldGVyGAMgASgJQnYKDmNvbS5nb29nbGUuYXBpQhRTeXN0ZW1Q", "YXJhbWV0ZXJQcm90b1ABWkVnb29nbGUuZ29sYW5nLm9yZy9nZW5wcm90by9n", "b29nbGVhcGlzL2FwaS9zZXJ2aWNlY29uZmlnO3NlcnZpY2Vjb25maWeiAgRH", "QVBJYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.SystemParameters), global::Google.Api.SystemParameters.Parser, new[]{ "Rules" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.SystemParameterRule), global::Google.Api.SystemParameterRule.Parser, new[]{ "Selector", "Parameters" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Api.SystemParameter), global::Google.Api.SystemParameter.Parser, new[]{ "Name", "HttpHeader", "UrlQueryParameter" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// ### System parameter configuration /// /// A system parameter is a special kind of parameter defined by the API /// system, not by an individual API. It is typically mapped to an HTTP header /// and/or a URL query parameter. This configuration specifies which methods /// change the names of the system parameters. /// </summary> public sealed partial class SystemParameters : pb::IMessage<SystemParameters> { private static readonly pb::MessageParser<SystemParameters> _parser = new pb::MessageParser<SystemParameters>(() => new SystemParameters()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SystemParameters> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.SystemParameterReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SystemParameters() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SystemParameters(SystemParameters other) : this() { rules_ = other.rules_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SystemParameters Clone() { return new SystemParameters(this); } /// <summary>Field number for the "rules" field.</summary> public const int RulesFieldNumber = 1; private static readonly pb::FieldCodec<global::Google.Api.SystemParameterRule> _repeated_rules_codec = pb::FieldCodec.ForMessage(10, global::Google.Api.SystemParameterRule.Parser); private readonly pbc::RepeatedField<global::Google.Api.SystemParameterRule> rules_ = new pbc::RepeatedField<global::Google.Api.SystemParameterRule>(); /// <summary> /// Define system parameters. /// /// The parameters defined here will override the default parameters /// implemented by the system. If this field is missing from the service /// config, default system parameters will be used. Default system parameters /// and names is implementation-dependent. /// /// Example: define api key for all methods /// /// system_parameters /// rules: /// - selector: "*" /// parameters: /// - name: api_key /// url_query_parameter: api_key /// /// Example: define 2 api key names for a specific method. /// /// system_parameters /// rules: /// - selector: "/ListShelves" /// parameters: /// - name: api_key /// http_header: Api-Key1 /// - name: api_key /// http_header: Api-Key2 /// /// **NOTE:** All service configuration rules follow "last one wins" order. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.SystemParameterRule> Rules { get { return rules_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SystemParameters); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SystemParameters other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!rules_.Equals(other.rules_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= rules_.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) { rules_.WriteTo(output, _repeated_rules_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += rules_.CalculateSize(_repeated_rules_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SystemParameters other) { if (other == null) { return; } rules_.Add(other.rules_); } [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: { rules_.AddEntriesFrom(input, _repeated_rules_codec); break; } } } } } /// <summary> /// Define a system parameter rule mapping system parameter definitions to /// methods. /// </summary> public sealed partial class SystemParameterRule : pb::IMessage<SystemParameterRule> { private static readonly pb::MessageParser<SystemParameterRule> _parser = new pb::MessageParser<SystemParameterRule>(() => new SystemParameterRule()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SystemParameterRule> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.SystemParameterReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SystemParameterRule() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SystemParameterRule(SystemParameterRule other) : this() { selector_ = other.selector_; parameters_ = other.parameters_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SystemParameterRule Clone() { return new SystemParameterRule(this); } /// <summary>Field number for the "selector" field.</summary> public const int SelectorFieldNumber = 1; private string selector_ = ""; /// <summary> /// Selects the methods to which this rule applies. Use '*' to indicate all /// methods in all APIs. /// /// Refer to [selector][google.api.DocumentationRule.selector] for syntax details. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Selector { get { return selector_; } set { selector_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "parameters" field.</summary> public const int ParametersFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Api.SystemParameter> _repeated_parameters_codec = pb::FieldCodec.ForMessage(18, global::Google.Api.SystemParameter.Parser); private readonly pbc::RepeatedField<global::Google.Api.SystemParameter> parameters_ = new pbc::RepeatedField<global::Google.Api.SystemParameter>(); /// <summary> /// Define parameters. Multiple names may be defined for a parameter. /// For a given method call, only one of them should be used. If multiple /// names are used the behavior is implementation-dependent. /// If none of the specified names are present the behavior is /// parameter-dependent. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::Google.Api.SystemParameter> Parameters { get { return parameters_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SystemParameterRule); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SystemParameterRule other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Selector != other.Selector) return false; if(!parameters_.Equals(other.parameters_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Selector.Length != 0) hash ^= Selector.GetHashCode(); hash ^= parameters_.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 (Selector.Length != 0) { output.WriteRawTag(10); output.WriteString(Selector); } parameters_.WriteTo(output, _repeated_parameters_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Selector.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Selector); } size += parameters_.CalculateSize(_repeated_parameters_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SystemParameterRule other) { if (other == null) { return; } if (other.Selector.Length != 0) { Selector = other.Selector; } parameters_.Add(other.parameters_); } [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: { Selector = input.ReadString(); break; } case 18: { parameters_.AddEntriesFrom(input, _repeated_parameters_codec); break; } } } } } /// <summary> /// Define a parameter's name and location. The parameter may be passed as either /// an HTTP header or a URL query parameter, and if both are passed the behavior /// is implementation-dependent. /// </summary> public sealed partial class SystemParameter : pb::IMessage<SystemParameter> { private static readonly pb::MessageParser<SystemParameter> _parser = new pb::MessageParser<SystemParameter>(() => new SystemParameter()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<SystemParameter> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Api.SystemParameterReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SystemParameter() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SystemParameter(SystemParameter other) : this() { name_ = other.name_; httpHeader_ = other.httpHeader_; urlQueryParameter_ = other.urlQueryParameter_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public SystemParameter Clone() { return new SystemParameter(this); } /// <summary>Field number for the "name" field.</summary> public const int NameFieldNumber = 1; private string name_ = ""; /// <summary> /// Define the name of the parameter, such as "api_key" . It is case sensitive. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Name { get { return name_; } set { name_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "http_header" field.</summary> public const int HttpHeaderFieldNumber = 2; private string httpHeader_ = ""; /// <summary> /// Define the HTTP header name to use for the parameter. It is case /// insensitive. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string HttpHeader { get { return httpHeader_; } set { httpHeader_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "url_query_parameter" field.</summary> public const int UrlQueryParameterFieldNumber = 3; private string urlQueryParameter_ = ""; /// <summary> /// Define the URL query parameter name to use for the parameter. It is case /// sensitive. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string UrlQueryParameter { get { return urlQueryParameter_; } set { urlQueryParameter_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as SystemParameter); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(SystemParameter other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (HttpHeader != other.HttpHeader) return false; if (UrlQueryParameter != other.UrlQueryParameter) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (HttpHeader.Length != 0) hash ^= HttpHeader.GetHashCode(); if (UrlQueryParameter.Length != 0) hash ^= UrlQueryParameter.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (HttpHeader.Length != 0) { output.WriteRawTag(18); output.WriteString(HttpHeader); } if (UrlQueryParameter.Length != 0) { output.WriteRawTag(26); output.WriteString(UrlQueryParameter); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (HttpHeader.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(HttpHeader); } if (UrlQueryParameter.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(UrlQueryParameter); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SystemParameter other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.HttpHeader.Length != 0) { HttpHeader = other.HttpHeader; } if (other.UrlQueryParameter.Length != 0) { UrlQueryParameter = other.UrlQueryParameter; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { HttpHeader = input.ReadString(); break; } case 26: { UrlQueryParameter = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
namespace android.view { [global::MonoJavaBridge.JavaClass()] public partial class KeyCharacterMap : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static KeyCharacterMap() { InitJNI(); } protected KeyCharacterMap(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class KeyData : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static KeyData() { InitJNI(); } protected KeyData(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _KeyData8766; public KeyData() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.KeyCharacterMap.KeyData.staticClass, global::android.view.KeyCharacterMap.KeyData._KeyData8766); Init(@__env, handle); } public static int META_LENGTH { get { return 4; } } internal static global::MonoJavaBridge.FieldId _displayLabel8767; public char displayLabel { get { return default(char); } set { } } internal static global::MonoJavaBridge.FieldId _number8768; public char number { get { return default(char); } set { } } internal static global::MonoJavaBridge.FieldId _meta8769; public char[] meta { get { return default(char[]); } set { } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.KeyCharacterMap.KeyData.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/KeyCharacterMap$KeyData")); global::android.view.KeyCharacterMap.KeyData._KeyData8766 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.KeyData.staticClass, "<init>", "()V"); } } internal static global::MonoJavaBridge.MethodId _finalize8770; protected override void finalize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.view.KeyCharacterMap._finalize8770); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._finalize8770); } internal static global::MonoJavaBridge.MethodId _get8771; public virtual int get(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.view.KeyCharacterMap._get8771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._get8771, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _load8772; public static global::android.view.KeyCharacterMap load(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._load8772, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.KeyCharacterMap; } internal static global::MonoJavaBridge.MethodId _getNumber8773; public virtual char getNumber(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallCharMethod(this.JvmHandle, global::android.view.KeyCharacterMap._getNumber8773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._getNumber8773, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDeadChar8774; public static int getDeadChar(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticIntMethod(android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._getDeadChar8774, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getDisplayLabel8775; public virtual char getDisplayLabel(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallCharMethod(this.JvmHandle, global::android.view.KeyCharacterMap._getDisplayLabel8775, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._getDisplayLabel8775, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getKeyData8776; public virtual bool getKeyData(int arg0, android.view.KeyCharacterMap.KeyData arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.KeyCharacterMap._getKeyData8776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._getKeyData8776, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getMatch8777; public virtual char getMatch(int arg0, char[] arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallCharMethod(this.JvmHandle, global::android.view.KeyCharacterMap._getMatch8777, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._getMatch8777, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getMatch8778; public virtual char getMatch(int arg0, char[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallCharMethod(this.JvmHandle, global::android.view.KeyCharacterMap._getMatch8778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualCharMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._getMatch8778, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isPrintingKey8779; public virtual bool isPrintingKey(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.KeyCharacterMap._isPrintingKey8779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._isPrintingKey8779, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getEvents8780; public virtual global::android.view.KeyEvent[] getEvents(char[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.view.KeyEvent>(@__env.CallObjectMethod(this.JvmHandle, global::android.view.KeyCharacterMap._getEvents8780, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.KeyEvent[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<android.view.KeyEvent>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._getEvents8780, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.view.KeyEvent[]; } internal static global::MonoJavaBridge.MethodId _getKeyboardType8781; public virtual int getKeyboardType() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.view.KeyCharacterMap._getKeyboardType8781); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._getKeyboardType8781); } internal static global::MonoJavaBridge.MethodId _deviceHasKey8782; public static bool deviceHasKey(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.CallStaticBooleanMethod(android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._deviceHasKey8782, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _deviceHasKeys8783; public static bool[] deviceHasKeys(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<bool>(@__env.CallStaticObjectMethod(android.view.KeyCharacterMap.staticClass, global::android.view.KeyCharacterMap._deviceHasKeys8783, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as bool[]; } public static int BUILT_IN_KEYBOARD { get { return 0; } } public static int NUMERIC { get { return 1; } } public static int PREDICTIVE { get { return 2; } } public static int ALPHA { get { return 3; } } public static char HEX_INPUT { get { return '0'; } } public static char PICKER_DIALOG_INPUT { get { return '0'; } } public static int COMBINING_ACCENT { get { return -2147483648; } } public static int COMBINING_ACCENT_MASK { get { return 2147483647; } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.view.KeyCharacterMap.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/KeyCharacterMap")); global::android.view.KeyCharacterMap._finalize8770 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "finalize", "()V"); global::android.view.KeyCharacterMap._get8771 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "get", "(II)I"); global::android.view.KeyCharacterMap._load8772 = @__env.GetStaticMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "load", "(I)Landroid/view/KeyCharacterMap;"); global::android.view.KeyCharacterMap._getNumber8773 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "getNumber", "(I)C"); global::android.view.KeyCharacterMap._getDeadChar8774 = @__env.GetStaticMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "getDeadChar", "(II)I"); global::android.view.KeyCharacterMap._getDisplayLabel8775 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "getDisplayLabel", "(I)C"); global::android.view.KeyCharacterMap._getKeyData8776 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "getKeyData", "(ILandroid/view/KeyCharacterMap$KeyData;)Z"); global::android.view.KeyCharacterMap._getMatch8777 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "getMatch", "(I[CI)C"); global::android.view.KeyCharacterMap._getMatch8778 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "getMatch", "(I[C)C"); global::android.view.KeyCharacterMap._isPrintingKey8779 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "isPrintingKey", "(I)Z"); global::android.view.KeyCharacterMap._getEvents8780 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "getEvents", "([C)[Landroid/view/KeyEvent;"); global::android.view.KeyCharacterMap._getKeyboardType8781 = @__env.GetMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "getKeyboardType", "()I"); global::android.view.KeyCharacterMap._deviceHasKey8782 = @__env.GetStaticMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "deviceHasKey", "(I)Z"); global::android.view.KeyCharacterMap._deviceHasKeys8783 = @__env.GetStaticMethodIDNoThrow(global::android.view.KeyCharacterMap.staticClass, "deviceHasKeys", "([I)[Z"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; using System.Diagnostics; namespace System.Collections.Immutable.Tests { public abstract class ImmutableListTestBase : SimpleElementImmutablesTestBase { protected static readonly Func<IList, object, object> IndexOfFunc = (l, v) => l.IndexOf(v); protected static readonly Func<IList, object, object> ContainsFunc = (l, v) => l.Contains(v); protected static readonly Func<IList, object, object> RemoveFunc = (l, v) => { l.Remove(v); return l.Count; }; internal abstract IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list); [Fact] public void CopyToEmptyTest() { var array = new int[0]; this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array, 0); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(0, array, 0, 0); ((ICollection)this.GetListQuery(ImmutableList<int>.Empty)).CopyTo(array, 0); } [Fact] public void CopyToTest() { var listQuery = this.GetListQuery(ImmutableList.Create(1, 2)); var list = (IEnumerable<int>)listQuery; var array = new int[2]; listQuery.CopyTo(array); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(array, 0); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(0, array, 0, listQuery.Count); Assert.Equal(list, array); array = new int[1]; // shorter than source length listQuery.CopyTo(0, array, 0, array.Length); Assert.Equal(list.Take(array.Length), array); array = new int[3]; listQuery.CopyTo(1, array, 2, 1); Assert.Equal(new[] { 0, 0, 2 }, array); array = new int[2]; ((ICollection)listQuery).CopyTo(array, 0); Assert.Equal(list, array); } [Fact] public void ForEachTest() { this.GetListQuery(ImmutableList<int>.Empty).ForEach(n => { throw new ShouldNotBeInvokedException(); }); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 3)); var hitTest = new bool[list.Max() + 1]; this.GetListQuery(list).ForEach(i => { Assert.False(hitTest[i]); hitTest[i] = true; }); for (int i = 0; i < hitTest.Length; i++) { Assert.Equal(list.Contains(i), hitTest[i]); Assert.Equal(((IList)list).Contains(i), hitTest[i]); } } [Fact] public void ExistsTest() { Assert.False(this.GetListQuery(ImmutableList<int>.Empty).Exists(n => true)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 5)); Assert.True(this.GetListQuery(list).Exists(n => n == 3)); Assert.False(this.GetListQuery(list).Exists(n => n == 8)); } [Fact] public void FindAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).FindAll(n => true).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); var actual = this.GetListQuery(list).FindAll(n => n % 2 == 1); var expected = list.ToList().FindAll(n => n % 2 == 1); Assert.Equal<int>(expected, actual.ToList()); } [Fact] public void FindTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).Find(n => true)); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(3, this.GetListQuery(list).Find(n => (n % 2) == 1)); } [Fact] public void FindLastTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).FindLast(n => { throw new ShouldNotBeInvokedException(); })); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(5, this.GetListQuery(list).FindLast(n => (n % 2) == 1)); } [Fact] public void FindIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= list.Count - idx; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == 0) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } [Fact] public void FindLastIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindLastIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= idx + 1; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindLastIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindLastIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == list.Count - 1) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } [Fact] public void IList_IndexOf_NullArgument() { this.AssertIListBaseline(IndexOfFunc, 1, null); this.AssertIListBaseline(IndexOfFunc, "item", null); this.AssertIListBaseline(IndexOfFunc, new int?(1), null); this.AssertIListBaseline(IndexOfFunc, new int?(), null); } [Fact] public void IList_IndexOf_ArgTypeMismatch() { this.AssertIListBaseline(IndexOfFunc, "first item", new object()); this.AssertIListBaseline(IndexOfFunc, 1, 1.0); this.AssertIListBaseline(IndexOfFunc, new int?(1), 1); this.AssertIListBaseline(IndexOfFunc, new int?(1), new int?(1)); this.AssertIListBaseline(IndexOfFunc, new int?(1), string.Empty); } [Fact] public void IList_IndexOf_EqualsOverride() { this.AssertIListBaseline(IndexOfFunc, new ProgrammaticEquals(v => v is string), "foo"); this.AssertIListBaseline(IndexOfFunc, new ProgrammaticEquals(v => v is string), 3); } [Fact] public void IList_Contains_NullArgument() { this.AssertIListBaseline(ContainsFunc, 1, null); this.AssertIListBaseline(ContainsFunc, "item", null); this.AssertIListBaseline(ContainsFunc, new int?(1), null); this.AssertIListBaseline(ContainsFunc, new int?(), null); } [Fact] public void IList_Contains_ArgTypeMismatch() { this.AssertIListBaseline(ContainsFunc, "first item", new object()); this.AssertIListBaseline(ContainsFunc, 1, 1.0); this.AssertIListBaseline(ContainsFunc, new int?(1), 1); this.AssertIListBaseline(ContainsFunc, new int?(1), new int?(1)); this.AssertIListBaseline(ContainsFunc, new int?(1), string.Empty); } [Fact] public void IList_Contains_EqualsOverride() { this.AssertIListBaseline(ContainsFunc, new ProgrammaticEquals(v => v is string), "foo"); this.AssertIListBaseline(ContainsFunc, new ProgrammaticEquals(v => v is string), 3); } [Fact] public void ConvertAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).ConvertAll<float>(n => n).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); Func<int, double> converter = n => 2.0 * n; var expected = list.ToList().Select(converter).ToList(); var actual = this.GetListQuery(list).ConvertAll(converter); Assert.Equal<double>(expected.ToList(), actual.ToList()); } [Fact] public void GetRangeTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).GetRange(0, 0).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); var bclList = list.ToList(); for (int index = 0; index < list.Count; index++) { for (int count = 0; count < list.Count - index; count++) { var expected = bclList.GetRange(index, count); var actual = this.GetListQuery(list).GetRange(index, count); Assert.Equal<int>(expected.ToList(), actual.ToList()); } } } [Fact] public void TrueForAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).TrueForAll(n => false)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.TrueForAllTestHelper(list, n => n % 2 == 0); this.TrueForAllTestHelper(list, n => n % 2 == 1); this.TrueForAllTestHelper(list, n => true); } [Fact] public void RemoveAllTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.RemoveAllTestHelper(list, n => false); this.RemoveAllTestHelper(list, n => true); this.RemoveAllTestHelper(list, n => n < 7); this.RemoveAllTestHelper(list, n => n > 7); this.RemoveAllTestHelper(list, n => n == 7); } [Fact] public void ReverseTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list.Count - i; j++) { this.ReverseTestHelper(list, i, j); } } } [Fact] public void Sort_NullComparison_Throws() { AssertExtensions.Throws<ArgumentNullException>("comparison", () => this.SortTestHelper(ImmutableList<int>.Empty, (Comparison<int>)null)); } [Fact] public void SortTest() { var scenarios = new[] { ImmutableList<int>.Empty, ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50)), ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50).Reverse()), }; foreach (var scenario in scenarios) { var expected = scenario.ToList(); expected.Sort(); var actual = this.SortTestHelper(scenario); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); Comparison<int> comparison = (x, y) => x > y ? 1 : (x < y ? -1 : 0); expected.Sort(comparison); actual = this.SortTestHelper(scenario, comparison); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); IComparer<int> comparer = null; expected.Sort(comparer); actual = this.SortTestHelper(scenario, comparer); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); comparer = Comparer<int>.Create(comparison); expected.Sort(comparer); actual = this.SortTestHelper(scenario, comparer); Assert.Equal<int>(expected, actual); for (int i = 0; i < scenario.Count; i++) { for (int j = 0; j < scenario.Count - i; j++) { expected = scenario.ToList(); comparer = null; expected.Sort(i, j, comparer); actual = this.SortTestHelper(scenario, i, j, comparer); Assert.Equal<int>(expected, actual); } } } } [Fact] public void BinarySearch() { var basis = new List<int>(Enumerable.Range(1, 50).Select(n => n * 2)); var query = this.GetListQuery(basis.ToImmutableList()); for (int value = basis.First() - 1; value <= basis.Last() + 1; value++) { int expected = basis.BinarySearch(value); int actual = query.BinarySearch(value); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); for (int index = 0; index < basis.Count - 1; index++) { for (int count = 0; count <= basis.Count - index; count++) { expected = basis.BinarySearch(index, count, value, null); actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void BinarySearchPartialSortedList() { var reverseSorted = ImmutableArray.CreateRange(Enumerable.Range(1, 150).Select(n => n * 2).Reverse()); this.BinarySearchPartialSortedListHelper(reverseSorted, 0, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 50, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 100, 50); } private void BinarySearchPartialSortedListHelper(ImmutableArray<int> inputData, int sortedIndex, int sortedLength) { Requires.Range(sortedIndex >= 0, nameof(sortedIndex)); Requires.Range(sortedLength > 0, nameof(sortedLength)); inputData = inputData.Sort(sortedIndex, sortedLength, Comparer<int>.Default); int min = inputData[sortedIndex]; int max = inputData[sortedIndex + sortedLength - 1]; var basis = new List<int>(inputData); var query = this.GetListQuery(inputData.ToImmutableList()); for (int value = min - 1; value <= max + 1; value++) { for (int index = sortedIndex; index < sortedIndex + sortedLength; index++) // make sure the index we pass in is always within the sorted range in the list. { for (int count = 0; count <= sortedLength - index; count++) { int expected = basis.BinarySearch(index, count, value, null); int actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void SyncRoot() { var collection = (ICollection)this.GetEnumerableOf<int>(); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } [Fact] public void GetEnumeratorTest() { var enumerable = this.GetEnumerableOf(1); Assert.Equal(new[] { 1 }, enumerable.ToList()); // exercises the enumerator IEnumerable enumerableNonGeneric = enumerable; Assert.Equal(new[] { 1 }, enumerableNonGeneric.Cast<int>().ToList()); // exercises the enumerator } protected abstract void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test); protected abstract void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer); protected void AssertIListBaselineBothDirections<T1, T2>(Func<IList, object, object> operation, T1 item, T2 other) { this.AssertIListBaseline(operation, item, other); this.AssertIListBaseline(operation, other, item); } /// <summary> /// Asserts that the <see cref="ImmutableList{T}"/> or <see cref="ImmutableList{T}.Builder"/>'s /// implementation of <see cref="IList"/> behave the same way <see cref="List{T}"/> does. /// </summary> /// <typeparam name="T">The type of the element for one collection to test with.</typeparam> /// <param name="operation"> /// The <see cref="IList"/> operation to perform. /// The function is provided with the <see cref="IList"/> implementation to test /// and the item to use as the argument to the operation. /// The function should return some equatable value by which to compare the effects /// of the operation across <see cref="IList"/> implementations. /// </param> /// <param name="item">The item to add to the collection.</param> /// <param name="other">The item to pass to the <paramref name="operation"/> function as the second parameter.</param> protected void AssertIListBaseline<T>(Func<IList, object, object> operation, T item, object other) { IList bclList = new List<T> { item }; IList testedList = (IList)this.GetListQuery(ImmutableList.Create(item)); object expected = operation(bclList, other); object actual = operation(testedList, other); Assert.Equal(expected, actual); } private void TrueForAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test) { var bclList = list.ToList(); var expected = bclList.TrueForAll(test); var actual = this.GetListQuery(list).TrueForAll(test); Assert.Equal(expected, actual); } protected class ProgrammaticEquals { private readonly Func<object, bool> equalsCallback; internal ProgrammaticEquals(Func<object, bool> equalsCallback) { this.equalsCallback = equalsCallback; } public override bool Equals(object obj) { return this.equalsCallback(obj); } public override int GetHashCode() { throw new NotImplementedException(); } } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: SQLiteErrorLog.cs 924 2011-12-23 22:41:47Z azizatif $")] namespace Elmah { #region Imports using System; using System.Collections.Generic; using System.Data; using System.Data.SQLite; using System.Globalization; using System.IO; using IDictionary = System.Collections.IDictionary; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses SQLite as its backing store. /// </summary> public class SQLiteErrorLog : ErrorLog { private readonly string _connectionString; /// <summary> /// Initializes a new instance of the <see cref="SQLiteErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public SQLiteErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); var connectionString = ConnectionStringHelper.GetConnectionString(config, true); // // If there is no connection string to use then throw an // exception to abort construction. // if (connectionString.Length == 0) throw new ApplicationException("Connection string is missing for the SQLite error log."); _connectionString = connectionString; InitializeDatabase(); ApplicationName = config.Find("applicationName", string.Empty); } /// <summary> /// Initializes a new instance of the <see cref="SQLiteErrorLog"/> class /// to use a specific connection string for connecting to the database. /// </summary> public SQLiteErrorLog(string connectionString) { if (connectionString == null) throw new ArgumentNullException("connectionString"); if (connectionString.Length == 0) throw new ArgumentException(null, "connectionString"); _connectionString = ConnectionStringHelper.GetResolvedConnectionString(connectionString); InitializeDatabase(); } private static readonly object _lock = new object(); private void InitializeDatabase() { var connectionString = ConnectionString; Debug.AssertStringNotEmpty(connectionString); var dbFilePath = ConnectionStringHelper.GetDataSourceFilePath(connectionString); if (File.Exists(dbFilePath)) return; // // Make sure that we don't have multiple threads all trying to create the database // lock (_lock) { // // Just double check that no other thread has created the database while // we were waiting for the lock // if (File.Exists(dbFilePath)) return; SQLiteConnection.CreateFile(dbFilePath); const string sql = @" CREATE TABLE Error ( ErrorId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Application TEXT NOT NULL, Host TEXT NOT NULL, Type TEXT NOT NULL, Source TEXT NOT NULL, Message TEXT NOT NULL, User TEXT NOT NULL, StatusCode INTEGER NOT NULL, TimeUtc TEXT NOT NULL, AllXml TEXT NOT NULL )"; using (var connection = new SQLiteConnection(connectionString)) using (var command = new SQLiteCommand(sql, connection)) { connection.Open(); command.ExecuteNonQuery(); } } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "SQLite Error Log"; } } /// <summary> /// Gets the connection string used by the log to connect to the database. /// </summary> public virtual string ConnectionString { get { return _connectionString; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Use the stored procedure called by this implementation to set a /// policy on how long errors are kept in the log. The default /// implementation stores all errors for an indefinite time. /// </remarks> public override string Log(Error error) { if (error == null) throw new ArgumentNullException("error"); var errorXml = ErrorXml.EncodeString(error); const string query = @" INSERT INTO Error ( Application, Host, Type, Source, Message, User, StatusCode, TimeUtc, AllXml) VALUES ( @Application, @Host, @Type, @Source, @Message, @User, @StatusCode, @TimeUtc, @AllXml); SELECT last_insert_rowid();"; using (var connection = new SQLiteConnection(ConnectionString)) using (var command = new SQLiteCommand(query, connection)) { var parameters = command.Parameters; parameters.Add("@Application", DbType.String, 60).Value = ApplicationName; parameters.Add("@Host", DbType.String, 30).Value = error.HostName; parameters.Add("@Type", DbType.String, 100).Value = error.Type; parameters.Add("@Source", DbType.String, 60).Value = error.Source; parameters.Add("@Message", DbType.String, 500).Value = error.Message; parameters.Add("@User", DbType.String, 50).Value = error.User; parameters.Add("@StatusCode", DbType.Int64).Value = error.StatusCode; parameters.Add("@TimeUtc", DbType.DateTime).Value = error.Time.ToUniversalTime(); parameters.Add("@AllXml", DbType.String).Value = errorXml; connection.Open(); return Convert.ToInt64(command.ExecuteScalar()).ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Returns a page of errors from the databse in descending order /// of logged time. /// </summary> public override int GetErrors(int pageIndex, int pageSize, ICollection<ErrorLogEntry> errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); const string sql = @" SELECT ErrorId, Application, Host, Type, Source, Message, User, StatusCode, TimeUtc FROM Error ORDER BY ErrorId DESC LIMIT @PageIndex * @PageSize, @PageSize; SELECT COUNT(*) FROM Error"; using (var connection = new SQLiteConnection(ConnectionString)) using (var command = new SQLiteCommand(sql, connection)) { var parameters = command.Parameters; parameters.Add("@PageIndex", DbType.Int16).Value = pageIndex; parameters.Add("@PageSize", DbType.Int16).Value = pageSize; connection.Open(); using (var reader = command.ExecuteReader()) { if (errorEntryList != null) { while (reader.Read()) { var id = Convert.ToString(reader["ErrorId"], CultureInfo.InvariantCulture); var error = new Error { ApplicationName = reader["Application"].ToString(), HostName = reader["Host"].ToString(), Type = reader["Type"].ToString(), Source = reader["Source"].ToString(), Message = reader["Message"].ToString(), User = reader["User"].ToString(), StatusCode = Convert.ToInt32(reader["StatusCode"]), Time = Convert.ToDateTime(reader["TimeUtc"]).ToLocalTime() }; errorEntryList.Add(new ErrorLogEntry(this, id, error)); } } // // Get the result of SELECT COUNT(*) FROM Page // reader.NextResult(); reader.Read(); return reader.GetInt32(0); } } } /// <summary> /// Returns the specified error from the database, or null /// if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { if (id == null) throw new ArgumentNullException("id"); if (id.Length == 0) throw new ArgumentException(null, "id"); long key; try { key = long.Parse(id, CultureInfo.InvariantCulture); } catch (FormatException e) { throw new ArgumentException(e.Message, "id", e); } const string sql = @" SELECT AllXml FROM Error WHERE ErrorId = @ErrorId"; using (var connection = new SQLiteConnection(ConnectionString)) using (var command = new SQLiteCommand(sql, connection)) { var parameters = command.Parameters; parameters.Add("@ErrorId", DbType.Int64).Value = key; connection.Open(); var errorXml = (string) command.ExecuteScalar(); if (errorXml == null) return null; var error = ErrorXml.DecodeString(errorXml); return new ErrorLogEntry(this, id, error); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using OpenSim.Data; using OpenSim.Services.Interfaces; using OpenSim.Framework.Console; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; using log4net; namespace OpenSim.Services.UserAccountService { public class UserAccountService : UserAccountServiceBase, IUserAccountService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static UserAccountService m_RootInstance; protected IGridService m_GridService; protected IAuthenticationService m_AuthenticationService; protected IGridUserService m_GridUserService; protected IInventoryService m_InventoryService; public UserAccountService(IConfigSource config) : base(config) { IConfig userConfig = config.Configs["UserAccountService"]; if (userConfig == null) throw new Exception("No UserAccountService configuration"); // In case there are several instances of this class in the same process, // the console commands are only registered for the root instance if (m_RootInstance == null) { m_RootInstance = this; string gridServiceDll = userConfig.GetString("GridService", string.Empty); if (gridServiceDll != string.Empty) m_GridService = LoadPlugin<IGridService>(gridServiceDll, new Object[] { config }); string authServiceDll = userConfig.GetString("AuthenticationService", string.Empty); if (authServiceDll != string.Empty) m_AuthenticationService = LoadPlugin<IAuthenticationService>(authServiceDll, new Object[] { config }); string presenceServiceDll = userConfig.GetString("GridUserService", string.Empty); if (presenceServiceDll != string.Empty) m_GridUserService = LoadPlugin<IGridUserService>(presenceServiceDll, new Object[] { config }); string invServiceDll = userConfig.GetString("InventoryService", string.Empty); if (invServiceDll != string.Empty) m_InventoryService = LoadPlugin<IInventoryService>(invServiceDll, new Object[] { config }); if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand("UserService", false, "create user", "create user [<first> [<last> [<pass> [<email>]]]]", "Create a new user", HandleCreateUser); MainConsole.Instance.Commands.AddCommand("UserService", false, "reset user password", "reset user password [<first> [<last> [<password>]]]", "Reset a user password", HandleResetUserPassword); } } } #region IUserAccountService public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName) { // m_log.DebugFormat( // "[USER ACCOUNT SERVICE]: Retrieving account by username for {0} {1}, scope {2}", // firstName, lastName, scopeID); UserAccountData[] d; if (scopeID != UUID.Zero) { d = m_Database.Get( new string[] { "ScopeID", "FirstName", "LastName" }, new string[] { scopeID.ToString(), firstName, lastName }); if (d.Length < 1) { d = m_Database.Get( new string[] { "ScopeID", "FirstName", "LastName" }, new string[] { UUID.Zero.ToString(), firstName, lastName }); } } else { d = m_Database.Get( new string[] { "FirstName", "LastName" }, new string[] { firstName, lastName }); } if (d.Length < 1) return null; return MakeUserAccount(d[0]); } private UserAccount MakeUserAccount(UserAccountData d) { UserAccount u = new UserAccount(); u.FirstName = d.FirstName; u.LastName = d.LastName; u.PrincipalID = d.PrincipalID; u.ScopeID = d.ScopeID; if (d.Data.ContainsKey("Email") && d.Data["Email"] != null) u.Email = d.Data["Email"].ToString(); else u.Email = string.Empty; u.Created = Convert.ToInt32(d.Data["Created"].ToString()); if (d.Data.ContainsKey("UserTitle") && d.Data["UserTitle"] != null) u.UserTitle = d.Data["UserTitle"].ToString(); else u.UserTitle = string.Empty; if (d.Data.ContainsKey("UserLevel") && d.Data["UserLevel"] != null) Int32.TryParse(d.Data["UserLevel"], out u.UserLevel); if (d.Data.ContainsKey("UserFlags") && d.Data["UserFlags"] != null) Int32.TryParse(d.Data["UserFlags"], out u.UserFlags); if (d.Data.ContainsKey("ServiceURLs") && d.Data["ServiceURLs"] != null) { string[] URLs = d.Data["ServiceURLs"].ToString().Split(new char[] { ' ' }); u.ServiceURLs = new Dictionary<string, object>(); foreach (string url in URLs) { string[] parts = url.Split(new char[] { '=' }); if (parts.Length != 2) continue; string name = System.Web.HttpUtility.UrlDecode(parts[0]); string val = System.Web.HttpUtility.UrlDecode(parts[1]); u.ServiceURLs[name] = val; } } else u.ServiceURLs = new Dictionary<string, object>(); return u; } public UserAccount GetUserAccount(UUID scopeID, string email) { UserAccountData[] d; if (scopeID != UUID.Zero) { d = m_Database.Get( new string[] { "ScopeID", "Email" }, new string[] { scopeID.ToString(), email }); if (d.Length < 1) { d = m_Database.Get( new string[] { "ScopeID", "Email" }, new string[] { UUID.Zero.ToString(), email }); } } else { d = m_Database.Get( new string[] { "Email" }, new string[] { email }); } if (d.Length < 1) return null; return MakeUserAccount(d[0]); } public UserAccount GetUserAccount(UUID scopeID, UUID principalID) { UserAccountData[] d; if (scopeID != UUID.Zero) { d = m_Database.Get( new string[] { "ScopeID", "PrincipalID" }, new string[] { scopeID.ToString(), principalID.ToString() }); if (d.Length < 1) { d = m_Database.Get( new string[] { "ScopeID", "PrincipalID" }, new string[] { UUID.Zero.ToString(), principalID.ToString() }); } } else { d = m_Database.Get( new string[] { "PrincipalID" }, new string[] { principalID.ToString() }); } if (d.Length < 1) { return null; } return MakeUserAccount(d[0]); } public bool StoreUserAccount(UserAccount data) { // m_log.DebugFormat( // "[USER ACCOUNT SERVICE]: Storing user account for {0} {1} {2}, scope {3}", // data.FirstName, data.LastName, data.PrincipalID, data.ScopeID); UserAccountData d = new UserAccountData(); d.FirstName = data.FirstName; d.LastName = data.LastName; d.PrincipalID = data.PrincipalID; d.ScopeID = data.ScopeID; d.Data = new Dictionary<string, string>(); d.Data["Email"] = data.Email; d.Data["Created"] = data.Created.ToString(); d.Data["UserLevel"] = data.UserLevel.ToString(); d.Data["UserFlags"] = data.UserFlags.ToString(); if (data.UserTitle != null) d.Data["UserTitle"] = data.UserTitle.ToString(); List<string> parts = new List<string>(); foreach (KeyValuePair<string, object> kvp in data.ServiceURLs) { string key = System.Web.HttpUtility.UrlEncode(kvp.Key); string val = System.Web.HttpUtility.UrlEncode(kvp.Value.ToString()); parts.Add(key + "=" + val); } d.Data["ServiceURLs"] = string.Join(" ", parts.ToArray()); return m_Database.Store(d); } public List<UserAccount> GetUserAccounts(UUID scopeID, string query) { UserAccountData[] d = m_Database.GetUsers(scopeID, query); if (d == null) return new List<UserAccount>(); List<UserAccount> ret = new List<UserAccount>(); foreach (UserAccountData data in d) ret.Add(MakeUserAccount(data)); return ret; } #endregion #region Console commands /// <summary> /// Handle the create user command from the console. /// </summary> /// <param name="cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param> protected void HandleCreateUser(string module, string[] cmdparams) { string firstName; string lastName; string password; string email; List<char> excluded = new List<char>(new char[]{' '}); if (cmdparams.Length < 3) firstName = MainConsole.Instance.CmdPrompt("First name", "Default", excluded); else firstName = cmdparams[2]; if (cmdparams.Length < 4) lastName = MainConsole.Instance.CmdPrompt("Last name", "User", excluded); else lastName = cmdparams[3]; if (cmdparams.Length < 5) password = MainConsole.Instance.PasswdPrompt("Password"); else password = cmdparams[4]; if (cmdparams.Length < 6) email = MainConsole.Instance.CmdPrompt("Email", ""); else email = cmdparams[5]; CreateUser(firstName, lastName, password, email); } protected void HandleResetUserPassword(string module, string[] cmdparams) { string firstName; string lastName; string newPassword; if (cmdparams.Length < 4) firstName = MainConsole.Instance.CmdPrompt("First name"); else firstName = cmdparams[3]; if (cmdparams.Length < 5) lastName = MainConsole.Instance.CmdPrompt("Last name"); else lastName = cmdparams[4]; if (cmdparams.Length < 6) newPassword = MainConsole.Instance.PasswdPrompt("New password"); else newPassword = cmdparams[5]; UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); if (account == null) m_log.ErrorFormat("[USER ACCOUNT SERVICE]: No such user"); bool success = false; if (m_AuthenticationService != null) success = m_AuthenticationService.SetPassword(account.PrincipalID, newPassword); if (!success) m_log.ErrorFormat("[USER ACCOUNT SERVICE]: Unable to reset password for account {0} {1}.", firstName, lastName); else m_log.InfoFormat("[USER ACCOUNT SERVICE]: Password reset for user {0} {1}", firstName, lastName); } #endregion /// <summary> /// Create a user /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="password"></param> /// <param name="email"></param> private void CreateUser(string firstName, string lastName, string password, string email) { UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); if (null == account) { account = new UserAccount(UUID.Zero, firstName, lastName, email); if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0)) { account.ServiceURLs = new Dictionary<string, object>(); account.ServiceURLs["HomeURI"] = string.Empty; account.ServiceURLs["GatekeeperURI"] = string.Empty; account.ServiceURLs["InventoryServerURI"] = string.Empty; account.ServiceURLs["AssetServerURI"] = string.Empty; } if (StoreUserAccount(account)) { bool success; if (m_AuthenticationService != null) { success = m_AuthenticationService.SetPassword(account.PrincipalID, password); if (!success) m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.", firstName, lastName); } GridRegion home = null; if (m_GridService != null) { List<GridRegion> defaultRegions = m_GridService.GetDefaultRegions(UUID.Zero); if (defaultRegions != null && defaultRegions.Count >= 1) home = defaultRegions[0]; if (m_GridUserService != null && home != null) m_GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); else m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.", firstName, lastName); } else m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.", firstName, lastName); if (m_InventoryService != null) { success = m_InventoryService.CreateUserInventory(account.PrincipalID); if (!success) m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.", firstName, lastName); } m_log.InfoFormat("[USER ACCOUNT SERVICE]: Account {0} {1} created successfully", firstName, lastName); } else { m_log.ErrorFormat("[USER ACCOUNT SERVICE]: Account creation failed for account {0} {1}", firstName, lastName); } } else { m_log.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} {1} already exists!", firstName, lastName); } } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace RunGPAsync { partial class RunGPForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RunGPForm)); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.panel1 = new System.Windows.Forms.Panel(); this.textBox7 = new System.Windows.Forms.TextBox(); this.textBox6 = new System.Windows.Forms.TextBox(); this.textBox5 = new System.Windows.Forms.TextBox(); this.txtBufferDistance = new System.Windows.Forms.TextBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl(); this.btnRunGP = new System.Windows.Forms.Button(); this.listView1 = new System.Windows.Forms.ListView(); this.axMapControl1 = new ESRI.ArcGIS.Controls.AxMapControl(); this.axToolbarControl1 = new ESRI.ArcGIS.Controls.AxToolbarControl(); this.panel2 = new System.Windows.Forms.Panel(); this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl(); this.tableLayoutPanel1.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).BeginInit(); this.panel2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit(); this.SuspendLayout(); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "error"); this.imageList1.Images.SetKeyName(1, "information"); this.imageList1.Images.SetKeyName(2, "warning"); this.imageList1.Images.SetKeyName(3, "success"); // // tableLayoutPanel1 // this.tableLayoutPanel1.BackColor = System.Drawing.Color.White; this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 27.70563F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 72.29437F)); this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.listView1, 1, 2); this.tableLayoutPanel1.Controls.Add(this.axMapControl1, 1, 1); this.tableLayoutPanel1.Controls.Add(this.axToolbarControl1, 1, 0); this.tableLayoutPanel1.Controls.Add(this.panel2, 0, 2); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 3; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 7.042253F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 92.95775F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 211F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(693, 558); this.tableLayoutPanel1.TabIndex = 7; // // panel1 // this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.panel1.Controls.Add(this.textBox7); this.panel1.Controls.Add(this.textBox6); this.panel1.Controls.Add(this.textBox5); this.panel1.Controls.Add(this.txtBufferDistance); this.panel1.Controls.Add(this.textBox4); this.panel1.Controls.Add(this.textBox3); this.panel1.Controls.Add(this.textBox2); this.panel1.Controls.Add(this.textBox1); this.panel1.Controls.Add(this.axLicenseControl1); this.panel1.Controls.Add(this.btnRunGP); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(3, 3); this.panel1.Name = "panel1"; this.tableLayoutPanel1.SetRowSpan(this.panel1, 2); this.panel1.Size = new System.Drawing.Size(186, 340); this.panel1.TabIndex = 0; // // textBox7 // this.textBox7.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.textBox7.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox7.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox7.Location = new System.Drawing.Point(3, 276); this.textBox7.Multiline = true; this.textBox7.Name = "textBox7"; this.textBox7.Size = new System.Drawing.Size(180, 61); this.textBox7.TabIndex = 15; this.textBox7.Text = "4. Test that the application stays responsive while the tools are executing, e.g." + " try to Pan and Zoom the map."; // // textBox6 // this.textBox6.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.textBox6.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox6.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox6.Location = new System.Drawing.Point(3, 201); this.textBox6.Multiline = true; this.textBox6.Name = "textBox6"; this.textBox6.Size = new System.Drawing.Size(180, 33); this.textBox6.TabIndex = 14; this.textBox6.Text = "3. Click Run to perform the analysis:"; // // textBox5 // this.textBox5.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.textBox5.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox5.Location = new System.Drawing.Point(69, 180); this.textBox5.Multiline = true; this.textBox5.Name = "textBox5"; this.textBox5.Size = new System.Drawing.Size(114, 13); this.textBox5.TabIndex = 13; this.textBox5.Text = "Miles"; // // txtBufferDistance // this.txtBufferDistance.BackColor = System.Drawing.Color.White; this.txtBufferDistance.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtBufferDistance.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtBufferDistance.Location = new System.Drawing.Point(17, 180); this.txtBufferDistance.Name = "txtBufferDistance"; this.txtBufferDistance.Size = new System.Drawing.Size(46, 13); this.txtBufferDistance.TabIndex = 12; this.txtBufferDistance.Text = "30"; this.txtBufferDistance.TextChanged += new System.EventHandler(this.txtBufferDistance_TextChanged); // // textBox4 // this.textBox4.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.textBox4.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox4.Location = new System.Drawing.Point(3, 158); this.textBox4.Multiline = true; this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(180, 25); this.textBox4.TabIndex = 11; this.textBox4.Text = "2. Enter a buffer distance:"; // // textBox3 // this.textBox3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.textBox3.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox3.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox3.Location = new System.Drawing.Point(3, 112); this.textBox3.Multiline = true; this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(180, 51); this.textBox3.TabIndex = 10; this.textBox3.Text = "1. Use the currently selected city, or use the Select Features tool to select som" + "e other cities"; // // textBox2 // this.textBox2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox2.Location = new System.Drawing.Point(3, 95); this.textBox2.Multiline = true; this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(180, 25); this.textBox2.TabIndex = 9; this.textBox2.Text = "Steps:"; // // textBox1 // this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox1.Location = new System.Drawing.Point(3, 3); this.textBox1.Multiline = true; this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(180, 92); this.textBox1.TabIndex = 8; this.textBox1.Text = "This sample demonstrates a two stage geoprocessing analysis. The selected cities" + " are buffered and the output layer is used to clip the zip codes layer. The resu" + "lt layer is then added to the map."; // // axLicenseControl1 // this.axLicenseControl1.Enabled = true; this.axLicenseControl1.Location = new System.Drawing.Point(130, 238); this.axLicenseControl1.Name = "axLicenseControl1"; this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState"))); this.axLicenseControl1.Size = new System.Drawing.Size(32, 32); this.axLicenseControl1.TabIndex = 6; // // btnRunGP // this.btnRunGP.Enabled = false; this.btnRunGP.Location = new System.Drawing.Point(17, 236); this.btnRunGP.Name = "btnRunGP"; this.btnRunGP.Size = new System.Drawing.Size(75, 23); this.btnRunGP.TabIndex = 5; this.btnRunGP.Text = "Run"; this.btnRunGP.UseVisualStyleBackColor = true; this.btnRunGP.Click += new System.EventHandler(this.btnRunGP_Click); // // listView1 // this.listView1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.listView1.Dock = System.Windows.Forms.DockStyle.Fill; this.listView1.Location = new System.Drawing.Point(195, 349); this.listView1.Name = "listView1"; this.listView1.Size = new System.Drawing.Size(495, 206); this.listView1.SmallImageList = this.imageList1; this.listView1.TabIndex = 1; this.listView1.UseCompatibleStateImageBehavior = false; this.listView1.View = System.Windows.Forms.View.Details; // // axMapControl1 // this.axMapControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.axMapControl1.Location = new System.Drawing.Point(195, 27); this.axMapControl1.Name = "axMapControl1"; this.axMapControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axMapControl1.OcxState"))); this.axMapControl1.Size = new System.Drawing.Size(495, 316); this.axMapControl1.TabIndex = 2; // // axToolbarControl1 // this.axToolbarControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.axToolbarControl1.Location = new System.Drawing.Point(195, 3); this.axToolbarControl1.Name = "axToolbarControl1"; this.axToolbarControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axToolbarControl1.OcxState"))); this.axToolbarControl1.Size = new System.Drawing.Size(495, 28); this.axToolbarControl1.TabIndex = 3; // // panel2 // this.panel2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); this.panel2.Controls.Add(this.axTOCControl1); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(3, 349); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(186, 206); this.panel2.TabIndex = 4; // // axTOCControl1 // this.axTOCControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.axTOCControl1.Location = new System.Drawing.Point(0, 0); this.axTOCControl1.Name = "axTOCControl1"; this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState"))); this.axTOCControl1.Size = new System.Drawing.Size(186, 206); this.axTOCControl1.TabIndex = 0; // // RunGPForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(693, 558); this.Controls.Add(this.tableLayoutPanel1); this.Name = "RunGPForm"; this.Text = "Run Geoprocessing Tools Asynchronously"; this.tableLayoutPanel1.ResumeLayout(false); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axMapControl1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.axToolbarControl1)).EndInit(); this.panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button btnRunGP; private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1; private System.Windows.Forms.ListView listView1; private ESRI.ArcGIS.Controls.AxMapControl axMapControl1; private ESRI.ArcGIS.Controls.AxToolbarControl axToolbarControl1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Panel panel2; private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.TextBox txtBufferDistance; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.TextBox textBox6; } }
using System; using System.Collections.Generic; using System.Linq; using ModestTree; using Zenject; namespace Zenject { public abstract class FactoryProviderBase<TValue, TFactory> : IProvider where TFactory : IFactory { readonly List<TypeValuePair> _factoryArgs; public FactoryProviderBase(DiContainer container, List<TypeValuePair> factoryArgs) { Container = container; _factoryArgs = factoryArgs; } protected DiContainer Container { get; private set; } public Type GetInstanceType(InjectContext context) { return typeof(TValue); } public abstract IEnumerator<List<object>> GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args); protected object CreateFactory() { return Container.InstantiateExplicit(typeof(TFactory), _factoryArgs); } } // Zero parameters public class FactoryProvider<TValue, TFactory> : FactoryProviderBase<TValue, TFactory> where TFactory : IFactory<TValue> { public FactoryProvider(DiContainer container, List<TypeValuePair> factoryArgs) : base(container, factoryArgs) { } public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args) { Assert.IsEmpty(args); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); // Do this even when validating in case it has its own dependencies var factory = CreateFactory(); if (Container.IsValidating) { // In case users define a custom IFactory that needs to be validated if (factory is IValidatable) { ((IValidatable)factory).Validate(); } // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { ((TFactory)factory).Create() }; } } } // One parameters public class FactoryProvider<TParam1, TValue, TFactory> : FactoryProviderBase<TValue, TFactory> where TFactory : IFactory<TParam1, TValue> { public FactoryProvider(DiContainer container, List<TypeValuePair> factoryArgs) : base(container, factoryArgs) { } public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 1); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.IsEqual(args[0].Type, typeof(TParam1)); // Do this even when validating in case it has its own dependencies var factory = CreateFactory(); if (Container.IsValidating) { // In case users define a custom IFactory that needs to be validated if (factory is IValidatable) { ((IValidatable)factory).Validate(); } // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { ((TFactory)factory).Create((TParam1)args[0].Value) }; } } } // Two parameters public class FactoryProvider<TParam1, TParam2, TValue, TFactory> : FactoryProviderBase<TValue, TFactory> where TFactory : IFactory<TParam1, TParam2, TValue> { public FactoryProvider(DiContainer container, List<TypeValuePair> factoryArgs) : base(container, factoryArgs) { } public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 2); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.IsEqual(args[0].Type, typeof(TParam1)); Assert.IsEqual(args[1].Type, typeof(TParam2)); // Do this even when validating in case it has its own dependencies var factory = CreateFactory(); if (Container.IsValidating) { // In case users define a custom IFactory that needs to be validated if (factory is IValidatable) { ((IValidatable)factory).Validate(); } // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { ((TFactory)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value) }; } } } // Three parameters public class FactoryProvider<TParam1, TParam2, TParam3, TValue, TFactory> : FactoryProviderBase<TValue, TFactory> where TFactory : IFactory<TParam1, TParam2, TParam3, TValue> { public FactoryProvider(DiContainer container, List<TypeValuePair> factoryArgs) : base(container, factoryArgs) { } public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 3); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.IsEqual(args[0].Type, typeof(TParam1)); Assert.IsEqual(args[1].Type, typeof(TParam2)); Assert.IsEqual(args[2].Type, typeof(TParam3)); // Do this even when validating in case it has its own dependencies var factory = CreateFactory(); if (Container.IsValidating) { // In case users define a custom IFactory that needs to be validated if (factory is IValidatable) { ((IValidatable)factory).Validate(); } // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { ((TFactory)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value) }; } } } // Four parameters public class FactoryProvider<TParam1, TParam2, TParam3, TParam4, TValue, TFactory> : FactoryProviderBase<TValue, TFactory> where TFactory : IFactory<TParam1, TParam2, TParam3, TParam4, TValue> { public FactoryProvider(DiContainer container, List<TypeValuePair> factoryArgs) : base(container, factoryArgs) { } public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 4); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.IsEqual(args[0].Type, typeof(TParam1)); Assert.IsEqual(args[1].Type, typeof(TParam2)); Assert.IsEqual(args[2].Type, typeof(TParam3)); Assert.IsEqual(args[3].Type, typeof(TParam4)); // Do this even when validating in case it has its own dependencies var factory = CreateFactory(); if (Container.IsValidating) { // In case users define a custom IFactory that needs to be validated if (factory is IValidatable) { ((IValidatable)factory).Validate(); } // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { ((TFactory)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value, (TParam4)args[3].Value) }; } } } // Five parameters public class FactoryProvider<TParam1, TParam2, TParam3, TParam4, TParam5, TValue, TFactory> : FactoryProviderBase<TValue, TFactory> where TFactory : IFactory<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> { public FactoryProvider(DiContainer container, List<TypeValuePair> factoryArgs) : base(container, factoryArgs) { } public override IEnumerator<List<object>> GetAllInstancesWithInjectSplit( InjectContext context, List<TypeValuePair> args) { Assert.IsEqual(args.Count, 5); Assert.IsNotNull(context); Assert.That(typeof(TValue).DerivesFromOrEqual(context.MemberType)); Assert.IsEqual(args[0].Type, typeof(TParam1)); Assert.IsEqual(args[1].Type, typeof(TParam2)); Assert.IsEqual(args[2].Type, typeof(TParam3)); Assert.IsEqual(args[3].Type, typeof(TParam4)); Assert.IsEqual(args[4].Type, typeof(TParam5)); // Do this even when validating in case it has its own dependencies var factory = CreateFactory(); if (Container.IsValidating) { // In case users define a custom IFactory that needs to be validated if (factory is IValidatable) { ((IValidatable)factory).Validate(); } // We assume here that we are creating a user-defined factory so there's // nothing else we can validate here yield return new List<object>() { new ValidationMarker(typeof(TValue)) }; } else { yield return new List<object>() { ((TFactory)factory).Create( (TParam1)args[0].Value, (TParam2)args[1].Value, (TParam3)args[2].Value, (TParam4)args[3].Value, (TParam5)args[4].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.IO; using System; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Shared; using Xunit; namespace Microsoft.Build.UnitTests { #if FEATURE_CODETASKFACTORY using System.CodeDom.Compiler; public sealed class CodeTaskFactoryTests { /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// </summary> [Fact] public void BuildTaskSimpleCodeFactory() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); } /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// Specifically testing that even when the ToolsVersion is post-4.0, and thus /// Microsoft.Build.Tasks.v4.0.dll is expected to NOT be in MSBuildToolsPath, that /// we will redirect under the covers to use the current tasks instead. /// </summary> [Fact] public void BuildTaskSimpleCodeFactory_RedirectFrom4() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); mockLogger.AssertLogDoesntContain("Microsoft.Build.Tasks.v4.0.dll"); } /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// Specifically testing that even when the ToolsVersion is post-12.0, and thus /// Microsoft.Build.Tasks.v12.0.dll is expected to NOT be in MSBuildToolsPath, that /// we will redirect under the covers to use the current tasks instead. /// </summary> [Fact] public void BuildTaskSimpleCodeFactory_RedirectFrom12() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.v12.0.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); mockLogger.AssertLogDoesntContain("Microsoft.Build.Tasks.v12.0.dll"); } /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// Specifically testing that even when the ToolsVersion is post-4.0, and we have redirection /// logic in place for the AssemblyFile case to deal with Microsoft.Build.Tasks.v4.0.dll not /// being in MSBuildToolsPath anymore, that this does NOT affect full fusion AssemblyNames -- /// it's picked up from the GAC, where it is anyway, so there's no need to redirect. /// </summary> [Fact] public void BuildTaskSimpleCodeFactory_NoAssemblyNameRedirect() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyName=`Microsoft.Build.Tasks.Core, Version=15.1.0.0` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); mockLogger.AssertLogContains("Microsoft.Build.Tasks.Core, Version=15.1.0.0"); } /// <summary> /// Test the simple case where we have a string parameter and we want to log that. /// </summary> [Fact] public void VerifyRequiredAttribute() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_VerifyRequiredAttribute` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text Required='true'/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_VerifyRequiredAttribute/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains("MSB4044"); } /// <summary> /// Verify we get an error if a runtime exception is logged /// </summary> [Fact] public void RuntimeException() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_RuntimeException` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> throw new InvalidOperationException(""MyCustomException""); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_RuntimeException/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, true); mockLogger.AssertLogContains("MSB4018"); mockLogger.AssertLogContains("MyCustomException"); } /// <summary> /// Verify we get an error if a the languages attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptyLanguage() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyLanguage` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Language=''> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyLanguage/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Language")); } /// <summary> /// Verify we get an error if a the Type attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptyType() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyType` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Type=''> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyType/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Type")); } /// <summary> /// Verify we get an error if a the source attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptySource() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptySource` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Source=''> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptySource/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Source")); } /// <summary> /// Verify we get an error if a reference is missing an include attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptyReferenceInclude() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyReferenceInclude` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Reference/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyReferenceInclude/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Include")); } /// <summary> /// Verify we get an error if a Using statement is missing an namespace attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void EmptyUsingNamespace() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyUsingNamespace` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Using/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyUsingNamespace/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.AttributeEmpty"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Namespace")); } /// <summary> /// Verify we get pass even if the reference is not a full path /// </summary> [Fact] public void ReferenceNotPath() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_ReferenceNotPath` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Reference Include='System'/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_ReferenceNotPath Text=""Hello""/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello"); } /// <summary> /// Verify we get an error a reference has strange chars /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ReferenceInvalidChars() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_ReferenceInvalidChars` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Reference Include='@@#$@#'/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_ReferenceInvalidChars/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains("MSB3755"); mockLogger.AssertLogContains("@@#$@#"); } /// <summary> /// Verify we get an error if a using has invalid chars /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void UsingInvalidChars() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_UsingInvalidChars` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Using Namespace='@@#$@#'/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_UsingInvalidChars/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains("CS1646"); } /// <summary> /// Verify we get an error if the sources points to an invalid file /// </summary> [Fact] public void SourcesInvalidFile() { string tempFileName = "Moose_" + Guid.NewGuid().ToString() + ".cs"; string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_SourcesInvalidFile` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Source='$(SystemDrive)\\" + tempFileName + @"'> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_SourcesInvalidFile/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains(Environment.GetEnvironmentVariable("SystemDrive") + '\\' + tempFileName); } /// <summary> /// Verify we get an error if a the code element is missing /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void MissingCodeElement() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_MissingCodeElement` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_MissingCodeElement/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); mockLogger.AssertLogContains(String.Format(ResourceUtilities.GetResourceString("CodeTaskFactory.CodeElementIsMissing"), "CustomTaskFromCodeFactory_MissingCodeElement")); } /// <summary> /// Test the case where we have adding a using statement /// </summary> [Fact] public void BuildTaskSimpleCodeFactoryTestExtraUsing() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestExtraUsing` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Using Namespace='System.Linq.Expressions'/> <Code> string linqString = ExpressionType.Add.ToString(); Log.LogMessage(MessageImportance.High, linqString + Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestExtraUsing Text=`:Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); string linqString = nameof(System.Linq.Expressions.ExpressionType.Add); mockLogger.AssertLogContains(linqString + ":Hello, World!"); } /// <summary> /// Verify setting the output tag on the parameter causes it to be an output from the perspective of the targets /// </summary> [Fact] public void BuildTaskDateCodeFactory() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`DateTaskFromCodeFactory_BuildTaskDateCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <CurrentDate ParameterType=`System.String` Output=`true` /> </ParameterGroup> <Task> <Code> CurrentDate = DateTime.Now.ToString(); </Code> </Task> </UsingTask> <Target Name=`Build`> <DateTaskFromCodeFactory_BuildTaskDateCodeFactory> <Output TaskParameter=`CurrentDate` PropertyName=`CurrentDate` /> </DateTaskFromCodeFactory_BuildTaskDateCodeFactory> <Message Text=`Current Date and Time: [[$(CurrentDate)]]` Importance=`High` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Current Date and Time:"); mockLogger.AssertLogDoesntContain("[[]]"); } /// <summary> /// Verify that the vb language works and that creating the execute method also works /// </summary> [Fact] public void MethodImplmentationVB() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CodeMethod_MethodImplmentationVB` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Text ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Method' Language='vb'> <![CDATA[ Public Overrides Function Execute() As Boolean Log.LogMessage(MessageImportance.High, Text) Return True End Function ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <CodeMethod_MethodImplmentationVB Text='IAMVBTEXT'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("IAMVBTEXT"); } /// <summary> /// Verify that System does not need to be passed in as a extra reference when targeting vb /// </summary> [Fact] public void BuildTaskSimpleCodeFactoryTestSystemVB() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestSystemVB` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Language='vb'> Dim headerRequest As String headerRequest = System.Net.HttpRequestHeader.Accept.ToString() Log.LogMessage(MessageImportance.High, headerRequest + Text) </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestSystemVB Text=`:Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Accept" + ":Hello, World!"); } /// <summary> /// Verify that System does not need to be passed in as a extra reference when targeting c# /// </summary> [Fact] public void BuildTaskSimpleCodeFactoryTestSystemCS() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestSystemCS` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code Language='cs'> string headerRequest = System.Net.HttpRequestHeader.Accept.ToString(); Log.LogMessage(MessageImportance.High, headerRequest + Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestSystemCS Text=`:Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Accept" + ":Hello, World!"); } /// <summary> /// Make sure we can pass in extra references than the automatic ones. For example the c# compiler does not pass in /// system.dll. So lets test that case /// </summary> [Fact] public void BuildTaskSimpleCodeFactoryTestExtraReferenceCS() { string netFrameworkDirectory = ToolLocationHelper.GetPathToDotNetFrameworkReferenceAssemblies(TargetDotNetFrameworkVersion.Version45); if (netFrameworkDirectory == null) { // "CouldNotFindRequiredTestDirectory" return; } string systemNETLocation = Path.Combine(netFrameworkDirectory, "System.Net.dll"); if (!File.Exists(systemNETLocation)) { // "CouldNotFindRequiredTestFile" return; } string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestExtraReferenceCS` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Using Namespace='System.Net'/> <Reference Include='" + systemNETLocation + @"'/> <Code> string netString = System.Net.HttpStatusCode.OK.ToString(); Log.LogMessage(MessageImportance.High, netString + Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactoryTestExtraReferenceCS Text=`:Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("OK" + ":Hello, World!"); } /// <summary> /// jscript .net works /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void MethodImplementationJScriptNet() { if (!CodeDomProvider.IsDefinedLanguage("js")) { // "JScript .net Is not installed on the test machine this test cannot run" return; } string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CodeMethod_MethodImplementationJScriptNet` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Text ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Method' Language='js'> <![CDATA[ override function Execute() : System.Boolean { Log.LogMessage(MessageImportance.High, Text); return true; } ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <CodeMethod_MethodImplementationJScriptNet Text='IAMJSTEXT'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("IAMJSTEXT"); } /// <summary> /// Verify we can set a code type of Method which expects us to override the execute method entirely. /// </summary> [Fact] public void MethodImplementation() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CodeMethod_MethodImplementation` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Text ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Method'> <![CDATA[ public override bool Execute() { Log.LogMessage(MessageImportance.High, Text); return true; } ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <CodeMethod_MethodImplementation Text='IAMTEXT'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("IAMTEXT"); } /// <summary> /// Verify we can set the type to Class and this expects an entire class to be entered into the code tag /// </summary> [Fact] public void ClassImplementationTest() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`LogNameValue_ClassImplementationTest` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Name ParameterType='System.String' /> <Value ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Class'> <![CDATA[ using System; using System.Collections.Generic; using System.Text; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; namespace Microsoft.Build.NonShippingTasks { public class LogNameValue_ClassImplementationTest : Task { private string variableName; private string variableValue; [Required] public string Name { get { return variableName; } set { variableName = value; } } public string Value { get { return variableValue; } set { variableValue = value; } } public override bool Execute() { // Set the process environment Log.LogMessage(""Setting {0}={1}"", this.variableName, this.variableValue); return true; } } } ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <LogNameValue_ClassImplementationTest Name='MyName' Value='MyValue'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("MyName=MyValue"); } /// <summary> /// Verify we can set the type to Class and this expects an entire class to be entered into the code tag /// </summary> [Fact] public void ClassImplementationTestDoesNotInheritFromITask() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`ClassImplementationTestDoesNotInheritFromITask` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Name ParameterType='System.String' /> <Value ParameterType='System.String' /> </ParameterGroup> <Task> <Code Type='Class'> <![CDATA[ using System; using System.Collections.Generic; using System.Text; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; namespace Microsoft.Build.NonShippingTasks { public class ClassImplementationTestDoesNotInheritFromITask { private string variableName; [Required] public string Name { get { return variableName; } set { variableName = value; } } public bool Execute() { // Set the process environment Console.Out.WriteLine(variableName); return true; } } } ]]> </Code> </Task> </UsingTask> <Target Name=`Build`> <ClassImplementationTestDoesNotInheritFromITask Name='MyName' Value='MyValue'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.NeedsITaskInterface"); mockLogger.AssertLogContains(unformattedMessage); } /// <summary> /// Verify we get an error if a the Type attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void MultipleCodeElements() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyType` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyType/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.MultipleCodeNodes"); mockLogger.AssertLogContains(unformattedMessage); } /// <summary> /// Verify we get an error if a the Type attribute is set but it is empty /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void ReferenceNestedInCode() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyType` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> <Reference Include=""System.Xml""/> <Using Namespace=""Hello""/> <Task/> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyType/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.InvalidElementLocation"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Reference", "Code")); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Using", "Code")); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Task", "Code")); } /// <summary> /// Verify we get an error if there is an unknown element in the task tag /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void UnknownElementInTask() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_EmptyType` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Unknown/> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_EmptyType Text=""HELLO""/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, false); string unformattedMessage = ResourceUtilities.GetResourceString("CodeTaskFactory.InvalidElementLocation"); mockLogger.AssertLogContains(String.Format(unformattedMessage, "Unknown", "Task")); } /// <summary> /// Verify we can set a source file location and this will be read in and used. /// </summary> [Fact] public void ClassSourcesTest() { string sourceFileContent = @" using System; using System.Collections.Generic; using System.Text; using Microsoft.Build.Utilities; using Microsoft.Build.Framework; namespace Microsoft.Build.NonShippingTasks { public class LogNameValue_ClassSourcesTest : Task { private string variableName; private string variableValue; [Required] public string Name { get { return variableName; } set { variableName = value; } } public string Value { get { return variableValue; } set { variableValue = value; } } public override bool Execute() { // Set the process environment Log.LogMessage(""Setting {0}={1}"", this.variableName, this.variableValue); return true; } } } "; string tempFileDirectory = Path.GetTempPath(); string tempFileName = Guid.NewGuid().ToString() + ".cs"; string tempSourceFile = Path.Combine(tempFileDirectory, tempFileName); File.WriteAllText(tempSourceFile, sourceFileContent); try { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`LogNameValue_ClassSourcesTest` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll`> <ParameterGroup> <Name ParameterType='System.String' /> <Value ParameterType='System.String' /> </ParameterGroup> <Task> <Code Source='" + tempSourceFile + @"'/> </Task> </UsingTask> <Target Name=`Build`> <LogNameValue_ClassSourcesTest Name='MyName' Value='MyValue'/> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("MyName=MyValue"); } finally { if (File.Exists(tempSourceFile)) { File.Delete(tempSourceFile); } } } /// <summary> /// Code factory test where the TMP directory does not exist. /// See https://github.com/Microsoft/msbuild/issues/328 for details. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void BuildTaskSimpleCodeFactoryTempDirectoryDoesntExist() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; var oldTempPath = Environment.GetEnvironmentVariable("TMP"); var newTempPath = Path.Combine(Path.GetFullPath(oldTempPath), Path.GetRandomFileName()); try { // Ensure we're getting the right temp path (%TMP% == GetTempPath()) Assert.Equal( FileUtilities.EnsureTrailingSlash(Path.GetTempPath()), FileUtilities.EnsureTrailingSlash(Path.GetFullPath(oldTempPath))); Assert.False(Directory.Exists(newTempPath)); Environment.SetEnvironmentVariable("TMP", newTempPath); Assert.Equal( FileUtilities.EnsureTrailingSlash(newTempPath), FileUtilities.EnsureTrailingSlash(Path.GetTempPath())); MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectSuccess(projectFileContents); mockLogger.AssertLogContains("Hello, World!"); } finally { Environment.SetEnvironmentVariable("TMP", oldTempPath); FileUtilities.DeleteDirectoryNoThrow(newTempPath, true); } } } #else public sealed class CodeTaskFactoryTests { [Fact] public void CodeTaskFactoryNotSupported() { string projectFileContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion='msbuilddefaulttoolsversion'> <UsingTask TaskName=`CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory` TaskFactory=`CodeTaskFactory` AssemblyFile=`$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll` > <ParameterGroup> <Text/> </ParameterGroup> <Task> <Code> Log.LogMessage(MessageImportance.High, Text); </Code> </Task> </UsingTask> <Target Name=`Build`> <CustomTaskFromCodeFactory_BuildTaskSimpleCodeFactory Text=`Hello, World!` /> </Target> </Project>"; MockLogger mockLogger = Helpers.BuildProjectWithNewOMExpectFailure(projectFileContents, allowTaskCrash: false); BuildErrorEventArgs error = mockLogger.Errors.FirstOrDefault(); Assert.NotNull(error); Assert.Equal("MSB4801", error.Code); Assert.Contains("CodeTaskFactory", error.Message); } } #endif }
using System.Diagnostics; using System.Text; using HANDLE = System.IntPtr; using i64 = System.Int64; using u32 = System.UInt32; using sqlite3_int64 = System.Int64; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2005 November 29 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file contains OS interface code that is common to all ** architectures. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-12-07 20:14:09 a586a4deeb25330037a49df295b36aaf624d0f45 ** ************************************************************************* */ //#define _SQLITE_OS_C_ 1 //#include "sqliteInt.h" //#undef _SQLITE_OS_C_ /* ** The default SQLite sqlite3_vfs implementations do not allocate ** memory (actually, os_unix.c allocates a small amount of memory ** from within OsOpen()), but some third-party implementations may. ** So we test the effects of a malloc() failing and the sqlite3OsXXX() ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro. ** ** The following functions are instrumented for malloc() failure ** testing: ** ** sqlite3OsOpen() ** sqlite3OsRead() ** sqlite3OsWrite() ** sqlite3OsSync() ** sqlite3OsLock() ** */ #if (SQLITE_TEST) static int sqlite3_memdebug_vfs_oom_test = 1; //#define DO_OS_MALLOC_TEST(x) \ //if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \ // void *pTstAlloc = sqlite3Malloc(10); \ // if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \ // sqlite3_free(pTstAlloc); \ //} static void DO_OS_MALLOC_TEST( sqlite3_file x ) { } #else //#define DO_OS_MALLOC_TEST(x) static void DO_OS_MALLOC_TEST( sqlite3_file x ) { } #endif /* ** The following routines are convenience wrappers around methods ** of the sqlite3_file object. This is mostly just syntactic sugar. All ** of this would be completely automatic if SQLite were coded using ** C++ instead of plain old C. */ static int sqlite3OsClose( sqlite3_file pId ) { int rc = SQLITE_OK; if ( pId.pMethods != null ) { rc = pId.pMethods.xClose( pId ); pId.pMethods = null; } return rc; } static int sqlite3OsRead( sqlite3_file id, byte[] pBuf, int amt, i64 offset ) { DO_OS_MALLOC_TEST( id ); if ( pBuf == null ) pBuf = sqlite3Malloc( amt ); return id.pMethods.xRead( id, pBuf, amt, offset ); } static int sqlite3OsWrite( sqlite3_file id, byte[] pBuf, int amt, i64 offset ) { DO_OS_MALLOC_TEST( id ); return id.pMethods.xWrite( id, pBuf, amt, offset ); } static int sqlite3OsTruncate( sqlite3_file id, i64 size ) { return id.pMethods.xTruncate( id, size ); } static int sqlite3OsSync( sqlite3_file id, int flags ) { DO_OS_MALLOC_TEST( id ); return id.pMethods.xSync( id, flags ); } static int sqlite3OsFileSize( sqlite3_file id, ref long pSize ) { return id.pMethods.xFileSize( id, ref pSize ); } static int sqlite3OsLock( sqlite3_file id, int lockType ) { DO_OS_MALLOC_TEST( id ); return id.pMethods.xLock( id, lockType ); } static int sqlite3OsUnlock( sqlite3_file id, int lockType ) { return id.pMethods.xUnlock( id, lockType ); } static int sqlite3OsCheckReservedLock( sqlite3_file id, ref int pResOut ) { DO_OS_MALLOC_TEST( id ); return id.pMethods.xCheckReservedLock( id, ref pResOut ); } static int sqlite3OsFileControl( sqlite3_file id, u32 op, ref sqlite3_int64 pArg ) { return id.pMethods.xFileControl( id, (int)op, ref pArg ); } static int sqlite3OsSectorSize( sqlite3_file id ) { dxSectorSize xSectorSize = id.pMethods.xSectorSize; return ( xSectorSize != null ? xSectorSize( id ) : SQLITE_DEFAULT_SECTOR_SIZE ); } static int sqlite3OsDeviceCharacteristics( sqlite3_file id ) { return id.pMethods.xDeviceCharacteristics( id ); } static int sqlite3OsShmLock( sqlite3_file id, int offset, int n, int flags ) { return id.pMethods.xShmLock( id, offset, n, flags ); } static void sqlite3OsShmBarrier( sqlite3_file id ) { id.pMethods.xShmBarrier( id ); } static int sqlite3OsShmUnmap( sqlite3_file id, int deleteFlag ) { return id.pMethods.xShmUnmap( id, deleteFlag ); } static int sqlite3OsShmMap( sqlite3_file id, /* Database file handle */ int iPage, int pgsz, int bExtend, /* True to extend file if necessary */ out object pp /* OUT: Pointer to mapping */ ) { return id.pMethods.xShmMap( id, iPage, pgsz, bExtend, out pp ); } /* ** The next group of routines are convenience wrappers around the ** VFS methods. */ static int sqlite3OsOpen( sqlite3_vfs pVfs, string zPath, sqlite3_file pFile, int flags, ref int pFlagsOut ) { int rc; DO_OS_MALLOC_TEST( null ); /* 0x87f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example, ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before ** reaching the VFS. */ rc = pVfs.xOpen( pVfs, zPath, pFile, flags & 0x87f3f, out pFlagsOut ); Debug.Assert( rc == SQLITE_OK || pFile.pMethods == null ); return rc; } static int sqlite3OsDelete( sqlite3_vfs pVfs, string zPath, int dirSync ) { return pVfs.xDelete( pVfs, zPath, dirSync ); } static int sqlite3OsAccess( sqlite3_vfs pVfs, string zPath, int flags, ref int pResOut ) { DO_OS_MALLOC_TEST( null ); return pVfs.xAccess( pVfs, zPath, flags, out pResOut ); } static int sqlite3OsFullPathname( sqlite3_vfs pVfs, string zPath, int nPathOut, StringBuilder zPathOut ) { zPathOut.Length = 0;//zPathOut[0] = 0; return pVfs.xFullPathname( pVfs, zPath, nPathOut, zPathOut ); } #if !SQLITE_OMIT_LOAD_EXTENSION static HANDLE sqlite3OsDlOpen( sqlite3_vfs pVfs, string zPath ) { return pVfs.xDlOpen( pVfs, zPath ); } static void sqlite3OsDlError( sqlite3_vfs pVfs, int nByte, string zBufOut ) { pVfs.xDlError( pVfs, nByte, zBufOut ); } static object sqlite3OsDlSym( sqlite3_vfs pVfs, HANDLE pHdle, ref string zSym ) { return pVfs.xDlSym( pVfs, pHdle, zSym ); } static void sqlite3OsDlClose( sqlite3_vfs pVfs, HANDLE pHandle ) { pVfs.xDlClose( pVfs, pHandle ); } #endif static int sqlite3OsRandomness( sqlite3_vfs pVfs, int nByte, byte[] zBufOut ) { return pVfs.xRandomness( pVfs, nByte, zBufOut ); } static int sqlite3OsSleep( sqlite3_vfs pVfs, int nMicro ) { return pVfs.xSleep( pVfs, nMicro ); } static int sqlite3OsCurrentTimeInt64( sqlite3_vfs pVfs, ref sqlite3_int64 pTimeOut ) { int rc; /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() ** method to get the current date and time if that method is available ** (if iVersion is 2 or greater and the function pointer is not NULL) and ** will fall back to xCurrentTime() if xCurrentTimeInt64() is ** unavailable. */ if ( pVfs.iVersion >= 2 && pVfs.xCurrentTimeInt64 != null ) { rc = pVfs.xCurrentTimeInt64( pVfs, ref pTimeOut ); } else { double r = 0; rc = pVfs.xCurrentTime( pVfs, ref r ); pTimeOut = (sqlite3_int64)( r * 86400000.0 ); } return rc; } static int sqlite3OsOpenMalloc( ref sqlite3_vfs pVfs, string zFile, ref sqlite3_file ppFile, int flags, ref int pOutFlags ) { int rc = SQLITE_NOMEM; sqlite3_file pFile; pFile = new sqlite3_file(); //sqlite3Malloc(ref pVfs.szOsFile); if ( pFile != null ) { rc = sqlite3OsOpen( pVfs, zFile, pFile, flags, ref pOutFlags ); if ( rc != SQLITE_OK ) { pFile = null; // was sqlite3DbFree(db,ref pFile); } else { ppFile = pFile; } } return rc; } static int sqlite3OsCloseFree( sqlite3_file pFile ) { int rc = SQLITE_OK; Debug.Assert( pFile != null ); rc = sqlite3OsClose( pFile ); //sqlite3_free( ref pFile ); return rc; } /* ** This function is a wrapper around the OS specific implementation of ** sqlite3_os_init(). The purpose of the wrapper is to provide the ** ability to simulate a malloc failure, so that the handling of an ** error in sqlite3_os_init() by the upper layers can be tested. */ static int sqlite3OsInit() { //void *p = sqlite3_malloc(10); //if( p==null ) return SQLITE_NOMEM; //sqlite3_free(ref p); return sqlite3_os_init(); } /* ** The list of all registered VFS implementations. */ static sqlite3_vfs vfsList; //#define vfsList GLOBAL(sqlite3_vfs *, vfsList) /* ** Locate a VFS by name. If no name is given, simply return the ** first VFS on the list. */ static bool isInit = false; static public sqlite3_vfs sqlite3_vfs_find(string zVfs) { sqlite3_vfs pVfs = null; #if SQLITE_THREADSAFE sqlite3_mutex mutex; #endif #if !SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if ( rc != 0 ) return null; #endif #if SQLITE_THREADSAFE mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif sqlite3_mutex_enter( mutex ); for ( pVfs = vfsList; pVfs != null; pVfs = pVfs.pNext ) { if ( zVfs == null || zVfs == "" ) break; if ( zVfs == pVfs.zName ) break; //strcmp(zVfs, pVfs.zName) == null) break; } sqlite3_mutex_leave( mutex ); return pVfs; } /* ** Unlink a VFS from the linked list */ static void vfsUnlink( sqlite3_vfs pVfs ) { Debug.Assert( sqlite3_mutex_held( sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ) ) ); if ( pVfs == null ) { /* No-op */ } else if ( vfsList == pVfs ) { vfsList = pVfs.pNext; } else if ( vfsList != null ) { sqlite3_vfs p = vfsList; while ( p.pNext != null && p.pNext != pVfs ) { p = p.pNext; } if ( p.pNext == pVfs ) { p.pNext = pVfs.pNext; } } } /* ** Register a VFS with the system. It is harmless to register the same ** VFS multiple times. The new VFS becomes the default if makeDflt is ** true. */ static public int sqlite3_vfs_register( sqlite3_vfs pVfs, int makeDflt ) { sqlite3_mutex mutex; #if !SQLITE_OMIT_AUTOINIT int rc = sqlite3_initialize(); if ( rc != 0 ) return rc; #endif mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); sqlite3_mutex_enter( mutex ); vfsUnlink( pVfs ); if ( makeDflt != 0 || vfsList == null ) { pVfs.pNext = vfsList; vfsList = pVfs; } else { pVfs.pNext = vfsList.pNext; vfsList.pNext = pVfs; } Debug.Assert( vfsList != null ); sqlite3_mutex_leave( mutex ); return SQLITE_OK; } /* ** Unregister a VFS so that it is no longer accessible. */ static int sqlite3_vfs_unregister( sqlite3_vfs pVfs ) { #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #endif sqlite3_mutex_enter( mutex ); vfsUnlink( pVfs ); sqlite3_mutex_leave( mutex ); return SQLITE_OK; } } }
using System.Diagnostics; using System; using GuiLabs.Canvas.Shapes; using GuiLabs.Canvas.DrawStyle; namespace GuiLabs.Canvas { [DebuggerStepThrough] public class Rect : IHasBounds { #region ctors public Rect() { Location = new Point(0, 0); Size = new Point(0, 0); } public Rect(Point NewLocation, Point NewSize) { Location = NewLocation; Size = NewSize; if (Location == null) Location = new Point(0, 0); if (Size == null) Size = new Point(0, 0); } public Rect(System.Drawing.Rectangle r) { Location = new Point(r.Left, r.Top); Size = new Point(r.Width, r.Height); } public Rect(Rect r) { Location = new Point(r.Location); Size = new Point(r.Size); } public Rect(int x, int y, int width, int height) { Location = new Point(x, y); Size = new Point(width, height); } #endregion public Rect Clone() { return new Rect(this); } #region Location & Size private Point mLocation; public Point Location { get { return mLocation; } set { mLocation = value; } } private Point mSize; public Point Size { get { return mSize; } set { mSize = value; } } #endregion public Rect AddMargins(FourSideValues margins) { return new Rect( this.Left - margins.Left, this.Top - margins.Top, this.Width + margins.LeftAndRight, this.Height + margins.TopAndBottom); } public int Width { get { return Size.X; } set { Size.X = value; } } public int Height { get { return Size.Y; } set { Size.Y = value; } } #region Infos: Left, Top, Right, Bottom, CenterX, CenterY public int Left { get { return mLocation.X; } set { mLocation.X = value; } } public int Top { get { return mLocation.Y; } set { mLocation.Y = value; } } public int Right { get { return mLocation.X + mSize.X; } } public int Bottom { get { return mLocation.Y + mSize.Y; } } public int CenterX { get { return Location.X + Size.X / 2; } } public int CenterY { get { return Location.Y + Size.Y / 2; } } public int HalfSizeX { get { return Size.X / 2; } } public int HalfSizeY { get { return Size.Y / 2; } } #endregion #region Set public void Set(Rect R) { this.Location.Set(R.Location); this.Size.Set(R.Size); } public void Set(Point location, Point size) { this.Location.Set(location); this.Size.Set(size); } public void Set(int x, int y, int width, int height) { this.Location.Set(x, y); this.Size.Set(width, height); } public void Set(System.Drawing.Rectangle dotnetRect) { this.Location.X = dotnetRect.Left; this.Location.Y = dotnetRect.Top; this.Size.X = dotnetRect.Width; this.Size.Y = dotnetRect.Height; } public void Set0() { this.Location.Set0(); this.Size.Set0(); } #endregion #region HitTest public bool HitTest(Point HitPoint) { return HitTest(HitPoint.X, HitPoint.Y); } public bool HitTest(int x, int y) { return ( (x >= this.Location.X) && (x <= this.Right) && (y >= this.Location.Y) && (y <= this.Bottom) ); } public bool HitTestX(int x) { return ( (x >= this.Location.X) && (x <= this.Right) ); } public bool HitTestY(int y) { return ( (y >= this.Location.Y) && (y <= this.Bottom) ); } public bool HitTestWithMargin(int x, int y, GuiLabs.Canvas.DrawStyle.FourSideValues margins) { return ( (x >= this.Left - margins.Left) && (x <= this.Right + margins.Right) && (y >= this.Top - margins.Top) && (y <= this.Bottom + margins.Bottom) ); } public bool HitTestWithMarginX(int x, GuiLabs.Canvas.DrawStyle.FourSideValues margins) { return ( (x >= this.Location.X - margins.Left) && (x <= this.Right + margins.Right) ); } public bool HitTestWithMarginY(int y, GuiLabs.Canvas.DrawStyle.FourSideValues margins) { return ( (y >= this.Location.Y - margins.Top) && (y <= this.Bottom + margins.Bottom) ); } #endregion public bool Contains(Rect inner) { return inner.Location.X >= this.Location.X && inner.Location.Y >= this.Location.Y && inner.Right <= this.Right && inner.Bottom <= this.Bottom; } public enum RectangleRelativePosition { FullyContaining = 0, FullyBefore = 1, IntersectingBeginning = 2, FullyInside = 3, IntersectingEnd = 4, FullyAfter = 5 } public RectangleRelativePosition RelativeToRectY(Rect Reference) { int y1 = Reference.Location.Y; int y2 = Reference.Bottom; int top = this.Location.Y; int bottom = this.Bottom; if (top >= y2) return RectangleRelativePosition.FullyAfter; if (bottom <= y1) return RectangleRelativePosition.FullyBefore; if (top < y1) { if (bottom <= y2) return RectangleRelativePosition.IntersectingBeginning; return RectangleRelativePosition.FullyContaining; } else // if (top >= y1) { if (bottom > y2) return RectangleRelativePosition.IntersectingEnd; return RectangleRelativePosition.FullyInside; } } public bool IntersectsRectX(Rect Reference) { int x1 = Reference.Location.X; int x2 = Reference.Right; int left = this.Location.X; int right = this.Right; return (right > x1 && left < x2); } public bool IntersectsRectY(Rect Reference) { int y1 = Reference.Location.Y; int y2 = Reference.Bottom; int top = this.Location.Y; int bottom = this.Bottom; return (bottom > y1 && top < y2); } public bool IntersectsRect(Rect Reference) { return IntersectsRectX(Reference) && IntersectsRectY(Reference); } public void EnsurePositiveSize() { EnsurePositiveSizeX(); EnsurePositiveSizeY(); } public void EnsurePositiveSizeX() { int width = this.Size.X; if (width < 0) { this.Location.X += width; this.Size.X = -width; } } public void EnsurePositiveSizeY() { int height = this.Size.Y; if (height < 0) { this.Location.Y += height; this.Size.Y = -height; } } public void Unite(Rect ToContain) { int x1 = ToContain.mLocation.X; int y1 = ToContain.mLocation.Y; int x2 = ToContain.Right; int y2 = ToContain.Bottom; if (x1 < this.Location.X) { this.Size.X += this.Location.X - x1; this.Location.X = x1; } if (y1 < this.Location.Y) { this.Size.Y += this.Location.Y - y1; this.Location.Y = y1; } if (x2 > this.Right) { this.Size.X = x2 - this.Location.X; } if (y2 > this.Bottom) { this.Size.Y = y2 - this.Location.Y; } } public System.Drawing.Rectangle GetRectangle() { return new System.Drawing.Rectangle(mLocation.X, mLocation.Y, mSize.X, mSize.Y); } [CLSCompliant(false)] public GuiLabs.Utils.API.RECT ToRECT() { GuiLabs.Utils.API.RECT result; result.Left = this.Location.X; result.Top = this.Location.Y; result.Right = this.Right; result.Bottom = this.Bottom; return result; } public static Rect NullRect { get { return new Rect(); } } Rect IHasBounds.Bounds { get { return this; } set { this.Set(value); } } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace Helper.CreateSiteCollection { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
//------------------------------------------------------------------------- // <copyright file="ChunkBuilderVisitor.cs"> // Copyright 2008-2010 Louis DeJardin - http://whereslou.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Louis DeJardin</author> // <author>maxild</author> // <author>John Gietzen</author> //------------------------------------------------------------------------- namespace Spark.Compiler.NodeVisitors { using System; using System.Collections.Generic; using System.Linq; using Spark.Parser; using Spark.Parser.Code; using Spark.Parser.Markup; public class ChunkBuilderVisitor : AbstractNodeVisitor { private readonly IDictionary<Node, Paint<Node>> _nodePaint; private readonly IDictionary<string, Action<SpecialNode, SpecialNodeInspector>> _specialNodeMap; public IList<Chunk> Chunks { get; set; } private IDictionary<string, IList<Chunk>> SectionChunks { get; set; } public IDictionary<string, Action<SpecialNode, SpecialNodeInspector>> SpecialNodeMap { get { return _specialNodeMap; } } class Frame : IDisposable { private readonly ChunkBuilderVisitor _visitor; private readonly IList<Chunk> _chunks; private readonly IDictionary<string, IList<Chunk>> _sectionChunks; public Frame(ChunkBuilderVisitor visitor, IList<Chunk> chunks) : this(visitor, chunks, null) { } public Frame(ChunkBuilderVisitor visitor, IList<Chunk> chunks, IDictionary<string, IList<Chunk>> sectionChunks) { _visitor = visitor; _chunks = _visitor.Chunks; _sectionChunks = _visitor.SectionChunks; _visitor.Chunks = chunks; _visitor.SectionChunks = sectionChunks; } public void Dispose() { _visitor.Chunks = _chunks; _visitor.SectionChunks = _sectionChunks; } } public ChunkBuilderVisitor(VisitorContext context) : base(context) { _nodePaint = Context.Paint.OfType<Paint<Node>>().ToDictionary(paint => paint.Value); Chunks = new List<Chunk>(); _specialNodeMap = new Dictionary<string, Action<SpecialNode, SpecialNodeInspector>> { {"var", VisitVar}, {"def", VisitVar}, {"default", VisitDefault}, {"global", (n,i)=>VisitGlobal(n)}, {"viewdata", (n,i)=>VisitViewdata(i)}, {"set", (n,i)=>VisitSet(i)}, {"for", VisitFor}, {"test", VisitIf}, {"if", VisitIf}, {"else", (n,i)=>VisitElse(i)}, {"elseif", VisitElseIf}, {"unless", VisitUnless}, {"content", (n,i)=>VisitContent(i)}, {"use", VisitUse}, {"macro", (n,i)=>VisitMacro(i)}, {"render", VisitRender}, {"segment", VisitSection}, {"cache", VisitCache}, {"markdown", VisitMarkdown}, {"ignore", VisitIgnore} }; if(context.ParseSectionTagAsSegment) _specialNodeMap.Add("section", VisitSection); } private Position Locate(Node expressionNode) { Paint<Node> paint; Node scan = expressionNode; while (scan != null) { if (_nodePaint.TryGetValue(scan, out paint)) return paint.Begin; scan = scan.OriginalNode; } return null; } private Position LocateEnd(Node expressionNode) { Paint<Node> paint; Node scan = expressionNode; while (scan != null) { if (_nodePaint.TryGetValue(scan, out paint)) return paint.End; scan = scan.OriginalNode; } return null; } public override IList<Node> Nodes { get { throw new NotImplementedException(); } } protected override void Visit(TextNode textNode) { AddLiteral(textNode.Text); } private void AddLiteral(string text) { var sendLiteral = Chunks.LastOrDefault() as SendLiteralChunk; if (sendLiteral == null) { sendLiteral = new SendLiteralChunk { Text = text }; Chunks.Add(sendLiteral); } else { sendLiteral.Text += text; } } private void AddUnordered(Chunk chunk) { var sendLiteral = Chunks.LastOrDefault() as SendLiteralChunk; if (sendLiteral == null) { Chunks.Add(chunk); } else { Chunks.Insert(Chunks.Count - 1, chunk); } } protected override void Visit(EntityNode entityNode) { AddLiteral("&" + entityNode.Name + ";"); } protected override void Visit(ExpressionNode node) { Chunks.Add(new SendExpressionChunk { Code = node.Code, Position = Locate(node), SilentNulls = node.SilentNulls, AutomaticallyEncode = node.AutomaticEncoding }); } protected override void Visit(StatementNode node) { //REFACTOR: what is UnarmorCode doing at this point? Chunks.Add(new CodeStatementChunk { Code = node.Code, Position = Locate(node) }); } protected override void Visit(IndentationNode node) { } protected override void Visit(DoctypeNode docTypeNode) { //[28] doctypedecl ::= '<!DOCTYPE' S Name (S ExternalID)? S? ('[' intSubset ']' S?)? '>' //[75] ExternalID ::= 'SYSTEM' S SystemLiteral | 'PUBLIC' S PubidLiteral S SystemLiteral //[12] PubidLiteral ::= '"' PubidChar* '"' | "'" (PubidChar - "'")* "'" //[11] SystemLiteral ::= ('"' [^"]* '"') | ("'" [^']* "'") if (docTypeNode.ExternalId == null) { AddLiteral(string.Format("<!DOCTYPE {0}>", docTypeNode.Name)); } else if (docTypeNode.ExternalId.ExternalIdType == "SYSTEM") { char systemQuote = docTypeNode.ExternalId.SystemId.Contains("\"") ? '\'' : '\"'; AddLiteral(string.Format("<!DOCTYPE {0} SYSTEM {2}{1}{2}>", docTypeNode.Name, docTypeNode.ExternalId.SystemId, systemQuote)); } else if (docTypeNode.ExternalId.ExternalIdType == "PUBLIC") { char systemQuote = docTypeNode.ExternalId.SystemId.Contains("\"") ? '\'' : '\"'; AddLiteral(string.Format("<!DOCTYPE {0} PUBLIC \"{1}\" {3}{2}{3}>", docTypeNode.Name, docTypeNode.ExternalId.PublicId, docTypeNode.ExternalId.SystemId, systemQuote)); } } protected override void Visit(XMLDeclNode node) { //[23] XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>' //[24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"') //[80] EncodingDecl ::= S 'encoding' Eq ('"' EncName '"' | "'" EncName "'" ) //[32] SDDecl ::= S 'standalone' Eq (("'" ('yes' | 'no') "'") | ('"' ('yes' | 'no') '"')) var encoding = ""; if (!string.IsNullOrEmpty(node.Encoding)) { if (node.Encoding.Contains("\"")) encoding = string.Concat(" encoding='", node.Encoding, "'"); else encoding = string.Concat(" encoding=\"", node.Encoding, "\""); } var standalone = ""; if (!string.IsNullOrEmpty(node.Standalone)) standalone = string.Concat(" standalone=\"", node.Standalone, "\""); AddLiteral(string.Concat("<?xml version=\"1.0\"", encoding, standalone, " ?>")); } protected override void Visit(ProcessingInstructionNode node) { //[16] PI ::= '<?' PITarget (S (Char* - (Char* '?>' Char*)))? '?>' if (string.IsNullOrEmpty(node.Body)) AddLiteral(string.Concat("<?", node.Name, "?>")); else AddLiteral(string.Concat("<?", node.Name, " ", node.Body, "?>")); } protected override void Visit(ElementNode node) { AddLiteral(node.PreceedingWhitespace + "<" + node.Name); foreach (var attribute in node.Attributes) Accept(attribute); if (node.IsEmptyElement) { bool isVoidElement = voidElements.Contains(node.Name); AddLiteral(isVoidElement ? "/>" : "></" + node.Name + ">"); } else { AddLiteral(">"); } } protected override void Visit(AttributeNode attributeNode) { var accumulatedNodes = new List<Node>(); var processedNodes = new List<Node>(); foreach (var node in attributeNode.Nodes) { if (node is ConditionNode) { // condition nodes take the prior unconditional nodes as content var conditionNode = (ConditionNode)node; MovePriorNodesUnderCondition(conditionNode, accumulatedNodes); // prior nodes and condition are set for output processedNodes.AddRange(accumulatedNodes); processedNodes.Add(conditionNode); accumulatedNodes.Clear(); } else { // other types add to the unconditional list accumulatedNodes.Add(node); } } processedNodes.AddRange(accumulatedNodes); var allNodesAreConditional = processedNodes.All(node => node is ConditionNode); if (allNodesAreConditional == false || processedNodes.Any() == false) { // This attribute may not disapper - send it literally AddLiteral(string.Format(" {0}={1}", attributeNode.Name, attributeNode.QuotChar)); foreach (var node in processedNodes) Accept(node); AddLiteral(attributeNode.QuotChar.ToString()); } else { var scope = new ScopeChunk(); scope.Body.Add(new LocalVariableChunk { Name = "__just__once__", Value = new Snippets("0") }); _sendAttributeOnce = new ConditionalChunk { Type = ConditionalType.If, Condition = new Snippets("__just__once__ < 1") }; _sendAttributeOnce.Body.Add(new SendLiteralChunk { Text = " " + attributeNode.Name + "=\"" }); _sendAttributeIncrement = new AssignVariableChunk { Name = "__just__once__", Value = "1" }; Chunks.Add(scope); using (new Frame(this, scope.Body)) { foreach (var node in processedNodes) Accept(node); } _sendAttributeOnce = null; _sendAttributeIncrement = null; var ifWasSent = new ConditionalChunk { Type = ConditionalType.If, Condition = new Snippets("__just__once__ > 0") }; scope.Body.Add(ifWasSent); ifWasSent.Body.Add(new SendLiteralChunk { Text = "\"" }); } } private static void MovePriorNodesUnderCondition(ConditionNode condition, ICollection<Node> priorNodes) { while (priorNodes.Count != 0) { var priorNode = priorNodes.Last(); priorNodes.Remove(priorNode); if (!(priorNode is TextNode)) { condition.Nodes.Insert(0, priorNode); continue; } // for text, extend back to and include the last whitespace var priorText = ((TextNode)priorNode).Text; var finalPieceIndex = priorText.LastIndexOfAny(new[] { ' ', '\t', '\r', '\n' }) + 1; if (finalPieceIndex == 0) { condition.Nodes.Insert(0, priorNode); continue; } while (finalPieceIndex != 0 && char.IsWhiteSpace(priorText[finalPieceIndex - 1])) --finalPieceIndex; condition.Nodes.Insert(0, new TextNode(priorText.Substring(finalPieceIndex)) { OriginalNode = priorNode }); if (finalPieceIndex != 0) { priorNodes.Add(new TextNode(priorText.Substring(0, finalPieceIndex)) { OriginalNode = priorNode }); } return; } } private ConditionalChunk _sendAttributeOnce; private Chunk _sendAttributeIncrement; private static readonly string[] voidElements = new[] { "area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr" }; protected override void Visit(ConditionNode conditionNode) { var conditionChunk = new ConditionalChunk { Condition = conditionNode.Code, Type = ConditionalType.If, Position = Locate(conditionNode) }; Chunks.Add(conditionChunk); if (_sendAttributeOnce != null) conditionChunk.Body.Add(_sendAttributeOnce); if (_sendAttributeIncrement != null) conditionChunk.Body.Add(_sendAttributeIncrement); using (new Frame(this, conditionChunk.Body)) { Accept(conditionNode.Nodes); } } protected override void Visit(EndElementNode node) { AddLiteral(node.PreceedingWhitespace + "</" + node.Name + ">"); } protected override void Visit(CommentNode commentNode) { AddLiteral("<!--" + commentNode.Text + "-->"); } protected override void Visit(SpecialNode specialNode) { string nqName = NameUtility.GetName(specialNode.Element.Name); if (!SpecialNodeMap.ContainsKey(nqName)) { throw new CompilerException(string.Format("Unknown special node {0}", specialNode.Element.Name)); } var action = SpecialNodeMap[nqName]; action(specialNode, new SpecialNodeInspector(specialNode)); } Snippets AsCode(AttributeNode attr) { var begin = Locate(attr.Nodes.FirstOrDefault()); var end = LocateEnd(attr.Nodes.LastOrDefault()); if (begin == null || end == null) { begin = new Position(new SourceContext(attr.Value)); end = begin.Advance(begin.PotentialLength()); } return Context.SyntaxProvider.ParseFragment(begin, end); } Snippets AsTextOrientedCode(AttributeNode attr) { return Context.AttributeBehaviour == AttributeBehaviour.CodeOriented ? AsCode(attr) : attr.AsCodeInverted(); } private void VisitMacro(SpecialNodeInspector inspector) { var name = inspector.TakeAttribute("name"); var macro = new MacroChunk { Name = name.Value, Position = Locate(inspector.OriginalNode) }; foreach (var attr in inspector.Attributes) { macro.Parameters.Add(new MacroParameter { Name = attr.Name, Type = AsCode(attr) }); } AddUnordered(macro); using (new Frame(this, macro.Body)) { Accept(inspector.Body); } } private void VisitUse(SpecialNode specialNode, SpecialNodeInspector inspector) { var file = inspector.TakeAttribute("file"); if (file != null) { var scope = new ScopeChunk { Position = Locate(inspector.OriginalNode) }; Chunks.Add(scope); using (new Frame(this, scope.Body)) { foreach (var attr in inspector.Attributes) { Chunks.Add(new LocalVariableChunk { Name = attr.Name, Value = AsTextOrientedCode(attr), Position = Locate(attr) }); } var useFileChunk = new RenderPartialChunk { Name = file.Value, Position = Locate(inspector.OriginalNode) }; Chunks.Add(useFileChunk); using (new Frame(this, useFileChunk.Body, useFileChunk.Sections)) { Accept(inspector.Body); } } } else { var contentAttr = inspector.TakeAttribute("content"); var namespaceAttr = inspector.TakeAttribute("namespace"); var assemblyAttr = inspector.TakeAttribute("assembly"); var importAttr = inspector.TakeAttribute("import"); var masterAttr = inspector.TakeAttribute("master"); var pageBaseTypeAttr = inspector.TakeAttribute("pageBaseType"); if (contentAttr != null) { var useContentChunk = new UseContentChunk { Name = contentAttr.Value, Position = Locate(inspector.OriginalNode) }; Chunks.Add(useContentChunk); using (new Frame(this, useContentChunk.Default)) { Accept(specialNode.Body); } } else if (namespaceAttr != null || assemblyAttr != null) { if (namespaceAttr != null) { var useNamespaceChunk = new UseNamespaceChunk { Namespace = AsCode(namespaceAttr) }; AddUnordered(useNamespaceChunk); } if (assemblyAttr != null) { var useAssemblyChunk = new UseAssemblyChunk { Assembly = assemblyAttr.Value }; AddUnordered(useAssemblyChunk); } } else if (importAttr != null) { var useImportChunk = new UseImportChunk { Name = importAttr.Value }; AddUnordered(useImportChunk); } else if (masterAttr != null) { var useMasterChunk = new UseMasterChunk { Name = masterAttr.Value }; AddUnordered(useMasterChunk); } else if (pageBaseTypeAttr != null) { var usePageBaseTypeChunk = new PageBaseTypeChunk { BaseClass = AsCode(pageBaseTypeAttr) }; AddUnordered(usePageBaseTypeChunk); } else { throw new CompilerException("Special node use had no understandable attributes"); } } } private void VisitRender(SpecialNode node, SpecialNodeInspector inspector) { var partial = inspector.TakeAttribute("partial"); if (partial != null) { var scope = new ScopeChunk { Position = Locate(inspector.OriginalNode) }; Chunks.Add(scope); using (new Frame(this, scope.Body)) { foreach (var attr in inspector.Attributes) { Chunks.Add(new LocalVariableChunk { Name = attr.Name, Value = AsTextOrientedCode(attr), Position = Locate(attr) }); } var renderPartial = new RenderPartialChunk { Name = partial.Value, Position = Locate(inspector.OriginalNode) }; Chunks.Add(renderPartial); using (new Frame(this, renderPartial.Body, renderPartial.Sections)) { Accept(inspector.Body); } } } else { var sectionAttr = inspector.TakeAttribute("segment"); if(Context.ParseSectionTagAsSegment && sectionAttr == null) sectionAttr = inspector.TakeAttribute("section"); string sectionName = null; if (sectionAttr != null) sectionName = sectionAttr.Value; var scope = new ScopeChunk { Position = Locate(inspector.OriginalNode) }; Chunks.Add(scope); using (new Frame(this, scope.Body)) { foreach (var attr in inspector.Attributes) { Chunks.Add(new LocalVariableChunk { Name = attr.Name, Value = AsTextOrientedCode(attr), Position = Locate(attr) }); } var render = new RenderSectionChunk { Name = sectionName }; Chunks.Add(render); using (new Frame(this, render.Default)) { Accept(inspector.Body); } } } } private void VisitSection(SpecialNode node, SpecialNodeInspector inspector) { if (SectionChunks == null) throw new CompilerException("Section cannot be used at this location", Locate(node.Element)); var name = inspector.TakeAttribute("name"); if (name == null) throw new CompilerException("Section element must have a name attribute", Locate(node.Element)); IList<Chunk> sectionChunks; if (!SectionChunks.TryGetValue(name.Value, out sectionChunks)) { sectionChunks = new List<Chunk>(); SectionChunks.Add(name.Value, sectionChunks); } var scope = new ScopeChunk { Position = Locate(inspector.OriginalNode) }; sectionChunks.Add(scope); using (new Frame(this, scope.Body)) { foreach (var attr in inspector.Attributes) { Chunks.Add(new LocalVariableChunk { Name = attr.Name, Value = AsCode(attr), Position = Locate(attr) }); } Accept(inspector.Body); } } private void VisitContent(SpecialNodeInspector inspector) { var nameAttr = inspector.TakeAttribute("name"); var varAttr = inspector.TakeAttribute("var"); var defAttr = inspector.TakeAttribute("def"); var setAttr = inspector.TakeAttribute("set"); if (nameAttr != null) { var contentChunk = new ContentChunk { Name = nameAttr.Value, Position = Locate(inspector.OriginalNode) }; Chunks.Add(contentChunk); using (new Frame(this, contentChunk.Body)) Accept(inspector.Body); } else if (varAttr != null || defAttr != null) { var variableChunk = new LocalVariableChunk { Name = AsCode(varAttr ?? defAttr), Type = "string" }; Chunks.Add(variableChunk); var contentSetChunk = new ContentSetChunk { Variable = variableChunk.Name, Position = Locate(inspector.OriginalNode) }; Chunks.Add(contentSetChunk); using (new Frame(this, contentSetChunk.Body)) Accept(inspector.Body); } else if (setAttr != null) { var addAttr = inspector.TakeAttribute("add"); var contentSetChunk = new ContentSetChunk { Variable = AsCode(setAttr), Position = Locate(inspector.OriginalNode) }; if (addAttr != null) { if (addAttr.Value == "before") contentSetChunk.AddType = ContentAddType.InsertBefore; else if (addAttr.Value == "after") contentSetChunk.AddType = ContentAddType.AppendAfter; else if (addAttr.Value == "replace") contentSetChunk.AddType = ContentAddType.Replace; else throw new CompilerException("add attribute must be 'before', 'after', or 'replace"); } Chunks.Add(contentSetChunk); using (new Frame(this, contentSetChunk.Body)) Accept(inspector.Body); } else { throw new CompilerException("content element must have name, var, def, or set attribute"); } } private void VisitCache(SpecialNode specialNode, SpecialNodeInspector inspector) { var keyAttr = inspector.TakeAttribute("key"); var expiresAttr = inspector.TakeAttribute("expires"); var signalAttr = inspector.TakeAttribute("signal"); var chunk = new CacheChunk { Position = Locate(specialNode.Element) }; if (keyAttr != null) chunk.Key = AsCode(keyAttr); else chunk.Key = "\"\""; if (expiresAttr != null) chunk.Expires = AsCode(expiresAttr); else chunk.Expires = ""; if (signalAttr != null) chunk.Signal = AsCode(signalAttr); else chunk.Signal = ""; Chunks.Add(chunk); using (new Frame(this, chunk.Body)) Accept(inspector.Body); } private void VisitIf(SpecialNode specialNode, SpecialNodeInspector inspector) { var conditionAttr = inspector.TakeAttribute("condition") ?? inspector.TakeAttribute("if"); var onceAttr = inspector.TakeAttribute("once"); if (conditionAttr == null && onceAttr == null) { throw new CompilerException("Element must contain an if, condition, or once attribute"); } Frame ifFrame = null; if (conditionAttr != null) { var ifChunk = new ConditionalChunk { Type = ConditionalType.If, Condition = AsCode(conditionAttr), Position = Locate(inspector.OriginalNode) }; Chunks.Add(ifChunk); ifFrame = new Frame(this, ifChunk.Body); } Frame onceFrame = null; if (onceAttr != null) { var onceChunk = new ConditionalChunk { Type = ConditionalType.Once, Condition = onceAttr.AsCodeInverted(), Position = Locate(inspector.OriginalNode) }; Chunks.Add(onceChunk); onceFrame = new Frame(this, onceChunk.Body); } Accept(specialNode.Body); if (onceFrame != null) onceFrame.Dispose(); if (ifFrame != null) ifFrame.Dispose(); } private void VisitElse(SpecialNodeInspector inspector) { if (!SatisfyElsePrecondition()) throw new CompilerException("An 'else' may only follow an 'if' or 'elseif'."); var ifAttr = inspector.TakeAttribute("if"); if (ifAttr == null) { var elseChunk = new ConditionalChunk { Type = ConditionalType.Else, Position = Locate(inspector.OriginalNode) }; Chunks.Add(elseChunk); using (new Frame(this, elseChunk.Body)) Accept(inspector.Body); } else { var elseIfChunk = new ConditionalChunk { Type = ConditionalType.ElseIf, Condition = AsCode(ifAttr), Position = Locate(inspector.OriginalNode) }; Chunks.Add(elseIfChunk); using (new Frame(this, elseIfChunk.Body)) Accept(inspector.Body); } } private void VisitElseIf(SpecialNode specialNode, SpecialNodeInspector inspector) { if (!SatisfyElsePrecondition()) throw new CompilerException("An 'elseif' may only follow an 'if' or 'elseif'."); var conditionAttr = inspector.TakeAttribute("condition"); var elseIfChunk = new ConditionalChunk { Type = ConditionalType.ElseIf, Condition = AsCode(conditionAttr), Position = Locate(inspector.OriginalNode) }; Chunks.Add(elseIfChunk); using (new Frame(this, elseIfChunk.Body)) Accept(specialNode.Body); } private void VisitUnless(SpecialNode specialNode, SpecialNodeInspector inspector) { var conditionAttr = inspector.TakeAttribute("condition") ?? inspector.TakeAttribute("unless"); var unlessChunk = new ConditionalChunk { Type = ConditionalType.Unless, Condition = AsCode(conditionAttr), Position = Locate(inspector.OriginalNode) }; Chunks.Add(unlessChunk); using (new Frame(this, unlessChunk.Body)) Accept(specialNode.Body); } private void VisitFor(SpecialNode specialNode, SpecialNodeInspector inspector) { var eachAttr = inspector.TakeAttribute("each"); var forEachChunk = new ForEachChunk { Code = AsCode(eachAttr), Position = Locate(specialNode.Element) }; Chunks.Add(forEachChunk); using (new Frame(this, forEachChunk.Body)) { foreach (var attr in inspector.Attributes) { Chunks.Add(new AssignVariableChunk { Name = attr.Name, Value = AsCode(attr), Position = Locate(attr) }); } Accept(specialNode.Body); } } private void VisitSet(SpecialNodeInspector inspector) { foreach (var attr in inspector.Attributes) { Chunks.Add(new AssignVariableChunk { Name = attr.Name, Value = AsTextOrientedCode(attr), Position = Locate(attr) }); } } private void VisitViewdata(SpecialNodeInspector inspector) { var defaultAttr = inspector.TakeAttribute("default"); Snippets defaultValue = null; if (defaultAttr != null) defaultValue = AsTextOrientedCode(defaultAttr); var modelAttr = inspector.TakeAttribute("model"); if (modelAttr != null) { var typeInspector = new TypeInspector(AsCode(modelAttr)); AddUnordered(new ViewDataModelChunk { TModel = typeInspector.Type, TModelAlias = typeInspector.Name }); } foreach (var attr in inspector.Attributes) { var typeInspector = new TypeInspector(AsCode(attr)); AddUnordered(new ViewDataChunk { Type = typeInspector.Type, Name = typeInspector.Name ?? attr.Name, Key = attr.Name, Default = defaultValue, Position = Locate(attr) }); } } private void VisitGlobal(SpecialNode specialNode) { var typeAttr = specialNode.Element.Attributes.FirstOrDefault(attr => attr.Name == "type"); var type = typeAttr != null ? AsCode(typeAttr) : (Snippets)"object"; foreach (var attr in specialNode.Element.Attributes.Where(a => a != typeAttr)) { AddUnordered(new GlobalVariableChunk { Type = type, Name = attr.Name, Value = AsTextOrientedCode(attr) }); } } private void VisitVar(SpecialNode specialNode, SpecialNodeInspector inspector) { Frame frame = null; if (!specialNode.Element.IsEmptyElement) { var scope = new ScopeChunk { Position = Locate(specialNode.Element) }; Chunks.Add(scope); frame = new Frame(this, scope.Body); } var typeAttr = inspector.TakeAttribute("type"); var type = typeAttr != null ? AsCode(typeAttr) : (Snippets)"var"; foreach (var attr in inspector.Attributes) { Chunks.Add(new LocalVariableChunk { Type = type, Name = attr.Name, Value = AsTextOrientedCode(attr), Position = Locate(attr) }); } Accept(specialNode.Body); if (frame != null) frame.Dispose(); } private void VisitDefault(SpecialNode specialNode, SpecialNodeInspector inspector) { Frame frame = null; if (!specialNode.Element.IsEmptyElement) { var scope = new ScopeChunk { Position = Locate(specialNode.Element) }; Chunks.Add(scope); frame = new Frame(this, scope.Body); } var typeAttr = inspector.TakeAttribute("type"); var type = typeAttr != null ? AsCode(typeAttr) : (Snippets)"var"; foreach (var attr in inspector.Attributes) { Chunks.Add(new DefaultVariableChunk { Type = type, Name = attr.Name, Value = AsTextOrientedCode(attr), Position = Locate(attr) }); } Accept(specialNode.Body); if (frame != null) frame.Dispose(); } private void VisitMarkdown(SpecialNode specialNode, SpecialNodeInspector inspector) { var markdownChunk = new MarkdownChunk(); Chunks.Add(markdownChunk); using (new Frame(this, markdownChunk.Body)) { Accept(inspector.Body); } } private void VisitIgnore(SpecialNode specialNode, SpecialNodeInspector inspector) { Accept(specialNode.Body); } private bool SatisfyElsePrecondition() { var lastChunk = Chunks.LastOrDefault(); // remove any literal that's entirely whitespace if (lastChunk is SendLiteralChunk) { var literal = ((SendLiteralChunk)lastChunk).Text; if (string.IsNullOrEmpty(literal.Trim())) { Chunks.Remove(lastChunk); lastChunk = Chunks.LastOrDefault(); } } if (lastChunk is ConditionalChunk) { var conditionalType = ((ConditionalChunk)lastChunk).Type; if (conditionalType == ConditionalType.If || conditionalType == ConditionalType.ElseIf) { return true; } } return false; } static string UnarmorCode(string code) { return code.Replace("[[", "<").Replace("]]", ">"); } protected override void Visit(ExtensionNode extensionNode) { var extensionChunk = new ExtensionChunk { Extension = extensionNode.Extension, Position = Locate(extensionNode) }; Chunks.Add(extensionChunk); using (new Frame(this, extensionChunk.Body)) extensionNode.Extension.VisitNode(this, extensionNode.Body, Chunks); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using GitVersion.Common; using GitVersion.Configuration; using GitVersion.Logging; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; namespace GitVersion { public class RepositoryStore : IRepositoryStore { private readonly Dictionary<IBranch, List<BranchCommit>> mergeBaseCommitsCache = new(); private readonly Dictionary<Tuple<IBranch, IBranch>, ICommit> mergeBaseCache = new(); private readonly Dictionary<IBranch, List<SemanticVersion>> semanticVersionTagsOnBranchCache = new(); private const string MissingTipFormat = "{0} has no tip. Please see http://example.com/docs for information on how to fix this."; private readonly ILog log; private readonly IGitRepository repository; public RepositoryStore(ILog log, IGitRepository repository) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.repository = repository ?? throw new ArgumentNullException(nameof(log)); } /// <summary> /// Find the merge base of the two branches, i.e. the best common ancestor of the two branches' tips. /// </summary> public ICommit FindMergeBase(IBranch branch, IBranch otherBranch) { var key = Tuple.Create(branch, otherBranch); if (mergeBaseCache.ContainsKey(key)) { log.Debug($"Cache hit for merge base between '{branch}' and '{otherBranch}'."); return mergeBaseCache[key]; } using (log.IndentLog($"Finding merge base between '{branch}' and '{otherBranch}'.")) { // Other branch tip is a forward merge var commitToFindCommonBase = otherBranch.Tip; var commit = branch.Tip; if (otherBranch.Tip.Parents.Contains(commit)) { commitToFindCommonBase = otherBranch.Tip.Parents.First(); } var findMergeBase = FindMergeBase(commit, commitToFindCommonBase); if (findMergeBase != null) { log.Info($"Found merge base of {findMergeBase}"); // We do not want to include merge base commits which got forward merged into the other branch ICommit forwardMerge; do { // Now make sure that the merge base is not a forward merge forwardMerge = GetForwardMerge(commitToFindCommonBase, findMergeBase); if (forwardMerge != null) { // TODO Fix the logging up in this section var second = forwardMerge.Parents.First(); log.Debug($"Second {second}"); var mergeBase = FindMergeBase(commit, second); if (mergeBase == null) { log.Warning("Could not find mergbase for " + commit); } else { log.Debug($"New Merge base {mergeBase}"); } if (Equals(mergeBase, findMergeBase)) { log.Debug("Breaking"); break; } findMergeBase = mergeBase; commitToFindCommonBase = second; log.Info($"Merge base was due to a forward merge, next merge base is {findMergeBase}"); } } while (forwardMerge != null); } // Store in cache. mergeBaseCache.Add(key, findMergeBase); log.Info($"Merge base of {branch}' and '{otherBranch} is {findMergeBase}"); return findMergeBase; } } public ICommit GetCurrentCommit(IBranch currentBranch, string commitId) { ICommit currentCommit = null; if (!string.IsNullOrWhiteSpace(commitId)) { log.Info($"Searching for specific commit '{commitId}'"); var commit = repository.Commits.FirstOrDefault(c => string.Equals(c.Sha, commitId, StringComparison.OrdinalIgnoreCase)); if (commit != null) { currentCommit = commit; } else { log.Warning($"Commit '{commitId}' specified but not found"); } } if (currentCommit == null) { log.Info("Using latest commit on specified branch"); currentCommit = currentBranch.Tip; } return currentCommit; } public ICommit GetBaseVersionSource(ICommit currentBranchTip) { try { var filter = new CommitFilter { IncludeReachableFrom = currentBranchTip }; var commitCollection = repository.Commits.QueryBy(filter); return commitCollection.First(c => !c.Parents.Any()); } catch (Exception exception) { throw new GitVersionException($"Cannot find commit {currentBranchTip}. Please ensure that the repository is an unshallow clone with `git fetch --unshallow`.", exception); } } public IEnumerable<ICommit> GetMainlineCommitLog(ICommit baseVersionSource, ICommit mainlineTip) { var filter = new CommitFilter { IncludeReachableFrom = mainlineTip, ExcludeReachableFrom = baseVersionSource, SortBy = CommitSortStrategies.Reverse, FirstParentOnly = true }; return repository.Commits.QueryBy(filter); } public IEnumerable<ICommit> GetMergeBaseCommits(ICommit mergeCommit, ICommit mergedHead, ICommit findMergeBase) { var filter = new CommitFilter { IncludeReachableFrom = mergedHead, ExcludeReachableFrom = findMergeBase }; var commitCollection = repository.Commits.QueryBy(filter); var commits = mergeCommit != null ? new[] { mergeCommit }.Union(commitCollection) : commitCollection; return commits; } public IBranch GetTargetBranch(string targetBranchName) { // By default, we assume HEAD is pointing to the desired branch var desiredBranch = repository.Head; // Make sure the desired branch has been specified if (!string.IsNullOrEmpty(targetBranchName)) { // There are some edge cases where HEAD is not pointing to the desired branch. // Therefore it's important to verify if 'currentBranch' is indeed the desired branch. var targetBranch = FindBranch(targetBranchName); // CanonicalName can be "refs/heads/develop", so we need to check for "/{TargetBranch}" as well if (!desiredBranch.Equals(targetBranch)) { // In the case where HEAD is not the desired branch, try to find the branch with matching name desiredBranch = repository.Branches? .Where(b => b.Name.EquivalentTo(targetBranchName)) .OrderBy(b => b.IsRemote) .FirstOrDefault(); // Failsafe in case the specified branch is invalid desiredBranch ??= repository.Head; } } return desiredBranch; } public IBranch FindBranch(string branchName) => repository.Branches.FirstOrDefault(x => x.Name.EquivalentTo(branchName)); public IBranch GetChosenBranch(Config configuration) { var developBranchRegex = configuration.Branches[Config.DevelopBranchKey].Regex; var masterBranchRegex = configuration.Branches[Config.MasterBranchKey].Regex; var chosenBranch = repository.Branches.FirstOrDefault(b => Regex.IsMatch(b.Name.Friendly, developBranchRegex, RegexOptions.IgnoreCase) || Regex.IsMatch(b.Name.Friendly, masterBranchRegex, RegexOptions.IgnoreCase)); return chosenBranch; } public IEnumerable<IBranch> GetBranchesForCommit(ICommit commit) { return repository.Branches.Where(b => !b.IsRemote && Equals(b.Tip, commit)).ToList(); } public IEnumerable<IBranch> GetExcludedInheritBranches(Config configuration) { return repository.Branches.Where(b => { var branchConfig = configuration.GetConfigForBranch(b.Name.WithoutRemote); return branchConfig == null || branchConfig.Increment == IncrementStrategy.Inherit; }).ToList(); } public IEnumerable<IBranch> GetReleaseBranches(IEnumerable<KeyValuePair<string, BranchConfig>> releaseBranchConfig) { return repository.Branches .Where(b => releaseBranchConfig.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value.Regex))); } public IEnumerable<IBranch> ExcludingBranches(IEnumerable<IBranch> branchesToExclude) { return repository.Branches.ExcludeBranches(branchesToExclude); } // TODO Should we cache this? public IEnumerable<IBranch> GetBranchesContainingCommit(ICommit commit, IEnumerable<IBranch> branches = null, bool onlyTrackedBranches = false) { branches ??= repository.Branches.ToList(); static bool IncludeTrackedBranches(IBranch branch, bool includeOnlyTracked) => includeOnlyTracked && branch.IsTracking || !includeOnlyTracked; if (commit == null) { throw new ArgumentNullException(nameof(commit)); } using (log.IndentLog($"Getting branches containing the commit '{commit.Id}'.")) { var directBranchHasBeenFound = false; log.Info("Trying to find direct branches."); // TODO: It looks wasteful looping through the branches twice. Can't these loops be merged somehow? @asbjornu var branchList = branches.ToList(); foreach (var branch in branchList) { if (branch.Tip != null && branch.Tip.Sha != commit.Sha || IncludeTrackedBranches(branch, onlyTrackedBranches)) { continue; } directBranchHasBeenFound = true; log.Info($"Direct branch found: '{branch}'."); yield return branch; } if (directBranchHasBeenFound) { yield break; } log.Info($"No direct branches found, searching through {(onlyTrackedBranches ? "tracked" : "all")} branches."); foreach (var branch in branchList.Where(b => IncludeTrackedBranches(b, onlyTrackedBranches))) { log.Info($"Searching for commits reachable from '{branch}'."); var commits = GetCommitsReacheableFrom(commit, branch); if (!commits.Any()) { log.Info($"The branch '{branch}' has no matching commits."); continue; } log.Info($"The branch '{branch}' has a matching commit."); yield return branch; } } } public Dictionary<string, List<IBranch>> GetMainlineBranches(ICommit commit, IEnumerable<KeyValuePair<string, BranchConfig>> mainlineBranchConfigs) { return repository.Branches .Where(b => { return mainlineBranchConfigs.Any(c => Regex.IsMatch(b.Name.Friendly, c.Value.Regex)); }) .Select(b => new { MergeBase = FindMergeBase(b.Tip, commit), Branch = b }) .Where(a => a.MergeBase != null) .GroupBy(b => b.MergeBase.Sha, b => b.Branch) .ToDictionary(b => b.Key, b => b.ToList()); } /// <summary> /// Find the commit where the given branch was branched from another branch. /// If there are multiple such commits and branches, tries to guess based on commit histories. /// </summary> public BranchCommit FindCommitBranchWasBranchedFrom(IBranch branch, Config configuration, params IBranch[] excludedBranches) { if (branch == null) { throw new ArgumentNullException(nameof(branch)); } using (log.IndentLog($"Finding branch source of '{branch}'")) { if (branch.Tip == null) { log.Warning(string.Format(MissingTipFormat, branch)); return BranchCommit.Empty; } var possibleBranches = GetMergeCommitsForBranch(branch, configuration, excludedBranches) .Where(b => !branch.Equals(b.Branch)) .ToList(); if (possibleBranches.Count > 1) { var first = possibleBranches.First(); log.Info($"Multiple source branches have been found, picking the first one ({first.Branch}).{System.Environment.NewLine}" + $"This may result in incorrect commit counting.{System.Environment.NewLine}Options were:{System.Environment.NewLine}" + string.Join(", ", possibleBranches.Select(b => b.Branch.ToString()))); return first; } return possibleBranches.SingleOrDefault(); } } public SemanticVersion GetCurrentCommitTaggedVersion(ICommit commit, EffectiveConfiguration config) { return repository.Tags .SelectMany(t => { var targetCommit = t.PeeledTargetCommit(); if (targetCommit != null && Equals(targetCommit, commit) && SemanticVersion.TryParse(t.Name.Friendly, config.GitTagPrefix, out var version)) return new[] { version }; return new SemanticVersion[0]; }) .Max(); } public SemanticVersion MaybeIncrement(BaseVersion baseVersion, GitVersionContext context) { var increment = IncrementStrategyFinder.DetermineIncrementedField(repository, context, baseVersion); return increment != null ? baseVersion.SemanticVersion.IncrementVersion(increment.Value) : baseVersion.SemanticVersion; } public IEnumerable<SemanticVersion> GetVersionTagsOnBranch(IBranch branch, string tagPrefixRegex) { if (semanticVersionTagsOnBranchCache.ContainsKey(branch)) { log.Debug($"Cache hit for version tags on branch '{branch.Name.Canonical}"); return semanticVersionTagsOnBranchCache[branch]; } using (log.IndentLog($"Getting version tags from branch '{branch.Name.Canonical}'.")) { var tags = GetValidVersionTags(tagPrefixRegex); var versionTags = branch.Commits.SelectMany(c => tags.Where(t => c.Sha == t.Item1.TargetSha).Select(t => t.Item2)).ToList(); semanticVersionTagsOnBranchCache.Add(branch, versionTags); return versionTags; } } public IEnumerable<Tuple<ITag, SemanticVersion>> GetValidVersionTags(string tagPrefixRegex, DateTimeOffset? olderThan = null) { var tags = new List<Tuple<ITag, SemanticVersion>>(); foreach (var tag in repository.Tags) { var commit = tag.PeeledTargetCommit(); if (commit == null) continue; if (olderThan.HasValue && commit.When > olderThan.Value) continue; if (SemanticVersion.TryParse(tag.Name.Friendly, tagPrefixRegex, out var semver)) { tags.Add(Tuple.Create(tag, semver)); } } return tags; } public IEnumerable<ICommit> GetCommitLog(ICommit baseVersionSource, ICommit currentCommit) { var filter = new CommitFilter { IncludeReachableFrom = currentCommit, ExcludeReachableFrom = baseVersionSource, SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time }; return repository.Commits.QueryBy(filter); } public VersionField? DetermineIncrementedField(BaseVersion baseVersion, GitVersionContext context) { return IncrementStrategyFinder.DetermineIncrementedField(repository, context, baseVersion); } public bool IsCommitOnBranch(ICommit baseVersionSource, IBranch branch, ICommit firstMatchingCommit) { var filter = new CommitFilter { IncludeReachableFrom = branch, ExcludeReachableFrom = baseVersionSource, FirstParentOnly = true, }; var commitCollection = repository.Commits.QueryBy(filter); return commitCollection.Contains(firstMatchingCommit); } private IEnumerable<BranchCommit> GetMergeCommitsForBranch(IBranch branch, Config configuration, IEnumerable<IBranch> excludedBranches) { if (mergeBaseCommitsCache.ContainsKey(branch)) { log.Debug($"Cache hit for getting merge commits for branch {branch.Name.Canonical}."); return mergeBaseCommitsCache[branch]; } var currentBranchConfig = configuration.GetConfigForBranch(branch.Name.WithoutRemote); var regexesToCheck = currentBranchConfig == null ? new[] { ".*" } // Match anything if we can't find a branch config : currentBranchConfig.SourceBranches.Select(sb => configuration.Branches[sb].Regex); var branchMergeBases = ExcludingBranches(excludedBranches) .Where(b => { if (Equals(b, branch)) return false; var branchCanBeMergeBase = regexesToCheck.Any(regex => Regex.IsMatch(b.Name.Friendly, regex)); return branchCanBeMergeBase; }) .Select(otherBranch => { if (otherBranch.Tip == null) { log.Warning(string.Format(MissingTipFormat, otherBranch)); return BranchCommit.Empty; } var findMergeBase = FindMergeBase(branch, otherBranch); return new BranchCommit(findMergeBase, otherBranch); }) .Where(b => b.Commit != null) .OrderByDescending(b => b.Commit.When) .ToList(); mergeBaseCommitsCache.Add(branch, branchMergeBases); return branchMergeBases; } private IEnumerable<ICommit> GetCommitsReacheableFrom(ICommit commit, IBranch branch) { var filter = new CommitFilter { IncludeReachableFrom = branch }; var commitCollection = repository.Commits.QueryBy(filter); return commitCollection.Where(c => c.Sha == commit.Sha); } private ICommit GetForwardMerge(ICommit commitToFindCommonBase, ICommit findMergeBase) { var filter = new CommitFilter { IncludeReachableFrom = commitToFindCommonBase, ExcludeReachableFrom = findMergeBase }; var commitCollection = repository.Commits.QueryBy(filter); return commitCollection.FirstOrDefault(c => c.Parents.Contains(findMergeBase)); } public ICommit FindMergeBase(ICommit commit, ICommit mainlineTip) => repository.FindMergeBase(commit, mainlineTip); public int GetNumberOfUncommittedChanges() => repository.GetNumberOfUncommittedChanges(); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: math.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 Math { /// <summary>Holder for reflection information generated from math.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class MathReflection { #region Descriptor /// <summary>File descriptor for math.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static MathReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CgptYXRoLnByb3RvEgRtYXRoIiwKB0RpdkFyZ3MSEAoIZGl2aWRlbmQYASAB", "KAMSDwoHZGl2aXNvchgCIAEoAyIvCghEaXZSZXBseRIQCghxdW90aWVudBgB", "IAEoAxIRCglyZW1haW5kZXIYAiABKAMiGAoHRmliQXJncxINCgVsaW1pdBgB", "IAEoAyISCgNOdW0SCwoDbnVtGAEgASgDIhkKCEZpYlJlcGx5Eg0KBWNvdW50", "GAEgASgDMqQBCgRNYXRoEiYKA0RpdhINLm1hdGguRGl2QXJncxoOLm1hdGgu", "RGl2UmVwbHkiABIuCgdEaXZNYW55Eg0ubWF0aC5EaXZBcmdzGg4ubWF0aC5E", "aXZSZXBseSIAKAEwARIjCgNGaWISDS5tYXRoLkZpYkFyZ3MaCS5tYXRoLk51", "bSIAMAESHwoDU3VtEgkubWF0aC5OdW0aCS5tYXRoLk51bSIAKAFiBnByb3Rv", "Mw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Math.DivArgs), global::Math.DivArgs.Parser, new[]{ "Dividend", "Divisor" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Math.DivReply), global::Math.DivReply.Parser, new[]{ "Quotient", "Remainder" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Math.FibArgs), global::Math.FibArgs.Parser, new[]{ "Limit" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Math.Num), global::Math.Num.Parser, new[]{ "Num_" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Math.FibReply), global::Math.FibReply.Parser, new[]{ "Count" }, null, null, null) })); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class DivArgs : pb::IMessage<DivArgs> { private static readonly pb::MessageParser<DivArgs> _parser = new pb::MessageParser<DivArgs>(() => new DivArgs()); public static pb::MessageParser<DivArgs> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Math.MathReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public DivArgs() { OnConstruction(); } partial void OnConstruction(); public DivArgs(DivArgs other) : this() { dividend_ = other.dividend_; divisor_ = other.divisor_; } public DivArgs Clone() { return new DivArgs(this); } /// <summary>Field number for the "dividend" field.</summary> public const int DividendFieldNumber = 1; private long dividend_; public long Dividend { get { return dividend_; } set { dividend_ = value; } } /// <summary>Field number for the "divisor" field.</summary> public const int DivisorFieldNumber = 2; private long divisor_; public long Divisor { get { return divisor_; } set { divisor_ = value; } } public override bool Equals(object other) { return Equals(other as DivArgs); } public bool Equals(DivArgs other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Dividend != other.Dividend) return false; if (Divisor != other.Divisor) return false; return true; } public override int GetHashCode() { int hash = 1; if (Dividend != 0L) hash ^= Dividend.GetHashCode(); if (Divisor != 0L) hash ^= Divisor.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Dividend != 0L) { output.WriteRawTag(8); output.WriteInt64(Dividend); } if (Divisor != 0L) { output.WriteRawTag(16); output.WriteInt64(Divisor); } } public int CalculateSize() { int size = 0; if (Dividend != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Dividend); } if (Divisor != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Divisor); } return size; } public void MergeFrom(DivArgs other) { if (other == null) { return; } if (other.Dividend != 0L) { Dividend = other.Dividend; } if (other.Divisor != 0L) { Divisor = other.Divisor; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Dividend = input.ReadInt64(); break; } case 16: { Divisor = input.ReadInt64(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class DivReply : pb::IMessage<DivReply> { private static readonly pb::MessageParser<DivReply> _parser = new pb::MessageParser<DivReply>(() => new DivReply()); public static pb::MessageParser<DivReply> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Math.MathReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public DivReply() { OnConstruction(); } partial void OnConstruction(); public DivReply(DivReply other) : this() { quotient_ = other.quotient_; remainder_ = other.remainder_; } public DivReply Clone() { return new DivReply(this); } /// <summary>Field number for the "quotient" field.</summary> public const int QuotientFieldNumber = 1; private long quotient_; public long Quotient { get { return quotient_; } set { quotient_ = value; } } /// <summary>Field number for the "remainder" field.</summary> public const int RemainderFieldNumber = 2; private long remainder_; public long Remainder { get { return remainder_; } set { remainder_ = value; } } public override bool Equals(object other) { return Equals(other as DivReply); } public bool Equals(DivReply other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Quotient != other.Quotient) return false; if (Remainder != other.Remainder) return false; return true; } public override int GetHashCode() { int hash = 1; if (Quotient != 0L) hash ^= Quotient.GetHashCode(); if (Remainder != 0L) hash ^= Remainder.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Quotient != 0L) { output.WriteRawTag(8); output.WriteInt64(Quotient); } if (Remainder != 0L) { output.WriteRawTag(16); output.WriteInt64(Remainder); } } public int CalculateSize() { int size = 0; if (Quotient != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Quotient); } if (Remainder != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Remainder); } return size; } public void MergeFrom(DivReply other) { if (other == null) { return; } if (other.Quotient != 0L) { Quotient = other.Quotient; } if (other.Remainder != 0L) { Remainder = other.Remainder; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Quotient = input.ReadInt64(); break; } case 16: { Remainder = input.ReadInt64(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class FibArgs : pb::IMessage<FibArgs> { private static readonly pb::MessageParser<FibArgs> _parser = new pb::MessageParser<FibArgs>(() => new FibArgs()); public static pb::MessageParser<FibArgs> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Math.MathReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public FibArgs() { OnConstruction(); } partial void OnConstruction(); public FibArgs(FibArgs other) : this() { limit_ = other.limit_; } public FibArgs Clone() { return new FibArgs(this); } /// <summary>Field number for the "limit" field.</summary> public const int LimitFieldNumber = 1; private long limit_; public long Limit { get { return limit_; } set { limit_ = value; } } public override bool Equals(object other) { return Equals(other as FibArgs); } public bool Equals(FibArgs other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Limit != other.Limit) return false; return true; } public override int GetHashCode() { int hash = 1; if (Limit != 0L) hash ^= Limit.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Limit != 0L) { output.WriteRawTag(8); output.WriteInt64(Limit); } } public int CalculateSize() { int size = 0; if (Limit != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Limit); } return size; } public void MergeFrom(FibArgs other) { if (other == null) { return; } if (other.Limit != 0L) { Limit = other.Limit; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Limit = input.ReadInt64(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Num : pb::IMessage<Num> { private static readonly pb::MessageParser<Num> _parser = new pb::MessageParser<Num>(() => new Num()); public static pb::MessageParser<Num> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Math.MathReflection.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Num() { OnConstruction(); } partial void OnConstruction(); public Num(Num other) : this() { num_ = other.num_; } public Num Clone() { return new Num(this); } /// <summary>Field number for the "num" field.</summary> public const int Num_FieldNumber = 1; private long num_; public long Num_ { get { return num_; } set { num_ = value; } } public override bool Equals(object other) { return Equals(other as Num); } public bool Equals(Num other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Num_ != other.Num_) return false; return true; } public override int GetHashCode() { int hash = 1; if (Num_ != 0L) hash ^= Num_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Num_ != 0L) { output.WriteRawTag(8); output.WriteInt64(Num_); } } public int CalculateSize() { int size = 0; if (Num_ != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Num_); } return size; } public void MergeFrom(Num other) { if (other == null) { return; } if (other.Num_ != 0L) { Num_ = other.Num_; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Num_ = input.ReadInt64(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class FibReply : pb::IMessage<FibReply> { private static readonly pb::MessageParser<FibReply> _parser = new pb::MessageParser<FibReply>(() => new FibReply()); public static pb::MessageParser<FibReply> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Math.MathReflection.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public FibReply() { OnConstruction(); } partial void OnConstruction(); public FibReply(FibReply other) : this() { count_ = other.count_; } public FibReply Clone() { return new FibReply(this); } /// <summary>Field number for the "count" field.</summary> public const int CountFieldNumber = 1; private long count_; public long Count { get { return count_; } set { count_ = value; } } public override bool Equals(object other) { return Equals(other as FibReply); } public bool Equals(FibReply other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Count != other.Count) return false; return true; } public override int GetHashCode() { int hash = 1; if (Count != 0L) hash ^= Count.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Count != 0L) { output.WriteRawTag(8); output.WriteInt64(Count); } } public int CalculateSize() { int size = 0; if (Count != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Count); } return size; } public void MergeFrom(FibReply other) { if (other == null) { return; } if (other.Count != 0L) { Count = other.Count; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { Count = input.ReadInt64(); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Data; namespace LumiSoft.Net.FTP.Client { /// <summary> /// Transfer mode. /// </summary> internal enum TransferMode { /// <summary> /// ASCII transfer mode. /// </summary> Ascii = 0, /// <summary> /// Binary transfer mode. /// </summary> Binary = 1, } /// <summary> /// Ftp client. /// </summary> public class FTP_Client : IDisposable { private BufferedSocket m_pSocket = null; private bool m_Connected = false; private bool m_Authenticated = false; private bool m_Passive = true; /// <summary> /// Default connection. /// </summary> public FTP_Client() { } #region function Dispose /// <summary> /// Clears resources and closes connection if open. /// </summary> public void Dispose() { Disconnect(); } #endregion #region function Connect /// <summary> /// Connects to specified host. /// </summary> /// <param name="host">Host name.</param> /// <param name="port">Port.</param> public void Connect(string host,int port) { Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPEndPoint ipdest = new IPEndPoint(System.Net.Dns.Resolve(host).AddressList[0],port); s.Connect(ipdest); s.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.NoDelay,1); m_pSocket = new BufferedSocket(s); string reply = m_pSocket.ReadLine(); while(!reply.StartsWith("220 ")){ reply = m_pSocket.ReadLine(); } m_Connected = true; } #endregion #region function Disconnect /// <summary> /// Disconnects from active host. /// </summary> public void Disconnect() { if(m_pSocket != null){ if(m_pSocket.Connected){ // Send QUIT m_pSocket.SendLine("QUIT"); } // m_pSocket.Close(); m_pSocket = null; } m_Connected = false; m_Authenticated = false; } #endregion #region function Authenticate /// <summary> /// Authenticates user. /// </summary> /// <param name="userName">User name.</param> /// <param name="password">Password.</param> public void Authenticate(string userName,string password) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(m_Authenticated){ throw new Exception("You are already authenticated !"); } m_pSocket.SendLine("USER " + userName); string reply = m_pSocket.ReadLine(); if(reply.StartsWith("331")){ m_pSocket.SendLine("PASS " + password); /* FTP server may give multiline reply here / For example: / 230-User someuser has group access to: someuser / 230 OK. Current restricted directory is / */ reply = m_pSocket.ReadLine(); while(!reply.StartsWith("230 ")){ if(!reply.StartsWith("230")){ throw new Exception(reply); } reply = m_pSocket.ReadLine(); } m_Authenticated = true; } else{ throw new Exception(reply); } } #endregion #region function SetCurrentDir /// <summary> /// Sets current directory. /// </summary> /// <param name="dir">Directory.</param> public void SetCurrentDir(string dir) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("CWD " + dir); string reply = m_pSocket.ReadLine(); if(!reply.StartsWith("250")){ throw new Exception("Server returned:" + reply); } } #endregion #region function GetList /// <summary> /// Gets directory listing. /// </summary> /// <returns>Returns DataSet(DirInfo DataTable) with directory listing info.</returns> public DataSet GetList() { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } // Set transfer mode this.SetTransferMode(TransferMode.Ascii); Socket socket = null; MemoryStream storeStream = new MemoryStream(); string reply = ""; try{ if(m_Passive){ socket = GetDataConnection(-1); // Send LIST command m_pSocket.SendLine("LIST"); reply = m_pSocket.ReadLine(); if(!(reply.StartsWith("125") || reply.StartsWith("150"))){ throw new Exception(reply); } } else{ int port = this.Port(); // Send LIST command m_pSocket.SendLine("LIST"); reply = m_pSocket.ReadLine(); if(!(reply.StartsWith("125") || reply.StartsWith("150"))){ throw new Exception(reply); } socket = GetDataConnection(port); } int count = 1; while(count > 0){ byte[] data = new Byte[4000]; count = socket.Receive(data,data.Length,SocketFlags.None); storeStream.Write(data,0,count); } if(socket != null){ socket.Shutdown(SocketShutdown.Both); socket.Close(); } } catch(Exception x){ if(socket != null){ socket.Shutdown(SocketShutdown.Both); socket.Close(); } throw x; } // Get "226 Transfer Complete" response /* FTP server may give multiline reply here / For example: / 226-Options: -l / 226 6 matches total */ reply = m_pSocket.ReadLine(); while(!reply.StartsWith("226 ")){ if(!reply.StartsWith("226")){ throw new Exception(reply); } reply = m_pSocket.ReadLine(); } return ParseDirListing(System.Text.Encoding.Default.GetString(storeStream.ToArray())); } #endregion #region function CreateDir /// <summary> /// Creates directory. /// </summary> /// <param name="dir">Directory name.</param> public void CreateDir(string dir) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("MKD " + dir); string reply = m_pSocket.ReadLine(); if(!reply.StartsWith("257")){ throw new Exception("Server returned:" + reply); } } #endregion #region function RenameDir /// <summary> /// Renames directory. /// </summary> /// <param name="oldDir">Name of directory which to rename.</param> /// <param name="newDir">New directory name.</param> public void RenameDir(string oldDir,string newDir) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("RNFR " + oldDir); string reply = m_pSocket.ReadLine(); if(!reply.StartsWith("350")){ throw new Exception("Server returned:" + reply); } m_pSocket.SendLine("RNTO " + newDir); reply = m_pSocket.ReadLine(); if(!reply.StartsWith("250")){ throw new Exception("Server returned:" + reply); } } #endregion #region function DeleteDir /// <summary> /// Deletes directory. /// </summary> /// <param name="dir">Name of directory which to delete.</param> public void DeleteDir(string dir) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } // ToDo: delete all sub directories and files m_pSocket.SendLine("RMD " + dir); string reply = m_pSocket.ReadLine(); if(!reply.StartsWith("250")){ throw new Exception("Server returned:" + reply); } } #endregion #region function ReceiveFile /// <summary> /// Recieves specified file from server. /// </summary> /// <param name="fileName">File name of file which to receive.</param> /// <param name="putFileName">File path+name which to store.</param> public void ReceiveFile(string fileName,string putFileName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } using(FileStream fs = File.Create(putFileName)){ ReceiveFile(fileName,fs); } } /// <summary> /// Recieves specified file from server. /// </summary> /// <param name="fileName">File name of file which to receive.</param> /// <param name="storeStream">Stream where to store file.</param> public void ReceiveFile(string fileName,Stream storeStream) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } // Set transfer mode this.SetTransferMode(TransferMode.Binary); Socket socket = null; string reply = ""; try{ if(m_Passive){ socket = GetDataConnection(-1); // Send RETR command m_pSocket.SendLine("RETR " + fileName); reply = m_pSocket.ReadLine(); if(!(reply.StartsWith("125") || reply.StartsWith("150"))){ throw new Exception(reply); } } else{ int port = this.Port(); // Send RETR command m_pSocket.SendLine("RETR " + fileName); reply = m_pSocket.ReadLine(); if(!(reply.StartsWith("125") || reply.StartsWith("150"))){ throw new Exception(reply); } socket = GetDataConnection(port); } int count = 1; while(count > 0){ byte[] data = new byte[4000]; count = socket.Receive(data,data.Length,SocketFlags.None); storeStream.Write(data,0,count); } if(socket != null){ socket.Shutdown(SocketShutdown.Both); socket.Close(); } } catch(Exception x){ if(socket != null){ socket.Shutdown(SocketShutdown.Both); socket.Close(); } throw x; } // Get "226 Transfer Complete" response /* FTP server may give multiline reply here / For example: / 226-File successfully transferred / 226 0.002 seconds (measured here), 199.65 Mbytes per second 339163 bytes received in 00:00 (8.11 MB/s) */ reply = m_pSocket.ReadLine(); while(!reply.StartsWith("226 ")){ if(!reply.StartsWith("226")){ throw new Exception(reply); } reply = m_pSocket.ReadLine(); } // Get "226 Transfer Complete" response /* reply = m_pSocket.ReadLine(); if(!reply.StartsWith("226")){ throw new Exception(reply); }*/ } #endregion #region function StoreFile /// <summary> /// Stores specified file to server. /// </summary> /// <param name="getFileName">File path+name which to store in server.</param> public void StoreFile(string getFileName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } using(FileStream fs = File.OpenRead(getFileName)){ StoreFile(fs,Path.GetFileName(getFileName)); } } /// <summary> /// Stores specified file to server. /// </summary> /// <param name="getStream">Stream from where to gets file.</param> /// <param name="fileName">File name to store in server.</param> public void StoreFile(Stream getStream,string fileName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } // Set transfer mode this.SetTransferMode(TransferMode.Binary); Socket socket = null; string reply = ""; try{ if(m_Passive){ socket = GetDataConnection(-1); // Send STOR command m_pSocket.SendLine("STOR " + fileName); reply = m_pSocket.ReadLine(); if(!(reply.StartsWith("125") || reply.StartsWith("150"))){ throw new Exception(reply); } } else{ int port = this.Port(); // Send STOR command m_pSocket.SendLine("STOR " + fileName); reply = m_pSocket.ReadLine(); if(!(reply.StartsWith("125") || reply.StartsWith("150"))){ throw new Exception(reply); } socket = GetDataConnection(port); } int count = 1; while(count > 0){ byte[] data = new Byte[4000]; count = getStream.Read(data,0,data.Length); socket.Send(data,0,count,SocketFlags.None); } if(socket != null){ socket.Shutdown(SocketShutdown.Both); socket.Close(); } } catch(Exception x){ if(socket != null){ socket.Shutdown(SocketShutdown.Both); socket.Close(); } throw x; } // Get "226 Transfer Complete" response /* FTP server may give multiline reply here / For example: / 226-File successfully transferred / 226 0.016 seconds (measured here), 6.64 Mbytes per second 110309 bytes sent in 00:00 (2.58 MB/s) */ reply = m_pSocket.ReadLine(); while(!reply.StartsWith("226 ")){ if(!reply.StartsWith("226")){ throw new Exception(reply); } reply = m_pSocket.ReadLine(); } // Get "226 Transfer Complete" response /* reply = m_pSocket.ReadLine(); if(!reply.StartsWith("226")){ throw new Exception(reply); }*/ } #endregion #region function DeleteFile /// <summary> /// Deletes specified file or directory. /// </summary> /// <param name="file">File name.</param> public void DeleteFile(string file) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("DELE " + file); string reply = m_pSocket.ReadLine(); if(!reply.StartsWith("250")){ throw new Exception("Server returned:" + reply); } } #endregion #region function RenameFile /// <summary> /// Renames specified file or directory. /// </summary> /// <param name="oldFileName">File name of file what to rename.</param> /// <param name="newFileName">New file name.</param> public void RenameFile(string oldFileName,string newFileName) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } m_pSocket.SendLine("RNFR " + oldFileName); string reply = m_pSocket.ReadLine(); if(!reply.StartsWith("350")){ throw new Exception("Server returned:" + reply); } m_pSocket.SendLine("RNTO " + newFileName); reply = m_pSocket.ReadLine(); if(!reply.StartsWith("250")){ throw new Exception("Server returned:" + reply); } } #endregion #region function Port private int Port() { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } /* Syntax:{PORT ipPart1,ipPart1,ipPart1,ipPart1,portPart1,portPart1<CRLF>} <host-port> ::= <host-number>,<port-number> <host-number> ::= <number>,<number>,<number>,<number> <port-number> ::= <number>,<number> <number> ::= any decimal integer 1 through 255 */ IPHostEntry ipThis = System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()); Random r = new Random(); int port = 0; bool found = false; // we will try all IP addresses assigned to this machine // the first one that the remote machine likes will be chosen for(int tryCount=0;!found && tryCount<20;tryCount++) { for(int i=0;i<ipThis.AddressList.Length;i++){ string ip = ipThis.AddressList[i].ToString().Replace(".",","); int p1 = r.Next(100); int p2 = r.Next(100); port = (p1 << 8) | p2; m_pSocket.SendLine("PORT " + ip + "," + p1.ToString() + "," + p2.ToString()); string reply = m_pSocket.ReadLine(); if(reply.StartsWith("200")){ found = true; break; } } } if(!found){ throw new Exception("No suitable port found"); } return port; } #endregion #region function SetTransferMode /// <summary> /// Sets transfer mode. /// </summary> /// <param name="mode">Transfer mode.</param> private void SetTransferMode(TransferMode mode) { if(!m_Connected){ throw new Exception("You must connect first !"); } if(!m_Authenticated){ throw new Exception("You must authenticate first !"); } switch(mode) { case TransferMode.Ascii: m_pSocket.SendLine("TYPE A"); break; case TransferMode.Binary: m_pSocket.SendLine("TYPE I"); break; } string reply = m_pSocket.ReadLine(); if(!reply.StartsWith("200")){ throw new Exception("Server returned:" + reply); } } #endregion #region method ParseDirListing /// <summary> /// Parses server returned directory listing. /// </summary> /// <param name="list"></param> /// <returns></returns> private DataSet ParseDirListing(string list) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add("DirInfo"); dt.Columns.Add("Name"); dt.Columns.Add("Date",typeof(DateTime)); dt.Columns.Add("Size",typeof(long)); dt.Columns.Add("IsDirectory",typeof(bool)); // Remove continues spaces while(list.IndexOf(" ") > -1){ list = list.Replace(" "," "); } string[] entries = list.Replace("\r\n","\n").Split('\n'); foreach(string entry in entries){ if(entry.Length > 0){ string[] entryParts = entry.Split(' '); DateTime date = DateTime.Today; long size = 0; bool isDir = false; string name = ""; bool winListing = false; try{ string[] dateFormats = new string[]{ "MM-dd-yy hh:mmtt", "M-d-yy h:mmtt", }; date = DateTime.ParseExact(entryParts[0] + " " + entryParts[1],dateFormats,System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None); winListing = true; } catch{ } // Windows listing if(winListing){ string[] dateFormats = new string[]{ "MM-dd-yy hh:mmtt", "M-d-yy h:mmtt", "MM-dd-yy hh:mm", "M-d-yy h:mm" }; // Date date = DateTime.ParseExact(entryParts[0] + " " + entryParts[1],dateFormats,System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None); // This block is <DIR> or file size if(entryParts[2].ToUpper().IndexOf("DIR") > -1){ isDir = true; } else{ size = Convert.ToInt64(entryParts[2]); } // Name. Name starts from 3 to ... (if contains <SP> in name) for(int i=3;i<entryParts.Length;i++){ name += entryParts[i] + " "; } name = name.Trim(); } // Unix listing else{ string[] dateFormats = new string[]{ "MMM dd HH:mm", "MMM dd H:mm", "MMM d HH:mm", "MMM d H:mm", "MMM dd yyyy", "MMM d yyyy", }; // Date date = DateTime.ParseExact(entryParts[5] + " " + entryParts[6] + " " + entryParts[7],dateFormats,System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None); // IsDir if(entryParts[0].ToUpper().StartsWith("D")){ isDir = true; } // Size size = Convert.ToInt64(entryParts[4]); // Name. Name starts from 8 to ... (if contains <SP> in name) for(int i=8;i<entryParts.Length;i++){ name += entryParts[i] + " "; } name = name.Trim(); } dt.Rows.Add(new object[]{name,date,size,isDir}); } } return ds; } #endregion #region method GetDataConnection private Socket GetDataConnection(int portA) { // Passive mode if(m_Passive){ // Send PASV command m_pSocket.SendLine("PASV"); // Get 227 Entering Passive Mode (192,168,1,10,1,10) string reply = m_pSocket.ReadLine(); if(!reply.StartsWith("227")){ throw new Exception(reply); } // Parse IP and port reply = reply.Substring(reply.IndexOf("(") + 1,reply.IndexOf(")") - reply.IndexOf("(") - 1); string[] parts = reply.Split(','); string ip = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3]; int port = (Convert.ToInt32(parts[4]) << 8) | Convert.ToInt32(parts[5]); Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); // socket.Connect(new IPEndPoint(System.Net.Dns.GetHostByAddress(ip).AddressList[0],port)); socket.Connect(new IPEndPoint(IPAddress.Parse(ip),port)); return socket; } // Active mode else{ TcpListener conn = new TcpListener(IPAddress.Any,portA); conn.Start(); //--- Wait ftp server connection -----------------------------// long startTime = DateTime.Now.Ticks; // Wait ftp server to connect while(!conn.Pending()){ System.Threading.Thread.Sleep(50); // Time out after 30 seconds if((DateTime.Now.Ticks - startTime) / 10000 > 20000){ throw new Exception("Ftp server didn't respond !"); } } //-----------------------------------------------------------// Socket connectedFtpServer = conn.AcceptSocket(); // Stop listening conn.Stop(); return connectedFtpServer; } } #endregion #region Properties Implementation /// <summary> /// Gets data connection mode. /// Passive - client connects to ftp server. /// Active - ftp server connects to client. /// </summary> public bool PassiveMode { get{ return m_Passive; } set{ m_Passive = value; } } #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; /// <summary> /// Convert.ToDouble(String) /// </summary> public class ConvertToDouble13 { public static int Main() { ConvertToDouble13 testObj = new ConvertToDouble13(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToDouble(String)"); if (testObj.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]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1(); retVal = NegTest2(); retVal = NegTest3(); retVal = NegTest4(); return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string c_TEST_DESC = "PosTest1: Verfify value is a vaild string ... "; string c_TEST_ID = "P001"; string actualValue = "62356.123"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Double resValue = Convert.ToDouble(actualValue); if (Double.Parse(actualValue) != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString(); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string c_TEST_DESC = "PosTest2: Verfify value is a null reference... "; string c_TEST_ID = "P002"; String actualValue = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Double resValue = Convert.ToDouble(actualValue); if (0 != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is 0"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string c_TEST_DESC = "PosTest3: Verfify value is a string end with a radix point... "; string c_TEST_ID = "P003"; String actualValue = "7923."; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Double resValue = Convert.ToDouble(actualValue); Double realValue = Double.Parse(actualValue); if (realValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is"+ realValue; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "unexpected exception occurs :" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string c_TEST_DESC = "PosTest4: Verfify value is a string started with a radix point... "; string c_TEST_ID = "P003"; String actualValue= ".7923"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Double resValue = Convert.ToDouble(actualValue); Double realValue = Double.Parse(actualValue); if (realValue != resValue) { string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + realValue; TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "unexpected exception occurs :" + e); retVal = false; } return retVal; } #endregion #region NegativeTesting public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: Value represents a number greater than Double.MaxValue "; const string c_TEST_ID = "N001"; string actualValue = "2.7976931348623157E+308"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToDouble(actualValue); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, "OverflowException is not thrown as expected."); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; const string c_TEST_DESC = "NegTest2: Value represents a number less than Double.MaxValue "; const string c_TEST_ID = "N002"; string actualValue = "-1.7976931348623159E+308"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToDouble(actualValue); TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, "OverflowException is not thrown as expected."); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_DESC = "NegTest3: value is a string cantains invalid chars "; const string c_TEST_ID = "N003"; string actualValue = "3222.79asd"; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToDouble(actualValue); TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "FormatException is not thrown as expected."); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; const string c_TEST_DESC = "NegTest4: value is a empty string "; const string c_TEST_ID = "N004"; string actualValue = ""; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { Convert.ToDouble(actualValue); TestLibrary.TestFramework.LogError("015" + " TestId-" + c_TEST_ID, "FormatException is not thrown as expected."); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("016" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using Avalonia.Platform; namespace Avalonia.Media { /// <summary> /// Parses a path markup string. /// </summary> public class PathMarkupParser : IDisposable { private static readonly Dictionary<char, Command> s_commands = new Dictionary<char, Command> { { 'F', Command.FillRule }, { 'M', Command.Move }, { 'L', Command.Line }, { 'H', Command.HorizontalLine }, { 'V', Command.VerticalLine }, { 'Q', Command.QuadraticBezierCurve }, { 'T', Command.SmoothQuadraticBezierCurve }, { 'C', Command.CubicBezierCurve }, { 'S', Command.SmoothCubicBezierCurve }, { 'A', Command.Arc }, { 'Z', Command.Close }, }; private IGeometryContext _geometryContext; private Point _currentPoint; private Point? _beginFigurePoint; private Point? _previousControlPoint; private bool _isOpen; private bool _isDisposed; /// <summary> /// Initializes a new instance of the <see cref="PathMarkupParser"/> class. /// </summary> /// <param name="geometryContext">The geometry context.</param> /// <exception cref="ArgumentNullException">geometryContext</exception> public PathMarkupParser(IGeometryContext geometryContext) { if (geometryContext == null) { throw new ArgumentNullException(nameof(geometryContext)); } _geometryContext = geometryContext; } private enum Command { None, FillRule, Move, Line, HorizontalLine, VerticalLine, CubicBezierCurve, QuadraticBezierCurve, SmoothCubicBezierCurve, SmoothQuadraticBezierCurve, Arc, Close } void IDisposable.Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (_isDisposed) { return; } if (disposing) { _geometryContext = null; } _isDisposed = true; } private static Point MirrorControlPoint(Point controlPoint, Point center) { var dir = controlPoint - center; return center + -dir; } /// <summary> /// Parses the specified path data and writes the result to the geometryContext of this instance. /// </summary> /// <param name="pathData">The path data.</param> public void Parse(string pathData) { var span = pathData.AsSpan(); _currentPoint = new Point(); while(!span.IsEmpty) { if(!ReadCommand(ref span, out var command, out var relative)) { break; } bool initialCommand = true; do { if (!initialCommand) { span = ReadSeparator(span); } switch (command) { case Command.None: break; case Command.FillRule: SetFillRule(ref span); break; case Command.Move: AddMove(ref span, relative); break; case Command.Line: AddLine(ref span, relative); break; case Command.HorizontalLine: AddHorizontalLine(ref span, relative); break; case Command.VerticalLine: AddVerticalLine(ref span, relative); break; case Command.CubicBezierCurve: AddCubicBezierCurve(ref span, relative); break; case Command.QuadraticBezierCurve: AddQuadraticBezierCurve(ref span, relative); break; case Command.SmoothCubicBezierCurve: AddSmoothCubicBezierCurve(ref span, relative); break; case Command.SmoothQuadraticBezierCurve: AddSmoothQuadraticBezierCurve(ref span, relative); break; case Command.Arc: AddArc(ref span, relative); break; case Command.Close: CloseFigure(); break; default: throw new NotSupportedException("Unsupported command"); } initialCommand = false; } while (PeekArgument(span)); } if (_isOpen) { _geometryContext.EndFigure(false); } } private void CreateFigure() { if (_isOpen) { _geometryContext.EndFigure(false); } _geometryContext.BeginFigure(_currentPoint); _beginFigurePoint = _currentPoint; _isOpen = true; } private void SetFillRule(ref ReadOnlySpan<char> span) { if (!ReadArgument(ref span, out var fillRule) || fillRule.Length != 1) { throw new InvalidDataException("Invalid fill rule."); } FillRule rule; switch (fillRule[0]) { case '0': rule = FillRule.EvenOdd; break; case '1': rule = FillRule.NonZero; break; default: throw new InvalidDataException("Invalid fill rule"); } _geometryContext.SetFillRule(rule); } private void CloseFigure() { if (_isOpen) { _geometryContext.EndFigure(true); if (_beginFigurePoint != null) { _currentPoint = _beginFigurePoint.Value; _beginFigurePoint = null; } } _previousControlPoint = null; _isOpen = false; } private void AddMove(ref ReadOnlySpan<char> span, bool relative) { var currentPoint = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); _currentPoint = currentPoint; CreateFigure(); while (PeekArgument(span)) { span = ReadSeparator(span); AddLine(ref span, relative); } } private void AddLine(ref ReadOnlySpan<char> span, bool relative) { _currentPoint = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (!_isOpen) { CreateFigure(); } _geometryContext.LineTo(_currentPoint); } private void AddHorizontalLine(ref ReadOnlySpan<char> span, bool relative) { _currentPoint = relative ? new Point(_currentPoint.X + ReadDouble(ref span), _currentPoint.Y) : _currentPoint.WithX(ReadDouble(ref span)); if (!_isOpen) { CreateFigure(); } _geometryContext.LineTo(_currentPoint); } private void AddVerticalLine(ref ReadOnlySpan<char> span, bool relative) { _currentPoint = relative ? new Point(_currentPoint.X, _currentPoint.Y + ReadDouble(ref span)) : _currentPoint.WithY(ReadDouble(ref span)); if (!_isOpen) { CreateFigure(); } _geometryContext.LineTo(_currentPoint); } private void AddCubicBezierCurve(ref ReadOnlySpan<char> span, bool relative) { var point1 = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); span = ReadSeparator(span); var point2 = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); _previousControlPoint = point2; span = ReadSeparator(span); var point3 = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (!_isOpen) { CreateFigure(); } _geometryContext.CubicBezierTo(point1, point2, point3); _currentPoint = point3; } private void AddQuadraticBezierCurve(ref ReadOnlySpan<char> span, bool relative) { var start = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); _previousControlPoint = start; span = ReadSeparator(span); var end = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (!_isOpen) { CreateFigure(); } _geometryContext.QuadraticBezierTo(start, end); _currentPoint = end; } private void AddSmoothCubicBezierCurve(ref ReadOnlySpan<char> span, bool relative) { var point2 = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); span = ReadSeparator(span); var end = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (_previousControlPoint != null) { _previousControlPoint = MirrorControlPoint((Point)_previousControlPoint, _currentPoint); } if (!_isOpen) { CreateFigure(); } _geometryContext.CubicBezierTo(_previousControlPoint ?? _currentPoint, point2, end); _previousControlPoint = point2; _currentPoint = end; } private void AddSmoothQuadraticBezierCurve(ref ReadOnlySpan<char> span, bool relative) { var end = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (_previousControlPoint != null) { _previousControlPoint = MirrorControlPoint((Point)_previousControlPoint, _currentPoint); } if (!_isOpen) { CreateFigure(); } _geometryContext.QuadraticBezierTo(_previousControlPoint ?? _currentPoint, end); _currentPoint = end; } private void AddArc(ref ReadOnlySpan<char> span, bool relative) { var size = ReadSize(ref span); span = ReadSeparator(span); var rotationAngle = ReadDouble(ref span); span = ReadSeparator(span); var isLargeArc = ReadBool(ref span); span = ReadSeparator(span); var sweepDirection = ReadBool(ref span) ? SweepDirection.Clockwise : SweepDirection.CounterClockwise; span = ReadSeparator(span); var end = relative ? ReadRelativePoint(ref span, _currentPoint) : ReadPoint(ref span); if (!_isOpen) { CreateFigure(); } _geometryContext.ArcTo(end, size, rotationAngle, isLargeArc, sweepDirection); _currentPoint = end; _previousControlPoint = null; } private static bool PeekArgument(ReadOnlySpan<char> span) { span = SkipWhitespace(span); return !span.IsEmpty && (span[0] == ',' || span[0] == '-' || span[0] == '.' || char.IsDigit(span[0])); } private static bool ReadArgument(ref ReadOnlySpan<char> remaining, out ReadOnlySpan<char> argument) { remaining = SkipWhitespace(remaining); if (remaining.IsEmpty) { argument = ReadOnlySpan<char>.Empty; return false; } var valid = false; int i = 0; if (remaining[i] == '-') { i++; } for (; i < remaining.Length && char.IsNumber(remaining[i]); i++) valid = true; if (i < remaining.Length && remaining[i] == '.') { valid = false; i++; } for (; i < remaining.Length && char.IsNumber(remaining[i]); i++) valid = true; if (i < remaining.Length) { // scientific notation if (remaining[i] == 'E' || remaining[i] == 'e') { valid = false; i++; if (remaining[i] == '-' || remaining[i] == '+') { i++; for (; i < remaining.Length && char.IsNumber(remaining[i]); i++) valid = true; } } } if (!valid) { argument = ReadOnlySpan<char>.Empty; return false; } argument = remaining.Slice(0, i); remaining = remaining.Slice(i); return true; } private static ReadOnlySpan<char> ReadSeparator(ReadOnlySpan<char> span) { span = SkipWhitespace(span); if (!span.IsEmpty && span[0] == ',') { span = span.Slice(1); } return span; } private static ReadOnlySpan<char> SkipWhitespace(ReadOnlySpan<char> span) { int i = 0; for (; i < span.Length && char.IsWhiteSpace(span[i]); i++) ; return span.Slice(i); } private bool ReadBool(ref ReadOnlySpan<char> span) { span = SkipWhitespace(span); if (span.IsEmpty) { throw new InvalidDataException("Invalid bool rule."); } var c = span[0]; span = span.Slice(1); switch (c) { case '0': return false; case '1': return true; default: throw new InvalidDataException("Invalid bool rule"); } } private double ReadDouble(ref ReadOnlySpan<char> span) { if (!ReadArgument(ref span, out var doubleValue)) { throw new InvalidDataException("Invalid double value"); } return double.Parse(doubleValue.ToString(), CultureInfo.InvariantCulture); } private Size ReadSize(ref ReadOnlySpan<char> span) { var width = ReadDouble(ref span); span = ReadSeparator(span); var height = ReadDouble(ref span); return new Size(width, height); } private Point ReadPoint(ref ReadOnlySpan<char> span) { var x = ReadDouble(ref span); span = ReadSeparator(span); var y = ReadDouble(ref span); return new Point(x, y); } private Point ReadRelativePoint(ref ReadOnlySpan<char> span, Point origin) { var x = ReadDouble(ref span); span = ReadSeparator(span); var y = ReadDouble(ref span); return new Point(origin.X + x, origin.Y + y); } private bool ReadCommand(ref ReadOnlySpan<char> span, out Command command, out bool relative) { span = SkipWhitespace(span); if (span.IsEmpty) { command = default; relative = false; return false; } var c = span[0]; if (!s_commands.TryGetValue(char.ToUpperInvariant(c), out command)) { throw new InvalidDataException("Unexpected path command '" + c + "'."); } relative = char.IsLower(c); span = span.Slice(1); return true; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Management.Automation; using System.Management.Automation.Provider; using System.Management.Automation.Runspaces; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Xml; using Dbg = System.Management.Automation; namespace Microsoft.WSMan.Management { #region Get-WSManInstance /// <summary> /// Executes action on a target object specified by RESOURCE_URI, where /// parameters are specified by key value pairs. /// eg., Call StartService method on the spooler service /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// </summary> [Cmdlet(VerbsCommon.Get, "WSManInstance", DefaultParameterSetName = "GetInstance", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096627")] public class GetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { #region parameter /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "GetInstance")] [Parameter(ParameterSetName = "Enumerate")] public string ApplicationName { get { return applicationname; } set { { applicationname = value; } } } private string applicationname = null; /// <summary> /// The following is the definition of the input parameter "BasePropertiesOnly". /// Enumerate only those properties that are part of the base class /// specification in the Resource URI. When /// Shallow is specified then this flag has no effect. /// </summary> [Parameter(ParameterSetName = "Enumerate")] [Alias("UBPO", "Base")] public SwitchParameter BasePropertiesOnly { get { return basepropertiesonly; } set { { basepropertiesonly = value; } } } private SwitchParameter basepropertiesonly; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "GetInstance")] [Parameter(ParameterSetName = "Enumerate")] [Alias("CN")] public string ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) { computername = "localhost"; } } } private string computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and Prefix, needed to connect to the /// remote machine. The format of this string is: /// transport://server:port/Prefix. /// </summary> [Parameter( ParameterSetName = "GetInstance")] [Parameter( ParameterSetName = "Enumerate")] [Alias("CURI", "CU")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ConnectionURI { get { return connectionuri; } set { { connectionuri = value; } } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "Dialect". /// Defines the dialect for the filter predicate. /// </summary> [Parameter] public Uri Dialect { get { return dialect; } set { { dialect = value; } } } private Uri dialect; /// <summary> /// The following is the definition of the input parameter "Enumerate". /// Switch indicates list all instances of a management resource. Equivalent to /// WSManagement Enumerate. /// </summary> [Parameter(Mandatory = true, ParameterSetName = "Enumerate")] public SwitchParameter Enumerate { get { return enumerate; } set { { enumerate = value; } } } private SwitchParameter enumerate; /// <summary> /// The following is the definition of the input parameter "Filter". /// Indicates the filter expression for the enumeration. /// </summary> [Parameter(ParameterSetName = "Enumerate")] [ValidateNotNullOrEmpty] public string Filter { get { return filter; } set { { filter = value; } } } private string filter; /// <summary> /// The following is the definition of the input parameter "Fragment". /// Specifies a section inside the instance that is to be updated or retrieved /// for the given operation. /// </summary> [Parameter(ParameterSetName = "GetInstance")] [ValidateNotNullOrEmpty] public string Fragment { get { return fragment; } set { { fragment = value; } } } private string fragment; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hashtable and is used to pass a set of switches to the /// service to modify or refine the nature of the request. /// </summary> [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [Alias("OS")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable OptionSet { get { return optionset; } set { { optionset = value; } } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "Enumerate")] [Parameter(ParameterSetName = "GetInstance")] public int Port { get { return port; } set { { port = value; } } } private int port = 0; /// <summary> /// The following is the definition of the input parameter "Associations". /// Associations indicates retrieval of association instances as opposed to /// associated instances. This can only be used when specifying the Dialect as /// Association. /// </summary> [Parameter(ParameterSetName = "Enumerate")] public SwitchParameter Associations { get { return associations; } set { { associations = value; } } } private SwitchParameter associations; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [Alias("RURI")] public Uri ResourceURI { get { return resourceuri; } set { { resourceuri = value; } } } private Uri resourceuri; /// <summary> /// The following is the definition of the input parameter "ReturnType". /// Indicates the type of data returned. Possible options are 'Object', 'EPR', /// and 'ObjectAndEPR'. Default is Object. /// If Object is specified or if this parameter is absent then only the objects /// are returned /// If EPR is specified then only the EPRs of the objects /// are returned. EPRs contain information about the Resource URI and selectors /// for the instance /// If ObjectAndEPR is specified, then both the object and the associated EPRs /// are returned. /// </summary> [Parameter(ParameterSetName = "Enumerate")] [ValidateNotNullOrEmpty] [ValidateSetAttribute(new string[] { "object", "epr", "objectandepr" })] [Alias("RT")] public string ReturnType { get { return returntype; } set { { returntype = value; } } } private string returntype = "object"; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are more than 1 instance of the resource /// class. /// </summary> [Parameter( ParameterSetName = "GetInstance")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable SelectorSet { get { return selectorset; } set { { selectorset = value; } } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This can be /// created by using the cmdlet New-WSManSessionOption. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Alias("SO")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public SessionOption SessionOption { get { return sessionoption; } set { { sessionoption = value; } } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "Shallow". /// Enumerate only instances of the base class specified in the resource URI. If /// this flag is not specified, instances of the base class specified in the URI /// and all its derived classes are returned. /// </summary> [Parameter(ParameterSetName = "Enumerate")] public SwitchParameter Shallow { get { return shallow; } set { { shallow = value; } } } private SwitchParameter shallow; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "GetInstance")] [Parameter(ParameterSetName = "Enumerate")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] [Alias("SSL")] public SwitchParameter UseSSL { get { return usessl; } set { { usessl = value; } } } private SwitchParameter usessl; #endregion parameter #region private private WSManHelper helper; private string GetFilter() { string name; string value; string[] Split = filter.Trim().Split(new char[] { '=', ';' }); if ((Split.Length) % 2 != 0) { // mismatched property name/value pair return null; } filter = "<wsman:SelectorSet xmlns:wsman='http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd'>"; for (int i = 0; i < Split.Length; i += 2) { value = Split[i + 1].Substring(1, Split[i + 1].Length - 2); name = Split[i]; filter = filter + "<wsman:Selector Name='" + name + "'>" + value + "</wsman:Selector>"; } filter += "</wsman:SelectorSet>"; return (filter); } private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsmanResourceLocator, IWSManSession wsmanSession) { string fragment; try { int flags = 0; IWSManEnumerator obj; if (returntype != null) { if (returntype.Equals("object", StringComparison.OrdinalIgnoreCase)) { flags = wsmanObject.EnumerationFlagReturnObject(); } else if (returntype.Equals("epr", StringComparison.OrdinalIgnoreCase)) { flags = wsmanObject.EnumerationFlagReturnEPR(); } else { flags = wsmanObject.EnumerationFlagReturnObjectAndEPR(); } } if (shallow) { flags |= wsmanObject.EnumerationFlagHierarchyShallow(); } else if (basepropertiesonly) { flags |= wsmanObject.EnumerationFlagHierarchyDeepBasePropsOnly(); } else { flags |= wsmanObject.EnumerationFlagHierarchyDeep(); } if (dialect != null && filter != null) { if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_WQL_DIALECT, StringComparison.OrdinalIgnoreCase)) { fragment = helper.URI_WQL_DIALECT; dialect = new Uri(fragment); } else if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_ASSOCIATION_DIALECT, StringComparison.OrdinalIgnoreCase)) { if (associations) { flags |= wsmanObject.EnumerationFlagAssociationInstance(); } else { flags |= wsmanObject.EnumerationFlagAssociatedInstance(); } fragment = helper.URI_ASSOCIATION_DIALECT; dialect = new Uri(fragment); } else if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.OrdinalIgnoreCase) || dialect.ToString().Equals(helper.URI_SELECTOR_DIALECT, StringComparison.OrdinalIgnoreCase)) { filter = GetFilter(); fragment = helper.URI_SELECTOR_DIALECT; dialect = new Uri(fragment); } obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else if (filter != null) { fragment = helper.URI_WQL_DIALECT; dialect = new Uri(fragment); obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else { obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, null, flags); } while (!obj.AtEndOfStream) { XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(obj.ReadItem()); WriteObject(xmldoc.FirstChild); } } catch (Exception ex) { ErrorRecord er = new ErrorRecord(ex, "Exception", ErrorCategory.InvalidOperation, null); WriteError(er); } } #endregion private #region override /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { IWSManSession m_session = null; IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); helper = new WSManHelper(this); helper.WSManOp = "Get"; string connectionStr = null; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try { // in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } try { IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); if (!enumerate) { XmlDocument xmldoc = new XmlDocument(); try { xmldoc.LoadXml(m_session.Get(m_resource, 0)); } catch (XmlException ex) { helper.AssertError(ex.Message, false, computername); } if (!string.IsNullOrEmpty(fragment)) { WriteObject(xmldoc.FirstChild.LocalName + "=" + xmldoc.FirstChild.InnerText); } else { WriteObject(xmldoc.FirstChild); } } else { try { ReturnEnumeration(m_wsmanObject, m_resource, m_session); } catch (Exception ex) { helper.AssertError(ex.Message, false, computername); } } } finally { if (!string.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!string.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) Dispose(m_session); } } #endregion override #region IDisposable Members /// <summary> /// Public dispose method. /// </summary> public void Dispose() { // CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// Public dispose method. /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// BeginProcessing method. /// </summary> protected override void EndProcessing() { helper.CleanUp(); } } #endregion #region Set-WsManInstance /// <summary> /// Executes action on a target object specified by RESOURCE_URI, where /// parameters are specified by key value pairs. /// eg., Call StartService method on the spooler service /// Set-WSManInstance -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// </summary> [Cmdlet(VerbsCommon.Set, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096937")] public class SetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { #region Parameters /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public string ApplicationName { get { return applicationname; } set { applicationname = value; } } private string applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Alias("cn")] public string ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) { computername = "localhost"; } } } private string computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "Dialect". /// Defines the dialect for the filter predicate. /// </summary> [Parameter] [ValidateNotNullOrEmpty] public Uri Dialect { get { return dialect; } set { dialect = value; } } private Uri dialect; /// <summary> /// The following is the definition of the input parameter "FilePath". /// Updates the management resource specified by the ResourceURI and SelectorSet /// via this input file. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Path")] [ValidateNotNullOrEmpty] public string FilePath { get { return filepath; } set { filepath = value; } } private string filepath; /// <summary> /// The following is the definition of the input parameter "Fragment". /// Specifies a section inside the instance that is to be updated or retrieved /// for the given operation. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] public string Fragment { get { return fragment; } set { fragment = value; } } private string fragment; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hahs table which help modify or refine the nature of the /// request. These are similar to switches used in command line shells in that /// they are service-specific. /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] [ValidateNotNullOrEmpty] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] [ValidateRange(1, int.MaxValue)] public int Port { get { return port; } set { port = value; } } private int port = 0; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")] [Parameter(Mandatory = true, Position = 0)] [Alias("ruri")] [ValidateNotNullOrEmpty] public Uri ResourceURI { get { return resourceuri; } set { resourceuri = value; } } private Uri resourceuri; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are more than 1 instance of the resource /// class. /// </summary> [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [ValidateNotNullOrEmpty] public Hashtable SelectorSet { get { return selectorset; } set { selectorset = value; } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This can be created /// by using the cmdlet New-WSManSessionOption. /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("so")] [ValidateNotNullOrEmpty] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] [Alias("ssl")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; /// <summary> /// The following is the definition of the input parameter "ValueSet". /// ValueSet is a hash table which helps to modify resource represented by the /// ResourceURI and SelectorSet. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [ValidateNotNullOrEmpty] public Hashtable ValueSet { get { return valueset; } set { valueset = value; } } private Hashtable valueset; #endregion private WSManHelper helper; /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); helper = new WSManHelper(this); helper.WSManOp = "set"; IWSManSession m_session = null; if (dialect != null) { if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.OrdinalIgnoreCase)) dialect = new Uri(helper.URI_WQL_DIALECT); if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.OrdinalIgnoreCase)) dialect = new Uri(helper.URI_SELECTOR_DIALECT); if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.OrdinalIgnoreCase)) dialect = new Uri(helper.URI_ASSOCIATION_DIALECT); } try { string connectionStr = string.Empty; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try { // in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); XmlDocument xmldoc = new XmlDocument(); try { xmldoc.LoadXml(m_session.Put(m_resource, input, 0)); } catch (XmlException ex) { helper.AssertError(ex.Message, false, computername); } if (!string.IsNullOrEmpty(fragment)) { if (xmldoc.DocumentElement.ChildNodes.Count > 0) { foreach (XmlNode node in xmldoc.DocumentElement.ChildNodes) { if (node.Name.Equals(fragment, StringComparison.OrdinalIgnoreCase)) WriteObject(node.Name + " = " + node.InnerText); } } } else WriteObject(xmldoc.DocumentElement); } finally { if (!string.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!string.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) Dispose(m_session); } } #region IDisposable Members /// <summary> /// Public dispose method. /// </summary> public void Dispose() { // CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// Public dispose method. /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// BeginProcessing method. /// </summary> protected override void EndProcessing() { helper.CleanUp(); } } #endregion #region Remove-WsManInstance /// <summary> /// Executes action on a target object specified by RESOURCE_URI, where /// parameters are specified by key value pairs. /// eg., Call StartService method on the spooler service /// Set-WSManInstance -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// </summary> [Cmdlet(VerbsCommon.Remove, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096721")] public class RemoveWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { #region Parameters /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public string ApplicationName { get { return applicationname; } set { applicationname = value; } } private string applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Alias("cn")] public string ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) { computername = "localhost"; } } } private string computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hahs table which help modify or refine the nature of the /// request. These are similar to switches used in command line shells in that /// they are service-specific. /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] [ValidateNotNullOrEmpty] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] [ValidateRange(1, int.MaxValue)] public int Port { get { return port; } set { port = value; } } private int port = 0; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")] [Parameter(Mandatory = true, Position = 0)] [Alias("ruri")] [ValidateNotNullOrEmpty] public Uri ResourceURI { get { return resourceuri; } set { resourceuri = value; } } private Uri resourceuri; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are more than 1 instance of the resource /// class. /// </summary> [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [ValidateNotNullOrEmpty] public Hashtable SelectorSet { get { return selectorset; } set { selectorset = value; } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This can be created /// by using the cmdlet New-WSManSessionOption. /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("so")] [ValidateNotNullOrEmpty] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] [Alias("ssl")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; #endregion /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { WSManHelper helper = new WSManHelper(this); IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); helper.WSManOp = "remove"; IWSManSession m_session = null; try { string connectionStr = string.Empty; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try { // in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string ResourceURI = helper.GetURIWithFilter(resourceuri.ToString(), null, selectorset, helper.WSManOp); try { ((IWSManSession)m_session).Delete(ResourceURI, 0); } catch (Exception ex) { helper.AssertError(ex.Message, false, computername); } } finally { if (!string.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (!string.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (m_session != null) Dispose(m_session); } } #region IDisposable Members /// <summary> /// Public dispose method. /// </summary> public void Dispose() { // CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// Public dispose method. /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members } #endregion #region New-WsManInstance /// <summary> /// Creates an instance of a management resource identified by the resource URI /// using specified ValueSet or input File. /// </summary> [Cmdlet(VerbsCommon.New, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096933")] public class NewWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public string ApplicationName { get { return applicationname; } set { applicationname = value; } } private string applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Alias("cn")] public string ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.OrdinalIgnoreCase))) { computername = "localhost"; } } } private string computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] [Alias("CURI", "CU")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "FilePath". /// Updates the management resource specified by the ResourceURI and SelectorSet /// via this input file. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Alias("Path")] public string FilePath { get { return filepath; } set { filepath = value; } } private string filepath; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hash table and is used to pass a set of switches to the /// service to modify or refine the nature of the request. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] [ValidateRange(1, int.MaxValue)] public int Port { get { return port; } set { port = value; } } private int port = 0; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation. /// </summary> [Parameter(Mandatory = true, Position = 0)] [ValidateNotNullOrEmpty] [Alias("ruri")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ResourceURI { get { return resourceuri; } set { resourceuri = value; } } private Uri resourceuri; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are more than 1 instance of the resource /// class. /// </summary> [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable SelectorSet { get { return selectorset; } set { selectorset = value; } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("so")] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; /// <summary> /// The following is the definition of the input parameter "ValueSet". /// ValueSet is a hash table which helps to modify resource represented by the /// ResourceURI and SelectorSet. /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable ValueSet { get { return valueset; } set { valueset = value; } } private Hashtable valueset; private WSManHelper helper; private readonly IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); private IWSManSession m_session = null; private string connectionStr = string.Empty; /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { helper = new WSManHelper(this); helper.WSManOp = "new"; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try { // in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionuri.OriginalString.Split(":" + port + "/" + applicationname, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split("//", StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); // create the session object m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); try { string resultXml = m_session.Create(m_resource, input, 0); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(resultXml); WriteObject(xmldoc.DocumentElement); } catch (Exception ex) { helper.AssertError(ex.Message, false, computername); } } finally { if (!string.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!string.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) { Dispose(m_session); } } } #region IDisposable Members /// <summary> /// Public dispose method. /// </summary> public void Dispose() { // CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// Public dispose method. /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { helper.CleanUp(); } } #endregion }
/* ** $Id: lua.c,v 1.160.1.2 2007/12/28 15:32:23 roberto Exp $ ** Lua stand-alone interpreter ** See Copyright Notice in lua.h */ using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.IO; using System.Reflection; namespace SharpLua { public class LuaInteractive { //#define lua_c //#include "lua.h" //#include "lauxlib.h" //#include "lualib.h" static Lua.LuaState globalL = null; static Lua.CharPtr progname = Lua.LUA_PROGNAME; static void lstop(Lua.LuaState L, Lua.lua_Debug ar) { Lua.lua_sethook(L, null, 0, 0); Lua.luaL_error(L, "interrupted!"); } static void laction(int i) { //signal(i, SIG_DFL); /* if another SIGINT happens before lstop, // terminate process (default action) */ Lua.lua_sethook(globalL, lstop, Lua.LUA_MASKCALL | Lua.LUA_MASKRET | Lua.LUA_MASKCOUNT, 1); } static void print_usage() { Console.Error.Write( "usage: {0} [options] [script [args]].\n" + "Available options are:\n" + " -e stat execute string " + Lua.LUA_QL("stat").ToString() + "\n" + " -l name require library " + Lua.LUA_QL("name").ToString() + "\n" + " -i enter interactive mode after executing " + Lua.LUA_QL("script").ToString() + "\n" + " -v show version information\n" + " -- stop handling options\n" + " - execute stdin and stop handling options\n" , progname); Console.Error.Flush(); } static void l_message(Lua.CharPtr pname, Lua.CharPtr msg) { if (pname != null) Lua.fprintf(Lua.stderr, "%s: ", pname); Lua.fprintf(Lua.stderr, "%s\n", msg); Lua.fflush(Lua.stderr); } static int report(Lua.LuaState L, int status) { if ((status != 0) && !Lua.lua_isnil(L, -1)) { Lua.CharPtr msg = Lua.lua_tostring(L, -1); if (msg == null) msg = "(error object is not a string)"; l_message(progname, msg); Lua.lua_pop(L, 1); } return status; } static int traceback(Lua.LuaState L) { if (Lua.lua_isstring(L, 1) == 0) /* 'message' not a string? */ return 1; /* keep it intact */ Lua.lua_getfield(L, Lua.LUA_GLOBALSINDEX, "debug"); if (!Lua.lua_istable(L, -1)) { Lua.lua_pop(L, 1); return 1; } Lua.lua_getfield(L, -1, "traceback"); if (!Lua.lua_isfunction(L, -1)) { Lua.lua_pop(L, 2); return 1; } Lua.lua_pushvalue(L, 1); /* pass error message */ Lua.lua_pushinteger(L, 2); /* skip this function and traceback */ Lua.lua_call(L, 2, 1); /* call debug.traceback */ return 1; } static int docall(Lua.LuaState L, int narg, int clear) { int status; int base_ = Lua.lua_gettop(L) - narg; /* function index */ Lua.lua_pushcfunction(L, traceback); /* push traceback function */ Lua.lua_insert(L, base_); /* put it under chunk and args */ //signal(SIGINT, laction); status = Lua.lua_pcall(L, narg, ((clear != 0) ? 0 : Lua.LUA_MULTRET), base_); //signal(SIGINT, SIG_DFL); Lua.lua_remove(L, base_); /* remove traceback function */ /* force a complete garbage collection in case of errors */ if (status != 0) Lua.lua_gc(L, Lua.LUA_GCCOLLECT, 0); return status; } static void print_version() { l_message(null, Lua.LUA_RELEASE + " " + Lua.LUA_COPYRIGHT); } static int getargs(Lua.LuaState L, string[] argv, int n) { int narg; int i; int argc = argv.Length; /* count total number of arguments */ narg = argc - (n + 1); /* number of arguments to the script */ Lua.luaL_checkstack(L, narg + 3, "too many arguments to script"); for (i = n + 1; i < argc; i++) Lua.lua_pushstring(L, argv[i]); Lua.lua_createtable(L, narg, n + 1); for (i = 0; i < argc; i++) { Lua.lua_pushstring(L, argv[i]); Lua.lua_rawseti(L, -2, i - n); } return narg; } static int dofile(Lua.LuaState L, Lua.CharPtr name) { int status = (Lua.luaL_loadfile(L, name) != 0) || (docall(L, 0, 1) != 0) ? 1 : 0; return report(L, status); } static int dostring(Lua.LuaState L, Lua.CharPtr s, Lua.CharPtr name) { int status = (Lua.luaL_loadbuffer(L, s, (uint)Lua.strlen(s), name) != 0) || (docall(L, 0, 1) != 0) ? 1 : 0; return report(L, status); } static int dolibrary(Lua.LuaState L, Lua.CharPtr name) { Lua.lua_getglobal(L, "require"); Lua.lua_pushstring(L, name); return report(L, docall(L, 1, 1)); } static Lua.CharPtr get_prompt(Lua.LuaState L, int firstline) { Lua.CharPtr p; Lua.lua_getfield(L, Lua.LUA_GLOBALSINDEX, (firstline != 0) ? "_PROMPT" : "_PROMPT2"); p = Lua.lua_tostring(L, -1); if (p == null) p = ((firstline != 0) ? Lua.LUA_PROMPT : Lua.LUA_PROMPT2); Lua.lua_pop(L, 1); /* remove global */ return p; } static int incomplete(Lua.LuaState L, int status) { if (status == Lua.LUA_ERRSYNTAX) { uint lmsg; Lua.CharPtr msg = Lua.lua_tolstring(L, -1, out lmsg); Lua.CharPtr tp = msg + lmsg - (Lua.strlen(Lua.LUA_QL("<eof>"))); if (Lua.strstr(msg, Lua.LUA_QL("<eof>")) == tp) { Lua.lua_pop(L, 1); return 1; } } return 0; /* else... */ } static int pushline(Lua.LuaState L, int firstline) { Lua.CharPtr buffer = new char[Lua.LUA_MAXINPUT]; Lua.CharPtr b = new Lua.CharPtr(buffer); int l; Lua.CharPtr prmt = get_prompt(L, firstline); if (!Lua.lua_readline(L, b, prmt)) return 0; /* no input */ l = Lua.strlen(b); if (l > 0 && b[l - 1] == '\n') /* line ends with newline? */ b[l - 1] = '\0'; /* remove it */ if ((firstline != 0) && (b[0] == '=')) /* first line starts with `=' ? */ Lua.lua_pushfstring(L, "return %s", b + 1); /* change it to `return' */ else Lua.lua_pushstring(L, b); Lua.lua_freeline(L, b); return 1; } static int loadline(Lua.LuaState L) { int status; Lua.lua_settop(L, 0); if (pushline(L, 1) == 0) return -1; /* no input */ for (; ; ) { /* repeat until gets a complete line */ status = Lua.luaL_loadbuffer(L, Lua.lua_tostring(L, 1), Lua.lua_strlen(L, 1), "=stdin"); if (incomplete(L, status) == 0) break; /* cannot try to add lines? */ if (pushline(L, 0) == 0) /* no more input? */ return -1; Lua.lua_pushliteral(L, "\n"); /* add a new line... */ Lua.lua_insert(L, -2); /* ...between the two lines */ Lua.lua_concat(L, 3); /* join them */ } Lua.lua_saveline(L, 1); Lua.lua_remove(L, 1); /* remove line */ return status; } static void dotty(Lua.LuaState L) { int status; Lua.CharPtr oldprogname = progname; progname = null; while ((status = loadline(L)) != -1) { if (status == 0) status = docall(L, 0, 0); report(L, status); if (status == 0 && Lua.lua_gettop(L) > 0) { /* any result to print? */ Lua.lua_getglobal(L, "print"); Lua.lua_insert(L, 1); if (Lua.lua_pcall(L, Lua.lua_gettop(L) - 1, 0, 0) != 0) l_message(progname, Lua.lua_pushfstring(L, "error calling " + Lua.LUA_QL("print").ToString() + " (%s)", Lua.lua_tostring(L, -1))); } } Lua.lua_settop(L, 0); /* clear stack */ Lua.fputs("\n", Lua.stdout); Lua.fflush(Lua.stdout); progname = oldprogname; } static int handle_script(Lua.LuaState L, string[] argv, int n) { int status; Lua.CharPtr fname; int narg = getargs(L, argv, n); /* collect arguments */ Lua.lua_setglobal(L, "arg"); fname = argv[n]; if (Lua.strcmp(fname, "-") == 0 && Lua.strcmp(argv[n - 1], "--") != 0) fname = null; /* stdin */ status = Lua.luaL_loadfile(L, fname); Lua.lua_insert(L, -(narg + 1)); if (status == 0) status = docall(L, narg, 0); else Lua.lua_pop(L, narg); return report(L, status); } /* check that argument has no extra characters at the end */ //#define notail(x) {if ((x)[2] != '\0') return -1;} static int collectargs(string[] argv, ref int pi, ref int pv, ref int pe) { int i; for (i = 1; i < argv.Length; i++) { if (argv[i][0] != '-') /* not an option? */ return i; switch (argv[i][1]) { /* option */ case '-': if (argv[i].Length != 2) return -1; return (i + 1) >= argv.Length ? i + 1 : 0; case '\0': return i; case 'i': if (argv[i].Length != 2) return -1; pi = 1; if (argv[i].Length != 2) return -1; pv = 1; break; case 'v': if (argv[i].Length != 2) return -1; pv = 1; break; case 'e': pe = 1; if (argv[i].Length == 2) { i++; if (argv[i] == null) return -1; } break; case 'l': if (argv[i].Length == 2) { i++; if (i >= argv.Length) return -1; } break; default: return -1; /* invalid option */ } } return 0; } static int runargs(Lua.LuaState L, string[] argv, int n) { int i; for (i = 1; i < n; i++) { if (argv[i] == null) continue; Lua.lua_assert(argv[i][0] == '-'); switch (argv[i][1]) { /* option */ case 'e': { string chunk = argv[i].Substring(2); if (chunk == "") chunk = argv[++i]; Lua.lua_assert(chunk != null); if (dostring(L, chunk, "=(command line)") != 0) return 1; break; } case 'l': { string filename = argv[i].Substring(2); if (filename == "") filename = argv[++i]; Lua.lua_assert(filename != null); if (dolibrary(L, filename) != 0) return 1; /* stop if file fails */ break; } default: break; } } return 0; } static int handle_luainit(Lua.LuaState L) { Lua.CharPtr init = Lua.getenv(Lua.LUA_INIT); if (init == null) return 0; /* status OK */ else if (init[0] == '@') return dofile(L, init + 1); else return dostring(L, init, "=" + Lua.LUA_INIT); } public class Smain { public int argc; public string[] argv; public int status; }; static int pmain(Lua.LuaState L) { Smain s = (Smain)Lua.lua_touserdata(L, 1); string[] argv = s.argv; int script; int has_i = 0, has_v = 0, has_e = 0; globalL = L; if ((argv.Length > 0) && (argv[0] != "")) progname = argv[0]; Lua.lua_gc(L, Lua.LUA_GCSTOP, 0); /* stop collector during initialization */ Lua.luaL_openlibs(L); /* open libraries */ Lua.lua_gc(L, Lua.LUA_GCRESTART, 0); s.status = handle_luainit(L); if (s.status != 0) return 0; script = collectargs(argv, ref has_i, ref has_v, ref has_e); if (script < 0) { /* invalid args? */ print_usage(); s.status = 1; return 0; } if (has_v != 0) print_version(); s.status = runargs(L, argv, (script > 0) ? script : s.argc); if (s.status != 0) return 0; if (script != 0) s.status = handle_script(L, argv, script); if (s.status != 0) return 0; if (has_i != 0) dotty(L); else if ((script == 0) && (has_e == 0) && (has_v == 0)) { if (Lua.lua_stdin_is_tty() != 0) { print_version(); dotty(L); } else dofile(L, null); /* executes stdin as a file */ } return 0; } static int Main(string[] args) { // prepend the exe name to the arg list as it's done in C // so that we don't have to change any of the args indexing // code above List<string> newargs = new List<string>(args); newargs.Insert(0, Assembly.GetExecutingAssembly().Location); args = (string[])newargs.ToArray(); int status; Smain s = new Smain(); Lua.LuaState L = Lua.lua_open(); /* create state */ if (L == null) { l_message(args[0], "cannot create state: not enough memory"); return Lua.EXIT_FAILURE; } s.argc = args.Length; s.argv = args; status = Lua.lua_cpcall(L, pmain, s); report(L, status); Lua.lua_close(L); return (status != 0) || (s.status != 0) ? Lua.EXIT_FAILURE : Lua.EXIT_SUCCESS; } } }
#region MIT License /* * Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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. */ #endregion #if UseDouble using Scalar = System.Double; #else using Scalar = System.Single; #endif using System; using System.Runtime.InteropServices; using AdvanceMath.Design; namespace AdvanceMath.Geometry2D { [StructLayout(LayoutKind.Sequential, Size = LineSegment.Size), Serializable] [AdvBrowsableOrder("Vertex1,Vertex2")] #if !CompactFramework && !WindowsCE && !PocketPC && !XBOX360 && !SILVERLIGHT [System.ComponentModel.TypeConverter(typeof(AdvTypeConverter<LineSegment>))] #endif public struct LineSegment : IEquatable<LineSegment> { public const int Size = Vector2D.Size * 2; public static void Intersects(ref Vector2D v1, ref Vector2D v2, ref Vector2D v3, ref Vector2D v4, out bool result) { Scalar div, ua, ub; div = 1 / ((v4.Y - v3.Y) * (v2.X - v1.X) - (v4.X - v3.X) * (v2.Y - v1.Y)); ua = ((v4.X - v3.X) * (v1.Y - v3.Y) - (v4.Y - v3.Y) * (v1.X - v3.X)) * div; ub = ((v2.X - v1.X) * (v1.Y - v3.Y) - (v2.Y - v1.Y) * (v1.X - v3.X)) * div; result = ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1; } public static bool Intersects(ref Vector2D v1, ref Vector2D v2, ref Vector2D v3, ref Vector2D v4, out Vector2D result) { Scalar div, ua, ub; div = 1 / ((v4.Y - v3.Y) * (v2.X - v1.X) - (v4.X - v3.X) * (v2.Y - v1.Y)); ua = ((v4.X - v3.X) * (v1.Y - v3.Y) - (v4.Y - v3.Y) * (v1.X - v3.X)) * div; ub = ((v2.X - v1.X) * (v1.Y - v3.Y) - (v2.Y - v1.Y) * (v1.X - v3.X)) * div; if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1) { Vector2D.Lerp(ref v1, ref v2, ref ua, out result); return true; } else { result = Vector2D.Zero; return false; } } public static void Intersects(ref Vector2D vertex1, ref Vector2D vertex2, ref Ray ray, out Scalar result) { Vector2D tanget, normal; Scalar edgeMagnitude; Vector2D.Subtract(ref vertex1, ref vertex2, out tanget); Vector2D.Normalize(ref tanget, out edgeMagnitude, out tanget); Vector2D.GetRightHandNormal(ref tanget, out normal); Scalar dir; Vector2D.Dot(ref normal, ref ray.Direction, out dir); if (Math.Abs(dir) >= MathHelper.Tolerance) { Vector2D originDiff; Vector2D.Subtract(ref ray.Origin, ref vertex2, out originDiff); Scalar actualDistance; Vector2D.Dot(ref normal, ref originDiff, out actualDistance); Scalar DistanceFromOrigin = -(actualDistance / dir); if (DistanceFromOrigin >= 0) { Vector2D intersectPos; Vector2D.Multiply(ref ray.Direction, ref DistanceFromOrigin, out intersectPos); Vector2D.Add(ref intersectPos, ref originDiff, out intersectPos); Scalar distanceFromSecond; Vector2D.Dot(ref intersectPos, ref tanget, out distanceFromSecond); if (distanceFromSecond >= 0 && distanceFromSecond <= edgeMagnitude) { result = DistanceFromOrigin; return; } } } result = -1; } public static void GetDistance(ref Vector2D vertex1, ref Vector2D vertex2, ref Vector2D point, out Scalar result) { Scalar edgeLength; Vector2D edge, local; Vector2D.Subtract(ref point, ref vertex2, out local); Vector2D.Subtract(ref vertex1, ref vertex2, out edge); Vector2D.Normalize(ref edge, out edgeLength, out edge); Scalar nProj = local.Y * edge.X - local.X * edge.Y; Scalar tProj = local.X * edge.X + local.Y * edge.Y; if (tProj < 0) { result = MathHelper.Sqrt(tProj * tProj + nProj * nProj); } else if (tProj > edgeLength) { tProj -= edgeLength; result = MathHelper.Sqrt(tProj * tProj + nProj * nProj); } else { result = Math.Abs(nProj); } } public static void GetDistanceSq(ref Vector2D vertex1, ref Vector2D vertex2, ref Vector2D point, out Scalar result) { Scalar edgeLength; Vector2D edge, local; Vector2D.Subtract(ref point, ref vertex2, out local); Vector2D.Subtract(ref vertex1, ref vertex2, out edge); Vector2D.Normalize(ref edge, out edgeLength, out edge); Scalar nProj = local.Y * edge.X - local.X * edge.Y; Scalar tProj = local.X * edge.X + local.Y * edge.Y; if (tProj < 0) { result = tProj * tProj + nProj * nProj; } else if (tProj > edgeLength) { tProj -= edgeLength; result = tProj * tProj + nProj * nProj; } else { result = nProj * nProj; } } [AdvBrowsable] public Vector2D Vertex1; [AdvBrowsable] public Vector2D Vertex2; [InstanceConstructor("Vertex1,Vertex2")] public LineSegment(Vector2D vertex1, Vector2D vertex2) { this.Vertex1 = vertex1; this.Vertex2 = vertex2; } public Scalar GetDistance(Vector2D point) { Scalar result; GetDistance(ref point, out result); return result; } public void GetDistance(ref Vector2D point, out Scalar result) { GetDistance(ref Vertex1, ref Vertex2, ref point, out result); } public Scalar Intersects(Ray ray) { Scalar result; Intersects(ref ray, out result); return result; } public void Intersects(ref Ray ray, out Scalar result) { Intersects(ref Vertex1, ref Vertex2, ref ray, out result); } public override string ToString() { return string.Format("V1: {0} V2: {1}", Vertex1, Vertex2); } public override int GetHashCode() { return Vertex1.GetHashCode() ^ Vertex2.GetHashCode(); } public override bool Equals(object obj) { return obj is LineSegment && Equals((LineSegment)obj); } public bool Equals(LineSegment other) { return Equals(ref this, ref other); } public static bool Equals(LineSegment line1, LineSegment line2) { return Equals(ref line1, ref line2); } [CLSCompliant(false)] public static bool Equals(ref LineSegment line1, ref LineSegment line2) { return Vector2D.Equals(ref line1.Vertex1, ref line2.Vertex1) && Vector2D.Equals(ref line1.Vertex2, ref line2.Vertex2); } public static bool operator ==(LineSegment line1, LineSegment line2) { return Equals(ref line1, ref line2); } public static bool operator !=(LineSegment line1, LineSegment line2) { return !Equals(ref line1, ref line2); } } }
using System; using System.Globalization; /// <summary> /// ConvertToUInt16(String,IFormatProvider) /// </summary> public class ConvertToUInt6417 { public static int Main() { ConvertToUInt6417 convertToUInt6417 = new ConvertToUInt6417(); TestLibrary.TestFramework.BeginTestCase("ConvertToUInt6417"); if (convertToUInt6417.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]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert to UInt64 from string 1"); try { string strVal = UInt64.MaxValue.ToString(); ulong ulongVal = Convert.ToUInt64(strVal, null); if (ulongVal != UInt64.MaxValue) { TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Convert to UInt64 from string 2"); try { string strVal = UInt64.MaxValue.ToString(); CultureInfo myculture = new CultureInfo("en-us"); IFormatProvider provider = myculture.NumberFormat; ulong ulongVal = Convert.ToUInt64(strVal, provider); if (ulongVal != UInt64.MaxValue) { TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Convert to UInt64 from string 3"); try { string strVal = UInt64.MinValue.ToString(); ulong ulongVal = Convert.ToUInt64(strVal, null); if (ulongVal != UInt64.MinValue) { TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert to UInt64 from string 4"); try { string strVal = "-" + UInt64.MinValue.ToString(); ulong ulongVal = Convert.ToUInt64(strVal, null); if (ulongVal != UInt64.MinValue) { TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Convert to UInt64 from string 5"); try { ulong sourceVal = (UInt64)TestLibrary.Generator.GetInt64(-55); string strVal = "+" + sourceVal.ToString(); ulong ulongVal = Convert.ToUInt64(strVal, null); if (ulongVal != sourceVal) { TestLibrary.TestFramework.LogError("009", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Convert to UInt64 from string 6"); try { string strVal = null; ulong ulongVal = Convert.ToUInt64(strVal, null); if (ulongVal != 0) { TestLibrary.TestFramework.LogError("011", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: the string represents a number less than MinValue"); try { int intVal = this.GetInt32(1, Int32.MaxValue); string strVal = "-" + intVal.ToString(); ulong ulongVal = Convert.ToUInt64(strVal, null); TestLibrary.TestFramework.LogError("N001", "the string represents a number less than MinValue but not throw exception"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: the string represents a number greater than MaxValue"); try { string strVal = UInt64.MaxValue.ToString() + "1"; ulong ulongVal = Convert.ToUInt64(strVal, null); TestLibrary.TestFramework.LogError("N003", "the string represents a number greater than MaxValue but not throw exception"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: the string does not consist of an optional sign followed by a sequence of digits "); try { string strVal = "helloworld"; ulong ulongVal = Convert.ToUInt64(strVal, null); TestLibrary.TestFramework.LogError("N005", "the string does not consist of an optional sign followed by a sequence of digits but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: the string is empty string"); try { string strVal = string.Empty; ulong ulongVal = Convert.ToUInt64(strVal, null); TestLibrary.TestFramework.LogError("N007", "the string is empty string but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// Creates a Spot Instance request. /// </summary> /// <remarks> /// Spot Instances are instances that Amazon EC2 starts on your behalf /// when the maximum price that you specify exceeds the current Spot Price. /// Amazon EC2 periodically sets the Spot Price based on available /// Spot Instance capacity and current Spot Instance requests. /// </remarks> [XmlRootAttribute(IsNullable = false)] public class RequestSpotInstancesRequest : EC2Request { private string spotPriceField; private Decimal? instanceCountField; private string typeField; private string validFromField; private string validUntilField; private string launchGroupField; private string availabilityZoneGroupField; private LaunchSpecification launchSpecificationField; /// <summary> /// The maximum price you will pay to launch one or more Spot Instances. /// </summary> [XmlElementAttribute(ElementName = "SpotPrice")] public string SpotPrice { get { return this.spotPriceField; } set { this.spotPriceField = value; } } /// <summary> /// Sets the maximum price you will pay to launch one or more Spot Instances. /// </summary> /// <param name="spotPrice">Specifies the maximum price you will pay to /// launch one or more Spot Instances.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestSpotInstancesRequest WithSpotPrice(string spotPrice) { this.spotPriceField = spotPrice; return this; } /// <summary> /// Checks if SpotPrice property is set /// </summary> /// <returns>true if SpotPrice property is set</returns> public bool IsSetSpotPrice() { return this.spotPriceField != null; } /// <summary> /// The maximum number of Spot Instances to launch. /// Default is 1. /// </summary> [XmlElementAttribute(ElementName = "InstanceCount")] public Decimal InstanceCount { get { return this.instanceCountField.GetValueOrDefault(); } set { this.instanceCountField = value; } } /// <summary> /// Sets the maximum number of Spot Instances to launch. /// </summary> /// <param name="instanceCount">The maximum number of Spot Instances to launch. Default - 1.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestSpotInstancesRequest WithInstanceCount(Decimal instanceCount) { this.instanceCountField = instanceCount; return this; } /// <summary> /// Checks if InstanceCount property is set /// </summary> /// <returns>true if InstanceCount property is set</returns> public bool IsSetInstanceCount() { return this.instanceCountField.HasValue; } /// <summary> /// The instance type. /// Valid values: m1.small|m1.medium|m1.large|m1.xlarge|c1.medium|c1.xlarge|m2.2xlarge|m4.4xlarge /// Default - m1.small. /// </summary> [XmlElementAttribute(ElementName = "Type")] public string Type { get { return this.typeField; } set { this.typeField = value; } } /// <summary> /// Sets the instance type. /// </summary> /// <param name="type">The instance type. Valid values: /// m1.small|m1.medium|m1.large|m1.xlarge|c1.medium|c1.xlarge|m2.2xlarge|m4.4xlarge. /// Default - m1.small.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestSpotInstancesRequest WithType(string type) { this.typeField = type; return this; } /// <summary> /// Checks if Type property is set /// </summary> /// <returns>true if Type property is set</returns> public bool IsSetType() { return this.typeField != null; } /// <summary> /// Start date of the request. /// If this is a one-time request, the request remains active until all instances /// launch, the request expires, or the request is canceled. If the /// request is persistent, it remains active until it expires or /// is canceled. /// Default: Request is effective immediately /// </summary> [XmlElementAttribute(ElementName = "ValidFrom")] public string ValidFrom { get { return this.validFromField; } set { this.validFromField = value; } } /// <summary> /// Sets the start date of the request. /// </summary> /// <param name="validFrom">Start date of the request. If this is a one-time request, /// the request remains active until all instances /// launch, the request expires, or the request is canceled. If the /// request is persistent, it remains active until it expires or /// is canceled. /// Default: Request is effective immediately</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestSpotInstancesRequest WithValidFrom(string validFrom) { this.validFromField = validFrom; return this; } /// <summary> /// Checks if ValidFrom property is set /// </summary> /// <returns>true if ValidFrom property is set</returns> public bool IsSetValidFrom() { return this.validFromField != null; } /// <summary> /// End date of the request. /// If this is a one-time request, the request remains active /// until all instances launch, the request expires, or the /// request is canceled. If the request is persistent, it remains /// active until it expires or is canceled. /// Default: Request remains open until criteria for closing are met /// </summary> [XmlElementAttribute(ElementName = "ValidUntil")] public string ValidUntil { get { return this.validUntilField; } set { this.validUntilField = value; } } /// <summary> /// Sets the end date of the request. /// </summary> /// <param name="validUntil">End date of the request. If this is a one-time request, /// the request remains active until all instances launch, /// the request expires, or the request is canceled. If the /// request is persistent, it remains active until it expires or /// is canceled. /// Default: Request remains open until criteria for closing are met</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestSpotInstancesRequest WithValidUntil(string validUntil) { this.validUntilField = validUntil; return this; } /// <summary> /// Checks if ValidUntil property is set /// </summary> /// <returns>true if ValidUntil property is set</returns> public bool IsSetValidUntil() { return this.validUntilField != null; } /// <summary> /// The instance launch group. /// Launch groups are Spot Instances that launch together and terminate /// together. /// Default: Instances are launched and terminated individually /// </summary> [XmlElementAttribute(ElementName = "LaunchGroup")] public string LaunchGroup { get { return this.launchGroupField; } set { this.launchGroupField = value; } } /// <summary> /// Sets the instance launch group. /// </summary> /// <param name="launchGroup">Specifies the instance launch group. Launch /// groups are Spot Instances that launch together and terminate /// together. /// Default: Instances are launched and terminated individually</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestSpotInstancesRequest WithLaunchGroup(string launchGroup) { this.launchGroupField = launchGroup; return this; } /// <summary> /// Checks if LaunchGroup property is set /// </summary> /// <returns>true if LaunchGroup property is set</returns> public bool IsSetLaunchGroup() { return this.launchGroupField != null; } /// <summary> /// The Availability Zone group. /// If you specify the same Availability Zone group for all /// Spot Instance requests, all Spot Instances are launched /// in the same Availability Zone. /// Default: Instances are launched in any available Availability Zone. /// </summary> [XmlElementAttribute(ElementName = "AvailabilityZoneGroup")] public string AvailabilityZoneGroup { get { return this.availabilityZoneGroupField; } set { this.availabilityZoneGroupField = value; } } /// <summary> /// Sets the Availability Zone group. /// </summary> /// <param name="availabilityZoneGroup">Specifies the Availability Zone group. If you specify /// the same Availability Zone group for all Spot Instance /// requests, all Spot Instances are launched in the same /// Availability Zone. /// Default: Instances are launched in any available Availability Zone.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestSpotInstancesRequest WithAvailabilityZoneGroup(string availabilityZoneGroup) { this.availabilityZoneGroupField = availabilityZoneGroup; return this; } /// <summary> /// Checks if AvailabilityZoneGroup property is set /// </summary> /// <returns>true if AvailabilityZoneGroup property is set</returns> public bool IsSetAvailabilityZoneGroup() { return this.availabilityZoneGroupField != null; } /// <summary> /// Additional launch instance information. /// </summary> [XmlElementAttribute(ElementName = "LaunchSpecification")] public LaunchSpecification LaunchSpecification { get { return this.launchSpecificationField; } set { this.launchSpecificationField = value; } } /// <summary> /// Sets additional launch instance information. /// </summary> /// <param name="launchSpecification">Specifies additional launch instance information.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public RequestSpotInstancesRequest WithLaunchSpecification(LaunchSpecification launchSpecification) { this.launchSpecificationField = launchSpecification; return this; } /// <summary> /// Checks if LaunchSpecification property is set /// </summary> /// <returns>true if LaunchSpecification property is set</returns> public bool IsSetLaunchSpecification() { return this.launchSpecificationField != null; } } }
// *********************************************************************** // Assembly : ACBr.Net.Sat // Author : RFTD // Created : 04-23-2016 // // Last Modified By : RFTD // Last Modified On : 04-29-2016 // *********************************************************************** // <copyright file="CFeDetProd.cs" company="ACBr.Net"> // The MIT License (MIT) // Copyright (c) 2016 Grupo ACBr.Net // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // </copyright> // <summary></summary> // *********************************************************************** using ACBr.Net.DFe.Core.Attributes; using ACBr.Net.DFe.Core.Collection; using ACBr.Net.DFe.Core.Serializer; using PropertyChanged; using System.Globalization; namespace ACBr.Net.Sat { /// <summary> /// Class CFeDetProd. This class cannot be inherited. /// </summary> [ImplementPropertyChanged] public sealed class CFeDetProd { #region Fields private bool ehConbustivel; #endregion Fields #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CFeDetProd"/> class. /// </summary> public CFeDetProd() { ObsFiscoDet = new DFeCollection<ProdObsFisco>(); EhCombustivel = false; } /// <summary> /// Initializes a new instance of the <see cref="CFeDetProd"/> class. /// </summary> public CFeDetProd(CFe parent) : this() { Parent = parent; } #endregion Constructors #region Propriedades /// <summary> /// Gets the parent. /// </summary> /// <value>The parent.</value> [DFeIgnore] internal CFe Parent { get; set; } /// <summary> /// Gets or sets a value indicating whether [eh combustivel]. /// </summary> /// <value><c>true</c> if [eh combustivel]; otherwise, <c>false</c>.</value> [DFeIgnore] public bool EhCombustivel { get { return ehConbustivel; } set { if (value == ehConbustivel) return; IndRegra = value ? IndRegra.Truncamento : IndRegra.Arredondamento; ehConbustivel = value; } } /// <summary> /// Gets or sets the c product. /// </summary> /// <value>The c product.</value> [DFeElement(TipoCampo.Str, "cProd", Id = "I02", Min = 1, Max = 60, Ocorrencia = Ocorrencia.Obrigatoria)] public string CProd { get; set; } /// <summary> /// Gets or sets the c ean. /// </summary> /// <value>The c ean.</value> [DFeElement(TipoCampo.Str, "cEAN", Id = "I03", Min = 8, Max = 14, Ocorrencia = Ocorrencia.NaoObrigatoria)] public string CEAN { get; set; } /// <summary> /// Gets or sets the x product. /// </summary> /// <value>The x product.</value> [DFeElement(TipoCampo.Str, "xProd", Id = "I04", Min = 1, Max = 120, Ocorrencia = Ocorrencia.Obrigatoria)] public string XProd { get; set; } /// <summary> /// Gets or sets the NCM. /// </summary> /// <value>The NCM.</value> [DFeElement(TipoCampo.Str, "NCM", Id = "I05", Min = 2, Max = 8, Ocorrencia = Ocorrencia.NaoObrigatoria)] public string NCM { get; set; } /// <summary> /// Gets or sets the cest. /// </summary> /// <value>The cest.</value> [DFeElement(TipoCampo.Str, "CEST", Id = "I05w", Min = 2, Max = 7, Ocorrencia = Ocorrencia.NaoObrigatoria)] public string CEST { get; set; } /// <summary> /// Gets or sets the cfop. /// </summary> /// <value>The cfop.</value> [DFeElement(TipoCampo.StrNumberFill, "CFOP", Id = "I06", Min = 4, Max = 4, Ocorrencia = Ocorrencia.Obrigatoria)] public string CFOP { get; set; } /// <summary> /// Gets or sets the u COM. /// </summary> /// <value>The u COM.</value> [DFeElement(TipoCampo.Str, "uCom", Id = "I07", Min = 1, Max = 6, Ocorrencia = Ocorrencia.Obrigatoria)] public string UCom { get; set; } /// <summary> /// Gets or sets the q COM. /// </summary> /// <value>The q COM.</value> [DFeElement(TipoCampo.De4, "qCom", Id = "I08", Min = 5, Max = 15, Ocorrencia = Ocorrencia.Obrigatoria)] public decimal QCom { get; set; } /// <summary> /// Gets or sets the v un COM. /// </summary> /// <value>The v un COM.</value> [DFeElement(TipoCampo.Custom, "vUnCom", Id = "I09", Min = 3, Max = 15, Ocorrencia = Ocorrencia.Obrigatoria)] public decimal VUnCom { get; set; } /// <summary> /// Gets or sets the v product. /// </summary> /// <value>The v product.</value> [DFeElement(TipoCampo.De2, "vProd", Id = "I10", Min = 3, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)] public decimal VProd { get; set; } /// <summary> /// Gets or sets the ind regra. /// </summary> /// <value>The ind regra.</value> [DFeElement(TipoCampo.Enum, "indRegra", Id = "I11", Min = 1, Max = 1, Ocorrencia = Ocorrencia.Obrigatoria)] public IndRegra IndRegra { get; set; } /// <summary> /// Gets or sets the v desc. /// </summary> /// <value>The v desc.</value> [DFeElement(TipoCampo.De2, "vDesc", Id = "I12", Min = 3, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)] public decimal VDesc { get; set; } /// <summary> /// Gets or sets the v outro. /// </summary> /// <value>The v outro.</value> [DFeElement(TipoCampo.De2, "vOutro", Id = "I13", Min = 3, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)] public decimal VOutro { get; set; } /// <summary> /// Gets or sets the v item. /// </summary> /// <value>The v item.</value> [DFeElement(TipoCampo.De2, "vItem", Id = "I14", Min = 3, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)] public decimal VItem { get; set; } /// <summary> /// Gets or sets the v rat desc. /// </summary> /// <value>The v rat desc.</value> [DFeElement(TipoCampo.De2, "vRatDesc", Id = "I15", Min = 3, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)] public decimal VRatDesc { get; set; } /// <summary> /// Gets or sets the v rat acr. /// </summary> /// <value>The v rat acr.</value> [DFeElement(TipoCampo.De2, "vRatAcr", Id = "I16", Min = 3, Max = 15, Ocorrencia = Ocorrencia.MaiorQueZero)] public decimal VRatAcr { get; set; } /// <summary> /// Gets or sets the obs fisco det. /// </summary> /// <value>The obs fisco det.</value> [DFeCollection("obsFiscoDet", Id = "I18", MinSize = 0, MaxSize = 500, Ocorrencia = Ocorrencia.NaoObrigatoria)] public DFeCollection<ProdObsFisco> ObsFiscoDet { get; set; } #endregion Propriedades #region Methods private bool ShouldSerializeCEST() { return Parent != null && Parent.InfCFe.Ide.DEmi.Year > 2016; } private string SerializeVUnCom() { var numberFormat = CultureInfo.InvariantCulture.NumberFormat; var format = ehConbustivel ? "{0:0.000}" : "{0:0.00}"; return string.Format(numberFormat, format, VUnCom); } private object DeserializeVUnCom(string value) { var decimais = value.Split('.')[1]; EhCombustivel = decimais.Length > 2; var numberFormat = CultureInfo.InvariantCulture.NumberFormat; return decimal.Parse(value, numberFormat); } #endregion Methods } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Net; using System.Security.Claims; using System.Threading.Tasks; using FluentAssertions; using IdentityServer.IntegrationTests.Common; using IdentityServer4.Models; using IdentityServer4.Stores; using IdentityServer4.Stores.Default; using IdentityServer4.Test; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace IdentityServer.IntegrationTests.Endpoints.Authorize { public class ConsentTests { private const string Category = "Authorize and consent tests"; private IdentityServerPipeline _mockPipeline = new IdentityServerPipeline(); public ConsentTests() { _mockPipeline.Clients.AddRange(new Client[] { new Client { ClientId = "client1", AllowedGrantTypes = GrantTypes.Implicit, RequireConsent = false, AllowedScopes = new List<string> { "openid", "profile" }, RedirectUris = new List<string> { "https://client1/callback" }, AllowAccessTokensViaBrowser = true }, new Client { ClientId = "client2", AllowedGrantTypes = GrantTypes.Implicit, RequireConsent = true, AllowedScopes = new List<string> { "openid", "profile", "api1", "api2" }, RedirectUris = new List<string> { "https://client2/callback" }, AllowAccessTokensViaBrowser = true }, new Client { ClientId = "client3", AllowedGrantTypes = GrantTypes.Implicit, RequireConsent = false, AllowedScopes = new List<string> { "openid", "profile", "api1", "api2" }, RedirectUris = new List<string> { "https://client3/callback" }, AllowAccessTokensViaBrowser = true, IdentityProviderRestrictions = new List<string> { "google" } } }); _mockPipeline.Users.Add(new TestUser { SubjectId = "bob", Username = "bob", Claims = new Claim[] { new Claim("name", "Bob Loblaw"), new Claim("email", "bob@loblaw.com"), new Claim("role", "Attorney") } }); _mockPipeline.IdentityScopes.AddRange(new IdentityResource[] { new IdentityResources.OpenId(), new IdentityResources.Profile(), new IdentityResources.Email() }); _mockPipeline.ApiScopes.AddRange(new ApiResource[] { new ApiResource { Name = "api", Scopes = { new Scope { Name = "api1" }, new Scope { Name = "api2" } } } }); _mockPipeline.Initialize(); } [Fact] [Trait("Category", Category)] public async Task client_requires_consent_should_show_consent_page() { await _mockPipeline.LoginAsync("bob"); var url = _mockPipeline.CreateAuthorizeUrl( clientId: "client2", responseType: "id_token", scope: "openid", redirectUri: "https://client2/callback", state: "123_state", nonce: "123_nonce" ); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ConsentWasCalled.Should().BeTrue(); } [Theory] [InlineData((Type)null)] [InlineData(typeof(QueryStringAuthorizationParametersMessageStore))] [InlineData(typeof(DistributedCacheAuthorizationParametersMessageStore))] [Trait("Category", Category)] public async Task consent_page_should_have_authorization_params(Type storeType) { if (storeType != null) { _mockPipeline.OnPostConfigureServices += services => { services.AddTransient(typeof(IAuthorizationParametersMessageStore), storeType); }; _mockPipeline.Initialize(); } await _mockPipeline.LoginAsync("bob"); var url = _mockPipeline.CreateAuthorizeUrl( clientId: "client2", responseType: "id_token token", scope: "openid api1 api2", redirectUri: "https://client2/callback", state: "123_state", nonce: "123_nonce", acrValues: "acr_1 acr_2 tenant:tenant_value", extra: new { display = "popup", // must use a valid value form the spec for display ui_locales = "ui_locale_value", custom_foo = "foo_value" } ); var response = await _mockPipeline.BrowserClient.GetAsync(url); _mockPipeline.ConsentRequest.Should().NotBeNull(); _mockPipeline.ConsentRequest.ClientId.Should().Be("client2"); _mockPipeline.ConsentRequest.DisplayMode.Should().Be("popup"); _mockPipeline.ConsentRequest.UiLocales.Should().Be("ui_locale_value"); _mockPipeline.ConsentRequest.Tenant.Should().Be("tenant_value"); _mockPipeline.ConsentRequest.AcrValues.Should().BeEquivalentTo(new string[] { "acr_2", "acr_1" }); _mockPipeline.ConsentRequest.Parameters.AllKeys.Should().Contain("custom_foo"); _mockPipeline.ConsentRequest.Parameters["custom_foo"].Should().Be("foo_value"); _mockPipeline.ConsentRequest.ScopesRequested.Should().BeEquivalentTo(new string[] { "api2", "openid", "api1" }); } [Theory] [InlineData((Type)null)] [InlineData(typeof(QueryStringAuthorizationParametersMessageStore))] [InlineData(typeof(DistributedCacheAuthorizationParametersMessageStore))] [Trait("Category", Category)] public async Task consent_response_should_allow_successful_authorization_response(Type storeType) { if (storeType != null) { _mockPipeline.OnPostConfigureServices += services => { services.AddTransient(typeof(IAuthorizationParametersMessageStore), storeType); }; _mockPipeline.Initialize(); } await _mockPipeline.LoginAsync("bob"); _mockPipeline.ConsentResponse = new ConsentResponse() { ScopesConsented = new string[] { "openid", "api2" } }; _mockPipeline.BrowserClient.StopRedirectingAfter = 2; var url = _mockPipeline.CreateAuthorizeUrl( clientId: "client2", responseType: "id_token token", scope: "openid profile api1 api2", redirectUri: "https://client2/callback", state: "123_state", nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); response.StatusCode.Should().Be(HttpStatusCode.Redirect); response.Headers.Location.ToString().Should().StartWith("https://client2/callback"); var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); authorization.IsError.Should().BeFalse(); authorization.IdentityToken.Should().NotBeNull(); authorization.State.Should().Be("123_state"); var scopes = authorization.Scope.Split(' '); scopes.Should().BeEquivalentTo(new string[] { "api2", "openid" }); } [Fact] [Trait("Category", Category)] public async Task consent_response_should_reject_modified_request_params() { await _mockPipeline.LoginAsync("bob"); _mockPipeline.ConsentResponse = new ConsentResponse() { ScopesConsented = new string[] { "openid", "api2" } }; _mockPipeline.BrowserClient.AllowAutoRedirect = false; var url = _mockPipeline.CreateAuthorizeUrl( clientId: "client2", responseType: "id_token token", scope: "openid profile api2", redirectUri: "https://client2/callback", state: "123_state", nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); response.StatusCode.Should().Be(HttpStatusCode.Redirect); response.Headers.Location.ToString().Should().StartWith("https://server/consent"); response = await _mockPipeline.BrowserClient.GetAsync(response.Headers.Location.ToString()); response.StatusCode.Should().Be(HttpStatusCode.Redirect); response.Headers.Location.ToString().Should().StartWith("/connect/authorize/callback"); var modifiedAuthorizeCallback = "https://server" + response.Headers.Location.ToString(); modifiedAuthorizeCallback = modifiedAuthorizeCallback.Replace("api2", "api1%20api2"); response = await _mockPipeline.BrowserClient.GetAsync(modifiedAuthorizeCallback); response.StatusCode.Should().Be(HttpStatusCode.Redirect); response.Headers.Location.ToString().Should().StartWith("https://server/consent"); } [Fact()] [Trait("Category", Category)] public async Task consent_response_missing_required_scopes_should_error() { await _mockPipeline.LoginAsync("bob"); _mockPipeline.ConsentResponse = new ConsentResponse() { ScopesConsented = new string[] { "api2" } }; _mockPipeline.BrowserClient.StopRedirectingAfter = 2; var url = _mockPipeline.CreateAuthorizeUrl( clientId: "client2", responseType: "id_token token", scope: "openid profile api1 api2", redirectUri: "https://client2/callback", state: "123_state", nonce: "123_nonce"); var response = await _mockPipeline.BrowserClient.GetAsync(url); response.StatusCode.Should().Be(HttpStatusCode.Redirect); response.Headers.Location.ToString().Should().StartWith("https://client2/callback"); var authorization = new IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString()); authorization.IsError.Should().BeTrue(); authorization.Error.Should().Be("access_denied"); authorization.State.Should().Be("123_state"); } } }
//------------------------------------------------------------------------------ // <copyright file="SqlPersonalizationProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls.WebParts { using System; using System.Collections; using System.Collections.Specialized; using System.Configuration.Provider; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Web; using System.Web.DataAccess; using System.Web.Util; /// <devdoc> /// The provider used to access the personalization store for WebPart pages from a SQL Server /// database. /// </devdoc> public class SqlPersonalizationProvider : PersonalizationProvider { private enum ResetUserStateMode { PerInactiveDate, PerPaths, PerUsers } private const int maxStringLength = 256; private string _applicationName; private int _commandTimeout; private string _connectionString; private int _SchemaVersionCheck; /// <devdoc> /// Initializes an instance of SqlPersonalizationProvider. /// </devdoc> public SqlPersonalizationProvider() { } public override string ApplicationName { get { if (String.IsNullOrEmpty(_applicationName)) { _applicationName = SecUtility.GetDefaultAppName(); } return _applicationName; } set { if (value != null && value.Length > maxStringLength) { throw new ProviderException(SR.GetString(SR.PersonalizationProvider_ApplicationNameExceedMaxLength, maxStringLength.ToString(CultureInfo.CurrentCulture))); } _applicationName = value; } } /// <devdoc> /// </devdoc> private SqlParameter CreateParameter(string name, SqlDbType dbType, object value) { SqlParameter param = new SqlParameter(name, dbType); param.Value = value; return param; } private PersonalizationStateInfoCollection FindSharedState(string path, int pageIndex, int pageSize, out int totalRecords) { SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; SqlDataReader reader = null; totalRecords = 0; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; Debug.Assert(connection != null); CheckSchemaVersion( connection ); SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_FindState", connection); SetCommandTypeAndTimeout(command); SqlParameterCollection parameters = command.Parameters; SqlParameter parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit)); parameter.Value = true; parameters.AddWithValue("ApplicationName", ApplicationName); parameters.AddWithValue("PageIndex", pageIndex); parameters.AddWithValue("PageSize", pageSize); SqlParameter returnValue = new SqlParameter("@ReturnValue", SqlDbType.Int); returnValue.Direction = ParameterDirection.ReturnValue; parameters.Add(returnValue); parameter = parameters.Add("Path", SqlDbType.NVarChar); if (path != null) { parameter.Value = path; } parameter = parameters.Add("UserName", SqlDbType.NVarChar); parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime); reader = command.ExecuteReader(CommandBehavior.SequentialAccess); PersonalizationStateInfoCollection sharedStateInfoCollection = new PersonalizationStateInfoCollection(); if (reader != null) { if (reader.HasRows) { while(reader.Read()) { string returnedPath = reader.GetString(0); // Data can be null if there is no data associated with the path DateTime lastUpdatedDate = (reader.IsDBNull(1)) ? DateTime.MinValue : DateTime.SpecifyKind(reader.GetDateTime(1), DateTimeKind.Utc); int size = (reader.IsDBNull(2)) ? 0 : reader.GetInt32(2); int userDataSize = (reader.IsDBNull(3)) ? 0 : reader.GetInt32(3); int userCount = (reader.IsDBNull(4)) ? 0 : reader.GetInt32(4); sharedStateInfoCollection.Add(new SharedPersonalizationStateInfo( returnedPath, lastUpdatedDate, size, userDataSize, userCount)); } } // The reader needs to be closed so return value can be accessed // See MSDN doc for SqlParameter.Direction for details. reader.Close(); reader = null; } // Set the total count at the end after all operations pass if (returnValue.Value != null && returnValue.Value is int) { totalRecords = (int)returnValue.Value; } return sharedStateInfoCollection; } finally { if (reader != null) { reader.Close(); } if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } } public override PersonalizationStateInfoCollection FindState(PersonalizationScope scope, PersonalizationStateQuery query, int pageIndex, int pageSize, out int totalRecords) { PersonalizationProviderHelper.CheckPersonalizationScope(scope); PersonalizationProviderHelper.CheckPageIndexAndSize(pageIndex, pageSize); if (scope == PersonalizationScope.Shared) { string pathToMatch = null; if (query != null) { pathToMatch = StringUtil.CheckAndTrimString(query.PathToMatch, "query.PathToMatch", false, maxStringLength); } return FindSharedState(pathToMatch, pageIndex, pageSize, out totalRecords); } else { string pathToMatch = null; DateTime inactiveSinceDate = PersonalizationAdministration.DefaultInactiveSinceDate; string usernameToMatch = null; if (query != null) { pathToMatch = StringUtil.CheckAndTrimString(query.PathToMatch, "query.PathToMatch", false, maxStringLength); inactiveSinceDate = query.UserInactiveSinceDate; usernameToMatch = StringUtil.CheckAndTrimString(query.UsernameToMatch, "query.UsernameToMatch", false, maxStringLength); } return FindUserState(pathToMatch, inactiveSinceDate, usernameToMatch, pageIndex, pageSize, out totalRecords); } } private PersonalizationStateInfoCollection FindUserState(string path, DateTime inactiveSinceDate, string username, int pageIndex, int pageSize, out int totalRecords) { SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; SqlDataReader reader = null; totalRecords = 0; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; Debug.Assert(connection != null); CheckSchemaVersion( connection ); SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_FindState", connection); SetCommandTypeAndTimeout(command); SqlParameterCollection parameters = command.Parameters; SqlParameter parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit)); parameter.Value = false; parameters.AddWithValue("ApplicationName", ApplicationName); parameters.AddWithValue("PageIndex", pageIndex); parameters.AddWithValue("PageSize", pageSize); SqlParameter returnValue = new SqlParameter("@ReturnValue", SqlDbType.Int); returnValue.Direction = ParameterDirection.ReturnValue; parameters.Add(returnValue); parameter = parameters.Add("Path", SqlDbType.NVarChar); if (path != null) { parameter.Value = path; } parameter = parameters.Add("UserName", SqlDbType.NVarChar); if (username != null) { parameter.Value = username; } parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime); if (inactiveSinceDate != PersonalizationAdministration.DefaultInactiveSinceDate) { parameter.Value = inactiveSinceDate.ToUniversalTime(); } reader = command.ExecuteReader(CommandBehavior.SequentialAccess); PersonalizationStateInfoCollection stateInfoCollection = new PersonalizationStateInfoCollection(); if (reader != null) { if (reader.HasRows) { while(reader.Read()) { string returnedPath = reader.GetString(0); DateTime lastUpdatedDate = DateTime.SpecifyKind(reader.GetDateTime(1), DateTimeKind.Utc); int size = reader.GetInt32(2); string returnedUsername = reader.GetString(3); DateTime lastActivityDate = DateTime.SpecifyKind(reader.GetDateTime(4), DateTimeKind.Utc); stateInfoCollection.Add(new UserPersonalizationStateInfo( returnedPath, lastUpdatedDate, size, returnedUsername, lastActivityDate)); } } // The reader needs to be closed so return value can be accessed // See MSDN doc for SqlParameter.Direction for details. reader.Close(); reader = null; } // Set the total count at the end after all operations pass if (returnValue.Value != null && returnValue.Value is int) { totalRecords = (int)returnValue.Value; } return stateInfoCollection; } finally { if (reader != null) { reader.Close(); } if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } } /// <devdoc> /// </devdoc> private SqlConnectionHolder GetConnectionHolder() { SqlConnection connection = null; SqlConnectionHolder connectionHolder = SqlConnectionHelper.GetConnection(_connectionString, true); if (connectionHolder != null) { connection = connectionHolder.Connection; } if (connection == null) { throw new ProviderException(SR.GetString(SR.PersonalizationProvider_CantAccess, Name)); } return connectionHolder; } private int GetCountOfSharedState(string path) { SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; int count = 0; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; Debug.Assert(connection != null); CheckSchemaVersion( connection ); SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_GetCountOfState", connection); SetCommandTypeAndTimeout(command); SqlParameterCollection parameters = command.Parameters; SqlParameter parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int)); parameter.Direction = ParameterDirection.Output; parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit)); parameter.Value = true; parameters.AddWithValue("ApplicationName", ApplicationName); parameter = parameters.Add("Path", SqlDbType.NVarChar); if (path != null) { parameter.Value = path; } parameter = parameters.Add("UserName", SqlDbType.NVarChar); parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime); command.ExecuteNonQuery(); parameter = command.Parameters[0]; if (parameter != null && parameter.Value != null && parameter.Value is Int32) { count = (Int32) parameter.Value; } } finally { if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } return count; } public override int GetCountOfState(PersonalizationScope scope, PersonalizationStateQuery query) { PersonalizationProviderHelper.CheckPersonalizationScope(scope); if (scope == PersonalizationScope.Shared) { string pathToMatch = null; if (query != null) { pathToMatch = StringUtil.CheckAndTrimString(query.PathToMatch, "query.PathToMatch", false, maxStringLength); } return GetCountOfSharedState(pathToMatch); } else { string pathToMatch = null; DateTime userInactiveSinceDate = PersonalizationAdministration.DefaultInactiveSinceDate; string usernameToMatch = null; if (query != null) { pathToMatch = StringUtil.CheckAndTrimString(query.PathToMatch, "query.PathToMatch", false, maxStringLength); userInactiveSinceDate = query.UserInactiveSinceDate; usernameToMatch = StringUtil.CheckAndTrimString(query.UsernameToMatch, "query.UsernameToMatch", false, maxStringLength); } return GetCountOfUserState(pathToMatch, userInactiveSinceDate, usernameToMatch); } } private int GetCountOfUserState(string path, DateTime inactiveSinceDate, string username) { SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; int count = 0; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; Debug.Assert(connection != null); CheckSchemaVersion( connection ); SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_GetCountOfState", connection); SetCommandTypeAndTimeout(command); SqlParameterCollection parameters = command.Parameters; SqlParameter parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int)); parameter.Direction = ParameterDirection.Output; parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit)); parameter.Value = false; parameters.AddWithValue("ApplicationName", ApplicationName); parameter = parameters.Add("Path", SqlDbType.NVarChar); if (path != null) { parameter.Value = path; } parameter = parameters.Add("UserName", SqlDbType.NVarChar); if (username != null) { parameter.Value = username; } parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime); if (inactiveSinceDate != PersonalizationAdministration.DefaultInactiveSinceDate) { parameter.Value = inactiveSinceDate.ToUniversalTime(); } command.ExecuteNonQuery(); parameter = command.Parameters[0]; if (parameter != null && parameter.Value != null && parameter.Value is Int32) { count = (Int32) parameter.Value; } } finally { if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } return count; } public override void Initialize(string name, NameValueCollection configSettings) { HttpRuntime.CheckAspNetHostingPermission(AspNetHostingPermissionLevel.Low, SR.Feature_not_supported_at_this_level); // configSettings cannot be null because there are required settings needed below if (configSettings == null) { throw new ArgumentNullException("configSettings"); } if (String.IsNullOrEmpty(name)) { name = "SqlPersonalizationProvider"; } // description will be set from the base class' Initialize method if (string.IsNullOrEmpty(configSettings["description"])) { configSettings.Remove("description"); configSettings.Add("description", SR.GetString(SR.SqlPersonalizationProvider_Description)); } base.Initialize(name, configSettings); _SchemaVersionCheck = 0; // If not available, the default value is set in the get accessor of ApplicationName _applicationName = configSettings["applicationName"]; if (_applicationName != null) { configSettings.Remove("applicationName"); if (_applicationName.Length > maxStringLength) { throw new ProviderException(SR.GetString(SR.PersonalizationProvider_ApplicationNameExceedMaxLength, maxStringLength.ToString(CultureInfo.CurrentCulture))); } } string connectionStringName = configSettings["connectionStringName"]; if (String.IsNullOrEmpty(connectionStringName)) { throw new ProviderException(SR.GetString(SR.PersonalizationProvider_NoConnection)); } configSettings.Remove("connectionStringName"); string connectionString = SqlConnectionHelper.GetConnectionString(connectionStringName, true, true); if (String.IsNullOrEmpty(connectionString)) { throw new ProviderException(SR.GetString(SR.PersonalizationProvider_BadConnection, connectionStringName)); } _connectionString = connectionString; _commandTimeout = SecUtility.GetIntValue(configSettings, "commandTimeout", -1, true, 0); configSettings.Remove("commandTimeout"); if (configSettings.Count > 0) { string invalidAttributeName = configSettings.GetKey(0); throw new ProviderException(SR.GetString(SR.PersonalizationProvider_UnknownProp, invalidAttributeName, name)); } } private void CheckSchemaVersion( SqlConnection connection ) { string[] features = { "Personalization" }; string version = "1"; SecUtility.CheckSchemaVersion( this, connection, features, version, ref _SchemaVersionCheck ); } /// <devdoc> /// </devdoc> private byte[] LoadPersonalizationBlob(SqlConnection connection, string path, string userName) { Debug.Assert(connection != null); Debug.Assert(!String.IsNullOrEmpty(path)); SqlCommand command; if (userName != null) { command = new SqlCommand("dbo.aspnet_PersonalizationPerUser_GetPageSettings", connection); } else { command = new SqlCommand("dbo.aspnet_PersonalizationAllUsers_GetPageSettings", connection); } SetCommandTypeAndTimeout(command); command.Parameters.Add(CreateParameter("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName)); command.Parameters.Add(CreateParameter("@Path", SqlDbType.NVarChar, path)); if (userName != null) { command.Parameters.Add(CreateParameter("@UserName", SqlDbType.NVarChar, userName)); command.Parameters.Add(CreateParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow)); } SqlDataReader reader = null; try { reader = command.ExecuteReader(CommandBehavior.SingleRow); if (reader.Read()) { int length = (int)reader.GetBytes(0, 0, null, 0, 0); byte[] state = new byte[length]; reader.GetBytes(0, 0, state, 0, length); return state; } } finally { if (reader != null) { reader.Close(); } } return null; } /// <internalonly /> protected override void LoadPersonalizationBlobs(WebPartManager webPartManager, string path, string userName, ref byte[] sharedDataBlob, ref byte[] userDataBlob) { sharedDataBlob = null; userDataBlob = null; SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; CheckSchemaVersion( connection ); sharedDataBlob = LoadPersonalizationBlob(connection, path, null); if (!String.IsNullOrEmpty(userName)) { userDataBlob = LoadPersonalizationBlob(connection, path, userName); } } finally { if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } } /// <devdoc> /// </devdoc> private void ResetPersonalizationState(SqlConnection connection, string path, string userName) { Debug.Assert(connection != null); Debug.Assert(!String.IsNullOrEmpty(path)); SqlCommand command; if (userName != null) { command = new SqlCommand("dbo.aspnet_PersonalizationPerUser_ResetPageSettings", connection); } else { command = new SqlCommand("dbo.aspnet_PersonalizationAllUsers_ResetPageSettings", connection); } SetCommandTypeAndTimeout(command); command.Parameters.Add(CreateParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName)); command.Parameters.Add(CreateParameter("@Path", SqlDbType.NVarChar, path)); if (userName != null) { command.Parameters.Add(CreateParameter("@UserName", SqlDbType.NVarChar, userName)); command.Parameters.Add(CreateParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow)); } command.ExecuteNonQuery(); } /// <internalonly /> protected override void ResetPersonalizationBlob(WebPartManager webPartManager, string path, string userName) { SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; CheckSchemaVersion( connection ); ResetPersonalizationState(connection, path, userName); } finally { if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } } private int ResetAllState(PersonalizationScope scope) { SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; int count = 0; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; Debug.Assert(connection != null); CheckSchemaVersion( connection ); SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_DeleteAllState", connection); SetCommandTypeAndTimeout(command); SqlParameterCollection parameters = command.Parameters; SqlParameter parameter = parameters.Add(new SqlParameter("AllUsersScope", SqlDbType.Bit)); parameter.Value = (scope == PersonalizationScope.Shared); parameters.AddWithValue("ApplicationName", ApplicationName); parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int)); parameter.Direction = ParameterDirection.Output; command.ExecuteNonQuery(); parameter = command.Parameters[2]; if (parameter != null && parameter.Value != null && parameter.Value is Int32) { count = (Int32) parameter.Value; } } finally { if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } return count; } private int ResetSharedState(string[] paths) { int resultCount = 0; if (paths == null) { resultCount = ResetAllState(PersonalizationScope.Shared); } else { SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { bool beginTranCalled = false; try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; Debug.Assert(connection != null); CheckSchemaVersion( connection ); SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_ResetSharedState", connection); SetCommandTypeAndTimeout(command); SqlParameterCollection parameters = command.Parameters; SqlParameter parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int)); parameter.Direction = ParameterDirection.Output; parameters.AddWithValue("ApplicationName", ApplicationName); parameter = parameters.Add("Path", SqlDbType.NVarChar); foreach (string path in paths) { if (!beginTranCalled && paths.Length > 1) { (new SqlCommand("BEGIN TRANSACTION", connection)).ExecuteNonQuery(); beginTranCalled = true; } parameter.Value = path; command.ExecuteNonQuery(); SqlParameter countParam = command.Parameters[0]; if (countParam != null && countParam.Value != null && countParam.Value is Int32) { resultCount += (Int32) countParam.Value; } } if (beginTranCalled) { (new SqlCommand("COMMIT TRANSACTION", connection)).ExecuteNonQuery(); beginTranCalled = false; } } catch { if (beginTranCalled) { (new SqlCommand("ROLLBACK TRANSACTION", connection)).ExecuteNonQuery(); beginTranCalled = false; } throw; } finally { if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } } return resultCount; } public override int ResetUserState(string path, DateTime userInactiveSinceDate) { path = StringUtil.CheckAndTrimString(path, "path", false, maxStringLength); string [] paths = (path == null) ? null : new string [] {path}; return ResetUserState(ResetUserStateMode.PerInactiveDate, userInactiveSinceDate, paths, null); } public override int ResetState(PersonalizationScope scope, string[] paths, string[] usernames) { PersonalizationProviderHelper.CheckPersonalizationScope(scope); paths = PersonalizationProviderHelper.CheckAndTrimNonEmptyStringEntries(paths, "paths", false, false, maxStringLength); usernames = PersonalizationProviderHelper.CheckAndTrimNonEmptyStringEntries(usernames, "usernames", false, true, maxStringLength); if (scope == PersonalizationScope.Shared) { PersonalizationProviderHelper.CheckUsernamesInSharedScope(usernames); return ResetSharedState(paths); } else { PersonalizationProviderHelper.CheckOnlyOnePathWithUsers(paths, usernames); return ResetUserState(paths, usernames); } } private int ResetUserState(string[] paths, string[] usernames) { int count = 0; bool hasPaths = !(paths == null || paths.Length == 0); bool hasUsernames = !(usernames == null || usernames.Length == 0); if (!hasPaths && !hasUsernames) { count = ResetAllState(PersonalizationScope.User); } else if (!hasUsernames) { count = ResetUserState(ResetUserStateMode.PerPaths, PersonalizationAdministration.DefaultInactiveSinceDate, paths, usernames); } else { count = ResetUserState(ResetUserStateMode.PerUsers, PersonalizationAdministration.DefaultInactiveSinceDate, paths, usernames); } return count; } private int ResetUserState(ResetUserStateMode mode, DateTime userInactiveSinceDate, string[] paths, string[] usernames) { SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; int count = 0; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { bool beginTranCalled = false; try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; Debug.Assert(connection != null); CheckSchemaVersion( connection ); SqlCommand command = new SqlCommand("dbo.aspnet_PersonalizationAdministration_ResetUserState", connection); SetCommandTypeAndTimeout(command); SqlParameterCollection parameters = command.Parameters; SqlParameter parameter = parameters.Add(new SqlParameter("Count", SqlDbType.Int)); parameter.Direction = ParameterDirection.Output; parameters.AddWithValue("ApplicationName", ApplicationName); string firstPath = (paths != null && paths.Length > 0) ? paths[0] : null; if (mode == ResetUserStateMode.PerInactiveDate) { if (userInactiveSinceDate != PersonalizationAdministration.DefaultInactiveSinceDate) { // Special note: DateTime object cannot be added to collection // via AddWithValue for some reason. parameter = parameters.Add("InactiveSinceDate", SqlDbType.DateTime); parameter.Value = userInactiveSinceDate.ToUniversalTime(); } if (firstPath != null) { parameters.AddWithValue("Path", firstPath); } command.ExecuteNonQuery(); SqlParameter countParam = command.Parameters[0]; if (countParam != null && countParam.Value != null && countParam.Value is Int32) { count = (Int32) countParam.Value; } } else if (mode == ResetUserStateMode.PerPaths) { Debug.Assert(paths != null); parameter = parameters.Add("Path", SqlDbType.NVarChar); foreach (string path in paths) { if (!beginTranCalled && paths.Length > 1) { (new SqlCommand("BEGIN TRANSACTION", connection)).ExecuteNonQuery(); beginTranCalled = true; } parameter.Value = path; command.ExecuteNonQuery(); SqlParameter countParam = command.Parameters[0]; if (countParam != null && countParam.Value != null && countParam.Value is Int32) { count += (Int32) countParam.Value; } } } else { Debug.Assert(mode == ResetUserStateMode.PerUsers); if (firstPath != null) { parameters.AddWithValue("Path", firstPath); } parameter = parameters.Add("UserName", SqlDbType.NVarChar); foreach (string user in usernames) { if (!beginTranCalled && usernames.Length > 1) { (new SqlCommand("BEGIN TRANSACTION", connection)).ExecuteNonQuery(); beginTranCalled = true; } parameter.Value = user; command.ExecuteNonQuery(); SqlParameter countParam = command.Parameters[0]; if (countParam != null && countParam.Value != null && countParam.Value is Int32) { count += (Int32) countParam.Value; } } } if (beginTranCalled) { (new SqlCommand("COMMIT TRANSACTION", connection)).ExecuteNonQuery(); beginTranCalled = false; } } catch { if (beginTranCalled) { (new SqlCommand("ROLLBACK TRANSACTION", connection)).ExecuteNonQuery(); beginTranCalled = false; } throw; } finally { if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } return count; } /// <devdoc> /// </devdoc> private void SavePersonalizationState(SqlConnection connection, string path, string userName, byte[] state) { Debug.Assert(connection != null); Debug.Assert(!String.IsNullOrEmpty(path)); Debug.Assert((state != null) && (state.Length != 0)); SqlCommand command; if (userName != null) { command = new SqlCommand("dbo.aspnet_PersonalizationPerUser_SetPageSettings", connection); } else { command = new SqlCommand("dbo.aspnet_PersonalizationAllUsers_SetPageSettings", connection); } SetCommandTypeAndTimeout(command); command.Parameters.Add(CreateParameter("@ApplicationName", SqlDbType.NVarChar, ApplicationName)); command.Parameters.Add(CreateParameter("@Path", SqlDbType.NVarChar, path)); command.Parameters.Add(CreateParameter("@PageSettings", SqlDbType.Image, state)); command.Parameters.Add(CreateParameter("@CurrentTimeUtc", SqlDbType.DateTime, DateTime.UtcNow)); if (userName != null) { command.Parameters.Add(CreateParameter("@UserName", SqlDbType.NVarChar, userName)); } command.ExecuteNonQuery(); } /// <internalonly /> protected override void SavePersonalizationBlob(WebPartManager webPartManager, string path, string userName, byte[] dataBlob) { SqlConnectionHolder connectionHolder = null; SqlConnection connection = null; // Extra try-catch block to prevent elevation of privilege attack via exception filter try { try { connectionHolder = GetConnectionHolder(); connection = connectionHolder.Connection; CheckSchemaVersion( connection ); SavePersonalizationState(connection, path, userName, dataBlob); } catch(SqlException sqlEx) { // Check if it failed due to duplicate user name if (userName != null && (sqlEx.Number == 2627 || sqlEx.Number == 2601 || sqlEx.Number == 2512)) { // Try again, because it failed first time with duplicate user name SavePersonalizationState(connection, path, userName, dataBlob); } else { throw; } } finally { if (connectionHolder != null) { connectionHolder.Close(); connectionHolder = null; } } } catch { throw; } } private void SetCommandTypeAndTimeout(SqlCommand command) { command.CommandType = CommandType.StoredProcedure; if (_commandTimeout != -1) { command.CommandTimeout = _commandTimeout; } } } }
using OpenKh.Common; using System; using System.Numerics; namespace OpenKh.Engine { public static class VectorHelpers { public static Vector3 ToVector3(this Vector4 v) => new Vector3(v.X, v.Y, v.Z); public static Vector3 Invert(this Vector3 v) => new Vector3(-v.X, -v.Y, -v.Z); } public class TargetCamera { private class CameraMode { public float Fov { get; set; } public float Radius { get; set; } public float LockRadius { get; set; } public float RadiusMin { get; set; } public float RadiusMax { get; set; } public float ObjectiveUpCurve { get; set; } } private const float FovDefault = 1.5f; private const float FovClose = (float)(Math.PI / (FovDefault * 2f)); private static readonly CameraMode CameraOutDoor = new CameraMode { Fov = 1.5f, Radius = 420f, LockRadius = 380f, RadiusMin = 250f, RadiusMax = 500f, ObjectiveUpCurve = 0.008f }; private static readonly CameraMode CameraInDoor = new CameraMode { Fov = FovClose, Radius = 600f, LockRadius = 520f, RadiusMin = 400f, RadiusMax = 700f, ObjectiveUpCurve = 0.005f }; private static readonly CameraMode CameraCrowd = new CameraMode { Fov = FovClose, Radius = 600f, LockRadius = 520f, RadiusMin = 400f, RadiusMax = 700f, ObjectiveUpCurve = 0.005f }; private static readonly CameraMode CameraLightCycle = new CameraMode { Fov = FovClose, Radius = 600f, LockRadius = 520f, RadiusMin = 400f, RadiusMax = 633f, ObjectiveUpCurve = 0.005f }; private static readonly CameraMode[] CameraTypes = new CameraMode[] { CameraOutDoor, CameraInDoor, CameraCrowd, CameraLightCycle, }; private Vector4 m_eyeTarget; private Vector3 _targetPositionPrev; private int _type; public TargetCamera(Camera camera) { Camera = camera; Type = 0; Interpolate = true; } public Camera Camera { get; } public bool Interpolate { get; set; } public Vector4 At { get; set; } public Vector4 Eye { get; set; } public Vector4 FovV { get; set; } public float Fov { get; set; } public float Roll { get; set; } public float Radius { get; set; } public float YRotation { get; set; } public float BackYRotation { get; set; } public Vector4 EyeTarget { get => m_eyeTarget; set => m_eyeTarget = value; } public Vector4 EyeTargetPrev { get; set; } public Vector4 AtTarget { get; set; } public Vector4 AtTargetPrev { get; set; } public Vector4 FovVTarget { get; set; } public Vector4 FovVTargetPrev { get; set; } public float Yaw { get; set; } public float Pitch { get; set; } public float ObjectiveInitRadius { get; set; } public float ObjectiveLockRadius { get; set; } public float ObjectiveRadiusMin { get; set; } public float ObjectiveRadiusMax { get; set; } public float ObjectiveUpCurve { get; set; } public float DefaultFov { get; set; } public float DefaultRoll { get; set; } public int Type { get => _type; set { Log.Info("{0}.{1}={2}", nameof(TargetCamera), nameof(Type), value); if (value < 0 || value >= CameraTypes.Length) Log.Err("{0}.{1}={2} not valid", nameof(TargetCamera), nameof(Type), value); _type = value; var cameraMode = CameraTypes[value]; Fov = DefaultFov = cameraMode.Fov; Radius = ObjectiveInitRadius = cameraMode.Radius; ObjectiveLockRadius = cameraMode.LockRadius; ObjectiveRadiusMin = cameraMode.RadiusMin; ObjectiveRadiusMax = cameraMode.RadiusMax; ObjectiveUpCurve = cameraMode.ObjectiveUpCurve; } } public void Update(IEntity objTarget, double deltaTime, bool isYRotationLocked = false) { var targetPosition = objTarget.Position; AtTarget = new Vector4( targetPosition.X, -targetPosition.Y - 170f, -targetPosition.Z, 1f); // This is not really the right way to know if the focused entity is actually moving var isEntityMoving = targetPosition.X != _targetPositionPrev.X || targetPosition.Z != _targetPositionPrev.Z; _targetPositionPrev = targetPosition; if (isEntityMoving && !isYRotationLocked) { AdjustHorizontalRotation(objTarget, deltaTime); AdjustVerticalDefaultRotation(deltaTime); } CalculateEyeTarget(AtTarget, false, deltaTime); FovVTarget = new Vector4(Fov, WarpRadians(Roll), 0f, 1f); if (Interpolate) { At = InterpolateVector(At, AtTarget, AtTargetPrev, 30.0 * deltaTime * 0.1f, 2.5f, 0.5f, 1.0f); Eye = InterpolateVector(Eye, EyeTarget, EyeTargetPrev, 30.0 * deltaTime * 0.07f, 2.5f, 0.5f, 1.0f); FovV = InterpolateVector(FovV, FovVTarget, FovVTargetPrev, 30.0 * deltaTime * 0.07f, 2.5f, 0.5f, 0.001f); } else { Eye = EyeTarget; At = AtTarget; FovV = FovVTarget; } EyeTargetPrev = EyeTarget; AtTargetPrev = AtTarget; FovVTargetPrev = FovVTarget; Camera.FieldOfView = Fov; Camera.CameraPosition = Eye.ToVector3().Invert(); Camera.CameraLookAt = At.ToVector3().Invert(); } public void InstantlyRotateCameraToEntity(IEntity objTarget) => YRotation = BackYRotation = GetYRotation(objTarget); private float GetYRotation(IEntity objTarget) => WarpRadians((float)(Math.PI * 2 - objTarget.Rotation.Y)); private void AdjustVerticalDefaultRotation(double deltaTime) => AdjustVerticalRotation(ObjectiveInitRadius, deltaTime / 2.0); private void AdjustVerticalLockonRotation(double deltaTime) => AdjustVerticalRotation(ObjectiveLockRadius, deltaTime); private void AdjustVerticalRotation(float objectiveRadius, double deltaTime) { if (Math.Abs(Radius - objectiveRadius) >= 1.0) { if (Radius > objectiveRadius) { Radius = (float)(Radius - deltaTime * 60); if (Radius <= ObjectiveRadiusMin) Radius = ObjectiveRadiusMin; } else { Radius = (float)(Radius + deltaTime * 60); if (Radius >= ObjectiveRadiusMax) Radius = ObjectiveRadiusMax; } } } private void AdjustHorizontalRotation(IEntity objTarget, double deltaTime) { const double Speed = Math.PI / 720.0; const double PlayerSpeedMul = Speed / 25.0; const float analogX = 0f; const float analogY = 0f; const float analogW = 1f; const float playerSpeed = 8f; // ??? float objYRotation = GetYRotation(objTarget); var deltaFrame = deltaTime * 60.0; var speed = (Math.Abs(analogX) + 1.0) * (Math.Abs(analogY) + 1.0) * analogW * 4.0 * ((PlayerSpeedMul * (playerSpeed - 8.0)) + Speed) * deltaFrame; var rotation = InterpolateYRotation(YRotation, objYRotation, speed); YRotation = BackYRotation = rotation; } private void CalculateEyeTarget(Vector4 atTarget, bool interpolate, double deltaTime) { const double TurnSpeed = 10.4719752; var radiusDiff = Radius - ObjectiveRadiusMin; if (interpolate) YRotation = InterpolateYRotation(YRotation, BackYRotation, TurnSpeed * deltaTime); else YRotation = BackYRotation; EyeTarget = atTarget + Vector4.Transform( new Vector4(0, 0, Radius, 0), Matrix4x4.CreateRotationY(YRotation)); m_eyeTarget.Y = -((radiusDiff * radiusDiff * ObjectiveUpCurve) - (atTarget.Y + 150.0f)); } private Vector4 InterpolateVector( Vector4 dst, Vector4 src, Vector4 srcPrev, double deltaTime, float springConst, float dampConst, float springLen) { var vDiff = dst - src; var vectorLength = vDiff.Length(); if (vectorLength == 0) return dst; var v0 = vDiff * Vector4.Multiply(srcPrev - src, (float)deltaTime); var f0 = v0.X + v0.Y + v0.Z; var f2 = (springConst * (springLen - vectorLength)) + dampConst * f0 / vectorLength; return dst + Vector4.Multiply(vDiff, (float)(1f / vectorLength * f2 * deltaTime)); } private float InterpolateYRotation(float src, float dst, double speed) { var diff = dst - src; double actualSpeed; if (WarpRadians(diff) >= -speed) { if (WarpRadians(diff) <= speed) actualSpeed = WarpRadians(diff); else actualSpeed = speed; } else actualSpeed = -speed; return WarpRadians((float)(src + actualSpeed)); } private float WarpRadians(float radians) { const float PI_2 = (float)(Math.PI * 2); if (radians < -Math.PI) { do { radians += PI_2; } while (radians < -Math.PI); } else if (Math.PI < radians) { do { radians -= PI_2; } while (radians > Math.PI); } return radians; } } }
/* * @(#) TraceGroup.cs 1.0 06-08-2007 author: Manoj Prasad ************************************************************************* * Copyright (c) 2008 Hewlett-Packard Development Company, L.P. * 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. **************************************************************************/ /************************************************************************ * SVN MACROS * * $Revision: 244 $ * $Author: mnab $ * $LastChangedDate: 2008-07-04 13:57:50 +0530 (Fri, 04 Jul 2008) $ ************************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Collections; namespace InkML { /// <summary> /// /// </summary> public class TraceGroup:Stroke { #region attributes private List<InkElement> groupList; private string id=""; private string brushRef=""; private string contextRef=""; private bool ContainsBrush = false; private Brush associatedBrush; private Context associatedContext; private Context associatedCurrentContext; private Definitions definitions; /// <summary> /// Gets/Sets the 'id' attribute of the TraceGroup Element /// </summary> public string Id { get { return id; } } /// <summary> /// Gets/Sets the 'contextRef' attribute of the TraceGroup Element /// </summary> public string ContextRef { get { return contextRef; } set { contextRef = value; ResolveContext(); } } /// <summary> /// Gets/Sets the 'brushRef' attribute of the TraceGroup Element /// </summary> public string BrushRef { get { return brushRef; } set { brushRef = value; ResolveBrush(); } } /// <summary> /// Gets the associated Brush of the TraceGroup Element /// </summary> public Brush AssociatedBrush { get { return associatedBrush; } } /// <summary> /// Gets the associated context of the TraceGroup Element /// </summary> public Context AssociatedContext { get { return associatedContext; } } #endregion Attributes #region Constructor public TraceGroup(Definitions defs, XmlElement element) { associatedContext = new Context(defs); associatedCurrentContext = new Context(defs); groupList = new List<InkElement>(); this.TagName = "traceGroup"; if (defs != null) { definitions = defs; } else { throw new Exception("Null Definitions Block."); } if (element != null) { ParseElement(element); } else { throw new Exception("Null xml element"); } } public TraceGroup(Definitions defs, Context currentContext, XmlElement element) { associatedCurrentContext = new Context(defs); associatedBrush = currentContext.BrushElement; associatedCurrentContext.BrushElement = currentContext.BrushElement; associatedCurrentContext.TraceFormatElement = currentContext.TraceFormatElement; associatedCurrentContext.CanvasElement = currentContext.CanvasElement; associatedCurrentContext.InksourceElement = currentContext.InksourceElement; associatedContext = associatedCurrentContext; groupList = new List<InkElement>(); this.TagName = "traceGroup"; if (defs != null) { definitions = defs; } else { throw new Exception("Null Definitions Block."); } if (element != null) { ParseElement(element); } else { throw new Exception("Null xml element"); } } public TraceGroup(Definitions defs) { groupList = new List<InkElement>(); this.TagName = "traceGroup"; if (defs != null) { definitions = defs; } else { throw new Exception("Null Definitions Block."); } associatedContext = new Context(defs); associatedCurrentContext = new Context(defs); } public TraceGroup(Definitions defs, string id):this(defs) { if (!id.Equals("")) { this.id = id; definitions.AddTraceGroup(this); } } #endregion Constructor #region Override methods Parse and toInkML public override void ParseElement(XmlElement element) { if (element != null && element.LocalName.Equals("traceGroup")) { id = element.GetAttribute("id"); if (!id.Equals("")) { definitions.AddTraceGroup(this); } brushRef = element.GetAttribute("brushRef"); if (!brushRef.Equals("")) { ResolveBrush(); } contextRef = element.GetAttribute("contextRef"); if (!contextRef.Equals("")) { ResolveContext(); } foreach (XmlNode Node in element.ChildNodes) { if(Node.LocalName.Equals("traceGroup")) { if (associatedContext != null) { groupList.Add(new TraceGroup(definitions, associatedContext, Node as XmlElement)); } else { groupList.Add(new TraceGroup(definitions, Node as XmlElement)); } } if (Node.LocalName.Equals("trace")) { if (associatedContext != null) { groupList.Add(new Trace(definitions, associatedContext, Node as XmlElement)); } else { groupList.Add(new Trace(definitions, Node as XmlElement)); } } if (Node.LocalName.Equals("annotation")) { groupList.Add(new Annotation(Node as XmlElement)); } if (Node.LocalName.Equals("annotationXML")) { groupList.Add(new AnnotationXML(Node as XmlElement)); } } } else { throw new Exception("Invalid Element ."); } } public override XmlElement ToInkML(XmlDocument inkDocument) { XmlElement result = inkDocument.CreateElement("traceGroup"); if (!id.Equals("")) { result.SetAttribute("id", id); } if (!brushRef.Equals("")) { result.SetAttribute("brushRef", brushRef); } if (!contextRef.Equals("")) { result.SetAttribute("contextRef", contextRef); } foreach (InkElement element in groupList) { result.AppendChild(element.ToInkML(inkDocument)); } return result; } #endregion Override methods Parse and toInkML #region Resolve context and brush public void ResolveContext() { Context tctx; if (definitions.ContainsID(contextRef)) { tctx = definitions.GetContext(contextRef); if (tctx != null) { if (tctx.CanvasElement != null) { associatedContext.CanvasElement = tctx.CanvasElement; } if (tctx.InksourceElement != null) { associatedContext.InksourceElement = tctx.InksourceElement; } if (tctx.TraceFormatElement != null) { associatedContext.TraceFormatElement = tctx.TraceFormatElement; } if (!ContainsBrush && tctx.BrushElement != null) { associatedContext.BrushElement = tctx.BrushElement; associatedBrush = tctx.BrushElement; } } } else { throw new Exception("Invalid Reference."); } } public void ResolveBrush() { Brush tb; if (definitions.ContainsID(brushRef)) { tb = definitions.GetBrush(brushRef); if (tb != null) { associatedBrush = tb; ContainsBrush = true; } } else { throw new Exception("Invalid Reference."); } } #endregion Resolve context and brush #region Add and Remove Methods public void AddTrace(Trace trace) { if (trace != null) { groupList.Add(trace); } } public void AddTraceGroup(TraceGroup traceGroup) { if (traceGroup != null) { groupList.Add(traceGroup); } } public void AddAnnotation(Annotation annotation) { if (annotation != null) { groupList.Add(annotation); } } public void AddAnnotationXML(AnnotationXML annotationXML) { if (annotationXML != null) { groupList.Add(annotationXML); } } #endregion Add and Remove Methods public List<InkElement>.Enumerator GetEnumerator() { return groupList.GetEnumerator(); } } }
using System; using Cosmos.Debug.Kernel; using Cosmos.IL2CPU.API; using Cosmos.IL2CPU.API.Attribs; namespace Cosmos.System_Plugs.System { [Plug(Target = typeof(Math))] public static class MathImpl { internal static Debugger mDebugger = new Debugger("System", "Math Plugs"); #region Internal Constants private const double sq2p1 = 2.414213562373095048802e0F; private const double sq2m1 = .414213562373095048802e0F; private const double pio2 = 1.570796326794896619231e0F; private const double pio4 = .785398163397448309615e0F; private const double log2e = 1.4426950408889634073599247F; private const double sqrt2 = 1.4142135623730950488016887F; private const double ln2 = 6.93147180559945286227e-01F; private const double atan_p4 = .161536412982230228262e2F; private const double atan_p3 = .26842548195503973794141e3F; private const double atan_p2 = .11530293515404850115428136e4F; private const double atan_p1 = .178040631643319697105464587e4F; private const double atan_p0 = .89678597403663861959987488e3F; private const double atan_q4 = .5895697050844462222791e2F; private const double atan_q3 = .536265374031215315104235e3F; private const double atan_q2 = .16667838148816337184521798e4F; private const double atan_q1 = .207933497444540981287275926e4F; private const double atan_q0 = .89678597403663861962481162e3F; #endregion public const double PI = 3.1415926535897932384626433832795; public const double E = 2.71828182845904523536; #region Abs public static double Abs(double value) { if (value < 0) { return -value; } else { return value; } } public static float Abs(float value) { if (value < 0) { return -value; } else { return value; } } #endregion #region Acos public static double Acos(double x) { if ((x > 1.0) || (x < -1.0)) throw new ArgumentOutOfRangeException("Domain error"); return (pio2 - Asin(x)); } #endregion #region Asin public static double Asin(double x) { if (x > 1.0F) { throw new ArgumentOutOfRangeException("Domain error"); } double sign = 1F, temp; if (x < 0.0F) { x = -x; sign = -1.0F; } temp = Sqrt(1.0F - (x * x)); if (x > 0.7) { temp = pio2 - Atan(temp / x); } else { temp = Atan(x / temp); } return (sign * temp); } #endregion #region Atan public static double Atan(double x) { return ((x > 0F) ? atans(x) : (-atans(-x))); } #endregion #region Atan2 public static double Atan2(double x, double y) { if ((x + y) == x) { if ((x == 0F) & (y == 0F)) return 0F; if (x >= 0.0F) return pio2; return (-pio2); } if (y < 0.0F) { if (x >= 0.0F) return ((pio2 * 2) - atans((-x) / y)); return (((-pio2) * 2) + atans(x / y)); } if (x > 0.0F) { return (atans(x / y)); } return (-atans((-x) / y)); //return (((x + y) == x) ? (((x == 0F) & (y == 0F)) ? 0F : ((x >= 0F) ? pio2 : (-pio2))) : ((y < 0F) ? ((x >= 0F) ? ((pio2 * 2) - atans((-x) / y)) : (((-pio2) * 2) + atans(x / y))) : ((x > 0F) ? atans(x / y) : -atans((-x) / y)))); } #endregion #region Ceiling public static double Ceiling(double a) { // should be using assembler for bigger values than int or long max if (a == Double.NaN || a == Double.NegativeInfinity || a == Double.PositiveInfinity) return a; int i = (a - (int)a > 0) ? (int)(a + 1) : (int)a; return i; } #endregion #region Cos public static double Cos(double x) { // First we need to anchor it to a valid range. while (x > (2 * PI)) { x -= (2 * PI); } if (x < 0) x = -x; byte quadrand = 0; if ((x > (PI / 2F)) && (x < (PI))) { quadrand = 1; x = PI - x; } if ((x > (PI)) && (x < ((3F * PI) / 2))) { quadrand = 2; x = x - PI; } if ((x > ((3F * PI) / 2))) { quadrand = 3; x = (2F * PI) - x; } const double c1 = 0.9999999999999999999999914771; const double c2 = -0.4999999999999999999991637437; const double c3 = 0.04166666666666666665319411988; const double c4 = -0.00138888888888888880310186415; const double c5 = 0.00002480158730158702330045157; const double c6 = -0.000000275573192239332256421489; const double c7 = 0.000000002087675698165412591559; const double c8 = -0.0000000000114707451267755432394; const double c9 = 0.0000000000000477945439406649917; const double c10 = -0.00000000000000015612263428827781; const double c11 = 0.00000000000000000039912654507924; double x2 = x * x; if (quadrand == 0 || quadrand == 3) { return (c1 + (x2 * (c2 + (x2 * (c3 + (x2 * (c4 + (x2 * (c5 + (x2 * (c6 + (x2 * (c7 + (x2 * (c8 + (x2 * (c9 + (x2 * (c10 + (x2 * c11)))))))))))))))))))); } else { return -(c1 + (x2 * (c2 + (x2 * (c3 + (x2 * (c4 + (x2 * (c5 + (x2 * (c6 + (x2 * (c7 + (x2 * (c8 + (x2 * (c9 + (x2 * (c10 + (x2 * c11)))))))))))))))))))); } } #endregion #region Cosh public static double Cosh(double x) { if (x < 0.0F) x = -x; return ((x == 0F) ? 1F : ((x <= (ln2 / 2)) ? (1 + (_power((Exp(x) - 1), 2) / (2 * Exp(x)))) : ((x <= 22F) ? ((Exp(x) + (1 / Exp(x))) / 2) : (0.5F * (Exp(x) + Exp(-x)))))); } #endregion #region Exp public static double Exp(double x) { double c; int n = 1; double ex = 1F; double m = 1F; while (x > 10.000F) { m *= 22026.4657948067; x -= 10F; } while (x > 01.000F) { m *= E; x -= 1F; } while (x > 00.100F) { m *= 1.10517091807565; ; x -= 0.1F; } while (x > 00.010F) { m *= 1.01005016708417; x -= 0.01F; } for (int y = 1; y <= 4; y++) { c = _power(x, y); ex += c / (double)n; n *= (y + 1); } return ex * m; } #endregion #region Floor public static double Floor(double a) { // should be using assembler for bigger values than int or long max if (a == Double.NaN || a == Double.NegativeInfinity || a == Double.PositiveInfinity) return a; int i = (a - (int)a < 0) ? (int)(a - 1) : (int)a; return i; } #endregion #region Log (base e) public static double Log(double x) { return Log(x, E); } #endregion #region Log (base specified) public static double Log(double x, double newBase) { if (x == 0.0F) { return double.NegativeInfinity; } if ((x < 1.0F) && (newBase < 1.0F)) { throw new ArgumentOutOfRangeException("can't compute Log"); } double partial = 0.5F; double integer = 0F; double fractional = 0.0F; while (x < 1.0F) { integer -= 1F; x *= newBase; } while (x >= newBase) { integer += 1F; x /= newBase; } x *= x; while (partial >= 2.22045e-016) { if (x >= newBase) { fractional += partial; x = x / newBase; } partial *= 0.5F; x *= x; } return (integer + fractional); } #endregion #region Log10 public static double Log10(double x) { return Log(x, 10F); } #endregion #region Pow public static double Pow(double x, double y) { if (x <= 0.0F) { double temp = 0F; long l; if (x == 0.0F && y <= 0.0F) throw new ArgumentException(); l = (long)Floor(y); if (l != y) temp = Exp(y * Log(-x)); if ((l % 2) == 1) temp = -temp; return (temp); } return (Exp(y * Log(x))); //if (y == 0) //{ // return 1; //} //else if (y == 1) //{ // return x; //} //else //{ // double xResult = x; // for (int i = 2; i <= y; i++) // { // xResult = xResult * x; // } // return xResult; //} } #endregion #region Round public static double Round(double d) { return ((Math.Floor(d) % 2 == 0) ? Math.Floor(d) : Math.Ceiling(d)); } #endregion #region Sin public static double Sin(double x) { // First we need to anchor it to a valid range. while (x > (2 * PI)) { x -= (2 * PI); } return Cos((PI / 2.0F) - x); } #endregion #region Sinh public static double Sinh(double x) { if (x < 0F) x = -x; if (x <= 22F) { double Ex_1 = Tanh(x / 2) * (Exp(x) + 1); return ((Ex_1 + (Ex_1 / (Ex_1 - 1))) / 2); } else { return (Exp(x) / 2); } } #endregion #region Sqrt public static double Sqrt(double x) { long x1; double x2; int i; if (double.IsNaN(x) || x < 0) return double.NaN; if (double.IsPositiveInfinity(x)) return double.PositiveInfinity; if (x == 0F) return 0F; // Approximating the square root value // This makes use of IEEE 754 double-precision floating point format // Sign: 1 bit, Exponent: 11 bits, Signficand: 52 bits x1 = BitConverter.DoubleToInt64Bits(x); x1 -= 1L << 53; x1 >>= 1; x1 += 1L << 61; x2 = BitConverter.Int64BitsToDouble(x1); // Use Newton's Method for(i = 0; i < 5; i++) { x2 = x2 - (x2 * x2 - x) / (2 * x2); } return x2; } #endregion #region Tan public static double Tan(double x) { // First we need to anchor it to a valid range. while (x > (2 * PI)) { x -= (2 * PI); } byte octant = (byte)Floor(x * (1 / (PI / 4))); switch (octant) { case 0: x = x * (4 / PI); break; case 1: x = ((PI / 2) - x) * (4 / PI); break; case 2: x = (x - (PI / 2)) * (4 / PI); break; case 3: x = (PI - x) * (4 / PI); break; case 4: x = (x - PI) * (4 / PI); break; case 5: x = ((3.5 * PI) - x) * (4 / PI); break; case 6: x = (x - (3.5 * PI)) * (4 / PI); break; case 7: x = ((2 * PI) - x) * (4 / PI); break; } const double c1 = 4130240.588996024013440146267; const double c2 = -349781.8562517381616631012487; const double c3 = 6170.317758142494245331944348; const double c4 = -27.94920941380194872760036319; const double c5 = 0.0175143807040383602666563058; const double c6 = 5258785.647179987798541780825; const double c7 = -1526650.549072940686776259893; const double c8 = 54962.51616062905361152230566; const double c9 = -497.495460280917265024506937; double x2 = x * x; if (octant == 0 || octant == 4) { return ((x * (c1 + (x2 * (c2 + (x2 * (c3 + (x2 * (c4 + (x2 * c5))))))))) / (c6 + (x2 * (c7 + (x2 * (c8 + (x2 * (c9 + x2)))))))); } else if (octant == 1 || octant == 5) { return (1 / ((x * (c1 + (x2 * (c2 + (x2 * (c3 + (x2 * (c4 + (x2 * c5))))))))) / (c6 + (x2 * (c7 + (x2 * (c8 + (x2 * (c9 + x2))))))))); } else if (octant == 2 || octant == 6) { return (-1 / ((x * (c1 + (x2 * (c2 + (x2 * (c3 + (x2 * (c4 + (x2 * c5))))))))) / (c6 + (x2 * (c7 + (x2 * (c8 + (x2 * (c9 + x2))))))))); } else // octant == 3 || octant == 7 { return -((x * (c1 + (x2 * (c2 + (x2 * (c3 + (x2 * (c4 + (x2 * c5))))))))) / (c6 + (x2 * (c7 + (x2 * (c8 + (x2 * (c9 + x2)))))))); } } #endregion #region Tanh public static double Tanh(double x) { return (expm1(2F * x) / (expm1(2F * x) + 2F)); } #endregion #region Truncate public static double Truncate(double x) { return ((x == 0) ? 0F : ((x > 0F) ? Floor(x) : Ceiling(x))); } #endregion //#region Factorial (only used in Sin(), not plug ) //public static int Factorial(int n) //{ // if (n == 0) // return 1; // else // return n * Factorial(n - 1); //} //#endregion #region Internaly used functions #region expm1 private static double expm1(double x) { double u = Exp(x); return ((u == 1.0F) ? x : ((u - 1.0F == -1.0F) ? -1.0F : ((u - 1.0F) * x / Log(u)))); } #endregion #region _power private static double _power(double x, int c) { if (c == 0) return 1.0F; int _c; double ret = x; if (c >= 0f) { for (_c = 1; _c < c; _c++) ret *= ret; } else { for (_c = 1; _c < c; _c++) ret /= ret; } return ret; } #endregion #region atans private static double atans(double x) { if (x < sq2m1) { return atanx(x); } else if (x > sq2p1) { return (pio2 - atanx(1.0F / x)); } else { return (pio4 + atanx((x - 1.0F) / (x + 1.0F))); } } #endregion #region atanx private static double atanx(double x) { double argsq, value; /* get denormalized add in following if range arg**10 is much smaller than q1, so check for that case */ if ((x > -.01) && (x < .01)) { value = (atan_p0 / atan_q0); } else { argsq = x * x; value = ((((atan_p4 * argsq + atan_p3) * argsq + atan_p2) * argsq + atan_p1) * argsq + atan_p0) / (((((argsq + atan_q4) * argsq + atan_q3) * argsq + atan_q2) * argsq + atan_q1) * argsq + atan_q0); } return value * x; //if (-.01 < arg && arg < .01) // value = p0 / q0; //double ArgSquared = x * x; //return // (((((atan_p4 * ArgSquared + atan_p3) * ArgSquared + atan_p2) * ArgSquared + atan_p1) * ArgSquared + atan_p0) // / // (((((ArgSquared + atan_q4) * ArgSquared + atan_q3) * ArgSquared + atan_q2) * ArgSquared + atan_q1) * ArgSquared + atan_q0) * x); } #endregion #endregion } }
//--------------------------------------------------------------------------- // // <copyright file="EmbossBitmapEffect.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.KnownBoxes; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Effects { sealed partial class EmbossBitmapEffect : BitmapEffect { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new EmbossBitmapEffect Clone() { return (EmbossBitmapEffect)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new EmbossBitmapEffect CloneCurrentValue() { return (EmbossBitmapEffect)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void LightAnglePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { EmbossBitmapEffect target = ((EmbossBitmapEffect) d); target.PropertyChanged(LightAngleProperty); } private static void ReliefPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { EmbossBitmapEffect target = ((EmbossBitmapEffect) d); target.PropertyChanged(ReliefProperty); } #region Public Properties /// <summary> /// LightAngle - double. Default value is 45.0. /// </summary> public double LightAngle { get { return (double) GetValue(LightAngleProperty); } set { SetValueInternal(LightAngleProperty, value); } } /// <summary> /// Relief - double. Default value is 0.44. /// </summary> public double Relief { get { return (double) GetValue(ReliefProperty); } set { SetValueInternal(ReliefProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new EmbossBitmapEffect(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the EmbossBitmapEffect.LightAngle property. /// </summary> public static readonly DependencyProperty LightAngleProperty; /// <summary> /// The DependencyProperty for the EmbossBitmapEffect.Relief property. /// </summary> public static readonly DependencyProperty ReliefProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal const double c_LightAngle = 45.0; internal const double c_Relief = 0.44; #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static EmbossBitmapEffect() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(EmbossBitmapEffect); LightAngleProperty = RegisterProperty("LightAngle", typeof(double), typeofThis, 45.0, new PropertyChangedCallback(LightAnglePropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); ReliefProperty = RegisterProperty("Relief", typeof(double), typeofThis, 0.44, new PropertyChangedCallback(ReliefPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); } #endregion Constructors } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Microsoft.Research.Naiad.Dataflow { /// <summary> /// Describes the physical location of a dataflow <see cref="Vertex"/>. /// </summary> public struct VertexLocation { /// <summary> /// The vertex identifier. /// </summary> public readonly int VertexId; /// <summary> /// The process on which the vertex with <see cref="VertexId"/> resides. /// </summary> public readonly int ProcessId; /// <summary> /// The worker thread on which the vertex with <see cref="VertexId"/> resides. /// </summary> public readonly int ThreadId; /// <summary> /// Constructs a new vertex location. /// </summary> /// <param name="vertexId">The vertex ID.</param> /// <param name="processId">The process ID.</param> /// <param name="threadId">The worker thread ID.</param> public VertexLocation(int vertexId, int processId, int threadId) { this.VertexId = vertexId; this.ProcessId = processId; this.ThreadId = threadId; } } /// <summary> /// Represents the placement of physical dataflow <see cref="Vertex"/> objects in a <see cref="Stage{TVertex}"/>. /// </summary> public abstract class Placement : IEnumerable<VertexLocation>, IEquatable<Placement> { /// <summary> /// Returns location information about the vertex with the given ID. /// </summary> /// <param name="vertexId">The vertex ID.</param> /// <returns>Location information about the vertex with the given ID.</returns> public abstract VertexLocation this[int vertexId] { get; } /// <summary> /// The number of vertices. /// </summary> public abstract int Count { get; } /// <summary> /// Returns an object for enumerating location information about every vertex in this placement. /// </summary> /// <returns>An object for enumerating location information about every vertex in this placement.</returns> public abstract IEnumerator<VertexLocation> GetEnumerator(); /// <summary> /// Returns <c>true</c> if and only if each vertex in this placement has the same location as the vertex /// with the same ID in the <paramref name="other"/> placement, and vice versa. /// </summary> /// <param name="other">The other placement.</param> /// <returns><c>true</c> if and only if each vertex in this placement has the same location as the vertex /// with the same ID in the <paramref name="other"/> placement, and vice versa.</returns> public abstract bool Equals(Placement other); System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary> /// Round robin placement /// </summary> internal class RoundRobin : Placement { private readonly int numProcs; private readonly int numThreads; /// <summary> /// Constructor /// </summary> /// <param name="numProcs">number of processes</param> /// <param name="numThreads">number of threads per process</param> public RoundRobin(int numProcs, int numThreads) { this.numProcs = numProcs; this.numThreads = numThreads; } /// <summary> /// Number of workers /// </summary> public override int Count { get { return this.numProcs * this.numThreads; } } /// <summary> /// Indexer /// </summary> /// <param name="vertexId">vertex identifier</param> /// <returns></returns> public override VertexLocation this[int vertexId] { get { return new VertexLocation(vertexId, (vertexId / this.numThreads) % this.numProcs, vertexId % this.numThreads); } } /// <summary> /// Enumerator /// </summary> /// <returns></returns> public override IEnumerator<VertexLocation> GetEnumerator() { for (int i = 0; i < this.numProcs * this.numThreads; ++i) yield return this[i]; } /// <summary> /// Tests equality between placements /// </summary> /// <param name="that">other placement</param> /// <returns></returns> public override bool Equals(Placement that) { RoundRobin other = that as RoundRobin; return this == other || (other != null && this.numProcs == other.numProcs && this.numThreads == other.numThreads); } } /// <summary> /// Placement with one vertex /// </summary> public class SingleVertex : Placement { private readonly VertexLocation location; /// <summary> /// Constructor /// </summary> public SingleVertex() { this.location = new VertexLocation(0, 0, 0); } /// <summary> /// Constructor /// </summary> /// <param name="processId">process identifier for the vertex</param> /// <param name="threadId">thread identifier for the vertex</param> internal SingleVertex(int processId, int threadId) { this.location = new VertexLocation(0, processId, threadId); } /// <summary> /// Indexer /// </summary> /// <param name="vertexId">ignored</param> /// <returns></returns> public override VertexLocation this[int vertexId] { get { return this.location; } } /// <summary> /// Returns one /// </summary> public override int Count { get { return 1; } } /// <summary> /// Enumerator /// </summary> /// <returns>an enumeration of the Placement's locations</returns> public override IEnumerator<VertexLocation> GetEnumerator() { yield return this.location; } /// <summary> /// Test equality with another SingleVertexPlacement /// </summary> /// <param name="that">placement to compare to</param> /// <returns>true if the placements are equal</returns> public override bool Equals(Placement that) { SingleVertex other = that as SingleVertex; return this == other || (other != null && this.location.Equals(other.location)); } } /// <summary> /// Represents a <see cref="Placement"/> based on an explicit <see cref="Vertex"/>-to-location mapping. /// </summary> public class Explicit : Placement { private readonly VertexLocation[] locations; /// <summary> /// Returns location information about the vertex with the given ID. /// </summary> /// <param name="vertexId">The vertex ID.</param> /// <returns>Location information about the vertex with the given ID.</returns> public override VertexLocation this[int vertexId] { get { return this.locations[vertexId]; } } /// <summary> /// The number of vertices. /// </summary> public override int Count { get { return this.locations.Length; } } /// <summary> /// Returns an object for enumerating location information about every vertex in this placement. /// </summary> /// <returns>An object for enumerating location information about every vertex in this placement.</returns> public override IEnumerator<VertexLocation> GetEnumerator() { return this.locations.AsEnumerable().GetEnumerator(); } /// <summary> /// Returns <c>true</c> if and only if each vertex in this placement has the same location as the vertex /// with the same ID in the <paramref name="other"/> placement, and vice versa. /// </summary> /// <param name="other">The other placement.</param> /// <returns><c>true</c> if and only if each vertex in this placement has the same location as the vertex /// with the same ID in the <paramref name="other"/> placement, and vice versa.</returns> public override bool Equals(Placement other) { return this.locations.SequenceEqual(other); } /// <summary> /// Constructs explicit placement from a sequence of <see cref="VertexLocation"/> objects. /// </summary> /// <param name="locations">The explicit locations of each vertex in this placement.</param> public Explicit(IEnumerable<VertexLocation> locations) { this.locations = locations.ToArray(); } } /// <summary> /// Placement with one vertex per process /// </summary> internal class SingleVertexPerProcess : Placement { private readonly int numProcs; private readonly int threadId; /// <summary> /// Constructor /// </summary> /// <param name="numProcs">number of processes</param> /// <param name="threadId">thread index for the vertex</param> public SingleVertexPerProcess(int numProcs, int threadId) { this.numProcs = numProcs; this.threadId = threadId; } /// <summary> /// Indexer /// </summary> /// <param name="vertexId"></param> /// <returns></returns> public override VertexLocation this[int vertexId] { get { return new VertexLocation(vertexId, vertexId, this.threadId); } } /// <summary> /// Count /// </summary> public override int Count { get { return this.numProcs; } } /// <summary> /// Equals /// </summary> /// <param name="that">other placement</param> /// <returns></returns> public override bool Equals(Placement that) { SingleVertexPerProcess other = that as SingleVertexPerProcess; return this == other || (other != null && this.numProcs == other.numProcs && this.threadId == other.threadId); } /// <summary> /// Enumerator /// </summary> /// <returns></returns> public override IEnumerator<VertexLocation> GetEnumerator() { for (int i = 0; i < this.Count; ++i) yield return this[i]; } } } }
using System.IO; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using k8s.Models; namespace k8s { /// <summary>Describes the type of a watch event.</summary> public enum WatchEventType { /// <summary>Emitted when an object is created, modified to match a watch's filter, or when a watch is first opened.</summary> [EnumMember(Value = "ADDED")] Added, /// <summary>Emitted when an object is modified.</summary> [EnumMember(Value = "MODIFIED")] Modified, /// <summary>Emitted when an object is deleted or modified to no longer match a watch's filter.</summary> [EnumMember(Value = "DELETED")] Deleted, /// <summary>Emitted when an error occurs while watching resources. Most commonly, the error is 410 Gone which indicates that /// the watch resource version was outdated and events were probably lost. In that case, the watch should be restarted. /// </summary> [EnumMember(Value = "ERROR")] Error, /// <summary>Bookmarks may be emitted periodically to update the resource version. The object will /// contain only the resource version. /// </summary> [EnumMember(Value = "BOOKMARK")] Bookmark, } public class Watcher<T> : IDisposable { /// <summary> /// indicate if the watch object is alive /// </summary> public bool Watching { get; private set; } private readonly CancellationTokenSource _cts; private readonly Func<Task<TextReader>> _streamReaderCreator; private bool disposedValue; private readonly Task _watcherLoop; /// <summary> /// Initializes a new instance of the <see cref="Watcher{T}"/> class. /// </summary> /// <param name="streamReaderCreator"> /// A <see cref="StreamReader"/> from which to read the events. /// </param> /// <param name="onEvent"> /// The action to invoke when the server sends a new event. /// </param> /// <param name="onError"> /// The action to invoke when an error occurs. /// </param> /// <param name="onClosed"> /// The action to invoke when the server closes the connection. /// </param> public Watcher(Func<Task<StreamReader>> streamReaderCreator, Action<WatchEventType, T> onEvent, Action<Exception> onError, Action onClosed = null) : this( async () => (TextReader)await streamReaderCreator().ConfigureAwait(false), onEvent, onError, onClosed) { } /// <summary> /// Initializes a new instance of the <see cref="Watcher{T}"/> class. /// </summary> /// <param name="streamReaderCreator"> /// A <see cref="TextReader"/> from which to read the events. /// </param> /// <param name="onEvent"> /// The action to invoke when the server sends a new event. /// </param> /// <param name="onError"> /// The action to invoke when an error occurs. /// </param> /// <param name="onClosed"> /// The action to invoke when the server closes the connection. /// </param> public Watcher(Func<Task<TextReader>> streamReaderCreator, Action<WatchEventType, T> onEvent, Action<Exception> onError, Action onClosed = null) { _streamReaderCreator = streamReaderCreator; OnEvent += onEvent; OnError += onError; OnClosed += onClosed; _cts = new CancellationTokenSource(); _watcherLoop = Task.Run(async () => await WatcherLoop(_cts.Token).ConfigureAwait(false)); } /// <summary> /// add/remove callbacks when any event raised from api server /// </summary> public event Action<WatchEventType, T> OnEvent; /// <summary> /// add/remove callbacks when any exception was caught during watching /// </summary> public event Action<Exception> OnError; /// <summary> /// The event which is raised when the server closes the connection. /// </summary> public event Action OnClosed; public class WatchEvent { [JsonPropertyName("type")] public WatchEventType Type { get; set; } [JsonPropertyName("object")] public T Object { get; set; } } private async Task WatcherLoop(CancellationToken cancellationToken) { try { Watching = true; await foreach (var (t, evt) in CreateWatchEventEnumerator(_streamReaderCreator, OnError, cancellationToken) .ConfigureAwait(false) ) { OnEvent?.Invoke(t, evt); } } catch (OperationCanceledException) { // ignore } catch (Exception e) { // error when transport error, IOException ect OnError?.Invoke(e); } finally { Watching = false; OnClosed?.Invoke(); } } internal static async IAsyncEnumerable<(WatchEventType, T)> CreateWatchEventEnumerator( Func<Task<TextReader>> streamReaderCreator, Action<Exception> onError = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) { Task<TR> AttachCancellationToken<TR>(Task<TR> task) { if (!task.IsCompleted) { // here to pass cancellationToken into task return task.ContinueWith(t => t.GetAwaiter().GetResult(), cancellationToken); } return task; } using var streamReader = await AttachCancellationToken(streamReaderCreator()).ConfigureAwait(false); for (; ; ) { // ReadLineAsync will return null when we've reached the end of the stream. var line = await AttachCancellationToken(streamReader.ReadLineAsync()).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); if (line == null) { yield break; } WatchEvent @event = null; try { var genericEvent = KubernetesJson.Deserialize<Watcher<KubernetesObject>.WatchEvent>(line); if (genericEvent.Object.Kind == "Status") { var statusEvent = KubernetesJson.Deserialize<Watcher<V1Status>.WatchEvent>(line); var exception = new KubernetesException(statusEvent.Object); onError?.Invoke(exception); } else { @event = KubernetesJson.Deserialize<WatchEvent>(line); } } catch (Exception e) { onError?.Invoke(e); } if (@event != null) { yield return (@event.Type, @event.Object); } } } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { _cts?.Cancel(); _cts?.Dispose(); } disposedValue = true; } } // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources // ~Watcher() // { // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Dispose(disposing: false); // } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(true); GC.SuppressFinalize(this); } } }