context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using Invio.Xunit; using Xunit; namespace Invio.Immutable { [UnitTest] public sealed class StringPropertyHandlerTests : PropertyHandlerTestsBase { private static PropertyInfo stringProperty { get; } static StringPropertyHandlerTests() { var propertyName = nameof(FakeImmutable.StringProperty); stringProperty = typeof(FakeImmutable).GetProperty(propertyName); } [Fact] public void Constructor_NullProperty() { // Arrange PropertyInfo property = null; // Act var exception = Record.Exception( () => new StringPropertyHandler(property) ); // Assert Assert.IsType<ArgumentNullException>(exception); } [Fact] public void Constructor_NonStringProperty() { // Arrange var property = typeof(FakeImmutable) .GetProperty(nameof(FakeImmutable.NullableDateTimeProperty)); // Act var exception = Record.Exception( () => new StringPropertyHandler(property) ); // Assert Assert.IsType<ArgumentException>(exception); Assert.Equal( $"The '{property.Name}' property is not of type 'String'." + Environment.NewLine + "Parameter name: property", exception.Message ); } [Fact] public void Constructor_NullComparer() { // Arrange StringComparer comparer = null; // Act var exception = Record.Exception( () => new StringPropertyHandler(stringProperty, comparer) ); // Assert Assert.IsType<ArgumentNullException>(exception); } [Theory] [InlineData("foo", "foo")] [InlineData("foo", "bar")] [InlineData("FOO", "foo")] public void ArePropertyValuesEqual_OrdinalByDefault(string left, string right) { // Arrange var handler = this.CreateHandler(stringProperty); var leftFake = this.NextFake().SetStringProperty(left); var rightFake = this.NextFake().SetStringProperty(right); // Act var comparerResult = StringComparer.Ordinal.Equals(left, right); var handlerResult = handler.ArePropertyValuesEqual(leftFake, rightFake); // Assert Assert.Equal(comparerResult, handlerResult); } public static IEnumerable<object[]> GetPropertyValueHashCode_NullValues_MemberData { get { yield return new object[] { StringComparer.Ordinal }; yield return new object[] { StringComparer.OrdinalIgnoreCase }; yield return new object[] { StringComparer.CurrentCulture }; } } [Theory] [MemberData(nameof(GetPropertyValueHashCode_NullValues_MemberData))] public void GetPropertyValueHashCode_NullValues(StringComparer comparer) { // Arrange var handler = this.CreateHandler(stringProperty, comparer); var fake = this.NextFake().SetStringProperty(null); // Act var hashCode = handler.GetPropertyValueHashCode(fake); // Assert Assert.Equal(37, hashCode); // 37 is the universal default hash code for "null" that is // defined in the abstract PropertyHandlerBase implementation. } [Theory] [InlineData("foo")] [InlineData("Foo")] [InlineData("FOO")] public void GetPropertyValueHashCode_OrdinalByDefault(string stringValue) { // Arrange var handler = this.CreateHandler(stringProperty); var fake = this.NextFake().SetStringProperty(stringValue); // Act var comparerResult = StringComparer.Ordinal.GetHashCode(stringValue); var handlerResult = handler.GetPropertyValueHashCode(fake); // Assert Assert.Equal(comparerResult, handlerResult); } public static IEnumerable<object[]> ArePropertyValuesEqual_MemberData { get; } = ImmutableList.Create<object[]>( new object[] { "foo", "foo", StringComparer.Ordinal }, new object[] { "FOO", "foo", StringComparer.Ordinal }, new object[] { "foo", "bar", StringComparer.Ordinal }, new object[] { null, "foo", StringComparer.Ordinal }, new object[] { "foo", null, StringComparer.Ordinal }, new object[] { null, null, StringComparer.Ordinal }, new object[] { "foo", "foo", StringComparer.OrdinalIgnoreCase }, new object[] { "FOO", "foo", StringComparer.OrdinalIgnoreCase }, new object[] { "foo", "bar", StringComparer.OrdinalIgnoreCase }, new object[] { null, "foo", StringComparer.OrdinalIgnoreCase }, new object[] { "foo", null, StringComparer.OrdinalIgnoreCase }, new object[] { null, null, StringComparer.OrdinalIgnoreCase } ); [Theory] [MemberData(nameof(ArePropertyValuesEqual_MemberData))] public void ArePropertyValuesEqual_MatchesComparer( string left, string right, StringComparer comparer) { // Arrange var handler = this.CreateHandler(stringProperty, comparer); var leftFake = this.NextFake().SetStringProperty(left); var rightFake = this.NextFake().SetStringProperty(right); // Act var comparerResult = comparer.Equals(left, right); var handlerResult = handler.ArePropertyValuesEqual(leftFake, rightFake); // Assert Assert.Equal(comparerResult, handlerResult); } public static IEnumerable<object[]> GetPropertyValueHashCode_MemberData { get; } = ImmutableList.Create<object[]>( new object[] { "foo", StringComparer.Ordinal }, new object[] { "FOO", StringComparer.Ordinal }, new object[] { "foo", StringComparer.OrdinalIgnoreCase }, new object[] { "FOO", StringComparer.OrdinalIgnoreCase } ); [Theory] [MemberData(nameof(GetPropertyValueHashCode_MemberData))] public void GetPropertyValueHashCode_MatchesComparer( String stringValue, StringComparer comparer) { // Arrange var handler = this.CreateHandler(stringProperty, comparer); var fake = this.NextFake().SetStringProperty(stringValue); // Act var comparerResult = comparer.GetHashCode(stringValue); var handlerResult = handler.GetPropertyValueHashCode(fake); // Assert Assert.Equal(comparerResult, handlerResult); } protected override PropertyInfo NextValidPropertyInfo() { return stringProperty; } protected override object NextParent() { return this.NextFake(); } private FakeImmutable NextFake() { return new FakeImmutable(Guid.NewGuid().ToString(), DateTime.UtcNow); } protected override IPropertyHandler CreateHandler(PropertyInfo property) { return new StringPropertyHandler(property); } private IPropertyHandler CreateHandler(PropertyInfo property, StringComparer comparer) { return new StringPropertyHandler(property, comparer); } public sealed class FakeImmutable : ImmutableBase<FakeImmutable> { public String StringProperty { get; } public DateTime? NullableDateTimeProperty { get; } public Guid UnrelatedGuid { get; } public FakeImmutable( String stringProperty = default(String), DateTime? nullableDateTimeProperty = default(DateTime?), Guid unrelatedGuid = default(Guid)) { this.StringProperty = stringProperty; this.NullableDateTimeProperty = nullableDateTimeProperty; this.UnrelatedGuid = unrelatedGuid; } public FakeImmutable SetStringProperty(String stringProperty) { return this.SetPropertyValueImpl(nameof(StringProperty), stringProperty); } } } }
// // support.cs: Support routines to work around the fact that System.Reflection.Emit // can not introspect types that are being constructed // // Author: // Miguel de Icaza ([email protected]) // Marek Safar ([email protected]) // // Copyright 2001 Ximian, Inc (http://www.ximian.com) // Copyright 2003-2009 Novell, Inc // Copyright 2011 Xamarin Inc // using System; using System.Linq; using System.IO; using System.Text; using System.Collections.Generic; namespace Mono.CSharp { sealed class ReferenceEquality<T> : IEqualityComparer<T> where T : class { public static readonly IEqualityComparer<T> Default = new ReferenceEquality<T> (); private ReferenceEquality () { } public bool Equals (T x, T y) { return ReferenceEquals (x, y); } public int GetHashCode (T obj) { return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode (obj); } } #if !NET_4_0 && !MONODROID public class Tuple<T1, T2> : IEquatable<Tuple<T1, T2>> { public Tuple (T1 item1, T2 item2) { Item1 = item1; Item2 = item2; } public T1 Item1 { get; private set; } public T2 Item2 { get; private set; } public override int GetHashCode () { return ((object)Item1 ?? 0) .GetHashCode () ^ ((object)Item2 ?? 0).GetHashCode (); } #region IEquatable<Tuple<T1,T2>> Members public bool Equals (Tuple<T1, T2> other) { return EqualityComparer<T1>.Default.Equals (Item1, other.Item1) && EqualityComparer<T2>.Default.Equals (Item2, other.Item2); } #endregion } public class Tuple<T1, T2, T3> : IEquatable<Tuple<T1, T2, T3>> { public Tuple (T1 item1, T2 item2, T3 item3) { Item1 = item1; Item2 = item2; Item3 = item3; } public T1 Item1 { get; private set; } public T2 Item2 { get; private set; } public T3 Item3 { get; private set; } public override int GetHashCode () { return Item1.GetHashCode () ^ Item2.GetHashCode () ^ Item3.GetHashCode (); } #region IEquatable<Tuple<T1,T2>> Members public bool Equals (Tuple<T1, T2, T3> other) { return EqualityComparer<T1>.Default.Equals (Item1, other.Item1) && EqualityComparer<T2>.Default.Equals (Item2, other.Item2) && EqualityComparer<T3>.Default.Equals (Item3, other.Item3); } #endregion } static class Tuple { public static Tuple<T1, T2> Create<T1, T2> (T1 item1, T2 item2) { return new Tuple<T1, T2> (item1, item2); } public static Tuple<T1, T2, T3> Create<T1, T2, T3> (T1 item1, T2 item2, T3 item3) { return new Tuple<T1, T2, T3> (item1, item2, item3); } } #endif static class ArrayComparer { public static bool IsEqual<T> (T[] array1, T[] array2) { if (array1 == null || array2 == null) return array1 == array2; var eq = EqualityComparer<T>.Default; for (int i = 0; i < array1.Length; ++i) { if (!eq.Equals (array1[i], array2[i])) { return false; } } return true; } } #if !FULL_AST /// <summary> /// This is an arbitrarily seekable StreamReader wrapper. /// /// It uses a self-tuning buffer to cache the seekable data, /// but if the seek is too far, it may read the underly /// stream all over from the beginning. /// </summary> public class SeekableStreamReader : IDisposable { public const int DefaultReadAheadSize = 2048; StreamReader reader; Stream stream; char[] buffer; int read_ahead_length; // the length of read buffer int buffer_start; // in chars int char_count; // count of filled characters in buffer[] int pos; // index into buffer[] public SeekableStreamReader (Stream stream, Encoding encoding, char[] sharedBuffer = null) { this.stream = stream; this.buffer = sharedBuffer; InitializeStream (DefaultReadAheadSize); reader = new StreamReader (stream, encoding, true); } public void Dispose () { // Needed to release stream reader buffers reader.Dispose (); } void InitializeStream (int read_length_inc) { read_ahead_length += read_length_inc; int required_buffer_size = read_ahead_length * 2; if (buffer == null || buffer.Length < required_buffer_size) buffer = new char [required_buffer_size]; stream.Position = 0; buffer_start = char_count = pos = 0; } /// <remarks> /// This value corresponds to the current position in a stream of characters. /// The StreamReader hides its manipulation of the underlying byte stream and all /// character set/decoding issues. Thus, we cannot use this position to guess at /// the corresponding position in the underlying byte stream even though there is /// a correlation between them. /// </remarks> public int Position { get { return buffer_start + pos; } set { // // If the lookahead was too small, re-read from the beginning. Increase the buffer size while we're at it // This should never happen until we are parsing some weird source code // if (value < buffer_start) { InitializeStream (read_ahead_length); // // Discard buffer data after underlying stream changed position // Cannot use handy reader.DiscardBufferedData () because it for // some strange reason resets encoding as well // reader = new StreamReader (stream, reader.CurrentEncoding, true); } while (value > buffer_start + char_count) { pos = char_count; if (!ReadBuffer ()) throw new InternalErrorException ("Seek beyond end of file: " + (buffer_start + char_count - value)); } pos = value - buffer_start; } } bool ReadBuffer () { int slack = buffer.Length - char_count; // // read_ahead_length is only half of the buffer to deal with // reads ahead and moves back without re-reading whole buffer // if (slack <= read_ahead_length) { // // shift the buffer to make room for read_ahead_length number of characters // int shift = read_ahead_length - slack; Array.Copy (buffer, shift, buffer, 0, char_count - shift); // Update all counters pos -= shift; char_count -= shift; buffer_start += shift; slack += shift; } char_count += reader.Read (buffer, char_count, slack); return pos < char_count; } public char GetChar (int position) { if (buffer_start <= position && position < buffer.Length) return buffer[position]; return '\0'; } public char[] ReadChars (int fromPosition, int toPosition) { char[] chars = new char[toPosition - fromPosition]; if (buffer_start <= fromPosition && toPosition <= buffer_start + buffer.Length) { Array.Copy (buffer, fromPosition - buffer_start, chars, 0, chars.Length); } else { throw new NotImplementedException (); } return chars; } public int Peek () { if ((pos >= char_count) && !ReadBuffer ()) return -1; return buffer [pos]; } public int Read () { if ((pos >= char_count) && !ReadBuffer ()) return -1; return buffer [pos++]; } } #endif public class UnixUtils { [System.Runtime.InteropServices.DllImport ("libc", EntryPoint="isatty")] extern static int _isatty (int fd); public static bool isatty (int fd) { try { return _isatty (fd) == 1; } catch { return false; } } } /// <summary> /// An exception used to terminate the compiler resolution phase and provide completions /// </summary> /// <remarks> /// This is thrown when we want to return the completions or /// terminate the completion process by AST nodes used in /// the completion process. /// </remarks> public class CompletionResult : Exception { string [] result; string base_text; public CompletionResult (string base_text, string [] res) { if (base_text == null) throw new ArgumentNullException ("base_text"); this.base_text = base_text; result = res; Array.Sort (result); } public string [] Result { get { return result; } } public string BaseText { get { return base_text; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using Xunit; namespace System.IO.Tests { public partial class StreamReaderTests { protected virtual Stream CreateStream() { return new MemoryStream(); } protected virtual Stream GetSmallStream() { byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; return new MemoryStream(testData); } protected virtual Stream GetLargeStream() { byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; // System.Collections.Generic. List<byte> data = new List<byte>(); for (int i = 0; i < 1000; i++) { data.AddRange(testData); } return new MemoryStream(data.ToArray()); } protected Tuple<char[], StreamReader> GetCharArrayStream() { var chArr = TestDataProvider.CharData; var ms = CreateStream(); var sw = new StreamWriter(ms); for (int i = 0; i < chArr.Length; i++) sw.Write(chArr[i]); sw.Flush(); ms.Position = 0; return new Tuple<char[], StreamReader>(chArr, new StreamReader(ms)); } [Fact] public void EndOfStream() { var sw = new StreamReader(GetSmallStream()); var result = sw.ReadToEnd(); Assert.Equal("HELLO", result); Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); } [Fact] public void EndOfStreamSmallDataLargeBuffer() { var sw = new StreamReader(GetSmallStream(), Encoding.UTF8, true, 1024); var result = sw.ReadToEnd(); Assert.Equal("HELLO", result); Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); } [Fact] public void EndOfStreamLargeDataSmallBuffer() { var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1); var result = sw.ReadToEnd(); Assert.Equal(5000, result.Length); Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); } [Fact] public void EndOfStreamLargeDataLargeBuffer() { var sw = new StreamReader(GetLargeStream(), Encoding.UTF8, true, 1 << 16); var result = sw.ReadToEnd(); Assert.Equal(5000, result.Length); Assert.True(sw.EndOfStream, "End of Stream was not true after ReadToEnd"); } [Fact] public async Task ReadToEndAsync() { var sw = new StreamReader(GetLargeStream()); var result = await sw.ReadToEndAsync(); Assert.Equal(5000, result.Length); } [Fact] public void GetBaseStream() { var ms = GetSmallStream(); var sw = new StreamReader(ms); Assert.Same(sw.BaseStream, ms); } [Fact] public void TestRead() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; for (int i = 0; i < baseInfo.Item1.Length; i++) { int tmp = sr.Read(); Assert.Equal((int)baseInfo.Item1[i], tmp); } sr.Dispose(); } [Fact] public void TestPeek() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; for (int i = 0; i < baseInfo.Item1.Length; i++) { var peek = sr.Peek(); Assert.Equal((int)baseInfo.Item1[i], peek); sr.Read(); } } [Fact] public void ArgumentNullOnNullArray() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; Assert.Throws<ArgumentNullException>(() => sr.Read(null, 0, 0)); } [Fact] public void ArgumentOutOfRangeOnInvalidOffset() { var sr = GetCharArrayStream().Item2; Assert.Throws<ArgumentOutOfRangeException>(() => sr.Read(new char[0], -1, 0)); } [Fact] public void ArgumentOutOfRangeOnNegativCount() { var sr = GetCharArrayStream().Item2; AssertExtensions.Throws<ArgumentException>(null, () => sr.Read(new char[0], 0, 1)); } [Fact] public void ArgumentExceptionOffsetAndCount() { var sr = GetCharArrayStream().Item2; AssertExtensions.Throws<ArgumentException>(null, () => sr.Read(new char[0], 2, 0)); } [Fact] public void ObjectDisposedExceptionDisposedStream() { var sr = GetCharArrayStream().Item2; sr.Dispose(); Assert.Throws<ObjectDisposedException>(() => sr.Read(new char[1], 0, 1)); } [Fact] public void ObjectDisposedExceptionDisposedBaseStream() { var ms = GetSmallStream(); var sr = new StreamReader(ms); ms.Dispose(); Assert.Throws<ObjectDisposedException>(() => sr.Read(new char[1], 0, 1)); } [Fact] public void EmptyStream() { var ms = CreateStream(); var sr = new StreamReader(ms); var buffer = new char[10]; int read = sr.Read(buffer, 0, 1); Assert.Equal(0, read); } [Fact] public void VanillaReads1() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; var chArr = new char[baseInfo.Item1.Length]; var read = sr.Read(chArr, 0, chArr.Length); Assert.Equal(chArr.Length, read); for (int i = 0; i < baseInfo.Item1.Length; i++) { Assert.Equal(baseInfo.Item1[i], chArr[i]); } } [Fact] public async Task VanillaReads2WithAsync() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; var chArr = new char[baseInfo.Item1.Length]; var read = await sr.ReadAsync(chArr, 4, 3); Assert.Equal(read, 3); for (int i = 0; i < 3; i++) { Assert.Equal(baseInfo.Item1[i], chArr[i + 4]); } } [Fact] public void ObjectDisposedReadLine() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; sr.Dispose(); Assert.Throws<ObjectDisposedException>(() => sr.ReadLine()); } [Fact] public void ObjectDisposedReadLineBaseStream() { var ms = GetLargeStream(); var sr = new StreamReader(ms); ms.Dispose(); Assert.Throws<ObjectDisposedException>(() => sr.ReadLine()); } [Fact] public void VanillaReadLines() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; string valueString = new string(baseInfo.Item1); var data = sr.ReadLine(); Assert.Equal(valueString.Substring(0, valueString.IndexOf('\r')), data); data = sr.ReadLine(); Assert.Equal(valueString.Substring(valueString.IndexOf('\r') + 1, 3), data); data = sr.ReadLine(); Assert.Equal(valueString.Substring(valueString.IndexOf('\n') + 1, 2), data); data = sr.ReadLine(); Assert.Equal((valueString.Substring(valueString.LastIndexOf('\n') + 1)), data); } [Fact] public void VanillaReadLines2() { var baseInfo = GetCharArrayStream(); var sr = baseInfo.Item2; string valueString = new string(baseInfo.Item1); var temp = new char[10]; sr.Read(temp, 0, 1); var data = sr.ReadLine(); Assert.Equal(valueString.Substring(1, valueString.IndexOf('\r') - 1), data); } [Fact] public async Task ContinuousNewLinesAndTabsAsync() { var ms = CreateStream(); var sw = new StreamWriter(ms); sw.Write("\n\n\r\r\n"); sw.Flush(); ms.Position = 0; var sr = new StreamReader(ms); for (int i = 0; i < 4; i++) { var data = await sr.ReadLineAsync(); Assert.Equal(string.Empty, data); } var eol = await sr.ReadLineAsync(); Assert.Null(eol); } [Fact] public void CurrentEncoding() { var ms = CreateStream(); var sr = new StreamReader(ms); Assert.Equal(Encoding.UTF8, sr.CurrentEncoding); sr = new StreamReader(ms, Encoding.Unicode); Assert.Equal(Encoding.Unicode, sr.CurrentEncoding); } } }
using System.Diagnostics; using System; using System.Management; using System.Collections; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Web.UI.Design; using System.Data; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Security; // POP3 Quoted Printable // ===================== // // copyright by Peter Huber, Singapore, 2006 // this code is provided as is, bugs are probable, free for any use, no responsiblity accepted :-) // // based on QuotedPrintable Class from ASP emporium, http://www.aspemporium.com/classes.aspx?cid=6 namespace ACSGhana.Web.Framework { namespace Mail { namespace Pop3 { /// <summary> /// <para> /// Robust and fast implementation of Quoted Printable /// Multipart Internet Mail Encoding (MIME) which encodes every /// character, not just "special characters" for transmission over SMTP. /// </para> /// <para> /// More information on the quoted-printable encoding can be found /// here: http://www.freesoft.org/CIE/RFC/1521/6.htm /// </para> /// </summary> /// <remarks> /// <para> /// detailed in: RFC 1521 /// </para> /// <para> /// more info: http://www.freesoft.org/CIE/RFC/1521/6.htm /// </para> /// <para> /// The QuotedPrintable class encodes and decodes strings and files /// that either were encoded or need encoded in the Quoted-Printable /// MIME encoding for Internet mail. The encoding methods of the class /// use pointers wherever possible to guarantee the fastest possible /// encoding times for any size file or string. The decoding methods /// use only the .NET framework classes. /// </para> /// <para> /// The Quoted-Printable implementation /// is robust which means it encodes every character to ensure that the /// information is decoded properly regardless of machine or underlying /// operating system or protocol implementation. The decode can recognize /// robust encodings as well as minimal encodings that only encode special /// characters and any implementation in between. Internally, the /// class uses a regular expression replace pattern to decode a quoted- /// printable string or file. /// </para> /// </remarks> /// <example> /// This example shows how to quoted-printable encode an html file and then /// decode it. /// <code> /// string encoded = QuotedPrintable.EncodeFile( /// @"C:\WEBS\wwwroot\index.html" /// ); /// /// string decoded = QuotedPrintable.Decode(encoded); /// /// Console.WriteLine(decoded); /// </code> /// </example> internal class QuotedPrintable { private QuotedPrintable() { } /// <summary> /// Gets the maximum number of characters per quoted-printable /// line as defined in the RFC minus 1 to allow for the = /// character (soft line break). /// </summary> /// <remarks> /// (Soft Line Breaks): The Quoted-Printable encoding REQUIRES /// that encoded lines be no more than 76 characters long. If /// longer lines are to be encoded with the Quoted-Printable /// encoding, 'soft' line breaks must be used. An equal sign /// as the last character on a encoded line indicates such a /// non-significant ('soft') line break in the encoded text. /// </remarks> public const int RFC_1521_MAX_CHARS_PER_LINE = 75; private static string HexDecoderEvaluator(Match m) { string hex = m.Groups[2].Value; int iHex = Convert.ToInt32(hex, 16); char c = Strings.ChrW(iHex); return c.ToString(); } static public string HexDecoder(string line) { if (line == null) { throw (new ArgumentNullException()); } //parse looking for =XX where XX is hexadecimal Regex re = new Regex("(\\=([0-9A-F][0-9A-F]))", RegexOptions.IgnoreCase); return re.Replace(line, new MatchEvaluator(HexDecoderEvaluator)); } /// <summary> /// decodes an entire file's contents into plain text that /// was encoded with quoted-printable. /// </summary> /// <param name="filepath"> /// The path to the quoted-printable encoded file to decode. /// </param> /// <returns>The decoded string.</returns> /// <exception cref="ObjectDisposedException"> /// A problem occurred while attempting to decode the /// encoded string. /// </exception> /// <exception cref="OutOfMemoryException"> /// There is insufficient memory to allocate a buffer for the /// returned string. /// </exception> /// <exception cref="ArgumentNullException"> /// A string is passed in as a null reference. /// </exception> /// <exception cref="IOException"> /// An I/O error occurs, such as the stream being closed. /// </exception> /// <exception cref="FileNotFoundException"> /// The file was not found. /// </exception> /// <exception cref="SecurityException"> /// The caller does not have the required permission to open /// the file specified in filepath. /// </exception> /// <exception cref="UnauthorizedAccessException"> /// filepath is read-only or a directory. /// </exception> /// <remarks> /// Decodes a quoted-printable encoded file into a string /// of unencoded text of any size. /// </remarks> public static string DecodeFile(string filepath) { if (filepath == null) { throw (new ArgumentNullException()); } string decodedHtml = ""; string line; FileInfo f = new FileInfo(filepath); if (! f.Exists) { throw (new FileNotFoundException()); } StreamReader sr = f.OpenText(); try { line = sr.ReadLine(); while (line != null) { decodedHtml += Decode(line); line = sr.ReadLine(); } return decodedHtml; } finally { sr.Close(); sr = null; f = null; } } /// <summary> /// Decodes a Quoted-Printable string of any size into /// it's original text. /// </summary> /// <param name="encoded"> /// The encoded string to decode. /// </param> /// <returns>The decoded string.</returns> /// <exception cref="ArgumentNullException"> /// A string is passed in as a null reference. /// </exception> /// <remarks> /// Decodes a quoted-printable encoded string into a string /// of unencoded text of any size. /// </remarks> public static string Decode(string encoded) { if (encoded == null) { throw (new ArgumentNullException()); } string line; StringWriter sw = new StringWriter(); StringReader sr = new StringReader(encoded); try { line = sr.ReadLine(); while (line != null) { if (line.EndsWith("=")) { sw.Write(HexDecoder(line.Substring(0, line.Length - 1))); } else { sw.WriteLine(HexDecoder(line)); } sw.Flush(); line = sr.ReadLine(); } return sw.ToString(); } finally { sw.Close(); sr.Close(); sw = null; sr = null; } } } } } }
using ImGuiNET; using Microsoft.Xna.Framework.Input; using OpenKh.Common; using OpenKh.Engine.Renders; using OpenKh.Kh2; using OpenKh.Kh2.Extensions; using OpenKh.Tools.Common; using OpenKh.Tools.Common.CustomImGui; using OpenKh.Tools.LayoutEditor.Dialogs; using OpenKh.Tools.LayoutEditor.Interfaces; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; using System.Windows; using Xe.Tools.Wpf.Dialogs; using static OpenKh.Tools.Common.CustomImGui.ImGuiEx; namespace OpenKh.Tools.LayoutEditor { public class App : IEditorSettings, IDisposable { private static readonly List<FileDialogFilter> Filters = FileDialogFilterComposer .Compose() .AddPatterns("All supported files", "2ld;*.lad;*.2dd;*.map;P_*.a.*;00font.bar;10font.bar") .AddExtensions("2LD Layout container file", "2ld", "lad") .AddExtensions("2DD Sequence container file", "2dd") .AddExtensions("MAP file", "map") .AddExtensions("Character file", "a.*") .AddPatterns("00font and 10font", "00font.bar", "10font.bar") .AddAllFiles(); private static readonly List<FileDialogFilter> ImzFilter = FileDialogFilterComposer .Compose() .AddExtensions("Image container IMGZ", "imz") .AddAllFiles(); private static readonly List<FileDialogFilter> ImdFilter = FileDialogFilterComposer .Compose() .AddExtensions("Image IMGD", "imd") .AddAllFiles(); private const string DefaultName = "FAKE"; private readonly MonoGameImGuiBootstrap _bootstrap; private bool _exitFlag = false; private string _animationName; private string _spriteName; private string _fileName; private ToolInvokeDesc _toolInvokeDesc; private IApp _app; private bool _linkToPcsx2; private ProcessStream _processStream; private int _processOffset; private const string LinkToPcsx2ActionName = "Open file and link it to PCSX2"; private const string ResourceSelectionDialogTitle = "Resource selection"; private bool _isResourceSelectionDialogOpening; private bool _isResourceSelectingLayout; private ResourceSelectionDialog _resourceSelectionDialog; private Dictionary<Keys, Action> _keyMapping = new Dictionary<Keys, Action>(); public event IEditorSettings.ChangeBackground OnChangeBackground; public string Title { get { var contentName = IsBar ? $"{AnimationName ?? DefaultName},{TextureName ?? DefaultName} | " : string.Empty; var fileName = IsToolDesc ? _toolInvokeDesc.Title : (FileName ?? "untitled"); if (_processStream != null) fileName = $"{fileName}@pcsx2:{_processOffset}"; return $"{contentName}{fileName} | {MonoGameImGuiBootstrap.ApplicationName}"; } } private string FileName { get => _fileName; set { _fileName = value; UpdateTitle(); } } public bool IsToolDesc => _toolInvokeDesc != null; public ISaveBar CurrentEditor { get; private set; } public bool IsBar { get; set; } public string AnimationName { get => _animationName; set => _animationName = value.Length > 4 ? value.Substring(0, 4) : value; } public string TextureName { get => _spriteName; set => _spriteName = value.Length > 4 ? value.Substring(0, 4) : value; } public bool CheckerboardBackground { get; set; } public ColorF EditorBackground { get => new ColorF(Settings.Default.BgColorR, Settings.Default.BgColorG, Settings.Default.BgColorB, 1f); set { Settings.Default.BgColorR = value.R; Settings.Default.BgColorG = value.G; Settings.Default.BgColorB = value.B; Settings.Default.Save(); } } public bool ShowViewportOriginal { get => Settings.Default.ShowViewportOriginal; set { Settings.Default.ShowViewportOriginal = value; Settings.Default.Save(); } } public bool ShowViewportRemix { get => Settings.Default.ShowViewportRemix; set { Settings.Default.ShowViewportRemix = value; Settings.Default.Save(); } } public bool IsViewportOnTop { get => Settings.Default.IsViewportOnTop; set { Settings.Default.IsViewportOnTop = value; Settings.Default.Save(); } } public App(MonoGameImGuiBootstrap bootstrap) { _bootstrap = bootstrap; _bootstrap.Title = Title; AddKeyMapping(Keys.O, MenuFileOpenWithoutPcsx2); AddKeyMapping(Keys.L, MenuFileOpenPcsx2); AddKeyMapping(Keys.S, MenuFileSave); } public bool MainLoop() { ProcessKeyMapping(); bool dummy = true; if (ImGui.BeginPopupModal(ResourceSelectionDialogTitle, ref dummy, ImGuiWindowFlags.Popup | ImGuiWindowFlags.Modal | ImGuiWindowFlags.AlwaysAutoResize)) { _resourceSelectionDialog.Run(); ImGui.EndPopup(); if (_resourceSelectionDialog.HasResourceBeenSelected) { if (_isResourceSelectingLayout) OpenLayoutEditor(_resourceSelectionDialog.SelectedAnimation, _resourceSelectionDialog.SelectedTexture); else OpenSequenceEditor(_resourceSelectionDialog.SelectedAnimation, _resourceSelectionDialog.SelectedTexture); } } ImGuiEx.MainWindow(() => { MainMenu(); MainWindow(); }); if (_isResourceSelectionDialogOpening) { ImGui.OpenPopup(ResourceSelectionDialogTitle); _isResourceSelectionDialogOpening = false; } return _exitFlag; } public void Dispose() { CloseProcessStream(); } private void MainWindow() { if (_app != null) { _app.Run(); } else { ImGui.Text("No files loaded at the moment"); } } void MainMenu() { ForMenuBar(() => { ForMenu("File", () => { ForMenuItem("Open...", "CTRL+O", MenuFileOpenWithoutPcsx2); ForMenuItem($"{LinkToPcsx2ActionName}...", "CTRL+L", MenuFileOpenPcsx2); ForMenuItem("Save", "CTRL+S", MenuFileSave, CurrentEditor != null); ForMenuItem("Save as...", MenuFileSaveAs, CurrentEditor != null); ImGui.Separator(); ForMenu("Preferences", () => { //var checkerboardBackground = CheckerboardBackground; //if (ImGui.Checkbox("Checkerboard background", ref checkerboardBackground)) //{ // CheckerboardBackground = false; // OnChangeBackground?.Invoke(this, this); //} var editorBackground = new Vector3(EditorBackground.R, EditorBackground.G, EditorBackground.B); if (ImGui.ColorEdit3("Background color", ref editorBackground)) { EditorBackground = new ColorF(editorBackground.X, editorBackground.Y, editorBackground.Z, 1f); OnChangeBackground?.Invoke(this, this); } ForMenuCheck("Show PS2 viewport", () => ShowViewportOriginal, x => ShowViewportOriginal = x); ForMenuCheck("Show ReMIX viewport", () => ShowViewportRemix, x => ShowViewportRemix = x); ForMenuCheck("Viewport always on top", () => IsViewportOnTop, x => IsViewportOnTop = x); }); ImGui.Separator(); ForMenuItem("Exit", MenuFileExit); }); _app?.Menu(); ForMenu("Help", () => { ForMenuItem("About", ShowAboutDialog); }); }); } private void MenuFileOpen() { FileDialog.OnOpen(fileName => { OpenFile(fileName); }, Filters); } private void MenuFileOpenWithoutPcsx2() { _linkToPcsx2 = false; CloseProcessStream(); MenuFileOpen(); } private void MenuFileOpenPcsx2() { CloseProcessStream(); var processes = Process.GetProcessesByName("pcsx2"); if (processes.Length == 0) { ShowLinkPcsx2ErrorProcessNotFound(); return; } _linkToPcsx2 = true; MenuFileOpen(); } private void MenuFileSave() { if (!string.IsNullOrEmpty(FileName)) SaveFile(FileName, FileName); else MenuFileSaveAs(); } private void MenuFileSaveAs() { FileDialog.OnSave(fileName => { SaveFile(FileName, fileName); FileName = fileName; }, Filters); } private void MenuFileExit() => _exitFlag = true; public void OpenToolDesc(ToolInvokeDesc toolInvokeDesc) { _toolInvokeDesc = toolInvokeDesc; OpenFile(_toolInvokeDesc.ActualFileName); } public void OpenFile(string fileName, bool doNotShowLayoutSelectionDialog = false) { try { bool isSuccess; if (File.OpenRead(fileName).Using(Layout.IsValid)) { IEnumerable<Imgd> imgd = null; FileDialog.OnOpen(texFileName => { imgd = File.OpenRead(texFileName).Using(Imgz.Read); }, ImzFilter); if (imgd != null) { using var layoutStream = File.OpenRead(fileName); OpenLayoutEditor(layoutStream, imgd); isSuccess = true; IsBar = false; } else isSuccess = false; } else if (File.OpenRead(fileName).Using(Sequence.IsValid)) { ShowError("SED files can not be opened directly."); isSuccess = false; IsBar = false; } else if (File.OpenRead(fileName).Using(Bar.IsValid)) { isSuccess = OpenBarContent(ReadBarEntriesFromFileName(fileName), doNotShowLayoutSelectionDialog); IsBar = true; } else { ShowError("File not recognized."); isSuccess = false; } if (isSuccess) FileName = fileName; } catch (Exception ex) { ShowError(ex.Message); } } public void SaveFile(string previousFileName, string fileName) { if (!IsBar) { var entry = CurrentEditor.SaveAnimation("dummy"); using var stream = File.Create(fileName); entry.Stream.SetPosition(0).CopyTo(stream); } else { SaveFileAsBar(previousFileName, fileName); } } public void SaveFileAsBar(string previousFileName, string fileName) { var existingEntries = File.Exists(previousFileName) ? ReadBarEntriesFromFileName(previousFileName) : new List<Bar.Entry>(); var animationEntry = CurrentEditor.SaveAnimation(AnimationName); if (_processStream != null) { animationEntry.Stream.SetPosition(0); _processStream.SetPosition(_processOffset); animationEntry.Stream.CopyTo(_processStream); animationEntry.Stream.SetPosition(0); } var newEntries = existingEntries .AddOrReplace(animationEntry) .AddOrReplace(CurrentEditor.SaveTexture(TextureName)); File.Create(fileName).Using(stream => Bar.Write(stream, newEntries)); if (IsToolDesc) _toolInvokeDesc.ContentChange = ToolInvokeDesc.ContentChangeInfo.File; } private static IEnumerable<Bar.Entry> ReadBarEntriesFromFileName(string fileName) => File.OpenRead(fileName).Using(stream => { if (!Bar.IsValid(stream)) throw new InvalidDataException("Not a bar file"); return Bar.Read(stream); }); private bool OpenBarContent(IEnumerable<Bar.Entry> entries, bool doNotShowLayoutSelectionDialog = false) { var layoutEntries = entries.Count(x => x.Type == Bar.EntryType.Layout); var sequenceEntries = entries.Count(x => x.Type == Bar.EntryType.Seqd); if (DoesContainSequenceAnimations(entries)) return Open2dd(entries); if (DoesContainLayoutAnimations(entries)) return Open2ld(entries, doNotShowLayoutSelectionDialog); throw new Exception("The specified file does not contain any sequence or layout content to be played."); } private bool Open2ld(IEnumerable<Bar.Entry> entries, bool doNotShowLayoutSelectionDialog = false) { var layoutEntries = entries.Count(x => x.Type == Bar.EntryType.Layout); int imagesEntries = entries.Count(x => x.Type == Bar.EntryType.Imgz); if (layoutEntries == 0) throw new Exception("No layout found."); if (imagesEntries == 0) throw new Exception("No image container found."); if (layoutEntries > 1 || imagesEntries > 1) { OpenResourceSelectionDialog(entries, Bar.EntryType.Layout, Bar.EntryType.Imgz); return true; } var layoutEntry = entries.First(x => x.Type == Bar.EntryType.Layout); var textureContainerEntry = entries.First(x => x.Type == Bar.EntryType.Imgz); OpenLayoutEditor(layoutEntry, textureContainerEntry); return true; } private bool Open2dd(IEnumerable<Bar.Entry> entries) { var sequenceEntries = entries.Count(x => x.Type == Bar.EntryType.Seqd); int imagesEntries = entries.Count(x => x.Type == Bar.EntryType.Imgd); if (sequenceEntries == 0) throw new Exception("No sequence found."); if (imagesEntries == 0) throw new Exception("No image found."); if (sequenceEntries > 1 || imagesEntries > 1) { OpenResourceSelectionDialog(entries, Bar.EntryType.Seqd, Bar.EntryType.Imgd); return true; } var sequenceEntry = entries.First(x => x.Type == Bar.EntryType.Seqd); var textureEntry = entries.First(x => x.Type == Bar.EntryType.Imgd); OpenSequenceEditor(sequenceEntry, textureEntry); return true; } private void OpenResourceSelectionDialog(IEnumerable<Bar.Entry> entries, Bar.EntryType animationType, Bar.EntryType textureType) { _resourceSelectionDialog = new ResourceSelectionDialog( entries, animationType, textureType); _isResourceSelectionDialogOpening = true; _isResourceSelectingLayout = animationType == Bar.EntryType.Layout; } private void OpenSequenceEditor(Bar.Entry sequenceEntry, Bar.Entry textureEntry) { AnimationName = sequenceEntry.Name; TextureName = textureEntry.Name; if (_linkToPcsx2) { _linkToPcsx2 = false; if (!LinkSeqdToPcs2(sequenceEntry.Stream)) return; } var app = new AppSequenceEditor(_bootstrap, this, Sequence.Read(sequenceEntry.Stream.SetPosition(0)), Imgd.Read(textureEntry.Stream)); _app = app; CurrentEditor = app; } private void OpenLayoutEditor(Bar.Entry layoutEntry, Bar.Entry textureContainerEntry) { AnimationName = layoutEntry.Name; TextureName = textureContainerEntry.Name; OpenLayoutEditor(layoutEntry.Stream, Imgz.Read(textureContainerEntry.Stream)); } private void OpenLayoutEditor(Stream layoutStream, IEnumerable<Imgd> images) { if (_linkToPcsx2) { _linkToPcsx2 = false; if (!LinkLaydToPcs2(layoutStream)) return; } var app = new AppLayoutEditor(_bootstrap, this, Layout.Read(layoutStream.SetPosition(0)), images); _app = app; CurrentEditor = app; } private void UpdateTitle() { _bootstrap.Title = Title; } private void AddKeyMapping(Keys key, Action action) { _keyMapping[key] = action; } private void ProcessKeyMapping() { var k = Keyboard.GetState(); if (k.IsKeyDown(Keys.LeftControl)) { var keys = k.GetPressedKeys(); foreach (var key in keys) { if (_keyMapping.TryGetValue(key, out var action)) action(); } } } //private void OpenLayout(LayoutEntryModel layoutEntryModel) //{ // AnimationName = layoutEntryModel.Layout.Name; // SpriteName = layoutEntryModel.Images.Name; // var texturesViewModel = new TexturesViewModel(layoutEntryModel.Images.Value); // var layoutEditorViewModel = new LayoutEditorViewModel(this, this, EditorDebugRenderingService) // { // SequenceGroups = new SequenceGroupsViewModel(layoutEntryModel.Layout.Value, texturesViewModel, EditorDebugRenderingService), // Layout = layoutEntryModel.Layout.Value, // Images = layoutEntryModel.Images.Value // }; // CurrentEditor = layoutEditorViewModel; // OnControlChanged?.Invoke(new LayoutEditorView() // { // DataContext = layoutEditorViewModel // }); //} private bool LinkLaydToPcs2(Stream stream) => LinkToPcs2(stream, Layout.MagicCodeValidator, 0x1c); private bool LinkSeqdToPcs2(Stream stream) => LinkToPcs2(stream, Sequence.MagicCodeValidator, 0x2c); private bool LinkToPcs2(Stream stream, uint magicCode, int headerLength) { var process = Process.GetProcessesByName("pcsx2").FirstOrDefault(); if (process == null) { ShowLinkPcsx2ErrorProcessNotFound(); return false; } var processStream = new ProcessStream(process, ToolConstants.Pcsx2BaseAddress, ToolConstants.Ps2MemoryLength); var bufferedStream = new BufferedStream(processStream, 0x10000); var header = stream.SetPosition(sizeof(uint)).ReadBytes(headerLength); while (bufferedStream.Position < bufferedStream.Length) { if (bufferedStream.ReadUInt32() == magicCode) { // header matches. Check if the rest of 0x2c SEQD header matches as well... if (header.SequenceEqual(bufferedStream.ReadBytes(headerLength))) { _processStream = processStream; _processOffset = (int)(bufferedStream.Position - headerLength - sizeof(uint)); return true; } } } ShowLinkPcsx2ErrorFileNotFound(); CloseProcessStream(); return false; } private void CloseProcessStream() { _processStream?.Dispose(); _processStream = null; } private static bool DoesContainSequenceAnimations(IEnumerable<Bar.Entry> entries) => entries.Any(x => x.Type == Bar.EntryType.Seqd); private static bool DoesContainLayoutAnimations(IEnumerable<Bar.Entry> entries) => entries.Any(x => x.Type == Bar.EntryType.Layout); private static void ShowLinkPcsx2ErrorProcessNotFound() => ShowError("No PCSX2 process found.\nPlease run PCSX2 with Kingdom Hearts II/Re:CoM first and try again.", LinkToPcsx2ActionName); private static void ShowLinkPcsx2ErrorFileNotFound() => ShowError("The file you specified can not be found on the running game.", LinkToPcsx2ActionName); public static void ShowError(string message, string title = "Error") => MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Error); private void ShowAboutDialog() => MessageBox.Show("OpenKH is amazing."); } }
#region License, Terms and Conditions // // MetadataResult.cs // // Authors: Kori Francis <twitter.com/djbyter>, David Ball // Copyright (C) 2010-2014 Clinical Support Systems, Inc. All rights reserved. // // THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Xml; using ChargifyNET.Json; namespace ChargifyNET { #region Imports #endregion /// <summary> /// An array of Metadata /// </summary> public class MetadataResult : ChargifyBase, IMetadataResult { #region Field Keys private const string TotalCountKey = "total-count"; private const string CurrentPageKey = "current-page"; private const string TotalPagesKey = "total-pages"; private const string PerPageKey = "per-page"; private const string MetadataKey = "metadata"; #endregion #region Constructors /// <summary> /// Constructor /// </summary> public MetadataResult() { } /// <summary> /// Constructor (xml) /// </summary> /// <param name="metadataResultXml"></param> public MetadataResult(string metadataResultXml) { // get the XML into an XML document XmlDocument doc = new XmlDocument(); doc.LoadXml(metadataResultXml); if (doc.ChildNodes.Count == 0) throw new ArgumentException("XML not valid", nameof(metadataResultXml)); // loop through the child nodes of this node foreach (XmlNode elementNode in doc.ChildNodes) { if (elementNode.Name == "results") { LoadFromNode(elementNode); return; } } // if we get here, then no metadata result data was found throw new ArgumentException("XML does not contain metadata result information", nameof(metadataResultXml)); } /// <summary> /// Constructor (xml) /// </summary> /// <param name="metadataResultNode"></param> public MetadataResult(XmlNode metadataResultNode) { if (metadataResultNode == null) throw new ArgumentNullException(nameof(metadataResultNode)); if (metadataResultNode.Name != "results") throw new ArgumentException("Not a vaild metadata results node", nameof(metadataResultNode)); if (metadataResultNode.ChildNodes.Count == 0) throw new ArgumentException("XML not valid", nameof(metadataResultNode)); LoadFromNode(metadataResultNode); } /// <summary> /// Constructor (json) /// </summary> /// <param name="metadataResultObject"></param> public MetadataResult(JsonObject metadataResultObject) { if (metadataResultObject == null) throw new ArgumentNullException(nameof(metadataResultObject)); if (metadataResultObject.Keys.Count <= 0) throw new ArgumentException("Not a vaild metadata results object", nameof(metadataResultObject)); LoadFromJson(metadataResultObject); } private void LoadFromNode(XmlNode parentNode) { foreach (XmlNode dataNode in parentNode.ChildNodes) { switch (dataNode.Name) { case TotalCountKey: _totalCount = dataNode.GetNodeContentAsInt(); break; case CurrentPageKey: _currentPage = dataNode.GetNodeContentAsInt(); break; case TotalPagesKey: _totalPages = dataNode.GetNodeContentAsInt(); break; case PerPageKey: _perPage = dataNode.GetNodeContentAsInt(); break; case MetadataKey: if (dataNode.FirstChild != null) { _metadata = new List<IMetadata>(); // There's no constructor that takes in an XmlNode, so parse it here. foreach (XmlNode metadataNode in dataNode.ChildNodes) { var newObj = new Metadata(); var hasData = false; foreach (XmlNode metadatumNode in metadataNode.ChildNodes) { switch (metadatumNode.Name) { case "resource-id": hasData = true; newObj.ResourceID = metadatumNode.GetNodeContentAsInt(); break; case "name": hasData = true; newObj.Name = metadatumNode.GetNodeContentAsString(); break; case "value": hasData = true; newObj.Value = metadatumNode.GetNodeContentAsString(); break; } } if (hasData) { _metadata.Add(newObj); } } } break; } } } private void LoadFromJson(JsonObject obj) { foreach (string key in obj.Keys) { string theKey = key; if (key.Contains("_")) theKey = key.Replace("_", "-"); // Chargify seems to return different keys based on xml or json return type switch (theKey) { case TotalCountKey: _totalCount = obj.GetJSONContentAsInt(key); break; case CurrentPageKey: _currentPage = obj.GetJSONContentAsInt(key); break; case TotalPagesKey: _totalPages = obj.GetJSONContentAsInt(key); break; case PerPageKey: _perPage = obj.GetJSONContentAsInt(key); break; case MetadataKey: _metadata = new List<IMetadata>(); JsonArray viewObj = obj[key] as JsonArray; if (viewObj?.Items != null && viewObj.Length > 0) { foreach (JsonValue item in viewObj.Items) { var newObj = new Metadata(); var hasData = false; var itemObj = (JsonObject)item; foreach (string subItemKey in itemObj.Keys) { switch (subItemKey) { case "resource_id": hasData = true; newObj.ResourceID = obj.GetJSONContentAsInt(subItemKey); break; case "name": hasData = true; newObj.Name = obj.GetJSONContentAsString(subItemKey); break; case "value": hasData = true; newObj.Value = obj.GetJSONContentAsString(subItemKey); break; } } if (hasData) { _metadata.Add(newObj); } } } break; } } } #endregion #region IMetadataResult Members /// <summary> /// The total number of metadatum /// </summary> public int TotalCount { get { return _totalCount; } } private int _totalCount = int.MinValue; /// <summary> /// The current page being returned /// </summary> public int CurrentPage { get { return _currentPage; } } private int _currentPage = int.MinValue; /// <summary> /// The total number of pages (based on per-page and total count) /// </summary> public int TotalPages { get { return _totalPages; } } private int _totalPages = int.MinValue; /// <summary> /// How many metadata are being returned per paged result /// </summary> public int PerPage { get { return _perPage; } } private int _perPage = int.MinValue; /// <summary> /// The list of metadata contained in this response /// </summary> public List<IMetadata> Metadata { get { return _metadata; } } private List<IMetadata> _metadata = new List<IMetadata>(); #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Xunit; namespace NuGet.Test.NuGetCommandLine { public class CommandManagerTests { [Fact] public void RegisterCommand_AddsCommandToDictionary() { // Arrange CommandManager cm = new CommandManager(); ICommand mockCommand = new MockCommand(); // Act cm.RegisterCommand(mockCommand); // Assert Assert.Equal(1, cm.GetCommands().Count()); } [Fact] public void GetCommand_ThrowsIfNoCommandFound() { // Arrange CommandManager cm = new CommandManager(); // Act and Assert ExceptionAssert.Throws<CommandLineException>(() => cm.GetCommand("NoCommandByThisName"), "Unknown command: 'NoCommandByThisName'"); } [Fact] public void GetCommand_ReturnsCorrectCommand() { // Arrange CommandManager cm = new CommandManager(); ICommand expectedCommand = new MockCommand(); cm.RegisterCommand(expectedCommand); // Act ICommand actualCommand = cm.GetCommand("MockCommand"); // Assert Assert.Equal(expectedCommand, actualCommand); } [Fact] public void GetCommandOptions_ThrowsWhenOptionHasNoSetter() { // Arrange CommandManager cm = new CommandManager(); ICommand cmd = new MockCommandBadOption(); cm.RegisterCommand(cmd); string expectedErrorText = "[option] on 'NuGet.Test.NuGetCommandLine.CommandManagerTests+MockCommandBadOption.Message' is invalid without a setter."; // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => cm.GetCommandOptions(cmd), expectedErrorText); } [Fact] public void GetCommandOptions_ReturnsCorrectOpionAttributeAndPropertyInfo() { // Arrange CommandManager cm = new CommandManager(); ICommand cmd = new MockCommand(); cm.RegisterCommand(cmd); Dictionary<OptionAttribute, PropertyInfo> expected = new Dictionary<OptionAttribute, PropertyInfo>(); var expectedOptionAttributeOne = new OptionAttribute("A Option"); var expectedPropertyInfoOne = typeof(MockCommand).GetProperty("Message"); expected.Add(expectedOptionAttributeOne, expectedPropertyInfoOne); var expectedOptionAttributeTwo = new OptionAttribute("A Option Two"); var expectedPropertyInfoTwo = typeof(MockCommand).GetProperty("MessageTwo"); expected.Add(expectedOptionAttributeTwo, expectedPropertyInfoTwo); // Act IDictionary<OptionAttribute, PropertyInfo> actual = cm.GetCommandOptions(cmd); // Assert Assert.Equal(2, actual.Count); Assert.Equal(expectedOptionAttributeOne, actual.Keys.First()); Assert.Equal(expectedPropertyInfoOne, actual[expectedOptionAttributeOne]); Assert.Equal(expectedOptionAttributeTwo, actual.Keys.Last()); Assert.Equal(expectedPropertyInfoTwo, actual[expectedOptionAttributeTwo]); } [Fact] public void RegisterCommand_DoesNotRegisterCommandIfNoCommandAttributesArePresent() { // Arrange CommandManager cm = new CommandManager(); ICommand cmd = new MockCommandEmptyAttributes(); cm.RegisterCommand(cmd); // Act var registeredCommands = cm.GetCommands(); // Assert Assert.False(registeredCommands.Any()); } [Fact] public void RegisterCommand_ReturnsExactMatchesEvenIfAmbigious() { // Arrange CommandManager cm = new CommandManager(); cm.RegisterCommand(new MockCommand(new CommandAttribute("Foo", "desc"))); cm.RegisterCommand(new MockCommand(new CommandAttribute("FooBar", "desc"))); // Act var result = cm.GetCommand("Foo"); // Assert // If we get this far, we've found 'foo' Assert.NotNull(result); Assert.Equal(result.CommandAttribute.CommandName, "Foo"); } [Fact] public void RegisterCommand_ThrowsIfCommandNamesAreAmbigious() { // Arrange CommandManager cm = new CommandManager(); cm.RegisterCommand(new MockCommand(new CommandAttribute("Foo", "desc"))); cm.RegisterCommand(new MockCommand(new CommandAttribute("FooBar", "desc"))); // Act and Assert ExceptionAssert.Throws<CommandLineException>(() => cm.GetCommand("f"), "Ambiguous command 'f'. Possible values: Foo FooBar."); } private class MockCommand : ICommand { private readonly List<string> _arguments = new List<string>(); private readonly CommandAttribute _attribute; public IList<string> Arguments { get { return _arguments; } } [Option("A Option")] public string Message { get; set; } [Option("A Option Two")] public string MessageTwo { get; set; } public void Execute() { } public MockCommand() : this(new CommandAttribute("MockCommand", "This is a Mock Command")) { } public MockCommand(CommandAttribute attribute) { _attribute = attribute; } public CommandAttribute CommandAttribute { get { return _attribute; } } public IEnumerable<CommandAttribute> GetCommandAttribute() { return new[] { CommandAttribute }; } public bool IncludedInHelp(string optionName) { return true; } } private class MockCommandBadOption : ICommand { private readonly List<string> _arguments = new List<string>(); public IList<string> Arguments { get { return _arguments; } } [Option("A Option")] public string Message { get { return "Bad"; } } public void Execute() { } public CommandAttribute CommandAttribute { get { return new CommandAttribute("MockCommandBadOption", "This is a Mock Command With A Option Without a Setter"); } } public IEnumerable<CommandAttribute> GetCommandAttribute() { return new[] { CommandAttribute }; } public bool IncludedInHelp(string optionName) { return true; } } private class MockCommandEmptyAttributes : ICommand { [Option("A Option")] public string Message { get { return "Bad"; } } public void Execute() { } public IList<string> Arguments { get; set; } public CommandAttribute CommandAttribute { get { return null; } } public IEnumerable<CommandAttribute> GetCommandAttribute() { return Enumerable.Empty<CommandAttribute>(); } public bool IncludedInHelp(string optionName) { return true; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Reflection; using System.Text; using System.Collections.Generic; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim; using OpenSim.Region; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Interfaces; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using Nini.Config; using log4net; using Mono.Addins; using Caps = OpenSim.Framework.Capabilities.Caps; using OSDMap = OpenMetaverse.StructuredData.OSDMap; namespace OpenSim.Region.OptionalModules.ViewerSupport { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DynamicFloater")] public class DynamicFloaterModule : INonSharedRegionModule, IDynamicFloaterModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Scene m_scene; private Dictionary<UUID, Dictionary<int, FloaterData>> m_floaters = new Dictionary<UUID, Dictionary<int, FloaterData>>(); public string Name { get { return "DynamicFloaterModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource config) { } public void Close() { } public void AddRegion(Scene scene) { m_scene = scene; scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnClientClosed += OnClientClosed; m_scene.RegisterModuleInterface<IDynamicFloaterModule>(this); } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { } private void OnNewClient(IClientAPI client) { client.OnChatFromClient += OnChatFromClient; } private void OnClientClosed(UUID agentID, Scene scene) { m_floaters.Remove(agentID); } private void SendToClient(ScenePresence sp, string msg) { sp.ControllingClient.SendChatMessage(msg, (byte)ChatTypeEnum.Owner, sp.AbsolutePosition, "Server", UUID.Zero, UUID.Zero, (byte)ChatSourceType.Object, (byte)ChatAudibleLevel.Fully); } public void DoUserFloater(UUID agentID, FloaterData dialogData, string configuration) { ScenePresence sp = m_scene.GetScenePresence(agentID); if (sp == null || sp.IsChildAgent) return; if (!m_floaters.ContainsKey(agentID)) m_floaters[agentID] = new Dictionary<int, FloaterData>(); if (m_floaters[agentID].ContainsKey(dialogData.Channel)) return; m_floaters[agentID].Add(dialogData.Channel, dialogData); string xml; if (dialogData.XmlText != null && dialogData.XmlText != String.Empty) { xml = dialogData.XmlText; } else { using (FileStream fs = File.Open(dialogData.XmlName + ".xml", FileMode.Open, FileAccess.Read)) { using (StreamReader sr = new StreamReader(fs)) xml = sr.ReadToEnd().Replace("\n", ""); } } List<string> xparts = new List<string>(); while (xml.Length > 0) { string x = xml; if (x.Length > 600) { x = x.Substring(0, 600); xml = xml.Substring(600); } else { xml = String.Empty; } xparts.Add(x); } for (int i = 0 ; i < xparts.Count ; i++) SendToClient(sp, String.Format("># floater {2} create {0}/{1} " + xparts[i], i + 1, xparts.Count, dialogData.FloaterName)); SendToClient(sp, String.Format("># floater {0} {{notify:1}} {{channel: {1}}} {{node:cancel {{notify:1}}}} {{node:ok {{notify:1}}}} {2}", dialogData.FloaterName, (uint)dialogData.Channel, configuration)); } private void OnChatFromClient(object sender, OSChatMessage msg) { if (msg.Sender == null) return; //m_log.DebugFormat("chan {0} msg {1}", msg.Channel, msg.Message); IClientAPI client = msg.Sender; if (!m_floaters.ContainsKey(client.AgentId)) return; string[] parts = msg.Message.Split(new char[] {':'}); if (parts.Length == 0) return; ScenePresence sp = m_scene.GetScenePresence(client.AgentId); if (sp == null || sp.IsChildAgent) return; Dictionary<int, FloaterData> d = m_floaters[client.AgentId]; // Work around a viewer bug - VALUE from any // dialog can appear on this channel and needs to // be dispatched to ALL open dialogs for the user if (msg.Channel == 427169570) { if (parts[0] == "VALUE") { foreach (FloaterData dd in d.Values) { if(dd.Handler(client, dd, parts)) { m_floaters[client.AgentId].Remove(dd.Channel); SendToClient(sp, String.Format("># floater {0} destroy", dd.FloaterName)); break; } } } return; } if (!d.ContainsKey(msg.Channel)) return; FloaterData data = d[msg.Channel]; if (parts[0] == "NOTIFY") { if (parts[1] == "cancel" || parts[1] == data.FloaterName) { m_floaters[client.AgentId].Remove(data.Channel); SendToClient(sp, String.Format("># floater {0} destroy", data.FloaterName)); } } if (data.Handler != null && data.Handler(client, data, parts)) { m_floaters[client.AgentId].Remove(data.Channel); SendToClient(sp, String.Format("># floater {0} destroy", data.FloaterName)); } } public void FloaterControl(ScenePresence sp, FloaterData d, string msg) { string sendData = String.Format("># floater {0} {1}", d.FloaterName, msg); SendToClient(sp, sendData); } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// ItemRevguard /// </summary> [DataContract] public partial class ItemRevguard : IEquatable<ItemRevguard>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ItemRevguard" /> class. /// </summary> /// <param name="revguardCanceledCsrPromptGroup">Canceled CSR prompt group.</param> /// <param name="revguardCanceledIvrPromptGroup">IVR prompt group.</param> /// <param name="revguardCanceledWebPromptGroup">Canceled web prompt group.</param> /// <param name="revguardClientBrand">Client brand.</param> /// <param name="revguardCsrPromptGroup">CSR prompt group.</param> /// <param name="revguardIvrPromptGroup">IVR prompt group.</param> /// <param name="revguardWebPromptGroup">Web prompt group.</param> public ItemRevguard(long? revguardCanceledCsrPromptGroup = default(long?), long? revguardCanceledIvrPromptGroup = default(long?), long? revguardCanceledWebPromptGroup = default(long?), long? revguardClientBrand = default(long?), long? revguardCsrPromptGroup = default(long?), long? revguardIvrPromptGroup = default(long?), long? revguardWebPromptGroup = default(long?)) { this.RevguardCanceledCsrPromptGroup = revguardCanceledCsrPromptGroup; this.RevguardCanceledIvrPromptGroup = revguardCanceledIvrPromptGroup; this.RevguardCanceledWebPromptGroup = revguardCanceledWebPromptGroup; this.RevguardClientBrand = revguardClientBrand; this.RevguardCsrPromptGroup = revguardCsrPromptGroup; this.RevguardIvrPromptGroup = revguardIvrPromptGroup; this.RevguardWebPromptGroup = revguardWebPromptGroup; } /// <summary> /// Canceled CSR prompt group /// </summary> /// <value>Canceled CSR prompt group</value> [DataMember(Name="revguard_canceled_csr_prompt_group", EmitDefaultValue=false)] public long? RevguardCanceledCsrPromptGroup { get; set; } /// <summary> /// IVR prompt group /// </summary> /// <value>IVR prompt group</value> [DataMember(Name="revguard_canceled_ivr_prompt_group", EmitDefaultValue=false)] public long? RevguardCanceledIvrPromptGroup { get; set; } /// <summary> /// Canceled web prompt group /// </summary> /// <value>Canceled web prompt group</value> [DataMember(Name="revguard_canceled_web_prompt_group", EmitDefaultValue=false)] public long? RevguardCanceledWebPromptGroup { get; set; } /// <summary> /// Client brand /// </summary> /// <value>Client brand</value> [DataMember(Name="revguard_client_brand", EmitDefaultValue=false)] public long? RevguardClientBrand { get; set; } /// <summary> /// CSR prompt group /// </summary> /// <value>CSR prompt group</value> [DataMember(Name="revguard_csr_prompt_group", EmitDefaultValue=false)] public long? RevguardCsrPromptGroup { get; set; } /// <summary> /// IVR prompt group /// </summary> /// <value>IVR prompt group</value> [DataMember(Name="revguard_ivr_prompt_group", EmitDefaultValue=false)] public long? RevguardIvrPromptGroup { get; set; } /// <summary> /// Web prompt group /// </summary> /// <value>Web prompt group</value> [DataMember(Name="revguard_web_prompt_group", EmitDefaultValue=false)] public long? RevguardWebPromptGroup { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ItemRevguard {\n"); sb.Append(" RevguardCanceledCsrPromptGroup: ").Append(RevguardCanceledCsrPromptGroup).Append("\n"); sb.Append(" RevguardCanceledIvrPromptGroup: ").Append(RevguardCanceledIvrPromptGroup).Append("\n"); sb.Append(" RevguardCanceledWebPromptGroup: ").Append(RevguardCanceledWebPromptGroup).Append("\n"); sb.Append(" RevguardClientBrand: ").Append(RevguardClientBrand).Append("\n"); sb.Append(" RevguardCsrPromptGroup: ").Append(RevguardCsrPromptGroup).Append("\n"); sb.Append(" RevguardIvrPromptGroup: ").Append(RevguardIvrPromptGroup).Append("\n"); sb.Append(" RevguardWebPromptGroup: ").Append(RevguardWebPromptGroup).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ItemRevguard); } /// <summary> /// Returns true if ItemRevguard instances are equal /// </summary> /// <param name="input">Instance of ItemRevguard to be compared</param> /// <returns>Boolean</returns> public bool Equals(ItemRevguard input) { if (input == null) return false; return ( this.RevguardCanceledCsrPromptGroup == input.RevguardCanceledCsrPromptGroup || (this.RevguardCanceledCsrPromptGroup != null && this.RevguardCanceledCsrPromptGroup.Equals(input.RevguardCanceledCsrPromptGroup)) ) && ( this.RevguardCanceledIvrPromptGroup == input.RevguardCanceledIvrPromptGroup || (this.RevguardCanceledIvrPromptGroup != null && this.RevguardCanceledIvrPromptGroup.Equals(input.RevguardCanceledIvrPromptGroup)) ) && ( this.RevguardCanceledWebPromptGroup == input.RevguardCanceledWebPromptGroup || (this.RevguardCanceledWebPromptGroup != null && this.RevguardCanceledWebPromptGroup.Equals(input.RevguardCanceledWebPromptGroup)) ) && ( this.RevguardClientBrand == input.RevguardClientBrand || (this.RevguardClientBrand != null && this.RevguardClientBrand.Equals(input.RevguardClientBrand)) ) && ( this.RevguardCsrPromptGroup == input.RevguardCsrPromptGroup || (this.RevguardCsrPromptGroup != null && this.RevguardCsrPromptGroup.Equals(input.RevguardCsrPromptGroup)) ) && ( this.RevguardIvrPromptGroup == input.RevguardIvrPromptGroup || (this.RevguardIvrPromptGroup != null && this.RevguardIvrPromptGroup.Equals(input.RevguardIvrPromptGroup)) ) && ( this.RevguardWebPromptGroup == input.RevguardWebPromptGroup || (this.RevguardWebPromptGroup != null && this.RevguardWebPromptGroup.Equals(input.RevguardWebPromptGroup)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.RevguardCanceledCsrPromptGroup != null) hashCode = hashCode * 59 + this.RevguardCanceledCsrPromptGroup.GetHashCode(); if (this.RevguardCanceledIvrPromptGroup != null) hashCode = hashCode * 59 + this.RevguardCanceledIvrPromptGroup.GetHashCode(); if (this.RevguardCanceledWebPromptGroup != null) hashCode = hashCode * 59 + this.RevguardCanceledWebPromptGroup.GetHashCode(); if (this.RevguardClientBrand != null) hashCode = hashCode * 59 + this.RevguardClientBrand.GetHashCode(); if (this.RevguardCsrPromptGroup != null) hashCode = hashCode * 59 + this.RevguardCsrPromptGroup.GetHashCode(); if (this.RevguardIvrPromptGroup != null) hashCode = hashCode * 59 + this.RevguardIvrPromptGroup.GetHashCode(); if (this.RevguardWebPromptGroup != null) hashCode = hashCode * 59 + this.RevguardWebPromptGroup.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
namespace MyMarket.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class InitialCreate : DbMigration { public override void Up() { CreateTable( "dbo.Ads", c => new { Id = c.Int(nullable: false, identity: true), Title = c.String(nullable: false, maxLength: 250), Description = c.String(nullable: false), MainImageId = c.Int(), Price = c.Decimal(nullable: false, precision: 18, scale: 2), UserId = c.String(maxLength: 128), CategoryId = c.Int(nullable: false), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Categories", t => t.CategoryId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .ForeignKey("dbo.Images", t => t.MainImageId) .Index(t => t.MainImageId) .Index(t => t.UserId) .Index(t => t.CategoryId) .Index(t => t.IsDeleted); CreateTable( "dbo.Categories", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 250), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true) .Index(t => t.IsDeleted); CreateTable( "dbo.Comments", c => new { Id = c.Int(nullable: false, identity: true), Content = c.String(nullable: false), AdId = c.Int(nullable: false), UserId = c.String(maxLength: 128), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Ads", t => t.AdId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.AdId) .Index(t => t.UserId) .Index(t => t.IsDeleted); CreateTable( "dbo.AspNetUsers", c => new { Id = c.String(nullable: false, maxLength: 128), ProfilePicture = c.Binary(), FirstName = c.String(maxLength: 250), LastName = c.String(maxLength: 250), DateOfBirth = c.DateTime(), Gender = c.Int(nullable: false), Nationality = c.String(), FullAddress = c.String(), LastLogin = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), LastLogout = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), Email = c.String(maxLength: 256), EmailConfirmed = c.Boolean(nullable: false), PasswordHash = c.String(), SecurityStamp = c.String(), PhoneNumber = c.String(), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEndDateUtc = c.DateTime(), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.String(nullable: false, maxLength: 128), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.Feedbacks", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 250), Email = c.String(maxLength: 250), Content = c.String(nullable: false), UserId = c.String(maxLength: 128), IsFixed = c.Boolean(nullable: false), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId) .Index(t => t.IsDeleted); CreateTable( "dbo.Flags", c => new { Id = c.Int(nullable: false, identity: true), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), AdId = c.Int(nullable: false), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Ads", t => t.AdId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.AdId) .Index(t => t.UserId); CreateTable( "dbo.Likes", c => new { Id = c.Int(nullable: false, identity: true), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), AdId = c.Int(nullable: false), UserId = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Ads", t => t.AdId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.AdId) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 128), UserId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.String(nullable: false, maxLength: 128), RoleId = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.Visits", c => new { Id = c.Int(nullable: false, identity: true), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), AdId = c.Int(nullable: false), UserId = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Ads", t => t.AdId, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.AdId) .Index(t => t.UserId); CreateTable( "dbo.Images", c => new { Id = c.Int(nullable: false, identity: true), AdId = c.Int(), OriginalFileName = c.String(nullable: false, maxLength: 255), FileExtension = c.String(nullable: false, maxLength: 4), UrlPath = c.String(), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Ads", t => t.AdId) .Index(t => t.AdId) .Index(t => t.IsDeleted); CreateTable( "dbo.Cities", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 250), CountryId = c.Int(nullable: false), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Countries", t => t.CountryId, cascadeDelete: true) .Index(t => t.Name, unique: true) .Index(t => t.CountryId) .Index(t => t.IsDeleted); CreateTable( "dbo.Countries", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 250), CreatedOn = c.DateTime(nullable: false), ModifiedOn = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeletedOn = c.DateTime(), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true) .Index(t => t.IsDeleted); CreateTable( "dbo.AspNetRoles", c => new { Id = c.String(nullable: false, maxLength: 128), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.Cities", "CountryId", "dbo.Countries"); DropForeignKey("dbo.Ads", "MainImageId", "dbo.Images"); DropForeignKey("dbo.Images", "AdId", "dbo.Ads"); DropForeignKey("dbo.Visits", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Visits", "AdId", "dbo.Ads"); DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Likes", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Likes", "AdId", "dbo.Ads"); DropForeignKey("dbo.Flags", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Flags", "AdId", "dbo.Ads"); DropForeignKey("dbo.Feedbacks", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Comments", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Ads", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Comments", "AdId", "dbo.Ads"); DropForeignKey("dbo.Ads", "CategoryId", "dbo.Categories"); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.Countries", new[] { "IsDeleted" }); DropIndex("dbo.Countries", new[] { "Name" }); DropIndex("dbo.Cities", new[] { "IsDeleted" }); DropIndex("dbo.Cities", new[] { "CountryId" }); DropIndex("dbo.Cities", new[] { "Name" }); DropIndex("dbo.Images", new[] { "IsDeleted" }); DropIndex("dbo.Images", new[] { "AdId" }); DropIndex("dbo.Visits", new[] { "UserId" }); DropIndex("dbo.Visits", new[] { "AdId" }); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropIndex("dbo.Likes", new[] { "UserId" }); DropIndex("dbo.Likes", new[] { "AdId" }); DropIndex("dbo.Flags", new[] { "UserId" }); DropIndex("dbo.Flags", new[] { "AdId" }); DropIndex("dbo.Feedbacks", new[] { "IsDeleted" }); DropIndex("dbo.Feedbacks", new[] { "UserId" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.Comments", new[] { "IsDeleted" }); DropIndex("dbo.Comments", new[] { "UserId" }); DropIndex("dbo.Comments", new[] { "AdId" }); DropIndex("dbo.Categories", new[] { "IsDeleted" }); DropIndex("dbo.Categories", new[] { "Name" }); DropIndex("dbo.Ads", new[] { "IsDeleted" }); DropIndex("dbo.Ads", new[] { "CategoryId" }); DropIndex("dbo.Ads", new[] { "UserId" }); DropIndex("dbo.Ads", new[] { "MainImageId" }); DropTable("dbo.AspNetRoles"); DropTable("dbo.Countries"); DropTable("dbo.Cities"); DropTable("dbo.Images"); DropTable("dbo.Visits"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.Likes"); DropTable("dbo.Flags"); DropTable("dbo.Feedbacks"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.Comments"); DropTable("dbo.Categories"); DropTable("dbo.Ads"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Xe.IO; namespace OpenKh.Kh1 { public class Img1 : IDisposable { public const int IsoBlockAlign = 0x800; private readonly Stream _stream; private readonly int _firstBlock; public Dictionary<string, Idx1> Entries { get; } public Img1(Stream stream, IEnumerable<Idx1> idxEntries, int firstBlock) { _stream = stream; _firstBlock = firstBlock; Entries = Idx1Name.Lookup(idxEntries).ToDictionary(x => x.Name ?? $"@noname/{x.Entry.Hash:X08}", x => x.Entry); } public void Dispose() => _stream.Dispose(); public bool FileExists(string fileName) => Entries.ContainsKey(fileName); public bool TryFileOpen(string fileName, out Stream stream) { if (Entries.TryGetValue(fileName, out var entry)) { stream = FileOpen(entry); return true; } stream = null; return false; } public bool FileOpen(string fileName, Action<Stream> callback) { bool result; if (result = Entries.TryGetValue(fileName, out var entry)) callback(FileOpen(entry)); return result; } public Stream FileOpen(string fileName) { if (Entries.TryGetValue(fileName, out var entry)) return FileOpen(entry); throw new FileNotFoundException("File not found", fileName); } public Stream FileOpen(Idx1 entry) { if (entry.CompressionFlag != 0) { var fileStream = new SubStream(_stream, (_firstBlock + entry.IsoBlock) * IsoBlockAlign, entry.Length); return new MemoryStream(Decompress(fileStream)); } return new SubStream(_stream, (_firstBlock + entry.IsoBlock) * IsoBlockAlign, entry.Length); } public static byte[] Decompress(Stream src) { return Decompress(new BinaryReader(src).ReadBytes((int)src.Length)); } public static byte[] Decompress(byte[] srcData) { var srcIndex = srcData.Length - 1; if (srcIndex == 0) return Array.Empty<byte>(); var key = srcData[srcIndex--]; var decSize = srcData[srcIndex--] | (srcData[srcIndex--] << 8) | (srcData[srcIndex--] << 16); int dstIndex = decSize - 1; var dstData = new byte[decSize]; while (dstIndex >= 0 && srcIndex >= 0) { var data = srcData[srcIndex--]; if (data == key && srcIndex >= 0) { var copyIndex = srcData[srcIndex--]; if (copyIndex > 0 && srcIndex >= 0) { var copyLength = srcData[srcIndex--]; for (int i = 0; i < copyLength + 3 && dstIndex >= 0; i++) { if (dstIndex + copyIndex + 1 < dstData.Length) dstData[dstIndex--] = dstData[dstIndex + copyIndex + 1]; else dstData[dstIndex--] = 0; } } else { dstData[dstIndex--] = data; } } else { dstData[dstIndex--] = data; } } return dstData; } public static byte[] Compress(byte[] srcData) { const int MaxWindowSize = 0x102; const int MaxSlidingIndex = 0xff; var decompressedLength = srcData.Length; var key = GetLeastUsedByte(srcData); var buffer = new List<byte>(decompressedLength); buffer.Add(key); buffer.Add((byte)(decompressedLength >> 0)); buffer.Add((byte)(decompressedLength >> 8)); buffer.Add((byte)(decompressedLength >> 16)); int sourceIndex = decompressedLength - 1; while (sourceIndex >= 0) { var ch = srcData[sourceIndex]; if (ch == key) { buffer.Add(key); buffer.Add(0); sourceIndex--; continue; } var windowSizeCandidate = 0; var slidingIndexCandidate = -1; var maxWindowSize = Math.Min(sourceIndex, MaxWindowSize); for (var slidingIndex = MaxSlidingIndex; slidingIndex > 0; slidingIndex--) { if (slidingIndex + sourceIndex >= decompressedLength) continue; int windowSize; for (windowSize = 0; windowSize < maxWindowSize; windowSize++) { var startWindow = sourceIndex + slidingIndex - windowSize; if (srcData[startWindow] != srcData[sourceIndex - windowSize]) break; } if (windowSize > windowSizeCandidate) { windowSizeCandidate = windowSize; slidingIndexCandidate = slidingIndex; } } if (windowSizeCandidate > 3) { buffer.Add(key); buffer.Add((byte)slidingIndexCandidate); buffer.Add((byte)(windowSizeCandidate - 3)); sourceIndex -= windowSizeCandidate; } else { buffer.Add(ch); sourceIndex--; } } var compressedLength = buffer.Count; var cmp = new byte[compressedLength]; for (var i = 0; i < compressedLength; i++) { cmp[i] = buffer[compressedLength - i - 1]; } return cmp; } private static byte GetLeastUsedByte(byte[] data) { var dictionary = new int[0x100]; foreach (var ch in data) dictionary[ch]++; var elementFound = int.MaxValue; var indexFound = 1; // the least used byte is never zero for (var i = 0; i < 0x100; i++) { if (dictionary[i] < elementFound) { elementFound = dictionary[i]; indexFound = i; } } return (byte)indexFound; } } }
using ClosedXML.Excel.CalcEngine.Functions; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace ClosedXML.Excel.CalcEngine { /// <summary> /// CalcEngine parses strings and returns Expression objects that can /// be evaluated. /// </summary> /// <remarks> /// <para>This class has three extensibility points:</para> /// <para>Use the <b>DataContext</b> property to add an object's properties to the engine scope.</para> /// <para>Use the <b>RegisterFunction</b> method to define custom functions.</para> /// <para>Override the <b>GetExternalObject</b> method to add arbitrary variables to the engine scope.</para> /// </remarks> internal class CalcEngine { //--------------------------------------------------------------------------- #region ** fields // members private string _expr; // expression being parsed private int _len; // length of the expression being parsed private int _ptr; // current pointer into expression private char[] _idChars; // valid characters in identifiers (besides alpha and digits) private Token _token; // current token being parsed private Dictionary<object, Token> _tkTbl; // table with tokens (+, -, etc) private Dictionary<string, FunctionDefinition> _fnTbl; // table with constants and functions (pi, sin, etc) private Dictionary<string, object> _vars; // table with variables private object _dataContext; // object with properties private bool _optimize; // optimize expressions when parsing private ExpressionCache _cache; // cache with parsed expressions private CultureInfo _ci; // culture info used to parse numbers/dates private char _decimal, _listSep, _percent; // localized decimal separator, list separator, percent sign #endregion ** fields //--------------------------------------------------------------------------- #region ** ctor public CalcEngine() { CultureInfo = CultureInfo.InvariantCulture; _tkTbl = GetSymbolTable(); _fnTbl = GetFunctionTable(); _vars = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); _cache = new ExpressionCache(this); _optimize = true; #if DEBUG //this.Test(); #endif } #endregion ** ctor //--------------------------------------------------------------------------- #region ** object model /// <summary> /// Parses a string into an <see cref="Expression"/>. /// </summary> /// <param name="expression">String to parse.</param> /// <returns>An <see cref="Expression"/> object that can be evaluated.</returns> public Expression Parse(string expression) { // initialize _expr = expression; _len = _expr.Length; _ptr = 0; // skip leading equals sign if (_len > 0 && _expr[0] == '=') _ptr++; // skip leading +'s while (_len > _ptr && _expr[_ptr] == '+') _ptr++; // parse the expression var expr = ParseExpression(); // check for errors if (_token.ID == TKID.OPEN) Throw("Unknown function: " + expr.LastParseItem); else if (_token.ID != TKID.END) Throw("Expected end of expression"); // optimize expression if (_optimize) { expr = expr.Optimize(); } // done return expr; } /// <summary> /// Evaluates a string. /// </summary> /// <param name="expression">Expression to evaluate.</param> /// <returns>The value of the expression.</returns> /// <remarks> /// If you are going to evaluate the same expression several times, /// it is more efficient to parse it only once using the <see cref="Parse"/> /// method and then using the Expression.Evaluate method to evaluate /// the parsed expression. /// </remarks> public object Evaluate(string expression) { var x = _cache != null ? _cache[expression] : Parse(expression); return x.Evaluate(); } /// <summary> /// Gets or sets whether the calc engine should keep a cache with parsed /// expressions. /// </summary> public bool CacheExpressions { get { return _cache != null; } set { if (value != CacheExpressions) { _cache = value ? new ExpressionCache(this) : null; } } } /// <summary> /// Gets or sets whether the calc engine should optimize expressions when /// they are parsed. /// </summary> public bool OptimizeExpressions { get { return _optimize; } set { _optimize = value; } } /// <summary> /// Gets or sets a string that specifies special characters that are valid for identifiers. /// </summary> /// <remarks> /// Identifiers must start with a letter or an underscore, which may be followed by /// additional letters, underscores, or digits. This string allows you to specify /// additional valid characters such as ':' or '!' (used in Excel range references /// for example). /// </remarks> public char[] IdentifierChars { get { return _idChars; } set { _idChars = value; } } /// <summary> /// Registers a function that can be evaluated by this <see cref="CalcEngine"/>. /// </summary> /// <param name="functionName">Function name.</param> /// <param name="parmMin">Minimum parameter count.</param> /// <param name="parmMax">Maximum parameter count.</param> /// <param name="fn">Delegate that evaluates the function.</param> public void RegisterFunction(string functionName, int parmMin, int parmMax, CalcEngineFunction fn) { _fnTbl.Add(functionName, new FunctionDefinition(parmMin, parmMax, fn)); } /// <summary> /// Registers a function that can be evaluated by this <see cref="CalcEngine"/>. /// </summary> /// <param name="functionName">Function name.</param> /// <param name="parmCount">Parameter count.</param> /// <param name="fn">Delegate that evaluates the function.</param> public void RegisterFunction(string functionName, int parmCount, CalcEngineFunction fn) { RegisterFunction(functionName, parmCount, parmCount, fn); } /// <summary> /// Gets an external object based on an identifier. /// </summary> /// <remarks> /// This method is useful when the engine needs to create objects dynamically. /// For example, a spreadsheet calc engine would use this method to dynamically create cell /// range objects based on identifiers that cannot be enumerated at design time /// (such as "AB12", "A1:AB12", etc.) /// </remarks> public virtual object GetExternalObject(string identifier) { return null; } /// <summary> /// Gets or sets the DataContext for this <see cref="CalcEngine"/>. /// </summary> /// <remarks> /// Once a DataContext is set, all public properties of the object become available /// to the CalcEngine, including sub-properties such as "Address.Street". These may /// be used with expressions just like any other constant. /// </remarks> public virtual object DataContext { get { return _dataContext; } set { _dataContext = value; } } /// <summary> /// Gets the dictionary that contains function definitions. /// </summary> public Dictionary<string, FunctionDefinition> Functions { get { return _fnTbl; } } /// <summary> /// Gets the dictionary that contains simple variables (not in the DataContext). /// </summary> public Dictionary<string, object> Variables { get { return _vars; } } /// <summary> /// Gets or sets the <see cref="CultureInfo"/> to use when parsing numbers and dates. /// </summary> public CultureInfo CultureInfo { get { return _ci; } set { _ci = value; var nf = _ci.NumberFormat; _decimal = nf.NumberDecimalSeparator[0]; _percent = nf.PercentSymbol[0]; _listSep = _ci.TextInfo.ListSeparator[0]; } } #endregion ** object model //--------------------------------------------------------------------------- #region ** token/keyword tables private static readonly IDictionary<string, ErrorExpression.ExpressionErrorType> ErrorMap = new Dictionary<string, ErrorExpression.ExpressionErrorType>() { ["#REF!"] = ErrorExpression.ExpressionErrorType.CellReference, ["#VALUE!"] = ErrorExpression.ExpressionErrorType.CellValue, ["#DIV/0!"] = ErrorExpression.ExpressionErrorType.DivisionByZero, ["#NAME?"] = ErrorExpression.ExpressionErrorType.NameNotRecognized, ["#N/A"] = ErrorExpression.ExpressionErrorType.NoValueAvailable, ["#NULL!"] = ErrorExpression.ExpressionErrorType.NullValue, ["#NUM!"] = ErrorExpression.ExpressionErrorType.NumberInvalid }; // build/get static token table private Dictionary<object, Token> GetSymbolTable() { if (_tkTbl == null) { _tkTbl = new Dictionary<object, Token>(); AddToken('&', TKID.CONCAT, TKTYPE.ADDSUB); AddToken('+', TKID.ADD, TKTYPE.ADDSUB); AddToken('-', TKID.SUB, TKTYPE.ADDSUB); AddToken('(', TKID.OPEN, TKTYPE.GROUP); AddToken(')', TKID.CLOSE, TKTYPE.GROUP); AddToken('*', TKID.MUL, TKTYPE.MULDIV); AddToken('.', TKID.PERIOD, TKTYPE.GROUP); AddToken('/', TKID.DIV, TKTYPE.MULDIV); AddToken('\\', TKID.DIVINT, TKTYPE.MULDIV); AddToken('=', TKID.EQ, TKTYPE.COMPARE); AddToken('>', TKID.GT, TKTYPE.COMPARE); AddToken('<', TKID.LT, TKTYPE.COMPARE); AddToken('^', TKID.POWER, TKTYPE.POWER); AddToken("<>", TKID.NE, TKTYPE.COMPARE); AddToken(">=", TKID.GE, TKTYPE.COMPARE); AddToken("<=", TKID.LE, TKTYPE.COMPARE); // list separator is localized, not necessarily a comma // so it can't be on the static table //AddToken(',', TKID.COMMA, TKTYPE.GROUP); } return _tkTbl; } private void AddToken(object symbol, TKID id, TKTYPE type) { var token = new Token(symbol, id, type); _tkTbl.Add(symbol, token); } // build/get static keyword table private Dictionary<string, FunctionDefinition> GetFunctionTable() { if (_fnTbl == null) { // create table _fnTbl = new Dictionary<string, FunctionDefinition>(StringComparer.InvariantCultureIgnoreCase); // register built-in functions (and constants) Information.Register(this); Logical.Register(this); Lookup.Register(this); MathTrig.Register(this); Text.Register(this); Statistical.Register(this); DateAndTime.Register(this); } return _fnTbl; } #endregion ** token/keyword tables //--------------------------------------------------------------------------- #region ** private stuff private Expression ParseExpression() { GetToken(); return ParseCompare(); } private Expression ParseCompare() { var x = ParseAddSub(); while (_token.Type == TKTYPE.COMPARE) { var t = _token; GetToken(); var exprArg = ParseAddSub(); x = new BinaryExpression(t, x, exprArg); } return x; } private Expression ParseAddSub() { var x = ParseMulDiv(); while (_token.Type == TKTYPE.ADDSUB) { var t = _token; GetToken(); var exprArg = ParseMulDiv(); x = new BinaryExpression(t, x, exprArg); } return x; } private Expression ParseMulDiv() { var x = ParsePower(); while (_token.Type == TKTYPE.MULDIV) { var t = _token; GetToken(); var a = ParsePower(); x = new BinaryExpression(t, x, a); } return x; } private Expression ParsePower() { var x = ParseUnary(); while (_token.Type == TKTYPE.POWER) { var t = _token; GetToken(); var a = ParseUnary(); x = new BinaryExpression(t, x, a); } return x; } private Expression ParseUnary() { // unary plus and minus if (_token.ID == TKID.ADD || _token.ID == TKID.SUB) { var t = _token; GetToken(); var a = ParseAtom(); return new UnaryExpression(t, a); } // not unary, return atom return ParseAtom(); } private Expression ParseAtom() { string id; Expression x = null; switch (_token.Type) { // literals case TKTYPE.LITERAL: x = new Expression(_token); break; // identifiers case TKTYPE.IDENTIFIER: // get identifier id = (string)_token.Value; // look for functions if (_fnTbl.TryGetValue(id, out FunctionDefinition fnDef)) { var p = GetParameters(); var pCnt = p == null ? 0 : p.Count; if (fnDef.ParmMin != -1 && pCnt < fnDef.ParmMin) { Throw(string.Format("Too few parameters for function '{0}'. Expected a minimum of {1} and a maximum of {2}.", id, fnDef.ParmMin, fnDef.ParmMax)); } if (fnDef.ParmMax != -1 && pCnt > fnDef.ParmMax) { Throw(string.Format("Too many parameters for function '{0}'.Expected a minimum of {1} and a maximum of {2}.", id, fnDef.ParmMin, fnDef.ParmMax)); } x = new FunctionExpression(fnDef, p); break; } // look for simple variables (much faster than binding!) if (_vars.ContainsKey(id)) { x = new VariableExpression(_vars, id); break; } // look for external objects var xObj = GetExternalObject(id); if (xObj != null) { x = new XObjectExpression(xObj); break; } Throw("Unexpected identifier"); break; // sub-expressions case TKTYPE.GROUP: // Normally anything other than opening parenthesis is illegal here // but Excel allows omitted parameters so return empty value expression. if (_token.ID != TKID.OPEN) { return new EmptyValueExpression(); } // get expression GetToken(); x = ParseCompare(); // check that the parenthesis was closed if (_token.ID != TKID.CLOSE) { Throw("Unbalanced parenthesis."); } break; case TKTYPE.ERROR: x = new ErrorExpression((ErrorExpression.ExpressionErrorType)_token.Value); break; } // make sure we got something... if (x == null) { Throw(); } // done GetToken(); return x; } #endregion ** private stuff //--------------------------------------------------------------------------- #region ** parser private static IDictionary<char, char> matchingClosingSymbols = new Dictionary<char, char>() { { '\'', '\'' }, { '[', ']' } }; private void GetToken() { // eat white space while (_ptr < _len && _expr[_ptr] <= ' ') { _ptr++; } // are we done? if (_ptr >= _len) { _token = new Token(null, TKID.END, TKTYPE.GROUP); return; } // prepare to parse int i; var c = _expr[_ptr]; // operators // this gets called a lot, so it's pretty optimized. // note that operators must start with non-letter/digit characters. var isLetter = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); var isDigit = c >= '0' && c <= '9'; var isEnclosed = matchingClosingSymbols.Keys.Contains(c); char matchingClosingSymbol = '\0'; if (isEnclosed) matchingClosingSymbol = matchingClosingSymbols[c]; if (!isLetter && !isDigit && !isEnclosed) { // if this is a number starting with a decimal, don't parse as operator var nxt = _ptr + 1 < _len ? _expr[_ptr + 1] : 0; bool isNumber = c == _decimal && nxt >= '0' && nxt <= '9'; if (!isNumber) { // look up localized list separator if (c == _listSep) { _token = new Token(c, TKID.COMMA, TKTYPE.GROUP); _ptr++; return; } // look up single-char tokens on table if (_tkTbl.TryGetValue(c, out Token tk)) { // save token we found _token = tk; _ptr++; // look for double-char tokens (special case) if (_ptr < _len && (c == '>' || c == '<') && _tkTbl.TryGetValue(_expr.Substring(_ptr - 1, 2), out tk)) { _token = tk; _ptr++; } // found token on the table return; } } } // parse numbers if (isDigit || c == _decimal) { var sci = false; var pct = false; var div = -1.0; // use double, not int (this may get really big) var val = 0.0; for (i = 0; i + _ptr < _len; i++) { c = _expr[_ptr + i]; // digits always OK if (c >= '0' && c <= '9') { val = val * 10 + (c - '0'); if (div > -1) { div *= 10; } continue; } // one decimal is OK if (c == _decimal && div < 0) { div = 1; continue; } // scientific notation? if ((c == 'E' || c == 'e') && !sci) { sci = true; c = _expr[_ptr + i + 1]; if (c == '+' || c == '-') i++; continue; } // percentage? if (c == _percent) { pct = true; i++; break; } // end of literal break; } // end of number, get value if (!sci) { // much faster than ParseDouble if (div > 1) { val /= div; } if (pct) { val /= 100.0; } } else { var lit = _expr.Substring(_ptr, i); val = ParseDouble(lit, _ci); } if (c != ':') { // build token _token = new Token(val, TKID.ATOM, TKTYPE.LITERAL); // advance pointer and return _ptr += i; return; } } // parse strings if (c == '\"') { // look for end quote, skip double quotes for (i = 1; i + _ptr < _len; i++) { c = _expr[_ptr + i]; if (c != '\"') continue; char cNext = i + _ptr < _len - 1 ? _expr[_ptr + i + 1] : ' '; if (cNext != '\"') break; i++; } // check that we got the end of the string if (c != '\"') { Throw("Can't find final quote."); } // end of string var lit = _expr.Substring(_ptr + 1, i - 1); _ptr += i + 1; _token = new Token(lit.Replace("\"\"", "\""), TKID.ATOM, TKTYPE.LITERAL); return; } // parse #REF! (and other errors) in formula if (c == '#' && ErrorMap.Any(pair => _len > _ptr + pair.Key.Length && _expr.Substring(_ptr, pair.Key.Length).Equals(pair.Key, StringComparison.OrdinalIgnoreCase))) { var errorPair = ErrorMap.Single(pair => _len > _ptr + pair.Key.Length && _expr.Substring(_ptr, pair.Key.Length).Equals(pair.Key, StringComparison.OrdinalIgnoreCase)); _ptr += errorPair.Key.Length; _token = new Token(errorPair.Value, TKID.ATOM, TKTYPE.ERROR); return; } // identifiers (functions, objects) must start with alpha or underscore if (!isEnclosed && !isLetter && c != '_' && (_idChars == null || !_idChars.Contains(c))) { Throw("Identifier expected."); } // and must contain only letters/digits/_idChars for (i = 1; i + _ptr < _len; i++) { c = _expr[_ptr + i]; isLetter = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); isDigit = c >= '0' && c <= '9'; if (isEnclosed && c == matchingClosingSymbol) { isEnclosed = false; matchingClosingSymbol = '\0'; i++; c = _expr[_ptr + i]; isLetter = (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); isDigit = c >= '0' && c <= '9'; } var disallowedSymbols = new List<char>() { '\\', '/', '*', '[', ':', '?' }; if (isEnclosed && disallowedSymbols.Contains(c)) break; var allowedSymbols = new List<char>() { '_', '.' }; if (!isLetter && !isDigit && !(isEnclosed || allowedSymbols.Contains(c)) && (_idChars == null || !_idChars.Contains(c))) break; } // got identifier var id = _expr.Substring(_ptr, i); _ptr += i; _token = new Token(id, TKID.ATOM, TKTYPE.IDENTIFIER); } private static double ParseDouble(string str, CultureInfo ci) { if (str.Length > 0 && str[str.Length - 1] == ci.NumberFormat.PercentSymbol[0]) { str = str.Substring(0, str.Length - 1); return double.Parse(str, NumberStyles.Any, ci) / 100.0; } return double.Parse(str, NumberStyles.Any, ci); } private List<Expression> GetParameters() // e.g. myfun(a, b, c+2) { // check whether next token is a (, // restore state and bail if it's not var pos = _ptr; var tk = _token; GetToken(); if (_token.ID != TKID.OPEN) { _ptr = pos; _token = tk; return null; } // check for empty Parameter list pos = _ptr; GetToken(); if (_token.ID == TKID.CLOSE) { return null; } _ptr = pos; // get Parameters until we reach the end of the list var parms = new List<Expression>(); var expr = ParseExpression(); parms.Add(expr); while (_token.ID == TKID.COMMA) { expr = ParseExpression(); parms.Add(expr); } // make sure the list was closed correctly if (_token.ID == TKID.OPEN) Throw("Unknown function: " + expr.LastParseItem); else if (_token.ID != TKID.CLOSE) Throw("Syntax error: expected ')'"); // done return parms; } private Token GetMember() { // check whether next token is a MEMBER token ('.'), // restore state and bail if it's not var pos = _ptr; var tk = _token; GetToken(); if (_token.ID != TKID.PERIOD) { _ptr = pos; _token = tk; return null; } // skip member token GetToken(); if (_token.Type != TKTYPE.IDENTIFIER) { Throw("Identifier expected"); } return _token; } #endregion ** parser //--------------------------------------------------------------------------- #region ** static helpers private static void Throw() { Throw("Syntax error."); } private static void Throw(string msg) { throw new ExpressionParseException(msg); } #endregion ** static helpers } /// <summary> /// Delegate that represents CalcEngine functions. /// </summary> /// <param name="parms">List of <see cref="Expression"/> objects that represent the /// parameters to be used in the function call.</param> /// <returns>The function result.</returns> internal delegate object CalcEngineFunction(List<Expression> parms); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace TestLibrary { public static class Generator { internal static Random m_rand = new Random(); internal static int? seed = null; public static int? Seed { get { if (seed.HasValue) { return seed.Value; } else { return null; } } set { if (!(seed.HasValue)) { seed = value; if (seed.HasValue) { TestFramework.LogVerbose("Seeding Random with: " + seed.Value.ToString()); m_rand = new Random(seed.Value); } } else { TestFramework.LogVerbose("Attempt to seed Random to " + value.ToString() + " rejected it was already seeded to: " + seed.Value.ToString()); } } } // returns a byte array of random data public static void GetBytes(int new_seed, byte[] buffer) { Seed = new_seed; GetBytes(buffer); } public static void GetBytes(byte[] buffer) { m_rand.NextBytes(buffer); TestFramework.LogVerbose("Random Byte[] produced: " + Utilities.ByteArrayToString(buffer)); } // returns a non-negative Int64 between 0 and Int64.MaxValue public static Int64 GetInt64(Int32 new_seed) { Seed = new_seed; return GetInt64(); } public static Int64 GetInt64() { byte[] buffer = new byte[8]; Int64 iVal; GetBytes(buffer); // convert to Int64 iVal = 0; for (int i = 0; i < buffer.Length; i++) { iVal |= ((Int64)buffer[i] << (i * 8)); } if (0 > iVal) iVal *= -1; TestFramework.LogVerbose("Random Int64 produced: " + iVal.ToString()); return iVal; } // returns a UInt64 between 0 and UInt64.MaxValue public static UInt64 GetUInt64(Int32 new_seed) { Seed = new_seed; return GetUInt64(); } public static UInt64 GetUInt64() { byte[] buffer = new byte[8]; UInt64 iVal; GetBytes(buffer); // convert to UInt64 iVal = 0; for (int i = 0; i < buffer.Length; i++) { iVal |= ((UInt64)buffer[i] << (i * 8)); } TestFramework.LogVerbose("Random UInt64 produced: " + iVal.ToString()); return iVal; } // returns a non-negative Int32 between 0 and Int32.MaxValue public static Int32 GetInt32(Int32 new_seed) { Seed = new_seed; return GetInt32(); } public static Int32 GetInt32() { Int32 i = m_rand.Next(); TestFramework.LogVerbose("Random Int32 produced: " + i.ToString()); return i; } // returns a UInt32 between 0 and UInt32.MaxValue public static UInt32 GetUInt32(Int32 new_seed) { Seed = new_seed; return GetUInt32(); } public static UInt32 GetUInt32() { byte[] buffer = new byte[4]; UInt32 iVal; GetBytes(buffer); // convert to UInt32 iVal = 0; for (int i = 0; i < buffer.Length; i++) { iVal |= ((UInt32)buffer[i] << (i * 4)); } TestFramework.LogVerbose("Random UInt32 produced: " + iVal.ToString()); return iVal; } // returns a non-negative Int16 between 0 and Int16.MaxValue public static Int16 GetInt16(Int32 new_seed) { Seed = new_seed; return GetInt16(); } public static Int16 GetInt16() { Int16 i = Convert.ToInt16(m_rand.Next() % (1 + Int16.MaxValue)); TestFramework.LogVerbose("Random Int16 produced: " + i.ToString()); return i; } // returns a UInt16 between 0 and UInt16.MaxValue public static UInt16 GetUInt16(Int32 new_seed) { Seed = new_seed; return GetUInt16(); } public static UInt16 GetUInt16() { UInt16 i = Convert.ToUInt16(m_rand.Next() % (1 + UInt16.MaxValue)); TestFramework.LogVerbose("Random UInt16 produced: " + i.ToString()); return i; } // returns a non-negative Byte between 0 and Byte.MaxValue public static Byte GetByte(Int32 new_seed) { Seed = new_seed; return GetByte(); } public static Byte GetByte() { Byte i = Convert.ToByte(m_rand.Next() % (1 + Byte.MaxValue)); TestFramework.LogVerbose("Random Byte produced: " + i.ToString()); return i; } // returns a non-negative SByte between 0 and SByte.MaxValue public static SByte GetSByte(Int32 new_seed) { Seed = new_seed; return GetSByte(); } public static SByte GetSByte() { SByte i = Convert.ToSByte(m_rand.Next() % (1 + SByte.MaxValue)); TestFramework.LogVerbose("Random SByte produced: " + i.ToString()); return i; } // returns a non-negative Double between 0.0 and 1.0 public static Double GetDouble(Int32 new_seed) { Seed = new_seed; return GetDouble(); } public static Double GetDouble() { Double i = m_rand.NextDouble(); TestFramework.LogVerbose("Random Double produced: " + i.ToString()); return i; } // returns a non-negative Single between 0.0 and 1.0 public static Single GetSingle(Int32 new_seed) { Seed = new_seed; return GetSingle(); } public static Single GetSingle() { Single i = Convert.ToSingle(m_rand.NextDouble()); TestFramework.LogVerbose("Random Single produced: " + i.ToString()); return i; } // returns a valid char that is a letter public static Char GetCharLetter(Int32 new_seed) { Seed = new_seed; return GetCharLetter(); } public static Char GetCharLetter() { return GetCharLetter(true); } //returns a valid char that is a letter //if allowsurrogate is true then surrogates are valid return values public static Char GetCharLetter(Int32 new_seed, bool allowsurrogate) { Seed = new_seed; return GetCharLetter(allowsurrogate); } public static Char GetCharLetter(bool allowsurrogate) { return GetCharLetter(allowsurrogate, true); } //returns a valid char that is a letter //if allowsurrogate is true then surrogates are valid return values //if allownoweight is true, then no-weight characters are valid return values public static Char GetCharLetter(Int32 new_seed, bool allowsurrogate, bool allownoweight) { Seed = new_seed; return GetCharLetter(allowsurrogate, allownoweight); } public static Char GetCharLetter(bool allowsurrogate, bool allownoweight) { Int16 iVal; Char c = 'a'; //this value is never used Int32 counter; bool loopCondition = true; // attempt to randomly find a letter counter = 100; do { counter--; iVal = GetInt16(); TestFramework.LogVerbose("Random CharLetter produced: " + Convert.ToChar(iVal).ToString()); if (false == allownoweight) { throw new NotSupportedException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES"); } c = Convert.ToChar(iVal); loopCondition = allowsurrogate ? (!Char.IsLetter(c)) : (!Char.IsLetter(c) || Char.IsSurrogate(c)); } while (loopCondition && 0 < counter); if (!Char.IsLetter(c)) { // we tried and failed to get a letter // Grab an ASCII letter c = Convert.ToChar(GetInt16() % 26 + 'A'); } TestFramework.LogVerbose("Random Char produced: " + c.ToString()); return c; } // returns a valid char that is a number public static char GetCharNumber(Int32 new_seed) { Seed = new_seed; return GetCharNumber(); } public static char GetCharNumber() { return GetCharNumber(true); } // returns a valid char that is a number //if allownoweight is true, then no-weight characters are valid return values public static char GetCharNumber(Int32 new_seed, bool allownoweight) { Seed = new_seed; return GetCharNumber(allownoweight); } public static char GetCharNumber(bool allownoweight) { Char c = '0'; //this value is never used Int32 counter; Int16 iVal; bool loopCondition = true; // attempt to randomly find a number counter = 100; do { counter--; iVal = GetInt16(); TestFramework.LogVerbose("Random Char produced: " + Convert.ToChar(iVal).ToString()); if (false == allownoweight) { throw new InvalidOperationException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES"); } c = Convert.ToChar(iVal); loopCondition = !Char.IsNumber(c); } while (loopCondition && 0 < counter); if (!Char.IsNumber(c)) { // we tried and failed to get a letter // Grab an ASCII number c = Convert.ToChar(GetInt16() % 10 + '0'); } TestFramework.LogVerbose("Random Char produced: " + c.ToString()); return c; } // returns a valid char public static Char GetChar(Int32 new_seed) { Seed = new_seed; return GetChar(); } public static Char GetChar() { return GetChar(true); } // returns a valid char //if allowsurrogate is true then surrogates are valid return values public static Char GetChar(Int32 new_seed, bool allowsurrogate) { Seed = new_seed; return GetChar(allowsurrogate); } public static Char GetChar(bool allowsurrogate) { return GetChar(allowsurrogate, true); } // returns a valid char // if allowsurrogate is true then surrogates are valid return values // if allownoweight characters then noweight characters are valid return values public static Char GetChar(Int32 new_seed, bool allowsurrogate, bool allownoweight) { Seed = new_seed; return GetChar(allowsurrogate, allownoweight); } public static Char GetChar(bool allowsurrogate, bool allownoweight) { Int16 iVal = GetInt16(); Char c = (char)(iVal); if (!Char.IsLetter(c)) { // we tried and failed to get a letter // Just grab an ASCII letter // This is a hack but will work for now c = (char)(GetInt16() % 26 + 'A'); } return c; } // returns a string. If "validPath" is set, only valid path characters // will be included public static string GetString(Int32 new_seed, Boolean validPath, Int32 minLength, Int32 maxLength) { Seed = new_seed; return GetString(validPath, minLength, maxLength); } public static string GetString(Boolean validPath, Int32 minLength, Int32 maxLength) { return GetString(validPath, true, true, minLength, maxLength); } // several string APIs don't like nulls in them, so this generates a string without nulls public static string GetString(Int32 new_seed, Boolean validPath, Boolean allowNulls, Int32 minLength, Int32 maxLength) { Seed = new_seed; return GetString(validPath, allowNulls, minLength, maxLength); } public static string GetString(Boolean validPath, Boolean allowNulls, Int32 minLength, Int32 maxLength) { return GetString(validPath, allowNulls, true, minLength, maxLength); } // some string operations don't like no-weight characters public static string GetString(Int32 new_seed, Boolean validPath, Boolean allowNulls, Boolean allowNoWeight, Int32 minLength, Int32 maxLength) { Seed = new_seed; return GetString(validPath, allowNulls, allowNoWeight, minLength, maxLength); } public static string GetString(Boolean validPath, Boolean allowNulls, Boolean allowNoWeight, Int32 minLength, Int32 maxLength) { StringBuilder sVal = new StringBuilder(); Char c; Int32 length; if (0 == minLength && 0 == maxLength) return String.Empty; if (minLength > maxLength) return null; length = minLength; if (minLength != maxLength) { length = (GetInt32() % (maxLength - minLength)) + minLength; } for (int i = 0; length > i; i++) { if (validPath) { // TODO: Make this smarter if (0 == (GetByte() % 2)) { c = GetCharLetter(true, allowNoWeight); } else { c = GetCharNumber(allowNoWeight); } } else if (!allowNulls) { do { c = GetChar(true, allowNoWeight); } while (c == '\u0000'); } else { c = GetChar(true, allowNoWeight); } sVal.Append(c); } string s = sVal.ToString(); TestFramework.LogVerbose("Random String produced: " + s); return s; } public static string[] GetStrings(Int32 new_seed, Boolean validPath, Int32 minLength, Int32 maxLength) { Seed = new_seed; return GetStrings(validPath, minLength, maxLength); } public static string[] GetStrings(Boolean validPath, Int32 minLength, Int32 maxLength) { string validString; const char c_LATIN_A = '\u0100'; const char c_LOWER_A = 'a'; const char c_UPPER_A = 'A'; const char c_ZERO_WEIGHT = '\uFEFF'; const char c_DOUBLE_WIDE_A = '\uFF21'; const string c_SURROGATE_UPPER = "\uD801\uDC00"; const string c_SURROGATE_LOWER = "\uD801\uDC28"; const char c_LOWER_SIGMA1 = (char)0x03C2; const char c_LOWER_SIGMA2 = (char)0x03C3; const char c_UPPER_SIGMA = (char)0x03A3; const char c_SPACE = ' '; int numConsts = 12; string[] retStrings; if (2 >= minLength && 2 >= maxLength || minLength > maxLength) return null; retStrings = new string[numConsts]; validString = TestLibrary.Generator.GetString(validPath, minLength - 1, maxLength - 1); retStrings[0] = TestLibrary.Generator.GetString(validPath, minLength, maxLength); retStrings[1] = validString + c_LATIN_A; retStrings[2] = validString + c_LOWER_A; retStrings[3] = validString + c_UPPER_A; retStrings[4] = validString + c_ZERO_WEIGHT; retStrings[5] = validString + c_DOUBLE_WIDE_A; retStrings[6] = TestLibrary.Generator.GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_UPPER; retStrings[7] = TestLibrary.Generator.GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_LOWER; retStrings[8] = validString + c_LOWER_SIGMA1; retStrings[9] = validString + c_LOWER_SIGMA2; retStrings[10] = validString + c_UPPER_SIGMA; retStrings[11] = validString + c_SPACE; return retStrings; } [SecuritySafeCritical] public static object GetType(Type t) { return Activator.CreateInstance(t); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: List for exceptions. ** ** ===========================================================*/ using System.Diagnostics.Contracts; namespace System.Collections { /// This is a simple implementation of IDictionary using a singly linked list. This /// will be smaller and faster than a Hashtable if the number of elements is 10 or less. /// This should not be used if performance is important for large numbers of elements. [Serializable] internal class ListDictionaryInternal: IDictionary { DictionaryNode head; int version; int count; [NonSerialized] private Object _syncRoot; public ListDictionaryInternal() { } public Object this[Object key] { get { if (key == null) { throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); DictionaryNode node = head; while (node != null) { if ( node.key.Equals(key) ) { return node.value; } node = node.next; } return null; } set { if (key == null) { throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); #if FEATURE_SERIALIZATION if (!key.GetType().IsSerializable) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key)); if( (value != null) && (!value.GetType().IsSerializable ) ) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value)); #endif version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { if( node.key.Equals(key) ) { break; } last = node; } if (node != null) { // Found it node.value = value; return; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } } public int Count { get { return count; } } public ICollection Keys { get { return new NodeKeyValueCollection(this, true); } } public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return false; } } public bool IsSynchronized { get { return false; } } public Object SyncRoot { get { if( _syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } public ICollection Values { get { return new NodeKeyValueCollection(this, false); } } public void Add(Object key, Object value) { if (key == null) { throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); #if FEATURE_SERIALIZATION if (!key.GetType().IsSerializable) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(key) ); if( (value != null) && (!value.GetType().IsSerializable) ) throw new ArgumentException(Environment.GetResourceString("Argument_NotSerializable"), nameof(value)); #endif version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) { throw new ArgumentException(Environment.GetResourceString("Argument_AddingDuplicate__", node.key, key)); } last = node; } if (node != null) { // Found it node.value = value; return; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } public void Clear() { count = 0; head = null; version++; } public bool Contains(Object key) { if (key == null) { throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); for (DictionaryNode node = head; node != null; node = node.next) { if (node.key.Equals(key)) { return true; } } return false; } public void CopyTo(Array array, int index) { if (array==null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if ( array.Length - index < this.Count ) throw new ArgumentException( Environment.GetResourceString("ArgumentOutOfRange_Index"), nameof(index)); Contract.EndContractBlock(); for (DictionaryNode node = head; node != null; node = node.next) { array.SetValue(new DictionaryEntry(node.key, node.value), index); index++; } } public IDictionaryEnumerator GetEnumerator() { return new NodeEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new NodeEnumerator(this); } public void Remove(Object key) { if (key == null) { throw new ArgumentNullException(nameof(key), Environment.GetResourceString("ArgumentNull_Key")); } Contract.EndContractBlock(); version++; DictionaryNode last = null; DictionaryNode node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) { break; } last = node; } if (node == null) { return; } if (node == head) { head = node.next; } else { last.next = node.next; } count--; } private class NodeEnumerator : IDictionaryEnumerator { ListDictionaryInternal list; DictionaryNode current; int version; bool start; public NodeEnumerator(ListDictionaryInternal list) { this.list = list; version = list.version; start = true; current = null; } public Object Current { get { return Entry; } } public DictionaryEntry Entry { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return new DictionaryEntry(current.key, current.value); } } public Object Key { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return current.key; } } public Object Value { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return current.value; } } public bool MoveNext() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } if (start) { current = list.head; start = false; } else { if( current != null ) { current = current.next; } } return (current != null); } public void Reset() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } start = true; current = null; } } private class NodeKeyValueCollection : ICollection { ListDictionaryInternal list; bool isKeys; public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys) { this.list = list; this.isKeys = isKeys; } void ICollection.CopyTo(Array array, int index) { if (array==null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported")); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); if (array.Length - index < list.Count) throw new ArgumentException(Environment.GetResourceString("ArgumentOutOfRange_Index"), nameof(index)); for (DictionaryNode node = list.head; node != null; node = node.next) { array.SetValue(isKeys ? node.key : node.value, index); index++; } } int ICollection.Count { get { int count = 0; for (DictionaryNode node = list.head; node != null; node = node.next) { count++; } return count; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return list.SyncRoot; } } IEnumerator IEnumerable.GetEnumerator() { return new NodeKeyValueEnumerator(list, isKeys); } private class NodeKeyValueEnumerator: IEnumerator { ListDictionaryInternal list; DictionaryNode current; int version; bool isKeys; bool start; public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys) { this.list = list; this.isKeys = isKeys; this.version = list.version; this.start = true; this.current = null; } public Object Current { get { if (current == null) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumOpCantHappen")); } return isKeys ? current.key : current.value; } } public bool MoveNext() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } if (start) { current = list.head; start = false; } else { if( current != null) { current = current.next; } } return (current != null); } public void Reset() { if (version != list.version) { throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EnumFailedVersion")); } start = true; current = null; } } } [Serializable] private class DictionaryNode { public Object key; public Object value; public DictionaryNode next; } } }
// 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 Encoding = System.Text.Encoding; #if ES_BUILD_STANDALONE using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment; namespace Microsoft.Diagnostics.Tracing #else namespace System.Diagnostics.Tracing #endif { /// <summary> /// TraceLogging: Contains the information needed to generate tracelogging /// metadata for an event field. /// </summary> internal class FieldMetadata { /// <summary> /// Name of the field /// </summary> private readonly string name; /// <summary> /// The number of bytes in the UTF8 Encoding of 'name' INCLUDING a null terminator. /// </summary> private readonly int nameSize; private readonly EventFieldTags tags; private readonly byte[] custom; /// <summary> /// ETW supports fixed sized arrays. If inType has the InTypeFixedCountFlag then this is the /// statically known count for the array. It is also used to encode the number of bytes of /// custom meta-data if InTypeCustomCountFlag set. /// </summary> private readonly ushort fixedCount; private byte inType; private byte outType; /// <summary> /// Scalar or variable-length array. /// </summary> public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, bool variableCount) : this( name, type, tags, variableCount ? Statics.InTypeVariableCountFlag : (byte)0, 0, null) { return; } /// <summary> /// Fixed-length array. /// </summary> public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, ushort fixedCount) : this( name, type, tags, Statics.InTypeFixedCountFlag, fixedCount, null) { return; } /// <summary> /// Custom serializer /// </summary> public FieldMetadata( string name, TraceLoggingDataType type, EventFieldTags tags, byte[] custom) : this( name, type, tags, Statics.InTypeCustomCountFlag, checked((ushort)(custom == null ? 0 : custom.Length)), custom) { return; } private FieldMetadata( string name, TraceLoggingDataType dataType, EventFieldTags tags, byte countFlags, ushort fixedCount = 0, byte[] custom = null) { if (name == null) { throw new ArgumentNullException( "name", "This usually means that the object passed to Write is of a type that" + " does not support being used as the top-level object in an event," + " e.g. a primitive or built-in type."); } Statics.CheckName(name); var coreType = (int)dataType & Statics.InTypeMask; this.name = name; this.nameSize = Encoding.UTF8.GetByteCount(this.name) + 1; this.inType = (byte)(coreType | countFlags); this.outType = (byte)(((int)dataType >> 8) & Statics.OutTypeMask); this.tags = tags; this.fixedCount = fixedCount; this.custom = custom; if (countFlags != 0) { if (coreType == (int)TraceLoggingDataType.Nil) { throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedArrayOfNil")); } if (coreType == (int)TraceLoggingDataType.Binary) { throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedArrayOfBinary")); } #if !BROKEN_UNTIL_M3 if (coreType == (int)TraceLoggingDataType.Utf16String || coreType == (int)TraceLoggingDataType.MbcsString) { throw new NotSupportedException(Resources.GetResourceString("EventSource_NotSupportedArrayOfNullTerminatedString")); } #endif } if (((int)this.tags & 0xfffffff) != 0) { this.outType |= Statics.OutTypeChainFlag; } if (this.outType != 0) { this.inType |= Statics.InTypeChainFlag; } } public void IncrementStructFieldCount() { this.inType |= Statics.InTypeChainFlag; this.outType++; if ((this.outType & Statics.OutTypeMask) == 0) { throw new NotSupportedException(Resources.GetResourceString("EventSource_TooManyFields")); } } /// <summary> /// This is the main routine for FieldMetaData. Basically it will serialize the data in /// this structure as TraceLogging style meta-data into the array 'metaArray' starting at /// 'pos' (pos is updated to reflect the bytes written). /// /// Note that 'metaData' can be null, in which case it only updates 'pos'. This is useful /// for a 'two pass' approach where you figure out how big to make the array, and then you /// fill it in. /// </summary> public void Encode(ref int pos, byte[] metadata) { // Write out the null terminated UTF8 encoded name if (metadata != null) { Encoding.UTF8.GetBytes(this.name, 0, this.name.Length, metadata, pos); } pos += this.nameSize; // Write 1 byte for inType if (metadata != null) { metadata[pos] = this.inType; } pos += 1; // If InTypeChainFlag set, then write out the outType if (0 != (this.inType & Statics.InTypeChainFlag)) { if (metadata != null) { metadata[pos] = this.outType; } pos += 1; // If OutTypeChainFlag set, then write out tags if (0 != (this.outType & Statics.OutTypeChainFlag)) { Statics.EncodeTags((int)this.tags, ref pos, metadata); } } // If InTypeFixedCountFlag set, write out the fixedCount (2 bytes little endian) if (0 != (this.inType & Statics.InTypeFixedCountFlag)) { if (metadata != null) { metadata[pos + 0] = unchecked((byte)this.fixedCount); metadata[pos + 1] = (byte)(this.fixedCount >> 8); } pos += 2; // If InTypeCustomCountFlag set, write out the blob of custom meta-data. if (Statics.InTypeCustomCountFlag == (this.inType & Statics.InTypeCountMask) && this.fixedCount != 0) { if (metadata != null) { Buffer.BlockCopy(this.custom, 0, metadata, pos, this.fixedCount); } pos += this.fixedCount; } } } } }
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 Topshelf.Hosts { using System; using System.Collections.Generic; using System.Linq; using System.ServiceProcess; using Logging; using Runtime; public class InstallHost : Host { static readonly LogWriter _log = HostLogger.Get<InstallHost>(); readonly HostEnvironment _environment; readonly InstallHostSettings _installSettings; readonly IEnumerable<Action<InstallHostSettings>> _postActions; readonly IEnumerable<Action<InstallHostSettings>> _preActions; readonly IEnumerable<Action<InstallHostSettings>> _postRollbackActions; readonly IEnumerable<Action<InstallHostSettings>> _preRollbackActions; readonly HostSettings _settings; readonly bool _sudo; public InstallHost(HostEnvironment environment, HostSettings settings, HostStartMode startMode, IEnumerable<string> dependencies, Credentials credentials, IEnumerable<Action<InstallHostSettings>> preActions, IEnumerable<Action<InstallHostSettings>> postActions, IEnumerable<Action<InstallHostSettings>> preRollbackActions, IEnumerable<Action<InstallHostSettings>> postRollbackActions, bool sudo) { _environment = environment; _settings = settings; _installSettings = new InstallServiceSettingsImpl(settings, credentials, startMode, dependencies.ToArray()); _preActions = preActions; _postActions = postActions; _preRollbackActions = preRollbackActions; _postRollbackActions = postRollbackActions; _sudo = sudo; } public InstallHostSettings InstallSettings { get { return _installSettings; } } public HostSettings Settings { get { return _settings; } } public TopshelfExitCode Run() { if (_environment.IsServiceInstalled(_settings.ServiceName)) { _log.ErrorFormat("The {0} service is already installed.", _settings.ServiceName); return TopshelfExitCode.ServiceAlreadyInstalled; } if (!_environment.IsAdministrator) { if (_sudo) { if (_environment.RunAsAdministrator()) return TopshelfExitCode.Ok; } _log.ErrorFormat("The {0} service can only be installed as an administrator", _settings.ServiceName); return TopshelfExitCode.SudoRequired; } _log.DebugFormat("Attempting to install '{0}'", _settings.ServiceName); _environment.InstallService(_installSettings, ExecutePreActions, ExecutePostActions, ExecutePreRollbackActions, ExecutePostRollbackActions); return TopshelfExitCode.Ok; } void ExecutePreActions(InstallHostSettings settings) { foreach (Action<InstallHostSettings> action in _preActions) { action(_installSettings); } } void ExecutePostActions() { foreach (Action<InstallHostSettings> action in _postActions) { action(_installSettings); } } void ExecutePreRollbackActions() { foreach (Action<InstallHostSettings> action in _preRollbackActions) { action(_installSettings); } } void ExecutePostRollbackActions() { foreach (Action<InstallHostSettings> action in _postRollbackActions) { action(_installSettings); } } class InstallServiceSettingsImpl : InstallHostSettings { private Credentials _credentials; readonly string[] _dependencies; readonly HostSettings _settings; readonly HostStartMode _startMode; public InstallServiceSettingsImpl(HostSettings settings, Credentials credentials, HostStartMode startMode, string[] dependencies) { _credentials = credentials; _settings = settings; _startMode = startMode; _dependencies = dependencies; } public string Name { get { return _settings.Name; } } public string DisplayName { get { return _settings.DisplayName; } } public string Description { get { return _settings.Description; } } public string InstanceName { get { return _settings.InstanceName; } } public string ServiceName { get { return _settings.ServiceName; } } public bool CanPauseAndContinue { get { return _settings.CanPauseAndContinue; } } public bool CanShutdown { get { return _settings.CanShutdown; } } public bool CanSessionChanged { get { return _settings.CanSessionChanged; } } public Credentials Credentials { get { return _credentials; } set { _credentials = value; } } public string[] Dependencies { get { return _dependencies; } } public HostStartMode StartMode { get { return _startMode; } } public TimeSpan StartTimeOut { get { return _settings.StartTimeOut; } } public TimeSpan StopTimeOut { get { return _settings.StopTimeOut; } } public Action<Exception> ExceptionCallback { get { return _settings.ExceptionCallback; } } } } }
// ==++== // // Copyright(c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.ConstrainedExecution; using System.Security.Permissions; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_EventInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class EventInfo : MemberInfo, _EventInfo { #region Constructor protected EventInfo() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(EventInfo left, EventInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeEventInfo || right is RuntimeEventInfo) { return false; } return left.Equals(right); } public static bool operator !=(EventInfo left, EventInfo right) { return !(left == right); } #endif // !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Event; } } #endregion #region Public Abstract\Virtual Members public virtual MethodInfo[] GetOtherMethods(bool nonPublic) { throw new NotImplementedException(); } public abstract MethodInfo GetAddMethod(bool nonPublic); public abstract MethodInfo GetRemoveMethod(bool nonPublic); public abstract MethodInfo GetRaiseMethod(bool nonPublic); public abstract EventAttributes Attributes { get; } #endregion #region Public Members public virtual MethodInfo AddMethod { get { return GetAddMethod(true); } } public virtual MethodInfo RemoveMethod { get { return GetRemoveMethod(true); } } public virtual MethodInfo RaiseMethod { get { return GetRaiseMethod(true); } } public MethodInfo[] GetOtherMethods() { return GetOtherMethods(false); } public MethodInfo GetAddMethod() { return GetAddMethod(false); } public MethodInfo GetRemoveMethod() { return GetRemoveMethod(false); } public MethodInfo GetRaiseMethod() { return GetRaiseMethod(false); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public virtual void AddEventHandler(Object target, Delegate handler) { MethodInfo addMethod = GetAddMethod(); if (addMethod == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod")); #if FEATURE_COMINTEROP if (addMethod.ReturnType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event Contract.Assert(addMethod.ReturnType == typeof(void)); #endif // FEATURE_COMINTEROP addMethod.Invoke(target, new object[] { handler }); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public virtual void RemoveEventHandler(Object target, Delegate handler) { MethodInfo removeMethod = GetRemoveMethod(); if (removeMethod == null) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicRemoveMethod")); #if FEATURE_COMINTEROP ParameterInfo[] parameters = removeMethod.GetParametersNoCopy(); Contract.Assert(parameters != null && parameters.Length == 1); if (parameters[0].ParameterType == typeof(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotSupportedOnWinRTEvent")); // Must be a normal non-WinRT event Contract.Assert(parameters[0].ParameterType.BaseType == typeof(MulticastDelegate)); #endif // FEATURE_COMINTEROP removeMethod.Invoke(target, new object[] { handler }); } public virtual Type EventHandlerType { get { MethodInfo m = GetAddMethod(true); ParameterInfo[] p = m.GetParametersNoCopy(); Type del = typeof(Delegate); for (int i = 0; i < p.Length; i++) { Type c = p[i].ParameterType; if (c.IsSubclassOf(del)) return c; } return null; } } public bool IsSpecialName { get { return(Attributes & EventAttributes.SpecialName) != 0; } } public virtual bool IsMulticast { get { Type cl = EventHandlerType; Type mc = typeof(MulticastDelegate); return mc.IsAssignableFrom(cl); } } #endregion #if !FEATURE_CORECLR Type _EventInfo.GetType() { return base.GetType(); } void _EventInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _EventInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _EventInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _EventInfo.Invoke in VM\DangerousAPIs.h and // include _EventInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _EventInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal unsafe sealed class RuntimeEventInfo : EventInfo, ISerializable { #region Private Data Members private int m_token; private EventAttributes m_flags; private string m_name; [System.Security.SecurityCritical] private void* m_utf8name; private RuntimeTypeCache m_reflectedTypeCache; private RuntimeMethodInfo m_addMethod; private RuntimeMethodInfo m_removeMethod; private RuntimeMethodInfo m_raiseMethod; private MethodInfo[] m_otherMethod; private RuntimeType m_declaringType; private BindingFlags m_bindingFlags; #endregion #region Constructor internal RuntimeEventInfo() { // Used for dummy head node during population } [System.Security.SecurityCritical] // auto-generated internal RuntimeEventInfo(int tkEvent, RuntimeType declaredType, RuntimeTypeCache reflectedTypeCache, out bool isPrivate) { Contract.Requires(declaredType != null); Contract.Requires(reflectedTypeCache != null); Contract.Assert(!reflectedTypeCache.IsGlobal); MetadataImport scope = declaredType.GetRuntimeModule().MetadataImport; m_token = tkEvent; m_reflectedTypeCache = reflectedTypeCache; m_declaringType = declaredType; RuntimeType reflectedType = reflectedTypeCache.GetRuntimeType(); scope.GetEventProps(tkEvent, out m_utf8name, out m_flags); RuntimeMethodInfo dummy; Associates.AssignAssociates(scope, tkEvent, declaredType, reflectedType, out m_addMethod, out m_removeMethod, out m_raiseMethod, out dummy, out dummy, out m_otherMethod, out isPrivate, out m_bindingFlags); } #endregion #region Internal Members [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RuntimeEventInfo m = o as RuntimeEventInfo; if ((object)m == null) return false; return m.m_token == m_token && RuntimeTypeHandle.GetModule(m_declaringType).Equals( RuntimeTypeHandle.GetModule(m.m_declaringType)); } internal BindingFlags BindingFlags { get { return m_bindingFlags; } } #endregion #region Object Overrides public override String ToString() { if (m_addMethod == null || m_addMethod.GetParametersNoCopy().Length == 0) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NoPublicAddMethod")); return m_addMethod.GetParametersNoCopy()[0].ParameterType.FormatTypeName() + " " + Name; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Event; } } public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = new Utf8String(m_utf8name).ToString(); return m_name; } } public override Type DeclaringType { get { return m_declaringType; } } public override Type ReflectedType { get { return ReflectedTypeInternal; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } public override int MetadataToken { get { return m_token; } } public override Module Module { get { return GetRuntimeModule(); } } internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } #endregion #region ISerializable [System.Security.SecurityCritical] // auto-generated_required public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, null, MemberTypes.Event); } #endregion #region EventInfo Overrides public override MethodInfo[] GetOtherMethods(bool nonPublic) { List<MethodInfo> ret = new List<MethodInfo>(); if ((object)m_otherMethod == null) return new MethodInfo[0]; for(int i = 0; i < m_otherMethod.Length; i ++) { if (Associates.IncludeAccessor((MethodInfo)m_otherMethod[i], nonPublic)) ret.Add(m_otherMethod[i]); } return ret.ToArray(); } public override MethodInfo GetAddMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_addMethod, nonPublic)) return null; return m_addMethod; } public override MethodInfo GetRemoveMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_removeMethod, nonPublic)) return null; return m_removeMethod; } public override MethodInfo GetRaiseMethod(bool nonPublic) { if (!Associates.IncludeAccessor(m_raiseMethod, nonPublic)) return null; return m_raiseMethod; } public override EventAttributes Attributes { get { return m_flags; } } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using ClientDependency.Core; using System.Linq; using ClientDependency.Core.Controls; using umbraco.IO; namespace umbraco.uicontrols { [ClientDependency(ClientDependencyType.Javascript, "CodeArea/javascript.js", "UmbracoClient")] [ClientDependency(ClientDependencyType.Javascript, "CodeArea/UmbracoEditor.js", "UmbracoClient")] [ClientDependency(ClientDependencyType.Css, "CodeArea/styles.css", "UmbracoClient")] [ClientDependency(ClientDependencyType.Javascript, "Application/jQuery/jquery-fieldselection.js", "UmbracoClient")] public class CodeArea : WebControl { public CodeArea() { //set the default to Css CodeBase = EditorType.Css; } protected TextBox CodeTextBox; public bool AutoResize { get; set; } public bool AutoSuggest { get; set; } public string EditorMimeType { get; set; } public int OffSetX { get; set; } public int OffSetY { get; set; } public string Text { get { EnsureChildControls(); return CodeTextBox.Text; } set { EnsureChildControls(); CodeTextBox.Text = value; } } public bool CodeMirrorEnabled { get { return UmbracoSettings.ScriptDisableEditor == false; } } public EditorType CodeBase { get; set; } public string ClientSaveMethod { get; set; } public enum EditorType { JavaScript, Css, Python, XML, HTML, Razor, HtmlMixed } protected override void OnInit(EventArgs e) { base.OnInit(e); EnsureChildControls(); if (CodeMirrorEnabled) { ClientDependencyLoader.Instance.RegisterDependency(0, "CodeMirror/js/lib/codemirror.js", "UmbracoClient", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(2, "CodeMirror/js/mode/" + CodeBase.ToString().ToLower() + "/" + CodeBase.ToString().ToLower() + ".js", "UmbracoClient", ClientDependencyType.Javascript); if (CodeBase == EditorType.HtmlMixed) { ClientDependencyLoader.Instance.RegisterDependency(1, "CodeMirror/js/mode/xml/xml.js", "UmbracoClient", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(1, "CodeMirror/js/mode/javascript/javascript.js", "UmbracoClient", ClientDependencyType.Javascript); ClientDependencyLoader.Instance.RegisterDependency(1, "CodeMirror/js/mode/css/css.js", "UmbracoClient", ClientDependencyType.Javascript); } ClientDependencyLoader.Instance.RegisterDependency(2, "CodeMirror/js/lib/codemirror.css", "UmbracoClient", ClientDependencyType.Css); ClientDependencyLoader.Instance.RegisterDependency(3, "CodeMirror/css/umbracoCustom.css", "UmbracoClient", ClientDependencyType.Css); ClientDependencyLoader.Instance.RegisterDependency(4, "CodeArea/styles.css", "UmbracoClient", ClientDependencyType.Css); } } protected override void CreateChildControls() { base.CreateChildControls(); CodeTextBox = new TextBox(); CodeTextBox.ID = "CodeTextBox"; if (CodeMirrorEnabled == false) { CodeTextBox.Attributes.Add("class", "codepress"); CodeTextBox.Attributes.Add("wrap", "off"); } CodeTextBox.TextMode = TextBoxMode.MultiLine; this.Controls.Add(CodeTextBox); } /// <summary> /// Client ID is different if the code editor is turned on/off /// </summary> public override string ClientID { get { if (CodeMirrorEnabled == false) return CodeTextBox.ClientID; else return base.ClientID; } } protected override void Render(HtmlTextWriter writer) { EnsureChildControls(); var jsEventCode = ""; if (CodeMirrorEnabled == false) { CodeTextBox.RenderControl(writer); jsEventCode = RenderBasicEditor(); } else { writer.WriteBeginTag("div"); writer.WriteAttribute("id", this.ClientID); writer.WriteAttribute("class", this.CssClass); this.ControlStyle.AddAttributesToRender(writer); writer.Write(HtmlTextWriter.TagRightChar); CodeTextBox.RenderControl(writer); writer.WriteEndTag("div"); jsEventCode = RenderCodeEditor(); } if (this.AutoResize) { if (CodeMirrorEnabled) { //reduce the width if using code mirror because of the line numbers OffSetX += 20; } jsEventCode += @" //TODO: for now this is a global var, need to refactor all this so that is using proper js standards //with correct objects, and proper accessors to these objects. var UmbEditor; $(document).ready(function () { //create the editor UmbEditor = new Umbraco.Controls.CodeEditor.UmbracoEditor(" + (CodeMirrorEnabled == false).ToString().ToLower() + @", '" + this.ClientID + @"'); var m_textEditor = jQuery('#" + this.ClientID + @"'); //with codemirror adding divs for line numbers, we need to target a different element m_textEditor = m_textEditor.find('iframe').length > 0 ? m_textEditor.children('div').get(0) : m_textEditor.get(0); jQuery(window).resize(function(){ resizeTextArea(m_textEditor, " + OffSetX.ToString() + "," + OffSetY.ToString() + @"); }); jQuery(document).ready(function(){ resizeTextArea(m_textEditor, " + OffSetX.ToString() + "," + OffSetY.ToString() + @"); }); });"; } jsEventCode = string.Format(@"<script type=""text/javascript"">{0}</script>", jsEventCode); writer.WriteLine(jsEventCode); } protected string RenderBasicEditor() { string jsEventCode = @" var m_textEditor = document.getElementById('" + this.ClientID + @"'); tab.watch('" + this.ClientID + @"'); "; return jsEventCode; } protected string RenderCodeEditor() { var extraKeys = ""; var editorMimetype = ""; if (string.IsNullOrEmpty(EditorMimeType) == false) editorMimetype = @", mode: """ + EditorMimeType + "\""; var jsEventCode = @" var textarea = document.getElementById('" + CodeTextBox.ClientID + @"'); var codeEditor = CodeMirror.fromTextArea(textarea, { width: ""100%"", height: ""100%"", tabMode: ""shift"", matchBrackets: true, indentUnit: 4, indentWithTabs: true, enterMode: ""keep"", onCursorActivity: updateLineInfo, lineWrapping: false" + editorMimetype + @", lineNumbers: true" + extraKeys + @" }); updateLineInfo(codeEditor); "; return jsEventCode; } } }
using System; using System.Diagnostics; using System.Text; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2001 September 15 ** ** 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. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that splits an SQL input string up into ** individual tokens and sends those tokens one-by-one over to the ** parser for analysis. ************************************************************************* ** 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: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2 ** ************************************************************************* */ //#include "sqliteInt.h" //#include <stdlib.h> /* ** The charMap() macro maps alphabetic characters into their ** lower-case ASCII equivalent. On ASCII machines, this is just ** an upper-to-lower case map. On EBCDIC machines we also need ** to adjust the encoding. Only alphabetic characters and underscores ** need to be translated. */ #if SQLITE_ASCII //# define charMap(X) sqlite3UpperToLower[(unsigned char)X] #endif //#if SQLITE_EBCDIC //# define charMap(X) ebcdicToAscii[(unsigned char)X] //const unsigned char ebcdicToAscii[] = { ///* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */ // 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */ // 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */ // 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ // 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */ // 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */ // 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */ //}; //#endif /* ** The sqlite3KeywordCode function looks up an identifier to determine if ** it is a keyword. If it is a keyword, the token code of that keyword is ** returned. If the input is not a keyword, TK_ID is returned. ** ** The implementation of this routine was generated by a program, ** mkkeywordhash.h, located in the tool subdirectory of the distribution. ** The output of the mkkeywordhash.c program is written into a file ** named keywordhash.h and then included into this source file by ** the #include below. */ //#include "keywordhash.h" /* ** If X is a character that can be used in an identifier then ** IdChar(X) will be true. Otherwise it is false. ** ** For ASCII, any character with the high-order bit set is ** allowed in an identifier. For 7-bit characters, ** sqlite3IsIdChar[X] must be 1. ** ** For EBCDIC, the rules are more complex but have the same ** end result. ** ** Ticket #1066. the SQL standard does not allow '$' in the ** middle of identfiers. But many SQL implementations do. ** SQLite will allow '$' in identifiers for compatibility. ** But the feature is undocumented. */ #if SQLITE_ASCII //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) #endif //#if SQLITE_EBCDIC //const char sqlite3IsEbcdicIdChar[] = { ///* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */ // 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */ // 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */ // 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */ // 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */ // 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */ // 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */ // 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */ //}; //#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) //#endif /* ** Return the length of the token that begins at z[iOffset + 0]. ** Store the token type in *tokenType before returning. */ static int sqlite3GetToken( string z, int iOffset, ref int tokenType ) { int i; byte c = 0; switch ( z[iOffset + 0] ) { case ' ': case '\t': case '\n': case '\f': case '\r': { testcase( z[iOffset + 0] == ' ' ); testcase( z[iOffset + 0] == '\t' ); testcase( z[iOffset + 0] == '\n' ); testcase( z[iOffset + 0] == '\f' ); testcase( z[iOffset + 0] == '\r' ); for ( i = 1; z.Length > iOffset + i && sqlite3Isspace( z[iOffset + i] ); i++ ) { } tokenType = TK_SPACE; return i; } case '-': { if ( z.Length > iOffset + 1 && z[iOffset + 1] == '-' ) { /* IMP: R-15891-05542 -- syntax diagram for comments */ for ( i = 2; z.Length > iOffset + i && ( c = (byte)z[iOffset + i] ) != 0 && c != '\n'; i++ ) { } tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } tokenType = TK_MINUS; return 1; } case '(': { tokenType = TK_LP; return 1; } case ')': { tokenType = TK_RP; return 1; } case ';': { tokenType = TK_SEMI; return 1; } case '+': { tokenType = TK_PLUS; return 1; } case '*': { tokenType = TK_STAR; return 1; } case '/': { if ( iOffset + 2 >= z.Length || z[iOffset + 1] != '*' ) { tokenType = TK_SLASH; return 1; } /* IMP: R-15891-05542 -- syntax diagram for comments */ for ( i = 3, c = (byte)z[iOffset + 2]; iOffset + i < z.Length && ( c != '*' || ( z[iOffset + i] != '/' ) && ( c != 0 ) ); i++ ) { c = (byte)z[iOffset + i]; } if ( iOffset + i == z.Length ) c = 0; if ( c != 0 ) i++; tokenType = TK_SPACE; /* IMP: R-22934-25134 */ return i; } case '%': { tokenType = TK_REM; return 1; } case '=': { tokenType = TK_EQ; return 1 + ( z[iOffset + 1] == '=' ? 1 : 0 ); } case '<': { if ( ( c = (byte)z[iOffset + 1] ) == '=' ) { tokenType = TK_LE; return 2; } else if ( c == '>' ) { tokenType = TK_NE; return 2; } else if ( c == '<' ) { tokenType = TK_LSHIFT; return 2; } else { tokenType = TK_LT; return 1; } } case '>': { if ( z.Length > iOffset + 1 && ( c = (byte)z[iOffset + 1] ) == '=' ) { tokenType = TK_GE; return 2; } else if ( c == '>' ) { tokenType = TK_RSHIFT; return 2; } else { tokenType = TK_GT; return 1; } } case '!': { if ( z[iOffset + 1] != '=' ) { tokenType = TK_ILLEGAL; return 2; } else { tokenType = TK_NE; return 2; } } case '|': { if ( z[iOffset + 1] != '|' ) { tokenType = TK_BITOR; return 1; } else { tokenType = TK_CONCAT; return 2; } } case ',': { tokenType = TK_COMMA; return 1; } case '&': { tokenType = TK_BITAND; return 1; } case '~': { tokenType = TK_BITNOT; return 1; } case '`': case '\'': case '"': { int delim = z[iOffset + 0]; testcase( delim == '`' ); testcase( delim == '\'' ); testcase( delim == '"' ); for ( i = 1; ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0; i++ ) { if ( c == delim ) { if ( z.Length > iOffset + i + 1 && z[iOffset + i + 1] == delim ) { i++; } else { break; } } } if ( ( iOffset + i == z.Length && c != delim ) || z[iOffset + i] != delim ) { tokenType = TK_ILLEGAL; return i + 1; } if ( c == '\'' ) { tokenType = TK_STRING; return i + 1; } else if ( c != 0 ) { tokenType = TK_ID; return i + 1; } else { tokenType = TK_ILLEGAL; return i; } } case '.': { #if !SQLITE_OMIT_FLOATING_POINT if ( !sqlite3Isdigit( z[iOffset + 1] ) ) #endif { tokenType = TK_DOT; return 1; } /* If the next character is a digit, this is a floating point ** number that begins with ".". Fall thru into the next case */ goto case '0'; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { testcase( z[iOffset] == '0' ); testcase( z[iOffset] == '1' ); testcase( z[iOffset] == '2' ); testcase( z[iOffset] == '3' ); testcase( z[iOffset] == '4' ); testcase( z[iOffset] == '5' ); testcase( z[iOffset] == '6' ); testcase( z[iOffset] == '7' ); testcase( z[iOffset] == '8' ); testcase( z[iOffset] == '9' ); tokenType = TK_INTEGER; for ( i = 0; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ ) { } #if !SQLITE_OMIT_FLOATING_POINT if ( z.Length > iOffset + i && z[iOffset + i] == '.' ) { i++; while ( z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ) ) { i++; } tokenType = TK_FLOAT; } if ( z.Length > iOffset + i + 1 && ( z[iOffset + i] == 'e' || z[iOffset + i] == 'E' ) && ( sqlite3Isdigit( z[iOffset + i + 1] ) || z.Length > iOffset + i + 2 && ( ( z[iOffset + i + 1] == '+' || z[iOffset + i + 1] == '-' ) && sqlite3Isdigit( z[iOffset + i + 2] ) ) ) ) { i += 2; while ( z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ) ) { i++; } tokenType = TK_FLOAT; } #endif while ( iOffset + i < z.Length && IdChar( (byte)z[iOffset + i] ) ) { tokenType = TK_ILLEGAL; i++; } return i; } case '[': { for ( i = 1, c = (byte)z[iOffset + 0]; c != ']' && ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0; i++ ) { } tokenType = c == ']' ? TK_ID : TK_ILLEGAL; return i; } case '?': { tokenType = TK_VARIABLE; for ( i = 1; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ ) { } return i; } case '#': { for ( i = 1; z.Length > iOffset + i && sqlite3Isdigit( z[iOffset + i] ); i++ ) { } if ( i > 1 ) { /* Parameters of the form #NNN (where NNN is a number) are used ** internally by sqlite3NestedParse. */ tokenType = TK_REGISTER; return i; } /* Fall through into the next case if the '#' is not followed by ** a digit. Try to match #AAAA where AAAA is a parameter name. */ goto case ':'; } #if !SQLITE_OMIT_TCL_VARIABLE case '$': #endif case '@': /* For compatibility with MS SQL Server */ case ':': { int n = 0; testcase( z[iOffset + 0] == '$' ); testcase( z[iOffset + 0] == '@' ); testcase( z[iOffset + 0] == ':' ); tokenType = TK_VARIABLE; for ( i = 1; z.Length > iOffset + i && ( c = (byte)z[iOffset + i] ) != 0; i++ ) { if ( IdChar( c ) ) { n++; #if !SQLITE_OMIT_TCL_VARIABLE } else if ( c == '(' && n > 0 ) { do { i++; } while ( ( iOffset + i ) < z.Length && ( c = (byte)z[iOffset + i] ) != 0 && !sqlite3Isspace( c ) && c != ')' ); if ( c == ')' ) { i++; } else { tokenType = TK_ILLEGAL; } break; } else if ( c == ':' && z[iOffset + i + 1] == ':' ) { i++; #endif } else { break; } } if ( n == 0 ) tokenType = TK_ILLEGAL; return i; } #if !SQLITE_OMIT_BLOB_LITERAL case 'x': case 'X': { testcase( z[iOffset + 0] == 'x' ); testcase( z[iOffset + 0] == 'X' ); if ( z.Length > iOffset + 1 && z[iOffset + 1] == '\'' ) { tokenType = TK_BLOB; for ( i = 2; z.Length > iOffset + i && sqlite3Isxdigit( z[iOffset + i] ); i++ ) { } if ( iOffset + i == z.Length || z[iOffset + i] != '\'' || i % 2 != 0 ) { tokenType = TK_ILLEGAL; while ( z.Length > iOffset + i && z[iOffset + i] != '\'' ) { i++; } } if ( z.Length > iOffset + i ) i++; return i; } goto default; /* Otherwise fall through to the next case */ } #endif default: { if ( !IdChar( (byte)z[iOffset] ) ) { break; } for ( i = 1; i < z.Length - iOffset && IdChar( (byte)z[iOffset + i] ); i++ ) { } tokenType = keywordCode( z, iOffset, i ); return i; } } tokenType = TK_ILLEGAL; return 1; } /* ** Run the parser on the given SQL string. The parser structure is ** passed in. An SQLITE_ status code is returned. If an error occurs ** then an and attempt is made to write an error message into ** memory obtained from sqlite3_malloc() and to make pzErrMsg point to that ** error message. */ static int sqlite3RunParser( Parse pParse, string zSql, ref string pzErrMsg ) { int nErr = 0; /* Number of errors encountered */ int i; /* Loop counter */ yyParser pEngine; /* The LEMON-generated LALR(1) parser */ int tokenType = 0; /* type of the next token */ int lastTokenParsed = -1; /* type of the previous token */ byte enableLookaside; /* Saved value of db->lookaside.bEnabled */ sqlite3 db = pParse.db; /* The database connection */ int mxSqlLen; /* Max length of an SQL string */ mxSqlLen = db.aLimit[SQLITE_LIMIT_SQL_LENGTH]; if ( db.activeVdbeCnt == 0 ) { db.u1.isInterrupted = false; } pParse.rc = SQLITE_OK; pParse.zTail = new StringBuilder( zSql ); i = 0; Debug.Assert( pzErrMsg != null ); pEngine = sqlite3ParserAlloc();//sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc); //if ( pEngine == null ) //{ // db.mallocFailed = 1; // return SQLITE_NOMEM; //} Debug.Assert( pParse.pNewTable == null ); Debug.Assert( pParse.pNewTrigger == null ); Debug.Assert( pParse.nVar == 0 ); Debug.Assert( pParse.nzVar == 0 ); Debug.Assert( pParse.azVar == null ); enableLookaside = db.lookaside.bEnabled; if ( db.lookaside.pStart != 0 ) db.lookaside.bEnabled = 1; while ( /* 0 == db.mallocFailed && */ i < zSql.Length ) { Debug.Assert( i >= 0 ); //pParse->sLastToken.z = &zSql[i]; pParse.sLastToken.n = sqlite3GetToken( zSql, i, ref tokenType ); pParse.sLastToken.z = zSql.Substring( i ); i += pParse.sLastToken.n; if ( i > mxSqlLen ) { pParse.rc = SQLITE_TOOBIG; break; } switch ( tokenType ) { case TK_SPACE: { if ( db.u1.isInterrupted ) { sqlite3ErrorMsg( pParse, "interrupt" ); pParse.rc = SQLITE_INTERRUPT; goto abort_parse; } break; } case TK_ILLEGAL: { sqlite3DbFree( db, ref pzErrMsg ); pzErrMsg = sqlite3MPrintf( db, "unrecognized token: \"%T\"", (object)pParse.sLastToken ); nErr++; goto abort_parse; } case TK_SEMI: { //pParse.zTail = new StringBuilder(zSql.Substring( i,zSql.Length-i )); /* Fall thru into the default case */ goto default; } default: { sqlite3Parser( pEngine, tokenType, pParse.sLastToken, pParse ); lastTokenParsed = tokenType; if ( pParse.rc != SQLITE_OK ) { goto abort_parse; } break; } } } abort_parse: pParse.zTail = new StringBuilder( zSql.Length <= i ? "" : zSql.Substring( i, zSql.Length - i ) ); if ( zSql.Length >= i && nErr == 0 && pParse.rc == SQLITE_OK ) { if ( lastTokenParsed != TK_SEMI ) { sqlite3Parser( pEngine, TK_SEMI, pParse.sLastToken, pParse ); } sqlite3Parser( pEngine, 0, pParse.sLastToken, pParse ); } #if YYTRACKMAXSTACKDEPTH sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK, sqlite3ParserStackPeak(pEngine) ); #endif //* YYDEBUG */ sqlite3ParserFree( pEngine, null );//sqlite3_free ); db.lookaside.bEnabled = enableLookaside; //if ( db.mallocFailed != 0 ) //{ // pParse.rc = SQLITE_NOMEM; //} if ( pParse.rc != SQLITE_OK && pParse.rc != SQLITE_DONE && pParse.zErrMsg == "" ) { sqlite3SetString( ref pParse.zErrMsg, db, sqlite3ErrStr( pParse.rc ) ); } //assert( pzErrMsg!=0 ); if ( pParse.zErrMsg != null ) { pzErrMsg = pParse.zErrMsg; sqlite3_log( pParse.rc, "%s", pzErrMsg ); pParse.zErrMsg = ""; nErr++; } if ( pParse.pVdbe != null && pParse.nErr > 0 && pParse.nested == 0 ) { sqlite3VdbeDelete( ref pParse.pVdbe ); pParse.pVdbe = null; } #if NO_SQLITE_OMIT_SHARED_CACHE //#if !SQLITE_OMIT_SHARED_CACHE if ( pParse.nested == 0 ) { sqlite3DbFree( db, ref pParse.aTableLock ); pParse.aTableLock = null; pParse.nTableLock = 0; } #endif #if !SQLITE_OMIT_VIRTUALTABLE pParse.apVtabLock = null;//sqlite3_free( pParse.apVtabLock ); #endif if ( !IN_DECLARE_VTAB(pParse) ) { /* If the pParse.declareVtab flag is set, do not delete any table ** structure built up in pParse.pNewTable. The calling code (see vtab.c) ** will take responsibility for freeing the Table structure. */ sqlite3DeleteTable( db, ref pParse.pNewTable ); } #if !SQLITE_OMIT_TRIGGER sqlite3DeleteTrigger( db, ref pParse.pNewTrigger ); #endif //for ( i = pParse.nzVar - 1; i >= 0; i-- ) // sqlite3DbFree( db, pParse.azVar[i] ); sqlite3DbFree( db, ref pParse.azVar ); sqlite3DbFree( db, ref pParse.aAlias ); while ( pParse.pAinc != null ) { AutoincInfo p = pParse.pAinc; pParse.pAinc = p.pNext; sqlite3DbFree( db, ref p ); } while ( pParse.pZombieTab != null ) { Table p = pParse.pZombieTab; pParse.pZombieTab = p.pNextZombie; sqlite3DeleteTable( db, ref p ); } if ( nErr > 0 && pParse.rc == SQLITE_OK ) { pParse.rc = SQLITE_ERROR; } return nErr; } } }
using System; namespace Magnesium.Vulkan { internal enum VkFormat : uint { FormatUndefined = 0, FormatR4g4UnormPack8 = 1, FormatR4g4b4a4UnormPack16 = 2, FormatB4g4r4a4UnormPack16 = 3, FormatR5g6b5UnormPack16 = 4, FormatB5g6r5UnormPack16 = 5, FormatR5g5b5a1UnormPack16 = 6, FormatB5g5r5a1UnormPack16 = 7, FormatA1r5g5b5UnormPack16 = 8, FormatR8Unorm = 9, FormatR8Snorm = 10, FormatR8Uscaled = 11, FormatR8Sscaled = 12, FormatR8Uint = 13, FormatR8Sint = 14, FormatR8Srgb = 15, FormatR8g8Unorm = 16, FormatR8g8Snorm = 17, FormatR8g8Uscaled = 18, FormatR8g8Sscaled = 19, FormatR8g8Uint = 20, FormatR8g8Sint = 21, FormatR8g8Srgb = 22, FormatR8g8b8Unorm = 23, FormatR8g8b8Snorm = 24, FormatR8g8b8Uscaled = 25, FormatR8g8b8Sscaled = 26, FormatR8g8b8Uint = 27, FormatR8g8b8Sint = 28, FormatR8g8b8Srgb = 29, FormatB8g8r8Unorm = 30, FormatB8g8r8Snorm = 31, FormatB8g8r8Uscaled = 32, FormatB8g8r8Sscaled = 33, FormatB8g8r8Uint = 34, FormatB8g8r8Sint = 35, FormatB8g8r8Srgb = 36, FormatR8g8b8a8Unorm = 37, FormatR8g8b8a8Snorm = 38, FormatR8g8b8a8Uscaled = 39, FormatR8g8b8a8Sscaled = 40, FormatR8g8b8a8Uint = 41, FormatR8g8b8a8Sint = 42, FormatR8g8b8a8Srgb = 43, FormatB8g8r8a8Unorm = 44, FormatB8g8r8a8Snorm = 45, FormatB8g8r8a8Uscaled = 46, FormatB8g8r8a8Sscaled = 47, FormatB8g8r8a8Uint = 48, FormatB8g8r8a8Sint = 49, FormatB8g8r8a8Srgb = 50, FormatA8b8g8r8UnormPack32 = 51, FormatA8b8g8r8SnormPack32 = 52, FormatA8b8g8r8UscaledPack32 = 53, FormatA8b8g8r8SscaledPack32 = 54, FormatA8b8g8r8UintPack32 = 55, FormatA8b8g8r8SintPack32 = 56, FormatA8b8g8r8SrgbPack32 = 57, FormatA2r10g10b10UnormPack32 = 58, FormatA2r10g10b10SnormPack32 = 59, FormatA2r10g10b10UscaledPack32 = 60, FormatA2r10g10b10SscaledPack32 = 61, FormatA2r10g10b10UintPack32 = 62, FormatA2r10g10b10SintPack32 = 63, FormatA2b10g10r10UnormPack32 = 64, FormatA2b10g10r10SnormPack32 = 65, FormatA2b10g10r10UscaledPack32 = 66, FormatA2b10g10r10SscaledPack32 = 67, FormatA2b10g10r10UintPack32 = 68, FormatA2b10g10r10SintPack32 = 69, FormatR16Unorm = 70, FormatR16Snorm = 71, FormatR16Uscaled = 72, FormatR16Sscaled = 73, FormatR16Uint = 74, FormatR16Sint = 75, FormatR16Sfloat = 76, FormatR16g16Unorm = 77, FormatR16g16Snorm = 78, FormatR16g16Uscaled = 79, FormatR16g16Sscaled = 80, FormatR16g16Uint = 81, FormatR16g16Sint = 82, FormatR16g16Sfloat = 83, FormatR16g16b16Unorm = 84, FormatR16g16b16Snorm = 85, FormatR16g16b16Uscaled = 86, FormatR16g16b16Sscaled = 87, FormatR16g16b16Uint = 88, FormatR16g16b16Sint = 89, FormatR16g16b16Sfloat = 90, FormatR16g16b16a16Unorm = 91, FormatR16g16b16a16Snorm = 92, FormatR16g16b16a16Uscaled = 93, FormatR16g16b16a16Sscaled = 94, FormatR16g16b16a16Uint = 95, FormatR16g16b16a16Sint = 96, FormatR16g16b16a16Sfloat = 97, FormatR32Uint = 98, FormatR32Sint = 99, FormatR32Sfloat = 100, FormatR32g32Uint = 101, FormatR32g32Sint = 102, FormatR32g32Sfloat = 103, FormatR32g32b32Uint = 104, FormatR32g32b32Sint = 105, FormatR32g32b32Sfloat = 106, FormatR32g32b32a32Uint = 107, FormatR32g32b32a32Sint = 108, FormatR32g32b32a32Sfloat = 109, FormatR64Uint = 110, FormatR64Sint = 111, FormatR64Sfloat = 112, FormatR64g64Uint = 113, FormatR64g64Sint = 114, FormatR64g64Sfloat = 115, FormatR64g64b64Uint = 116, FormatR64g64b64Sint = 117, FormatR64g64b64Sfloat = 118, FormatR64g64b64a64Uint = 119, FormatR64g64b64a64Sint = 120, FormatR64g64b64a64Sfloat = 121, FormatB10g11r11UfloatPack32 = 122, FormatE5b9g9r9UfloatPack32 = 123, FormatD16Unorm = 124, FormatX8D24UnormPack32 = 125, FormatD32Sfloat = 126, FormatS8Uint = 127, FormatD16UnormS8Uint = 128, FormatD24UnormS8Uint = 129, FormatD32SfloatS8Uint = 130, FormatBc1RgbUnormBlock = 131, FormatBc1RgbSrgbBlock = 132, FormatBc1RgbaUnormBlock = 133, FormatBc1RgbaSrgbBlock = 134, FormatBc2UnormBlock = 135, FormatBc2SrgbBlock = 136, FormatBc3UnormBlock = 137, FormatBc3SrgbBlock = 138, FormatBc4UnormBlock = 139, FormatBc4SnormBlock = 140, FormatBc5UnormBlock = 141, FormatBc5SnormBlock = 142, FormatBc6hUfloatBlock = 143, FormatBc6hSfloatBlock = 144, FormatBc7UnormBlock = 145, FormatBc7SrgbBlock = 146, FormatEtc2R8g8b8UnormBlock = 147, FormatEtc2R8g8b8SrgbBlock = 148, FormatEtc2R8g8b8a1UnormBlock = 149, FormatEtc2R8g8b8a1SrgbBlock = 150, FormatEtc2R8g8b8a8UnormBlock = 151, FormatEtc2R8g8b8a8SrgbBlock = 152, FormatEacR11UnormBlock = 153, FormatEacR11SnormBlock = 154, FormatEacR11g11UnormBlock = 155, FormatEacR11g11SnormBlock = 156, FormatAstc4x4UnormBlock = 157, FormatAstc4x4SrgbBlock = 158, FormatAstc5x4UnormBlock = 159, FormatAstc5x4SrgbBlock = 160, FormatAstc5x5UnormBlock = 161, FormatAstc5x5SrgbBlock = 162, FormatAstc6x5UnormBlock = 163, FormatAstc6x5SrgbBlock = 164, FormatAstc6x6UnormBlock = 165, FormatAstc6x6SrgbBlock = 166, FormatAstc8x5UnormBlock = 167, FormatAstc8x5SrgbBlock = 168, FormatAstc8x6UnormBlock = 169, FormatAstc8x6SrgbBlock = 170, FormatAstc8x8UnormBlock = 171, FormatAstc8x8SrgbBlock = 172, FormatAstc10x5UnormBlock = 173, FormatAstc10x5SrgbBlock = 174, FormatAstc10x6UnormBlock = 175, FormatAstc10x6SrgbBlock = 176, FormatAstc10x8UnormBlock = 177, FormatAstc10x8SrgbBlock = 178, FormatAstc10x10UnormBlock = 179, FormatAstc10x10SrgbBlock = 180, FormatAstc12x10UnormBlock = 181, FormatAstc12x10SrgbBlock = 182, FormatAstc12x12UnormBlock = 183, FormatAstc12x12SrgbBlock = 184, FormatPvrtc12bppUnormBlockImg = 1000054000, FormatPvrtc14bppUnormBlockImg = 1000054001, FormatPvrtc22bppUnormBlockImg = 1000054002, FormatPvrtc24bppUnormBlockImg = 1000054003, FormatPvrtc12bppSrgbBlockImg = 1000054004, FormatPvrtc14bppSrgbBlockImg = 1000054005, FormatPvrtc22bppSrgbBlockImg = 1000054006, FormatPvrtc24bppSrgbBlockImg = 1000054007, } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using gView.Framework.UI; using gView.Framework.system; using gView.Framework.IO; using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.system.UI; using gView.Framework.FDB; using gView.OGC; using gView.Framework.Db.UI; using gView.Framework.OGC.UI; using gView.Framework.Globalisation; using System.Windows.Forms; namespace gView.DataSources.MSSqlSpatial.UI { [gView.Framework.system.RegisterPlugIn("25F9A2DE-D54F-4DCD-832A-C2EFB544CF8F")] public class MsSql2008SpatialExplorerGroupObject : ExplorerParentObject, IOgcGroupExplorerObject { private IExplorerIcon _icon = new MsSql2008SpatialIcon(); public MsSql2008SpatialExplorerGroupObject() : base(null, null, 0) { } #region IExplorerGroupObject Members public IExplorerIcon Icon { get { return _icon; } } #endregion #region IExplorerObject Members public string Name { get { return "MsSql 2008 Spatial Geometry"; } } public string FullName { get { return @"OGC\MsSql2008Spatial"; } } public string Type { get { return "MsSql Spatial Connection"; } } public new object Object { get { return null; } } public IExplorerObject CreateInstanceByFullName(string FullName) { return null; } #endregion #region IExplorerParentObject Members public override void Refresh() { base.Refresh(); base.AddChildObject(new MsSql2008SpatialNewConnectionObject(this)); ConfigTextStream stream = new ConfigTextStream("MsSql2008Spatial_connections"); string connStr, id; while ((connStr = stream.Read(out id)) != null) { base.AddChildObject(new MsSql2008SpatialExplorerObject(this, id, connStr)); } stream.Close(); } #endregion #region ISerializableExplorerObject Member public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache) { if (cache.Contains(FullName)) return cache[FullName]; if (this.FullName == FullName) { MsSql2008SpatialExplorerGroupObject exObject = new MsSql2008SpatialExplorerGroupObject(); cache.Append(exObject); return exObject; } return null; } #endregion } [gView.Framework.system.RegisterPlugIn("1039B5BC-9460-40FC-8837-9A87EDFBBA8E")] public class MsSql2008SpatialNewConnectionObject : ExplorerObjectCls, IExplorerSimpleObject, IExplorerObjectDoubleClick, IExplorerObjectCreatable { private IExplorerIcon _icon = new MsSql2008SpatialNewConnectionIcon(); public MsSql2008SpatialNewConnectionObject() : base(null, null, 0) { } public MsSql2008SpatialNewConnectionObject(IExplorerObject parent) : base(parent, null, 0) { } #region IExplorerSimpleObject Members public IExplorerIcon Icon { get { return _icon; } } #endregion #region IExplorerObject Members public string Name { get { return LocalizedResources.GetResString("String.NewConnection", "New Connection..."); } } public string FullName { get { return ""; } } public string Type { get { return "New MsSql 2008 Spatial Connection"; } } public void Dispose() { } public new object Object { get { return null; } } public IExplorerObject CreateInstanceByFullName(string FullName) { return null; } #endregion #region IExplorerObjectDoubleClick Members public void ExplorerObjectDoubleClick(ExplorerObjectEventArgs e) { FormConnectionString dlg = new FormConnectionString(); dlg.ProviderID = "mssql"; dlg.UseProviderInConnectionString = false; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string connStr = dlg.ConnectionString; ConfigTextStream stream = new ConfigTextStream("MsSql2008Spatial_connections", true, true); string id = ConfigTextStream.ExtractValue(connStr, "Database"); id += "@" + ConfigTextStream.ExtractValue(connStr, "Server"); if (id == "@") id = "MsSql 2008 Spatial Connection"; stream.Write(connStr, ref id); stream.Close(); e.NewExplorerObject = new MsSql2008SpatialExplorerObject(this.ParentExplorerObject, id, dlg.ConnectionString); } } #endregion #region ISerializableExplorerObject Member public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache) { if (cache.Contains(FullName)) return cache[FullName]; return null; } #endregion #region IExplorerObjectCreatable Member public bool CanCreate(IExplorerObject parentExObject) { return (parentExObject is MsSql2008SpatialExplorerGroupObject); } public IExplorerObject CreateExplorerObject(IExplorerObject parentExObject) { ExplorerObjectEventArgs e = new ExplorerObjectEventArgs(); ExplorerObjectDoubleClick(e); return e.NewExplorerObject; } #endregion } public class MsSql2008SpatialExplorerObject : gView.Framework.OGC.UI.ExplorerObjectFeatureClassImport, IExplorerSimpleObject, IExplorerObjectDeletable, IExplorerObjectRenamable, ISerializableExplorerObject { private MsSql2008SpatialIcon _icon = new MsSql2008SpatialIcon(); private string _server = "", _connectionString = "", _errMsg = ""; private IFeatureDataset _dataset; public MsSql2008SpatialExplorerObject() : base(null,typeof(IFeatureDataset)) { } public MsSql2008SpatialExplorerObject(IExplorerObject parent, string server, string connectionString) : base(parent,typeof(IFeatureDataset)) { _server = server; _connectionString = connectionString; } internal string ConnectionString { get { return _connectionString; } } #region IExplorerObject Members public string Name { get { return _server; } } public string FullName { get { return @"OGC\MsSql2008Spatial\" + _server; } } public string Type { get { return "MsSql2008Spatial Database"; } } public IExplorerIcon Icon { get { return _icon; } } public object Object { get { if (_dataset != null) _dataset.Dispose(); _dataset = new GeometryDataset(); _dataset.ConnectionString = _connectionString; _dataset.Open(); return _dataset; } } #endregion #region IExplorerParentObject Members public override void Refresh() { base.Refresh(); GeometryDataset dataset = new GeometryDataset(); dataset.ConnectionString = _connectionString; dataset.Open(); List<IDatasetElement> elements = dataset.Elements; if (elements == null) return; foreach (IDatasetElement element in elements) { if (element.Class is IFeatureClass) { base.AddChildObject(new MsSql2008SpatialFeatureClassExplorerObject(this, element)); } } } #endregion #region ISerializableExplorerObject Member public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache) { if (cache.Contains(FullName)) return cache[FullName]; MsSql2008SpatialExplorerGroupObject group = new MsSql2008SpatialExplorerGroupObject(); if (FullName.IndexOf(group.FullName) != 0 || FullName.Length < group.FullName.Length + 2) return null; group = (MsSql2008SpatialExplorerGroupObject)((cache.Contains(group.FullName)) ? cache[group.FullName] : group); foreach (IExplorerObject exObject in group.ChildObjects) { if (exObject.FullName == FullName) { cache.Append(exObject); return exObject; } } return null; } #endregion #region IExplorerObjectDeletable Member public event ExplorerObjectDeletedEvent ExplorerObjectDeleted = null; public bool DeleteExplorerObject(ExplorerObjectEventArgs e) { ConfigTextStream stream = new ConfigTextStream("MsSql2008Spatial_connections", true, true); stream.Remove(this.Name, _connectionString); stream.Close(); if (ExplorerObjectDeleted != null) ExplorerObjectDeleted(this); return true; } #endregion #region IExplorerObjectRenamable Member public event ExplorerObjectRenamedEvent ExplorerObjectRenamed = null; public bool RenameExplorerObject(string newName) { bool ret = false; ConfigTextStream stream = new ConfigTextStream("MsSql2008Spatial_connections", true, true); ret = stream.ReplaceHoleLine(ConfigTextStream.BuildLine(_server, _connectionString), ConfigTextStream.BuildLine(newName, _connectionString)); stream.Close(); if (ret == true) { _server = newName; if (ExplorerObjectRenamed != null) ExplorerObjectRenamed(this); } return ret; } #endregion } [gView.Framework.system.RegisterPlugIn("BAC5EF61-8E60-48D5-9744-4260BDCDBD56")] public class MsSql2008SpatialFeatureClassExplorerObject : ExplorerObjectCls, IExplorerSimpleObject, ISerializableExplorerObject, IExplorerObjectDeletable { private string _fcname = "", _type = ""; private IExplorerIcon _icon = null; private IFeatureClass _fc = null; private MsSql2008SpatialExplorerObject _parent = null; public MsSql2008SpatialFeatureClassExplorerObject() : base(null,typeof(IFeatureClass), 1) { } public MsSql2008SpatialFeatureClassExplorerObject(MsSql2008SpatialExplorerObject parent, IDatasetElement element) : base(parent,typeof(IFeatureClass), 1) { if (element == null || !(element.Class is IFeatureClass)) return; _parent = parent; _fcname = element.Title; if (element.Class is IFeatureClass) { _fc = (IFeatureClass)element.Class; switch (_fc.GeometryType) { case geometryType.Envelope: case geometryType.Polygon: _icon = new MsSql2008SpatialPolygonIcon(); _type = "Polygon Featureclass"; break; case geometryType.Multipoint: case geometryType.Point: _icon = new MsSql2008SpatialPointIcon(); _type = "Point Featureclass"; break; case geometryType.Polyline: _icon = new MsSql2008SpatialLineIcon(); _type = "Polyline Featureclass"; break; default: _icon = new MsSql2008SpatialLineIcon(); _type = "Featureclass"; break; } } } internal string ConnectionString { get { if (_parent == null) return ""; return _parent.ConnectionString; } } #region IExplorerObject Members public string Name { get { return _fcname; } } public string FullName { get { if (_parent == null) return ""; return _parent.FullName + @"\" + this.Name; } } public string Type { get { return _type; } } public IExplorerIcon Icon { get { return _icon; } } public void Dispose() { if (_fc != null) { _fc = null; } } public object Object { get { return _fc; } } #endregion #region ISerializableExplorerObject Member public IExplorerObject CreateInstanceByFullName(string FullName, ISerializableExplorerObjectCache cache) { if (cache.Contains(FullName)) return cache[FullName]; FullName = FullName.Replace("/", @"\"); int lastIndex = FullName.LastIndexOf(@"\"); if (lastIndex == -1) return null; string dsName = FullName.Substring(0, lastIndex); string fcName = FullName.Substring(lastIndex + 1, FullName.Length - lastIndex - 1); MsSql2008SpatialExplorerObject dsObject = new MsSql2008SpatialExplorerObject(); dsObject = dsObject.CreateInstanceByFullName(dsName, cache) as MsSql2008SpatialExplorerObject; if (dsObject == null || dsObject.ChildObjects == null) return null; foreach (IExplorerObject exObject in dsObject.ChildObjects) { if (exObject.Name == fcName) { cache.Append(exObject); return exObject; } } return null; } #endregion #region IExplorerObjectDeletable Member public event ExplorerObjectDeletedEvent ExplorerObjectDeleted; public bool DeleteExplorerObject(ExplorerObjectEventArgs e) { if (_parent.Object is IFeatureDatabase) { if (((IFeatureDatabase)_parent.Object).DeleteFeatureClass(this.Name)) { if (ExplorerObjectDeleted != null) ExplorerObjectDeleted(this); return true; } else { MessageBox.Show("ERROR: " + ((IFeatureDatabase)_parent.Object).lastErrorMsg); return false; } } return false; } #endregion } class MsSql2008SpatialIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("B22782D4-59D2-448a-A531-DE29B0067DE6"); } } public System.Drawing.Image Image { get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.cat6; } } #endregion } class MsSql2008SpatialNewConnectionIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("56943EE9-DCE8-4ad9-9F13-D306A8A9210E"); } } public System.Drawing.Image Image { get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.gps_point; } } #endregion } public class MsSql2008SpatialPointIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("372EBA30-1F19-4109-B476-8B158CAA6360"); } } public System.Drawing.Image Image { get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.img_32; } } #endregion } public class MsSql2008SpatialLineIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("5EA3477F-7616-4775-B233-72C94BE055CA"); } } public System.Drawing.Image Image { get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.img_33; } } #endregion } public class MsSql2008SpatialPolygonIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("D1297B06-4306-4d5d-BBC6-10E26792CE5F"); } } public System.Drawing.Image Image { get { return global::gView.DataSources.MSSqlSpatial.UI.Properties.Resources.img_34; } } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; using Security.Cryptography.Properties; namespace Security.Cryptography { /// <summary> /// <para> /// The AuthenticatedSymmetricAlgorithm abstract base class forms the base class for symmetric /// algorithms which support authentication as well as encryption. Authenticated symmetric /// algorithms produce an authentication tag in addition to ciphertext, which allows data to be /// both authenticated and protected for privacy. For instance, AES with CCM or GCM chaining modes /// provides authentication, and therefore derive from AuthenticatedSymmetricAlgorithm. /// </para> /// <para> /// AuthenticatedSymmetricAlgorithm derives from <see cref="SymmetricAlgorithm" />, so all of the /// SymmetricAlgorithm APIs also apply to AuthenticatedSymmericAlgorithm objects. /// </para> /// </summary> public abstract class AuthenticatedSymmetricAlgorithm : SymmetricAlgorithm { private byte[] m_authenticatedData; private byte[] m_tag; // // Tag size values - these are protected fields without array copy semantics to behave similar to // the KeySize / IVSize mechanisms // /// <summary> /// The LegalTagSizes field is set by authenticated symmetric algorithm implementations to be the /// set of valid authentication tag sizes expressed in bits. /// </summary> [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Consistency with other SymmetricAlgorithm APIs (LegalKeySizesValue, LegalBlockSizesValue")] protected KeySizes[] LegalTagSizesValue; /// <summary> /// The TagSizeValue field contains the current authentication tag size used by the authenticated /// symmetric algorithm, expressed in bits. /// </summary> [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Justification = "Consistency with other SymmetricAlgorithm APIs (KeyValue, BlockValue, etc)")] protected int TagSizeValue; /// <summary> /// <para> /// Gets or sets the authenticated data buffer. /// </para> /// <para> /// This data is included in calculations of the authentication tag, but is not included in /// the ciphertext. A value of null means that there is no additional authenticated data. /// </para> /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Consistency with the other SymmetricAlgorithm API (Key, IV, etc)")] public virtual byte[] AuthenticatedData { get { return m_authenticatedData != null ? m_authenticatedData.Clone() as byte[] : null; } set { if (value != null) { m_authenticatedData = value.Clone() as byte[]; } else { m_authenticatedData = null; } } } /// <summary> /// Get or set the IV (nonce) to use with transorms created with this object. /// </summary> /// <exception cref="ArgumentNullException">if set to null</exception> public override byte[] IV { // Note that we override the base implementation because it requires that the nonce equal the // block size, while in general authenticated transforms do not. get { if (IVValue == null) { GenerateIV(); } return IVValue.Clone() as byte[]; } set { if (value == null) throw new ArgumentNullException("value"); IVValue = value.Clone() as byte[]; } } /// <summary> /// Gets the ranges of legal sizes for authentication tags produced by this algorithm, expressed /// in bits. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Consistency with other SymmetricAlgorithm APIs (LegalKeySizes, LegalBlockSizes)")] public virtual KeySizes[] LegalTagSizes { get { return LegalTagSizesValue.Clone() as KeySizes[]; } } /// <summary> /// Gets or sets the authentication tag to use when verifying a decryption operation. This /// value is only read for decryption operaions, and is not used for encryption operations. To /// find the value of the tag generated on encryption, check the Tag property of the /// IAuthenticatedCryptoTransform encryptor object. /// </summary> /// <exception cref="ArgumentNullException">if the tag is set to null</exception> /// <exception cref="ArgumentException">if the tag is not a legal size</exception> [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Consistency with other SymmetricAlgorithm APIs (Key, IV)")] public virtual byte[] Tag { get { if (m_tag == null) { m_tag = new byte[TagSizeValue / 8]; } return m_tag.Clone() as byte[]; } set { if (value == null) throw new ArgumentNullException("value"); if (!ValidTagSize(value.Length * 8)) throw new ArgumentException(Resources.InvalidTagSize, "value"); m_tag = value.Clone() as byte[]; TagSizeValue = m_tag.Length * 8; } } /// <summary> /// Get or set the size (in bits) of the authentication tag /// </summary> /// <exception cref="ArgumentException">if the value is not a legal tag size</exception> public virtual int TagSize { get { return TagSizeValue; } set { if (!ValidTagSize(value)) throw new ArgumentOutOfRangeException(Resources.InvalidTagSize); TagSizeValue = value; m_tag = null; } } /// <summary> /// Creates an instance of the default AuthenticatedSymmetricAlgorithm registered in /// <see cref="CryptoConfig2" />. By default, this is the <see cref="AuthenticatedAesCng" /> /// algorithm. /// </summary> public static new AuthenticatedSymmetricAlgorithm Create() { return Create(typeof(AuthenticatedSymmetricAlgorithm).Name); } /// <summary> /// Create an instance of the specified AuthenticatedSymmetricAlgorithm type. If the type cannot /// be found in <see cref="CryptoConfig2" />, Create returns null. /// </summary> /// <param name="algorithm">name of the authenticated symmetric algorithm to create</param> /// <exception cref="ArgumentNullException">if <paramref name="algorithm"/> is null</exception> public static new AuthenticatedSymmetricAlgorithm Create(string algorithm) { if (algorithm == null) throw new ArgumentNullException("algorithm"); return CryptoConfig2.CreateFromName(algorithm) as AuthenticatedSymmetricAlgorithm; } /// <summary> /// Create an authenticated encryptor using the key, nonce, and authenticated data from the /// properties of this algorithm object. /// </summary> public virtual IAuthenticatedCryptoTransform CreateAuthenticatedEncryptor() { return CreateAuthenticatedEncryptor(Key, IV, AuthenticatedData); } /// <summary> /// Create an authenticated encryptor using the specified key and nonce, and using the /// authenticated data from the property of this algorithm object. /// </summary> /// <param name="rgbKey">key to use for the encryption operation</param> /// <param name="rgbIV">nonce to use for the encryption operation</param> public virtual IAuthenticatedCryptoTransform CreateAuthenticatedEncryptor(byte[] rgbKey, byte[] rgbIV) { return CreateAuthenticatedEncryptor(rgbKey, rgbIV, AuthenticatedData); } /// <summary> /// Create an authenticated encryptor using the specified key, nonce, and authenticated data. /// </summary> /// <param name="rgbKey">key to use for the encryption operation</param> /// <param name="rgbIV">nonce to use for the encryption operation</param> /// <param name="rgbAuthenticatedData">optional extra authenticated data to use for the encryption operation</param> public abstract IAuthenticatedCryptoTransform CreateAuthenticatedEncryptor(byte[] rgbKey, byte[] rgbIV, byte[] rgbAuthenticatedData); /// <summary> /// Create a decryptor using the key, nonce, authenticated data, and authentication tag from the /// properties of this algorithm object. /// </summary> public override ICryptoTransform CreateDecryptor() { return CreateDecryptor(Key, IV, AuthenticatedData, Tag); } /// <summary> /// Create a decryptor with the given key and nonce, using the authenticated data and /// authentication tag from the properties of the algorithm object. /// </summary> /// <param name="rgbKey">key to use for the decryption operation</param> /// <param name="rgbIV">nonce to use for the decryption operation</param> public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { return CreateDecryptor(rgbKey, rgbIV, AuthenticatedData, Tag); } /// <summary> /// Create a decryption transform with the given key, nonce, authenticated data, and /// authentication tag. /// </summary> /// <param name="rgbKey">key to use for the decryption operation</param> /// <param name="rgbIV">nonce to use for the decryption operation</param> /// <param name="rgbAuthenticatedData">optional extra authenticated data to use for the decryption operation</param> /// <param name="rgbTag">authenticated tag to verify while decrypting</param> public abstract ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV, byte[] rgbAuthenticatedData, byte[] rgbTag); /// <summary> /// Create an encryptor using the given key and nonce, and the authenticated data from this /// algorithm. /// </summary> public override ICryptoTransform CreateEncryptor() { return CreateAuthenticatedEncryptor(); } /// <summary> /// Create an encryptor using the given key and nonce, and the authenticated data from this /// algorithm. /// </summary> public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { return CreateAuthenticatedEncryptor(rgbKey, rgbIV); } /// <summary> /// Determine if an authentication tag size (in bits) is valid for use with this algorithm. /// </summary> /// <param name="tagSize">authentication tag size in bits to check</param> public bool ValidTagSize(int tagSize) { // If we don't have any valid tag sizes, then no tag is of the correct size if (LegalTagSizes == null) { return false; } // Loop over all of the legal size ranges, and see if we match any of them foreach (KeySizes legalTagSizeRange in LegalTagSizes) { for (int legalTagSize = legalTagSizeRange.MinSize; legalTagSize <= legalTagSizeRange.MaxSize; legalTagSize += legalTagSizeRange.SkipSize) { if (legalTagSize == tagSize) { return true; } } } // No matches - this isn't a valid tag size return false; } } }
using System; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel.Channels; using System.Web; using System.Xml; using ServiceStack.Common.Web; using ServiceStack.ServiceClient.Web; using ServiceStack.ServiceHost; using ServiceStack.ServiceModel.Serialization; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Extensions; using ServiceStack.WebHost.Endpoints.Utils; namespace ServiceStack.WebHost.Endpoints.Support { public class SoapHandler : EndpointHandlerBase, IOneWay, ISyncReply { public SoapHandler(EndpointAttributes soapType) { this.HandlerAttributes = soapType; } public void SendOneWay(Message requestMsg) { var endpointAttributes = EndpointAttributes.AsyncOneWay | this.HandlerAttributes; ExecuteMessage(requestMsg, endpointAttributes); } public Message Send(Message requestMsg) { var endpointAttributes = EndpointAttributes.SyncReply | this.HandlerAttributes; return ExecuteMessage(requestMsg, endpointAttributes); } public Message EmptyResponse(Message requestMsg, Type requestType) { var responseType = AssemblyUtils.FindType(requestType.FullName + "Response"); var response = (responseType ?? typeof(object)).CreateInstance(); return requestMsg.Headers.Action == null ? Message.CreateMessage(requestMsg.Version, null, response) : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response); } protected Message ExecuteMessage(Message requestMsg, EndpointAttributes endpointAttributes) { if ((EndpointAttributes.Soap11 & this.HandlerAttributes) == EndpointAttributes.Soap11) EndpointHost.Config.AssertFeatures(Feature.Soap11); else if ((EndpointAttributes.Soap12 & this.HandlerAttributes) == EndpointAttributes.Soap12) EndpointHost.Config.AssertFeatures(Feature.Soap12); string requestXml; using (var reader = requestMsg.GetReaderAtBodyContents()) { requestXml = reader.ReadOuterXml(); } var requestType = GetRequestType(requestMsg, requestXml); try { var request = DataContractDeserializer.Instance.Parse(requestXml, requestType); var httpReq = HttpContext.Current != null ? new HttpRequestWrapper(requestType.Name, HttpContext.Current.Request) : null; var httpRes = HttpContext.Current != null ? new HttpResponseWrapper(HttpContext.Current.Response) : null; if (EndpointHost.ApplyPreRequestFilters(httpReq, httpRes)) return EmptyResponse(requestMsg, requestType); var hasRequestFilters = EndpointHost.RequestFilters.Count > 0 || FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).Any(); if (hasRequestFilters && EndpointHost.ApplyRequestFilters(httpReq, httpRes, request)) return EmptyResponse(requestMsg, requestType); var response = ExecuteService(request, endpointAttributes, httpReq, httpRes); var hasResponseFilters = EndpointHost.ResponseFilters.Count > 0 || FilterAttributeCache.GetResponseFilterAttributes(response.GetType()).Any(); if (hasResponseFilters && EndpointHost.ApplyResponseFilters(httpReq, httpRes, response)) return EmptyResponse(requestMsg, requestType); var httpResult = response as IHttpResult; if (httpResult != null) response = httpResult.Response; return requestMsg.Headers.Action == null ? Message.CreateMessage(requestMsg.Version, null, response) : Message.CreateMessage(requestMsg.Version, requestType.Name + "Response", response); } catch (Exception ex) { throw new SerializationException("3) Error trying to deserialize requestType: " + requestType + ", xml body: " + requestXml, ex); } } protected static Message GetSoap12RequestMessage(HttpContext context) { return GetRequestMessage(context, MessageVersion.Soap12WSAddressingAugust2004); } protected static Message GetSoap11RequestMessage(HttpContext context) { return GetRequestMessage(context, MessageVersion.Soap11WSAddressingAugust2004); } protected static Message GetRequestMessage(HttpContext context, MessageVersion msgVersion) { using (var sr = new StreamReader(context.Request.InputStream)) { var requestXml = sr.ReadToEnd(); var doc = new XmlDocument(); doc.LoadXml(requestXml); var msg = Message.CreateMessage(new XmlNodeReader(doc), int.MaxValue, msgVersion); return msg; } } protected Type GetRequestType(Message requestMsg, string xml) { var action = GetAction(requestMsg, xml); var operationType = EndpointHost.ServiceOperations.GetOperationType(action); AssertOperationExists(action, operationType); return operationType; } protected string GetAction(Message requestMsg, string xml) { var action = GetActionFromHttpContext(); if (action != null) return action; if (requestMsg.Headers.Action != null) { return requestMsg.Headers.Action; } return xml.StartsWith("<") ? xml.Substring(1, xml.IndexOf(" ") - 1).SplitOnFirst(':').Last() : null; } protected static string GetActionFromHttpContext() { var context = HttpContext.Current; return GetAction(context); } private static string GetAction(HttpContext context) { if (context != null) { var contentType = context.Request.ContentType; return GetOperationName(contentType); } return null; } private static string GetOperationName(string contentType) { var urlActionPos = contentType.IndexOf("action=\""); if (urlActionPos != -1) { var startIndex = urlActionPos + "action=\"".Length; var urlAction = contentType.Substring( startIndex, contentType.IndexOf('"', startIndex) - startIndex); var parts = urlAction.Split('/'); var operationName = parts.Last(); return operationName; } return null; } public string GetSoapContentType(HttpContext context) { var requestOperationName = GetAction(context); return requestOperationName != null ? context.Request.ContentType.Replace(requestOperationName, requestOperationName + "Response") : (this.HandlerAttributes == EndpointAttributes.Soap11 ? ContentType.Soap11 : ContentType.Soap12); } public override object CreateRequest(IHttpRequest request, string operationName) { throw new NotImplementedException(); } public override object GetResponse(IHttpRequest httpReq, IHttpResponse httpRes, object request) { throw new NotImplementedException(); } } }
using System; using System.Drawing; using System.Windows.Forms; using SIL.Windows.Forms; using SIL.Windows.Forms.Miscellaneous; using SIL.Windows.Forms.PortableSettingsProvider; namespace SIL.Archiving { /// ---------------------------------------------------------------------------------------- public partial class ArchivingDlg : Form { private readonly FormSettings _settings; protected readonly ArchivingDlgViewModel _viewModel; protected readonly string _launchButtonTextFormat; /// ------------------------------------------------------------------------------------ /// <summary>Caller can use this to retrieve and persist form settings (typically /// after form is closed).</summary> /// ------------------------------------------------------------------------------------ public FormSettings FormSettings { get { return _settings; } } /// ------------------------------------------------------------------------------------ /// <param name="model">View model</param> /// <param name="localizationManagerId">The ID of the localization manager for the /// calling application.</param> /// <param name="programDialogFont">Application can set this to ensure a consistent look /// in the UI (especially useful for when a localization requires a particular font).</param> /// <param name="settings">Location, size, and state where the client would like the /// dialog box to appear (can be null)</param> /// ------------------------------------------------------------------------------------ public ArchivingDlg(ArchivingDlgViewModel model, string localizationManagerId, Font programDialogFont, FormSettings settings) { _settings = settings ?? FormSettings.Create(this); _viewModel = model; InitializeComponent(); if (!string.IsNullOrEmpty(localizationManagerId)) locExtender.LocalizationManagerId = localizationManagerId; Text = string.Format(Text, model.AppName, model.ArchiveType); _progressBar.Visible = false; // remember this because we will need it later in a derived class _launchButtonTextFormat = _buttonLaunchRamp.Text; UpdateLaunchButtonText(); _buttonLaunchRamp.Enabled = false; //!string.IsNullOrEmpty(model.PathToProgramToLaunch); _chkMetadataOnly.Visible = _viewModel is ISupportMetadataOnly; _linkOverview.Text = model.InformativeText; _linkOverview.Links.Clear(); if (!string.IsNullOrEmpty(model.ArchiveInfoUrl) && !string.IsNullOrEmpty(model.ArchiveInfoHyperlinkText)) { int i = _linkOverview.Text.IndexOf(model.ArchiveInfoHyperlinkText, StringComparison.InvariantCulture); if (i >= 0) _linkOverview.Links.Add(i, model.ArchiveInfoHyperlinkText.Length, model.ArchiveInfoUrl); } // this is for a display problem in mono _linkOverview.SizeToContents(); _logBox.Tag = false; model.OnDisplayMessage += DisplayMessage; model.OnDisplayError += new ArchivingDlgViewModel.DisplayErrorEventHandler(model_DisplayError); if (programDialogFont != null) { _linkOverview.Font = programDialogFont; _logBox.Font = FontHelper.MakeFont(programDialogFont, FontStyle.Bold); _buttonCancel.Font = programDialogFont; _buttonCreatePackage.Font = programDialogFont; _buttonLaunchRamp.Font = programDialogFont; Font = programDialogFont; } _buttonLaunchRamp.Click += (s, e) => model.LaunchArchivingProgram(); _buttonCancel.MouseLeave += delegate { if (model.IsBusy) WaitCursor.Show(); }; _buttonCancel.MouseEnter += delegate { if (model.IsBusy) WaitCursor.Hide(); }; _buttonCancel.Click += delegate { model.Cancel(); WaitCursor.Hide(); }; } private void CreatePackage(object sender, EventArgs eventArgs) { Focus(); DisableControlsDuringPackageCreation(); _progressBar.Visible = true; WaitCursor.Show(); _logBox.Clear(); _buttonLaunchRamp.Enabled = _viewModel.CreatePackage(); _progressBar.Visible = false; WaitCursor.Hide(); } protected virtual void DisableControlsDuringPackageCreation() { _buttonCreatePackage.Enabled = false; _chkMetadataOnly.Enabled = false; } /// ------------------------------------------------------------------------------------ protected void UpdateLaunchButtonText() { _buttonLaunchRamp.Text = string.Format(_launchButtonTextFormat, _viewModel.NameOfProgramToLaunch); } /// ------------------------------------------------------------------------------------ protected void UpdateOverviewText() { _linkOverview.Text = _viewModel.InformativeText; } /// ------------------------------------------------------------------------------------ void DisplayMessage(string msg, ArchivingDlgViewModel.MessageType type) { if ((bool) _logBox.Tag) { _logBox.Clear(); _logBox.Tag = false; } switch (type) { case ArchivingDlgViewModel.MessageType.Normal: _logBox.WriteMessage(msg); break; case ArchivingDlgViewModel.MessageType.Indented: _logBox.WriteMessage(Environment.NewLine + " " + msg); break; case ArchivingDlgViewModel.MessageType.Detail: _logBox.WriteMessageWithFontStyle(FontStyle.Regular, "\t" + msg); break; case ArchivingDlgViewModel.MessageType.Bullet: _logBox.WriteMessageWithFontStyle(FontStyle.Regular, " \u00B7 {0}", msg); break; case ArchivingDlgViewModel.MessageType.Progress: _logBox.WriteMessage(Environment.NewLine + msg); break; case ArchivingDlgViewModel.MessageType.Warning: _logBox.WriteWarning(msg); break; case ArchivingDlgViewModel.MessageType.Error: _logBox.WriteMessageWithColor("Red", msg + Environment.NewLine); break; case ArchivingDlgViewModel.MessageType.Success: _logBox.WriteMessageWithColor(Color.DarkGreen, Environment.NewLine + msg); break; case ArchivingDlgViewModel.MessageType.Volatile: _logBox.WriteMessage(msg); _logBox.Tag = true; break; } } /// ------------------------------------------------------------------------------------ void model_DisplayError(string msg, string packageTitle, Exception e) { if (_logBox.IsHandleCreated) { WaitCursor.Hide(); _logBox.WriteError(msg, packageTitle); if (e != null) _logBox.WriteException(e); } } /// ------------------------------------------------------------------------------------ protected override void OnLoad(EventArgs e) { _settings.InitializeForm(this); base.OnLoad(e); } /// ------------------------------------------------------------------------------------ protected override void OnShown(EventArgs e) { base.OnShown(e); try { WaitCursor.Show(); _viewModel.IncrementProgressBarAction = () => _progressBar.Increment(1); _buttonCreatePackage.Enabled = _viewModel.Initialize(); _logBox.ScrollToTop(); _progressBar.Maximum = _viewModel.CalculateMaxProgressBarValue(); WaitCursor.Hide(); } catch { WaitCursor.Hide(); throw; } } /// ------------------------------------------------------------------------------------ private void HandleRampLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { var tgt = e.Link.LinkData as string; if (!string.IsNullOrEmpty(tgt)) System.Diagnostics.Process.Start(tgt); } /// ------------------------------------------------------------------------------------ private void HandleLogBoxReportErrorLinkClicked(object sender, EventArgs e) { Close(); } private void _chkMetadataOnly_CheckedChanged(object sender, EventArgs e) { ((ISupportMetadataOnly)_viewModel).MetadataOnly = _chkMetadataOnly.Checked; } } }
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 WootzJs.Site.Api.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ActionDescriptor.ReturnType; 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 file="HttpClientTests.Basic.netcore31.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if NETCOREAPP3_1_OR_GREATER using System; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Moq; using OpenTelemetry.Context; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Instrumentation.Http.Implementation; using OpenTelemetry.Tests; using OpenTelemetry.Trace; using Xunit; namespace OpenTelemetry.Instrumentation.Http.Tests { public partial class HttpClientTests : IDisposable { private readonly IDisposable serverLifeTime; private readonly string url; public HttpClientTests() { this.serverLifeTime = TestHttpServer.RunServer( (ctx) => { ctx.Response.StatusCode = 200; ctx.Response.OutputStream.Close(); }, out var host, out var port); this.url = $"http://{host}:{port}/"; } [Fact] public void AddHttpClientInstrumentation_BadArgs() { TracerProviderBuilder builder = null; Assert.Throws<ArgumentNullException>(() => builder.AddHttpClientInstrumentation()); } [Theory] [InlineData(true)] [InlineData(false)] public async Task HttpClientInstrumentationInjectsHeadersAsync(bool shouldEnrich) { var processor = new Mock<BaseProcessor<Activity>>(); processor.Setup(x => x.OnStart(It.IsAny<Activity>())).Callback<Activity>(c => c.SetTag("enriched", "no")); var request = new HttpRequestMessage { RequestUri = new Uri(this.url), Method = new HttpMethod("GET"), }; var parent = new Activity("parent") .SetIdFormat(ActivityIdFormat.W3C) .Start(); parent.TraceStateString = "k1=v1,k2=v2"; parent.ActivityTraceFlags = ActivityTraceFlags.Recorded; // var isInjectedHeaderValueGetterThrows = false; // mockTextFormat // .Setup(x => x.IsInjected(It.IsAny<HttpRequestMessage>(), It.IsAny<Func<HttpRequestMessage, string, IEnumerable<string>>>())) // .Callback<HttpRequestMessage, Func<HttpRequestMessage, string, IEnumerable<string>>>( // (carrier, getter) => // { // try // { // // traceparent doesn't exist // getter(carrier, "traceparent"); // } // catch // { // isInjectedHeaderValueGetterThrows = true; // } // }); using (Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation(o => { if (shouldEnrich) { o.Enrich = ActivityEnrichmentSetTag; } }) .AddProcessor(processor.Object) .Build()) { using var c = new HttpClient(); await c.SendAsync(request); } Assert.Equal(5, processor.Invocations.Count); // SetParentProvider/OnStart/OnEnd/OnShutdown/Dispose called. var activity = (Activity)processor.Invocations[2].Arguments[0]; Assert.Equal(ActivityKind.Client, activity.Kind); Assert.Equal(parent.TraceId, activity.Context.TraceId); Assert.Equal(parent.SpanId, activity.ParentSpanId); Assert.NotEqual(parent.SpanId, activity.Context.SpanId); Assert.NotEqual(default, activity.Context.SpanId); Assert.True(request.Headers.TryGetValues("traceparent", out var traceparents)); Assert.True(request.Headers.TryGetValues("tracestate", out var tracestates)); Assert.Single(traceparents); Assert.Single(tracestates); Assert.Equal($"00-{activity.Context.TraceId}-{activity.Context.SpanId}-01", traceparents.Single()); Assert.Equal("k1=v1,k2=v2", tracestates.Single()); Assert.NotEmpty(activity.Tags.Where(tag => tag.Key == "enriched")); Assert.Equal(shouldEnrich ? "yes" : "no", activity.Tags.Where(tag => tag.Key == "enriched").FirstOrDefault().Value); } [Theory] [InlineData(true)] [InlineData(false)] public async Task HttpClientInstrumentationInjectsHeadersAsync_CustomFormat(bool shouldEnrich) { var propagator = new Mock<TextMapPropagator>(); propagator.Setup(m => m.Inject<HttpRequestMessage>(It.IsAny<PropagationContext>(), It.IsAny<HttpRequestMessage>(), It.IsAny<Action<HttpRequestMessage, string, string>>())) .Callback<PropagationContext, HttpRequestMessage, Action<HttpRequestMessage, string, string>>((context, message, action) => { action(message, "custom_traceparent", $"00/{context.ActivityContext.TraceId}/{context.ActivityContext.SpanId}/01"); action(message, "custom_tracestate", Activity.Current.TraceStateString); }); var processor = new Mock<BaseProcessor<Activity>>(); var request = new HttpRequestMessage { RequestUri = new Uri(this.url), Method = new HttpMethod("GET"), }; var parent = new Activity("parent") .SetIdFormat(ActivityIdFormat.W3C) .Start(); parent.TraceStateString = "k1=v1,k2=v2"; parent.ActivityTraceFlags = ActivityTraceFlags.Recorded; Sdk.SetDefaultTextMapPropagator(propagator.Object); using (Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation((opt) => { if (shouldEnrich) { opt.Enrich = ActivityEnrichment; } }) .AddProcessor(processor.Object) .Build()) { using var c = new HttpClient(); await c.SendAsync(request); } Assert.Equal(5, processor.Invocations.Count); // SetParentProvider/OnStart/OnEnd/OnShutdown/Dispose called. var activity = (Activity)processor.Invocations[2].Arguments[0]; Assert.Equal(ActivityKind.Client, activity.Kind); Assert.Equal(parent.TraceId, activity.Context.TraceId); Assert.Equal(parent.SpanId, activity.ParentSpanId); Assert.NotEqual(parent.SpanId, activity.Context.SpanId); Assert.NotEqual(default, activity.Context.SpanId); Assert.True(request.Headers.TryGetValues("custom_traceparent", out var traceparents)); Assert.True(request.Headers.TryGetValues("custom_tracestate", out var tracestates)); Assert.Single(traceparents); Assert.Single(tracestates); Assert.Equal($"00/{activity.Context.TraceId}/{activity.Context.SpanId}/01", traceparents.Single()); Assert.Equal("k1=v1,k2=v2", tracestates.Single()); Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[] { new TraceContextPropagator(), new BaggagePropagator(), })); } [Fact] public async Task HttpClientInstrumentationRespectsSuppress() { try { var propagator = new Mock<TextMapPropagator>(); propagator.Setup(m => m.Inject<HttpRequestMessage>(It.IsAny<PropagationContext>(), It.IsAny<HttpRequestMessage>(), It.IsAny<Action<HttpRequestMessage, string, string>>())) .Callback<PropagationContext, HttpRequestMessage, Action<HttpRequestMessage, string, string>>((context, message, action) => { action(message, "custom_traceparent", $"00/{context.ActivityContext.TraceId}/{context.ActivityContext.SpanId}/01"); action(message, "custom_tracestate", Activity.Current.TraceStateString); }); var processor = new Mock<BaseProcessor<Activity>>(); var request = new HttpRequestMessage { RequestUri = new Uri(this.url), Method = new HttpMethod("GET"), }; var parent = new Activity("parent") .SetIdFormat(ActivityIdFormat.W3C) .Start(); parent.TraceStateString = "k1=v1,k2=v2"; parent.ActivityTraceFlags = ActivityTraceFlags.Recorded; Sdk.SetDefaultTextMapPropagator(propagator.Object); using (Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation() .AddProcessor(processor.Object) .Build()) { using var c = new HttpClient(); using (SuppressInstrumentationScope.Begin()) { await c.SendAsync(request); } } // If suppressed, activity is not emitted and // propagation is also not performed. Assert.Equal(3, processor.Invocations.Count); // SetParentProvider/OnShutdown/Dispose called. Assert.False(request.Headers.Contains("custom_traceparent")); Assert.False(request.Headers.Contains("custom_tracestate")); } finally { Sdk.SetDefaultTextMapPropagator(new CompositeTextMapPropagator(new TextMapPropagator[] { new TraceContextPropagator(), new BaggagePropagator(), })); } } [Fact] public async Task HttpClientInstrumentation_AddViaFactory_HttpInstrumentation_CollectsSpans() { var processor = new Mock<BaseProcessor<Activity>>(); using (Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation() .AddProcessor(processor.Object) .Build()) { using var c = new HttpClient(); await c.GetAsync(this.url); } Assert.Single(processor.Invocations.Where(i => i.Method.Name == "OnStart")); Assert.Single(processor.Invocations.Where(i => i.Method.Name == "OnEnd")); Assert.IsType<Activity>(processor.Invocations[1].Arguments[0]); } [Fact] public async Task HttpClientInstrumentationBacksOffIfAlreadyInstrumented() { // TODO: Investigate why this feature is required. var processor = new Mock<BaseProcessor<Activity>>(); var request = new HttpRequestMessage { RequestUri = new Uri(this.url), Method = new HttpMethod("GET"), }; request.Headers.Add("traceparent", "00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"); using (Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation() .AddProcessor(processor.Object) .Build()) { using var c = new HttpClient(); await c.SendAsync(request); } Assert.Equal(4, processor.Invocations.Count); // SetParentProvider/OnShutdown/Dispose/OnStart called. } [Fact] public async void RequestNotCollectedWhenInstrumentationFilterApplied() { var processor = new Mock<BaseProcessor<Activity>>(); using (Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation( (opt) => opt.Filter = (req) => !req.RequestUri.OriginalString.Contains(this.url)) .AddProcessor(processor.Object) .Build()) { using var c = new HttpClient(); await c.GetAsync(this.url); } Assert.Equal(4, processor.Invocations.Count); // SetParentProvider/OnShutdown/Dispose/OnStart called. } [Fact] public async void RequestNotCollectedWhenInstrumentationFilterThrowsException() { var processor = new Mock<BaseProcessor<Activity>>(); using (Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation( (opt) => opt.Filter = (req) => throw new Exception("From InstrumentationFilter")) .AddProcessor(processor.Object) .Build()) { using var c = new HttpClient(); using (var inMemoryEventListener = new InMemoryEventListener(HttpInstrumentationEventSource.Log)) { await c.GetAsync(this.url); Assert.Single(inMemoryEventListener.Events.Where((e) => e.EventId == 4)); } } Assert.Equal(4, processor.Invocations.Count); // SetParentProvider/OnShutdown/Dispose/OnStart called. } [Fact] public async Task HttpClientInstrumentationCorrelationAndBaggage() { var activityProcessor = new Mock<BaseProcessor<Activity>>(); using var parent = new Activity("w3c activity"); parent.SetIdFormat(ActivityIdFormat.W3C); parent.AddBaggage("k1", "v1"); parent.ActivityTraceFlags = ActivityTraceFlags.Recorded; parent.Start(); Baggage.SetBaggage("k2", "v2"); using (Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation(options => options.Enrich = ActivityEnrichment) .AddProcessor(activityProcessor.Object) .Build()) { using var c = new HttpClient(); using var r = await c.GetAsync(this.url).ConfigureAwait(false); } Assert.Equal(5, activityProcessor.Invocations.Count); } [Fact] public async Task HttpClientInstrumentationContextPropagation() { var processor = new Mock<BaseProcessor<Activity>>(); var request = new HttpRequestMessage { RequestUri = new Uri(this.url), Method = new HttpMethod("GET"), }; var parent = new Activity("parent") .SetIdFormat(ActivityIdFormat.W3C) .Start(); parent.TraceStateString = "k1=v1,k2=v2"; parent.ActivityTraceFlags = ActivityTraceFlags.Recorded; Baggage.SetBaggage("b1", "v1"); using (Sdk.CreateTracerProviderBuilder() .AddHttpClientInstrumentation() .AddProcessor(processor.Object) .Build()) { using var c = new HttpClient(); await c.SendAsync(request); } Assert.Equal(5, processor.Invocations.Count); // SetParentProvider/OnStart/OnEnd/OnShutdown/Dispose called. var activity = (Activity)processor.Invocations[1].Arguments[0]; Assert.Equal(ActivityKind.Client, activity.Kind); Assert.Equal(parent.TraceId, activity.Context.TraceId); Assert.Equal(parent.SpanId, activity.ParentSpanId); Assert.NotEqual(parent.SpanId, activity.Context.SpanId); Assert.NotEqual(default, activity.Context.SpanId); Assert.True(request.Headers.TryGetValues("traceparent", out var traceparents)); Assert.True(request.Headers.TryGetValues("tracestate", out var tracestates)); Assert.True(request.Headers.TryGetValues("baggage", out var baggages)); Assert.Single(traceparents); Assert.Single(tracestates); Assert.Single(baggages); Assert.Equal($"00-{activity.Context.TraceId}-{activity.Context.SpanId}-01", traceparents.Single()); Assert.Equal("k1=v1,k2=v2", tracestates.Single()); Assert.Equal("b1=v1", baggages.Single()); } public void Dispose() { this.serverLifeTime?.Dispose(); Activity.Current = null; } private static void ActivityEnrichmentSetTag(Activity activity, string method, object obj) { ActivityEnrichment(activity, method, obj); activity.SetTag("enriched", "yes"); } private static void ActivityEnrichment(Activity activity, string method, object obj) { switch (method) { case "OnStartActivity": Assert.True(obj is HttpRequestMessage); break; case "OnStopActivity": Assert.True(obj is HttpResponseMessage); break; case "OnException": Assert.True(obj is Exception); break; default: break; } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading.Tasks; namespace Microsoft.AspNetCore.Mvc.ModelBinding { /// <summary> /// Represents a <see cref="IValueProvider"/> whose values come from a collection of <see cref="IValueProvider"/>s. /// </summary> public class CompositeValueProvider : Collection<IValueProvider>, IEnumerableValueProvider, IBindingSourceValueProvider, IKeyRewriterValueProvider { /// <summary> /// Initializes a new instance of <see cref="CompositeValueProvider"/>. /// </summary> public CompositeValueProvider() { } /// <summary> /// Initializes a new instance of <see cref="CompositeValueProvider"/>. /// </summary> /// <param name="valueProviders">The sequence of <see cref="IValueProvider"/> to add to this instance of /// <see cref="CompositeValueProvider"/>.</param> public CompositeValueProvider(IList<IValueProvider> valueProviders) : base(valueProviders) { } /// <summary> /// Asynchronously creates a <see cref="CompositeValueProvider"/> using the provided /// <paramref name="controllerContext"/>. /// </summary> /// <param name="controllerContext">The <see cref="ControllerContext"/> associated with the current request.</param> /// <returns> /// A <see cref="Task{TResult}"/> which, when completed, asynchronously returns a /// <see cref="CompositeValueProvider"/>. /// </returns> public static async Task<CompositeValueProvider> CreateAsync(ControllerContext controllerContext) { if (controllerContext == null) { throw new ArgumentNullException(nameof(controllerContext)); } var factories = controllerContext.ValueProviderFactories; return await CreateAsync(controllerContext, factories); } /// <summary> /// Asynchronously creates a <see cref="CompositeValueProvider"/> using the provided /// <paramref name="actionContext"/>. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/> associated with the current request.</param> /// <param name="factories">The <see cref="IValueProviderFactory"/> to be applied to the context.</param> /// <returns> /// A <see cref="Task{TResult}"/> which, when completed, asynchronously returns a /// <see cref="CompositeValueProvider"/>. /// </returns> public static async Task<CompositeValueProvider> CreateAsync( ActionContext actionContext, IList<IValueProviderFactory> factories) { var valueProviderFactoryContext = new ValueProviderFactoryContext(actionContext); for (var i = 0; i < factories.Count; i++) { var factory = factories[i]; await factory.CreateValueProviderAsync(valueProviderFactoryContext); } return new CompositeValueProvider(valueProviderFactoryContext.ValueProviders); } internal static async ValueTask<(bool success, CompositeValueProvider? valueProvider)> TryCreateAsync( ActionContext actionContext, IList<IValueProviderFactory> factories) { try { var valueProvider = await CreateAsync(actionContext, factories); return (true, valueProvider); } catch (ValueProviderException exception) { actionContext.ModelState.TryAddModelException(key: string.Empty, exception); return (false, null); } } /// <inheritdoc /> public virtual bool ContainsPrefix(string prefix) { for (var i = 0; i < Count; i++) { if (this[i].ContainsPrefix(prefix)) { return true; } } return false; } /// <inheritdoc /> public virtual ValueProviderResult GetValue(string key) { // Performance-sensitive // Caching the count is faster for IList<T> var itemCount = Items.Count; for (var i = 0; i < itemCount; i++) { var valueProvider = Items[i]; var result = valueProvider.GetValue(key); if (result != ValueProviderResult.None) { return result; } } return ValueProviderResult.None; } /// <inheritdoc /> public virtual IDictionary<string, string> GetKeysFromPrefix(string prefix) { foreach (var valueProvider in this) { if (valueProvider is IEnumerableValueProvider enumeratedProvider) { var result = enumeratedProvider.GetKeysFromPrefix(prefix); if (result != null && result.Count > 0) { return result; } } } return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); } /// <inheritdoc /> protected override void InsertItem(int index, IValueProvider item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } base.InsertItem(index, item); } /// <inheritdoc /> protected override void SetItem(int index, IValueProvider item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } base.SetItem(index, item); } /// <inheritdoc /> public IValueProvider? Filter(BindingSource bindingSource) { if (bindingSource == null) { throw new ArgumentNullException(nameof(bindingSource)); } var shouldFilter = false; for (var i = 0; i < Count; i++) { var valueProvider = Items[i]; if (valueProvider is IBindingSourceValueProvider) { shouldFilter = true; break; } } if (!shouldFilter) { // No inner IBindingSourceValueProvider implementations. Result will be empty. return null; } var filteredValueProviders = new List<IValueProvider>(); for (var i = 0; i < Count; i++) { var valueProvider = Items[i]; if (valueProvider is IBindingSourceValueProvider bindingSourceValueProvider) { var result = bindingSourceValueProvider.Filter(bindingSource); if (result != null) { filteredValueProviders.Add(result); } } } if (filteredValueProviders.Count == 0) { // Do not create an empty CompositeValueProvider. return null; } return new CompositeValueProvider(filteredValueProviders); } /// <inheritdoc /> /// <remarks> /// Value providers are included by default. If a contained <see cref="IValueProvider"/> does not implement /// <see cref="IKeyRewriterValueProvider"/>, <see cref="Filter()"/> will not remove it. /// </remarks> public IValueProvider? Filter() { var shouldFilter = false; for (var i = 0; i < Count; i++) { var valueProvider = Items[i]; if (valueProvider is IKeyRewriterValueProvider) { shouldFilter = true; break; } } if (!shouldFilter) { // No inner IKeyRewriterValueProvider implementations. Nothing to exclude. return this; } var filteredValueProviders = new List<IValueProvider>(); for (var i = 0; i < Count; i++) { var valueProvider = Items[i]; if (valueProvider is IKeyRewriterValueProvider keyRewriterValueProvider) { var result = keyRewriterValueProvider.Filter(); if (result != null) { filteredValueProviders.Add(result); } } else { // Assume value providers that aren't rewriter-aware do not rewrite their keys. filteredValueProviders.Add(valueProvider); } } if (filteredValueProviders.Count == 0) { // Do not create an empty CompositeValueProvider. return null; } return new CompositeValueProvider(filteredValueProviders); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareScalarUnorderedDouble() { var test = new SimpleBinaryOpTest__CompareScalarUnorderedDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareScalarUnorderedDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__CompareScalarUnorderedDouble testClass) { var result = Sse2.CompareScalarUnordered(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareScalarUnorderedDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareScalarUnordered( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__CompareScalarUnorderedDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__CompareScalarUnorderedDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.CompareScalarUnordered( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.CompareScalarUnordered( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.CompareScalarUnordered( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarUnordered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarUnordered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareScalarUnordered), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.CompareScalarUnordered( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.CompareScalarUnordered( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareScalarUnordered(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareScalarUnordered(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareScalarUnordered(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__CompareScalarUnorderedDouble(); var result = Sse2.CompareScalarUnordered(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__CompareScalarUnorderedDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.CompareScalarUnordered( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.CompareScalarUnordered(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.CompareScalarUnordered( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.CompareScalarUnordered(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.CompareScalarUnordered( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != ((double.IsNaN(left[0]) || double.IsNaN(right[0])) ? -1 : 0)) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(left[i]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareScalarUnordered)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Common.Authentication; using Microsoft.Azure.Commands.ScenarioTest.Mocks; using Microsoft.Azure.Graph.RBAC; using Microsoft.Azure.Management.Authorization; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Test; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.ScenarioTest; using Microsoft.WindowsAzure.Commands.Test.Utilities.Common; using Microsoft.WindowsAzure.Management.Storage; using System; using System.Collections.Generic; using System.Linq; using Microsoft.Azure.ServiceManagemenet.Common.Models; using Xunit.Abstractions; using RestTestFramework = Microsoft.Rest.ClientRuntime.Azure.TestFramework; namespace Microsoft.Azure.Commands.ScenarioTest.SqlTests { using System.IO; public class SqlTestsBase : RMTestBase { protected SqlEvnSetupHelper helper; private const string TenantIdKey = "TenantId"; private const string DomainKey = "Domain"; public string UserDomain { get; private set; } protected SqlTestsBase(ITestOutputHelper output) { helper = new SqlEvnSetupHelper(); XunitTracingInterceptor tracer = new XunitTracingInterceptor(output); XunitTracingInterceptor.AddToContext(tracer); helper.TracingInterceptor = tracer; } protected virtual void SetupManagementClients(RestTestFramework.MockContext context) { var sqlClient = GetSqlClient(context); var sqlLegacyClient = GetLegacySqlClient(); var storageClient = GetStorageClient(); //TODO, Remove the MockDeploymentFactory call when the test is re-recorded var resourcesClient = MockDeploymentClientFactory.GetResourceClient(GetResourcesClient()); var authorizationClient = GetAuthorizationManagementClient(); helper.SetupSomeOfManagementClients(sqlClient, sqlLegacyClient, storageClient, resourcesClient, authorizationClient); } protected void RunPowerShellTest(params string[] scripts) { var callingClassType = TestUtilities.GetCallingClass(2); var mockName = TestUtilities.GetCurrentMethodName(2); Dictionary<string, string> d = new Dictionary<string, string>(); d.Add("Microsoft.Resources", null); d.Add("Microsoft.Features", null); d.Add("Microsoft.Authorization", null); var providersToIgnore = new Dictionary<string, string>(); providersToIgnore.Add("Microsoft.Azure.Graph.RBAC.GraphRbacManagementClient", "1.42-previewInternal"); providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01"); HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(true, d, providersToIgnore); HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords"); // Enable undo functionality as well as mock recording using (RestTestFramework.MockContext context = RestTestFramework.MockContext.Start(callingClassType, mockName)) { SetupManagementClients(context); helper.SetupEnvironment(); helper.SetupModules(AzureModule.AzureResourceManager, "ScenarioTests\\Common.ps1", "ScenarioTests\\" + this.GetType().Name + ".ps1", helper.RMProfileModule, helper.RMResourceModule, helper.RMStorageDataPlaneModule, helper.GetRMModulePath(@"AzureRM.Insights.psd1"), helper.GetRMModulePath(@"AzureRM.Sql.psd1"), "AzureRM.Storage.ps1", "AzureRM.Resources.ps1"); helper.RunPowerShellTest(scripts); } } protected Management.Sql.SqlManagementClient GetSqlClient(RestTestFramework.MockContext context) { Management.Sql.SqlManagementClient client = context.GetServiceClient<Management.Sql.SqlManagementClient>( RestTestFramework.TestEnvironmentFactory.GetTestEnvironment()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationRetryTimeout = 0; } return client; } protected Management.Sql.LegacySdk.SqlManagementClient GetLegacySqlClient() { Management.Sql.LegacySdk.SqlManagementClient client = TestBase.GetServiceClient<Management.Sql.LegacySdk.SqlManagementClient>( new CSMTestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } protected StorageManagementClient GetStorageClient() { StorageManagementClient client = TestBase.GetServiceClient<StorageManagementClient>(new RDFETestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } protected ResourceManagementClient GetResourcesClient() { ResourceManagementClient client = TestBase.GetServiceClient<ResourceManagementClient>(new CSMTestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } protected AuthorizationManagementClient GetAuthorizationManagementClient() { AuthorizationManagementClient client = TestBase.GetServiceClient<AuthorizationManagementClient>(new CSMTestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } protected GraphRbacManagementClient GetGraphClient(RestTestFramework.MockContext context) { var environment = RestTestFramework.TestEnvironmentFactory.GetTestEnvironment(); string tenantId = null; if (HttpMockServer.Mode == HttpRecorderMode.Record) { tenantId = environment.Tenant; UserDomain = environment.UserName.Split(new[] { "@" }, StringSplitOptions.RemoveEmptyEntries).Last(); HttpMockServer.Variables[TenantIdKey] = tenantId; HttpMockServer.Variables[DomainKey] = UserDomain; } else if (HttpMockServer.Mode == HttpRecorderMode.Playback) { if (HttpMockServer.Variables.ContainsKey(TenantIdKey)) { tenantId = HttpMockServer.Variables[TenantIdKey]; AzureRmProfileProvider.Instance.Profile.Context.Tenant.Id = new Guid(tenantId); } if (HttpMockServer.Variables.ContainsKey(DomainKey)) { UserDomain = HttpMockServer.Variables[DomainKey]; AzureRmProfileProvider.Instance.Profile.Context.Tenant.Domain = UserDomain; } } var client = context.GetGraphServiceClient<GraphRbacManagementClient>(environment); client.TenantID = tenantId; return client; } protected Management.Storage.StorageManagementClient GetStorageV2Client() { var client = TestBase.GetServiceClient<Management.Storage.StorageManagementClient>(new CSMTestEnvironmentFactory()); if (HttpMockServer.Mode == HttpRecorderMode.Playback) { client.LongRunningOperationInitialTimeout = 0; client.LongRunningOperationRetryTimeout = 0; } return client; } } }
// ************************ CommentRemover : char ************************ // // Parse : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // '/' = ParseCommentType, default = Parse; // ParseCommentType : '/' = ParseSingleComment, '*' = ParseMultiComment, // default = IllegalCommentType; // ParseSingleComment : '\r' = Parse, '\n' = Parse, default = ParseSingleComment; // ParseMultiComment : '*' = TestEndMultiComment, default = ParseMultiComment; // TestEndMultiComment : '/' = EndComment, default = ParseMultiComment; // EndComment : '\'' = ParseSingleQuotes, '"' = ParseDoubleQuotes, // '/' = ParseCommentType, default = Parse; // ParseSingleQuotes : ParseSingleQuotes ? Parse : IllegalSingleQuotes; // ParseDoubleQuotes : ParseDoubleQuotes ? Parse : IllegalDoubleQuotes; // // IllegalCommentType : default = decline; // IllegalSingleQuotes : default = decline; // IllegalDoubleQuotes : default = decline; // // // This file was automatically generated from a tool that converted the // above state machine definition into this state machine class. // Any changes to this code will be replaced the next time the code is generated. using System; using System.Collections.Generic; namespace StateMachineParser { public class CommentRemover { public enum States { Parse = 0, ParseCommentType = 1, ParseSingleComment = 2, ParseMultiComment = 3, TestEndMultiComment = 4, EndComment = 5, ParseSingleQuotes = 6, ParseDoubleQuotes = 7, IllegalCommentType = 8, IllegalSingleQuotes = 9, IllegalDoubleQuotes = 10, } private States? state = null; public States? CurrentState { get { return state; } } private char currentCommand; public char CurrentCommand { get { return currentCommand; } } private bool reset = false; private Action<char> onParseState = null; private Action<char> onParseEnter = null; private Action<char> onParseExit = null; private Action<char> onParseCommentTypeState = null; private Action<char> onParseCommentTypeEnter = null; private Action<char> onParseCommentTypeExit = null; private Action<char> onParseSingleCommentState = null; private Action<char> onParseSingleCommentEnter = null; private Action<char> onParseSingleCommentExit = null; private Action<char> onParseMultiCommentState = null; private Action<char> onParseMultiCommentEnter = null; private Action<char> onParseMultiCommentExit = null; private Action<char> onTestEndMultiCommentState = null; private Action<char> onTestEndMultiCommentEnter = null; private Action<char> onTestEndMultiCommentExit = null; private Action<char> onEndCommentState = null; private Action<char> onEndCommentEnter = null; private Action<char> onEndCommentExit = null; private Action<char> onParseSingleQuotesState = null; private Action<char> onParseSingleQuotesEnter = null; private Action<char> onParseSingleQuotesExit = null; private Action<char> onParseDoubleQuotesState = null; private Action<char> onParseDoubleQuotesEnter = null; private Action<char> onParseDoubleQuotesExit = null; private Action<char> onIllegalCommentTypeState = null; private Action<char> onIllegalCommentTypeEnter = null; private Action<char> onIllegalCommentTypeExit = null; private Action<char> onIllegalSingleQuotesState = null; private Action<char> onIllegalSingleQuotesEnter = null; private Action<char> onIllegalSingleQuotesExit = null; private Action<char> onIllegalDoubleQuotesState = null; private Action<char> onIllegalDoubleQuotesEnter = null; private Action<char> onIllegalDoubleQuotesExit = null; private Action<char> onAccept = null; private Action<char> onDecline = null; private Action<char> onEnd = null; public readonly ParseSingleQuotes ParseSingleQuotesMachine = new ParseSingleQuotes(); public readonly ParseDoubleQuotes ParseDoubleQuotesMachine = new ParseDoubleQuotes(); public bool? Input(Queue<char> data) { if (reset) state = null; bool? result = null; if (data == null) return null; bool? nestResult; Reset: reset = false; switch (state) { case null: if (data.Count > 0) { state = States.Parse; goto ResumeParse; } else goto End; case States.Parse: goto ResumeParse; case States.ParseCommentType: goto ResumeParseCommentType; case States.ParseSingleComment: goto ResumeParseSingleComment; case States.ParseMultiComment: goto ResumeParseMultiComment; case States.TestEndMultiComment: goto ResumeTestEndMultiComment; case States.EndComment: goto ResumeEndComment; case States.ParseSingleQuotes: goto ResumeParseSingleQuotes; case States.ParseDoubleQuotes: goto ResumeParseDoubleQuotes; case States.IllegalCommentType: goto ResumeIllegalCommentType; case States.IllegalSingleQuotes: goto ResumeIllegalSingleQuotes; case States.IllegalDoubleQuotes: goto ResumeIllegalDoubleQuotes; } EnterParse: state = States.Parse; if (onParseEnter != null) onParseEnter(currentCommand); Parse: if (onParseState != null) onParseState(currentCommand); ResumeParse: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onParseExit != null) onParseExit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onParseExit != null) onParseExit(currentCommand); goto EnterParseDoubleQuotes; case '/': if (onParseExit != null) onParseExit(currentCommand); goto EnterParseCommentType; default: goto Parse; } EnterParseCommentType: state = States.ParseCommentType; if (onParseCommentTypeEnter != null) onParseCommentTypeEnter(currentCommand); if (onParseCommentTypeState != null) onParseCommentTypeState(currentCommand); ResumeParseCommentType: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '/': if (onParseCommentTypeExit != null) onParseCommentTypeExit(currentCommand); goto EnterParseSingleComment; case '*': if (onParseCommentTypeExit != null) onParseCommentTypeExit(currentCommand); goto EnterParseMultiComment; default: if (onParseCommentTypeExit != null) onParseCommentTypeExit(currentCommand); goto EnterIllegalCommentType; } EnterParseSingleComment: state = States.ParseSingleComment; if (onParseSingleCommentEnter != null) onParseSingleCommentEnter(currentCommand); ParseSingleComment: if (onParseSingleCommentState != null) onParseSingleCommentState(currentCommand); ResumeParseSingleComment: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\r': if (onParseSingleCommentExit != null) onParseSingleCommentExit(currentCommand); goto EnterParse; case '\n': if (onParseSingleCommentExit != null) onParseSingleCommentExit(currentCommand); goto EnterParse; default: goto ParseSingleComment; } EnterParseMultiComment: state = States.ParseMultiComment; if (onParseMultiCommentEnter != null) onParseMultiCommentEnter(currentCommand); ParseMultiComment: if (onParseMultiCommentState != null) onParseMultiCommentState(currentCommand); ResumeParseMultiComment: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '*': if (onParseMultiCommentExit != null) onParseMultiCommentExit(currentCommand); goto EnterTestEndMultiComment; default: goto ParseMultiComment; } EnterTestEndMultiComment: state = States.TestEndMultiComment; if (onTestEndMultiCommentEnter != null) onTestEndMultiCommentEnter(currentCommand); if (onTestEndMultiCommentState != null) onTestEndMultiCommentState(currentCommand); ResumeTestEndMultiComment: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '/': if (onTestEndMultiCommentExit != null) onTestEndMultiCommentExit(currentCommand); goto EnterEndComment; default: if (onTestEndMultiCommentExit != null) onTestEndMultiCommentExit(currentCommand); goto EnterParseMultiComment; } EnterEndComment: state = States.EndComment; if (onEndCommentEnter != null) onEndCommentEnter(currentCommand); if (onEndCommentState != null) onEndCommentState(currentCommand); ResumeEndComment: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { case '\'': if (onEndCommentExit != null) onEndCommentExit(currentCommand); goto EnterParseSingleQuotes; case '"': if (onEndCommentExit != null) onEndCommentExit(currentCommand); goto EnterParseDoubleQuotes; case '/': if (onEndCommentExit != null) onEndCommentExit(currentCommand); goto EnterParseCommentType; default: if (onEndCommentExit != null) onEndCommentExit(currentCommand); goto EnterParse; } EnterParseSingleQuotes: state = States.ParseSingleQuotes; if (onParseSingleQuotesEnter != null) onParseSingleQuotesEnter(currentCommand); if (onParseSingleQuotesState != null) onParseSingleQuotesState(currentCommand); ResumeParseSingleQuotes: nestResult = ParseSingleQuotesMachine.Input(data); switch (nestResult) { case null: goto End; case true: if (onParseSingleQuotesExit != null) onParseSingleQuotesExit(ParseSingleQuotesMachine.CurrentCommand); goto EnterParse; case false: if (onParseSingleQuotesExit != null) onParseSingleQuotesExit(ParseSingleQuotesMachine.CurrentCommand); goto EnterIllegalSingleQuotes; } EnterParseDoubleQuotes: state = States.ParseDoubleQuotes; if (onParseDoubleQuotesEnter != null) onParseDoubleQuotesEnter(currentCommand); if (onParseDoubleQuotesState != null) onParseDoubleQuotesState(currentCommand); ResumeParseDoubleQuotes: nestResult = ParseDoubleQuotesMachine.Input(data); switch (nestResult) { case null: goto End; case true: if (onParseDoubleQuotesExit != null) onParseDoubleQuotesExit(ParseDoubleQuotesMachine.CurrentCommand); goto EnterParse; case false: if (onParseDoubleQuotesExit != null) onParseDoubleQuotesExit(ParseDoubleQuotesMachine.CurrentCommand); goto EnterIllegalDoubleQuotes; } EnterIllegalCommentType: state = States.IllegalCommentType; if (onIllegalCommentTypeEnter != null) onIllegalCommentTypeEnter(currentCommand); if (onIllegalCommentTypeState != null) onIllegalCommentTypeState(currentCommand); ResumeIllegalCommentType: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { default: if (onIllegalCommentTypeExit != null) onIllegalCommentTypeExit(currentCommand); goto Decline; } EnterIllegalSingleQuotes: state = States.IllegalSingleQuotes; if (onIllegalSingleQuotesEnter != null) onIllegalSingleQuotesEnter(currentCommand); if (onIllegalSingleQuotesState != null) onIllegalSingleQuotesState(currentCommand); ResumeIllegalSingleQuotes: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { default: if (onIllegalSingleQuotesExit != null) onIllegalSingleQuotesExit(currentCommand); goto Decline; } EnterIllegalDoubleQuotes: state = States.IllegalDoubleQuotes; if (onIllegalDoubleQuotesEnter != null) onIllegalDoubleQuotesEnter(currentCommand); if (onIllegalDoubleQuotesState != null) onIllegalDoubleQuotesState(currentCommand); ResumeIllegalDoubleQuotes: if (data.Count > 0) currentCommand = data.Dequeue(); else goto End; switch (currentCommand) { default: if (onIllegalDoubleQuotesExit != null) onIllegalDoubleQuotesExit(currentCommand); goto Decline; } Decline: result = false; state = null; if (onDecline != null) onDecline(currentCommand); goto End; End: if (onEnd != null) onEnd(currentCommand); if (reset) { goto Reset; } return result; } public void AddOnParse(Action<char> addedFunc) { onParseState += addedFunc; } public void AddOnParseCommentType(Action<char> addedFunc) { onParseCommentTypeState += addedFunc; } public void AddOnParseSingleComment(Action<char> addedFunc) { onParseSingleCommentState += addedFunc; } public void AddOnParseMultiComment(Action<char> addedFunc) { onParseMultiCommentState += addedFunc; } public void AddOnTestEndMultiComment(Action<char> addedFunc) { onTestEndMultiCommentState += addedFunc; } public void AddOnEndComment(Action<char> addedFunc) { onEndCommentState += addedFunc; } public void AddOnParseSingleQuotes(Action<char> addedFunc) { AddOnParseSingleQuotesEnter(addedFunc); ParseSingleQuotesMachine.addOnAllStates(addedFunc); } public void AddOnParseDoubleQuotes(Action<char> addedFunc) { AddOnParseDoubleQuotesEnter(addedFunc); ParseDoubleQuotesMachine.addOnAllStates(addedFunc); } public void AddOnIllegalCommentType(Action<char> addedFunc) { onIllegalCommentTypeState += addedFunc; } public void AddOnIllegalSingleQuotes(Action<char> addedFunc) { onIllegalSingleQuotesState += addedFunc; } public void AddOnIllegalDoubleQuotes(Action<char> addedFunc) { onIllegalDoubleQuotesState += addedFunc; } public void AddOnParseEnter(Action<char> addedFunc) { onParseEnter += addedFunc; } public void AddOnParseCommentTypeEnter(Action<char> addedFunc) { onParseCommentTypeEnter += addedFunc; } public void AddOnParseSingleCommentEnter(Action<char> addedFunc) { onParseSingleCommentEnter += addedFunc; } public void AddOnParseMultiCommentEnter(Action<char> addedFunc) { onParseMultiCommentEnter += addedFunc; } public void AddOnTestEndMultiCommentEnter(Action<char> addedFunc) { onTestEndMultiCommentEnter += addedFunc; } public void AddOnEndCommentEnter(Action<char> addedFunc) { onEndCommentEnter += addedFunc; } public void AddOnParseSingleQuotesEnter(Action<char> addedFunc) { onParseSingleQuotesEnter += addedFunc; } public void AddOnParseDoubleQuotesEnter(Action<char> addedFunc) { onParseDoubleQuotesEnter += addedFunc; } public void AddOnIllegalCommentTypeEnter(Action<char> addedFunc) { onIllegalCommentTypeEnter += addedFunc; } public void AddOnIllegalSingleQuotesEnter(Action<char> addedFunc) { onIllegalSingleQuotesEnter += addedFunc; } public void AddOnIllegalDoubleQuotesEnter(Action<char> addedFunc) { onIllegalDoubleQuotesEnter += addedFunc; } public void AddOnParseExit(Action<char> addedFunc) { onParseExit += addedFunc; } public void AddOnParseCommentTypeExit(Action<char> addedFunc) { onParseCommentTypeExit += addedFunc; } public void AddOnParseSingleCommentExit(Action<char> addedFunc) { onParseSingleCommentExit += addedFunc; } public void AddOnParseMultiCommentExit(Action<char> addedFunc) { onParseMultiCommentExit += addedFunc; } public void AddOnTestEndMultiCommentExit(Action<char> addedFunc) { onTestEndMultiCommentExit += addedFunc; } public void AddOnEndCommentExit(Action<char> addedFunc) { onEndCommentExit += addedFunc; } public void AddOnParseSingleQuotesExit(Action<char> addedFunc) { onParseSingleQuotesExit += addedFunc; } public void AddOnParseDoubleQuotesExit(Action<char> addedFunc) { onParseDoubleQuotesExit += addedFunc; } public void AddOnIllegalCommentTypeExit(Action<char> addedFunc) { onIllegalCommentTypeExit += addedFunc; } public void AddOnIllegalSingleQuotesExit(Action<char> addedFunc) { onIllegalSingleQuotesExit += addedFunc; } public void AddOnIllegalDoubleQuotesExit(Action<char> addedFunc) { onIllegalDoubleQuotesExit += addedFunc; } public void AddOnAccept(Action<char> addedFunc) { onAccept += addedFunc; } public void AddOnDecline(Action<char> addedFunc) { onDecline += addedFunc; } public void AddOnEnd(Action<char> addedFunc) { onEnd += addedFunc; } internal void addOnAllStates( Action<char> addedFunc ) { onParseState += addedFunc; onParseCommentTypeState += addedFunc; onParseSingleCommentState += addedFunc; onParseMultiCommentState += addedFunc; onTestEndMultiCommentState += addedFunc; onEndCommentState += addedFunc; AddOnParseSingleQuotes(addedFunc); AddOnParseDoubleQuotes(addedFunc); onIllegalCommentTypeState += addedFunc; onIllegalSingleQuotesState += addedFunc; onIllegalDoubleQuotesState += addedFunc; } public void ResetStateOnEnd() { state = null; reset = true; ParseSingleQuotesMachine.ResetStateOnEnd(); ParseDoubleQuotesMachine.ResetStateOnEnd(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Input.StateChanges; using osu.Game.Beatmaps; using osu.Game.Graphics.Sprites; using osu.Game.Replays; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.UI; using osu.Game.Scoring; using osu.Game.Screens.Play; using osu.Game.Tests.Visual.UserInterface; using osuTK; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneReplayRecording : OsuTestScene { private readonly TestRulesetInputManager playbackManager; private readonly TestRulesetInputManager recordingManager; [Cached] private GameplayState gameplayState = new GameplayState(new Beatmap(), new OsuRuleset(), Array.Empty<Mod>()); public TestSceneReplayRecording() { Replay replay = new Replay(); Add(new GridContainer { RelativeSizeAxes = Axes.Both, Content = new[] { new Drawable[] { recordingManager = new TestRulesetInputManager(new TestSceneModSettings.TestRulesetInfo(), 0, SimultaneousBindingMode.Unique) { Recorder = new TestReplayRecorder(new Score { Replay = replay, ScoreInfo = { BeatmapInfo = gameplayState.Beatmap.BeatmapInfo } }) { ScreenSpaceToGamefield = pos => recordingManager.ToLocalSpace(pos) }, Child = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { Colour = Color4.Brown, RelativeSizeAxes = Axes.Both, }, new OsuSpriteText { Text = "Recording", Scale = new Vector2(3), Anchor = Anchor.Centre, Origin = Anchor.Centre, }, new TestConsumer() } }, } }, new Drawable[] { playbackManager = new TestRulesetInputManager(new TestSceneModSettings.TestRulesetInfo(), 0, SimultaneousBindingMode.Unique) { ReplayInputHandler = new TestFramedReplayInputHandler(replay) { GamefieldToScreenSpace = pos => playbackManager.ToScreenSpace(pos), }, Child = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { Colour = Color4.DarkBlue, RelativeSizeAxes = Axes.Both, }, new OsuSpriteText { Text = "Playback", Scale = new Vector2(3), Anchor = Anchor.Centre, Origin = Anchor.Centre, }, new TestConsumer() } }, } } } }); } protected override void Update() { base.Update(); playbackManager.ReplayInputHandler.SetFrameFromTime(Time.Current - 500); } } public class TestFramedReplayInputHandler : FramedReplayInputHandler<TestReplayFrame> { public TestFramedReplayInputHandler(Replay replay) : base(replay) { } public override void CollectPendingInputs(List<IInput> inputs) { inputs.Add(new MousePositionAbsoluteInput { Position = GamefieldToScreenSpace(CurrentFrame?.Position ?? Vector2.Zero) }); inputs.Add(new ReplayState<TestAction> { PressedActions = CurrentFrame?.Actions ?? new List<TestAction>() }); } } public class TestConsumer : CompositeDrawable, IKeyBindingHandler<TestAction> { public override bool ReceivePositionalInputAt(Vector2 screenSpacePos) => Parent.ReceivePositionalInputAt(screenSpacePos); private readonly Box box; public TestConsumer() { Size = new Vector2(30); Origin = Anchor.Centre; InternalChildren = new Drawable[] { box = new Box { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, }, }; } protected override bool OnMouseMove(MouseMoveEvent e) { Position = e.MousePosition; return base.OnMouseMove(e); } public bool OnPressed(KeyBindingPressEvent<TestAction> e) { box.Colour = Color4.White; return true; } public void OnReleased(KeyBindingReleaseEvent<TestAction> e) { box.Colour = Color4.Black; } } public class TestRulesetInputManager : RulesetInputManager<TestAction> { public TestRulesetInputManager(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) : base(ruleset, variant, unique) { } protected override KeyBindingContainer<TestAction> CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) => new TestKeyBindingContainer(); internal class TestKeyBindingContainer : KeyBindingContainer<TestAction> { public override IEnumerable<IKeyBinding> DefaultKeyBindings => new[] { new KeyBinding(InputKey.MouseLeft, TestAction.Down), }; } } public class TestReplayFrame : ReplayFrame { public Vector2 Position; public List<TestAction> Actions = new List<TestAction>(); public TestReplayFrame(double time, Vector2 position, params TestAction[] actions) : base(time) { Position = position; Actions.AddRange(actions); } } public enum TestAction { Down, } internal class TestReplayRecorder : ReplayRecorder<TestAction> { public TestReplayRecorder(Score target) : base(target) { } protected override ReplayFrame HandleFrame(Vector2 mousePosition, List<TestAction> actions, ReplayFrame previousFrame) => new TestReplayFrame(Time.Current, mousePosition, actions.ToArray()); } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// CredentialResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Types; namespace Twilio.Rest.Notify.V1 { public class CredentialResource : Resource { public sealed class PushServiceEnum : StringEnum { private PushServiceEnum(string value) : base(value) {} public PushServiceEnum() {} public static implicit operator PushServiceEnum(string value) { return new PushServiceEnum(value); } public static readonly PushServiceEnum Gcm = new PushServiceEnum("gcm"); public static readonly PushServiceEnum Apn = new PushServiceEnum("apn"); public static readonly PushServiceEnum Fcm = new PushServiceEnum("fcm"); } private static Request BuildReadRequest(ReadCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Notify, "/v1/Credentials", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static ResourceSet<CredentialResource> Read(ReadCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<CredentialResource>.FromJson("credentials", response.Content); return new ResourceSet<CredentialResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<ResourceSet<CredentialResource>> ReadAsync(ReadCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<CredentialResource>.FromJson("credentials", response.Content); return new ResourceSet<CredentialResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static ResourceSet<CredentialResource> Read(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCredentialOptions(){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<ResourceSet<CredentialResource>> ReadAsync(int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadCredentialOptions(){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<CredentialResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<CredentialResource>.FromJson("credentials", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<CredentialResource> NextPage(Page<CredentialResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Notify) ); var response = client.Request(request); return Page<CredentialResource>.FromJson("credentials", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<CredentialResource> PreviousPage(Page<CredentialResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Notify) ); var response = client.Request(request); return Page<CredentialResource>.FromJson("credentials", response.Content); } private static Request BuildCreateRequest(CreateCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Notify, "/v1/Credentials", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Create(CreateCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> CreateAsync(CreateCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="type"> The Credential type </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="certificate"> [APN only] The URL-encoded representation of the certificate </param> /// <param name="privateKey"> [APN only] URL-encoded representation of the private key </param> /// <param name="sandbox"> [APN only] Whether to send the credential to sandbox APNs </param> /// <param name="apiKey"> [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud /// messaging </param> /// <param name="secret"> [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud /// messaging </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Create(CredentialResource.PushServiceEnum type, string friendlyName = null, string certificate = null, string privateKey = null, bool? sandbox = null, string apiKey = null, string secret = null, ITwilioRestClient client = null) { var options = new CreateCredentialOptions(type){FriendlyName = friendlyName, Certificate = certificate, PrivateKey = privateKey, Sandbox = sandbox, ApiKey = apiKey, Secret = secret}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="type"> The Credential type </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="certificate"> [APN only] The URL-encoded representation of the certificate </param> /// <param name="privateKey"> [APN only] URL-encoded representation of the private key </param> /// <param name="sandbox"> [APN only] Whether to send the credential to sandbox APNs </param> /// <param name="apiKey"> [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud /// messaging </param> /// <param name="secret"> [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud /// messaging </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> CreateAsync(CredentialResource.PushServiceEnum type, string friendlyName = null, string certificate = null, string privateKey = null, bool? sandbox = null, string apiKey = null, string secret = null, ITwilioRestClient client = null) { var options = new CreateCredentialOptions(type){FriendlyName = friendlyName, Certificate = certificate, PrivateKey = privateKey, Sandbox = sandbox, ApiKey = apiKey, Secret = secret}; return await CreateAsync(options, client); } #endif private static Request BuildFetchRequest(FetchCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Notify, "/v1/Credentials/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Fetch(FetchCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> FetchAsync(FetchCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchCredentialOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchCredentialOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Notify, "/v1/Credentials/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Update(UpdateCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="options"> Update Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> UpdateAsync(UpdateCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// update /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="certificate"> [APN only] The URL-encoded representation of the certificate </param> /// <param name="privateKey"> [APN only] URL-encoded representation of the private key </param> /// <param name="sandbox"> [APN only] Whether to send the credential to sandbox APNs </param> /// <param name="apiKey"> [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud /// messaging </param> /// <param name="secret"> [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud /// messaging </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static CredentialResource Update(string pathSid, string friendlyName = null, string certificate = null, string privateKey = null, bool? sandbox = null, string apiKey = null, string secret = null, ITwilioRestClient client = null) { var options = new UpdateCredentialOptions(pathSid){FriendlyName = friendlyName, Certificate = certificate, PrivateKey = privateKey, Sandbox = sandbox, ApiKey = apiKey, Secret = secret}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="friendlyName"> A string to describe the resource </param> /// <param name="certificate"> [APN only] The URL-encoded representation of the certificate </param> /// <param name="privateKey"> [APN only] URL-encoded representation of the private key </param> /// <param name="sandbox"> [APN only] Whether to send the credential to sandbox APNs </param> /// <param name="apiKey"> [GCM only] The `Server key` of your project from Firebase console under Settings / Cloud /// messaging </param> /// <param name="secret"> [FCM only] The `Server key` of your project from Firebase console under Settings / Cloud /// messaging </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<CredentialResource> UpdateAsync(string pathSid, string friendlyName = null, string certificate = null, string privateKey = null, bool? sandbox = null, string apiKey = null, string secret = null, ITwilioRestClient client = null) { var options = new UpdateCredentialOptions(pathSid){FriendlyName = friendlyName, Certificate = certificate, PrivateKey = privateKey, Sandbox = sandbox, ApiKey = apiKey, Secret = secret}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteCredentialOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Notify, "/v1/Credentials/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static bool Delete(DeleteCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Credential parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteCredentialOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Credential </returns> public static bool Delete(string pathSid, ITwilioRestClient client = null) { var options = new DeleteCredentialOptions(pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Credential </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathSid, ITwilioRestClient client = null) { var options = new DeleteCredentialOptions(pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a CredentialResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> CredentialResource object represented by the provided JSON </returns> public static CredentialResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<CredentialResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The string that you assigned to describe the resource /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The Credential type, one of `gcm`, `fcm`, or `apn` /// </summary> [JsonProperty("type")] [JsonConverter(typeof(StringEnumConverter))] public CredentialResource.PushServiceEnum Type { get; private set; } /// <summary> /// [APN only] Whether to send the credential to sandbox APNs /// </summary> [JsonProperty("sandbox")] public string Sandbox { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the Credential resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private CredentialResource() { } } }
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; using Object = UnityEngine.Object; namespace UMA { /// <summary> /// Default UMA character generator. /// </summary> public abstract class UMAGeneratorBuiltin : UMAGeneratorBase { [Obsolete("UMA 2.1 - UMAGeneratorBuiltin.umaData is an internal reference that will be hidden in the future.", false)] [NonSerialized] public UMAData umaData; [Obsolete("UMA 2.1 - UMAGeneratorBuiltin.umaDirtyList is an internal list that will be hidden in the future.", false)] [NonSerialized] public List<UMAData> umaDirtyList = new List<UMAData>(); private LinkedList<UMAData> cleanUmas = new LinkedList<UMAData>(); private LinkedList<UMAData> dirtyUmas = new LinkedList<UMAData>(); private UMAGeneratorCoroutine activeGeneratorCoroutine; public Transform textureMergePrefab; public UMAMeshCombiner meshCombiner; /// <summary> /// /// </summary> [Tooltip("Increase scale factor to decrease texture usage. A value of 1 means the textures will not be downsampled. Values greater than 1 will result in texture savings. The size of the texture is divided by this value.")] public int InitialScaleFactor = 1; /// <summary> /// If true, generate in a single update. /// </summary> [Tooltip("Set Fast Generation to true to have the UMA Avatar generated in a single update. Otherwise, generation can span multiple frames.")] public bool fastGeneration = true; private int forceGarbageCollect; /// <summary> /// Number of character updates before triggering System garbage collect. /// </summary> [Tooltip("Number of character updates before triggering garbage collection.")] public int garbageCollectionRate = 8; private System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); [NonSerialized] public long ElapsedTicks; [NonSerialized] public long DnaChanged; [NonSerialized] public long TextureChanged; [NonSerialized] public long SlotsChanged; public virtual void OnEnable() { activeGeneratorCoroutine = null; } public virtual void Awake() { activeGeneratorCoroutine = null; if (atlasResolution == 0) atlasResolution = 256; if (!textureMerge) { Transform tempTextureMerger = Instantiate(textureMergePrefab, Vector3.zero, Quaternion.identity) as Transform; textureMerge = tempTextureMerger.GetComponent("TextureMerge") as TextureMerge; textureMerge.transform.parent = transform; textureMerge.gameObject.SetActive(false); } //Garbage Collection hack var mb = (System.GC.GetTotalMemory(false) / (1024 * 1024)); if (mb < 10) { byte[] data = new byte[10 * 1024 * 1024]; data[0] = 0; data[10 * 1024 * 1024 - 1] = 0; } } void Update() { if (CheckRenderTextures()) return; // if render textures needs rebuild we'll not do anything else if (forceGarbageCollect > garbageCollectionRate) { GC.Collect(); forceGarbageCollect = 0; if (garbageCollectionRate < 1) garbageCollectionRate = 1; } else { Work(); } } private bool CheckRenderTextures() { var rt = FindRenderTexture(); if (rt != null && !rt.IsCreated()) { RebuildAllRenderTextures(); return true; } return false; } private RenderTexture FindRenderTexture() { var iteratorNode = cleanUmas.First; while (iteratorNode != null) { var rt = iteratorNode.Value.GetFirstRenderTexture(); if (rt != null) return rt; iteratorNode = iteratorNode.Next; } return null; } public override void Work() { if (!IsIdle()) { stopWatch.Reset(); stopWatch.Start(); OnDirtyUpdate(); ElapsedTicks += stopWatch.ElapsedTicks; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); #endif stopWatch.Stop(); UMATime.ReportTimeSpendtThisFrameTicks(stopWatch.ElapsedTicks); } } #pragma warning disable 618 private void RebuildAllRenderTextures() { var activeUmaData = umaData; var storedGeneratorCoroutine = activeGeneratorCoroutine; var iteratorNode = cleanUmas.First; while (iteratorNode != null) { RebuildRenderTexture(iteratorNode.Value); iteratorNode = iteratorNode.Next; } umaData = activeUmaData; activeGeneratorCoroutine = storedGeneratorCoroutine; } private void RebuildRenderTexture(UMAData data) { var rt = data.GetFirstRenderTexture(); if (rt != null && !rt.IsCreated()) { umaData = data; TextureProcessBaseCoroutine textureProcessCoroutine; textureProcessCoroutine = new TextureProcessPROCoroutine(); textureProcessCoroutine.Prepare(data, this); activeGeneratorCoroutine = new UMAGeneratorCoroutine(); activeGeneratorCoroutine.Prepare(this, umaData, textureProcessCoroutine, true, InitialScaleFactor); while (!activeGeneratorCoroutine.Work()) ; activeGeneratorCoroutine = null; TextureChanged++; } } public virtual bool HandleDirtyUpdate(UMAData data) { if (data == null) return true; if (umaData != data) { umaData = data; if (!umaData.Validate()) return true; if (meshCombiner != null) { meshCombiner.Preprocess(umaData); } umaData.FireCharacterBegunEvents(); } if (umaData.isTextureDirty) { if (activeGeneratorCoroutine == null) { TextureProcessBaseCoroutine textureProcessCoroutine; textureProcessCoroutine = new TextureProcessPROCoroutine(); textureProcessCoroutine.Prepare(data, this); activeGeneratorCoroutine = new UMAGeneratorCoroutine(); activeGeneratorCoroutine.Prepare(this, umaData, textureProcessCoroutine, !umaData.isMeshDirty, InitialScaleFactor); } bool workDone = activeGeneratorCoroutine.Work(); if (workDone) { activeGeneratorCoroutine = null; umaData.isTextureDirty = false; umaData.isAtlasDirty |= umaData.isMeshDirty; TextureChanged++; } if (!workDone || !fastGeneration || umaData.isMeshDirty) return false; } if (umaData.isMeshDirty) { UpdateUMAMesh(umaData.isAtlasDirty); umaData.isAtlasDirty = false; umaData.isMeshDirty = false; SlotsChanged++; forceGarbageCollect++; if (!fastGeneration) return false; } if (umaData.isShapeDirty) { UpdateUMABody(umaData); umaData.isShapeDirty = false; DnaChanged++; } UMAReady(); return true; } public virtual void OnDirtyUpdate() { if (HandleDirtyUpdate(umaDirtyList[0])) { umaDirtyList.RemoveAt(0); umaData.MoveToList(cleanUmas); umaData = null; } else if (fastGeneration && HandleDirtyUpdate(umaDirtyList[0])) { umaDirtyList.RemoveAt(0); umaData.MoveToList(cleanUmas); umaData = null; } } private void UpdateUMAMesh(bool updatedAtlas) { if (meshCombiner != null) { meshCombiner.UpdateUMAMesh(updatedAtlas, umaData, atlasResolution); } else { Debug.LogError("UMAGenerator.UpdateUMAMesh, no MeshCombiner specified", gameObject); } } /// <inheritdoc/> public override void addDirtyUMA(UMAData umaToAdd) { if (umaToAdd) { umaDirtyList.Add(umaToAdd); umaToAdd.MoveToList(dirtyUmas); } } /// <inheritdoc/> public override bool IsIdle() { return umaDirtyList.Count == 0; } /// <inheritdoc/> public override int QueueSize() { return umaDirtyList.Count; } public virtual void UMAReady() { if (umaData) { umaData.myRenderer.enabled = true; umaData.FireUpdatedEvent(false); umaData.FireCharacterCompletedEvents(); if (umaData.skeleton.boneCount > 300) { Debug.LogWarning("Skeleton has " + umaData.skeleton.boneCount + " bones, may be an error with slots!"); } } } public virtual void UpdateUMABody(UMAData umaData) { if (umaData) { umaData.skeleton.ResetAll(); // Put the skeleton into TPose so rotations will be valid for generating avatar umaData.GotoTPose(); umaData.ApplyDNA(); umaData.FireDNAAppliedEvents(); umaData.skeleton.EndSkeletonUpdate(); UpdateAvatar(umaData); } } #pragma warning restore 618 } }
// StreamWriterTest.cs - NUnit Test Cases for the SystemIO.StreamWriter class // // David Brandt ([email protected]) // // (C) Ximian, Inc. http://www.ximian.com // using NUnit.Framework; using System; using System.IO; using System.Text; namespace MonoTests.System.IO { [TestFixture] public class StreamWriterTest : Assertion { static string TempFolder = Path.Combine (Path.GetTempPath (), "MonoTests.System.IO.Tests"); private string _codeFileName = TempFolder + Path.DirectorySeparatorChar + "AFile.txt"; private string _thisCodeFileName = TempFolder + Path.DirectorySeparatorChar + "StreamWriterTest.temp"; [SetUp] public void SetUp () { if (Directory.Exists (TempFolder)) Directory.Delete (TempFolder, true); Directory.CreateDirectory (TempFolder); if (!File.Exists (_thisCodeFileName)) File.Create (_thisCodeFileName).Close (); } [TearDown] public void TearDown () { if (Directory.Exists (TempFolder)) Directory.Delete (TempFolder, true); } // TODO - ctors [Test] public void TestCtor1() { { bool errorThrown = false; try { StreamWriter r = new StreamWriter((Stream)null); } catch (ArgumentNullException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 1: " + e.ToString()); } Assert("null string error not thrown", errorThrown); } { bool errorThrown = false; FileStream f = new FileStream(_thisCodeFileName, FileMode.Open, FileAccess.Read); try { StreamWriter r = new StreamWriter(f); r.Close(); } catch (ArgumentException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 2: " + e.ToString()); } f.Close(); Assert("no read error not thrown", errorThrown); } { FileStream f = new FileStream(_codeFileName, FileMode.Append, FileAccess.Write); StreamWriter r = new StreamWriter(f); AssertNotNull("no stream writer", r); r.Close(); f.Close(); } } [Test] public void TestCtor2() { { bool errorThrown = false; try { StreamWriter r = new StreamWriter(""); } catch (ArgumentException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 1: " + e.ToString()); } Assert("empty string error not thrown", errorThrown); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter((string)null); } catch (ArgumentNullException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 2: " + e.ToString()); } Assert("null string error not thrown", errorThrown); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter("nonexistentdir/file"); } catch (DirectoryNotFoundException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 3: " + e.ToString()); } Assert("dirNotFound error not thrown", errorThrown); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter("!$what? what? Huh? !$*#" + Path.InvalidPathChars[0]); } catch (IOException) { errorThrown = true; } catch (ArgumentException) { // FIXME - the spec says 'IOExc', but the // compiler says 'ArgExc'... errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 4: " + e.ToString()); } Assert("1 invalid filename error not thrown", errorThrown); } // TODO - Security/Auth exceptions { StreamWriter r = new StreamWriter(_codeFileName); AssertNotNull("no stream writer", r); r.Close(); } } [Test] public void TestCtor3() { { bool errorThrown = false; try { StreamWriter r = new StreamWriter("", false); } catch (ArgumentException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 1: " + e.ToString()); } Assert("empty string error not thrown", errorThrown); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter((string)null, false); } catch (ArgumentNullException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 2: " + e.ToString()); } Assert("null string error not thrown", errorThrown); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter("nonexistentdir/file", false); } catch (DirectoryNotFoundException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 3: " + e.ToString()); } Assert("dirNotFound error not thrown", errorThrown); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter("!$what? what? Huh? !$*#" + Path.InvalidPathChars[0], false); } catch (IOException) { errorThrown = true; } catch (ArgumentException) { // FIXME - the spec says 'IOExc', but the // compiler says 'ArgExc'... errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 4: " + e.ToString()); } Assert("2 invalid filename error not thrown", errorThrown); } { StreamWriter r = new StreamWriter(_codeFileName, false); AssertNotNull("no stream writer", r); r.Close(); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter("", true); } catch (ArgumentException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 5: " + e.ToString()); } Assert("empty string error not thrown", errorThrown); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter((string)null, true); } catch (ArgumentNullException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 6: " + e.ToString()); } Assert("null string error not thrown", errorThrown); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter("nonexistentdir/file", true); } catch (DirectoryNotFoundException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 7: " + e.ToString()); } Assert("dirNotFound error not thrown", errorThrown); } { bool errorThrown = false; try { StreamWriter r = new StreamWriter("!$what? what? Huh? !$*#" + Path.InvalidPathChars[0], true); } catch (IOException) { errorThrown = true; } catch (ArgumentException) { // FIXME - the spec says 'IOExc', but the // compiler says 'ArgExc'... errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 8: " + e.ToString()); } Assert("3 invalid filename error not thrown", errorThrown); } { try { StreamWriter r = new StreamWriter(_codeFileName, true); AssertNotNull("no stream writer", r); r.Close(); } catch (Exception e) { Fail ("Unxpected exception e=" + e.ToString()); } } } // TODO - ctors with Encoding // TODO - AutoFlush [Test] public void TestAutoFlush() { { MemoryStream m = new MemoryStream(); StreamWriter w = new StreamWriter(m); w.AutoFlush = false; w.Write(1); w.Write(2); w.Write(3); w.Write(4); AssertEquals("Should be nothing before flush", 0L, m.Length); w.Flush(); AssertEquals("Should be something after flush", 4L, m.Length); } { MemoryStream m = new MemoryStream(); StreamWriter w = new StreamWriter(m); w.AutoFlush = true; w.Write(1); w.Write(2); w.Write(3); w.Write(4); AssertEquals("Should be something before flush", 4L, m.Length); w.Flush(); AssertEquals("Should be something after flush", 4L, m.Length); } } [Test] public void TestBaseStream() { FileStream f = new FileStream(_codeFileName, FileMode.Append, FileAccess.Write); StreamWriter r = new StreamWriter(f); AssertEquals("wrong base stream ", f, r.BaseStream); r.Close(); f.Close(); } [Test] public void TestEncoding() { StreamWriter r = new StreamWriter(_codeFileName); AssertEquals("wrong encoding", Encoding.UTF8.GetType(), r.Encoding.GetType()); r.Close(); } // TODO - Close - not entirely sure how to test Close //public void TestClose() { //{ //MemoryStream m = new MemoryStream(); //StreamWriter w = new StreamWriter(m); //StreamReader r = new StreamReader(m); //w.Write(1); //w.Write(2); //w.Write(3); //w.Write(4); //AssertEquals("Should be nothing before close", //0, m.Length); //AssertEquals("Should be nothing in reader", //-1, r.Peek()); //w.Close(); //AssertEquals("Should be something after close", //1, r.Peek()); //} //} // TODO - Flush [Test] public void TestFlush() { { bool errorThrown = false; try { FileStream f = new FileStream(_codeFileName, FileMode.Append, FileAccess.Write); StreamWriter r = new StreamWriter(f); r.Close(); r.Flush(); } catch (ObjectDisposedException) { errorThrown = true; } catch (Exception e) { Fail ("Incorrect exception thrown at 1: " + e.ToString()); } Assert("can't flush closed error not thrown", errorThrown); } { MemoryStream m = new MemoryStream(); StreamWriter w = new StreamWriter(m); w.Write(1); w.Write(2); w.Write(3); w.Write(4); AssertEquals("Should be nothing before flush", 0L, m.Length); w.Flush(); AssertEquals("Should be something after flush", 4L, m.Length); } } [Test] [ExpectedException (typeof (ObjectDisposedException))] public void AutoFlush_Disposed () { StreamWriter w = new StreamWriter (new MemoryStream ()); w.Close (); w.AutoFlush = true; } [Test] [ExpectedException (typeof (ObjectDisposedException))] public void WriteChar_Disposed () { StreamWriter w = new StreamWriter (new MemoryStream ()); w.Close (); w.Write ('A'); } [Test] [ExpectedException (typeof (ObjectDisposedException))] public void WriteCharArray_Disposed () { char[] c = new char [2] { 'a', 'b' }; StreamWriter w = new StreamWriter (new MemoryStream ()); w.Close (); w.Write (c, 0, 2); } [Test] // accepted [ExpectedException (typeof (ArgumentNullException))] public void WriteCharArray_Null () { char[] c = null; StreamWriter w = new StreamWriter (new MemoryStream ()); w.Write (c); } [Test] [ExpectedException (typeof (ArgumentException))] public void WriteCharArray_IndexOverflow () { char[] c = new char [2] { 'a', 'b' }; StreamWriter w = new StreamWriter (new MemoryStream ()); w.Write (c, Int32.MaxValue, 2); } [Test] [ExpectedException (typeof (ArgumentException))] public void WriteCharArray_CountOverflow () { char[] c = new char [2] { 'a', 'b' }; StreamWriter w = new StreamWriter (new MemoryStream ()); w.Write (c, 1, Int32.MaxValue); } [Test] [ExpectedException (typeof (ObjectDisposedException))] public void WriteString_Disposed () { StreamWriter w = new StreamWriter (new MemoryStream ()); w.Close (); w.Write ("mono"); } [Test] // accepted [ExpectedException (typeof (ArgumentNullException))] public void WriteString_Null () { string s = null; StreamWriter w = new StreamWriter (new MemoryStream ()); w.Write (s); } [Test] public void NoPreambleOnAppend () { MemoryStream ms = new MemoryStream (); StreamWriter w = new StreamWriter (ms, Encoding.UTF8); w.Write ("a"); w.Flush (); AssertEquals ("Incorrect size after writing 1 byte plus header", ms.Position, 4); // Append 1 byte, should skip the preamble now. w.Write ("a"); w.Flush (); w = new StreamWriter (ms, Encoding.UTF8); AssertEquals ("Incorrect size after writing 1 byte, must have been 5", ms.Position, 5); } // TODO - Write - test errors, functionality tested in TestFlush. } }
// 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 Xunit; namespace System.Reflection.Tests { public class ConstructorInfoInvokeArrayTests { [Fact] public void Invoke_SZArrayConstructor() { Type type = Type.GetType("System.Object[]"); ConstructorInfo[] constructors = type.GetConstructors(); Assert.Equal(1, constructors.Length); ConstructorInfo constructor = constructors[0]; int[] blength = new int[] { -100, -9, -1 }; for (int j = 0; j < blength.Length; j++) { Assert.Throws<OverflowException>(() => constructor.Invoke(new object[] { blength[j] })); } int[] glength = new int[] { 0, 1, 2, 3, 5, 10, 99, 65535 }; for (int j = 0; j < glength.Length; j++) { object[] arr = (object[])constructor.Invoke(new object[] { glength[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(glength[j] - 1, arr.GetUpperBound(0)); Assert.Equal(glength[j], arr.Length); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Multidim arrays of rank 1 not supported on UapAot: https://github.com/dotnet/corert/issues/3331")] public void Invoke_1DArrayConstructor() { Type type = Type.GetType("System.Char[*]"); MethodInfo getLowerBound = type.GetMethod("GetLowerBound"); MethodInfo getUpperBound = type.GetMethod("GetUpperBound"); PropertyInfo getLength = type.GetProperty("Length"); ConstructorInfo[] constructors = type.GetConstructors(); Assert.Equal(2, constructors.Length); for (int i = 0; i < constructors.Length; i++) { switch (constructors[i].GetParameters().Length) { case 1: { int[] invalidLengths = new int[] { -100, -9, -1 }; for (int j = 0; j < invalidLengths.Length; j++) { Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLengths[j] })); } int[] validLengths = new int[] { 0, 1, 2, 3, 5, 10, 99 }; for (int j = 0; j < validLengths.Length; j++) { char[] arr = (char[])constructors[i].Invoke(new object[] { validLengths[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(validLengths[j] - 1, arr.GetUpperBound(0)); Assert.Equal(validLengths[j], arr.Length); } } break; case 2: { int[] invalidLowerBounds = new int[] { -20, 0, 20 }; int[] invalidLengths = new int[] { -100, -9, -1 }; for (int j = 0; j < invalidLengths.Length; j++) { Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLowerBounds[j], invalidLengths[j] })); } int[] validLowerBounds = new int[] { 0, 1, -1, 2, -3, 5, -10, 99, 100 }; int[] validLengths = new int[] { 0, 1, 3, 2, 3, 5, 10, 99, 0 }; for (int j = 0; j < validLengths.Length; j++) { object o = constructors[i].Invoke(new object[] { validLowerBounds[j], validLengths[j] }); Assert.Equal(validLowerBounds[j], (int)getLowerBound.Invoke(o, new object[] { 0 })); Assert.Equal(validLowerBounds[j] + validLengths[j] - 1, (int)getUpperBound.Invoke(o, new object[] { 0 })); Assert.Equal(validLengths[j], (int)getLength.GetValue(o, null)); } } break; } } } [Fact] public void Invoke_2DArrayConstructor() { Type type = Type.GetType("System.Int32[,]", false); ConstructorInfo[] constructors = type.GetConstructors(); Assert.Equal(2, constructors.Length); for (int i = 0; i < constructors.Length; i++) { switch (constructors[i].GetParameters().Length) { case 2: { int[] invalidLengths1 = new int[] { -11, -10, 0, 10 }; int[] invalidLengths2 = new int[] { -33, 0, -20, -33 }; for (int j = 0; j < invalidLengths1.Length; j++) { Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLengths1[j], invalidLengths2[j] })); } int[] validLengths1 = new int[] { 0, 0, 1, 1, 2, 1, 2, 10, 17, 99 }; int[] validLengths2 = new int[] { 0, 1, 0, 1, 1, 2, 2, 110, 5, 900 }; for (int j = 0; j < validLengths1.Length; j++) { int[,] arr = (int[,])constructors[i].Invoke(new object[] { validLengths1[j], validLengths2[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(validLengths1[j] - 1, arr.GetUpperBound(0)); Assert.Equal(0, arr.GetLowerBound(1)); Assert.Equal(validLengths2[j] - 1, arr.GetUpperBound(1)); Assert.Equal(validLengths1[j] * validLengths2[j], arr.Length); } } break; case 4: { int[] invalidLowerBounds1 = new int[] { 10, -10, 20 }; int[] invalidLowerBounds2 = new int[] { -10, 10, 0 }; int[] invalidLengths3 = new int[] { -11, -10, 0 }; int[] invalidLengths4 = new int[] { -33, 0, -20 }; if (!PlatformDetection.IsNonZeroLowerBoundArraySupported) { Array.Clear(invalidLowerBounds1, 0, invalidLowerBounds1.Length); Array.Clear(invalidLowerBounds2, 0, invalidLowerBounds2.Length); } for (int j = 0; j < invalidLengths3.Length; j++) { Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLowerBounds1[j], invalidLengths3[j], invalidLowerBounds2[j], invalidLengths4[j] })); } int baseNum = 3; int baseNum4 = baseNum * baseNum * baseNum * baseNum; int[] validLowerBounds1 = new int[baseNum4]; int[] validLowerBounds2 = new int[baseNum4]; int[] validLengths1 = new int[baseNum4]; int[] validLengths2 = new int[baseNum4]; int cnt = 0; for (int pos1 = 0; pos1 < baseNum; pos1++) for (int pos2 = 0; pos2 < baseNum; pos2++) for (int pos3 = 0; pos3 < baseNum; pos3++) for (int pos4 = 0; pos4 < baseNum; pos4++) { int saved = cnt; validLowerBounds1[cnt] = saved % baseNum; saved = saved / baseNum; validLengths1[cnt] = saved % baseNum; saved = saved / baseNum; validLowerBounds2[cnt] = saved % baseNum; saved = saved / baseNum; validLengths2[cnt] = saved % baseNum; cnt++; } if (!PlatformDetection.IsNonZeroLowerBoundArraySupported) { Array.Clear(validLowerBounds1, 0, validLowerBounds1.Length); Array.Clear(validLowerBounds2, 0, validLowerBounds2.Length); } for (int j = 0; j < validLengths1.Length; j++) { int[,] arr = (int[,])constructors[i].Invoke(new object[] { validLowerBounds1[j], validLengths1[j], validLowerBounds2[j], validLengths2[j] }); Assert.Equal(validLowerBounds1[j], arr.GetLowerBound(0)); Assert.Equal(validLowerBounds1[j] + validLengths1[j] - 1, arr.GetUpperBound(0)); Assert.Equal(validLowerBounds2[j], arr.GetLowerBound(1)); Assert.Equal(validLowerBounds2[j] + validLengths2[j] - 1, arr.GetUpperBound(1)); Assert.Equal(validLengths1[j] * validLengths2[j], arr.Length); } // Lower can be < 0 validLowerBounds1 = new int[] { 10, 10, 65535, 40, 0, -10, -10, -20, -40, 0 }; validLowerBounds2 = new int[] { 5, 99, -100, 30, 4, -5, 99, 100, -30, 0 }; validLengths1 = new int[] { 1, 200, 2, 40, 0, 1, 200, 2, 40, 65535 }; validLengths2 = new int[] { 5, 10, 1, 0, 4, 5, 65535, 1, 0, 4 }; if (!PlatformDetection.IsNonZeroLowerBoundArraySupported) { Array.Clear(validLowerBounds1, 0, validLowerBounds1.Length); Array.Clear(validLowerBounds2, 0, validLowerBounds2.Length); } for (int j = 0; j < validLengths1.Length; j++) { int[,] arr = (int[,])constructors[i].Invoke(new object[] { validLowerBounds1[j], validLengths1[j], validLowerBounds2[j], validLengths2[j] }); Assert.Equal(validLowerBounds1[j], arr.GetLowerBound(0)); Assert.Equal(validLowerBounds1[j] + validLengths1[j] - 1, arr.GetUpperBound(0)); Assert.Equal(validLowerBounds2[j], arr.GetLowerBound(1)); Assert.Equal(validLowerBounds2[j] + validLengths2[j] - 1, arr.GetUpperBound(1)); Assert.Equal(validLengths1[j] * validLengths2[j], arr.Length); } } break; } } } [Fact] public void Invoke_LargeDimensionalArrayConstructor() { Type type = Type.GetType("System.Type[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]"); ConstructorInfo[] cia = type.GetConstructors(); Assert.Equal(2, cia.Length); Assert.Throws<TypeLoadException>(() => Type.GetType("System.Type[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]")); } [Fact] public void Invoke_JaggedArrayConstructor() { Type type = Type.GetType("System.String[][]"); ConstructorInfo[] constructors = type.GetConstructors(); Assert.Equal(2, constructors.Length); for (int i = 0; i < constructors.Length; i++) { switch (constructors[i].GetParameters().Length) { case 1: { int[] invalidLengths = new int[] { -11, -10, -99 }; for (int j = 0; j < invalidLengths.Length; j++) { Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLengths[j] })); } int[] validLengths = new int[] { 0, 1, 2, 10, 17, 99 }; for (int j = 0; j < validLengths.Length; j++) { string[][] arr = (string[][])constructors[i].Invoke(new object[] { validLengths[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(validLengths[j] - 1, arr.GetUpperBound(0)); Assert.Equal(validLengths[j], arr.Length); } } break; case 2: { int[] invalidLengths1 = new int[] { -11, -10, 10, 1 }; int[] invalidLengths2 = new int[] { -33, 0, -33, -1 }; for (int j = 0; j < invalidLengths1.Length; j++) { Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLengths1[j], invalidLengths2[j] })); } int[] validLengths1 = new int[] { 0, 0, 0, 1, 1, 2, 1, 2, 10, 17, 500 }; int[] validLengths2 = new int[] { -33, 0, 1, 0, 1, 1, 2, 2, 110, 5, 100 }; for (int j = 0; j < validLengths1.Length; j++) { string[][] arr = (string[][])constructors[i].Invoke(new object[] { validLengths1[j], validLengths2[j] }); Assert.Equal(0, arr.GetLowerBound(0)); Assert.Equal(validLengths1[j] - 1, arr.GetUpperBound(0)); Assert.Equal(validLengths1[j], arr.Length); if (validLengths1[j] == 0) { Assert.Equal(arr.Length, 0); } else { Assert.Equal(0, arr[0].GetLowerBound(0)); Assert.Equal(validLengths2[j] - 1, arr[0].GetUpperBound(0)); Assert.Equal(validLengths2[j], arr[0].Length); } } } break; } } } } }
using System; using SharpDX.Windows; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX; using Valve.VR; using SharpDX.Diagnostics; using System.Diagnostics; using System.Windows.Forms; using System.Collections.Generic; using System.IO; using Microsoft.Extensions.CommandLineUtils; public class VRApp : IDisposable { private const bool debugDevice = false; private static void ReportUnhandledException(object sender, UnhandledExceptionEventArgs e) { using (var dialog = new ThreadExceptionDialog(e.ExceptionObject as Exception)) { dialog.ShowDialog(); } } [STAThread] public static void Main(string[] args) { if (!Debugger.IsAttached) { AppDomain.CurrentDomain.UnhandledException += ReportUnhandledException; } var commandLineParser = new CommandLineApplication(false); var archiveOption = commandLineParser.Option("--content", "content directory", CommandOptionType.SingleValue); commandLineParser.Execute(args); string contentPath; if (archiveOption.HasValue()) { contentPath = archiveOption.Value(); } else { contentPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "content"); } var contentDir = new DirectoryInfo(contentPath); List<IArchiveDirectory> contentArchiveDirs = new List<IArchiveDirectory>(); foreach (var archiveDir in contentDir.GetDirectories()) { contentArchiveDirs.Add(UnpackedArchiveDirectory.Make(archiveDir)); } foreach (var archiveFile in contentDir.GetFiles("*.archive")) { var archive = new PackedArchive(archiveFile); contentArchiveDirs.Add(archive.Root); } var unionedArchiveDir = UnionArchiveDirectory.Join("content", contentArchiveDirs); LeakTracking.Setup(); string title = Application.ProductName + " " + Application.ProductVersion; try { using (VRApp app = new VRApp(unionedArchiveDir, title)) { app.Run(); } } catch (VRInitException e) { string text =String.Join("\n\n", String.Format("OpenVR initialization failed: {0}", e.Message), "Please make sure SteamVR is installed and running, and VR headset is connected."); string caption = "OpenVR Initialization Error"; MessageBox.Show(text, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); } LeakTracking.Finish(); } private readonly CompanionWindow companionWindow; private readonly Device device; private readonly ShaderCache shaderCache; private readonly DeviceContext immediateContext; private OpenVRTimeKeeper timeKeeper; private TrackedDevicePose_t[] poses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount]; private TrackedDevicePose_t[] gamePoses = new TrackedDevicePose_t[OpenVR.k_unMaxTrackedDeviceCount]; private readonly HiddenAreaMeshes hiddenAreaMeshes; private readonly StandardSamplers standardSamplers; private readonly FramePreparer framePreparer; private readonly AsyncFramePreparer asyncFramePreparer; private IPreparedFrame preparedFrame; private static Device CreateDevice() { SharpDX.DXGI.Adapter chosenAdapter = null; using (var dxgiFactory = new SharpDX.DXGI.Factory1()) { var adapters = dxgiFactory.Adapters; try { ulong adapterLuid = OpenVR.System.GetOutputDevice(ETextureType.DirectX, IntPtr.Zero); if (adapterLuid != 0) { foreach (var adapter in adapters) { if ((ulong) adapter.Description.Luid == adapterLuid) { chosenAdapter = adapter; } } } if (chosenAdapter == null) { //fallback to the default adapter chosenAdapter = adapters[0]; } var device = new Device(chosenAdapter, debugDevice ? DeviceCreationFlags.Debug : DeviceCreationFlags.None); return device; } finally { foreach (var adapter in adapters) { adapter.Dispose(); } } } } public VRApp(IArchiveDirectory dataDir, string title) { OpenVRExtensions.Init(); device = CreateDevice(); shaderCache = new ShaderCache(device); standardSamplers = new StandardSamplers(device); companionWindow = new CompanionWindow(device, shaderCache, standardSamplers, title, dataDir); immediateContext = device.ImmediateContext; timeKeeper = new OpenVRTimeKeeper(); hiddenAreaMeshes = new HiddenAreaMeshes(device); Size2 targetSize = OpenVR.System.GetRecommendedRenderTargetSize(); framePreparer = new FramePreparer(dataDir, device, shaderCache, standardSamplers, targetSize); asyncFramePreparer = new AsyncFramePreparer(framePreparer); } public void Dispose() { preparedFrame?.Dispose(); framePreparer.Dispose(); standardSamplers.Dispose(); hiddenAreaMeshes.Dispose(); OpenVR.Shutdown(); immediateContext.Dispose(); companionWindow.Dispose(); shaderCache.Dispose(); device.Dispose(); } private void Run() { //setup initial frame timeKeeper.Start(); OpenVR.Compositor.SetTrackingSpace(ETrackingUniverseOrigin.TrackingUniverseStanding); OpenVR.Compositor.GetLastPoses(poses, gamePoses); KickoffFramePreparation(); preparedFrame = asyncFramePreparer.FinishPreparingFrame(); RenderLoop.Run(companionWindow.Form, DoFrame); } private Texture2D mostRecentRenderTexture; private Matrix mostRecentProjectionTransform; private Texture2D RenderView(IPreparedFrame preparedFrame, HiddenAreaMesh hiddenAreaMesh, Matrix viewTransform, Matrix projectionTransform) { var renderTexture = preparedFrame.RenderView(device.ImmediateContext, hiddenAreaMesh, viewTransform, projectionTransform); mostRecentProjectionTransform = projectionTransform; mostRecentRenderTexture = renderTexture; return renderTexture; } private void SubmitEye(EVREye eye, IPreparedFrame preparedFrame) { immediateContext.WithEvent($"VRApp::SubmitEye({eye})", () => { HiddenAreaMesh hiddenAreaMesh = hiddenAreaMeshes.GetMesh(eye); Matrix viewMatrix = GetViewMatrix(eye); Matrix projectionMatrix = GetProjectionMatrix(eye); var resultTexture = RenderView(preparedFrame, hiddenAreaMesh, viewMatrix, projectionMatrix); VRTextureBounds_t bounds; bounds.uMin = 0; bounds.uMax = 1; bounds.vMin = 0; bounds.vMax = 1; Texture_t eyeTexture; eyeTexture.handle = resultTexture.NativePointer; eyeTexture.eType = ETextureType.DirectX; eyeTexture.eColorSpace = EColorSpace.Auto; OpenVR.Compositor.Submit(eye, ref eyeTexture, ref bounds, EVRSubmitFlags.Submit_Default); }); } private void PumpVREvents() { VREvent_t vrEvent = default(VREvent_t); while (OpenVR.System.PollNextEvent(ref vrEvent)) { EVREventType type = (EVREventType) vrEvent.eventType; switch (type) { case EVREventType.VREvent_Quit: companionWindow.Form.Close(); break; case EVREventType.VREvent_HideRenderModels: Debug.WriteLine("hide render models"); break; } OpenVRKeyboardHelper.ProcessEvent(vrEvent); } } private void KickoffFramePreparation() { var headPosition = companionWindow.HasIndependentCamera ? companionWindow.CameraPosition : PlayerPositionUtils.GetHeadPosition(gamePoses); var updateParameters = new FrameUpdateParameters( timeKeeper.NextFrameTime, //need to go one frame ahead because this is for the next frame timeKeeper.TimeDelta, gamePoses, headPosition); asyncFramePreparer.StartPreparingFrame(updateParameters); } private void DoFrame() { OpenVR.Compositor.WaitGetPoses(poses, gamePoses); timeKeeper.AdvanceFrame(); PumpVREvents(); KickoffFramePreparation(); immediateContext.WithEvent("VRApp::Prework", () => { preparedFrame.DoPrework(device.ImmediateContext, poses); }); SubmitEye(EVREye.Eye_Left, preparedFrame); SubmitEye(EVREye.Eye_Right, preparedFrame); if (companionWindow.HasIndependentCamera) { Matrix companionViewTransform = companionWindow.GetViewTransform(); Matrix companionWindowProjectionMatrix = companionWindow.GetDesiredProjectionMatrix(); immediateContext.WithEvent("VRApp::RenderCompanionView", () => { RenderView(preparedFrame, null, companionViewTransform, companionWindowProjectionMatrix); }); } companionWindow.Display( mostRecentRenderTexture, mostRecentProjectionTransform, () => preparedFrame.DrawCompanionWindowUi(device.ImmediateContext)); preparedFrame.DoPostwork(device.ImmediateContext); OpenVR.Compositor.PostPresentHandoff(); preparedFrame.Dispose(); preparedFrame = asyncFramePreparer.FinishPreparingFrame(); } private Matrix GetViewMatrix(EVREye eye) { var hmdPose = poses[OpenVR.k_unTrackedDeviceIndex_Hmd]; var hmdTransform = hmdPose.mDeviceToAbsoluteTracking.Convert(); hmdTransform.Invert(); Matrix eyeTransform = OpenVR.System.GetEyeToHeadTransform(eye).Convert(); eyeTransform.Invert(); Matrix viewTransform = hmdTransform * eyeTransform; return viewTransform; } private Matrix GetProjectionMatrix(EVREye eye) { Matrix projection = OpenVR.System.GetProjectionMatrix(eye, RenderingConstants.ZNear, RenderingConstants.ZFar).Convert(); return projection; } }
#region License // Copyright (c) 2010-2019, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License using System.Linq; namespace GccCommon { /// <summary> /// Abstract class representing any Gcc linker tool /// </summary> abstract class LinkerBase : C.LinkerTool { protected LinkerBase() { this.GccMetaData = Bam.Core.Graph.Instance.PackageMetaData<Gcc.MetaData>("Gcc"); var discovery = this.GccMetaData as C.IToolchainDiscovery; discovery.Discover(depth: null); this.Version = this.GccMetaData.ToolchainVersion; var ldPath = this.GccMetaData.LdPath; var installPath = Bam.Core.TokenizedString.CreateVerbatim(System.IO.Path.GetDirectoryName(ldPath)); this.EnvironmentVariables.Add("PATH", new Bam.Core.TokenizedStringArray(installPath)); this.Macros.AddVerbatim(C.ModuleMacroNames.ExecutableFileExtension, string.Empty); this.Macros.AddVerbatim(C.ModuleMacroNames.DynamicLibraryPrefix, "lib"); // TODO: should be able to build these up cumulatively, but the deferred expansion only // works for a single depth (up to the Module using this Tool) so this needs looking into this.Macros.AddVerbatim(C.ModuleMacroNames.SharedObjectLinkerNameFileExtension, ".so"); this.Macros.Add(C.ModuleMacroNames.SharedObjectSONameFileExtension, Bam.Core.TokenizedString.Create(".so.$(MajorVersion)", null)); // dynamicext MUST be forced inline, in order for the pre-function #valid // to evaluate in the correct context, i.e. this string can never be parsed out of context this.Macros.Add(C.ModuleMacroNames.DynamicLibraryFileExtension, Bam.Core.TokenizedString.CreateForcedInline(".so.$(MajorVersion)#valid(.$(MinorVersion)#valid(.$(PatchVersion)))")); this.Macros.AddVerbatim(C.ModuleMacroNames.PluginPrefix, "lib"); this.Macros.AddVerbatim(C.ModuleMacroNames.PluginFileExtension, ".so"); } /// <summary> /// Get the meta data for this tool /// </summary> protected Gcc.MetaData GccMetaData { get; private set; } private static string GetLPrefixLibraryName( string fullLibraryPath) { var libName = System.IO.Path.GetFileNameWithoutExtension(fullLibraryPath); libName = libName.Substring(3); // trim off lib prefix return $"-l{libName}"; } private static Bam.Core.Array<C.CModule> FindAllDynamicDependents( C.IDynamicLibrary dynamicModule) { var dynamicDeps = new Bam.Core.Array<C.CModule>(); if (!(dynamicModule as C.CModule).Dependents.Any()) { return dynamicDeps; } foreach (var dep in (dynamicModule as C.CModule).Dependents) { var dependent = dep; if (dependent is C.SharedObjectSymbolicLink symlinkDep) { dependent = symlinkDep.SharedObject; } if (!(dependent is C.IDynamicLibrary)) { continue; } var dynDep = dependent as C.CModule; dynamicDeps.AddUnique(dynDep); dynamicDeps.AddRangeUnique(FindAllDynamicDependents(dynDep as C.IDynamicLibrary)); } return dynamicDeps; } public override Bam.Core.TokenizedString GetLibraryPath( C.CModule library) { if (library is C.StaticLibrary) { return library.GeneratedPaths[C.StaticLibrary.LibraryKey]; } else if (library is C.IDynamicLibrary) { return library.GeneratedPaths[C.DynamicLibrary.ExecutableKey]; } else if ((library is C.CSDKModule) || (library is C.HeaderLibrary) || (library is C.OSXFramework)) { return null; } throw new Bam.Core.Exception($"Unsupported library type, {library.GetType().ToString()}"); } public override void ProcessLibraryDependency( C.CModule executable, C.CModule library) { var linker = executable.Settings as C.ICommonLinkerSettings; if (library is C.StaticLibrary) { // TODO: @filenamenoext var libraryPath = library.GeneratedPaths[C.StaticLibrary.LibraryKey].ToString(); // order matters on libraries - the last occurrence is always the one that matters to resolve all symbols var libraryName = GetLPrefixLibraryName(libraryPath); if (linker.Libraries.Contains(libraryName)) { linker.Libraries.Remove(libraryName); } linker.Libraries.Add(libraryName); foreach (var dir in library.OutputDirectories) { linker.LibraryPaths.AddUnique(dir); } } else if (library is C.IDynamicLibrary) { // TODO: @filenamenoext var libraryPath = library.GeneratedPaths[C.DynamicLibrary.ExecutableKey].ToString(); var linkerNameSymLink = (library as C.IDynamicLibrary).LinkerNameSymbolicLink; // TODO: I think there's a problem when there's no linkerName symlink - i.e. taking the full shared object path var libraryName = (linkerNameSymLink != null) ? GetLPrefixLibraryName( linkerNameSymLink.GeneratedPaths[C.SharedObjectSymbolicLink.SOSymLinkKey].ToString() ) : GetLPrefixLibraryName( libraryPath ); // order matters on libraries - the last occurrence is always the one that matters to resolve all symbols if (linker.Libraries.Contains(libraryName)) { linker.Libraries.Remove(libraryName); } linker.Libraries.Add(libraryName); var gccLinker = executable.Settings as GccCommon.ICommonLinkerSettings; foreach (var dir in library.OutputDirectories) { linker.LibraryPaths.AddUnique(dir); // if an explicit link occurs in this executable/shared object, the library path // does not need to be on the rpath-link if (gccLinker.RPathLink.Contains(dir)) { gccLinker.RPathLink.Remove(dir); } } var allDynamicDependents = FindAllDynamicDependents(library as C.IDynamicLibrary); foreach (var dep in allDynamicDependents) { foreach (var dir in dep.OutputDirectories) { // only need to add to rpath-link, if there's been no explicit link to the library already if (!linker.LibraryPaths.Contains(dir)) { gccLinker.RPathLink.AddUnique(dir); } } } } } /// <summary> /// \copydoc Bam.Core.ITool.SettingsType /// </summary> public override System.Type SettingsType => typeof(Gcc.LinkerSettings); /// <summary> /// Get the executable for this tool /// </summary> public override Bam.Core.TokenizedString Executable => this.Macros["LinkerPath"]; } /// <summary> /// Both 32-bit and 64-bit GCC C linkers /// </summary> [C.RegisterCLinker("GCC", Bam.Core.EPlatform.Linux, C.EBit.ThirtyTwo)] [C.RegisterCLinker("GCC", Bam.Core.EPlatform.Linux, C.EBit.SixtyFour)] sealed class Linker : LinkerBase { public Linker() => this.Macros.Add("LinkerPath", Bam.Core.TokenizedString.CreateVerbatim(this.GccMetaData.GccPath)); } /// <summary> /// Both 32-bit and 64-bit GCC C++ linkers /// </summary> [C.RegisterCxxLinker("GCC", Bam.Core.EPlatform.Linux, C.EBit.ThirtyTwo)] [C.RegisterCxxLinker("GCC", Bam.Core.EPlatform.Linux, C.EBit.SixtyFour)] sealed class LinkerCxx : LinkerBase { public LinkerCxx() => this.Macros.Add("LinkerPath", Bam.Core.TokenizedString.CreateVerbatim(this.GccMetaData.GxxPath)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using Xunit; namespace System.Reflection.Metadata.Tests { /// <summary> /// Assert style type to deal with the lack of features in xUnit's Assert type /// </summary> public static class AssertEx { public static unsafe void Equal(byte* expected, byte* actual) { Assert.Equal((IntPtr)expected, (IntPtr)actual); } #region AssertEqualityComparer<T> private class AssertEqualityComparer<T> : IEqualityComparer<T> { private static readonly IEqualityComparer<T> s_instance = new AssertEqualityComparer<T>(); private static bool CanBeNull() { var type = typeof(T); return !type.GetTypeInfo().IsValueType || (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static bool IsNull(T @object) { if (!CanBeNull()) { return false; } return object.Equals(@object, default(T)); } public static bool Equals(T left, T right) { return s_instance.Equals(left, right); } bool IEqualityComparer<T>.Equals(T x, T y) { if (CanBeNull()) { if (object.Equals(x, default(T))) { return object.Equals(y, default(T)); } if (object.Equals(y, default(T))) { return false; } } if (x.GetType() != y.GetType()) { return false; } var equatable = x as IEquatable<T>; if (equatable != null) { return equatable.Equals(y); } var comparableT = x as IComparable<T>; if (comparableT != null) { return comparableT.CompareTo(y) == 0; } var comparable = x as IComparable; if (comparable != null) { return comparable.CompareTo(y) == 0; } var enumerableX = x as IEnumerable; var enumerableY = y as IEnumerable; if (enumerableX != null && enumerableY != null) { var enumeratorX = enumerableX.GetEnumerator(); var enumeratorY = enumerableY.GetEnumerator(); while (true) { bool hasNextX = enumeratorX.MoveNext(); bool hasNextY = enumeratorY.MoveNext(); if (!hasNextX || !hasNextY) { return hasNextX == hasNextY; } if (!Equals(enumeratorX.Current, enumeratorY.Current)) { return false; } } } return object.Equals(x, y); } int IEqualityComparer<T>.GetHashCode(T obj) { throw new NotImplementedException(); } } #endregion public static void AreEqual<T>(T expected, T actual, string message = null, IEqualityComparer<T> comparer = null) { if (ReferenceEquals(expected, actual)) { return; } if (expected == null) { Fail("expected was null, but actual wasn't\r\n" + message); } else if (actual == null) { Fail("actual was null, but expected wasn't\r\n" + message); } else { if (!(comparer != null ? comparer.Equals(expected, actual) : AssertEqualityComparer<T>.Equals(expected, actual))) { Fail("Expected and actual were different.\r\n" + "Expected: " + expected + "\r\n" + "Actual: " + actual + "\r\n" + message); } } } public static void Equal<T>(ImmutableArray<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null, string message = null) { if (actual == null || expected.IsDefault) { Assert.True((actual == null) == expected.IsDefault, message); } else { Equal((IEnumerable<T>)expected, actual, comparer, message); } } public static void Equal<T>(IEnumerable<T> expected, ImmutableArray<T> actual, IEqualityComparer<T> comparer = null, string message = null, string itemSeparator = null) { if (expected == null || actual.IsDefault) { Assert.True((expected == null) == actual.IsDefault, message); } else { Equal(expected, (IEnumerable<T>)actual, comparer, message, itemSeparator); } } public static void Equal<T>(ImmutableArray<T> expected, ImmutableArray<T> actual, IEqualityComparer<T> comparer = null, string message = null, string itemSeparator = null) { Equal(expected, (IEnumerable<T>)actual, comparer, message, itemSeparator); } public static void Equal<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null, string message = null, string itemSeparator = null, Func<T, string> itemInspector = null) { if (ReferenceEquals(expected, actual)) { return; } if (expected == null) { Fail("expected was null, but actual wasn't\r\n" + message); } else if (actual == null) { Fail("actual was null, but expected wasn't\r\n" + message); } else if (!SequenceEqual(expected, actual, comparer)) { string assertMessage = GetAssertMessage(expected, actual, comparer, itemInspector, itemSeparator); if (message != null) { assertMessage = message + "\r\n" + assertMessage; } Assert.True(false, assertMessage); } } private static bool SequenceEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null) { var enumerator1 = expected.GetEnumerator(); var enumerator2 = actual.GetEnumerator(); while (true) { var hasNext1 = enumerator1.MoveNext(); var hasNext2 = enumerator2.MoveNext(); if (hasNext1 != hasNext2) { return false; } if (!hasNext1) { break; } var value1 = enumerator1.Current; var value2 = enumerator2.Current; if (!(comparer != null ? comparer.Equals(value1, value2) : AssertEqualityComparer<T>.Equals(value1, value2))) { return false; } } return true; } public static void SetEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null, string message = null, string itemSeparator = "\r\n") { var expectedSet = new HashSet<T>(expected, comparer); var result = expected.Count() == actual.Count() && expectedSet.SetEquals(actual); if (!result) { if (string.IsNullOrEmpty(message)) { message = GetAssertMessage( ToString(expected, itemSeparator), ToString(actual, itemSeparator)); } Assert.True(result, message); } } public static void SetEqual<T>(IEnumerable<T> actual, params T[] expected) { var expectedSet = new HashSet<T>(expected); Assert.True(expectedSet.SetEquals(actual), string.Format("Expected: {0}\nActual: {1}", ToString(expected), ToString(actual))); } public static void None<T>(IEnumerable<T> actual, Func<T, bool> predicate) { var none = !actual.Any(predicate); if (!none) { Assert.True(none, string.Format( "Unexpected item found among existing items: {0}\nExisting items: {1}", ToString(actual.First(predicate)), ToString(actual))); } } public static void Any<T>(IEnumerable<T> actual, Func<T, bool> predicate) { var any = actual.Any(predicate); Assert.True(any, string.Format("No expected item was found.\nExisting items: {0}", ToString(actual))); } public static void All<T>(IEnumerable<T> actual, Func<T, bool> predicate) { var all = actual.All(predicate); if (!all) { Assert.True(all, string.Format( "Not all items satisfy condition:\n{0}", ToString(actual.Where(i => !predicate(i))))); } } public static string ToString(object o) { return Convert.ToString(o); } public static string ToString<T>(IEnumerable<T> list, string separator = ", ", Func<T, string> itemInspector = null) { if (itemInspector == null) { itemInspector = i => Convert.ToString(i); } return string.Join(separator, list.Select(itemInspector)); } public static void Fail(string message) { Assert.False(true, message); } public static void Fail(string format, params object[] args) { Assert.False(true, string.Format(format, args)); } public static void NotNull<T>(T @object, string message = null) { Assert.False(AssertEqualityComparer<T>.IsNull(@object), message); } // compares against a baseline public static void AssertEqualToleratingWhitespaceDifferences( string expected, string actual, bool escapeQuotes = true, [CallerFilePath]string expectedValueSourcePath = null, [CallerLineNumber]int expectedValueSourceLine = 0) { var normalizedExpected = NormalizeWhitespace(expected); var normalizedActual = NormalizeWhitespace(actual); if (normalizedExpected != normalizedActual) { Assert.True(false, GetAssertMessage(expected, actual, escapeQuotes, expectedValueSourcePath, expectedValueSourceLine)); } } // compares two results (no baseline) public static void AssertResultsEqual(string result1, string result2) { if (result1 != result2) { Assert.True(false, GetAssertMessage(result1, result2)); } } public static void AssertContainsToleratingWhitespaceDifferences(string expectedSubString, string actualString) { expectedSubString = NormalizeWhitespace(expectedSubString); actualString = NormalizeWhitespace(actualString); Assert.Contains(expectedSubString, actualString, StringComparison.Ordinal); } internal static string NormalizeWhitespace(string input) { var output = new StringBuilder(); var inputLines = input.Split('\n', '\r'); foreach (var line in inputLines) { var trimmedLine = line.Trim(); if (trimmedLine.Length > 0) { if (!(trimmedLine[0] == '{' || trimmedLine[0] == '}')) { output.Append(" "); } output.AppendLine(trimmedLine); } } return output.ToString(); } public static string GetAssertMessage(string expected, string actual, bool escapeQuotes = false, string expectedValueSourcePath = null, int expectedValueSourceLine = 0) { return GetAssertMessage(DiffUtil.Lines(expected), DiffUtil.Lines(actual), escapeQuotes, expectedValueSourcePath, expectedValueSourceLine); } public static string GetAssertMessage<T>(IEnumerable<T> expected, IEnumerable<T> actual, bool escapeQuotes, string expectedValueSourcePath = null, int expectedValueSourceLine = 0) { Func<T, string> itemInspector = escapeQuotes ? new Func<T, string>(t => t.ToString().Replace("\"", "\"\"")) : null; return GetAssertMessage(expected, actual, itemInspector: itemInspector, itemSeparator: "\r\n", expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); } private static readonly string s_diffToolPath = Environment.GetEnvironmentVariable("ROSLYN_DIFFTOOL"); public static string GetAssertMessage<T>( IEnumerable<T> expected, IEnumerable<T> actual, IEqualityComparer<T> comparer = null, Func<T, string> itemInspector = null, string itemSeparator = null, string expectedValueSourcePath = null, int expectedValueSourceLine = 0) { if (itemInspector == null) { if (typeof(T) == typeof(byte)) { itemInspector = b => $"0x{b:X2}"; } else { itemInspector = new Func<T, string>(obj => (obj != null) ? obj.ToString() : "<null>"); } } if (itemSeparator == null) { if (expected is IEnumerable<byte>) { itemSeparator = ", "; } else { itemSeparator = ",\r\n"; } } var expectedString = string.Join(itemSeparator, expected.Select(itemInspector)); var actualString = string.Join(itemSeparator, actual.Select(itemInspector)); var message = new StringBuilder(); message.AppendLine(); message.AppendLine("Expected:"); message.AppendLine(expectedString); message.AppendLine("Actual:"); message.AppendLine(actualString); message.AppendLine("Differences:"); message.AppendLine(DiffUtil.DiffReport(expected, actual, comparer, itemInspector, itemSeparator)); return message.ToString(); } public static void Empty<T>(IEnumerable<T> items, string message = "") { // realize the list in case it can't be traversed twice via .Count()/.Any() and .Select() var list = items.ToList(); if (list.Count != 0) { Fail($"Expected 0 items but found {list.Count}: {message}\r\nItems:\r\n {string.Join("\r\n ", list)}"); } } public static void Throws<T>(Func<object> testCode, Action<T> exceptionValidation) where T : Exception { try { testCode(); Assert.False(true, $"Exception of type '{typeof(T)}' was expected but none was thrown."); } catch (T e) { exceptionValidation(e); } catch (Exception e) { Assert.False(true, $"Exception of type '{typeof(T)}' was expected but '{e.GetType()}' was thrown instead."); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class NetworkScript:MonoBehaviour { public bool isServer = false; public string uniqueGameName = "KDC7dfps2013"; public string serverName; public bool connected = false; public string playerName; public string skinURL; public bool hasSkin; public GameObject fpsEntityPrefab; public List<FPSController> fpsEntities = new List<FPSController>(); public GameObject spawnHolder; public List<Transform> spawnPoints = new List<Transform>(); public NetworkViewID netviewID; public bool preppingLevel = false; public bool levelLoaded; public string levelString; public int lastLevelPrefix = 0; public bool useNat; public int port = 2300; public int gameMode = 0; public string gameModeString; public int level = 0; public int maxPlayers; public string comment; public HostData[] hostData; public bool hasRegistered = false; public bool hasSetGUI = false; public GUIScript myGUI; private float dmg; private string gName; //Damage Variables: private float pistolDmg = 20f; private float machineDmg = 15f; private float rocketDmg = 90f; private float shotgunDmg = 40f; private float railgunDmg = 1000f; // Use this for initialization void Start() { DontDestroyOnLoad(this); //Get Servers: MasterServer.RequestHostList(uniqueGameName); hostData = MasterServer.PollHostList(); if(PlayerPrefs.GetString("skinURL") != null || PlayerPrefs.GetString("skinURL") != " ") { skinURL = PlayerPrefs.GetString("playerSkinURL"); hasSkin = true; }else{ hasSkin = false; } if(PlayerPrefs.GetString("playerName") != null || PlayerPrefs.GetString("playerName") != " ") { playerName = PlayerPrefs.GetString("playerName"); } else { playerName = "DefaultName"; PlayerPrefs.SetString("playerName", "DefaultName"); } } // Update is called once per frame void Update() { if(levelLoaded && !hasSetGUI) { for(int i = 0; i < fpsEntities.Count; i++) { if(fpsEntities[i].viewID == netviewID) { myGUI = fpsEntities[i].gameObject.GetComponent<GUIScript>(); } } hasSetGUI = true; } if(!connected) { Screen.lockCursor = false; Screen.showCursor = true; } } public void Connect(HostData connectData) { Debug.Log("Connecting to " + connectData.ToString() + "."); Network.Connect(connectData); } public void StartServer(string name, int max, int gm, int map) { serverName = name; level = map; gameMode = gm; maxPlayers = max; useNat = !Network.HavePublicAddress(); Network.InitializeServer(max, port, useNat); } void OnConnectedToServer() { Debug.Log ("Connected to server."); connected = true; } void OnServerInitialized() { Debug.Log("Server initialized."); switch(level) { case(0): levelString = "TestLevel"; break; } switch(gameMode) { case(0): gameModeString = "FFA"; break; } isServer = true; connected = true; comment = levelString + "|" + gameModeString; MasterServer.RegisterHost(uniqueGameName, serverName, comment); } void OnMasterServerEvent(MasterServerEvent msEvent) { if(msEvent == MasterServerEvent.RegistrationSucceeded && !hasRegistered && isServer && connected) { Debug.Log("Server Registration Succeeded"); networkView.RPC( "LoadLevel", RPCMode.AllBuffered, level, lastLevelPrefix + 1); lastLevelPrefix++; hasRegistered = true; } else if(msEvent == MasterServerEvent.RegistrationFailedNoServer || msEvent == MasterServerEvent.RegistrationFailedGameType) { Network.Disconnect(); } } [RPC] void LoadLevel(int level, int levelPrefix) { switch(level) { case(0): levelString = "TestLevel"; break; } Network.SetSendingEnabled(0, false); Network.isMessageQueueRunning = true; Network.SetLevelPrefix(levelPrefix); preppingLevel = true; Application.LoadLevel(levelString); //Network.isMessageQueueRunning = true; Network.SetSendingEnabled(0, true); } void OnLevelWasLoaded() { if(connected) { Debug.Log("Level " + levelString + " was loaded."); levelLoaded = true; preppingLevel = false; spawnHolder = GameObject.FindGameObjectWithTag("Spawn"); foreach(Transform child in spawnHolder.GetComponentsInChildren<Transform>()) { if(child.gameObject.tag != "Spawn") spawnPoints.Add(child); } netviewID = Network.AllocateViewID(); InstantiateFPSEntity(true, netviewID, playerName, hasSkin, skinURL); networkView.RPC("NewPlayer", RPCMode.OthersBuffered, netviewID, playerName, hasSkin, skinURL); }else{ Debug.Log("The main menu was loaded."); } } [RPC] void NewPlayer(NetworkViewID viewID, string name, bool hasSkin, string skinURL) { InstantiateFPSEntity(false, viewID, name, hasSkin, skinURL); } void InstantiateFPSEntity(bool isLocal, NetworkViewID anID, string name, bool hasSkin, string skinURL) { if(levelLoaded) { Debug.Log("Make a new player, isLocal " + isLocal); GameObject newEntity = (GameObject)GameObject.Instantiate(fpsEntityPrefab); FPSController entity = newEntity.GetComponent<FPSController>(); entity.hasSkin = hasSkin; entity.skinURL = skinURL; entity.myName = name; if(isLocal) { entity.viewID = netviewID; entity.isLocal = true; }else{ entity.isLocal = false; entity.viewID = anID; } fpsEntities.Add(entity); }else{ StartCoroutine(WaitMakeNewPlayer(isLocal, anID, name, hasSkin, skinURL)); } } void OnPlayerConnected(NetworkPlayer player) { if(connected) { Debug.Log("Player connected from " + player.ipAddress + ":" + player.port); } } //Send my player shit: public void SendPlayer(NetworkViewID viewID, Vector3 pos, Vector3 ang, Vector3 moveVec, int myGun, bool iShot, float myHp) { if(connected) { //Send everyone else an RPC with my shit: networkView.RPC("SendPlayerRPC", RPCMode.Others, viewID, pos, ang, moveVec, myGun, iShot, myHp); } } //Recive player information: [RPC] void SendPlayerRPC(NetworkViewID viewID, Vector3 pos, Vector3 ang, Vector3 moveVec, int gun, bool shot, float hp) { if(connected) { for(int i = 0; i < fpsEntities.Count; i++) { if(viewID == fpsEntities[i].viewID) { //Update this players values: fpsEntities[i].UpdatePlayer(pos, ang, moveVec, gun, shot, hp); } } } } public void RegisterHit(NetworkViewID theShooter, NetworkViewID theVictim, int theGun) { //if(gameOver) return; if(!isServer) { networkView.RPC("RegisterHitRPC", RPCMode.Server, theShooter, theVictim, theGun); }else{ RegisterHitRPC(theShooter, theVictim, theGun); } } [RPC] void RegisterHitRPC(NetworkViewID shooter, NetworkViewID victim, int gun) { bool killingBlow= false; int shooterIndex = -1; int victimIndex = -1; float gunDamage = GetDamage(gun); //Find shooter and victim: for(int i = 0; i < fpsEntities.Count; i++) { if(fpsEntities[i].viewID == shooter) shooterIndex = i; if(fpsEntities[i].viewID == victim) victimIndex = i; } //If the player doesn't exist in our list or shot themselves, stop. if(shooterIndex == -1 || victimIndex == -1 || shooterIndex == victimIndex) return; fpsEntities[victimIndex].currentHealth -= gunDamage; if(fpsEntities[victimIndex].currentHealth <= 0f) { fpsEntities[victimIndex].currentHealth = 0f; killingBlow = true; } if(killingBlow) { fpsEntities[victimIndex].deaths++; fpsEntities[shooterIndex].kills++; } networkView.RPC("UpdatePlayerStats", RPCMode.All, victim, fpsEntities[victimIndex].currentHealth, fpsEntities[victimIndex].kills, fpsEntities[victimIndex].deaths); networkView.RPC("UpdatePlayerStats", RPCMode.All, shooter, fpsEntities[shooterIndex].currentHealth, fpsEntities[shooterIndex].kills, fpsEntities[shooterIndex].deaths); if(killingBlow) { string shooterName = fpsEntities[shooterIndex].myName; string victimName = fpsEntities[victimIndex].myName; string gunString = GetGunName(gun); networkView.RPC("SendMessageRPC", RPCMode.All, shooterName, " killed " + victimName + " with a " + gunString + "."); networkView.RPC("KillerRPC", RPCMode.All, shooter); networkView.RPC("DeathRPC", RPCMode.All, victim); //Check for win conditions: // // // // //TODO: } } [RPC] void UpdatePlayerStats(NetworkViewID viewID, float hp, int kills, int deaths) { for(int i = 0; i < fpsEntities.Count; i++) { if(fpsEntities[i].viewID == viewID) { fpsEntities[i].currentHealth = hp; fpsEntities[i].kills = kills; fpsEntities[i].deaths = deaths; } } } [RPC] void KillerRPC(NetworkViewID viewID) { if(viewID == netviewID) { for(int i = 0; i < fpsEntities.Count; i++) { if(fpsEntities[i].viewID == netviewID) { fpsEntities[i].Killer(); } } } } [RPC] void DeathRPC(NetworkViewID viewID) { if(viewID == netviewID) { for(int i = 0; i < fpsEntities.Count; i++) { if(fpsEntities[i].viewID == netviewID) { fpsEntities[i].Death(); } } } } public void RefreshServers() { //Get Servers: Debug.Log("Refreshing servers."); MasterServer.RequestHostList(uniqueGameName); hostData = MasterServer.PollHostList(); } void OnApplicationQuit() { if(connected) { if(isServer) { networkView.RPC("ServerLeave", RPCMode.OthersBuffered); }else{ networkView.RPC("PlayerLeave", RPCMode.OthersBuffered, netviewID); } if(isServer) MasterServer.UnregisterHost(); Network.Disconnect(); } } [RPC] void PlayerLeave(NetworkViewID viewID) { Debug.Log("Player " + viewID.ToString() + " has left."); for(int i = 0; i < fpsEntities.Count; i++) { if(fpsEntities[i].viewID == viewID) { Destroy(fpsEntities[i].gameObject); fpsEntities.RemoveAt(i); } } } [RPC] void ServerLeave() { if(isServer) MasterServer.UnregisterHost(); else Debug.Log("Server disconnected D:"); connected = false; isServer = false; Network.Disconnect(); } void OnDisconnectedFromServer() { //Reset all the variables we use: Debug.Log("Loading main menu."); for(int i = 0; i < fpsEntities.Count; i++) { Destroy(fpsEntities[i].gameObject); fpsEntities.RemoveAt(i); } netviewID = new NetworkViewID(); hasSetGUI = false; myGUI = null; isServer = false; connected = false; levelLoaded = false; spawnHolder = null; spawnPoints = new List<Transform>(); fpsEntities = new List<FPSController>(); hasRegistered = false; Application.LoadLevel("Menu"); } public void Kick(int playerIndex) { Network.CloseConnection(fpsEntities[playerIndex].viewID.owner, false); networkView.RPC("KickedPlayer", RPCMode.AllBuffered, fpsEntities[playerIndex].viewID); } [RPC] void KickedPlayer(NetworkViewID viewID) { string kickedName = "???"; for(int i = 0; i < fpsEntities.Count; i++) { if(fpsEntities[i].viewID == viewID) { kickedName = fpsEntities[i].myName; if(fpsEntities[i] != null) Destroy(fpsEntities[i].gameObject); fpsEntities.RemoveAt(i); } } //Send chat message saying "name" was kicked: SendChatMessage(kickedName, " was kicked by the host."); } public void DisconnectMe() { if(connected) { Debug.Log("Disconnecting from server."); if(isServer) { networkView.RPC("ServerLeave", RPCMode.OthersBuffered); }else{ networkView.RPC("PlayerLeave", RPCMode.OthersBuffered, netviewID); } if(isServer) MasterServer.UnregisterHost(); levelLoaded = false; Network.Disconnect(); connected = false; } } IEnumerator WaitMakeNewPlayer(bool isLocal, NetworkViewID anID, string name, bool hasSkin, string skinURL) { Debug.Log("Waiting 5 seconds then trying to make a new player again."); yield return new WaitForSeconds(5); InstantiateFPSEntity(isLocal, anID, name, hasSkin, skinURL); } //Chat public void SendChatMessage(string sender, string msg) { networkView.RPC("SendMessageRPC", RPCMode.All, sender, msg); } [RPC] void SendMessageRPC(string name, string msg) { Debug.Log("MSG: " + name + " " + msg); ChatMessage newMessage = new ChatMessage(); newMessage.sender = name; newMessage.message = msg; myGUI.messages.Add(newMessage); myGUI.textDisplayTime = Time.time + myGUI.chatFadeTime; } float GetDamage(int gun) { switch(gun) { case(0): dmg = 0f; break; case(1): dmg = pistolDmg; break; case(2): dmg = machineDmg; break; case(3): dmg = rocketDmg; break; case(4): dmg = shotgunDmg; break; case(5): dmg = railgunDmg; break; } return dmg; } string GetGunName(int gun) { switch(gun) { case(0): gName = "nothing"; break; case(1): gName = "pistol"; break; case(2): gName = "machine gun"; break; case(3): gName = "rocket launcher"; break; case(4): gName = "shotgun"; break; case(5): gName = "railgun"; break; } return gName; } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityObject = UnityEngine.Object; namespace Vexe.Runtime.Extensions { public static class GameObjectExtensions { public static void DestroyChildren(this Transform transform) { DestroyChildren(transform.gameObject); } public static void DestroyChildren(this GameObject gameObject) { var children = gameObject.GetChildren().ToList(); for (int i = 0, cnt = children.Count; i < cnt; i++) { var child = children[i]; child.Destroy(); } } public static string GetParentName(this GameObject source) { var parent = source.transform.parent; return parent == null ? string.Empty : parent.name; } public static bool HasComponent(this Transform source, Type componentType) { return HasComponent(source.gameObject, componentType); } public static bool HasComponent(this GameObject source, Type componentType) { return source.GetComponent(componentType) != null; } public static bool HasComponent(this Transform source, string componentName) { return HasComponent(source.gameObject, componentName); } public static bool HasComponent(this GameObject source, string componentName) { return source.GetComponent(componentName) != null; } public static bool HasComponent<T>(this Transform source) where T : Component { return HasComponent<T>(source.gameObject); } public static bool HasComponent<T>(this GameObject source) where T : Component { return source.GetComponent<T>() != null; } /// <summary> /// Recursively returns children gameObjects excluding inactive ones /// </summary> public static IEnumerable<GameObject> GetChildren(this GameObject parent) { return GetChildren(parent, false); } /// <summary> /// Recursively returns children gameObjects /// </summary> public static IEnumerable<GameObject> GetChildren(this GameObject parent, bool includeInactive) { var transform = parent.transform; int count = transform.childCount; for (int i = 0; i < count; i++) { yield return transform.GetChild(i).gameObject; } } /// <summary> /// Considers the gameObject's parents in the name /// ex: if 'Child' had a parent "Parent1" and "Parent1" had a parent "Parent2" /// the result is "Parent2.Parent1.Child" /// </summary> public static string GetLongName(this GameObject gameObject) { var parents = gameObject.GetParents(); return parents.IsEmpty() ? gameObject.name : string.Join(".", parents.Select(p => p.name) .Reverse() .ToArray() ) + "." + gameObject.name; } /// <summary> /// Deactivates (calls SetActive(false)) this gameObject /// </summary> public static void Deactivate(this GameObject go) { go.SetActive(false); } /// <summary> /// Activates (calls SetActive(true)) this gameObject /// </summary> public static void Activate(this GameObject go) { go.SetActive(true); } /// <summary> /// Returns an array of all the components attached to this gameObject with the gameObject included /// </summary> public static UnityObject[] GetAllComponentsIncludingSelf(this GameObject go) { Component[] comps = go.GetAllComponents(); int len = comps.Length; UnityObject[] targets = new UnityObject[len + 1]; Array.Copy(comps, 0, targets, 1, len); targets[0] = go; return targets; } /// <summary> /// Destroys all children objects under this gameObject /// </summary> public static void ClearChildren(this GameObject go) { ClearChildren(go, child => true); } /// <summary> /// Destroys children objects under this gameObject meeting the specified predicate condition /// </summary> public static void ClearChildren(this GameObject go, Predicate<GameObject> predicate) { var all = go.GetComponentsInChildren<Transform>(); for (int i = all.Length - 1; i > 0; i--) { var child = all[i].gameObject; if (predicate(child)) child.Destroy(true); } } /// <summary> /// Destroys all components in this gameObject /// </summary> public static void ClearComponents(this GameObject go) { ClearComponents(go, c => true); } /// <summary> /// Destroys any component in this gameObject meeting the specified predicate /// </summary> public static void ClearComponents(this GameObject go, Predicate<Component> predicate) { var all = GetAllComponents(go); for (int i = all.Length - 1; i > 0; i--) // Skip Transform { var c = all[i]; if (predicate(c)) c.Destroy(); } } /// <summary> /// Returns an array of all the components attached to this gameObject /// </summary> public static Component[] GetAllComponents(this GameObject go) { return go.GetComponents<Component>(); } /// <summary> /// Returns the names of all the components attached to this gameObject /// </summary> public static string[] GetComponentsNames(this GameObject go) { return go.GetAllComponents().Select(c => c.GetType().Name).ToArray(); } /// <summary> /// Returns an array of the parent gameObjects above this gameObject /// Ex: say we had the following hierarchy: /// GO 1 /// --- GO 1.1 /// --- GO 1.2 /// ----- GO 1.2.1 /// Then the parents of GO 1.2.1 are GO 1.2 and GO 1 /// </summary> public static GameObject[] GetParents(this GameObject go) { return EnumerateParentObjects(go).ToArray(); } /// <summary> /// Returns a lazy enumerable of the parent gameObjects above this gameObject /// Ex: say we had the following hierarchy: /// GO 1 /// --- GO 1.1 /// --- GO 1.2 /// ----- GO 1.2.1 /// Then the parents of GO 1.2.1 are GO 1.2 and GO 1 /// </summary> public static IEnumerable<GameObject> EnumerateParentObjects(this GameObject go) { var currentParent = go.transform.parent; while (currentParent != null) { yield return currentParent.gameObject; currentParent = currentParent.parent; } } public static Component GetOrAddComponent(this GameObject go, Type componentType) { var result = go.GetComponent(componentType); return result == null ? go.AddComponent(componentType) : result; } public static T GetOrAddComponent<T>(this GameObject go) where T : Component { return GetOrAddComponent(go, typeof(T)) as T; } /// <summary> /// Gets the child gameObject whose name is specified by 'wanted' /// The search is non-recursive by default unless true is passed to 'recursive' /// </summary> public static GameObject GetChild(this GameObject inside, string wanted, bool recursive = false) { foreach (Transform child in inside.transform) { if (child.name == wanted) return child.gameObject; if (recursive) { var within = GetChild(child.gameObject, wanted, true); if (within != null) return within; } } return null; } /// <summary> /// Adds and returns a child gameObject to this gameObject with the specified name and HideFlags /// </summary> public static GameObject AddChild(this GameObject parent, string name, HideFlags flags = HideFlags.None) { return AddRelative(parent, name, relative => { relative.parent = parent.transform; relative.Reset(); }, flags); } private static GameObject AddRelative(this GameObject from, string name, Action<Transform> setParent, HideFlags flags = HideFlags.None) { var relative = new GameObject(name); relative.hideFlags = flags; setParent(relative.transform); return relative; } /// <summary> /// Gets or adds the child gameObject whose name is 'name' /// Pass true to 'recursive' if you want the search to be recursive /// Specify HideFlags if you want to add the child using those flags /// </summary> public static GameObject GetOrAddChild(this GameObject parent, string name, bool recursive = false, HideFlags flags = HideFlags.None) { var child = parent.GetChild(name, recursive); return child == null ? parent.AddChild(name, flags) : child; } /// <summary> /// Gets the gameObject child under this gameObject whose path is specified by childPath /// </summary> public static GameObject GetChildAtPath(this GameObject inside, string childPath, bool throwIfNotFound) { return GetRelativeAtPath(inside, "child", childPath, throwIfNotFound, (path, child) => child.GetChild(path)); } /// <summary> /// Gets the gameObject child under this gameObject whose path is specified by childPath /// Throws an InvalidOperationException is not found /// </summary> public static GameObject GetChildAtPath(this GameObject inside, string childPath) { return GetChildAtPath(inside, childPath, true); } /// <summary> /// Gets or adds if not found the gameObject child under this gameObject whose path is specified by childPath /// </summary> public static GameObject GetOrAddChildAtPath(this GameObject inside, string childPath) { return GetOrAddRelativeAtPath(inside, childPath, (path, parent) => parent.GetChild(path), (path, parent) => parent.AddChild(path) ); } /// <summary> /// Adds and returns a parent gameObject to this gameObject with the specified name and HideFlags /// </summary> public static GameObject AddParent(this GameObject child, string name, HideFlags flags = HideFlags.None) { return AddRelative(child, name, relative => { child.transform.parent = relative; child.transform.Reset(); }, flags); } /// <summary> /// Gets the parent whose name is wanted above this gameObject /// </summary> public static GameObject GetParent(this GameObject child, string wanted) { Transform currentParent = child.transform.parent; while (currentParent != null) { if (currentParent.name == wanted) return currentParent.gameObject; currentParent = currentParent.parent; } return null; } /// <summary> /// Gets or add the specified parent to this gameObject /// </summary> public static GameObject GetOrAddParent(this GameObject child, string name, HideFlags flags = HideFlags.None) { var parent = child.GetParent(name); return parent == null ? child.AddParent(name, flags) : parent; } /// <summary> /// Gets the parent of this gameObject whose path is specified by parentPath /// </summary> public static GameObject GetParentAtPath(this GameObject from, string parentPath, bool throwIfNotFound) { return GetRelativeAtPath(from, "parent", parentPath, throwIfNotFound, (path, parent) => parent.GetParent(path)); } /// <summary> /// Gets the parent of this gameObject whose path is specified by parentPath /// Throws an InvalidOperationException if not found /// </summary> public static GameObject GetParentAtPath(this GameObject from, string parentPath) { return GetParentAtPath(from, parentPath, true); } /// <summary> /// Gets or adds the parent to this gameObject whose path is specifeid by parentPath /// </summary> /// <param name="from"></param> /// <param name="parentPath"></param> /// <returns></returns> public static GameObject GetOrAddParentAtPath(this GameObject from, string parentPath) { return GetOrAddRelativeAtPath(from, parentPath, (path, child) => child.GetParent(path), (path, child) => child.AddParent(path) ); } private static GameObject GetOrAddRelativeAtPath(this GameObject from, string relativePath, Func<string, GameObject, GameObject> get, Func<string, GameObject, GameObject> add) { return OperateOnRelativeAtPath(from, relativePath, (operatingName, previous, current) => { if (current == null) current = add(operatingName, previous); return current; }, get); } private static GameObject GetRelativeAtPath(this GameObject from, string relative, string relativePath, bool throwIfNotFound, Func<string, GameObject, GameObject> get) { return OperateOnRelativeAtPath(from, relativePath, (operatingName, previous, current) => { if (current == null && throwIfNotFound) throw new InvalidOperationException(relative + " wasn't found at path `" + relativePath + "`"); return current; }, get); } private static GameObject OperateOnRelativeAtPath( GameObject inside, string relativePath, Func<string, GameObject, GameObject, GameObject> operate, Func<string, GameObject, GameObject> get) { if (inside == null) throw new ArgumentNullException("inside"); string[] relatives = relativePath.Split('/'); GameObject current = inside; int i = 0; do { var relative = relatives[i]; var previous = current; current = get(relative, current); current = operate(relative, previous, current); } while (current != null && ++i < relatives.Length); return current == inside ? null : current; } public static void ToggleActive(this GameObject go) { go.SetActive(!go.activeSelf); } public static void SetActiveIfNot(this GameObject go, bool to) { if (go.activeSelf != to) go.SetActive(to); } } }
// // Copyright (c) 2004-2018 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System.Collections; using System.Linq; using System.Threading; using NLog.LayoutRenderers; using System.Xml; using NLog.Config; using NLog.UnitTests.LayoutRenderers; #if !NETSTANDARD namespace NLog.UnitTests { using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.IO; using System.Text; using Microsoft.CSharp; using Xunit; using NLog.Layouts; using System.Collections.Generic; public class ConfigFileLocatorTests : NLogTestBase { private string appConfigContents = @" <configuration> <configSections> <section name='nlog' type='NLog.Config.ConfigSectionHandler, NLog' requirePermission='false' /> </configSections> <nlog> <targets> <target name='c' type='Console' layout='AC ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> </configuration> "; private string appNLogContents = @" <nlog> <targets> <target name='c' type='Console' layout='AN ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string nlogConfigContents = @" <nlog> <targets> <target name='c' type='Console' layout='NLC ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string nlogDllNLogContents = @" <nlog> <targets> <target name='c' type='Console' layout='NDN ${message}' /> </targets> <rules> <logger name='*' minLevel='Info' writeTo='c' /> </rules> </nlog> "; private string appConfigOutput = "--BEGIN--|AC InfoMsg|AC WarnMsg|AC ErrorMsg|AC FatalMsg|--END--|"; private string appNLogOutput = "--BEGIN--|AN InfoMsg|AN WarnMsg|AN ErrorMsg|AN FatalMsg|--END--|"; private string nlogConfigOutput = "--BEGIN--|NLC InfoMsg|NLC WarnMsg|NLC ErrorMsg|NLC FatalMsg|--END--|"; private string nlogDllNLogOutput = "--BEGIN--|NDN InfoMsg|NDN WarnMsg|NDN ErrorMsg|NDN FatalMsg|--END--|"; private string missingConfigOutput = "--BEGIN--|--END--|"; private readonly string _tempDirectory; public ConfigFileLocatorTests() { _tempDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(_tempDirectory); } [Fact] public void MissingConfigFileTest() { string output = RunTest(); Assert.Equal(missingConfigOutput, output); } [Fact] public void NLogDotConfigTest() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.config"), nlogConfigContents); string output = RunTest(); Assert.Equal(nlogConfigOutput, output); } [Fact] public void NLogDotDllDotNLogTest() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents); string output = RunTest(); Assert.Equal(nlogDllNLogOutput, output); } [Fact] public void NLogDotDllDotNLogInDirectoryWithSpaces() { File.WriteAllText(Path.Combine(_tempDirectory, "NLog.dll.nlog"), nlogDllNLogContents); string output = RunTest(); Assert.Equal(nlogDllNLogOutput, output); } [Fact] public void AppDotConfigTest() { File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.config"), appConfigContents); string output = RunTest(); Assert.Equal(appConfigOutput, output); } [Fact] public void AppDotNLogTest() { File.WriteAllText(Path.Combine(_tempDirectory, "ConfigFileLocator.exe.nlog"), appNLogContents); string output = RunTest(); Assert.Equal(appNLogOutput, output); } [Fact] public void PrecedenceTest() { var precedence = new[] { new { File = "ConfigFileLocator.exe.config", Contents = appConfigContents, Output = appConfigOutput }, new { File = "NLog.config", Contents = nlogConfigContents, Output = nlogConfigOutput }, new { File = "ConfigFileLocator.exe.nlog", Contents = appNLogContents, Output = appNLogOutput }, new { File = "NLog.dll.nlog", Contents = nlogDllNLogContents, Output = nlogDllNLogOutput }, }; // deploy all files foreach (var p in precedence) { File.WriteAllText(Path.Combine(_tempDirectory, p.File), p.Contents); } string output; // walk files in precedence order and delete config files foreach (var p in precedence) { output = RunTest(); Assert.Equal(p.Output, output); File.Delete(Path.Combine(_tempDirectory, p.File)); } output = RunTest(); Assert.Equal(missingConfigOutput, output); } [Fact] void FuncLayoutRendererRegisterTest1() { LayoutRenderer.Register("the-answer", (info) => "42"); Layout l = "${the-answer}"; var result = l.Render(LogEventInfo.CreateNullEvent()); Assert.Equal("42", result); } [Fact] void FuncLayoutRendererRegisterTest1WithXML() { LayoutRenderer.Register("the-answer", (info) => "42"); LogManager.Configuration = CreateConfigurationFromString(@" <nlog throwExceptions='true'> <targets> <target name='debug' type='Debug' layout= '${the-answer}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetCurrentClassLogger(); logger.Debug("test1"); AssertDebugLastMessage("debug", "42"); } [Fact] void FuncLayoutRendererRegisterTest2() { LayoutRenderer.Register("message-length", (info) => info.Message.Length); Layout l = "${message-length}"; var result = l.Render(LogEventInfo.Create(LogLevel.Error, "logger-adhoc", "1234567890")); Assert.Equal("10", result); } [Fact] public void GetCandidateConfigTest() { Assert.NotNull(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths(); var count = candidateConfigFilePaths.Count(); Assert.True(count > 0); } [Fact] public void GetCandidateConfigTest_list_is_readonly() { Assert.Throws<NotSupportedException>(() => { var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); var candidateConfigFilePaths = XmlLoggingConfiguration.GetCandidateConfigFilePaths(); var list2 = candidateConfigFilePaths as IList; list2.Add("test"); }); } [Fact] public void SetCandidateConfigTest() { var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); //no side effects list.Add("c:\\global\\temp2.config"); Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); } [Fact] public void ResetCandidateConfigTest() { var countBefore = XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count(); var list = new List<string> { "c:\\global\\temp.config" }; XmlLoggingConfiguration.SetCandidateConfigFilePaths(list); Assert.Single(XmlLoggingConfiguration.GetCandidateConfigFilePaths()); XmlLoggingConfiguration.ResetCandidateConfigFilePath(); Assert.Equal(countBefore, XmlLoggingConfiguration.GetCandidateConfigFilePaths().Count()); } private string RunTest() { string sourceCode = @" using System; using System.Reflection; using NLog; class C1 { private static ILogger logger = LogManager.GetCurrentClassLogger(); static void Main(string[] args) { Console.WriteLine(""--BEGIN--""); logger.Trace(""TraceMsg""); logger.Debug(""DebugMsg""); logger.Info(""InfoMsg""); logger.Warn(""WarnMsg""); logger.Error(""ErrorMsg""); logger.Fatal(""FatalMsg""); Console.WriteLine(""--END--""); } }"; var provider = new CSharpCodeProvider(); var options = new CompilerParameters(); options.OutputAssembly = Path.Combine(_tempDirectory, "ConfigFileLocator.exe"); options.GenerateExecutable = true; options.ReferencedAssemblies.Add(typeof(ILogger).Assembly.Location); options.IncludeDebugInformation = true; if (!File.Exists(options.OutputAssembly)) { var results = provider.CompileAssemblyFromSource(options, sourceCode); Assert.False(results.Errors.HasWarnings); Assert.False(results.Errors.HasErrors); File.Copy(typeof(ILogger).Assembly.Location, Path.Combine(_tempDirectory, "NLog.dll")); } return RunAndRedirectOutput(options.OutputAssembly); } public static string RunAndRedirectOutput(string exeFile) { using (var proc = new Process()) { #if MONO var sb = new StringBuilder(); sb.AppendFormat("\"{0}\" ", exeFile); proc.StartInfo.Arguments = sb.ToString(); proc.StartInfo.FileName = "mono"; proc.StartInfo.StandardOutputEncoding = Encoding.UTF8; proc.StartInfo.StandardErrorEncoding = Encoding.UTF8; #else proc.StartInfo.FileName = exeFile; #endif proc.StartInfo.UseShellExecute = false; proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal; proc.StartInfo.RedirectStandardInput = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; proc.Start(); proc.WaitForExit(); Assert.Equal(string.Empty, proc.StandardError.ReadToEnd()); return proc.StandardOutput.ReadToEnd().Replace("\r", "").Replace("\n", "|"); } } } } #endif
// 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; using System.Diagnostics.Contracts; namespace System { public enum UriKind { RelativeOrAbsolute, Absolute, Relative } public enum UriFormat { SafeUnescaped = 3, Unescaped = 2, UriEscaped = 1 } public enum UriComponents { AbsoluteUri = 0x7f, Fragment = 0x40, Host = 4, HostAndPort = 0x84, HttpRequestUrl = 0x3d, KeepDelimiter = 0x40000000, Path = 0x10, PathAndQuery = 0x30, Port = 8, Query = 0x20, Scheme = 1, SchemeAndServer = 13, SerializationInfoString = -2147483648, StrongAuthority = 0x86, StrongPort = 0x80, UserInfo = 2 } #if !SILVERLIGHT public enum UriPartial { Scheme, Authority, Path, Query } #endif public class Uri { #region Constructors #if !SILVERLIGHT public Uri(Uri baseUri, string relativeUri, bool dontEscape) { Contract.Requires(baseUri != null); Contract.Requires(relativeUri != null); } #endif public Uri(Uri baseUri, string relativeUri) { Contract.Requires(baseUri != null); Contract.Requires(relativeUri != null); } #if !SILVERLIGHT public Uri(string uriString, bool dontEscape) { Contract.Requires(uriString != null); } #endif public Uri(string uriString) { Contract.Requires(uriString != null); } #endregion #region Properties public string AbsolutePath { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public string AbsoluteUri { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #if !SILVERLIGHT public string Authority { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #endif public string DnsSafeHost { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public string Fragment { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public string Host { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #if false public UriHostNameType HostNameType { get; } #endif #if !SILVERLIGHT extern public bool IsDefaultPort { get; } extern public bool IsFile { get; } extern public bool IsLoopback { get; } #endif extern public bool IsUnc { get; } public string LocalPath { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public string OriginalString { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #if !SILVERLIGHT public string PathAndQuery { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #endif extern public int Port { get; } public string Query { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } public string Scheme { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #if !SILVERLIGHT public String[] Segments { get { Contract.Ensures(Contract.Result<string[]>() != null); Contract.Ensures(Contract.ForAll(Contract.Result<string[]>(), x => x != null)); return default(string[]); } } #endif extern public bool UserEscaped { get; } public string UserInfo { get { Contract.Ensures(Contract.Result<string>() != null); return default(string); } } #endregion #region Methods // extern public static UriHostNameType CheckHostName(string name); extern public static bool CheckSchemeName(string schemeName); [Pure] public static int Compare( Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType ) { return default(int); } [Pure] public static string EscapeDataString( string stringToEscape ) { Contract.Requires(stringToEscape != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } [Pure] public static string EscapeUriString( string stringToEscape ) { Contract.Requires(stringToEscape != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } [Pure] public static int FromHex(Char digit) { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() < 16); return default(int); } [Pure] public string GetComponents( UriComponents components, UriFormat format ) { Contract.Ensures(Contract.Result<string>() != null); return default(string); } #if !SILVERLIGHT [Pure] public string GetLeftPart(UriPartial part) { Contract.Ensures(Contract.Result<string>() != null); return default(string); } #endif #if !SILVERLIGHT [Pure] public static string HexEscape(char character) { Contract.Ensures(Contract.Result<string>() != null); return default(string); } [Pure] public static Char HexUnescape(string pattern, ref int index) { Contract.Requires(pattern != null); Contract.Requires(index >= 0); Contract.Requires(index < pattern.Length); Contract.Ensures(index > Contract.OldValue(index)); return default(Char); } #endif [Pure] public bool IsBaseOf(Uri uri) { return default(bool); } [Pure] public static bool IsHexDigit(Char character) { return default(bool); } #if !SILVERLIGHT [Pure] public static bool IsHexEncoding(string pattern, int index) { Contract.Requires(pattern != null); Contract.Requires(index >= 0); Contract.Requires(index < pattern.Length); return default(bool); } [Pure] public bool IsWellFormedOriginalString() { return default(bool); } #endif [Pure] public static bool IsWellFormedUriString(string uriString, UriKind uriKind) { return default(bool); } [Pure] public Uri MakeRelativeUri(Uri uri) { Contract.Requires(uri != null); Contract.Ensures(Contract.Result<Uri>() != null); return default(Uri); } [Pure] public static bool TryCreate( string uriString, UriKind uriKind, out Uri result ) { Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out result) != null); result = null; return default(bool); } [Pure] public static bool TryCreate( Uri baseUri, string relativeUri, out Uri result ) { Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out result) != null); result = null; return default(bool); } public static bool TryCreate( Uri baseUri, Uri relativeUri, out Uri result ) { Contract.Ensures(!Contract.Result<bool>() || Contract.ValueAtReturn(out result) != null); result = null; return default(bool); } [Pure] public static string UnescapeDataString(string stringToUnescape) { Contract.Requires(stringToUnescape != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } #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.Diagnostics; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using Xunit; namespace System.Net.Http.Tests { public class CacheControlHeaderValueTest : RemoteExecutorTestBase { [Fact] public void Properties_SetAndGetAllProperties_SetValueReturnedInGetter() { CacheControlHeaderValue cacheControl = new CacheControlHeaderValue(); // Bool properties cacheControl.NoCache = true; Assert.True(cacheControl.NoCache); cacheControl.NoStore = true; Assert.True(cacheControl.NoStore); cacheControl.MaxStale = true; Assert.True(cacheControl.MaxStale); cacheControl.NoTransform = true; Assert.True(cacheControl.NoTransform); cacheControl.OnlyIfCached = true; Assert.True(cacheControl.OnlyIfCached); cacheControl.Public = true; Assert.True(cacheControl.Public); cacheControl.Private = true; Assert.True(cacheControl.Private); cacheControl.MustRevalidate = true; Assert.True(cacheControl.MustRevalidate); cacheControl.ProxyRevalidate = true; Assert.True(cacheControl.ProxyRevalidate); // TimeSpan properties TimeSpan timeSpan = new TimeSpan(1, 2, 3); cacheControl.MaxAge = timeSpan; Assert.Equal(timeSpan, cacheControl.MaxAge); cacheControl.SharedMaxAge = timeSpan; Assert.Equal(timeSpan, cacheControl.SharedMaxAge); cacheControl.MaxStaleLimit = timeSpan; Assert.Equal(timeSpan, cacheControl.MaxStaleLimit); cacheControl.MinFresh = timeSpan; Assert.Equal(timeSpan, cacheControl.MinFresh); // String collection properties Assert.NotNull(cacheControl.NoCacheHeaders); AssertExtensions.Throws<ArgumentException>("item", () => { cacheControl.NoCacheHeaders.Add(null); }); Assert.Throws<FormatException>(() => { cacheControl.NoCacheHeaders.Add("invalid token"); }); cacheControl.NoCacheHeaders.Add("token"); Assert.Equal(1, cacheControl.NoCacheHeaders.Count); Assert.Equal("token", cacheControl.NoCacheHeaders.First()); Assert.NotNull(cacheControl.PrivateHeaders); AssertExtensions.Throws<ArgumentException>("item", () => { cacheControl.PrivateHeaders.Add(null); }); Assert.Throws<FormatException>(() => { cacheControl.PrivateHeaders.Add("invalid token"); }); cacheControl.PrivateHeaders.Add("token"); Assert.Equal(1, cacheControl.PrivateHeaders.Count); Assert.Equal("token", cacheControl.PrivateHeaders.First()); // NameValueHeaderValue collection property Assert.NotNull(cacheControl.Extensions); Assert.Throws<ArgumentNullException>(() => { cacheControl.Extensions.Add(null); }); cacheControl.Extensions.Add(new NameValueHeaderValue("name", "value")); Assert.Equal(1, cacheControl.Extensions.Count); Assert.Equal(new NameValueHeaderValue("name", "value"), cacheControl.Extensions.First()); } [Fact] public void ToString_UseRequestDirectiveValues_AllSerializedCorrectly() { CacheControlHeaderValue cacheControl = new CacheControlHeaderValue(); Assert.Equal("", cacheControl.ToString()); // Note that we allow all combinations of all properties even though the RFC specifies rules what value // can be used together. // Also for property pairs (bool property + collection property) like 'NoCache' and 'NoCacheHeaders' the // caller needs to set the bool property in order for the collection to be populated as string. // Cache Request Directive sample cacheControl.NoStore = true; Assert.Equal("no-store", cacheControl.ToString()); cacheControl.NoCache = true; Assert.Equal("no-store, no-cache", cacheControl.ToString()); cacheControl.MaxAge = new TimeSpan(0, 1, 10); Assert.Equal("no-store, no-cache, max-age=70", cacheControl.ToString()); cacheControl.MaxStale = true; Assert.Equal("no-store, no-cache, max-age=70, max-stale", cacheControl.ToString()); cacheControl.MaxStaleLimit = new TimeSpan(0, 2, 5); Assert.Equal("no-store, no-cache, max-age=70, max-stale=125", cacheControl.ToString()); cacheControl.MinFresh = new TimeSpan(0, 3, 0); Assert.Equal("no-store, no-cache, max-age=70, max-stale=125, min-fresh=180", cacheControl.ToString()); cacheControl = new CacheControlHeaderValue(); cacheControl.NoTransform = true; Assert.Equal("no-transform", cacheControl.ToString()); cacheControl.OnlyIfCached = true; Assert.Equal("no-transform, only-if-cached", cacheControl.ToString()); cacheControl.Extensions.Add(new NameValueHeaderValue("custom")); cacheControl.Extensions.Add(new NameValueHeaderValue("customName", "customValue")); Assert.Equal("no-transform, only-if-cached, custom, customName=customValue", cacheControl.ToString()); cacheControl = new CacheControlHeaderValue(); cacheControl.Extensions.Add(new NameValueHeaderValue("custom")); Assert.Equal("custom", cacheControl.ToString()); } [Fact] public void ToString_UseResponseDirectiveValues_AllSerializedCorrectly() { CacheControlHeaderValue cacheControl = new CacheControlHeaderValue(); Assert.Equal("", cacheControl.ToString()); cacheControl.NoCache = true; Assert.Equal("no-cache", cacheControl.ToString()); cacheControl.NoCacheHeaders.Add("token1"); Assert.Equal("no-cache=\"token1\"", cacheControl.ToString()); cacheControl.Public = true; Assert.Equal("public, no-cache=\"token1\"", cacheControl.ToString()); cacheControl = new CacheControlHeaderValue(); cacheControl.Private = true; Assert.Equal("private", cacheControl.ToString()); cacheControl.PrivateHeaders.Add("token2"); cacheControl.PrivateHeaders.Add("token3"); Assert.Equal("private=\"token2, token3\"", cacheControl.ToString()); cacheControl.MustRevalidate = true; Assert.Equal("must-revalidate, private=\"token2, token3\"", cacheControl.ToString()); cacheControl.ProxyRevalidate = true; Assert.Equal("must-revalidate, proxy-revalidate, private=\"token2, token3\"", cacheControl.ToString()); } [Fact] public void ToString_NegativeValues_UsesMinusSignRegardlessOfCurrentCulture() { RemoteInvoke(() => { var cacheControl = new CacheControlHeaderValue() { MaxAge = new TimeSpan(0, 0, -1), MaxStale = true, MaxStaleLimit = new TimeSpan(0, 0, -2), MinFresh = new TimeSpan(0, 0, -3), SharedMaxAge = new TimeSpan(0, 0, -4) }; var ci = (CultureInfo)CultureInfo.CurrentCulture.Clone(); ci.NumberFormat.NegativeSign = "n"; CultureInfo.CurrentCulture = ci; Assert.Equal("max-age=-1, s-maxage=-4, max-stale=-2, min-fresh=-3", cacheControl.ToString()); }).Dispose(); } [Fact] public void GetHashCode_CompareValuesWithBoolFieldsSet_MatchExpectation() { // Verify that different bool fields return different hash values. CacheControlHeaderValue[] values = new CacheControlHeaderValue[9]; for (int i = 0; i < values.Length; i++) { values[i] = new CacheControlHeaderValue(); } values[0].ProxyRevalidate = true; values[1].NoCache = true; values[2].NoStore = true; values[3].MaxStale = true; values[4].NoTransform = true; values[5].OnlyIfCached = true; values[6].Public = true; values[7].Private = true; values[8].MustRevalidate = true; // Only one bool field set. All hash codes should differ for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { if (i != j) { CompareHashCodes(values[i], values[j], false); } } } // Validate that two instances with the same bool fields set are equal. values[0].NoCache = true; CompareHashCodes(values[0], values[1], false); values[1].ProxyRevalidate = true; CompareHashCodes(values[0], values[1], true); } [Fact] public void GetHashCode_CompareValuesWithTimeSpanFieldsSet_MatchExpectation() { // Verify that different timespan fields return different hash values. CacheControlHeaderValue[] values = new CacheControlHeaderValue[4]; for (int i = 0; i < values.Length; i++) { values[i] = new CacheControlHeaderValue(); } values[0].MaxAge = new TimeSpan(0, 1, 1); values[1].MaxStaleLimit = new TimeSpan(0, 1, 1); values[2].MinFresh = new TimeSpan(0, 1, 1); values[3].SharedMaxAge = new TimeSpan(0, 1, 1); // Only one timespan field set. All hash codes should differ for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { if (i != j) { CompareHashCodes(values[i], values[j], false); } } } values[0].MaxStaleLimit = new TimeSpan(0, 1, 2); CompareHashCodes(values[0], values[1], false); values[1].MaxAge = new TimeSpan(0, 1, 1); values[1].MaxStaleLimit = new TimeSpan(0, 1, 2); CompareHashCodes(values[0], values[1], true); } [Fact] public void GetHashCode_CompareCollectionFieldsSet_MatchExpectation() { CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue(); cacheControl1.NoCache = true; cacheControl1.NoCacheHeaders.Add("token2"); cacheControl2.NoCache = true; cacheControl2.NoCacheHeaders.Add("token1"); cacheControl2.NoCacheHeaders.Add("token2"); CompareHashCodes(cacheControl1, cacheControl2, false); cacheControl1.NoCacheHeaders.Add("token1"); CompareHashCodes(cacheControl1, cacheControl2, true); // Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders // have the same values, the hash code will be different. cacheControl3.Private = true; cacheControl3.PrivateHeaders.Add("token2"); CompareHashCodes(cacheControl1, cacheControl3, false); cacheControl4.Extensions.Add(new NameValueHeaderValue("custom")); CompareHashCodes(cacheControl1, cacheControl4, false); cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV")); cacheControl5.Extensions.Add(new NameValueHeaderValue("custom")); CompareHashCodes(cacheControl4, cacheControl5, false); cacheControl4.Extensions.Add(new NameValueHeaderValue("customN", "customV")); CompareHashCodes(cacheControl4, cacheControl5, true); } [Fact] public void Equals_CompareValuesWithBoolFieldsSet_MatchExpectation() { // Verify that different bool fields return different hash values. CacheControlHeaderValue[] values = new CacheControlHeaderValue[9]; for (int i = 0; i < values.Length; i++) { values[i] = new CacheControlHeaderValue(); } values[0].ProxyRevalidate = true; values[1].NoCache = true; values[2].NoStore = true; values[3].MaxStale = true; values[4].NoTransform = true; values[5].OnlyIfCached = true; values[6].Public = true; values[7].Private = true; values[8].MustRevalidate = true; // Only one bool field set. All hash codes should differ for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { if (i != j) { CompareValues(values[i], values[j], false); } } } // Validate that two instances with the same bool fields set are equal. values[0].NoCache = true; CompareValues(values[0], values[1], false); values[1].ProxyRevalidate = true; CompareValues(values[0], values[1], true); } [Fact] public void Equals_CompareValuesWithTimeSpanFieldsSet_MatchExpectation() { // Verify that different timespan fields return different hash values. CacheControlHeaderValue[] values = new CacheControlHeaderValue[4]; for (int i = 0; i < values.Length; i++) { values[i] = new CacheControlHeaderValue(); } values[0].MaxAge = new TimeSpan(0, 1, 1); values[1].MaxStaleLimit = new TimeSpan(0, 1, 1); values[2].MinFresh = new TimeSpan(0, 1, 1); values[3].SharedMaxAge = new TimeSpan(0, 1, 1); // Only one timespan field set. All hash codes should differ for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { if (i != j) { CompareValues(values[i], values[j], false); } } } values[0].MaxStaleLimit = new TimeSpan(0, 1, 2); CompareValues(values[0], values[1], false); values[1].MaxAge = new TimeSpan(0, 1, 1); values[1].MaxStaleLimit = new TimeSpan(0, 1, 2); CompareValues(values[0], values[1], true); CacheControlHeaderValue value1 = new CacheControlHeaderValue(); value1.MaxStale = true; CacheControlHeaderValue value2 = new CacheControlHeaderValue(); value2.MaxStale = true; CompareValues(value1, value2, true); value2.MaxStaleLimit = new TimeSpan(1, 2, 3); CompareValues(value1, value2, false); } [Fact] public void Equals_CompareCollectionFieldsSet_MatchExpectation() { CacheControlHeaderValue cacheControl1 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl2 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl3 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl4 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl5 = new CacheControlHeaderValue(); CacheControlHeaderValue cacheControl6 = new CacheControlHeaderValue(); cacheControl1.NoCache = true; cacheControl1.NoCacheHeaders.Add("token2"); Assert.False(cacheControl1.Equals(null), "Compare with 'null'"); cacheControl2.NoCache = true; cacheControl2.NoCacheHeaders.Add("token1"); cacheControl2.NoCacheHeaders.Add("token2"); CompareValues(cacheControl1, cacheControl2, false); cacheControl1.NoCacheHeaders.Add("token1"); CompareValues(cacheControl1, cacheControl2, true); // Since NoCache and Private generate different hash codes, even if NoCacheHeaders and PrivateHeaders // have the same values, the hash code will be different. cacheControl3.Private = true; cacheControl3.PrivateHeaders.Add("token2"); CompareValues(cacheControl1, cacheControl3, false); cacheControl4.Private = true; cacheControl4.PrivateHeaders.Add("token3"); CompareValues(cacheControl3, cacheControl4, false); cacheControl5.Extensions.Add(new NameValueHeaderValue("custom")); CompareValues(cacheControl1, cacheControl5, false); cacheControl6.Extensions.Add(new NameValueHeaderValue("customN", "customV")); cacheControl6.Extensions.Add(new NameValueHeaderValue("custom")); CompareValues(cacheControl5, cacheControl6, false); cacheControl5.Extensions.Add(new NameValueHeaderValue("customN", "customV")); CompareValues(cacheControl5, cacheControl6, true); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { CacheControlHeaderValue source = new CacheControlHeaderValue(); source.Extensions.Add(new NameValueHeaderValue("custom")); source.Extensions.Add(new NameValueHeaderValue("customN", "customV")); source.MaxAge = new TimeSpan(1, 1, 1); source.MaxStale = true; source.MaxStaleLimit = new TimeSpan(1, 1, 2); source.MinFresh = new TimeSpan(1, 1, 3); source.MustRevalidate = true; source.NoCache = true; source.NoCacheHeaders.Add("token1"); source.NoStore = true; source.NoTransform = true; source.OnlyIfCached = true; source.Private = true; source.PrivateHeaders.Add("token2"); source.ProxyRevalidate = true; source.Public = true; source.SharedMaxAge = new TimeSpan(1, 1, 4); CacheControlHeaderValue clone = (CacheControlHeaderValue)((ICloneable)source).Clone(); Assert.Equal(source, clone); } [Fact] public void GetCacheControlLength_DifferentValidScenariosAndNoExistingCacheControl_AllReturnNonZero() { CacheControlHeaderValue expected = new CacheControlHeaderValue(); expected.NoCache = true; CheckGetCacheControlLength("X , , no-cache ,,", 1, null, 16, expected); expected = new CacheControlHeaderValue(); expected.NoCache = true; expected.NoCacheHeaders.Add("token1"); expected.NoCacheHeaders.Add("token2"); CheckGetCacheControlLength("no-cache=\"token1, token2\"", 0, null, 25, expected); expected = new CacheControlHeaderValue(); expected.NoStore = true; expected.MaxAge = new TimeSpan(0, 0, 125); expected.MaxStale = true; CheckGetCacheControlLength("X no-store , max-age = 125, max-stale,", 1, null, 37, expected); expected = new CacheControlHeaderValue(); expected.MinFresh = new TimeSpan(0, 0, 123); expected.NoTransform = true; expected.OnlyIfCached = true; expected.Extensions.Add(new NameValueHeaderValue("custom")); CheckGetCacheControlLength("min-fresh=123, no-transform, only-if-cached, custom", 0, null, 51, expected); expected = new CacheControlHeaderValue(); expected.Public = true; expected.Private = true; expected.PrivateHeaders.Add("token1"); expected.MustRevalidate = true; expected.ProxyRevalidate = true; expected.Extensions.Add(new NameValueHeaderValue("c", "d")); expected.Extensions.Add(new NameValueHeaderValue("a", "b")); CheckGetCacheControlLength(",public, , private=\"token1\", must-revalidate, c=d, proxy-revalidate, a=b", 0, null, 72, expected); expected = new CacheControlHeaderValue(); expected.Private = true; expected.SharedMaxAge = new TimeSpan(0, 0, 1234567890); expected.MaxAge = new TimeSpan(0, 0, 987654321); CheckGetCacheControlLength("s-maxage=1234567890, private, max-age = 987654321,", 0, null, 50, expected); } [Fact] public void GetCacheControlLength_DifferentValidScenariosAndExistingCacheControl_AllReturnNonZero() { CacheControlHeaderValue storeValue = new CacheControlHeaderValue(); storeValue.NoStore = true; CacheControlHeaderValue expected = new CacheControlHeaderValue(); expected.NoCache = true; expected.NoStore = true; CheckGetCacheControlLength("X no-cache", 1, storeValue, 9, expected); storeValue = new CacheControlHeaderValue(); storeValue.Private = true; storeValue.PrivateHeaders.Add("token1"); storeValue.NoCache = true; expected.NoCacheHeaders.Add("token1"); expected.NoCacheHeaders.Clear(); // just make sure we have an assigned (empty) collection. expected = new CacheControlHeaderValue(); expected.Private = true; expected.PrivateHeaders.Add("token1"); expected.PrivateHeaders.Add("token2"); expected.NoCache = true; expected.NoCacheHeaders.Add("token1"); expected.NoCacheHeaders.Add("token2"); CheckGetCacheControlLength("private=\"token2\", no-cache=\"token1, , token2,\"", 0, storeValue, 46, expected); storeValue = new CacheControlHeaderValue(); storeValue.Extensions.Add(new NameValueHeaderValue("x", "y")); storeValue.NoTransform = true; storeValue.OnlyIfCached = true; expected = new CacheControlHeaderValue(); expected.Public = true; expected.Private = true; expected.PrivateHeaders.Add("token1"); expected.MustRevalidate = true; expected.ProxyRevalidate = true; expected.NoTransform = true; expected.OnlyIfCached = true; expected.Extensions.Add(new NameValueHeaderValue("a", "\"b\"")); expected.Extensions.Add(new NameValueHeaderValue("c", "d")); expected.Extensions.Add(new NameValueHeaderValue("x", "y")); // from store result CheckGetCacheControlLength(",public, , private=\"token1\", must-revalidate, c=d, proxy-revalidate, a=\"b\"", 0, storeValue, 74, expected); storeValue = new CacheControlHeaderValue(); storeValue.MaxStale = true; storeValue.MinFresh = new TimeSpan(1, 2, 3); expected = new CacheControlHeaderValue(); expected.MaxStale = true; expected.MaxStaleLimit = new TimeSpan(0, 0, 5); expected.MinFresh = new TimeSpan(0, 0, 10); // note that the last header value overwrites existing ones CheckGetCacheControlLength(" ,,max-stale=5,,min-fresh = 10,,", 0, storeValue, 33, expected); storeValue = new CacheControlHeaderValue(); storeValue.SharedMaxAge = new TimeSpan(1, 2, 3); storeValue.NoTransform = true; expected = new CacheControlHeaderValue(); expected.SharedMaxAge = new TimeSpan(1, 2, 3); expected.NoTransform = true; } [Fact] public void GetCacheControlLength_DifferentInvalidScenarios_AllReturnZero() { // Token-only values CheckInvalidCacheControlLength("no-store=15", 0); CheckInvalidCacheControlLength("no-store=", 0); CheckInvalidCacheControlLength("no-transform=a", 0); CheckInvalidCacheControlLength("no-transform=", 0); CheckInvalidCacheControlLength("only-if-cached=\"x\"", 0); CheckInvalidCacheControlLength("only-if-cached=", 0); CheckInvalidCacheControlLength("public=\"x\"", 0); CheckInvalidCacheControlLength("public=", 0); CheckInvalidCacheControlLength("must-revalidate=\"1\"", 0); CheckInvalidCacheControlLength("must-revalidate=", 0); CheckInvalidCacheControlLength("proxy-revalidate=x", 0); CheckInvalidCacheControlLength("proxy-revalidate=", 0); // Token with optional field-name list CheckInvalidCacheControlLength("no-cache=", 0); CheckInvalidCacheControlLength("no-cache=token", 0); CheckInvalidCacheControlLength("no-cache=\"token", 0); CheckInvalidCacheControlLength("no-cache=\"\"", 0); // at least one token expected as value CheckInvalidCacheControlLength("private=", 0); CheckInvalidCacheControlLength("private=token", 0); CheckInvalidCacheControlLength("private=\"token", 0); CheckInvalidCacheControlLength("private=\",\"", 0); // at least one token expected as value CheckInvalidCacheControlLength("private=\"=\"", 0); // Token with delta-seconds value CheckInvalidCacheControlLength("max-age", 0); CheckInvalidCacheControlLength("max-age=", 0); CheckInvalidCacheControlLength("max-age=a", 0); CheckInvalidCacheControlLength("max-age=\"1\"", 0); CheckInvalidCacheControlLength("max-age=1.5", 0); CheckInvalidCacheControlLength("max-stale=", 0); CheckInvalidCacheControlLength("max-stale=a", 0); CheckInvalidCacheControlLength("max-stale=\"1\"", 0); CheckInvalidCacheControlLength("max-stale=1.5", 0); CheckInvalidCacheControlLength("min-fresh", 0); CheckInvalidCacheControlLength("min-fresh=", 0); CheckInvalidCacheControlLength("min-fresh=a", 0); CheckInvalidCacheControlLength("min-fresh=\"1\"", 0); CheckInvalidCacheControlLength("min-fresh=1.5", 0); CheckInvalidCacheControlLength("s-maxage", 0); CheckInvalidCacheControlLength("s-maxage=", 0); CheckInvalidCacheControlLength("s-maxage=a", 0); CheckInvalidCacheControlLength("s-maxage=\"1\"", 0); CheckInvalidCacheControlLength("s-maxage=1.5", 0); // Invalid Extension values CheckInvalidCacheControlLength("custom=", 0); CheckInvalidCacheControlLength("custom value", 0); CheckInvalidCacheControlLength(null, 0); CheckInvalidCacheControlLength("", 0); CheckInvalidCacheControlLength("", 1); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { // Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue. CacheControlHeaderValue expected = new CacheControlHeaderValue(); expected.NoStore = true; expected.MinFresh = new TimeSpan(0, 2, 3); CheckValidParse(" , no-store, min-fresh=123", expected); expected = new CacheControlHeaderValue(); expected.MaxStale = true; expected.NoCache = true; expected.NoCacheHeaders.Add("t"); CheckValidParse("max-stale, no-cache=\"t\", ,,", expected); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("no-cache,=", 0); CheckInvalidParse("max-age=123x", 0); CheckInvalidParse("=no-cache", 0); CheckInvalidParse("no-cache no-store", 0); CheckInvalidParse("invalid =", 0); CheckInvalidParse("\u4F1A", 0); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { // Just verify parser is implemented correctly. Don't try to test syntax parsed by CacheControlHeaderValue. CacheControlHeaderValue expected = new CacheControlHeaderValue(); expected.NoStore = true; expected.MinFresh = new TimeSpan(0, 2, 3); CheckValidTryParse(" , no-store, min-fresh=123", expected); expected = new CacheControlHeaderValue(); expected.MaxStale = true; expected.NoCache = true; expected.NoCacheHeaders.Add("t"); CheckValidTryParse("max-stale, no-cache=\"t\", ,,", expected); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("no-cache,=", 0); CheckInvalidTryParse("max-age=123x", 0); CheckInvalidTryParse("=no-cache", 0); CheckInvalidTryParse("no-cache no-store", 0); CheckInvalidTryParse("invalid =", 0); CheckInvalidTryParse("\u4F1A", 0); } #region Helper methods private void CompareHashCodes(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual) { if (areEqual) { Assert.Equal(x.GetHashCode(), y.GetHashCode()); } else { Assert.NotEqual(x.GetHashCode(), y.GetHashCode()); } } private void CompareValues(CacheControlHeaderValue x, CacheControlHeaderValue y, bool areEqual) { Assert.Equal(areEqual, x.Equals(y)); Assert.Equal(areEqual, y.Equals(x)); } private static void CheckGetCacheControlLength(string input, int startIndex, CacheControlHeaderValue storeValue, int expectedLength, CacheControlHeaderValue expectedResult) { CacheControlHeaderValue result = null; Assert.Equal(expectedLength, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, storeValue, out result)); if (storeValue == null) { Assert.Equal(expectedResult, result); } else { // If we provide a 'storeValue', then that instance will be updated and result will be 'null' Assert.Null(result); Assert.Equal(expectedResult, storeValue); } } private static void CheckInvalidCacheControlLength(string input, int startIndex) { CacheControlHeaderValue result = null; Assert.Equal(0, CacheControlHeaderValue.GetCacheControlLength(input, startIndex, null, out result)); Assert.Null(result); } private void CheckValidParse(string input, CacheControlHeaderValue expectedResult) { CacheControlHeaderValue result = CacheControlHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input, int startIndex) { Assert.Throws<FormatException>(() => { CacheControlHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, CacheControlHeaderValue expectedResult) { CacheControlHeaderValue result = null; Assert.True(CacheControlHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input, int startIndex) { CacheControlHeaderValue result = null; Assert.False(CacheControlHeaderValue.TryParse(input, out result)); Assert.Null(result); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.AspNetCore.Http.Connections; namespace Microsoft.AspNetCore.SignalR.Crankier { public class Agent : IAgent { private readonly bool _workerWaitForDebugger; private readonly string _hostName; private readonly ConcurrentDictionary<int, AgentWorker> _workers; private readonly string _executable; public Agent(string executable = null, bool workerWaitForDebugger = false) { _workerWaitForDebugger = workerWaitForDebugger; _executable = executable ?? GetMyExecutable(); Trace.Listeners.Add(new TextWriterTraceListener(Console.Out)); _hostName = Dns.GetHostName(); _workers = new ConcurrentDictionary<int, AgentWorker>(); Trace.WriteLine("Agent created"); } private string GetMyExecutable() { var mainModuleFile = Process.GetCurrentProcess().MainModule.FileName; if (Path.GetFileNameWithoutExtension(mainModuleFile).Equals("dotnet")) { // We're running in 'dotnet' return Path.Combine(AppContext.BaseDirectory, $"{typeof(Program).Assembly.GetName().Name}.dll"); } else { // Standalone deployment return mainModuleFile; } } public IRunner Runner { get; set; } public string TargetAddress { get; private set; } public int TotalConnectionsRequested { get; private set; } public bool ApplyingLoad { get; private set; } public AgentHeartbeatInformation GetHeartbeatInformation() { return new AgentHeartbeatInformation { HostName = _hostName, TargetAddress = TargetAddress, TotalConnectionsRequested = TotalConnectionsRequested, ApplyingLoad = ApplyingLoad, Workers = _workers.Select(worker => worker.Value.GetHeartbeatInformation()).ToList() }; } public Dictionary<int, StatusInformation> GetWorkerStatus() { return _workers.Values.ToDictionary( k => k.Id, v => v.StatusInformation); } private AgentWorker CreateWorker() { var fileName = _executable; var arguments = $"worker --agent {Environment.ProcessId}"; if (_workerWaitForDebugger) { arguments += " --wait-for-debugger"; } if (fileName.EndsWith(".dll")) { // Execute using dotnet.exe fileName = GetDotNetHost(); arguments = _executable + " " + arguments; } var startInfo = new ProcessStartInfo() { FileName = fileName, Arguments = arguments, CreateNoWindow = true, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; var worker = new AgentWorker(startInfo, this); worker.StatusInformation = new StatusInformation(); worker.Start(); worker.OnError += OnError; worker.OnExit += OnExit; _workers.TryAdd(worker.Id, worker); return worker; } private static string GetDotNetHost() => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet"; private async Task StartWorker(int id, string targetAddress, HttpTransportType transportType, int numberOfConnectionsPerWorker) { if (_workers.TryGetValue(id, out var worker)) { await worker.Worker.ConnectAsync(targetAddress, transportType, numberOfConnectionsPerWorker); } } public async Task StartWorkersAsync(string targetAddress, int numberOfWorkers, HttpTransportType transportType, int numberOfConnections) { TargetAddress = targetAddress; TotalConnectionsRequested = numberOfConnections; var connectionsPerWorker = numberOfConnections / numberOfWorkers; var remainingConnections = numberOfConnections % numberOfWorkers; async Task RunWorker(int index, AgentWorker worker) { if (index == 0) { await StartWorker(worker.Id, targetAddress, transportType, connectionsPerWorker + remainingConnections); } else { await StartWorker(worker.Id, targetAddress, transportType, connectionsPerWorker); } await Runner.LogAgentAsync("Agent started listening to worker {0} ({1} of {2}).", worker.Id, index + 1, numberOfWorkers); } var workerTasks = new Task<AgentWorker>[numberOfWorkers]; for (var index = 0; index < numberOfWorkers; index++) { workerTasks[index] = Task.Run(() => CreateWorker()); } await Task.WhenAll(workerTasks); for (var index = 0; index < numberOfWorkers; index++) { _ = RunWorker(index, workerTasks[index].Result); } } public void KillWorker(int workerId) { if (_workers.TryGetValue(workerId, out var worker)) { worker.Kill(); Runner.LogAgentAsync("Agent killed Worker {0}.", workerId); } } public void KillWorkers(int numberOfWorkersToKill) { var keys = _workers.Keys.Take(numberOfWorkersToKill).ToList(); foreach (var key in keys) { if (_workers.TryGetValue(key, out var worker)) { worker.Kill(); Runner.LogAgentAsync("Agent killed Worker {0}.", key); } } } public void KillConnections() { var keys = _workers.Keys.ToList(); foreach (var key in keys) { if (_workers.TryGetValue(key, out var worker)) { worker.Kill(); Runner.LogAgentAsync("Agent killed Worker {0}.", key); } } TotalConnectionsRequested = 0; ApplyingLoad = false; } public void PingWorker(int workerId, int value) { if (_workers.TryGetValue(workerId, out var worker)) { worker.Worker.PingAsync(value); Runner.LogAgentAsync("Agent sent ping command to Worker {0} with value {1}.", workerId, value); } else { Runner.LogAgentAsync("Agent failed to send ping command, Worker {0} not found.", workerId); } } public void StartTest(int messageSize, TimeSpan sendInterval) { ApplyingLoad = true; Task.Run(() => { foreach (var worker in _workers.Values) { worker.Worker.StartTestAsync(sendInterval, messageSize); } }); } public void StopWorker(int workerId) { if (_workers.TryGetValue(workerId, out var worker)) { worker.Worker.StopAsync(); } } public async Task StopWorkersAsync() { var keys = _workers.Keys.ToList(); foreach (var key in keys) { if (_workers.TryGetValue(key, out var worker)) { await worker.Worker.StopAsync(); await Runner.LogAgentAsync("Agent stopped Worker {0}.", key); } } TotalConnectionsRequested = 0; ApplyingLoad = false; // Wait for workers to terminate while (_workers.Count > 0) { await Task.Delay(1000); } } public async Task PongAsync(int id, int value) { await Runner.LogAgentAsync("Agent received pong message from Worker {0} with value {1}.", id, value); await Runner.PongWorkerAsync(id, value); } public async Task LogAsync(int id, string text) { await Runner.LogWorkerAsync(id, text); } public Task StatusAsync( int id, StatusInformation statusInformation) { if (_workers.TryGetValue(id, out var worker)) { worker.StatusInformation = statusInformation; } return Task.CompletedTask; } private void OnError(int workerId, Exception ex) { Runner.LogWorkerAsync(workerId, ex.Message); } private void OnExit(int workerId, int exitCode) { _workers.TryRemove(workerId, out _); var message = $"Worker {workerId} exited with exit code {exitCode}."; Trace.WriteLine(message); if (exitCode != 0) { throw new Exception(message); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Runtime.InteropServices; using Xunit; using Xunit.Abstractions; using static System.Buffers.Binary.BinaryPrimitives; using static System.Runtime.InteropServices.MemoryMarshal; namespace System.Slices.Tests { public class UsageScenarioTests { private readonly ITestOutputHelper output; public UsageScenarioTests(ITestOutputHelper output) { this.output = output; } private struct MyByte { public MyByte(byte value) { Value = value; } public byte Value { get; private set; } } [Theory] [InlineData(new byte[] { })] [InlineData(new byte[] { 0 })] [InlineData(new byte[] { 0, 1 })] [InlineData(new byte[] { 0, 1, 2 })] [InlineData(new byte[] { 0, 1, 2, 3 })] [InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })] public void CtorSpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array) { Span<byte> span = new Span<byte>(array); Assert.Equal(array.Length, span.Length); Assert.NotSame(array, span.ToArray()); for (int i = 0; i < span.Length; i++) { Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); array[i] = unchecked((byte)(array[i] + 1)); Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); var byteValue = unchecked((byte)(array[i] + 1)); Write(span.Slice(i), ref byteValue); Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); var myByteValue = unchecked(new MyByte((byte)(array[i] + 1))); Write(span.Slice(i), ref myByteValue); Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); } } [Theory] [InlineData(new byte[] { })] [InlineData(new byte[] { 0 })] [InlineData(new byte[] { 0, 1 })] [InlineData(new byte[] { 0, 1, 2 })] [InlineData(new byte[] { 0, 1, 2, 3 })] [InlineData(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })] public void CtorReadOnlySpanOverByteArrayValidCasesWithPropertiesAndBasicOperationsChecks(byte[] array) { ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(array); Assert.Equal(array.Length, span.Length); Assert.NotSame(array, span.ToArray()); for (int i = 0; i < span.Length; i++) { Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); array[i] = unchecked((byte)(array[i] + 1)); Assert.Equal(array[i], Read<byte>(span.Slice(i))); Assert.Equal(array[i], Read<MyByte>(span.Slice(i)).Value); } } [Theory] // copy whole buffer [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)] // copy first half to first half (length match) [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)] // copy second half to second half (length match) [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3, new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)] // copy first half to first half [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)] // copy no bytes starting from index 0 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)] // copy no bytes starting from index 3 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)] // copy no bytes starting at the end [InlineData( new byte[] { 7, 7, 7, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)] // copy first byte of 1 element array to last position [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 6 }, 0, 1, new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)] // copy first two bytes of 2 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 5, 6 }, 0, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy first two bytes of 3 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 5, 6, 7 }, 0, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy last two bytes of 3 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 5, 6 }, 1, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy first two bytes of 2 element array to the middle of other array [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 3, 4 }, 0, 2, new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)] // copy one byte from the beginning at the end of other array [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1, new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)] // copy two bytes from the beginning at 5th element [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)] // copy one byte from the beginning at the end of other array [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1, new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)] // copy two bytes from the beginning at 5th element [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)] public void SpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount) { if (expected != null) { Span<byte> spanA = new Span<byte>(a, aidx, acount); Span<byte> spanB = new Span<byte>(b, bidx, bcount); spanA.CopyTo(spanB); Assert.Equal(expected, b); Span<byte> spanExpected = new Span<byte>(expected); Span<byte> spanBAll = new Span<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { Span<byte> spanA = new Span<byte>(a, aidx, acount); Span<byte> spanB = new Span<byte>(b, bidx, bcount); try { spanA.CopyTo(spanB); Assert.True(false); } catch (Exception) { Assert.True(true); } } } [Theory] // copy whole buffer [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 6)] // copy first half to first half (length match) [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 3)] // copy second half to second half (length match) [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3, new byte[] { 1, 2, 3, 7, 7, 7 }, 3, 3)] // copy first half to first half [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)] // copy no bytes starting from index 0 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)] // copy no bytes starting from index 3 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6)] // copy no bytes starting at the end [InlineData( new byte[] { 7, 7, 7, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0, new byte[] { 7, 7, 7, 4, 5, 6 }, 0, 6)] // copy first byte of 1 element array to last position [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 6 }, 0, 1, new byte[] { 1, 2, 3, 4, 5, 7 }, 5, 1)] // copy first two bytes of 2 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 5, 6 }, 0, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy first two bytes of 3 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 5, 6, 7 }, 0, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy last two bytes of 3 element array to last two positions [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 5, 6 }, 1, 2, new byte[] { 1, 2, 3, 4, 7, 7 }, 4, 2)] // copy first two bytes of 2 element array to the middle of other array [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 3, 4 }, 0, 2, new byte[] { 1, 2, 7, 7, 5, 6 }, 2, 3)] // copy one byte from the beginning at the end of other array [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 1, new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)] // copy two bytes from the beginning at 5th element [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 2, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)] // copy one byte from the beginning at the end of other array [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1, new byte[] { 7, 7, 7, 7, 7, 7 }, 6, 0)] // copy two bytes from the beginning at 5th element [InlineData( null, new byte[] { 7, 7, 7, 7, 7, 7 }, 4, 2, new byte[] { 7, 7, 7, 7, 7, 7 }, 5, 1)] public void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount) { if (expected != null) { ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount); Span<byte> spanB = new Span<byte>(b, bidx, bcount); spanA.CopyTo(spanB); Assert.Equal(expected, b); ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected); ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount); Span<byte> spanB = new Span<byte>(b, bidx, bcount); try { spanA.CopyTo(spanB); Assert.True(false); } catch (Exception) { Assert.True(true); } } ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative(expected, a, aidx, acount, b, bidx, bcount); } public unsafe void ReadOnlySpanOfByteCopyToAnotherSpanOfByteTwoDifferentBuffersValidCasesNative(byte[] expected, byte[] a, int aidx, int acount, byte[] b, int bidx, int bcount) { IntPtr pa = Marshal.AllocHGlobal(a.Length); Span<byte> na = new Span<byte>(pa.ToPointer(), a.Length); a.CopyTo(na); IntPtr pb = Marshal.AllocHGlobal(b.Length); Span<byte> nb = new Span<byte>(pb.ToPointer(), b.Length); b.CopyTo(nb); ReadOnlySpan<byte> spanA = na.Slice(aidx, acount); Span<byte> spanB = nb.Slice(bidx, bcount); if (expected != null) { spanA.CopyTo(spanB); Assert.Equal(expected, b); ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected); ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { try { spanA.CopyTo(spanB); Assert.True(false); } catch (Exception) { Assert.True(true); } } Marshal.FreeHGlobal(pa); Marshal.FreeHGlobal(pb); } [Theory] // copy whole buffer [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6, new byte[] { 7, 7, 7, 7, 7, 7 })] // copy first half [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 })] // copy second half [InlineData( new byte[] { 4, 5, 6, 7, 7, 7 }, new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3, new byte[] { 7, 7, 7, 7, 7, 7 })] // copy no bytes starting from index 0 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0, new byte[] { 1, 2, 3, 4, 5, 6 })] // copy no bytes starting from index 3 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0, new byte[] { 1, 2, 3, 4, 5, 6 })] // copy no bytes starting at the end [InlineData( new byte[] { 7, 7, 7, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0, new byte[] { 7, 7, 7, 4, 5, 6 })] // copy first byte of 1 element array [InlineData( new byte[] { 6, 2, 3, 4, 5, 6 }, new byte[] { 6 }, 0, 1, new byte[] { 1, 2, 3, 4, 5, 6 })] public void SpanCopyToArrayTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b) { if (expected != null) { Span<byte> spanA = new Span<byte>(a, aidx, acount); spanA.CopyTo(b); Assert.Equal(expected, b); Span<byte> spanExpected = new Span<byte>(expected); Span<byte> spanBAll = new Span<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { Span<byte> spanA = new Span<byte>(a, aidx, acount); try { spanA.CopyTo(b); Assert.True(false); } catch (Exception) { Assert.True(true); } } } [Theory] // copy whole buffer [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 4, 5, 6 }, 0, 6, new byte[] { 7, 7, 7, 7, 7, 7 })] // copy first half [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 0, 3, new byte[] { 7, 7, 7, 4, 5, 6 })] // copy second half [InlineData( new byte[] { 4, 5, 6, 7, 7, 7 }, new byte[] { 7, 7, 7, 4, 5, 6 }, 3, 3, new byte[] { 7, 7, 7, 7, 7, 7 })] // copy no bytes starting from index 0 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 0, 0, new byte[] { 1, 2, 3, 4, 5, 6 })] // copy no bytes starting from index 3 [InlineData( new byte[] { 1, 2, 3, 4, 5, 6 }, new byte[] { 7, 7, 7, 7, 7, 7 }, 3, 0, new byte[] { 1, 2, 3, 4, 5, 6 })] // copy no bytes starting at the end [InlineData( new byte[] { 7, 7, 7, 4, 5, 6 }, new byte[] { 1, 2, 3, 7, 7, 7 }, 6, 0, new byte[] { 7, 7, 7, 4, 5, 6 })] // copy first byte of 1 element array [InlineData( new byte[] { 6, 2, 3, 4, 5, 6 }, new byte[] { 6 }, 0, 1, new byte[] { 1, 2, 3, 4, 5, 6 })] public void ROSpanCopyToArrayTwoDifferentBuffersValidCases(byte[] expected, byte[] a, int aidx, int acount, byte[] b) { if (expected != null) { ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount); spanA.CopyTo(b); Assert.Equal(expected, b); ReadOnlySpan<byte> spanExpected = new ReadOnlySpan<byte>(expected); ReadOnlySpan<byte> spanBAll = new ReadOnlySpan<byte>(b); Assert.True(spanExpected.SequenceEqual(spanBAll)); } else { ReadOnlySpan<byte> spanA = new ReadOnlySpan<byte>(a, aidx, acount); try { spanA.CopyTo(b); Assert.True(false); } catch (Exception) { Assert.True(true); } } } } }
// 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 SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; using Encoding = System.Text.Encoding; namespace System.Xml.Linq { /// <summary> /// Represents an XML document. /// </summary> /// <remarks> /// An <see cref="XDocument"/> can contain: /// <list> /// <item> /// A Document Type Declaration (DTD), see <see cref="XDocumentType"/> /// </item> /// <item>One root element.</item> /// <item>Zero or more <see cref="XComment"/> objects.</item> /// <item>Zero or more <see cref="XProcessingInstruction"/> objects.</item> /// </list> /// </remarks> public class XDocument : XContainer { private XDeclaration _declaration; ///<overloads> /// Initializes a new instance of the <see cref="XDocument"/> class. /// Overloaded constructors are provided for creating a new empty /// <see cref="XDocument"/>, creating an <see cref="XDocument"/> with /// a parameter list of initial content, and as a copy of another /// <see cref="XDocument"/> object. /// </overloads> /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class. /// </summary> public XDocument() { } /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class with the specified content. /// </summary> /// <param name="content"> /// A parameter list of content objects to add to this document. /// </param> /// <remarks> /// Valid content includes: /// <list> /// <item>Zero or one <see cref="XDocumentType"/> objects</item> /// <item>Zero or one elements</item> /// <item>Zero or more comments</item> /// <item>Zero or more processing instructions</item> /// </list> /// See <see cref="XContainer.Add(object)"/> for details about the content that can be added /// using this method. /// </remarks> public XDocument(params object[] content) : this() { AddContentSkipNotify(content); } /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class /// with the specified <see cref="XDeclaration"/> and content. /// </summary> /// <param name="declaration"> /// The XML declaration for the document. /// </param> /// <param name="content"> /// The contents of the document. /// </param> /// <remarks> /// Valid content includes: /// <list> /// <item>Zero or one <see cref="XDocumentType"/> objects</item> /// <item>Zero or one elements</item> /// <item>Zero or more comments</item> /// <item>Zero or more processing instructions</item> /// <item></item> /// </list> /// See <see cref="XContainer.Add(object)"/> for details about the content that can be added /// using this method. /// </remarks> public XDocument(XDeclaration declaration, params object[] content) : this(content) { _declaration = declaration; } /// <summary> /// Initializes a new instance of the <see cref="XDocument"/> class from an /// existing XDocument object. /// </summary> /// <param name="other"> /// The <see cref="XDocument"/> object that will be copied. /// </param> public XDocument(XDocument other) : base(other) { if (other._declaration != null) { _declaration = new XDeclaration(other._declaration); } } /// <summary> /// Gets the XML declaration for this document. /// </summary> public XDeclaration Declaration { get { return _declaration; } set { _declaration = value; } } /// <summary> /// Gets the Document Type Definition (DTD) for this document. /// </summary> public XDocumentType DocumentType { get { return GetFirstNode<XDocumentType>(); } } /// <summary> /// Gets the node type for this node. /// </summary> /// <remarks> /// This property will always return XmlNodeType.Document. /// </remarks> public override XmlNodeType NodeType { get { return XmlNodeType.Document; } } /// <summary> /// Gets the root element of the XML Tree for this document. /// </summary> public XElement Root { get { return GetFirstNode<XElement>(); } } /// <overloads> /// The Load method provides multiple strategies for creating a new /// <see cref="XDocument"/> and initializing it from a data source containing /// raw XML. Load from a file (passing in a URI to the file), a /// <see cref="Stream"/>, a <see cref="TextReader"/>, or an /// <see cref="XmlReader"/>. Note: Use <see cref="XDocument.Parse(string)"/> /// to create an <see cref="XDocument"/> from a string containing XML. /// <seealso cref="XDocument.Parse(string)"/> /// </overloads> /// <summary> /// Create a new <see cref="XDocument"/> based on the contents of the file /// referenced by the URI parameter passed in. Note: Use /// <see cref="XDocument.Parse(string)"/> to create an <see cref="XDocument"/> from /// a string containing XML. /// <seealso cref="XmlReader.Create(string)"/> /// <seealso cref="XDocument.Parse(string)"/> /// </summary> /// <remarks> /// This method uses the <see cref="XmlReader.Create(string)"/> method to create /// an <see cref="XmlReader"/> to read the raw XML into the underlying /// XML tree. /// </remarks> /// <param name="uri"> /// A URI string referencing the file to load into a new <see cref="XDocument"/>. /// </param> /// <returns> /// An <see cref="XDocument"/> initialized with the contents of the file referenced /// in the passed in uri parameter. /// </returns> [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")] public static XDocument Load(string uri) { return Load(uri, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> based on the contents of the file /// referenced by the URI parameter passed in. Optionally, whitespace can be preserved. /// <see cref="XmlReader.Create(string)"/> /// </summary> /// <remarks> /// This method uses the <see cref="XmlReader.Create(string)"/> method to create /// an <see cref="XmlReader"/> to read the raw XML into an underlying /// XML tree. If LoadOptions.PreserveWhitespace is enabled then /// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// is set to false. /// </remarks> /// <param name="uri"> /// A string representing the URI of the file to be loaded into a new <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// An <see cref="XDocument"/> initialized with the contents of the file referenced /// in the passed uri parameter. If LoadOptions.PreserveWhitespace is enabled then /// all whitespace will be preserved. /// </returns> [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#", Justification = "Back-compat with System.Xml.")] public static XDocument Load(string uri, LoadOptions options) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(uri, rs)) { return Load(r, options); } } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="Stream"/> parameter. /// </summary> /// <param name="stream"> /// A <see cref="Stream"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="Stream"/>. /// </returns> public static XDocument Load(Stream stream) { return Load(stream, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="Stream"/> parameter. Optionally whitespace handling /// can be preserved. /// </summary> /// <remarks> /// If LoadOptions.PreserveWhitespace is enabled then /// the underlying <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// is set to false. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="Stream"/>. /// </returns> public static XDocument Load(Stream stream, LoadOptions options) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(stream, rs)) { return Load(r, options); } } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="TextReader"/> parameter. /// </summary> /// <param name="textReader"> /// A <see cref="TextReader"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="TextReader"/>. /// </returns> public static XDocument Load(TextReader textReader) { return Load(textReader, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> and initialize its underlying XML tree using /// the passed <see cref="TextReader"/> parameter. Optionally whitespace handling /// can be preserved. /// </summary> /// <remarks> /// If LoadOptions.PreserveWhitespace is enabled then /// the <see cref="XmlReaderSettings"/> property <see cref="XmlReaderSettings.IgnoreWhitespace"/> /// is set to false. /// </remarks> /// <param name="textReader"> /// A <see cref="TextReader"/> containing the raw XML to read into the newly /// created <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed in /// <see cref="TextReader"/>. /// </returns> public static XDocument Load(TextReader textReader, LoadOptions options) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(textReader, rs)) { return Load(r, options); } } /// <summary> /// Create a new <see cref="XDocument"/> containing the contents of the /// passed in <see cref="XmlReader"/>. /// </summary> /// <param name="reader"> /// An <see cref="XmlReader"/> containing the XML to be read into the new /// <see cref="XDocument"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed /// in <see cref="XmlReader"/>. /// </returns> public static XDocument Load(XmlReader reader) { return Load(reader, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> containing the contents of the /// passed in <see cref="XmlReader"/>. /// </summary> /// <param name="reader"> /// An <see cref="XmlReader"/> containing the XML to be read into the new /// <see cref="XDocument"/>. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// A new <see cref="XDocument"/> containing the contents of the passed /// in <see cref="XmlReader"/>. /// </returns> public static XDocument Load(XmlReader reader, LoadOptions options) { if (reader == null) throw new ArgumentNullException("reader"); if (reader.ReadState == ReadState.Initial) reader.Read(); XDocument d = new XDocument(); if ((options & LoadOptions.SetBaseUri) != 0) { string baseUri = reader.BaseURI; if (baseUri != null && baseUri.Length != 0) { d.SetBaseUri(baseUri); } } if ((options & LoadOptions.SetLineInfo) != 0) { IXmlLineInfo li = reader as IXmlLineInfo; if (li != null && li.HasLineInfo()) { d.SetLineInfo(li.LineNumber, li.LinePosition); } } if (reader.NodeType == XmlNodeType.XmlDeclaration) { d.Declaration = new XDeclaration(reader); } d.ReadContentFrom(reader, options); if (!reader.EOF) throw new InvalidOperationException(SR.InvalidOperation_ExpectedEndOfFile); if (d.Root == null) throw new InvalidOperationException(SR.InvalidOperation_MissingRoot); return d; } /// <overloads> /// Create a new <see cref="XDocument"/> from a string containing /// XML. Optionally whitespace can be preserved. /// </overloads> /// <summary> /// Create a new <see cref="XDocument"/> from a string containing /// XML. /// </summary> /// <param name="text"> /// A string containing XML. /// </param> /// <returns> /// An <see cref="XDocument"/> containing an XML tree initialized from the /// passed in XML string. /// </returns> public static XDocument Parse(string text) { return Parse(text, LoadOptions.None); } /// <summary> /// Create a new <see cref="XDocument"/> from a string containing /// XML. Optionally whitespace can be preserved. /// </summary> /// <remarks> /// This method uses <see cref="XmlReader.Create(TextReader, XmlReaderSettings)"/>, /// passing it a StringReader constructed from the passed in XML String. If /// <see cref="LoadOptions.PreserveWhitespace"/> is enabled then /// <see cref="XmlReaderSettings.IgnoreWhitespace"/> is set to false. See /// <see cref="XmlReaderSettings.IgnoreWhitespace"/> for more information on /// whitespace handling. /// </remarks> /// <param name="text"> /// A string containing XML. /// </param> /// <param name="options"> /// A set of <see cref="LoadOptions"/>. /// </param> /// <returns> /// An <see cref="XDocument"/> containing an XML tree initialized from the /// passed in XML string. /// </returns> public static XDocument Parse(string text, LoadOptions options) { using (StringReader sr = new StringReader(text)) { XmlReaderSettings rs = GetXmlReaderSettings(options); using (XmlReader r = XmlReader.Create(sr, rs)) { return Load(r, options); } } } /// <summary> /// Output this <see cref="XDocument"/> to the passed in <see cref="Stream"/>. /// </summary> /// <remarks> /// The format will be indented by default. If you want /// no indenting then use the SaveOptions version of Save (see /// <see cref="XDocument.Save(Stream, SaveOptions)"/>) enabling /// SaveOptions.DisableFormatting /// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations. /// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options. /// </remarks> /// <param name="stream"> /// The <see cref="Stream"/> to output this <see cref="XDocument"/> to. /// </param> public void Save(Stream stream) { Save(stream, GetSaveOptionsFromAnnotations()); } /// <summary> /// Output this <see cref="XDocument"/> to a <see cref="Stream"/>. /// </summary> /// <param name="stream"> /// The <see cref="Stream"/> to output the XML to. /// </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(Stream stream, SaveOptions options) { XmlWriterSettings ws = GetXmlWriterSettings(options); if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding)) { try { ws.Encoding = Encoding.GetEncoding(_declaration.Encoding); } catch (ArgumentException) { } } using (XmlWriter w = XmlWriter.Create(stream, ws)) { Save(w); } } /// <summary> /// Output this <see cref="XDocument"/> to the passed in <see cref="TextWriter"/>. /// </summary> /// <remarks> /// The format will be indented by default. If you want /// no indenting then use the SaveOptions version of Save (see /// <see cref="XDocument.Save(TextWriter, SaveOptions)"/>) enabling /// SaveOptions.DisableFormatting /// There is also an option SaveOptions.OmitDuplicateNamespaces for removing duplicate namespace declarations. /// Or instead use the SaveOptions as an annotation on this node or its ancestors, then this method will use those options. /// </remarks> /// <param name="textWriter"> /// The <see cref="TextWriter"/> to output this <see cref="XDocument"/> to. /// </param> public void Save(TextWriter textWriter) { Save(textWriter, GetSaveOptionsFromAnnotations()); } /// <summary> /// Output this <see cref="XDocument"/> to a <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter"> /// The <see cref="TextWriter"/> to output the XML to. /// </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(TextWriter textWriter, SaveOptions options) { XmlWriterSettings ws = GetXmlWriterSettings(options); using (XmlWriter w = XmlWriter.Create(textWriter, ws)) { Save(w); } } /// <summary> /// Output this <see cref="XDocument"/> to an <see cref="XmlWriter"/>. /// </summary> /// <param name="writer"> /// The <see cref="XmlWriter"/> to output the XML to. /// </param> public void Save(XmlWriter writer) { WriteTo(writer); } /// <summary> /// Output this <see cref="XDocument"/>'s underlying XML tree to the /// passed in <see cref="XmlWriter"/>. /// <seealso cref="XDocument.Save(XmlWriter)"/> /// </summary> /// <param name="writer"> /// The <see cref="XmlWriter"/> to output the content of this /// <see cref="XDocument"/>. /// </param> public override void WriteTo(XmlWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); if (_declaration != null && _declaration.Standalone == "yes") { writer.WriteStartDocument(true); } else if (_declaration != null && _declaration.Standalone == "no") { writer.WriteStartDocument(false); } else { writer.WriteStartDocument(); } WriteContentTo(writer); writer.WriteEndDocument(); } internal override void AddAttribute(XAttribute a) { throw new ArgumentException(SR.Argument_AddAttribute); } internal override void AddAttributeSkipNotify(XAttribute a) { throw new ArgumentException(SR.Argument_AddAttribute); } internal override XNode CloneNode() { return new XDocument(this); } internal override bool DeepEquals(XNode node) { XDocument other = node as XDocument; return other != null && ContentsEqual(other); } internal override int GetDeepHashCode() { return ContentsHashCode(); } T GetFirstNode<T>() where T : XNode { XNode n = content as XNode; if (n != null) { do { n = n.next; T e = n as T; if (e != null) return e; } while (n != content); } return null; } internal static bool IsWhitespace(string s) { foreach (char ch in s) { if (ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n') return false; } return true; } internal override void ValidateNode(XNode node, XNode previous) { switch (node.NodeType) { case XmlNodeType.Text: ValidateString(((XText)node).Value); break; case XmlNodeType.Element: ValidateDocument(previous, XmlNodeType.DocumentType, XmlNodeType.None); break; case XmlNodeType.DocumentType: ValidateDocument(previous, XmlNodeType.None, XmlNodeType.Element); break; case XmlNodeType.CDATA: throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.CDATA)); case XmlNodeType.Document: throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.Document)); } } void ValidateDocument(XNode previous, XmlNodeType allowBefore, XmlNodeType allowAfter) { XNode n = content as XNode; if (n != null) { if (previous == null) allowBefore = allowAfter; do { n = n.next; XmlNodeType nt = n.NodeType; if (nt == XmlNodeType.Element || nt == XmlNodeType.DocumentType) { if (nt != allowBefore) throw new InvalidOperationException(SR.InvalidOperation_DocumentStructure); allowBefore = XmlNodeType.None; } if (n == previous) allowBefore = allowAfter; } while (n != content); } } internal override void ValidateString(string s) { if (!IsWhitespace(s)) throw new ArgumentException(SR.Argument_AddNonWhitespace); } } }
using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace RMArt.Core { public class PicturesService : IPicturesService, IDisposable { private readonly IPicturesRepository _picturesRepository; private readonly IFileRepository _picturesFileRepository; private readonly IFileRepository _thumbsFileRepository; private readonly IRatesRepository _ratesRepository; private readonly IFavoritesRepository _favoritesRepository; private readonly ITagsService _tagsService; private readonly IHistoryService _historyService; private readonly IUsersService _usersService; private readonly long? _maxFileSize; private readonly IDictionary<int, Size> _thumbnailSizePresets; public PicturesService( IPicturesRepository picturesRepository, IFileRepository picturesFileRepository, IFileRepository thumbsFileRepository, IRatesRepository ratesRepository, IFavoritesRepository favoritesRepository, ITagsService tagsService, IHistoryService historyService, IUsersService usersService, IDictionary<int, Size> thumbnailSizePresets, long? maxFileSize = null) { _picturesRepository = picturesRepository; _picturesFileRepository = picturesFileRepository; _thumbsFileRepository = thumbsFileRepository; _tagsService = tagsService; _historyService = historyService; _usersService = usersService; _maxFileSize = maxFileSize; _thumbnailSizePresets = thumbnailSizePresets; _ratesRepository = ratesRepository; _favoritesRepository = favoritesRepository; _usersService = usersService; _usersService.RoleChanged += OnUserRoleChanged; } public void Dispose() { _usersService.RoleChanged -= OnUserRoleChanged; } public IQueryable<Picture> Find(PicturesQuery query = null) { if (query == PicturesQuery.None) return Enumerable.Empty<Picture>().AsQueryable(); return _picturesRepository.Find(query); } public IQueryable<Picture> GetSimilar(int id) { return _picturesRepository.GetSimilar(id); } public IFileInfo GetPictureFile(int id) { return _picturesFileRepository.Get(GetPictureFileName(id)); } public IFileInfo GetThumbFile(int id, int size) { return _thumbsFileRepository.Get(GetThumbFileName(id, size)); } public PictureAddingResult Add(Stream inputStream, ModerationStatus status, Identity identity, bool replaceFile, out int id) { if (inputStream == null) throw new ArgumentNullException("inputStream"); if (identity == null) throw new ArgumentNullException("identity"); var data = inputStream.ReadAll(); var size = data.Length; if (_maxFileSize != null && size > _maxFileSize.Value) { id = -1; return PictureAddingResult.FileTooBig; } var fileHash = data.ComputeMD5Hash(); ImageFormat format; int width; int height; byte[] bitmapHash; try { using (var sourceStream = new MemoryStream(data, false)) using (var image = new Bitmap(sourceStream, true)) { format = image.GetFormat(); width = image.Width; height = image.Height; bitmapHash = image.ComputeBitmapHash(); } } catch (ArgumentException) { id = -1; return PictureAddingResult.InvalidData; } catch (NotSupportedException) { id = -1; return PictureAddingResult.NotSupportedFormat; } var existing = Find(new PicturesQuery { BitmapHash = bitmapHash }).SingleOrDefault(); if (existing != null) { id = existing.ID; if (replaceFile) { var pictureFileName = GetPictureFileName(id); _picturesFileRepository.Delete(pictureFileName); using (var pictureFileStream = _picturesFileRepository.Create(pictureFileName)) pictureFileStream.Write(data, 0, data.Length); _picturesRepository.SetFileHashAndSize(id, fileHash, size); } return PictureAddingResult.AlreadyExists; } id = _picturesRepository.Add( new Picture { FileHash = fileHash, BitmapHash = bitmapHash, Format = format, Width = width, Height = height, FileSize = size, Status = status, CreatorID = identity.UserID, CreatorIP = identity.IPAddress.GetAddressBytes(), CreationDate = DateTime.UtcNow }); try { using (var pictureFileStream = _picturesFileRepository.Create(GetPictureFileName(id))) pictureFileStream.Write(data, 0, data.Length); using (var memoryStream = new MemoryStream(data, false)) MakeThumbs(id, memoryStream, true); } catch { Delete(id); throw; } return PictureAddingResult.Added; } public Picture CheckExists(Stream inputStream) { if (inputStream == null) throw new ArgumentNullException("inputStream"); byte[] bitmapHash; using (var image = new Bitmap(inputStream, true)) bitmapHash = image.ComputeBitmapHash(); return Find(new PicturesQuery { BitmapHash = bitmapHash }).SingleOrDefault(); } public void Delete(int id) { _ratesRepository.Delete(new RatesQuery { PictureID = id }); _favoritesRepository.Delete(new FavoritesQuery { PictureID = id }); var removedPicture = _picturesRepository.Remove(id); if (removedPicture.Status == ModerationStatus.Accepted) foreach (var tid in removedPicture.Tags) _tagsService.IncrementUsageCount(tid, -1); DeleteFiles(id); _historyService.DeleteFor(new ObjectReference(ObjectType.Picture, id)); } public void Update(int id, PictureUpdate update, Identity identity, string comment) { if (update == null) throw new ArgumentNullException("update"); if (update.Source != null && !PicturesHelper.IsValidSource(update.Source)) throw new ArgumentException("Invalid source format.", "update"); if (identity == null) throw new ArgumentNullException("identity"); var old = _picturesRepository.Update(id, update); if (update.Status != null && update.Status.Value != old.Status) { if (update.Status == ModerationStatus.Accepted) foreach (var tid in old.Tags) _tagsService.IncrementUsageCount(tid, 1); else if (old.Status == ModerationStatus.Accepted) foreach (var tid in old.Tags) _tagsService.IncrementUsageCount(tid, -1); _historyService.LogValueChange( new ObjectReference(ObjectType.Picture, id), HistoryField.Status, (int)old.Status, (int)update.Status, identity, comment); } var isAccepted = (update.Status ?? old.Status) == ModerationStatus.Accepted; if (update.AddTags != null) foreach (var tagID in update.AddTags.Except(old.Tags).Distinct()) { if (isAccepted) _tagsService.IncrementUsageCount(tagID, 1); _historyService.LogCollectionAdd( new ObjectReference(ObjectType.Picture, id), HistoryField.Tags, tagID, identity, comment); } if (update.RemoveTags != null) foreach (var tagID in update.RemoveTags.Intersect(old.Tags).Distinct()) { if (isAccepted) _tagsService.IncrementUsageCount(tagID, -1); _historyService.LogCollectionRemove( new ObjectReference(ObjectType.Picture, id), HistoryField.Tags, tagID, identity, comment); } if (update.RequiresTagging != null && update.RequiresTagging.Value != old.RequiresTagging) _historyService.LogValueChange( new ObjectReference(ObjectType.Picture, id), HistoryField.RequiresTagging, !update.RequiresTagging, update.RequiresTagging, identity, comment); if (update.Rating != null && update.Rating.Value != old.Rating) _historyService.LogValueChange( new ObjectReference(ObjectType.Picture, id), HistoryField.Rating, (int)old.Rating, (int)update.Rating, identity, comment); if (update.Source != null && !PicturesHelper.IsSourcesEquals(update.Source, old.Source)) _historyService.LogValueChange( new ObjectReference(ObjectType.Picture, id), HistoryField.Source, old.Source, update.Source, identity, comment); _picturesRepository.UpdateSimilar(id, 5); } public void Rate(int id, int score, Identity identity) { if (score < 0 || score > 3) throw new ArgumentOutOfRangeException("score"); // ReSharper disable PossibleInvalidOperationException var userID = identity.UserID.Value; // ReSharper restore PossibleInvalidOperationException var existingPredicate = new RatesQuery { PictureID = id, UserID = userID }; var existing = _ratesRepository.List(existingPredicate).SingleOrDefault(); if (existing != null) if (existing.Score == score) return; else _ratesRepository.Delete(existingPredicate); if (score != 0) _ratesRepository.Add( new Rate { PictureID = id, UserID = userID, Score = score, Date = DateTime.UtcNow, IPAddress = identity.IPAddress.GetAddressBytes(), IsActive = _usersService.GetRole(userID) >= UserRole.User }); UpdatePictureRateAggregates(id); } public void SetFavorited(int id, bool favorited, Identity identity) { if (identity.UserID == null) throw new InvalidOperationException(); if (_favoritesRepository.IsExists(new FavoritesQuery(identity.UserID, id)) == favorited) return; if (favorited) _favoritesRepository.Add(new FavoritesItem { PictureID = id, UserID = identity.UserID.Value, Date = DateTime.UtcNow }); else _favoritesRepository.Delete(new FavoritesQuery(identity.UserID, id)); } public void AssignTagChilds(int tagID, Identity identity) { var pictureIDsForTagging = new HashSet<int>(); foreach (var childrenTagID in _tagsService.GetChildsOf(tagID, true)) { var picturesWithTag = Find(new PicturesQuery { ReqiredTagIDs = new SortedSet<int> { childrenTagID } }).Select(_ => _.ID); foreach (var pid in picturesWithTag) pictureIDsForTagging.Add(pid); } foreach (var pid in pictureIDsForTagging) Update(pid, new PictureUpdate { AddTags = new[] { tagID } }, identity, null); } public void RecalcCachedTags() { _picturesRepository.RecalcCachedTags(); } public void UpdateRateAggregates() { foreach (var id in Find().Select(_ => _.ID).ToArray()) UpdatePictureRateAggregates(id); } public void RebuildThumbs(bool overwriteExisting, IProgressIndicator progressIndicator) { var ids = Find(new PicturesQuery { SortBy = PicturesSortOrder.Newest }).Select(_ => _.ID).ToArray(); for (var i = 0; i < ids.Length; i++) { if (progressIndicator != null && i % 100 == 0) progressIndicator.ReportProgress(ids.Length, i); var id = ids[i]; try { var pictureFile = GetPictureFile(id); if (pictureFile == null) continue; using (var fs = pictureFile.OpenRead()) MakeThumbs(id, fs, overwriteExisting); } catch (Exception exception) { if (progressIndicator != null) progressIndicator.Message(string.Format("Error making thumbnail for #{0}:\n{1}", id, exception)); } } } public void RecalcFileHashes(IProgressIndicator progressIndicator) { var ids = _picturesRepository.Find().Select(_ => _.ID).ToArray(); for (var i = 0; i < ids.Length; i++) { if (progressIndicator != null && i % 100 == 0) progressIndicator.ReportProgress(ids.Length, i); var currentID = ids[i]; var pictureFile = GetPictureFile(currentID); if (pictureFile == null) { if (progressIndicator != null) progressIndicator.Message(string.Format("Picture #{0} file is missing.", currentID)); continue; } byte[] hash; long fileSize; using (var fs = pictureFile.OpenRead()) { hash = fs.ComputeMD5Hash(); fileSize = fs.Length; } var conflicted = Find(new PicturesQuery { FileHash = hash }).SingleOrDefault(); if (conflicted == null) _picturesRepository.SetFileHashAndSize(currentID, hash, fileSize); else if (conflicted.ID != currentID) { var destantionID = Merge(currentID, conflicted.ID); if (destantionID == currentID) _picturesRepository.SetFileHashAndSize(currentID, hash, fileSize); if (progressIndicator != null) progressIndicator.Message(string.Format("Picture #{0} merged with #{1} into #{2}.", currentID, conflicted.ID, destantionID)); } } } public void RecalcBitmapHashes(IProgressIndicator progressIndicator) { var ids = _picturesRepository.Find().Select(_ => _.ID).ToArray(); var completed = 0; Parallel.ForEach( ids, currentID => { var pictureFile = GetPictureFile(currentID); if (pictureFile != null) { byte[] bitmapHash; using (var fs = pictureFile.OpenRead()) using (var image = new Bitmap(fs, true)) bitmapHash = image.ComputeBitmapHash(); var conflicted = Find(new PicturesQuery { BitmapHash = bitmapHash }).SingleOrDefault(); if (conflicted == null) _picturesRepository.SetBitmapHash(currentID, bitmapHash); else if (conflicted.ID != currentID) { var destantionID = Merge(currentID, conflicted.ID); if (destantionID == currentID) _picturesRepository.SetBitmapHash(currentID, bitmapHash); if (progressIndicator != null) progressIndicator.Message(string.Format("Picture #{0} merged with #{1} into #{2}.", currentID, conflicted.ID, destantionID)); } } else if (progressIndicator != null) progressIndicator.Message(string.Format("Picture #{0} file is missing.", currentID)); Interlocked.Increment(ref completed); if (progressIndicator != null && completed % 100 == 0) progressIndicator.ReportProgress(ids.Length, completed); }); } public void RecalcTagCount(IProgressIndicator progressIndicator) { var tagIDs = _tagsService.Find().Select(t => t.ID).ToArray(); foreach (var tagID in tagIDs) { var count = Find( new PicturesQuery { ReqiredTagIDs = new SortedSet<int> { tagID }, AllowedStatuses = new SortedSet<ModerationStatus> { ModerationStatus.Accepted } }).Count(); _tagsService.SetUsageCount(tagID, count); } } public void UpdateSimilarPictures(IProgressIndicator progressIndicator) { var ids = Find(new PicturesQuery { SortBy = PicturesSortOrder.Newest }).Select(_ => _.ID).ToArray(); for (var i = 0; i < ids.Length; i++) { if (progressIndicator != null && i % 100 == 0) progressIndicator.ReportProgress(ids.Length, i); _picturesRepository.UpdateSimilar(ids[i], 5); } } public IDictionary<int, Size> ThumbnailSizePresets { get { return _thumbnailSizePresets; } } private void DeleteFiles(int id) { _picturesFileRepository.Delete(GetPictureFileName(id)); foreach (var size in _thumbnailSizePresets.Keys) _thumbsFileRepository.Delete(GetThumbFileName(id, size)); } private void MakeThumbs(int id, Stream sourceStream, bool overwriteExisting) { using (var source = Image.FromStream(sourceStream)) foreach (var preset in _thumbnailSizePresets) { var thumbFileName = GetThumbFileName(id, preset.Key); if (_thumbsFileRepository.IsExists(thumbFileName)) if (overwriteExisting) _thumbsFileRepository.Delete(thumbFileName); else continue; using (var thumb = ImagingHelper.MakeThumb(source, preset.Value.Width, preset.Value.Height, Color.White)) using (var thumbFileStream = _thumbsFileRepository.Create(thumbFileName)) thumb.SaveAsJpeg(thumbFileStream); } } private void UpdatePictureRateAggregates(int id) { var pictureRates = _ratesRepository.List(new RatesQuery { PictureID = id, IsActive = true }); var count = pictureRates.Count(); var totalScore = pictureRates.Sum(r => r.Score); _picturesRepository.SetRateAggregates(id, count, totalScore); } private int Merge(int a, int b) { var source = _picturesRepository.Find(new PicturesQuery { ID = Math.Max(a, b) }).Single(); var destantion = _picturesRepository.Find(new PicturesQuery { ID = Math.Min(a, b) }).Single(); var update = new PictureUpdate(); if (source.Status == ModerationStatus.Accepted && destantion.Status != ModerationStatus.Accepted) update.Status = source.Status; if (source.Rating != Rating.Unrated && destantion.Rating == Rating.Unrated) update.Rating = source.Rating; if (!string.IsNullOrEmpty(source.Source) && string.IsNullOrEmpty(destantion.Source)) update.Source = source.Source; update.AddTags = source.Tags.Except(destantion.Tags).ToArray(); Update(destantion.ID, update, Identity.Empty, null); foreach (var rate in _ratesRepository.List(new RatesQuery { PictureID = source.ID })) if (!_ratesRepository.IsExists(new RatesQuery { PictureID = destantion.ID, UserID = rate.UserID })) _ratesRepository.Add(new Rate { PictureID = destantion.ID, UserID = rate.UserID, Score = rate.Score, Date = rate.Date, IPAddress = rate.IPAddress, IsActive = rate.IsActive }); foreach (var f in _favoritesRepository.Find(new FavoritesQuery { PictureID = source.ID })) if (!_favoritesRepository.IsExists(new FavoritesQuery(f.UserID, destantion.ID))) _favoritesRepository.Add(new FavoritesItem { PictureID = destantion.ID, UserID = f.UserID, Date = f.Date }); Delete(source.ID); return destantion.ID; } private void OnUserRoleChanged(object sender, RoleChangedEventArgs args) { if (args.NewRole == UserRole.Guest || args.OldRole == UserRole.Guest) { var isActive = args.NewRole != UserRole.Guest; _ratesRepository.UpdateIsActive(new RatesQuery { UserID = args.UserID }, isActive); foreach (var id in Find(new PicturesQuery { RatedBy = args.UserID }).Select(_ => _.ID)) UpdatePictureRateAggregates(id); } } private static string GetPictureFileName(int id) { return id.ToString(); } private static string GetThumbFileName(int id, int size) { return string.Concat(id, "_Thumb_", size); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Modules; using Microsoft.Extensions.Logging; using Orchard.Environment.Extensions; using Orchard.Environment.Shell.Builders; using Orchard.Environment.Shell.Descriptor.Models; using Orchard.Environment.Shell.Models; using Orchard.Hosting.ShellBuilders; namespace Orchard.Environment.Shell { /// <summary> /// All <see cref="ShellContext"/> object are loaded when <see cref="Initialize"/> is called. They can be removed when the /// tenant is removed, but are necessary to match an incoming request, even if they are not initialized. /// Each <see cref="ShellContext"/> is activated (its service provider is built) on the first request. /// </summary> public class ShellHost : IShellHost, IShellDescriptorManagerEventHandler { private static EventId TenantNotStarted = new EventId(0); private readonly IShellSettingsManager _shellSettingsManager; private readonly IShellContextFactory _shellContextFactory; private readonly IRunningShellTable _runningShellTable; private readonly ILogger _logger; private readonly static object _syncLock = new object(); private ConcurrentDictionary<string, ShellContext> _shellContexts; private readonly IExtensionManager _extensionManager; public ShellHost( IShellSettingsManager shellSettingsManager, IShellContextFactory shellContextFactory, IRunningShellTable runningShellTable, IExtensionManager extensionManager, ILogger<ShellHost> logger) { _extensionManager = extensionManager; _shellSettingsManager = shellSettingsManager; _shellContextFactory = shellContextFactory; _runningShellTable = runningShellTable; _logger = logger; } public void Initialize() { BuildCurrent(); } /// <summary> /// Ensures shells are activated, or re-activated if extensions have changed /// </summary> IDictionary<string, ShellContext> BuildCurrent() { if (_shellContexts == null) { lock (this) { if (_shellContexts == null) { _shellContexts = new ConcurrentDictionary<string, ShellContext>(); CreateAndRegisterShellsAsync().Wait(); } } } return _shellContexts; } public ShellContext GetOrCreateShellContext(ShellSettings settings) { return _shellContexts.GetOrAdd(settings.Name, tenant => { var shellContext = CreateShellContextAsync(settings).Result; RegisterShell(shellContext); return shellContext; }); } public void UpdateShellSettings(ShellSettings settings) { _shellSettingsManager.SaveSettings(settings); ReloadShellContext(settings); } async Task CreateAndRegisterShellsAsync() { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Start creation of shells"); } // Load all extensions and features so that the controllers are // registered in ITypeFeatureProvider and their areas defined in the application // conventions. var features = _extensionManager.LoadFeaturesAsync(); // Is there any tenant right now? var allSettings = _shellSettingsManager.LoadSettings().Where(CanCreateShell).ToArray(); features.Wait(); // No settings, run the Setup. if (allSettings.Length == 0) { var setupContext = await CreateSetupContextAsync(); RegisterShell(setupContext); } else { // Load all tenants, and activate their shell. Parallel.ForEach(allSettings, settings => { try { GetOrCreateShellContext(settings); } catch (Exception ex) { _logger.LogError(TenantNotStarted, ex, $"A tenant could not be started: {settings.Name}"); if (ex.IsFatal()) { throw; } } }); } if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Done creating shells"); } } /// <summary> /// Registers the shell settings in RunningShellTable /// </summary> private void RegisterShell(ShellContext context) { if (!CanRegisterShell(context.Settings)) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Skipping shell context registration for tenant {0}", context.Settings.Name); } return; } if (_shellContexts.TryAdd(context.Settings.Name, context)) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Registering shell context for tenant {0}", context.Settings.Name); } _runningShellTable.Add(context.Settings); } } /// <summary> /// Creates a shell context based on shell settings /// </summary> public Task<ShellContext> CreateShellContextAsync(ShellSettings settings) { if (settings.State == TenantState.Uninitialized) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Creating shell context for tenant {0} setup", settings.Name); } return _shellContextFactory.CreateSetupContextAsync(settings); } else if (settings.State == TenantState.Disabled) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Creating disabled shell context for tenant {0} setup", settings.Name); } return Task.FromResult(new ShellContext { Settings = settings }); } else if(settings.State == TenantState.Running || settings.State == TenantState.Initializing) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Creating shell context for tenant {0}", settings.Name); } return _shellContextFactory.CreateShellContextAsync(settings); } else { throw new InvalidOperationException("Unexpected shell state for " + settings.Name); } } /// <summary> /// Creates a transient shell for the default tenant's setup. /// </summary> private Task<ShellContext> CreateSetupContextAsync() { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug("Creating shell context for root setup."); } return _shellContextFactory.CreateSetupContextAsync(ShellHelper.BuildDefaultUninitializedShell); } /// <summary> /// A feature is enabled/disabled, the tenant needs to be restarted /// </summary> Task IShellDescriptorManagerEventHandler.Changed(ShellDescriptor descriptor, string tenant) { if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("A tenant needs to be restarted {0}", tenant); } if (_shellContexts == null) { return Task.CompletedTask; } if (_shellContexts.TryRemove(tenant, out var context)) { context.Release(); } return Task.CompletedTask; } public void ReloadShellContext(ShellSettings settings) { ShellContext context; if (_shellContexts.TryRemove(settings.Name, out context)) { _runningShellTable.Remove(settings); context.Release(); } GetOrCreateShellContext(settings); } public IEnumerable<ShellContext> ListShellContexts() { return _shellContexts.Values; } /// <summary> /// Whether or not a shell can be added to the list of available shells. /// </summary> private bool CanCreateShell(ShellSettings shellSettings) { return shellSettings.State == TenantState.Running || shellSettings.State == TenantState.Uninitialized || shellSettings.State == TenantState.Initializing || shellSettings.State == TenantState.Disabled; } /// <summary> /// Whether or not a shell can be activated and added to the running shells. /// </summary> private bool CanRegisterShell(ShellSettings shellSettings) { return shellSettings.State == TenantState.Running || shellSettings.State == TenantState.Uninitialized || shellSettings.State == TenantState.Initializing; } } }
// // JSClassDefinition.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright 2010 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Reflection; using System.Collections.Generic; using System.Runtime.InteropServices; namespace JavaScriptCore { public class JSClassDefinition { private struct JSClassDefinitionNative { public int version; public JSClassAttribute attributes; public IntPtr class_name; public IntPtr parent_class; public IntPtr /* JSStaticValue[] */ static_values; public IntPtr static_functions; public JSObject.InitializeCallback initialize; public JSObject.FinalizeCallback finalize; public JSObject.HasPropertyCallback has_property; public JSObject.GetPropertyCallback get_property; public JSObject.SetPropertyCallback set_property; public JSObject.DeletePropertyCallback delete_property; public JSObject.GetPropertyNamesCallback get_property_names; public JSObject.CallAsFunctionCallback call_as_function; public JSObject.CallAsConstructorCallback call_as_constructor; public JSObject.HasInstanceCallback has_instance; public JSObject.ConvertToTypeCallback convert_to_type; } private JSClassDefinitionNative raw; private Dictionary<string, MethodInfo> static_methods; private JSObject.CallAsFunctionCallback static_function_callback; public virtual string ClassName { get { return GetType ().FullName.Replace (".", "_").Replace ("+", "_"); } } public JSClassDefinition () { raw = new JSClassDefinitionNative (); raw.class_name = Marshal.StringToHGlobalAnsi (ClassName); InstallClassOverrides (); InstallStaticMethods (); } private void InstallClassOverrides () { Override ("OnInitialize", () => raw.initialize = new JSObject.InitializeCallback (JSInitialize)); Override ("OnFinalize", () => raw.finalize = new JSObject.FinalizeCallback (JSFinalize)); Override ("OnJSHasProperty", () => raw.has_property = new JSObject.HasPropertyCallback (JSHasProperty)); Override ("OnJSGetProperty", () => raw.get_property = new JSObject.GetPropertyCallback (JSGetProperty)); Override ("OnJSSetProperty", () => raw.set_property = new JSObject.SetPropertyCallback (JSSetProperty)); Override ("OnJSDeleteProperty", () => raw.delete_property = new JSObject.DeletePropertyCallback (JSDeleteProperty)); Override ("OnJSGetPropertyNames", () => raw.get_property_names = new JSObject.GetPropertyNamesCallback (JSGetPropertyNames)); Override ("OnJSCallAsConstructor", () => raw.call_as_constructor = new JSObject.CallAsConstructorCallback (JSCallAsConstructor)); } private void InstallStaticMethods () { List<JSStaticFunction> methods = null; foreach (var method in GetType ().GetMethods ( BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic)) { foreach (var _attr in method.GetCustomAttributes (typeof (JSStaticFunctionAttribute), false)) { var attr = (JSStaticFunctionAttribute)_attr; var p = method.GetParameters (); if (method.ReturnType != typeof (JSValue) || p.Length != 3 && p[0].ParameterType != typeof (JSObject) || p[1].ParameterType != typeof (JSObject) || p[2].ParameterType != typeof (JSValue [])) { throw new Exception (String.Format ("Invalid signature for method annotated " + "with JSStaticFunctionAttribute: {0}:{1} ('{2}'); signature should be " + "'JSValue:JSFunction,JSObject,JSValue[]'", GetType ().FullName, method.Name, attr.Name)); } if (static_methods == null) { static_methods = new Dictionary<string, MethodInfo> (); } else if (static_methods.ContainsKey (attr.Name)) { throw new Exception ("Class already contains static method named '" + attr.Name + "'"); } static_methods.Add (attr.Name, method); if (methods == null) { methods = new List<JSStaticFunction> (); } if (static_function_callback == null) { static_function_callback = new JSObject.CallAsFunctionCallback (OnStaticFunctionCallback); } methods.Add (new JSStaticFunction () { Name = attr.Name, Attributes = attr.Attributes, Callback = static_function_callback }); } } if (methods != null && methods.Count > 0) { var size = Marshal.SizeOf (typeof (JSStaticFunction)); var ptr = Marshal.AllocHGlobal (size * (methods.Count + 1)); for (int i = 0; i < methods.Count; i++) { Marshal.StructureToPtr (methods[i], new IntPtr (ptr.ToInt64 () + size * i), false); } Marshal.StructureToPtr (new JSStaticFunction (), new IntPtr (ptr.ToInt64 () + size * methods.Count), false); raw.static_functions = ptr; } } private void Override (string methodName, Action handler) { var method = GetType ().GetMethod (methodName, BindingFlags.Instance | BindingFlags.NonPublic); if (method != null && (method.Attributes & MethodAttributes.VtableLayoutMask) == 0) { handler (); } } [DllImport (JSContext.NATIVE_IMPORT)] private static extern IntPtr JSClassCreate (ref JSClassDefinition.JSClassDefinitionNative definition); private JSClass class_handle; public JSClass ClassHandle { get { return class_handle ?? (class_handle = CreateClass ()); } } public JSClass CreateClass () { return new JSClass (JSClassCreate (ref raw)); } private IntPtr OnStaticFunctionCallback (IntPtr ctx, IntPtr function, IntPtr thisObject, IntPtr argumentCount, IntPtr arguments, ref IntPtr exception) { var context = new JSContext (ctx); var fn = new JSObject (ctx, function); string fn_name = null; if (fn.HasProperty ("name")) { var prop = fn.GetProperty ("name"); if (prop != null && prop.IsString) { fn_name = prop.StringValue; } } MethodInfo method = null; if (fn_name == null || !static_methods.TryGetValue (fn_name, out method)) { return JSValue.NewUndefined (context).Raw; } var result = method.Invoke (null, new object [] { fn, new JSObject (context, thisObject), JSValue.MarshalArray (ctx, arguments, argumentCount) }); return result == null ? JSValue.NewUndefined (context).Raw : ((JSValue)result).Raw; } private void JSInitialize (IntPtr ctx, IntPtr obj) { OnJSInitialize (new JSObject (ctx, obj)); } protected virtual void OnJSInitialize (JSObject obj) { } private void JSFinalize (IntPtr obj) { OnJSFinalize (new JSObject (obj)); } protected virtual void OnJSFinalize (JSObject obj) { } private bool JSHasProperty (IntPtr ctx, IntPtr obj, JSString propertyName) { return OnJSHasProperty (new JSObject (ctx, obj), propertyName.Value); } protected virtual bool OnJSHasProperty (JSObject obj, string propertyName) { return false; } private IntPtr JSGetProperty (IntPtr ctx, IntPtr obj, JSString propertyName, ref IntPtr exception) { var context = new JSContext (ctx); return (OnJSGetProperty (new JSObject (context, obj), propertyName.Value) ?? JSValue.NewNull (context)).Raw; } protected virtual JSValue OnJSGetProperty (JSObject obj, string propertyName) { return JSValue.NewUndefined (obj.Context); } private bool JSSetProperty (IntPtr ctx, IntPtr obj, JSString propertyName, IntPtr value, ref IntPtr exception) { var context = new JSContext (ctx); try { return OnJSSetProperty (new JSObject (context, obj), propertyName.Value, new JSValue (context, value)); } catch (JSErrorException e) { exception = e.Error.Raw; return false; } } protected virtual bool OnJSSetProperty (JSObject obj, string propertyName, JSValue value) { return false; } private bool JSDeleteProperty (IntPtr ctx, IntPtr obj, JSString propertyName, ref IntPtr exception) { return OnJSDeleteProperty (new JSObject (ctx, obj), propertyName.Value); } protected virtual bool OnJSDeleteProperty (JSObject obj, string propertyName) { return false; } private void JSGetPropertyNames (IntPtr ctx, IntPtr obj, JSPropertyNameAccumulator propertyNames) { OnJSGetPropertyNames (new JSObject (ctx, obj), propertyNames); } protected virtual void OnJSGetPropertyNames (JSObject obj, JSPropertyNameAccumulator propertyNames) { } private IntPtr JSCallAsConstructor (IntPtr ctx, IntPtr constructor, IntPtr argumentCount, IntPtr arguments, ref IntPtr exception) { var result = OnJSCallAsConstructor (new JSObject (ctx, constructor), JSValue.MarshalArray (ctx, arguments, argumentCount)); return result == null ? JSValue.NewUndefined (new JSContext (ctx)).Raw : ((JSValue)result).Raw; } protected virtual JSObject OnJSCallAsConstructor (JSObject constructor, JSValue [] args) { return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void MinDouble() { var test = new SimpleBinaryOpTest__MinDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__MinDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Double> _fld1; public Vector128<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__MinDouble testClass) { var result = Sse2.Min(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__MinDouble testClass) { fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Min( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__MinDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); } public SimpleBinaryOpTest__MinDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.Min( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.Min( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.Min( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.Min( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Double>* pClsVar1 = &_clsVar1) fixed (Vector128<Double>* pClsVar2 = &_clsVar2) { var result = Sse2.Min( Sse2.LoadVector128((Double*)(pClsVar1)), Sse2.LoadVector128((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.Min(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__MinDouble(); var result = Sse2.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__MinDouble(); fixed (Vector128<Double>* pFld1 = &test._fld1) fixed (Vector128<Double>* pFld2 = &test._fld2) { var result = Sse2.Min( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.Min(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Double>* pFld1 = &_fld1) fixed (Vector128<Double>* pFld2 = &_fld2) { var result = Sse2.Min( Sse2.LoadVector128((Double*)(pFld1)), Sse2.LoadVector128((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.Min(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.Min( Sse2.LoadVector128((Double*)(&test._fld1)), Sse2.LoadVector128((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(Math.Min(left[0], right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(Math.Min(left[i], right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.Min)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using FarseerPhysics.Collision.Shapes; using FarseerPhysics.Dynamics; using FarseerPhysics.Dynamics.Joints; using FarseerPhysics.Factories; using FarseerPhysics.TestBed.Framework; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; namespace FarseerPhysics.TestBed.Tests { /// <summary> /// This tests distance joints, body destruction, and joint destruction. /// </summary> public class WebTest : Test { private Body[] _bodies = new Body[4]; private Joint[] _joints = new Joint[8]; private int _removedBodies; private int _removedJoints; private WebTest() { World.JointRemoved += JointRemovedFired; World.BodyRemoved += BodyRemovedFired; { PolygonShape shape = new PolygonShape(5); shape.SetAsBox(0.5f, 0.5f); _bodies[0] = BodyFactory.CreateBody(World); _bodies[0].BodyType = BodyType.Dynamic; _bodies[0].Position = new Vector2(-5.0f, 5.0f); _bodies[0].CreateFixture(shape); _bodies[1] = BodyFactory.CreateBody(World); _bodies[1].BodyType = BodyType.Dynamic; _bodies[1].Position = new Vector2(5.0f, 5.0f); _bodies[1].CreateFixture(shape); _bodies[2] = BodyFactory.CreateBody(World); _bodies[2].BodyType = BodyType.Dynamic; _bodies[2].Position = new Vector2(5.0f, 15.0f); _bodies[2].CreateFixture(shape); _bodies[3] = BodyFactory.CreateBody(World); _bodies[3].BodyType = BodyType.Dynamic; _bodies[3].Position = new Vector2(-5.0f, 15.0f); _bodies[3].CreateFixture(shape); FixedDistanceJoint dj = new FixedDistanceJoint(_bodies[0], new Vector2(-0.5f, -0.5f), new Vector2(-10.0f, 0.0f)); _joints[0] = dj; dj.Frequency = 2.0f; dj.DampingRatio = 0.0f; World.AddJoint(_joints[0]); FixedDistanceJoint dj1 = new FixedDistanceJoint(_bodies[1], new Vector2(0.5f, -0.5f), new Vector2(10.0f, 0.0f)); _joints[1] = dj1; dj1.Frequency = 2.0f; dj1.DampingRatio = 0.0f; World.AddJoint(_joints[1]); FixedDistanceJoint dj2 = new FixedDistanceJoint(_bodies[2], new Vector2(0.5f, 0.5f), new Vector2(10.0f, 20.0f)); _joints[2] = dj2; dj2.Frequency = 2.0f; dj2.DampingRatio = 0.0f; World.AddJoint(_joints[2]); FixedDistanceJoint dj3 = new FixedDistanceJoint(_bodies[3], new Vector2(-0.5f, 0.5f), new Vector2(-10.0f, 20.0f)); _joints[3] = dj3; dj3.Frequency = 2.0f; dj3.DampingRatio = 0.0f; World.AddJoint(_joints[3]); DistanceJoint dj4 = new DistanceJoint(_bodies[0], _bodies[1], Vector2.Zero, Vector2.Zero); _joints[4] = dj4; dj4.Frequency = 2.0f; dj4.DampingRatio = 0.0f; World.AddJoint(_joints[4]); DistanceJoint dj5 = new DistanceJoint(_bodies[1], _bodies[2], Vector2.Zero, Vector2.Zero); _joints[5] = dj5; dj5.Frequency = 2.0f; dj5.DampingRatio = 0.0f; World.AddJoint(_joints[5]); DistanceJoint dj6 = new DistanceJoint(_bodies[2], _bodies[3], Vector2.Zero, Vector2.Zero); _joints[6] = dj6; dj6.Frequency = 2.0f; dj6.DampingRatio = 0.0f; World.AddJoint(_joints[6]); DistanceJoint dj7 = new DistanceJoint(_bodies[3], _bodies[0], Vector2.Zero, Vector2.Zero); _joints[7] = dj7; dj7.Frequency = 2.0f; dj7.DampingRatio = 0.0f; World.AddJoint(_joints[7]); } } private void BodyRemovedFired(Body body) { _removedBodies++; } private void JointRemovedFired(Joint joint) { if (joint is FixedDistanceJoint || joint is DistanceJoint) _removedJoints++; } public override void Keyboard(KeyboardManager keyboardManager) { if (keyboardManager.IsNewKeyPress(Keys.B)) { for (int i = 0; i < 4; ++i) { if (_bodies[i] != null) { World.RemoveBody(_bodies[i]); _bodies[i] = null; break; } } } if (keyboardManager.IsNewKeyPress(Keys.J)) { for (int i = 0; i < 8; ++i) { if (_joints[i] != null) { World.RemoveJoint(_joints[i]); _joints[i] = null; break; } } } base.Keyboard(keyboardManager); } public override void Update(GameSettings settings, GameTime gameTime) { base.Update(settings, gameTime); DebugView.DrawString(50, TextLine, "This demonstrates a soft distance joint."); TextLine += 15; DebugView.DrawString(50, TextLine, "Press: (b) to delete a body, (j) to delete a joint"); TextLine += 15; DebugView.DrawString(50, TextLine, "Bodies removed: " + _removedBodies); TextLine += 15; DebugView.DrawString(50, TextLine, "Joints removed: " + _removedJoints); } protected override void JointRemoved(Joint joint) { for (int i = 0; i < 8; ++i) { if (_joints[i] == joint) { _joints[i] = null; break; } } base.JointRemoved(joint); } internal static Test Create() { return new WebTest(); } } }
// File: GenerationGuts.cs // Project: YAMLParser // // ROS.NET // Eric McCann <[email protected]> // UMass Lowell Robotics Laboratory // // Reimplementation of the ROS (ros.org) ros_cpp client in C#. // // Created: 04/28/2015 // Updated: 10/07/2015 #region USINGZ using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using YAMLParser; #endregion namespace FauxMessages { public class SrvsFile { private string GUTS; public string GeneratedDictHelper; public bool HasHeader; public string Name; public string Namespace = "Messages"; public MsgsFile Request, Response; public List<SingleType> Stuff = new List<SingleType>(); public string backhalf; public string classname; private List<string> def = new List<string>(); public string dimensions = ""; public string fronthalf; private string memoizedcontent; private bool meta; public string requestbackhalf; public string requestfronthalf; public string responsebackhalf; public string resposonebackhalf; public SrvsFile(MsgFileLocation filename) { //read in srv file string[] lines = File.ReadAllLines(filename.Path); classname = filename.basename; Namespace += "." + filename.package; Name = filename.package + "." + filename.basename; //def is the list of all lines in the file def = new List<string>(); int mid = 0; bool found = false; List<string> request = new List<string>(), response = new List<string>(); //Search through for the "---" separator between request and response for (; mid < lines.Length; mid++) { lines[mid] = lines[mid].Replace("\"", "\\\""); if (lines[mid].Contains('#')) { lines[mid] = lines[mid].Substring(0, lines[mid].IndexOf('#')); } lines[mid] = lines[mid].Trim(); if (lines[mid].Length == 0) { continue; } def.Add(lines[mid]); if (lines[mid].Contains("---")) { found = true; continue; } if (found) response.Add(lines[mid]); else request.Add(lines[mid]); } //treat request and response like 2 message files, each with a partial definition and extra stuff tagged on to the classname Request = new MsgsFile(new MsgFileLocation(filename.Path.Replace(".srv",".msg"), filename.searchroot), true, request, "\t"); Response = new MsgsFile(new MsgFileLocation(filename.Path.Replace(".srv", ".msg"), filename.searchroot), false, response, "\t"); } public void Write(string outdir) { string[] chunks = Name.Split('.'); for (int i = 0; i < chunks.Length - 1; i++) outdir += "\\" + chunks[i]; if (!Directory.Exists(outdir)) Directory.CreateDirectory(outdir); string localcn = classname; localcn = classname.Replace("Request", "").Replace("Response", ""); string contents = ToString(); if (contents != null) File.WriteAllText(outdir + "\\" + localcn + ".cs", contents.Replace("FauxMessages", "Messages")); } public override string ToString() { if (requestfronthalf == null) { requestfronthalf = ""; requestbackhalf = ""; string[] lines = Templates.SrvPlaceHolder.Split('\n'); int section = 0; for (int i = 0; i < lines.Length; i++) { //read until you find public class request... do everything once. //then, do it again response if (lines[i].Contains("$$REQUESTDOLLADOLLABILLS")) { section++; continue; } if (lines[i].Contains("namespace")) { requestfronthalf += "\nusing Messages.std_msgs;\nusing String=System.String;\nusing Messages.geometry_msgs;\nusing Messages.nav_msgs;\n\n"; //\nusing Messages.roscsharp; requestfronthalf += "namespace " + Namespace + "\n"; continue; } if (lines[i].Contains("$$RESPONSEDOLLADOLLABILLS")) { section++; continue; } switch (section) { case 0: requestfronthalf += lines[i] + "\n"; break; case 1: requestbackhalf += lines[i] + "\n"; break; case 2: responsebackhalf += lines[i] + "\n"; break; } } } GUTS = requestfronthalf + Request.GetSrvHalf() + requestbackhalf + Response.GetSrvHalf() + "\n" + responsebackhalf; /***********************************/ /* CODE BLOCK DUMP */ /***********************************/ #region definitions for (int i = 0; i < def.Count; i++) { while (def[i].Contains("\t")) def[i] = def[i].Replace("\t", " "); while (def[i].Contains("\n\n")) def[i] = def[i].Replace("\n\n", "\n"); def[i] = def[i].Replace('\t', ' '); while (def[i].Contains(" ")) def[i] = def[i].Replace(" ", " "); def[i] = def[i].Replace(" = ", "="); def[i] = def[i].Replace("\"", "\"\""); } StringBuilder md = new StringBuilder(); StringBuilder reqd = new StringBuilder(); StringBuilder resd = null; foreach (string s in def) { if (s == "---") { //only put this string in md, because the subclass defs don't contain it md.AppendLine(s); //we've hit the middle... move from the request to the response by making responsedefinition not null. resd = new StringBuilder(); continue; } //add every line to MessageDefinition for whole service md.AppendLine(s); //before we hit ---, add lines to request Definition. Otherwise, add them to response. if (resd == null) reqd.AppendLine(s); else resd.AppendLine(s); } string MessageDefinition = md.ToString().Trim(); string RequestDefinition = reqd.ToString().Trim(); string ResponseDefinition = resd.ToString().Trim(); #endregion #region THE SERVICE GUTS = GUTS.Replace("$WHATAMI", classname); GUTS = GUTS.Replace("$MYSRVTYPE", "SrvTypes." + Namespace.Replace("Messages.", "") + "__" + classname); GUTS = GUTS.Replace("$MYSERVICEDEFINITION", "@\"" + MessageDefinition + "\""); #endregion #region request string RequestDict = Request.GenFields(); meta = Request.meta; GUTS = GUTS.Replace("$REQUESTMYISMETA", meta.ToString().ToLower()); GUTS = GUTS.Replace("$REQUESTMYMSGTYPE", "MsgTypes." + Namespace.Replace("Messages.", "") + "__" + classname); GUTS = GUTS.Replace("$REQUESTMYMESSAGEDEFINITION", "@\"" + RequestDefinition + "\""); GUTS = GUTS.Replace("$REQUESTMYHASHEADER", Request.HasHeader.ToString().ToLower()); GUTS = GUTS.Replace("$REQUESTMYFIELDS", RequestDict.Length > 5 ? "{{" + RequestDict + "}}" : "()"); GUTS = GUTS.Replace("$REQUESTNULLCONSTBODY", ""); GUTS = GUTS.Replace("$REQUESTEXTRACONSTRUCTOR", ""); #endregion #region response string ResponseDict = Response.GenFields(); GUTS = GUTS.Replace("$RESPONSEMYISMETA", Response.meta.ToString().ToLower()); GUTS = GUTS.Replace("$RESPONSEMYMSGTYPE", "MsgTypes." + Namespace.Replace("Messages.", "") + "__" + classname); GUTS = GUTS.Replace("$RESPONSEMYMESSAGEDEFINITION", "@\"" + ResponseDefinition + "\""); GUTS = GUTS.Replace("$RESPONSEMYHASHEADER", Response.HasHeader.ToString().ToLower()); GUTS = GUTS.Replace("$RESPONSEMYFIELDS", ResponseDict.Length > 5 ? "{{" + ResponseDict + "}}" : "()"); GUTS = GUTS.Replace("$RESPONSENULLCONSTBODY", ""); GUTS = GUTS.Replace("$RESPONSEEXTRACONSTRUCTOR", ""); #endregion #region MD5 GUTS = GUTS.Replace("$REQUESTMYMD5SUM", MD5.Sum(Request)); GUTS = GUTS.Replace("$RESPONSEMYMD5SUM", MD5.Sum(Response)); string GeneratedReqDeserializationCode = "", GeneratedReqSerializationCode = "", GeneratedResDeserializationCode = "", GeneratedResSerializationCode = ""; //TODO: service support for (int i = 0; i < Request.Stuff.Count; i++) { GeneratedReqDeserializationCode += Request.GenerateDeserializationCode(Request.Stuff[i]); GeneratedReqSerializationCode += Request.GenerateSerializationCode(Request.Stuff[i]); } for (int i = 0; i < Response.Stuff.Count; i++) { GeneratedResDeserializationCode += Response.GenerateDeserializationCode(Response.Stuff[i]); GeneratedResSerializationCode += Response.GenerateSerializationCode(Response.Stuff[i]); } GUTS = GUTS.Replace("$REQUESTSERIALIZATIONCODE", GeneratedReqSerializationCode); GUTS = GUTS.Replace("$REQUESTDESERIALIZATIONCODE", GeneratedReqDeserializationCode); GUTS = GUTS.Replace("$RESPONSESERIALIZATIONCODE", GeneratedResSerializationCode); GUTS = GUTS.Replace("$RESPONSEDESERIALIZATIONCODE", GeneratedResDeserializationCode); string md5 = MD5.Sum(this); if (md5 == null) return null; GUTS = GUTS.Replace("$MYSRVMD5SUM", md5); #endregion /********END BLOCK**********/ return GUTS; } } public class MsgsFile { private const string stfmat = "\tname: {0}\n\t\ttype: {1}\n\t\ttrostype: {2}\n\t\tisliteral: {3}\n\t\tisconst: {4}\n\t\tconstvalue: {5}\n\t\tisarray: {6}\n\t\tlength: {7}\n\t\tismeta: {8}"; public class ResolvedMsg { public string OtherType; public MsgsFile Definer; } public static Dictionary<string, Dictionary<string, List<ResolvedMsg>>> resolver = new Dictionary<string, Dictionary<string, List<ResolvedMsg>>>(); private string GUTS; public string GeneratedDictHelper; public bool HasHeader; public string Name; public string Namespace = "Messages"; public List<SingleType> Stuff = new List<SingleType>(); public string backhalf; public string classname; private List<string> def = new List<string>(); public string Package; public string Definition { get { return !def.Any() ? "" : def.Aggregate((old, next) => "" + old + "\n" + next); } } public string dimensions = ""; public string fronthalf; private string memoizedcontent; public bool meta; public ServiceMessageType serviceMessageType = ServiceMessageType.Not; public MsgsFile(MsgFileLocation filename, bool isrequest, List<string> lines) : this(filename, isrequest, lines, "") { } //specifically for SRV halves public MsgsFile(MsgFileLocation filename, bool isrequest, List<string> lines, string extraindent) { if (resolver == null) resolver = new Dictionary<string, Dictionary<string, List<ResolvedMsg>>>(); serviceMessageType = isrequest ? ServiceMessageType.Request : ServiceMessageType.Response; //Parse The file name to get the classname; classname = filename.basename; //Parse for the Namespace Namespace += "." + filename.package; Name = filename.package + "." + classname; classname += (isrequest ? "Request" : "Response"); Namespace = Namespace.Trim('.'); Package = filename.package; if (!resolver.Keys.Contains(Package)) resolver.Add(Package, new Dictionary<string, List<ResolvedMsg>>()); if (!resolver[Package].ContainsKey(classname)) resolver[Package].Add(classname, new List<ResolvedMsg> { new ResolvedMsg { OtherType = Namespace + "." + classname, Definer = this } }); else resolver[Package][classname].Add(new ResolvedMsg { OtherType = Namespace + "." + classname, Definer = this }); def = new List<string>(); for (int i = 0; i < lines.Count; i++) { if (lines[i].Trim().Length == 0) { continue; } def.Add(lines[i]); SingleType test = KnownStuff.WhatItIs(this, lines[i], extraindent); if (test != null) Stuff.Add(test); } } public MsgsFile(MsgFileLocation filename) : this(filename, "") { } public MsgsFile(MsgFileLocation filename, string extraindent) { if (resolver == null) resolver = new Dictionary<string, Dictionary<string, List<ResolvedMsg>>>(); if (!filename.Path.Contains(".msg")) throw new Exception("" + filename + " IS NOT A VALID MSG FILE!"); classname = filename.basename; Package = filename.package; //Parse for the Namespace Namespace += "." + filename.package; Name = filename.package + "." + classname; Namespace = Namespace.Trim('.'); if (!resolver.Keys.Contains(Package)) resolver.Add(Package, new Dictionary<string, List<ResolvedMsg>>()); if (!resolver[Package].ContainsKey(classname)) resolver[Package].Add(classname, new List<ResolvedMsg> { new ResolvedMsg { OtherType = Namespace + "." + classname, Definer = this } }); else resolver[Package][classname].Add(new ResolvedMsg { OtherType = Namespace + "." + classname, Definer = this }); List<string> lines = new List<string>(File.ReadAllLines(filename.Path)); lines = lines.Where(st => (!st.Contains('#') || st.Split('#')[0].Length != 0)).ToList(); for (int i = 0; i < lines.Count; i++) lines[i] = lines[i].Split('#')[0].Trim(); //lines = lines.Where((st) => (st.Length > 0)).ToList(); lines.ForEach(s => { if (s.Contains('#') && s.Split('#')[0].Length != 0) s = s.Split('#')[0]; if (s.Contains('#')) s = ""; }); lines = lines.Where(st => (st.Length > 0)).ToList(); def = new List<string>(); for (int i = 0; i < lines.Count; i++) { def.Add(lines[i]); SingleType test = KnownStuff.WhatItIs(this, lines[i], extraindent); if (test != null) Stuff.Add(test); } } public void resolve(MsgsFile parent, SingleType st) { if (st.Type == null) { KnownStuff.WhatItIs(parent, st); } List<string> prefixes = new List<string>(new[] { "", "std_msgs", "geometry_msgs", "actionlib_msgs" }); if (st.Type.Contains("/")) { string[] pieces = st.Type.Split('/'); st.Package = pieces[0]; st.Type = pieces[1]; } if (!string.IsNullOrEmpty(st.Package)) prefixes[0] = st.Package; foreach (string p in prefixes) { if (resolver.Keys.Contains(p)) { if (resolver[p].ContainsKey(st.Type)) { if (resolver[p][st.Type].Count == 1) { st.Package = p; st.Definer = resolver[p][st.Type][0].Definer; } else if (resolver[p][st.Type].Count > 1) throw new Exception("Could not resolve " + st.Type); } } } } public string GetSrvHalf() { string wholename = classname.Replace("Request", ".Request").Replace("Response", ".Response"); classname = classname.Contains("Request") ? "Request" : "Response"; if (memoizedcontent == null) { memoizedcontent = ""; for (int i = 0; i < Stuff.Count; i++) { SingleType thisthing = Stuff[i]; if (thisthing.Type == "Header") { HasHeader = true; } /*else if (classname == "String") { thisthing.input = thisthing.input.Replace("String", "string"); thisthing.Type = thisthing.Type.Replace("String", "string"); thisthing.output = thisthing.output.Replace("String", "string"); }*/ else if (classname == "Time") { thisthing.input = thisthing.input.Replace("Time", "TimeData"); thisthing.Type = thisthing.Type.Replace("Time", "TimeData"); thisthing.output = thisthing.output.Replace("Time", "TimeData"); } else if (classname == "Duration") { thisthing.input = thisthing.input.Replace("Duration", "TimeData"); thisthing.Type = thisthing.Type.Replace("Duration", "TimeData"); thisthing.output = thisthing.output.Replace("Duration", "TimeData"); } meta |= thisthing.meta; memoizedcontent += "\t" + thisthing.output + "\n"; } /*if (classname.ToLower() == "string") { memoizedcontent += "\n\n\t\t\t\t\tpublic String(string s){ data = s; }\n\t\t\t\t\tpublic String(){ data = \"\"; }\n\n"; } else*/ if (classname == "Time") { memoizedcontent += "\n\n\t\t\t\t\tpublic Time(uint s, uint ns) : this(new TimeData{ sec=s, nsec = ns}){}\n\t\t\t\t\tpublic Time(TimeData s){ data = s; }\n\t\t\t\t\tpublic Time() : this(0,0){}\n\n"; } else if (classname == "Duration") { memoizedcontent += "\n\n\t\t\t\t\tpublic Duration(uint s, uint ns) : this(new TimeData{ sec=s, nsec = ns}){}\n\t\t\t\t\tpublic Duration(TimeData s){ data = s; }\n\t\t\t\t\tpublic Duration() : this(0,0){}\n\n"; } while (memoizedcontent.Contains("DataData")) memoizedcontent = memoizedcontent.Replace("DataData", "Data"); } string ns = Namespace.Replace("Messages.", ""); if (ns == "Messages") ns = ""; GeneratedDictHelper = ""; foreach (SingleType S in Stuff) { resolve(this, S); GeneratedDictHelper += MessageFieldHelper.Generate(S); } GUTS = fronthalf + memoizedcontent + "\n" + backhalf; return GUTS; } public string GenFields() { string ret = "\n\t\t\t\t"; for (int i = 0; i < Stuff.Count; i++) { Stuff[i].refinalize(this, Stuff[i].Type); ret += ((i > 0) ? "}, \n\t\t\t\t{" : "") + MessageFieldHelper.Generate(Stuff[i]); } return ret; } public override string ToString() { bool wasnull = false; if (fronthalf == null) { wasnull = true; fronthalf = ""; backhalf = ""; string[] lines = Templates.MsgPlaceHolder.Split('\n'); bool hitvariablehole = false; for (int i = 0; i < lines.Length; i++) { if (lines[i].Contains("$$DOLLADOLLABILLS")) { hitvariablehole = true; continue; } if (lines[i].Contains("namespace")) { fronthalf += "using Messages.std_msgs;\nusing String=System.String;\n\n" ; fronthalf += "namespace " + Namespace + "\n"; continue; } if (!hitvariablehole) fronthalf += lines[i] + "\n"; else backhalf += lines[i] + "\n"; } } string GeneratedDeserializationCode = "", GeneratedSerializationCode = ""; if (memoizedcontent == null) { memoizedcontent = ""; for (int i = 0; i < Stuff.Count; i++) { SingleType thisthing = Stuff[i]; if (thisthing.Type == "Header") { HasHeader = true; } else if (classname == "Time") { thisthing.input = thisthing.input.Replace("Time", "TimeData"); thisthing.Type = thisthing.Type.Replace("Time", "TimeData"); thisthing.output = thisthing.output.Replace("Time", "TimeData"); } else if (classname == "Duration") { thisthing.input = thisthing.input.Replace("Duration", "TimeData"); thisthing.Type = thisthing.Type.Replace("Duration", "TimeData"); thisthing.output = thisthing.output.Replace("Duration", "TimeData"); } thisthing.input = thisthing.input.Replace("String", "string"); thisthing.Type = thisthing.Type.Replace("String", "string"); thisthing.output = thisthing.output.Replace("String", "string"); meta |= thisthing.meta; memoizedcontent += "\t" + thisthing.output + "\n"; } string ns = Namespace.Replace("Messages.", ""); if (ns == "Messages") ns = ""; while (memoizedcontent.Contains("DataData")) memoizedcontent = memoizedcontent.Replace("DataData", "Data"); //if (GeneratedDictHelper == null) // GeneratedDictHelper = TypeInfo.Generate(classname, ns, HasHeader, meta, def, Stuff); GeneratedDictHelper = GenFields(); bool literal = false; StringBuilder DEF = new StringBuilder(); foreach (string s in def) DEF.AppendLine(s); Debug.WriteLine("============\n" + this.classname); } GUTS = (serviceMessageType != ServiceMessageType.Response ? fronthalf : "") + "\n" + memoizedcontent + "\n" + (serviceMessageType != ServiceMessageType.Request ? backhalf : ""); if (classname.ToLower() == "string") { GUTS = GUTS.Replace("$NULLCONSTBODY", "if (data == null)\n\t\t\tdata = \"\";\n"); GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", "\n\t\tpublic $WHATAMI(string d) : base($MYMSGTYPE, $MYMESSAGEDEFINITION, $MYHASHEADER, $MYISMETA, new Dictionary<string, MsgFieldInfo>$MYFIELDS)\n\t\t{\n\t\t\tdata = d;\n\t\t}\n"); } else if (classname == "Time" || classname == "Duration") { GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", "\n\t\tpublic $WHATAMI(TimeData d) : base($MYMSGTYPE, $MYMESSAGEDEFINITION, $MYHASHEADER, $MYISMETA, new Dictionary<string, MsgFieldInfo>$MYFIELDS)\n\t\t{\n\t\t\tdata = d;\n\t\t}\n"); } GUTS = GUTS.Replace("$WHATAMI", classname); GUTS = GUTS.Replace("$MYISMETA", meta.ToString().ToLower()); GUTS = GUTS.Replace("$MYMSGTYPE", "MsgTypes." + Namespace.Replace("Messages.", "") + "__" + classname); for (int i = 0; i < def.Count; i++) { while (def[i].Contains("\t")) def[i] = def[i].Replace("\t", " "); while (def[i].Contains("\n\n")) def[i] = def[i].Replace("\n\n", "\n"); def[i] = def[i].Replace('\t', ' '); while (def[i].Contains(" ")) def[i] = def[i].Replace(" ", " "); def[i] = def[i].Replace(" = ", "="); } GUTS = GUTS.Replace("$MYMESSAGEDEFINITION", "@\"" + def.Aggregate("", (current, d) => current + (d + "\n")).Trim('\n') + "\""); GUTS = GUTS.Replace("$MYHASHEADER", HasHeader.ToString().ToLower()); GUTS = GUTS.Replace("$MYFIELDS", GeneratedDictHelper.Length > 5 ? "{{" + GeneratedDictHelper + "}}" : "()"); GUTS = GUTS.Replace("$NULLCONSTBODY", ""); GUTS = GUTS.Replace("$EXTRACONSTRUCTOR", ""); string md5 = MD5.Sum(this); if (md5 == null) return null; for (int i = 0; i < Stuff.Count; i++) { GeneratedDeserializationCode += this.GenerateDeserializationCode(Stuff[i]); GeneratedSerializationCode += this.GenerateSerializationCode(Stuff[i]); } GUTS = GUTS.Replace("$SERIALIZATIONCODE", GeneratedSerializationCode); GUTS = GUTS.Replace("$DESERIALIZATIONCODE", GeneratedDeserializationCode); GUTS = GUTS.Replace("$MYMD5SUM", md5); return GUTS; } private string GenerateSerializationForOne(string type, string name, SingleType st) { if (type == "Time" || type == "Duration") { return string.Format(@"pieces.Add(BitConverter.GetBytes({0}.data.sec)); pieces.Add(BitConverter.GetBytes({0}.data.nsec));", name); } else if (type == "TimeData") return string.Format(@"pieces.Add(BitConverter.GetBytes({0}.sec)); pieces.Add(BitConverter.GetBytes({0}.nsec));", name); else if (type == "byte") { return string.Format("pieces.Add(new[] {{ (byte){0} }});", name); ; } else if (type == "string") { return string.Format(@" if ({0} == null) {0} = """"; scratch1 = Encoding.ASCII.GetBytes((string){0}); thischunk = new byte[scratch1.Length + 4]; scratch2 = BitConverter.GetBytes(scratch1.Length); Array.Copy(scratch1, 0, thischunk, 4, scratch1.Length); Array.Copy(scratch2, thischunk, 4); pieces.Add(thischunk);", name); } else if (type == "bool") { return string.Format(@" thischunk = new byte[1]; thischunk[0] = (byte) ((bool){0} ? 1 : 0 ); pieces.Add(thischunk);", name); } else if (st.IsLiteral) { string ret = string.Format(@" scratch1 = new byte[Marshal.SizeOf(typeof({1}))]; h = GCHandle.Alloc(scratch1, GCHandleType.Pinned); Marshal.StructureToPtr({0}, h.AddrOfPinnedObject(), false); h.Free(); pieces.Add(scratch1);", name, type); return ret; } else { return string.Format("pieces.Add({0}.Serialize(true));", name); } } public string GenerateSerializationCode(SingleType st) { System.Diagnostics.Debug.WriteLine(string.Format(stfmat, st.Name, st.Type, st.rostype, st.IsLiteral, st.Const, st.ConstValue, st.IsArray, st.length, st.meta)); if (st.Const) return ""; if (!st.IsArray) { return GenerateSerializationForOne(st.Type, st.Name, st); } int arraylength = -1; //TODO: if orientation_covariance does not send successfully, skip prepending length when array length is coded in .msg string ret = string.Format(@"hasmetacomponents |= {0};" + @" ", st.meta.ToString().ToLower()); if (string.IsNullOrEmpty(st.length) || !int.TryParse(st.length, out arraylength) || arraylength == -1) ret += "pieces.Add( BitConverter.GetBytes(" + st.Name + ".Length));" + @" "; ret += string.Format(@"for (int i=0;i<{0}.Length; i++) {{ {1} }}" + @" ", st.Name, GenerateSerializationForOne(st.Type, st.Name + "[i]", st)); return ret; } public string GenerateDeserializationCode(SingleType st) { // this happens for each member of the outer message // after concluding, make sure part of the string is "currentIndex += <amount read while deserializing this thing>" // start of deserializing piece referred to by st is currentIndex (its value at time of call to this fn)" System.Diagnostics.Debug.WriteLine(string.Format(stfmat, st.Name, st.Type, st.rostype, st.IsLiteral, st.Const, st.ConstValue, st.IsArray, st.length, st.meta)); if (st.Const) { return ""; } else if (!st.IsArray) { return GenerateDeserializationForOne(st.Type, st.Name, st); } int arraylength = -1; //If the object is an array, send each object to be processed individually, then add them to the string string ret = string.Format(@"hasmetacomponents |= {0};" + @" ", st.meta.ToString().ToLower()); if (string.IsNullOrEmpty(st.length) || !int.TryParse(st.length, out arraylength) || arraylength == -1) { ret += string.Format(@" arraylength = BitConverter.ToInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += Marshal.SizeOf(typeof(System.Int32)); {0} = new {1}[arraylength]; ", st.Name, st.Type); } else { ret += string.Format(@" {0} = new {1}[{2}]; ", st.Name, st.Type, arraylength); } ret += string.Format(@"for (int i=0;i<{0}.Length; i++) {{ {1} }}" + @" ", st.Name, GenerateDeserializationForOne(st.Type, st.Name + "[i]", st)); return ret; } private string GenerateDeserializationForOne(string type, string name, SingleType st) { if (type == "Time" || type == "Duration") { return string.Format(@" {0} = new {1}(new TimeData( BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex), BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex+Marshal.SizeOf(typeof(System.Int32))))); currentIndex += 2*Marshal.SizeOf(typeof(System.Int32));", name, st.Type); } else if (type == "TimeData") return string.Format(@" {0}.sec = BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += Marshal.SizeOf(typeof(System.Int32)); {0}.nsec = BitConverter.ToUInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += Marshal.SizeOf(typeof(System.Int32));", name); else if (type == "byte") { return string.Format("{0}=SERIALIZEDSTUFF[currentIndex++];", name); ; } else if (type == "string") { return string.Format(@" {0} = """"; piecesize = BitConverter.ToInt32(SERIALIZEDSTUFF, currentIndex); currentIndex += 4; {0} = Encoding.ASCII.GetString(SERIALIZEDSTUFF, currentIndex, piecesize); currentIndex += piecesize;", name); } else if (type == "bool") { return string.Format(@" {0} = SERIALIZEDSTUFF[currentIndex++]==1; ", name); } else if (st.IsLiteral) { string ret = string.Format(@" piecesize = Marshal.SizeOf(typeof({0})); h = IntPtr.Zero; if (SERIALIZEDSTUFF.Length - currentIndex != 0) {{ h = Marshal.AllocHGlobal(piecesize); Marshal.Copy(SERIALIZEDSTUFF, currentIndex, h, piecesize); }} if (h == IntPtr.Zero) throw new Exception(""Alloc failed""); {1} = ({0})Marshal.PtrToStructure(h, typeof({0})); Marshal.FreeHGlobal(h); currentIndex+= piecesize; ", st.Type, name); return ret; } else { return string.Format("{0} = new {1}(SERIALIZEDSTUFF, ref currentIndex);", name, st.Type); } } public void Write(string outdir) { string[] chunks = Name.Split('.'); for (int i = 0; i < chunks.Length - 1; i++) outdir += "\\" + chunks[i]; if (!Directory.Exists(outdir)) Directory.CreateDirectory(outdir); string localcn = classname; if (serviceMessageType != ServiceMessageType.Not) localcn = classname.Replace("Request", "").Replace("Response", ""); string contents = ToString(); if (contents == null) return; if (serviceMessageType == ServiceMessageType.Response) File.AppendAllText(outdir + "\\" + localcn + ".cs", contents.Replace("FauxMessages", "Messages")); else File.WriteAllText(outdir + "\\" + localcn + ".cs", contents.Replace("FauxMessages", "Messages")); } } public class SerializationTest { private Random r = new Random(); public SerializationTest() { } public static string dumphex(byte[] test) { if (test == null) return "dumphex(null)"; StringBuilder sb = new StringBuilder().Append(Array.ConvertAll<byte, string>(test, (t) => string.Format("{0,3:X2}", t)).Aggregate("", (current, t) => current + t)); return sb.ToString(); } private void RandomizeObject(Type T) { if(!T.IsArray) { if(T != typeof(TimeData) && T.Namespace.Contains("Message")) { object msg = Activator.CreateInstance(T); if (msg == null) throw new Exception("Error during object creation"); FieldInfo[] infos = GetFields(T, ref msg); foreach (FieldInfo info in infos) { //Randomize the field } } } } private void RandomizeField(Type T, ref object target, int hardcodedarraylength=-1) { if (!T.IsArray) { if (T != typeof(TimeData) && T.Namespace.Contains("Message")) { //Create a new object of the same type as target? object msg = Activator.CreateInstance(T); FieldInfo[] infos = GetFields(T, ref target); if (msg == null) { GetFields(T, ref target); throw new Exception("SOMETHING AIN'T RIGHT"); } foreach (FieldInfo info in infos) { if (info.Name.Contains("(")) continue; if (msg.GetType().GetField(info.Name).IsLiteral) continue; if (info.GetValue(target) == null) { if (info.FieldType == typeof(string)) info.SetValue(target, ""); else if (info.FieldType.IsArray) info.SetValue(target, Array.CreateInstance(info.FieldType.GetElementType(), 0)); else if (info.FieldType.FullName != null && !info.FieldType.FullName.Contains("Messages.")) info.SetValue(target, 0); else info.SetValue(target, Activator.CreateInstance(info.FieldType)); } object field = info.GetValue(target); //Randomize(info.FieldType, ref field, -1); info.SetValue(target, field); } } else if (target is byte || T == typeof(byte)) { target = (byte)r.Next(255); } else if (target is string || T == typeof(string)) { //create a string of random length [1,100], composed of random chars int length = r.Next(100) + 1; byte[] buf = new byte[length]; r.NextBytes(buf); //fill the whole buffer with random bytes for (int i = 0; i < length; i++) if (buf[i] == 0) //replace null chars with non-null random ones buf[i] = (byte)(r.Next(254) + 1); buf[length - 1] = 0; //null terminate target = Encoding.ASCII.GetString(buf); } else if (target is bool || T == typeof(bool)) { target = r.Next(2) == 1; } else if (target is int || T == typeof(int)) { target = r.Next(); } else if (target is uint || T == typeof(int)) { target = (uint)r.Next(); } else if (target is double || T == typeof(double)) { target = r.NextDouble(); } else if (target is TimeData || T == typeof(TimeData)) { target = new TimeData((uint)r.Next(), (uint)r.Next()); } else if (target is float || T == typeof(float)) { target = (float)r.NextDouble(); } else if (target is Int16 || T == typeof(Int16)) { target = (Int16)r.Next(Int16.MaxValue + 1); } else if (target is UInt16 || T == typeof(UInt16)) { target = (UInt16)r.Next(UInt16.MaxValue + 1); } else if (target is SByte || T == typeof(SByte)) { target = (SByte)(r.Next(255) - 127); } else if (target is UInt64 || T == typeof(UInt64)) { target = (UInt64)((uint)(r.Next() << 32)) | (uint)r.Next(); } else if (target is Int64 || T == typeof(Int64)) { target = (Int64)(r.Next() << 32) | r.Next(); } else if (target is char || T == typeof(char)) { target = (char)(byte)(r.Next(254) + 1); } else { throw new Exception("Unhandled randomization: " + T); } } else { int length = hardcodedarraylength != -1 ? hardcodedarraylength : r.Next(10); Type elem = T.GetElementType(); Array field = Array.CreateInstance(elem, new int[] { length }, new int[] { 0 }); for (int i = 0; i < length; i++) { object val = field.GetValue(i); RandomizeField(elem, ref val); field.SetValue(val, i); } target = field; } } private static Dictionary<Type, FieldInfo[]> speedyFields = new Dictionary<Type, FieldInfo[]>(); public static FieldInfo[] GetFields(Type T, ref object instance) { if (T.IsArray) throw new Exception("Called GetFields for an array type. Bad form!"); if (instance == null) { if (T.IsArray) //This will never run! { T = T.GetElementType(); instance = Array.CreateInstance(T, 0); } else if (T != typeof(string)) instance = Activator.CreateInstance(T); else instance = (object)""; } object MSG = instance; if (instance != null && MSG == null) throw new Exception("Garbage"); lock (speedyFields) { if (speedyFields.ContainsKey(T)) return speedyFields[T]; if (MSG == null || instance.GetType().ToString() == MsgTypes.Unknown.ToString()) { return (speedyFields[T] = instance.GetType().GetFields()); } else if (MSG != null) { return null;// (speedyFields[T] = MSG.GetType().GetFields().Where((fi => MSG.Fields.Keys.Contains(fi.Name) && !fi.IsStatic)).ToArray()); } } throw new Exception("GetFields is weaksauce"); } } public static class KnownStuff { private static char[] spliter = {' '}; public static Dictionary<string, string> KnownTypes = new Dictionary<string, string> { {"float64", "double"}, {"float32", "Single"}, {"uint64", "ulong"}, {"uint32", "uint"}, {"uint16", "ushort"}, {"uint8", "byte"}, {"int64", "long"}, {"int32", "int"}, {"int16", "short"}, {"int8", "sbyte"}, {"byte", "byte"}, {"bool", "bool"}, {"char", "char"}, {"time", "Time"}, {"string", "string"}, {"duration", "Duration"} }; public static string GetConstTypesAffix(string type) { switch (type.ToLower()) { case "decimal": return "m"; break; case "single": case "float": return "f"; break; case "long": return "l"; break; case "ulong": return "ul"; break; case "uint": return "u"; break; default: return ""; } } public static SingleType WhatItIs(MsgsFile parent, string s, string extraindent) { string[] pieces = s.Split('/'); string package = parent.Package; if (pieces.Length == 2) { package = pieces[0]; s = pieces[1]; } SingleType st = new SingleType(package, s, extraindent); parent.resolve(parent, st); WhatItIs(parent, st); return st; } public static void WhatItIs(MsgsFile parent, SingleType t) { foreach (KeyValuePair<string, string> test in KnownTypes) { if (t.Test(test)) { t.rostype = t.Type; SingleType.Finalize(parent, t, test); return; } } t.Finalize(parent, t.input.Split(spliter, StringSplitOptions.RemoveEmptyEntries), false); } } public class SingleType { public bool Const; public string ConstValue = ""; public bool IsArray; public bool IsLiteral; public string Name; public string Package; public string Type; private string[] backup; public string input; public string length = ""; public string lowestindent = "\t\t"; public bool meta; public string output; public string rostype = ""; public MsgsFile Definer; public SingleType(string s) : this("", s, "") { } public SingleType(string package, string s, string extraindent) { Package = package; lowestindent += extraindent; if (s.Contains('[') && s.Contains(']')) { string front = ""; string back = ""; string[] parts = s.Split('['); front = parts[0]; parts = parts[1].Split(']'); length = parts[0]; back = parts[1]; IsArray = true; s = front + back; } input = s; } public bool Test(KeyValuePair<string, string> candidate) { return (input.Split(' ')[0].ToLower().Equals(candidate.Key)); } public static void Finalize(MsgsFile parent, SingleType thing, KeyValuePair<string, string> csharptype) { string[] PARTS = thing.input.Split(' '); thing.rostype = PARTS[0]; if (!KnownStuff.KnownTypes.ContainsKey(thing.rostype)) thing.meta = true; PARTS[0] = csharptype.Value; thing.Finalize(parent, PARTS, true); } public void Finalize(MsgsFile parent, string[] s, bool isliteral) { backup = new string[s.Length]; Array.Copy(s, backup, s.Length); bool isconst = false; IsLiteral = isliteral; string type = s[0]; string name = s[1]; string otherstuff = ""; if (name.Contains('=')) { string[] parts = name.Split('='); isconst = true; name = parts[0]; otherstuff = " = " + parts[1]; } for (int i = 2; i < s.Length; i++) otherstuff += " " + s[i]; if (otherstuff.Contains('=')) isconst = true; if (!IsArray) { if (otherstuff.Contains('=') && type.Equals("string", StringComparison.CurrentCultureIgnoreCase)) { otherstuff = otherstuff.Replace("\\", "\\\\"); otherstuff = otherstuff.Replace("\"", "\\\""); string[] split = otherstuff.Split('='); otherstuff = split[0] + " = " + split[1].Trim() + ""; } if (otherstuff.Contains('=') && type == "bool") { otherstuff = otherstuff.Replace("0", "false").Replace("1", "true"); } if (otherstuff.Contains('=') && type == "byte") { otherstuff = otherstuff.Replace("-1", "255"); } Const = isconst; bool wantsconstructor = false; if (otherstuff.Contains("=")) { string[] chunks = otherstuff.Split('='); ConstValue = chunks[chunks.Length - 1].Trim(); if (type.Equals("string", StringComparison.InvariantCultureIgnoreCase)) { otherstuff = chunks[0] + " = \"" + chunks[1].Trim() + "\""; } } string prefix = "", suffix = ""; if (isconst) { if (!type.Equals("string", StringComparison.InvariantCultureIgnoreCase)) { prefix = "const "; } } if (otherstuff.Contains('=')) if (wantsconstructor) if (type == "string") suffix = " = \"\""; else suffix = " = new " + type + "()"; else suffix = KnownStuff.GetConstTypesAffix(type); string t = type; if (!KnownStuff.KnownTypes.ContainsKey(rostype) && !"using Messages.std_msgs;\nusing String=System.String;\nusing Messages.geometry_msgs;\nusing Messages.nav_msgs;".Contains("Messages."+Package)) t = "Messages." + Package + "." + t; output = lowestindent + "public " + prefix + t + " " + name + otherstuff + suffix + ";"; } else { if (length.Length > 0) IsLiteral = true; if (otherstuff.Contains('=')) { string[] split = otherstuff.Split('='); otherstuff = split[0] + " = (" + type + ")" + split[1]; } string t = type; if (!KnownStuff.KnownTypes.ContainsKey(rostype) && !"using Messages.std_msgs;\nusing String=System.String;\nusing Messages.geometry_msgs;\nusing Messages.nav_msgs;".Contains("Messages." + Package)) t = "Messages." + Package + "." + t; if (length.Length > 0) output = lowestindent + "public " + t + "[] " + name + otherstuff + " = new " + type + "[" + length + "];"; else output = lowestindent + "public " + "" + t + "[] " + name + otherstuff + ";"; } Type = type; parent.resolve(parent, this); if (!KnownStuff.KnownTypes.ContainsKey(rostype)) { meta = true; } Name = name.Length == 0 ? otherstuff.Trim() : name; if (Name.Contains('=')) { Name = Name.Substring(0, Name.IndexOf("=")).Trim(); } } public void refinalize(MsgsFile parent, string REALTYPE) { bool isconst = false; Type = REALTYPE; string name = backup[1]; string otherstuff = ""; if (name.Contains('=')) { string[] parts = name.Split('='); isconst = true; name = parts[0]; otherstuff = " = " + parts[1]; } for (int i = 2; i < backup.Length; i++) otherstuff += " " + backup[i]; if (otherstuff.Contains('=')) isconst = true; parent.resolve(parent, this); if (!IsArray) { if (otherstuff.Contains('=') && Type.Equals("string", StringComparison.CurrentCultureIgnoreCase)) { otherstuff = otherstuff.Replace("\\", "\\\\"); otherstuff = otherstuff.Replace("\"", "\\\""); string[] split = otherstuff.Split('='); otherstuff = split[0] + " = \"" + split[1].Trim() + "\""; } if (otherstuff.Contains('=') && Type == "bool") { otherstuff = otherstuff.Replace("0", "false").Replace("1", "true"); } if (otherstuff.Contains('=') && Type == "byte") { otherstuff = otherstuff.Replace("-1", "255"); } Const = isconst; bool wantsconstructor = false; if (otherstuff.Contains("=")) { string[] chunks = otherstuff.Split('='); ConstValue = chunks[chunks.Length - 1].Trim(); if (Type.Equals("string", StringComparison.InvariantCultureIgnoreCase)) { otherstuff = chunks[0] + " = \"" + chunks[1].Trim().Replace("\"", "") + "\""; } } else if (!Type.Equals("String")) { wantsconstructor = true; } string prefix = "", suffix = ""; if (isconst) { if (!Type.Equals("string", StringComparison.InvariantCultureIgnoreCase)) { prefix = "const "; } } if (otherstuff.Contains('=')) if (wantsconstructor) if (Type == "string") suffix = " = \"\""; else suffix = " = new " + Type + "()"; else suffix = KnownStuff.GetConstTypesAffix(Type); string t = Type; if (!KnownStuff.KnownTypes.ContainsKey(rostype) && !"using Messages.std_msgs;\nusing String=System.String;\nusing Messages.geometry_msgs;\nusing Messages.nav_msgs;".Contains("Messages." + Package)) t = "Messages." + Package + "." + t; output = lowestindent + "public " + prefix + t + " " + name + otherstuff + suffix + ";"; } else { if (length.Length != 0) IsLiteral = true; //type != "string"; if (otherstuff.Contains('=')) { string[] split = otherstuff.Split('='); otherstuff = split[0] + " = (" + Type + ")" + split[1]; } string t = Type; if (!KnownStuff.KnownTypes.ContainsKey(rostype) && !"using Messages.std_msgs;\nusing String=System.String;\nusing Messages.geometry_msgs;\nusing Messages.nav_msgs;".Contains("Messages." + Package)) t = "Messages." + Package + "." + t; if (length.Length != 0) output = lowestindent + "public " + t + "[] " + name + otherstuff + " = new " + Type + "[" + length + "];"; else output = lowestindent + "public " + "" + t + "[] " + name + otherstuff + ";"; } if (!KnownStuff.KnownTypes.ContainsKey(rostype)) meta = true; Name = name.Length == 0 ? otherstuff.Split('=')[0].Trim() : name; } } public static class MessageFieldHelper { public static string Generate(SingleType members) { string mt = "MsgTypes.Unknown"; string pt = members.Type; if (members.meta) { string t = members.Type.Replace("Messages.", ""); if (!t.Contains('.')) t = members.Definer.Package + "." + t; mt = "MsgTypes." + t.Replace(".", "__"); } if (!KnownStuff.KnownTypes.ContainsKey(members.rostype) && !"using Messages.std_msgs;\nusing String=System.String;\nusing Messages.geometry_msgs;\nusing Messages.nav_msgs;".Contains("Messages." + members.Package)) { pt = "Messages." + members.Package + "." + pt; } return String.Format ("\"{0}\", new MsgFieldInfo(\"{0}\", {1}, {2}, {3}, \"{4}\", {5}, \"{6}\", {7}, {8})", members.Name, members.IsLiteral.ToString().ToLower(), ("typeof(" + pt + ")"), members.Const.ToString().ToLower(), members.ConstValue.TrimStart('"').TrimEnd('"'), //members.Type.Equals("string", StringComparison.InvariantCultureIgnoreCase) ? ("new String("+members.ConstValue+")") : ("\""+members.ConstValue+"\""), members.IsArray.ToString().ToLower(), members.length, //FIX MEEEEEEEE members.meta.ToString().ToLower(), mt); } public static KeyValuePair<string, MsgFieldInfo> Instantiate(SingleType member) { string mt = "MsgTypes.Unknown"; if (member.meta) { string t = member.Type.Replace("Messages.", ""); if (!t.Contains('.')) t = "std_msgs." + t; mt = "MsgType." + t.Replace(".", "__"); } return new KeyValuePair<string, MsgFieldInfo>(member.Name, new MsgFieldInfo(member.Name, member.IsLiteral, member.Type, member.Const, member.ConstValue, member.IsArray, member.length, member.meta)); } public static Dictionary<string, MsgFieldInfo> Instantiate(IEnumerable<SingleType> stuff) { return stuff.Select(Instantiate).ToDictionary(field => field.Key, field => field.Value); } } public class MsgFieldInfo { public string ConstVal; public bool IsArray; public bool IsConst; public bool IsLiteral; public bool IsMetaType; public int Length = -1; public string Name; public string Type; #if !TRACE [DebuggerStepThrough] #endif public MsgFieldInfo(string name, bool isliteral, string type, bool isconst, string constval, bool isarray, string lengths, bool meta) { Name = name; IsArray = isarray; Type = type; IsLiteral = isliteral; IsMetaType = meta; IsConst = isconst; ConstVal = constval; if (lengths == null) return; if (lengths.Length > 0) { Length = int.Parse(lengths); } } } public enum ServiceMessageType { Not, Request, Response } public struct TimeData { public uint sec; public uint nsec; public TimeData(uint s, uint ns) { sec = s; nsec = ns; } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.Collections; using System.IO; namespace vectrast { class VectRast { ArrayList polygons; ArrayList objects; bool printProgressOn; bool printWarningsOn; public bool someWarning; int xmin; int xmax; int ymin; int ymax; public VectRast(bool printProgressOn, bool printWarningsOn) { this.printProgressOn = printProgressOn; this.printWarningsOn = printWarningsOn; someWarning = false; polygons = new ArrayList(); objects = new ArrayList(); } protected SortedList createVectors(byte[,] pixelOn, Bitmap bmp) { SortedList vectors = new SortedList(bmp.Width * bmp.Height / 32); Hashtable vectorsReverse = new Hashtable(bmp.Width * bmp.Height / 32); int steps = 0; for (int j = 0; j < bmp.Height + 1; j++) for (int i = 0; i < bmp.Width + 1; i++) { printProgress(ref steps, 400000); int type = (pixelOn[i, j] & 1) + ((pixelOn[i + 1, j] & 1) << 1) + ((pixelOn[i, j + 1] & 1) << 2) + ((pixelOn[i + 1, j + 1] & 1) << 3); if (type == 1 + 8 || type == 2 + 4) { // get rid of illegal situations pixelOn[i, j] |= 1; pixelOn[i + 1, j] |= 1; pixelOn[i, j + 1] |= 1; pixelOn[i + 1, j + 1] |= 1; printWarning("\nillegal pixel configuration at [" + i + ", " + j + "]"); } } for (int j = 0; j < bmp.Height; j++) for (int i = 0; i < bmp.Width; i++) { printProgress(ref steps, 800000); if ((pixelOn[i + 1, j + 1] & 1) == 1) { int type1 = (pixelOn[i + 1, j] & 1) + (pixelOn[i + 1, j + 2] & 1); int type2 = (pixelOn[i, j + 1] & 1) + (pixelOn[i + 2, j + 1] & 1); if (type1 == 2 && type2 == 0 || type1 == 0 && type2 == 2 ) { // get rid of illegal situations pixelOn[i + 2, j + 1] |= 1; pixelOn[i + 1, j + 2] |= 1; printWarning("\nillegal pixel configuration at [" + i + ", " + j + "]"); } } } for (int j = -1; j < bmp.Height; j++) for (int i = -1; i < bmp.Width; i++) { printProgress(ref steps, 400000); int type = (pixelOn[i + 1, j + 1] & 1) + ((pixelOn[i + 2, j + 1] & 1) << 1) + ((pixelOn[i + 1, j + 2] & 1) << 2) + ((pixelOn[i + 2, j + 2] & 1) << 3); IntVector2 fromPnt = new IntVector2(); IntVector2 toPnt = new IntVector2(); switch (type) { // create horizontal and vertical vectors between adjacent pixels case 3: // xx // -- fromPnt = new IntVector2(i, j); toPnt = new IntVector2(i + 1, j); break; case 12: // -- // xx fromPnt = new IntVector2(i + 1, j + 1); toPnt = new IntVector2(i, j + 1); break; case 5: // x- // x- fromPnt = new IntVector2(i, j + 1); toPnt = new IntVector2(i, j); break; case 10: // -x // -x fromPnt = new IntVector2(i + 1, j); toPnt = new IntVector2(i + 1, j + 1); break; case 14: // -x // xx fromPnt = new IntVector2(i + 1, j); toPnt = new IntVector2(i, j + 1); break; case 13: // x- // xx fromPnt = new IntVector2(i + 1, j + 1); toPnt = new IntVector2(i, j); break; case 11: // xx // -x fromPnt = new IntVector2(i, j); toPnt = new IntVector2(i + 1, j + 1); break; case 7: // xx // x- fromPnt = new IntVector2(i, j + 1); toPnt = new IntVector2(i + 1, j); break; } if (fromPnt.defined) { if (vectorsReverse.Contains(fromPnt)) { VectorPixel oldVP = (VectorPixel)vectorsReverse[fromPnt]; if ((toPnt - fromPnt).extension(oldVP.toPnt - oldVP.fromPnt)) { vectors.Remove(oldVP.fromPnt); vectorsReverse.Remove(oldVP.toPnt); fromPnt = oldVP.fromPnt; } } if (vectors.Contains(toPnt)) { VectorPixel oldVP = (VectorPixel)vectors[toPnt]; if ((toPnt - fromPnt).extension(oldVP.toPnt - oldVP.fromPnt)) { vectors.Remove(oldVP.fromPnt); vectorsReverse.Remove(oldVP.toPnt); toPnt = oldVP.toPnt; } } if (!fromPnt.Equals(toPnt)) { // do not add null vectors, they ugly :/ VectorPixel newVP = new VectorPixel(fromPnt, toPnt); if (vectors.Contains(newVP.fromPnt)) throw new Exception("illegal edge configuration at pixel [" + newVP.fromPnt.x + ", " + newVP.fromPnt.y + "]"); else vectors.Add(newVP.fromPnt, newVP); if (vectorsReverse.Contains(newVP.toPnt)) throw new Exception("illegal edge configuration at pixel [" + newVP.toPnt.x + ", " + newVP.toPnt.y + "]"); else vectorsReverse.Add(newVP.toPnt, newVP); } } } return vectors; } protected void collapseVectors(SortedList vectors) { ArrayList vertices; int steps = 0; while (vectors.Count > 0) { VectorPixel vectorOld = (VectorPixel)vectors.GetByIndex(0); // ensures we begin at start/end of some line (as opposed to an inner segment) IntVector2 startPnt = vectorOld.fromPnt; VectorPixel vectorNow; VectorPixel vectorNew; VectorPixel vectorPrev = null; Line line = new Line(vectorOld); vertices = new ArrayList(1000); do { printProgress(ref steps, 2000); vectorNow = (VectorPixel)vectors[vectorOld.toPnt]; vectorNew = (VectorPixel)vectors[vectorNow.toPnt]; if (!vectorNow.fromPnt.Equals(startPnt) && !vectorNow.toPnt.Equals(startPnt) && vectorNow.linkVector() && line.sameDir(vectorNow) && !vectorNew.linkVector() && line.sameDir(vectorNew) ) { if (line.satisfiesInner(vectorNew)) { // new segment ok, let's try the next one line.update(vectorNew); vectors.Remove(vectorNow.fromPnt); vectorOld = vectorNew; } else if (line.satisfiesOuter(vectorNew)) { // vectorNow can be an outer segment line.update(vectorNew); vertices.Add(new DoubleVector2(line.toPnt)); vectors.Remove(vectorNew.fromPnt); vectors.Remove(vectorNow.fromPnt); vectorOld = (VectorPixel)vectors[vectorNew.toPnt]; line = new Line(vectorOld); } else { // new segment off, but link is ok as an outer segment line.update(vectorNow); vertices.Add(new DoubleVector2(line.toPnt)); vectors.Remove(vectorNow.fromPnt); vectorOld = vectorNew; line = new Line(vectorOld); } } else if (!vectorNow.fromPnt.Equals(startPnt) && line.sameDir(vectorNow)) { // vectorNow is not a simple link between two segments if (line.satisfiesInner(vectorNow)) { // new segment ok, let's try the next one line.update(vectorNow); vectorOld = vectorNow; } else if (line.satisfiesOuter(vectorNow)) { // vectorNow can be an outer segment line.update(vectorNow); vertices.Add(new DoubleVector2(line.toPnt)); vectors.Remove(vectorNow.fromPnt); vectorOld = vectorNew; line = new Line(vectorOld); } else { // vectorNow just won't fit - process it separately vertices.Add(new DoubleVector2(line.toPnt)); vectorOld = vectorNow; line = new Line(vectorOld); } } else { // vectorNow just won't fit - process it separately vertices.Add(new DoubleVector2(line.toPnt)); vectorOld = vectorNow; line = new Line(vectorOld); } if (vectorPrev != null) vectors.Remove(vectorPrev.fromPnt); vectorPrev = vectorOld; } while (!vectorOld.fromPnt.Equals(startPnt)); vectors.Remove(startPnt); vertices.TrimToSize(); polygons.Add(vertices); } } protected void transformVectors(Matrix2D matrix) { Random randGen = new Random(); for (int j = 0; j < polygons.Count; j++) { ArrayList vertices = (ArrayList)polygons[j]; for (int i = 0; i < vertices.Count; i++) { DoubleVector2 vertexOld = (DoubleVector2)vertices[i]; vertices.RemoveAt(i); DoubleVector2 vertexNew = vertexOld * matrix; // add a little random jitter so as to remove the 'horizontal line' bug vertexNew.x += randGen.NextDouble() / 100000.0; vertexNew.y += randGen.NextDouble() / 100000.0; vertices.Insert(i, vertexNew); } } for (int i = 0; i < objects.Count; i++) { ElmaObject objectNow = (ElmaObject)objects[i]; DoubleVector2 vertexOld = new DoubleVector2(objectNow.x, objectNow.y); objects.RemoveAt(i); DoubleVector2 vertexNew = vertexOld * matrix; objectNow.x = vertexNew.x; objectNow.y = vertexNew.y; objects.Insert(i, objectNow); } getMinMax(); } protected void saveAsLev(String fileName, String levelName, String LGRName, String groundName, String skyName) { if (polygons.Count == 0) throw new Exception("there must be at least one polygon!"); if (xmax - xmin > 170 || ymax - ymin > 141) throw new Exception("too large polygons; use different scale"); int numPolys = polygons.Count; if (numPolys > 300) throw new Exception("too many polygons; max 300 polygons allowed by elma"); Random randGen = new Random(); byte[] randomNum = new byte[4]; randGen.NextBytes(randomNum); byte[] POT14 = {(byte)'P', (byte)'O', (byte)'T', (byte)'1', (byte)'4'}; double PSUM = 0; for (int j = 0; j < polygons.Count; j++) { ArrayList vertices = (ArrayList)polygons[j]; for (int i = 0; i < vertices.Count; i++) { DoubleVector2 vertex = (DoubleVector2)vertices[i]; PSUM += vertex.x + vertex.y; } } double OSUM = 0; IEnumerator objectNow = objects.GetEnumerator(); while (objectNow.MoveNext()) { ElmaObject elmaObject = (ElmaObject)objectNow.Current; OSUM += elmaObject.x + elmaObject.y + elmaObject.type; } double PICSUM = 0; double SUM = (PSUM + OSUM + PICSUM) * 3247.764325643; double integrity1 = SUM; double integrity2 = ((double) (randGen.Next() % 5871)) + 11877 - SUM; double integrity3 = ((double) (randGen.Next() % 5871)) + 11877 - SUM; bool unknown = false; if (unknown) integrity3 = ((double) (randGen.Next() % 4982)) + 20961 - SUM; double integrity4 = ((double) (randGen.Next() % 6102)) + 12112 - SUM; bool locked = false; if (locked) integrity4 = ((double) (randGen.Next() % 6310)) + 23090 - SUM; Int32 endOfData = 0x0067103A; byte[] emptyTables = { 21,5,106,183,137,237,89,196,72,255,143,115,118,188,112,192,223,87,180, 47,13,158,7,188,99,8,111,138,9,40,173,56,224,115,249,160,128,0,0, 138,55,111,105,96,23,9,119,65,172,140,38,52,172,2,167,152,201,165,254, 128,223,192,151,180,80,215,29,202,68,65,251,71,247,216,96,56,132,203,76, 130,49,36,154,145,118,201,14,107,204,117,252,204,248,165,116,152,142,2,187, 104,68,203,76,189,153,196,52,244,139,122,76,104,88,83,154,112,205,79,43, 204,209,26,224,128,46,143,115,52,231,14,212,70,29,189,2,154,191,51,39, 132,6,88,17,164,16,228,29,117,42,176,120,47,230,6,134,239,164,213,249, 252,145,46,84,116,93,248,145,177,246,162,85,249,35,251,71,142,15,69,244, 231,93,84,57,140,209,46,143,56,191,143,187,104,160,56,211,200,137,73,145, 59,189,2,3,136,229,44,127,156,181,147,95,87,160,161,228,75,17,92,253, 107,132,52,198,252,145,177,23,9,145,59,150,165,116,152,63,189,94,125,166, 137,132,39,224,82,100,167,165,162,144,64,79,115,52,152,4,144,31,205,184, 165,129,67,136,196,216,201,204,25,45,30,151,101,70,252,53,88,50,215,42, 45,253,74,22,152,129,218,132,157,25,91,140,176,133,21,85,190,56,165,254, 148,149,203,227,218,86,34,105,4,177,141,7,70,147,108,166,52,93,84,208, 248,132,144,31,225,195,182,103,237,56,152,96,246,96,200,91,2,95,28,194, 167,93,163,126,207,36,167,27,127,123,222,66,167,211,246,175,171,204,163,100, 3,44,35,21,190,174,64,79,69,244,80,5,126,233,247,203,253,140,255,143, 82,251,71,83,29,51,118,188,171,191,64,184,224,23,239,0,13,66,62,102, 19,246,83,246,142,28,181,180,80,202,186,30,184,27,2,16,77,230,137,132, 236,225,241,3,221,235,158,184,191,169,50,254,207,128,33,195,44,127,38,78, 192,72,104,173,227,21,236,186,17,72,78,212,116,113,36,154,40,173,181,180, 152,4,26,86,211,226,190,148,208,18,251,176,87,101,188,171,86,119,6,226, 59,91,245,62,69,1,21,229,175,105,4,111,33,228,49,213,52,172,48,15, 36,213,6,167,60,145,92,181,42,104,206,107,132,65,54,96,200,19,180,185, 252,171,99,159,179,59,25,196,216,17,164,29,163,8,183,137,204,235,158,0, 0,243,203,30,197,231,119,124,40,160,128,72,137,73,27,212,136,196,85,6, 206,166,170,255,143,187,45,56,145,177,187,163,139,89,183,196,236,48,74,232, 160,220,122,227,185,160,56,237,194,213,190,56,40,22,152,109,207,115,85,19, 75,76,25,242,169,4,157,235,66,141,33,215,75,43,7,155,219,35,80,110, 130,213,216,4,52,21,190,56,237,181,16,182,83,121,245,88,50,136,32,233, 214,152,234,222,151,42,150,106,163,93,12,248,47,197,172,107,86,198,121,81, 210,41,37,103,237,89,255,156,56,211,167,132,203,4,72,111,197,34,151,193, 54,175,20,195,149,216,96,233,76 }; Int32 endOfFile = 0x00845D52; BinaryWriter levWriter = new BinaryWriter((Stream)File.Create(fileName)); levWriter.Write(POT14); levWriter.Write(randomNum, 2, 2); levWriter.Write(randomNum); levWriter.Write(integrity1); levWriter.Write(integrity2); levWriter.Write(integrity3); levWriter.Write(integrity4); for (int i = 0; i < 51; i++) levWriter.Write(i < levelName.Length ? (byte)levelName[i] : (byte)0); for (int i = 0; i < 16; i++) levWriter.Write(i < LGRName.Length ? (byte)LGRName[i] : (byte)0); for (int i = 0; i < 10; i++) levWriter.Write(i < groundName.Length ? (byte)groundName[i] : (byte)0); for (int i = 0; i < 10; i++) levWriter.Write(i < skyName.Length ? (byte)skyName[i] : (byte)0); levWriter.Write(numPolys + 0.4643643); for (int j = 0; j < numPolys; j++) { ArrayList vertices = (ArrayList)polygons[j]; levWriter.Write((Int32)0); levWriter.Write((Int32)vertices.Count); for (int i = 0; i < vertices.Count; i++) { DoubleVector2 vertex = (DoubleVector2)vertices[i]; levWriter.Write(vertex.x); levWriter.Write(vertex.y); } } levWriter.Write(objects.Count + 0.4643643); for (int i = 0; i < objects.Count; i++) { ElmaObject elmaObject = (ElmaObject)objects[i]; levWriter.Write(elmaObject.x); levWriter.Write(elmaObject.y); levWriter.Write((Int32)elmaObject.type); levWriter.Write((Int32)elmaObject.typeOfFood); levWriter.Write((Int32)elmaObject.animationNumber); } levWriter.Write((double) 0.2345672); levWriter.Write(endOfData); levWriter.Write(emptyTables); levWriter.Write(endOfFile); levWriter.Close(); } protected void loadAsLev(String fileName) { BinaryReader levReader = new BinaryReader((Stream)File.OpenRead(fileName)); levReader.BaseStream.Seek(130, SeekOrigin.Begin); int numPolys = (int)Math.Round(levReader.ReadDouble() - 0.4643643); for (int j = 0; j < numPolys; j++) { int grassPoly = levReader.ReadInt32(); int numVertices = levReader.ReadInt32(); if (grassPoly == 0) { ArrayList vertices = new ArrayList(numVertices); for (int i = 0; i < numVertices; i++) { DoubleVector2 vertex = new DoubleVector2(levReader.ReadDouble(), levReader.ReadDouble()); vertices.Add(vertex); } polygons.Add(vertices); } else levReader.BaseStream.Seek(16 * numVertices, SeekOrigin.Current); } int numObjects = (int)Math.Round(levReader.ReadDouble() - 0.4643643); objects = new ArrayList(numObjects); for (int j = 0; j < numObjects; j++) { ElmaObject elmaObject = new ElmaObject(levReader.ReadDouble(), levReader.ReadDouble(), levReader.ReadUInt32(), levReader.ReadUInt32(), levReader.ReadUInt32()); objects.Add(elmaObject); } levReader.Close(); if (polygons.Count == 0) throw new Exception("there must be at least one polygon!"); getMinMax(); } protected void loadAsBmp(String fileName, out Bitmap bmp, out byte[,] pixelOn, double zoom, byte merging, int numFlowers) { bmp = new Bitmap(fileName); pixelOn = new byte[bmp.Width + 2, bmp.Height + 2]; int steps = 0; for (int j = -1; j <= bmp.Height; j++) for (int i = -1; i <= bmp.Width; i++) { printProgress(ref steps, 200000); if (j < 0 || j >= bmp.Height || i < 0 || i >= bmp.Width) pixelOn[i + 1, j + 1] = merging; else { Color col = bmp.GetPixel(i, j); if (col.R < 250 || col.G < 250 || col.B < 250) { pixelOn[i + 1, j + 1] = 1; } } } objects = new ArrayList(); for (int i = 0; i < numFlowers; i++) objects.Add(new ElmaObject( bmp.Width / 2 + (2 + 6 * Math.Cos(i * Math.PI / numFlowers)) / zoom, bmp.Height / 2 - 6 * Math.Sin(i * Math.PI / numFlowers) / zoom, 1, 0, 0)); objects.Add(new ElmaObject(bmp.Width / 2, bmp.Height / 2, 4, 0, 0)); } protected void saveAsBmp(String fileName) { if (polygons.Count == 0) throw new Exception("there must be at least one polygon!"); ArrayList[] inPnt = new ArrayList[ymax - ymin + 1]; for (int i = 0; i < inPnt.Length; i++) inPnt[i] = new ArrayList(20); for (int j = 0; j < polygons.Count; j++) { ArrayList vertices = (ArrayList)polygons[j]; for (int i = 0; i < vertices.Count; i++) { DoubleVector2 vertex = (DoubleVector2)vertices[i]; DoubleVector2 vertexNext = i + 1 < vertices.Count ? (DoubleVector2)vertices[i + 1] : (DoubleVector2)vertices[0]; IntVector2 pointFrom = new IntVector2((int)vertex.x - xmin, (int)vertex.y - ymin); IntVector2 pointTo = new IntVector2((int)vertexNext.x - xmin, (int)vertexNext.y - ymin); VectorPixel vect = new VectorPixel(pointFrom, pointTo); if (vect.dy != 1) { IntVector2 pointNow; for (int k = 0; k < vect.dy; k++) { if (vect.dx > vect.dy) { if (vect.sx * vect.sy == 1) pointNow = new IntVector2(pointFrom.x + vect.sx * (2 * vect.dx * k + vect.dy - 1) / (2 * vect.dy), pointFrom.y + vect.sy * k); else pointNow = new IntVector2(pointFrom.x + vect.sx * ((2 * vect.dx * (k + 1) + vect.dy - 1) / (2 * vect.dy) - 1), pointFrom.y + vect.sy * k); } else pointNow = new IntVector2(pointFrom.x + vect.sx * (2 * (vect.dx - 1) * k + vect.dy - 1) / (2 * (vect.dy - 1)), pointFrom.y + vect.sy * k); inPnt[pointNow.y].Add(new FromToInt(pointNow.x, vect.sx, vect.sy, pointFrom.x + pointTo.x)); } } } } Bitmap bmp = new Bitmap(xmax - xmin + 3, ymax - ymin + 3, PixelFormat.Format32bppRgb); BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat); int stride = bmpData.Stride; Int64 startPtr = bmpData.Scan0.ToInt64(); if (stride < 0) { startPtr += stride * (bmpData.Height - 1); stride = Math.Abs(stride); } byte[] rowBytes = new byte[bmpData.Stride]; for (int i = 0; i < bmpData.Height; i++) // make everything black first System.Runtime.InteropServices.Marshal.Copy(new IntPtr(startPtr + stride * i), rowBytes, 0, bmpData.Stride); for (int i = 0; i < bmpData.Stride; i++) rowBytes[i] = 255; for (int i = 0; i < inPnt.Length; i++) { inPnt[i].Sort(); for (int j = 1; j < inPnt[i].Count; j++) { FromToInt f = (FromToInt)inPnt[i][j]; FromToInt fprev = (FromToInt)inPnt[i][j - 1]; if (f.sy > 0 && fprev.sy <= 0 && f.x - (fprev.x + 1) > 0) // insert empty space where appropriate System.Runtime.InteropServices.Marshal.Copy(rowBytes, 0, new IntPtr(startPtr + stride * i + 4 * (fprev.x + 1)), 4 * (f.x - (fprev.x + 1))); f = (FromToInt)inPnt[i][j]; fprev = (FromToInt)inPnt[i][j - 1]; } } bmp.UnlockBits(bmpData); bmp.Save(fileName); } void getMinMax() { xmin = Int32.MaxValue; xmax = Int32.MinValue; ymin = Int32.MaxValue; ymax = Int32.MinValue; for (int j = 0; j < polygons.Count; j++) { ArrayList vertices = (ArrayList)polygons[j]; for (int i = 0; i < vertices.Count; i++) { DoubleVector2 vertex = (DoubleVector2)vertices[i]; xmin = Math.Min(xmin, (int)vertex.x); xmax = Math.Max(xmax, (int)vertex.x); ymin = Math.Min(ymin, (int)vertex.y); ymax = Math.Max(ymax, (int)vertex.y); } } for (int i = 0; i < objects.Count; i++) { DoubleVector2 vertex = new DoubleVector2(((ElmaObject)objects[i]).x, ((ElmaObject)objects[i]).y); xmin = Math.Min(xmin, (int)vertex.x); xmax = Math.Max(xmax, (int)vertex.x); ymin = Math.Min(ymin, (int)vertex.y); ymax = Math.Max(ymax, (int)vertex.y); } } void printProgress(ref int steps, int max) { if (printProgressOn) if (steps-- == 0) { steps = max; Console.Write("."); } } void printWarning(string warning) { someWarning = true; if (printWarningsOn) { Console.WriteLine(warning); } } static Int32 Main(string[] args) { #region init defaults const double ONEPIXEL = 1.0 / 47.0; bool printProgressOn = true; bool printWarningsOn = false; IOType load_type = IOType.None; IOType save_type = IOType.None; String loadLevFileName = null; String saveLevFileName = null; String loadBmpFileName = null; String saveBmpFileName = null; int numFlowers = 1; Matrix2D transformMatrix = Matrix2D.identityM(); #endregion #region arguments parse int arg_num = 0; try { while (arg_num < args.Length) { String arg_now = args[arg_num++]; switch (arg_now) { case "-loadbmp": // initialize from bitmap load_type = IOType.Bitmap; loadBmpFileName = args[arg_num++]; break; case "-loadlev": // initialize from level load_type = IOType.Level; loadLevFileName = args[arg_num++]; break; case "-savebmp": // save to bitmap save_type = IOType.Bitmap; saveBmpFileName = args[arg_num++]; break; case "-savelev": // save to level save_type = IOType.Level; saveLevFileName = args[arg_num++]; break; case "-loadlevbmp": load_type = IOType.LevelBitmap; loadLevFileName = args[arg_num++]; loadBmpFileName = args[arg_num++]; break; case "-translate": // offset by tx, ty double tx = Double.Parse(args[arg_num++]); double ty = Double.Parse(args[arg_num++]); transformMatrix = transformMatrix * Matrix2D.translationM(tx, ty); break; case "-rotate": // rotate by angle (in degrees) double ang = Double.Parse(args[arg_num++]); transformMatrix = transformMatrix * Matrix2D.rotationM(ang); break; case "-scale": // scale by factor sx, sy double sx = Double.Parse(args[arg_num++]) * ONEPIXEL; double sy = Double.Parse(args[arg_num++]) * ONEPIXEL; transformMatrix = transformMatrix * Matrix2D.scaleM(sx, sy); break; case "-flowers": // number of flowers numFlowers = Int32.Parse(args[arg_num++]); break; case "-progress": // show progress continually printProgressOn = Boolean.Parse(args[arg_num++]); break; case "-warnings": // print warnings printWarningsOn = Boolean.Parse(args[arg_num++]); break; default: throw new Exception("unknown parameter '" + arg_now + "'"); } } } catch (IndexOutOfRangeException) { Console.WriteLine("\nexpected value(s) after the switch"); return 7; } catch (Exception e) { Console.WriteLine("\nerror parsing command line: " + e.Message); return 8; } if (load_type == IOType.LevelBitmap && save_type == IOType.Bitmap) { Console.WriteLine("savebmp not allowed after loadlevbmp"); return 3; } #endregion #region load and transform VectRast vr = new VectRast(printProgressOn, printWarningsOn); if (load_type == IOType.Bitmap || load_type == IOType.LevelBitmap) { byte[,] pixelOn; Bitmap bmp; try { Console.Write("\nloading in bitmap {0}", loadBmpFileName); vr.loadAsBmp(loadBmpFileName, out bmp, out pixelOn, Math.Abs(transformMatrix.elements[0,0]) + Math.Abs(transformMatrix.elements[1,1]), load_type == IOType.LevelBitmap ? (byte)0 : (byte)1, numFlowers); } catch (Exception e) { Console.WriteLine("\nerror loading bitmap {0}: " + e.Message, loadBmpFileName); return 1; } try { Console.Write("\ncreating polygons"); vr.collapseVectors(vr.createVectors(pixelOn, bmp)); } catch (Exception e) { Console.WriteLine("\nerror vectorizing the bitmap: " + e.Message); return 2; } transformMatrix = Matrix2D.translationM(-bmp.Width / 2.0, -bmp.Height / 2.0) * transformMatrix; bmp.Dispose(); } if (load_type == IOType.LevelBitmap) try { Console.Write("\ntransforming vectors"); vr.transformVectors(transformMatrix); } catch (Exception e) { Console.WriteLine("\nerror transforming vectors: " + e.Message); return 4; } if (load_type == IOType.Level || load_type == IOType.LevelBitmap) try { Console.Write("\nloading in level {0}", loadLevFileName); vr.loadAsLev(loadLevFileName); } catch (Exception e) { Console.WriteLine("\nerror loading level {0}: " + e.Message, loadLevFileName); return 5; } if (load_type != IOType.LevelBitmap) try { Console.Write("\ntransforming vectors"); vr.transformVectors(transformMatrix); } catch (Exception e) { Console.WriteLine("\nerror transforming vectors: " + e.Message); return 6; } #endregion #region save switch (save_type) { case IOType.None: break; case IOType.Bitmap: try { Console.Write("\nsaving bitmap {0}", saveBmpFileName); vr.saveAsBmp(saveBmpFileName); } catch (Exception e) { Console.WriteLine("\nerror saving bitmap {0}: " + e.Message, saveBmpFileName); return 5; } break; case IOType.Level: try { Console.Write("\nsaving level {0}", saveLevFileName); vr.saveAsLev(saveLevFileName, "autogenerated on " + DateTime.Now.ToString("g"), "DEFAULT", "ground", "sky"); } catch (Exception e) { Console.WriteLine("\nerror saving level {0}: " + e.Message, saveLevFileName); return 6; } break; } if (vr.someWarning) Console.WriteLine("\ndone, but there were some warnings; set '-warnings true' to view them\n"); else Console.WriteLine("\ndone\n"); return 0; #endregion } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Numerics.Tests { public class StackCalc { public string[] input; public Stack<BigInteger> myCalc; public Stack<BigInteger> snCalc; public Queue<string> operators; private BigInteger _snOut = 0; private BigInteger _myOut = 0; public StackCalc(string _input) { myCalc = new Stack<System.Numerics.BigInteger>(); snCalc = new Stack<System.Numerics.BigInteger>(); string delimStr = " "; char[] delimiter = delimStr.ToCharArray(); input = _input.Split(delimiter); operators = new Queue<string>(input); } public bool DoNextOperation() { string op = ""; bool ret = false; bool checkValues = false; BigInteger snnum1 = 0; BigInteger snnum2 = 0; BigInteger snnum3 = 0; BigInteger mynum1 = 0; BigInteger mynum2 = 0; BigInteger mynum3 = 0; if (operators.Count == 0) { return false; } op = operators.Dequeue(); if (op.StartsWith("u")) { checkValues = true; snnum1 = snCalc.Pop(); snCalc.Push(DoUnaryOperatorSN(snnum1, op)); mynum1 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoUnaryOperatorMine(mynum1, op)); ret = true; } else if (op.StartsWith("b")) { checkValues = true; snnum1 = snCalc.Pop(); snnum2 = snCalc.Pop(); snCalc.Push(DoBinaryOperatorSN(snnum1, snnum2, op, out _snOut)); mynum1 = myCalc.Pop(); mynum2 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoBinaryOperatorMine(mynum1, mynum2, op, out _myOut)); ret = true; } else if (op.StartsWith("t")) { checkValues = true; snnum1 = snCalc.Pop(); snnum2 = snCalc.Pop(); snnum3 = snCalc.Pop(); snCalc.Push(DoTertanaryOperatorSN(snnum1, snnum2, snnum3, op)); mynum1 = myCalc.Pop(); mynum2 = myCalc.Pop(); mynum3 = myCalc.Pop(); myCalc.Push(MyBigIntImp.DoTertanaryOperatorMine(mynum1, mynum2, mynum3, op)); ret = true; } else { if (op.Equals("make")) { snnum1 = DoConstruction(); snCalc.Push(snnum1); myCalc.Push(snnum1); } else if (op.Equals("Corruption")) { snCalc.Push(-33); myCalc.Push(-555); } else if (BigInteger.TryParse(op, out snnum1)) { snCalc.Push(snnum1); myCalc.Push(snnum1); } else { Console.WriteLine("Failed to parse string {0}", op); } ret = true; } if (checkValues) { if ((snnum1 != mynum1) || (snnum2 != mynum2) || (snnum3 != mynum3)) { operators.Enqueue("Corruption"); } } return ret; } private BigInteger DoConstruction() { List<byte> bytes = new List<byte>(); BigInteger ret = new BigInteger(0); string op = operators.Dequeue(); while (String.CompareOrdinal(op, "endmake") != 0) { bytes.Add(byte.Parse(op)); op = operators.Dequeue(); } return new BigInteger(bytes.ToArray()); } private BigInteger DoUnaryOperatorSN(BigInteger num1, string op) { switch (op) { case "uSign": return new BigInteger(num1.Sign); case "u~": return (~(num1)); case "uLog10": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log10(num1)); case "uLog": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1)); case "uAbs": return BigInteger.Abs(num1); case "uNegate": return BigInteger.Negate(num1); case "u--": return (--(num1)); case "u++": return (++(num1)); case "u-": return (-(num1)); case "u+": return (+(num1)); case "uMultiply": return BigInteger.Multiply(num1, num1); case "u*": return num1 * num1; default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } private BigInteger DoBinaryOperatorSN(BigInteger num1, BigInteger num2, string op) { BigInteger num3; return DoBinaryOperatorSN(num1, num2, op, out num3); } private BigInteger DoBinaryOperatorSN(BigInteger num1, BigInteger num2, string op, out BigInteger num3) { switch (op) { case "bMin": return BigInteger.Min(num1, num2); case "bMax": return BigInteger.Max(num1, num2); case "b>>": return num1 >> (int)num2; case "b<<": return num1 << (int)num2; case "b^": return num1 ^ num2; case "b|": return num1 | num2; case "b&": return num1 & num2; case "b%": return num1 % num2; case "b/": return num1 / num2; case "b*": return num1 * num2; case "b-": return num1 - num2; case "b+": return num1 + num2; case "bLog": return MyBigIntImp.ApproximateBigInteger(BigInteger.Log(num1, (double)num2)); case "bGCD": return BigInteger.GreatestCommonDivisor(num1, num2); case "bPow": int arg2 = (int)num2; return BigInteger.Pow(num1, arg2); case "bDivRem": return BigInteger.DivRem(num1, num2, out num3); case "bRemainder": return BigInteger.Remainder(num1, num2); case "bDivide": return BigInteger.Divide(num1, num2); case "bMultiply": return BigInteger.Multiply(num1, num2); case "bSubtract": return BigInteger.Subtract(num1, num2); case "bAdd": return BigInteger.Add(num1, num2); default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } private BigInteger DoTertanaryOperatorSN(BigInteger num1, BigInteger num2, BigInteger num3, string op) { switch (op) { case "tModPow": return BigInteger.ModPow(num1, num2, num3); default: throw new ArgumentException(String.Format("Invalid operation found: {0}", op)); } } public void VerifyOutParameter() { Assert.Equal(_snOut, _myOut); _snOut = 0; _myOut = 0; } private static String Print(byte[] bytes) { return MyBigIntImp.PrintFormatX(bytes); } } }
// Licensed to the Apache Software Foundation(ASF) under one // or more contributor license agreements.See the NOTICE file // distributed with this work for additional information // regarding copyright ownership.The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; #pragma warning disable IDE0079 // unnecessary suppression #pragma warning disable IDE0063 // simplify using namespace Thrift.Transport.Client { // ReSharper disable once InconsistentNaming public class THttpTransport : TEndpointTransport { private readonly X509Certificate[] _certificates; private readonly Uri _uri; private int _connectTimeout = 30000; // Timeouts in milliseconds private HttpClient _httpClient; private Stream _inputStream; private MemoryStream _outputStream = new MemoryStream(); private bool _isDisposed; public THttpTransport(Uri uri, TConfiguration config, IDictionary<string, string> customRequestHeaders = null, string userAgent = null) : this(uri, config, Enumerable.Empty<X509Certificate>(), customRequestHeaders, userAgent) { } public THttpTransport(Uri uri, TConfiguration config, IEnumerable<X509Certificate> certificates, IDictionary<string, string> customRequestHeaders, string userAgent = null) : base(config) { _uri = uri; _certificates = (certificates ?? Enumerable.Empty<X509Certificate>()).ToArray(); if (!string.IsNullOrEmpty(userAgent)) UserAgent = userAgent; // due to current bug with performance of Dispose in netcore https://github.com/dotnet/corefx/issues/8809 // this can be switched to default way (create client->use->dispose per flush) later _httpClient = CreateClient(customRequestHeaders); ConfigureClient(_httpClient); } /// <summary> /// Constructor that takes a <c>HttpClient</c> instance to support using <c>IHttpClientFactory</c>. /// </summary> /// <remarks>As the <c>HttpMessageHandler</c> of the client must be configured at the time of creation, it /// is assumed that the consumer has already added any certificates and configured decompression methods. The /// consumer can use the <c>CreateHttpClientHandler</c> method to get a handler with these set.</remarks> /// <param name="httpClient">Client configured with the desired message handler, user agent, and URI if not /// specified in the <c>uri</c> parameter. A default user agent will be used if not set.</param> /// <param name="config">Thrift configuration object</param> /// <param name="uri">Optional URI to use for requests, if not specified the base address of <c>httpClient</c> /// is used.</param> public THttpTransport(HttpClient httpClient, TConfiguration config, Uri uri = null) : base(config) { _httpClient = httpClient; _uri = uri ?? httpClient.BaseAddress; httpClient.BaseAddress = _uri; var userAgent = _httpClient.DefaultRequestHeaders.UserAgent.ToString(); if (!string.IsNullOrEmpty(userAgent)) UserAgent = userAgent; ConfigureClient(_httpClient); } // According to RFC 2616 section 3.8, the "User-Agent" header may not carry a version number public readonly string UserAgent = "Thrift netstd THttpClient"; public int ConnectTimeout { set { _connectTimeout = value; if(_httpClient != null) _httpClient.Timeout = TimeSpan.FromMilliseconds(_connectTimeout); } get { if (_httpClient == null) return _connectTimeout; return (int)_httpClient.Timeout.TotalMilliseconds; } } public override bool IsOpen => true; public HttpRequestHeaders RequestHeaders => _httpClient.DefaultRequestHeaders; public MediaTypeHeaderValue ContentType { get; set; } public override Task OpenAsync(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); return Task.CompletedTask; } public override void Close() { if (_inputStream != null) { _inputStream.Dispose(); _inputStream = null; } if (_outputStream != null) { _outputStream.Dispose(); _outputStream = null; } if (_httpClient != null) { _httpClient.Dispose(); _httpClient = null; } } public override async ValueTask<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (_inputStream == null) throw new TTransportException(TTransportException.ExceptionType.NotOpen, "No request has been sent"); CheckReadBytesAvailable(length); try { #if NETSTANDARD2_0 var ret = await _inputStream.ReadAsync(buffer, offset, length, cancellationToken); #else var ret = await _inputStream.ReadAsync(new Memory<byte>(buffer, offset, length), cancellationToken); #endif if (ret == -1) { throw new TTransportException(TTransportException.ExceptionType.EndOfFile, "No more data available"); } CountConsumedMessageBytes(ret); return ret; } catch (IOException iox) { throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); } } public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); #if NETSTANDARD2_0 await _outputStream.WriteAsync(buffer, offset, length, cancellationToken); #else await _outputStream.WriteAsync(buffer.AsMemory(offset, length), cancellationToken); #endif } /// <summary> /// Get a client handler configured with recommended properties to use with the <c>HttpClient</c> constructor /// and an <c>IHttpClientFactory</c>. /// </summary> /// <param name="certificates">An optional array of client certificates to associate with the handler.</param> /// <returns> /// A client handler with deflate and gZip compression-decompression algorithms and any client /// certificates passed in via <c>certificates</c>. /// </returns> public virtual HttpClientHandler CreateHttpClientHandler(X509Certificate[] certificates = null) { var handler = new HttpClientHandler(); if (certificates != null) handler.ClientCertificates.AddRange(certificates); handler.AutomaticDecompression = System.Net.DecompressionMethods.Deflate | System.Net.DecompressionMethods.GZip; return handler; } private HttpClient CreateClient(IDictionary<string, string> customRequestHeaders) { var handler = CreateHttpClientHandler(_certificates); var httpClient = new HttpClient(handler); if (customRequestHeaders != null) { foreach (var item in customRequestHeaders) { httpClient.DefaultRequestHeaders.Add(item.Key, item.Value); } } return httpClient; } private void ConfigureClient(HttpClient httpClient) { if (_connectTimeout > 0) { httpClient.Timeout = TimeSpan.FromMilliseconds(_connectTimeout); } httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-thrift")); // Clear any user agent values to avoid drift with the field value httpClient.DefaultRequestHeaders.UserAgent.Clear(); httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd(UserAgent); httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate")); httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip")); } public override async Task FlushAsync(CancellationToken cancellationToken) { try { _outputStream.Seek(0, SeekOrigin.Begin); using (var contentStream = new StreamContent(_outputStream)) { contentStream.Headers.ContentType = ContentType ?? new MediaTypeHeaderValue(@"application/x-thrift"); var response = (await _httpClient.PostAsync(_uri, contentStream, cancellationToken)).EnsureSuccessStatusCode(); _inputStream?.Dispose(); #if NETSTANDARD2_0 || NETSTANDARD2_1 _inputStream = await response.Content.ReadAsStreamAsync(); #else _inputStream = await response.Content.ReadAsStreamAsync(cancellationToken); #endif if (_inputStream.CanSeek) { _inputStream.Seek(0, SeekOrigin.Begin); } } } catch (IOException iox) { throw new TTransportException(TTransportException.ExceptionType.Unknown, iox.ToString()); } catch (HttpRequestException wx) { throw new TTransportException(TTransportException.ExceptionType.Unknown, "Couldn't connect to server: " + wx); } catch (Exception ex) { throw new TTransportException(TTransportException.ExceptionType.Unknown, ex.Message); } finally { _outputStream = new MemoryStream(); ResetConsumedMessageSize(); } } // IDisposable protected override void Dispose(bool disposing) { if (!_isDisposed) { if (disposing) { _inputStream?.Dispose(); _outputStream?.Dispose(); _httpClient?.Dispose(); } } _isDisposed = true; } } }
// // Options.cs // // Authors: // Jonathan Pryor <[email protected]> // // Copyright (C) 2008 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Log.Info (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Log.Info (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; #if LINQ using System.Linq; #endif #if TEST using NDesk.Options; #endif namespace NDesk.Options { public class OptionValueCollection : IList, IList<string> { List<string> values = new List<string> (); OptionContext c; internal OptionValueCollection (OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo (Array array, int index) {(values as ICollection).CopyTo (array, index);} bool ICollection.IsSynchronized {get {return (values as ICollection).IsSynchronized;}} object ICollection.SyncRoot {get {return (values as ICollection).SyncRoot;}} #endregion #region ICollection<T> public void Add (string item) {values.Add (item);} public void Clear () {values.Clear ();} public bool Contains (string item) {return values.Contains (item);} public void CopyTo (string[] array, int arrayIndex) {values.CopyTo (array, arrayIndex);} public bool Remove (string item) {return values.Remove (item);} public int Count {get {return values.Count;}} public bool IsReadOnly {get {return false;}} #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator () {return values.GetEnumerator ();} #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator () {return values.GetEnumerator ();} #endregion #region IList int IList.Add (object value) {return (values as IList).Add (value);} bool IList.Contains (object value) {return (values as IList).Contains (value);} int IList.IndexOf (object value) {return (values as IList).IndexOf (value);} void IList.Insert (int index, object value) {(values as IList).Insert (index, value);} void IList.Remove (object value) {(values as IList).Remove (value);} void IList.RemoveAt (int index) {(values as IList).RemoveAt (index);} bool IList.IsFixedSize {get {return false;}} object IList.this [int index] {get {return this [index];} set {(values as IList)[index] = value;}} #endregion #region IList<T> public int IndexOf (string item) {return values.IndexOf (item);} public void Insert (int index, string item) {values.Insert (index, item);} public void RemoveAt (int index) {values.RemoveAt (index);} private void AssertValid (int index) { if (c.Option == null) throw new InvalidOperationException ("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException ("index"); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException (string.Format ( c.OptionSet.MessageLocalizer ("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this [int index] { get { AssertValid (index); return index >= values.Count ? null : values [index]; } set { values [index] = value; } } #endregion public List<string> ToList () { return new List<string> (values); } public string[] ToArray () { return values.ToArray (); } public override string ToString () { return string.Join (", ", values.ToArray ()); } } public class OptionContext { private Option option; private string name; private int index; private OptionSet set; private OptionValueCollection c; public OptionContext (OptionSet set) { this.set = set; this.c = new OptionValueCollection (this); } public Option Option { get {return option;} set {option = value;} } public string OptionName { get {return name;} set {name = value;} } public int OptionIndex { get {return index;} set {index = value;} } public OptionSet OptionSet { get {return set;} } public OptionValueCollection OptionValues { get {return c;} } } public enum OptionValueType { None, Optional, Required, } public abstract class Option { string prototype, description; string[] names; OptionValueType type; int count; string[] separators; protected Option (string prototype, string description) : this (prototype, description, 1) { } protected Option (string prototype, string description, int maxValueCount) { if (prototype == null) throw new ArgumentNullException ("prototype"); if (prototype.Length == 0) throw new ArgumentException ("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException ("maxValueCount"); this.prototype = prototype; this.names = prototype.Split ('|'); this.description = description; this.count = maxValueCount; this.type = ParsePrototype (); if (this.count == 0 && type != OptionValueType.None) throw new ArgumentException ( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (this.type == OptionValueType.None && maxValueCount > 1) throw new ArgumentException ( string.Format ("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf (names, "<>") >= 0 && ((names.Length == 1 && this.type != OptionValueType.None) || (names.Length > 1 && this.MaxValueCount > 1))) throw new ArgumentException ( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype {get {return prototype;}} public string Description {get {return description;}} public OptionValueType OptionValueType {get {return type;}} public int MaxValueCount {get {return count;}} public string[] GetNames () { return (string[]) names.Clone (); } public string[] GetValueSeparators () { if (separators == null) return new string [0]; return (string[]) separators.Clone (); } protected static T Parse<T> (string value, OptionContext c) { TypeConverter conv = TypeDescriptor.GetConverter (typeof (T)); T t = default (T); try { if (value != null) t = (T) conv.ConvertFromString (value); } catch (Exception e) { throw new OptionException ( string.Format ( c.OptionSet.MessageLocalizer ("Could not convert string `{0}' to type {1} for option `{2}'."), value, typeof (T).Name, c.OptionName), c.OptionName, e); } return t; } internal string[] Names {get {return names;}} internal string[] ValueSeparators {get {return separators;}} static readonly char[] NameTerminator = new char[]{'=', ':'}; private OptionValueType ParsePrototype () { char type = '\0'; List<string> seps = new List<string> (); for (int i = 0; i < names.Length; ++i) { string name = names [i]; if (name.Length == 0) throw new ArgumentException ("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny (NameTerminator); if (end == -1) continue; names [i] = name.Substring (0, end); if (type == '\0' || type == name [end]) type = name [end]; else throw new ArgumentException ( string.Format ("Conflicting option types: '{0}' vs. '{1}'.", type, name [end]), "prototype"); AddSeparators (name, end, seps); } if (type == '\0') return OptionValueType.None; if (count <= 1 && seps.Count != 0) throw new ArgumentException ( string.Format ("Cannot provide key/value separators for Options taking {0} value(s).", count), "prototype"); if (count > 1) { if (seps.Count == 0) this.separators = new string[]{":", "="}; else if (seps.Count == 1 && seps [0].Length == 0) this.separators = null; else this.separators = seps.ToArray (); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } private static void AddSeparators (string name, int end, ICollection<string> seps) { int start = -1; for (int i = end+1; i < name.Length; ++i) { switch (name [i]) { case '{': if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i+1; break; case '}': if (start == -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add (name.Substring (start, i-start)); start = -1; break; default: if (start == -1) seps.Add (name [i].ToString ()); break; } } if (start != -1) throw new ArgumentException ( string.Format ("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke (OptionContext c) { OnParseComplete (c); c.OptionName = null; c.Option = null; c.OptionValues.Clear (); } protected abstract void OnParseComplete (OptionContext c); public override string ToString () { return Prototype; } } [Serializable] public class OptionException : Exception { private string option; public OptionException () { } public OptionException (string message, string optionName) : base (message) { this.option = optionName; } public OptionException (string message, string optionName, Exception innerException) : base (message, innerException) { this.option = optionName; } protected OptionException (SerializationInfo info, StreamingContext context) : base (info, context) { this.option = info.GetString ("OptionName"); } public string OptionName { get {return this.option;} } [SecurityPermission (SecurityAction.LinkDemand, SerializationFormatter = true)] public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData (info, context); info.AddValue ("OptionName", option); } } public delegate void OptionAction<TKey, TValue> (TKey key, TValue value); public class OptionSet : KeyedCollection<string, Option> { public OptionSet () : this (delegate (string f) {return f;}) { } public OptionSet (Converter<string, string> localizer) { this.localizer = localizer; } Converter<string, string> localizer; public Converter<string, string> MessageLocalizer { get {return localizer;} } protected override string GetKeyForItem (Option item) { if (item == null) throw new ArgumentNullException ("option"); if (item.Names != null && item.Names.Length > 0) return item.Names [0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException ("Option has no names!"); } [Obsolete ("Use KeyedCollection.this[string]")] protected Option GetOptionForName (string option) { if (option == null) throw new ArgumentNullException ("option"); try { return base [option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem (int index, Option item) { base.InsertItem (index, item); AddImpl (item); } protected override void RemoveItem (int index) { base.RemoveItem (index); Option p = Items [index]; // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove (p.Names [i]); } } protected override void SetItem (int index, Option item) { base.SetItem (index, item); RemoveItem (index); AddImpl (item); } private void AddImpl (Option option) { if (option == null) throw new ArgumentNullException ("option"); List<string> added = new List<string> (option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add (option.Names [i], option); added.Add (option.Names [i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove (name); throw; } } public new OptionSet Add (Option option) { base.Add (option); return this; } sealed class ActionOption : Option { Action<OptionValueCollection> action; public ActionOption (string prototype, string description, int count, Action<OptionValueCollection> action) : base (prototype, description, count) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (c.OptionValues); } } public OptionSet Add (string prototype, Action<string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, Action<string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 1, delegate (OptionValueCollection v) { action (v [0]); }); base.Add (p); return this; } public OptionSet Add (string prototype, OptionAction<string, string> action) { return Add (prototype, null, action); } public OptionSet Add (string prototype, string description, OptionAction<string, string> action) { if (action == null) throw new ArgumentNullException ("action"); Option p = new ActionOption (prototype, description, 2, delegate (OptionValueCollection v) {action (v [0], v [1]);}); base.Add (p); return this; } sealed class ActionOption<T> : Option { Action<T> action; public ActionOption (string prototype, string description, Action<T> action) : base (prototype, description, 1) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action (Parse<T> (c.OptionValues [0], c)); } } sealed class ActionOption<TKey, TValue> : Option { OptionAction<TKey, TValue> action; public ActionOption (string prototype, string description, OptionAction<TKey, TValue> action) : base (prototype, description, 2) { if (action == null) throw new ArgumentNullException ("action"); this.action = action; } protected override void OnParseComplete (OptionContext c) { action ( Parse<TKey> (c.OptionValues [0], c), Parse<TValue> (c.OptionValues [1], c)); } } public OptionSet Add<T> (string prototype, Action<T> action) { return Add (prototype, null, action); } public OptionSet Add<T> (string prototype, string description, Action<T> action) { return Add (new ActionOption<T> (prototype, description, action)); } public OptionSet Add<TKey, TValue> (string prototype, OptionAction<TKey, TValue> action) { return Add (prototype, null, action); } public OptionSet Add<TKey, TValue> (string prototype, string description, OptionAction<TKey, TValue> action) { return Add (new ActionOption<TKey, TValue> (prototype, description, action)); } protected virtual OptionContext CreateOptionContext () { return new OptionContext (this); } #if LINQ public List<string> Parse (IEnumerable<string> arguments) { bool process = true; OptionContext c = CreateOptionContext (); c.OptionIndex = -1; var def = GetOptionForName ("<>"); var unprocessed = from argument in arguments where ++c.OptionIndex >= 0 && (process || def != null) ? process ? argument == "--" ? (process = false) : !Parse (argument, c) ? def != null ? Unprocessed (null, def, c, argument) : true : false : def != null ? Unprocessed (null, def, c, argument) : true : true select argument; List<string> r = unprocessed.ToList (); if (c.Option != null) c.Option.Invoke (c); return r; } #else public List<string> Parse (IEnumerable<string> arguments) { OptionContext c = CreateOptionContext (); c.OptionIndex = -1; bool process = true; List<string> unprocessed = new List<string> (); Option def = Contains ("<>") ? this ["<>"] : null; foreach (string argument in arguments) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed (unprocessed, def, c, argument); continue; } if (!Parse (argument, c)) Unprocessed (unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke (c); return unprocessed; } #endif private static bool Unprocessed (ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add (argument); return false; } c.OptionValues.Add (argument); c.Option = def; c.Option.Invoke (c); return false; } private readonly Regex ValueOption = new Regex ( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); protected bool GetOptionParts (string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException ("argument"); flag = name = sep = value = null; Match m = ValueOption.Match (argument); if (!m.Success) { return false; } flag = m.Groups ["flag"].Value; name = m.Groups ["name"].Value; if (m.Groups ["sep"].Success && m.Groups ["value"].Success) { sep = m.Groups ["sep"].Value; value = m.Groups ["value"].Value; } return true; } protected virtual bool Parse (string argument, OptionContext c) { if (c.Option != null) { ParseValue (argument, c); return true; } string f, n, s, v; if (!GetOptionParts (argument, out f, out n, out s, out v)) return false; Option p; if (Contains (n)) { p = this [n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add (n); c.Option.Invoke (c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue (v, c); break; } return true; } // no match; is it a bool option? if (ParseBool (argument, n, c)) return true; // is it a bundled option? if (ParseBundledValue (f, string.Concat (n + s + v), c)) return true; return false; } private void ParseValue (string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split (c.Option.ValueSeparators, StringSplitOptions.None) : new string[]{option}) { c.OptionValues.Add (o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke (c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException (localizer (string.Format ( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } private bool ParseBool (string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n [n.Length-1] == '+' || n [n.Length-1] == '-') && Contains ((rn = n.Substring (0, n.Length-1)))) { p = this [rn]; string v = n [n.Length-1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add (v); p.Invoke (c); return true; } return false; } private bool ParseBundledValue (string f, string n, OptionContext c) { if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n [i].ToString (); string rn = n [i].ToString (); if (!Contains (rn)) { if (i == 0) return false; throw new OptionException (string.Format (localizer ( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this [rn]; switch (p.OptionValueType) { case OptionValueType.None: Invoke (c, opt, n, p); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring (i+1); c.Option = p; c.OptionName = opt; ParseValue (v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException ("Unknown OptionValueType: " + p.OptionValueType); } } return true; } private static void Invoke (OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add (value); option.Invoke (c); } private const int OptionWidth = 29; public void WriteOptionDescriptions (TextWriter o) { foreach (Option p in this) { int written = 0; if (!WriteOptionPrototype (o, p, ref written)) continue; if (written < OptionWidth) o.Write (new string (' ', OptionWidth - written)); else { o.WriteLine (); o.Write (new string (' ', OptionWidth)); } List<string> lines = GetLines (localizer (GetDescription (p.Description))); o.WriteLine (lines [0]); string prefix = new string (' ', OptionWidth+2); for (int i = 1; i < lines.Count; ++i) { o.Write (prefix); o.WriteLine (lines [i]); } } } bool WriteOptionPrototype (TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex (names, 0); if (i == names.Length) return false; if (names [i].Length == 1) { Write (o, ref written, " -"); Write (o, ref written, names [0]); } else { Write (o, ref written, " --"); Write (o, ref written, names [0]); } for ( i = GetNextOptionIndex (names, i+1); i < names.Length; i = GetNextOptionIndex (names, i+1)) { Write (o, ref written, ", "); Write (o, ref written, names [i].Length == 1 ? "-" : "--"); Write (o, ref written, names [i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("[")); } Write (o, ref written, localizer ("=" + GetArgumentName (0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators [0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write (o, ref written, localizer (sep + GetArgumentName (c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write (o, ref written, localizer ("]")); } } return true; } static int GetNextOptionIndex (string[] names, int i) { while (i < names.Length && names [i] == "<>") { ++i; } return i; } static void Write (TextWriter o, ref int n, string s) { n += s.Length; o.Write (s); } private static string GetArgumentName (int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new string[]{"{0:", "{"}; else nameStart = new string[]{"{" + index + ":"}; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf (nameStart [i], j); } while (start >= 0 && j != 0 ? description [j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf ("}", start); if (end == -1) continue; return description.Substring (start + nameStart [i].Length, end - start - nameStart [i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } private static string GetDescription (string description) { if (description == null) return string.Empty; StringBuilder sb = new StringBuilder (description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description [i]) { case '{': if (i == start) { sb.Append ('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i+1) == description.Length || description [i+1] != '}') throw new InvalidOperationException ("Invalid option description: " + description); ++i; sb.Append ("}"); } else { sb.Append (description.Substring (start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append (description [i]); break; } } return sb.ToString (); } private static List<string> GetLines (string description) { List<string> lines = new List<string> (); if (string.IsNullOrEmpty (description)) { lines.Add (string.Empty); return lines; } int length = 80 - OptionWidth - 2; int start = 0, end; do { end = GetLineEnd (start, length, description); bool cont = false; if (end < description.Length) { char c = description [end]; if (c == '-' || (char.IsWhiteSpace (c) && c != '\n')) ++end; else if (c != '\n') { cont = true; --end; } } lines.Add (description.Substring (start, end - start)); if (cont) { lines [lines.Count-1] += "-"; } start = end; if (start < description.Length && description [start] == '\n') ++start; } while (end < description.Length); return lines; } private static int GetLineEnd (int start, int length, string description) { int end = Math.Min (start + length, description.Length); int sep = -1; for (int i = start; i < end; ++i) { switch (description [i]) { case ' ': case '\t': case '\v': case '-': case ',': case '.': case ';': sep = i; break; case '\n': return i; } } if (sep == -1 || end == description.Length) return end; return sep; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Net.Mime; using System.Globalization; using System.Collections; using System.Diagnostics; using System.Collections.Generic; namespace System.Net.Mail { // // This class is responsible for parsing E-mail addresses as described in RFC 2822. // // Ideally, addresses are formatted as ("Display name" <username@domain>), but we still try to read several // other formats, including common invalid formats like (Display name username@domain). // // To make the detection of invalid address formats simpler, all address parsing is done in reverse order, // including lists. This way we know that the domain must be first, then the local-part, and then whatever // remains must be the display-name. // internal static class MailAddressParser { // Parse a single MailAddress from the given string. // // Throws a FormatException if any part of the MailAddress is invalid. internal static MailAddress ParseAddress(string data) { int index = data.Length - 1; MailAddress parsedAddress = MailAddressParser.ParseAddress(data, false, ref index); Debug.Assert(index == -1, "The index indicates that part of the address was not parsed: " + index); return parsedAddress; } // Parse a comma separated list of MailAddress's // // Throws a FormatException if any MailAddress is invalid. internal static IList<MailAddress> ParseMultipleAddresses(string data) { IList<MailAddress> results = new List<MailAddress>(); int index = data.Length - 1; while (index >= 0) { // Because we're parsing in reverse, we must make an effort to preserve the order of the addresses. results.Insert(0, MailAddressParser.ParseAddress(data, true, ref index)); Debug.Assert(index == -1 || data[index] == MailBnfHelper.Comma, "separator not found while parsing multiple addresses"); index--; } return results; } // // Parse a single MailAddress, potentially from a list. // // Preconditions: // - Index must be within the bounds of the data string. // - The data string must not be null or empty // // Postconditions: // - Returns a valid MailAddress object parsed from the string // - For a single MailAddress index is set to -1 // - For a list data[index] is the comma separator or -1 if the end of the data string was reached. // // Throws a FormatException if any part of the MailAddress is invalid. private static MailAddress ParseAddress(string data, bool expectMultipleAddresses, ref int index) { Debug.Assert(!String.IsNullOrEmpty(data)); Debug.Assert(index >= 0 && index < data.Length, "Index out of range: " + index + ", " + data.Length); // Parsed components to be assembled as a MailAddress later string domain = null; string localPart = null; string displayName = null; // Skip comments and whitespace index = ReadCfwsAndThrowIfIncomplete(data, index); // Do we expect angle brackets around the address? // e.g. ("display name" <user@domain>) bool expectAngleBracket = false; if (data[index] == MailBnfHelper.EndAngleBracket) { expectAngleBracket = true; index--; } domain = ParseDomain(data, ref index); // The next character after the domain must be the '@' symbol if (data[index] != MailBnfHelper.At) { throw new FormatException(SR.MailAddressInvalidFormat); } // Skip the '@' symbol index--; localPart = ParseLocalPart(data, ref index, expectAngleBracket, expectMultipleAddresses); // Check for a matching angle bracket around the address if (expectAngleBracket) { if (index >= 0 && data[index] == MailBnfHelper.StartAngleBracket) { index--; // Skip the angle bracket // Skip white spaces, but leave comments, as they may be part of the display name. index = WhitespaceReader.ReadFwsReverse(data, index); } else { // Mismatched angle brackets, throw throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, (index >= 0 ? data[index] : MailBnfHelper.EndAngleBracket))); } } // Is there anything left to parse? // There could still be a display name or another address if (index >= 0 && !(expectMultipleAddresses && data[index] == MailBnfHelper.Comma)) { displayName = ParseDisplayName(data, ref index, expectMultipleAddresses); } else { displayName = String.Empty; } return new MailAddress(displayName, localPart, domain); } // Read through a section of CFWS. If we reach the end of the data string then throw because not enough of the // MailAddress components were found. private static int ReadCfwsAndThrowIfIncomplete(string data, int index) { index = WhitespaceReader.ReadCfwsReverse(data, index); if (index < 0) { // More components were expected. Incomplete address, invalid throw new FormatException(SR.MailAddressInvalidFormat); } return index; } // Parses the domain section of an address. The domain may be in dot-atom format or surrounded by square // brackets in domain-literal format. // e.g. <[email protected]> or <user@[whatever I want]> // // Preconditions: // - data[index] is just inside of the angle brackets (if any). // // Postconditions: // - data[index] should refer to the '@' symbol // - returns the parsed domain, including any square brackets for domain-literals // // Throws a FormatException: // - For invalid un-escaped chars, including Unicode // - If the start of the data string is reached private static string ParseDomain(string data, ref int index) { // Skip comments and whitespace index = ReadCfwsAndThrowIfIncomplete(data, index); // Mark one end of the domain component int startingIndex = index; // Is the domain component in domain-literal format or dot-atom format? if (data[index] == MailBnfHelper.EndSquareBracket) { index = DomainLiteralReader.ReadReverse(data, index); } else { index = DotAtomReader.ReadReverse(data, index); } string domain = data.Substring(index + 1, startingIndex - index); // Skip comments and whitespace index = ReadCfwsAndThrowIfIncomplete(data, index); return NormalizeOrThrow(domain); } // Parses the local-part section of an address. The local-part may be in dot-atom format or // quoted-string format. e.g. <user.name@domain> or <"user name"@domain> // We do not support the obsolete formats of user."name"@domain, "user".name@domain, or "user"."name"@domain. // // Preconditions: // - data[index + 1] is the '@' symbol // // Postconditions: // - data[index] should refer to the '<', if any, otherwise the next non-CFWS char. // - index == -1 if the beginning of the data string has been reached. // - returns the parsed local-part, including any bounding quotes around quoted-strings // // Throws a FormatException: // - For invalid un-escaped chars, including Unicode // - If the final value of data[index] is not a valid character to precede the local-part private static string ParseLocalPart(string data, ref int index, bool expectAngleBracket, bool expectMultipleAddresses) { // Skip comments and whitespace index = ReadCfwsAndThrowIfIncomplete(data, index); // Mark the start of the local-part int startingIndex = index; // Is the local-part component in quoted-string format or dot-atom format? if (data[index] == MailBnfHelper.Quote) { index = QuotedStringFormatReader.ReadReverseQuoted(data, index, true); } else { index = DotAtomReader.ReadReverse(data, index); // Check that the local-part is properly separated from the next component. It may be separated by a // comment, white space, an expected angle bracket, a quote for the display-name, or an expected comma // before the next address. if (index >= 0 && !( MailBnfHelper.Whitespace.Contains(data[index]) // < local@domain > || data[index] == MailBnfHelper.EndComment // <(comment)local@domain> || (expectAngleBracket && data[index] == MailBnfHelper.StartAngleBracket) // <local@domain> || (expectMultipleAddresses && data[index] == MailBnfHelper.Comma) // local@dom,local@dom // Note: The following condition is more lax than the RFC. This is done so we could support // a common invalid formats as shown below. || data[index] == MailBnfHelper.Quote // "display"local@domain ) ) { throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[index])); } } string localPart = data.Substring(index + 1, startingIndex - index); index = WhitespaceReader.ReadCfwsReverse(data, index); return NormalizeOrThrow(localPart); } // Parses the display-name section of an address. In departure from the RFC, we attempt to read data in the // quoted-string format even if the bounding quotes are omitted. We also permit Unicode, which the RFC does // not allow for. // e.g. ("display name" <user@domain>) or (display name <user@domain>) // // Preconditions: // // Postconditions: // - data[index] should refer to the comma ',' separator, if any // - index == -1 if the beginning of the data string has been reached. // - returns the parsed display-name, excluding any bounding quotes around quoted-strings // // Throws a FormatException: // - For invalid un-escaped chars, except Unicode // - If the postconditions cannot be met. private static string ParseDisplayName(string data, ref int index, bool expectMultipleAddresses) { string displayName; // Whatever is left over must be the display name. The display name should be a single word/atom or a // quoted string, but for robustness we allow the quotes to be omitted, so long as we can find the comma // separator before the next address. // Read the comment (if any). If the display name is contained in quotes, the surrounding comments are // omitted. Otherwise, mark this end of the comment so we can include it as part of the display name. int firstNonCommentIndex = WhitespaceReader.ReadCfwsReverse(data, index); // Check to see if there's a quoted-string display name if (firstNonCommentIndex >= 0 && data[firstNonCommentIndex] == MailBnfHelper.Quote) { // The preceding comment was not part of the display name. Read just the quoted string. index = QuotedStringFormatReader.ReadReverseQuoted(data, firstNonCommentIndex, true); Debug.Assert(data[index + 1] == MailBnfHelper.Quote, "Mis-aligned index: " + index); // Do not include the bounding quotes on the display name int leftIndex = index + 2; displayName = data.Substring(leftIndex, firstNonCommentIndex - leftIndex); // Skip any CFWS after the display name index = WhitespaceReader.ReadCfwsReverse(data, index); // Check for completion. We are valid if we hit the end of the data string or if the rest of the data // belongs to another address. if (index >= 0 && !(expectMultipleAddresses && data[index] == MailBnfHelper.Comma)) { // If there was still data, only a comma could have been the next valid character throw new FormatException(SR.Format(SR.MailHeaderFieldInvalidCharacter, data[index])); } } else { // The comment (if any) should be part of the display name. int startingIndex = index; // Read until the dividing comma or the end of the line. index = QuotedStringFormatReader.ReadReverseUnQuoted(data, index, true, expectMultipleAddresses); Debug.Assert(index < 0 || data[index] == MailBnfHelper.Comma, "Mis-aligned index: " + index); // Do not include the Comma (if any), and because there were no bounding quotes, // trim extra whitespace. displayName = data.SubstringTrim(index + 1, startingIndex - index); } return NormalizeOrThrow(displayName); } internal static string NormalizeOrThrow(string input) { return input; } } }
// // DatabaseSource.cs // // Author: // Aaron Bockover <[email protected]> // Gabriel Burt <[email protected]> // // Copyright (C) 2005-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Linq; using System.Text; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Data; using Hyena.Query; using Hyena.Data.Sqlite; using Hyena.Collections; using Banshee.Base; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration; using Banshee.Query; namespace Banshee.Sources { public abstract class DatabaseSource : Source, ITrackModelSource, IFilterableSource, IDurationAggregator, IFileSizeAggregator { public event EventHandler FiltersChanged; protected delegate void TrackRangeHandler (DatabaseTrackListModel model, RangeCollection.Range range); protected DatabaseTrackListModel track_model; protected DatabaseAlbumListModel album_model; protected DatabaseArtistListModel artist_model; protected DatabaseQueryFilterModel<string> genre_model; private RateLimiter reload_limiter; public DatabaseSource (string generic_name, string name, string id, int order) : this (generic_name, name, id, order, null) { } public DatabaseSource (string generic_name, string name, string id, int order, Source parent) : base (generic_name, name, order, id) { if (parent != null) { SetParentSource (parent); } DatabaseSourceInitialize (); } protected DatabaseSource () : base () { } public void UpdateCounts () { DatabaseTrackModel.UpdateUnfilteredAggregates (); ever_counted = true; OnUpdated (); } public abstract void Save (); protected override void Initialize () { base.Initialize (); DatabaseSourceInitialize (); } protected virtual bool HasArtistAlbum { get { return true; } } public DatabaseTrackListModel DatabaseTrackModel { get { return track_model ?? (track_model = (Parent as DatabaseSource ?? this).CreateTrackModelFor (this)); } protected set { track_model = value; } } private IDatabaseTrackModelCache track_cache; protected IDatabaseTrackModelCache TrackCache { get { return track_cache ?? (track_cache = new DatabaseTrackModelCache<DatabaseTrackInfo> ( ServiceManager.DbConnection, UniqueId, DatabaseTrackModel, TrackProvider)); } set { track_cache = value; } } protected DatabaseTrackModelProvider<DatabaseTrackInfo> TrackProvider { get { return DatabaseTrackInfo.Provider; } } private void DatabaseSourceInitialize () { InitializeTrackModel (); current_filters_schema = CreateSchema<string[]> ("current_filters"); DatabaseSource filter_src = Parent as DatabaseSource ?? this; foreach (IFilterListModel filter in filter_src.CreateFiltersFor (this)) { AvailableFilters.Add (filter); DefaultFilters.Add (filter); } reload_limiter = new RateLimiter (RateLimitedReload); } protected virtual DatabaseTrackListModel CreateTrackModelFor (DatabaseSource src) { return new DatabaseTrackListModel (ServiceManager.DbConnection, TrackProvider, src); } protected virtual IEnumerable<IFilterListModel> CreateFiltersFor (DatabaseSource src) { if (!HasArtistAlbum) { yield break; } DatabaseArtistListModel artist_model = new DatabaseArtistListModel (src, src.DatabaseTrackModel, ServiceManager.DbConnection, src.UniqueId); DatabaseAlbumListModel album_model = new DatabaseAlbumListModel (src, src.DatabaseTrackModel, ServiceManager.DbConnection, src.UniqueId); DatabaseQueryFilterModel<string> genre_model = new DatabaseQueryFilterModel<string> (src, src.DatabaseTrackModel, ServiceManager.DbConnection, Catalog.GetString ("All Genres ({0})"), src.UniqueId, BansheeQuery.GenreField, "Genre"); if (this == src) { this.artist_model = artist_model; this.album_model = album_model; this.genre_model = genre_model; } yield return artist_model; yield return album_model; yield return genre_model; } protected virtual void AfterInitialized () { DatabaseTrackModel.Initialize (TrackCache); OnSetupComplete (); } protected virtual void InitializeTrackModel () { } protected bool NeedsReloadWhenFieldsChanged (Hyena.Query.QueryField [] fields) { if (fields == null) { return true; } foreach (QueryField field in fields) if (NeedsReloadWhenFieldChanged (field)) return true; return false; } private List<QueryField> query_fields; private QueryNode last_query; protected virtual bool NeedsReloadWhenFieldChanged (Hyena.Query.QueryField field) { if (field == null) return true; // If it's the artist or album name, then we care, since it affects the browser // FIXME this should be based on what filters (aka browsers) are active. InternetRadio, // for example, has only a Genre filter. if (field == Banshee.Query.BansheeQuery.ArtistField || field == Banshee.Query.BansheeQuery.AlbumField) { return true; } if (DatabaseTrackModel == null) { Log.Error ("DatabaseTrackModel should not be null in DatabaseSource.NeedsReloadWhenFieldChanged"); return false; } // If it's the field we're sorting by, then yes, we care var sort_column = DatabaseTrackModel.SortColumn; if (sort_column != null && sort_column.Field == field) { return true; } // Make sure the query isn't dependent on this field QueryNode query = DatabaseTrackModel.Query; if (query != null) { if (query != last_query) { query_fields = new List<QueryField> (query.GetFields ()); last_query = query; } if (query_fields.Contains (field)) return true; } return false; } #region Public Properties public override int Count { get { return ever_counted ? DatabaseTrackModel.UnfilteredCount : SavedCount; } } public override int FilteredCount { get { return DatabaseTrackModel.Count; } } public virtual TimeSpan Duration { get { return DatabaseTrackModel.Duration; } } public virtual long FileSize { get { return DatabaseTrackModel.FileSize; } } public override string FilterQuery { set { base.FilterQuery = value; DatabaseTrackModel.UserQuery = FilterQuery; ThreadAssist.SpawnFromMain (delegate { Reload (); }); } } public virtual bool CanAddTracks { get { return true; } } public virtual bool CanRemoveTracks { get { return true; } } public virtual bool CanDeleteTracks { get { return true; } } public virtual bool ConfirmRemoveTracks { get { return true; } } public virtual bool CanRepeat { get { return true; } } public virtual bool CanShuffle { get { return true; } } public override string TrackModelPath { get { return DBusServiceManager.MakeObjectPath (DatabaseTrackModel); } } public TrackListModel TrackModel { get { return DatabaseTrackModel; } } public virtual bool ShowBrowser { get { return true; } } public virtual bool Indexable { get { return false; } } private int saved_count; protected int SavedCount { get { return saved_count; } set { saved_count = value; } } public override bool AcceptsInputFromSource (Source source) { return CanAddTracks && source != this; } public override bool AcceptsUserInputFromSource (Source source) { return base.AcceptsUserInputFromSource (source) && CanAddTracks; } public override bool HasViewableTrackProperties { get { return true; } } #endregion #region Filters (aka Browsers) private IList<IFilterListModel> available_filters; public IList<IFilterListModel> AvailableFilters { get { return available_filters ?? (available_filters = new List<IFilterListModel> ()); } protected set { available_filters = value; } } private IList<IFilterListModel> default_filters; public IList<IFilterListModel> DefaultFilters { get { return default_filters ?? (default_filters = new List<IFilterListModel> ()); } protected set { default_filters = value; } } private IList<IFilterListModel> current_filters; public IList<IFilterListModel> CurrentFilters { get { if (current_filters == null) { current_filters = new List<IFilterListModel> (); string [] current = current_filters_schema.Get (); if (current != null) { foreach (string filter_name in current) { foreach (IFilterListModel filter in AvailableFilters) { if (filter.FilterName == filter_name) { current_filters.Add (filter); break; } } } } else { foreach (IFilterListModel filter in DefaultFilters) { current_filters.Add (filter); } } } return current_filters; } protected set { current_filters = value; } } public void ReplaceFilter (IFilterListModel old_filter, IFilterListModel new_filter) { int i = current_filters.IndexOf (old_filter); if (i != -1) { current_filters[i] = new_filter; SaveCurrentFilters (); } } public void AppendFilter (IFilterListModel filter) { if (current_filters.IndexOf (filter) == -1) { current_filters.Add (filter); SaveCurrentFilters (); } } public void RemoveFilter (IFilterListModel filter) { if (current_filters.Remove (filter)) { SaveCurrentFilters (); } } private void SaveCurrentFilters () { Reload (); if (current_filters == null) { current_filters_schema.Set (null); } else { string [] filters = new string [current_filters.Count]; int i = 0; foreach (IFilterListModel filter in CurrentFilters) { filters[i++] = filter.FilterName; } current_filters_schema.Set (filters); } EventHandler handler = FiltersChanged; if (handler != null) { handler (this, EventArgs.Empty); } } private SchemaEntry<string[]> current_filters_schema; #endregion #region Public Methods public virtual void Reload () { ever_counted = ever_reloaded = true; reload_limiter.Execute (); } protected void RateLimitedReload () { lock (track_model) { DatabaseTrackModel.Reload (); } OnUpdated (); Save (); } public virtual bool HasDependencies { get { return false; } } public void RemoveTrack (int index) { if (index != -1) { first_nonremoved_track = TrackModel[index - 1]; RemoveTrackRange (track_model, new RangeCollection.Range (index, index)); OnTracksRemoved (); } } public void RemoveTrack (DatabaseTrackInfo track) { RemoveTrack (track_model.IndexOf (track)); } public void RemoveTracks (Selection selection) { RemoveTracks (track_model, selection); } public void RemoveTracks (DatabaseTrackListModel model, Selection selection) { FindFirstNotRemovedTrack (model, selection); WithTrackSelection (model, selection, RemoveTrackRange); OnTracksRemoved (); } protected void FindFirstNotRemovedTrack (DatabaseTrackListModel model, Selection selection) { first_nonremoved_track = null; var playback_src = ServiceManager.PlaybackController.Source as DatabaseSource; if (playback_src != this && playback_src.Parent != this) return; int i = model.IndexOf (ServiceManager.PlayerEngine.CurrentTrack); if (!selection.Contains (i)) return; var range = selection.Ranges.First (r => r.Start <= i && i <= r.End); first_nonremoved_track = model[range.Start - 1]; } public void DeleteTracks (Selection selection) { DeleteTracks (track_model, selection); } public virtual void DeleteTracks (DatabaseTrackListModel model, Selection selection) { if (model == null) return; FindFirstNotRemovedTrack (model, selection); WithTrackSelection (model, selection, DeleteTrackRange); OnTracksDeleted (); } public bool AddSelectedTracks (Source source) { var track_src = source as ITrackModelSource; return AddSelectedTracks (source, track_src == null ? null : track_src.TrackModel.Selection); } public virtual bool AddSelectedTracks (Source source, Selection selection) { if (!AcceptsInputFromSource (source) || selection.Count == 0) return false; DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel; if (model == null) { return false; } WithTrackSelection (model, selection, AddTrackRange); OnTracksAdded (); OnUserNotifyUpdated (); return true; } public bool AddAllTracks (Source source) { var track_src = source as ITrackModelSource; if (track_src != null) { var selection = new Selection () { MaxIndex = track_src.TrackModel.Selection.MaxIndex }; selection.SelectAll (); return AddSelectedTracks (source, selection); } return false; } public virtual void RateSelectedTracks (int rating) { RateSelectedTracks (track_model, rating); } public virtual void RateSelectedTracks (DatabaseTrackListModel model, int rating) { Selection selection = model.Selection; if (selection.Count == 0) return; lock (model) { foreach (RangeCollection.Range range in selection.Ranges) { RateTrackRange (model, range, rating); } } OnTracksChanged (BansheeQuery.RatingField); // In case we updated the currently playing track DatabaseTrackInfo track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo; if (track != null) { track.Refresh (); ServiceManager.PlayerEngine.TrackInfoUpdated (); } } public override SourceMergeType SupportedMergeTypes { get { return SourceMergeType.All; } } public override void MergeSourceInput (Source source, SourceMergeType mergeType) { if (mergeType == SourceMergeType.Source || mergeType == SourceMergeType.All) { AddAllTracks (source); } else if (mergeType == SourceMergeType.ModelSelection) { AddSelectedTracks (source); } } #endregion #region Protected Methods protected virtual void OnTracksAdded () { Reload (); } protected void OnTracksChanged () { OnTracksChanged (null); } protected virtual void OnTracksChanged (params QueryField [] fields) { HandleTracksChanged (this, new TrackEventArgs (fields)); foreach (PrimarySource psource in PrimarySources) { psource.NotifyTracksChanged (fields); } } TrackInfo first_nonremoved_track = null; protected virtual void OnTracksDeleted () { PruneArtistsAlbums (); HandleTracksDeleted (this, new TrackEventArgs ()); foreach (PrimarySource psource in PrimarySources) { psource.NotifyTracksDeleted (); } SkipTrackIfRemoved (); } protected virtual void OnTracksRemoved () { PruneArtistsAlbums (); Reload (); SkipTrackIfRemoved (); } protected void SkipTrackIfRemoved () { var playback_src = ServiceManager.PlaybackController.Source as DatabaseSource; if (playback_src == null || (playback_src != this && playback_src.Parent != this)) return; var track = ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo; if (track == null || playback_src.DatabaseTrackModel.Contains (track)) return; Log.DebugFormat ("Playing track was removed from {0}, so stopping it", this); if (ServiceManager.PlaybackController.StopWhenFinished) { ServiceManager.PlayerEngine.Close (); } else { // Set the PriorTrack to the track before the one we removed, so that, if we're in non-shuffle mode, // we'll pick the first non-removed track after the one that was playing if (first_nonremoved_track != null) { ServiceManager.PlaybackController.PriorTrack = first_nonremoved_track; } ServiceManager.PlaybackController.Next (); } } // If we are a PrimarySource, return ourself and our children, otherwise if our Parent // is one, do so for it, otherwise do so for all PrimarySources. private IEnumerable<PrimarySource> PrimarySources { get { PrimarySource psource; if ((psource = this as PrimarySource) != null) { yield return psource; } else { if ((psource = Parent as PrimarySource) != null) { yield return psource; } else { foreach (Source source in ServiceManager.SourceManager.Sources) { if ((psource = source as PrimarySource) != null) { yield return psource; } } } } } } protected HyenaSqliteCommand rate_track_range_command; protected HyenaSqliteCommand RateTrackRangeCommand { get { if (rate_track_range_command == null) { if (track_model.CachesJoinTableEntries) { rate_track_range_command = new HyenaSqliteCommand (String.Format (@" UPDATE CoreTracks SET Rating = ?, DateUpdatedStamp = ? WHERE TrackID IN (SELECT TrackID FROM {0} WHERE {1} IN (SELECT ItemID FROM CoreCache WHERE ModelID = {2} LIMIT ?, ?))", track_model.JoinTable, track_model.JoinPrimaryKey, track_model.CacheId )); } else { rate_track_range_command = new HyenaSqliteCommand (String.Format (@" UPDATE CoreTracks SET Rating = ?, DateUpdatedStamp = ? WHERE TrackID IN ( SELECT ItemID FROM CoreCache WHERE ModelID = {0} LIMIT ?, ?)", track_model.CacheId )); } } return rate_track_range_command; } } private bool ever_reloaded = false, ever_counted = false; public override void Activate () { if (!ever_reloaded) Reload (); } public override void Deactivate () { DatabaseTrackModel.InvalidateCache (false); foreach (IFilterListModel filter in AvailableFilters) { filter.InvalidateCache (false); } } protected virtual void RemoveTrackRange (DatabaseTrackListModel model, RangeCollection.Range range) { Log.ErrorFormat ("RemoveTrackRange not implemented by {0}", this); } protected virtual void DeleteTrackRange (DatabaseTrackListModel model, RangeCollection.Range range) { Log.ErrorFormat ("DeleteTrackRange not implemented by {0}", this); } protected virtual void AddTrackRange (DatabaseTrackListModel model, RangeCollection.Range range) { Log.ErrorFormat ("AddTrackRange not implemented by {0}", this); } protected virtual void AddTrack (DatabaseTrackInfo track) { Log.ErrorFormat ("AddTrack not implemented by {0}", this); } protected virtual void RateTrackRange (DatabaseTrackListModel model, RangeCollection.Range range, int rating) { ServiceManager.DbConnection.Execute (RateTrackRangeCommand, rating, DateTime.Now, range.Start, range.End - range.Start + 1); } protected void WithTrackSelection (DatabaseTrackListModel model, TrackRangeHandler handler) { WithTrackSelection (model, model.Selection, handler); } protected void WithTrackSelection (DatabaseTrackListModel model, Selection selection, TrackRangeHandler handler) { if (selection.Count == 0) return; lock (model) { foreach (RangeCollection.Range range in selection.Ranges) { handler (model, range); } } } protected HyenaSqliteCommand prune_command; protected HyenaSqliteCommand PruneCommand { get { return prune_command ?? (prune_command = new HyenaSqliteCommand (String.Format ( @"DELETE FROM CoreCache WHERE ModelID = ? AND ItemID NOT IN (SELECT ArtistID FROM CoreTracks WHERE TrackID IN (SELECT {0})); DELETE FROM CoreCache WHERE ModelID = ? AND ItemID NOT IN (SELECT AlbumID FROM CoreTracks WHERE TrackID IN (SELECT {0}));", track_model.TrackIdsSql ), artist_model.CacheId, artist_model.CacheId, 0, artist_model.Count, album_model.CacheId, album_model.CacheId, 0, album_model.Count )); } } protected void InvalidateCaches () { track_model.InvalidateCache (true); foreach (IFilterListModel filter in CurrentFilters) { filter.InvalidateCache (true); } } protected virtual void PruneArtistsAlbums () { //Console.WriteLine ("Pruning with {0}", PruneCommand.Text); //ServiceManager.DbConnection.Execute (PruneCommand); } protected virtual void HandleTracksAdded (Source sender, TrackEventArgs args) { } protected virtual void HandleTracksChanged (Source sender, TrackEventArgs args) { } protected virtual void HandleTracksDeleted (Source sender, TrackEventArgs args) { } #endregion } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_FULL_CONSOLE using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Threading; using IronPython.Compiler; using IronPython.Modules; using IronPython.Runtime; using IronPython.Runtime.Exceptions; using IronPython.Runtime.Operations; using Microsoft.Scripting; using Microsoft.Scripting.Hosting.Shell; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; namespace IronPython.Hosting { /// <summary> /// A simple Python command-line should mimic the standard python.exe /// </summary> public sealed class PythonCommandLine : CommandLine { private PythonContext PythonContext { get { return (PythonContext)Language; } } private new PythonConsoleOptions Options { get { return (PythonConsoleOptions)base.Options; } } public PythonCommandLine() { } protected override string/*!*/ Logo { get { return GetLogoDisplay(); } } /// <summary> /// Returns the display look for IronPython. /// /// The returned string uses This \n instead of Environment.NewLine for it's line seperator /// because it is intended to be outputted through the Python I/O system. /// </summary> public static string GetLogoDisplay() { return PythonContext.GetVersionString() + "\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n"; } private int GetEffectiveExitCode(SystemExitException/*!*/ e) { object nonIntegerCode; int exitCode = e.GetExitCode(out nonIntegerCode); if (nonIntegerCode != null) { Console.WriteLine(nonIntegerCode.ToString(), Style.Error); } return exitCode; } protected override void Shutdown() { try { Language.Shutdown(); } catch (Exception e) { Console.WriteLine("", Style.Error); Console.WriteLine("Error in sys.exitfunc:", Style.Error); Console.Write(Language.FormatException(e), Style.Error); } } protected override int Run() { if (Options.ModuleToRun != null) { // PEP 338 support - http://www.python.org/dev/peps/pep-0338 // This requires the presence of the Python standard library or // an equivalent runpy.py which defines a run_module method. // import the runpy module object runpy, runMod; try { runpy = Importer.Import( PythonContext.SharedContext, "runpy", PythonTuple.EMPTY, 0 ); } catch (Exception) { Console.WriteLine("Could not import runpy module", Style.Error); return -1; } // get the run_module method try { runMod = PythonOps.GetBoundAttr(PythonContext.SharedContext, runpy, "run_module"); } catch (Exception) { Console.WriteLine("Could not access runpy.run_module", Style.Error); return -1; } // call it with the name of the module to run try { PythonOps.CallWithKeywordArgs( PythonContext.SharedContext, runMod, new object[] { Options.ModuleToRun, "__main__", ScriptingRuntimeHelpers.True }, new string[] { "run_name", "alter_sys" } ); } catch (SystemExitException e) { object dummy; return e.GetExitCode(out dummy); } return 0; } int result = base.Run(); // Check if IRONPYTHONINSPECT was set during execution string inspectLine = Environment.GetEnvironmentVariable("IRONPYTHONINSPECT"); if (inspectLine != null && !Options.Introspection) result = RunInteractiveLoop(); return result; } #region Initialization protected override void Initialize() { Debug.Assert(Language != null); base.Initialize(); Console.Output = new OutputWriter(PythonContext, false); Console.ErrorOutput = new OutputWriter(PythonContext, true); // TODO: must precede path initialization! (??? - test test_importpkg.py) int pathIndex = PythonContext.PythonOptions.SearchPaths.Count; Language.DomainManager.LoadAssembly(typeof(string).Assembly); Language.DomainManager.LoadAssembly(typeof(System.Diagnostics.Debug).Assembly); InitializePath(ref pathIndex); InitializeModules(); InitializeExtensionDLLs(); ImportSite(); // Equivalent to -i command line option // Check if IRONPYTHONINSPECT was set before execution string inspectLine = Environment.GetEnvironmentVariable("IRONPYTHONINSPECT"); if (inspectLine != null) Options.Introspection = true; // If running in console mode (including with -c), the current working directory should be // the first entry in sys.path. If running a script file, however, the CWD should not be added; // instead, the script's containg folder should be added. string fullPath = "."; // this is a valid path resolving to current working dir. Pinky-swear. if (Options.Command == null && Options.FileName != null) { if (Options.FileName == "-") { Options.FileName = "<stdin>"; } else { #if !SILVERLIGHT if (Directory.Exists(Options.FileName)) { Options.FileName = Path.Combine(Options.FileName, "__main__.py"); } if (!File.Exists(Options.FileName)) { Console.WriteLine( String.Format( System.Globalization.CultureInfo.InvariantCulture, "File {0} does not exist.", Options.FileName), Style.Error); Environment.Exit(1); } #endif fullPath = Path.GetDirectoryName( Language.DomainManager.Platform.GetFullPath(Options.FileName) ); } } PythonContext.InsertIntoPath(0, fullPath); PythonContext.MainThread = Thread.CurrentThread; } protected override Scope/*!*/ CreateScope() { var modCtx = new ModuleContext(new PythonDictionary(), PythonContext); modCtx.Features = ModuleOptions.None; modCtx.InitializeBuiltins(true); PythonContext.PublishModule("__main__", modCtx.Module); modCtx.Globals["__doc__"] = null; modCtx.Globals["__name__"] = "__main__"; return modCtx.GlobalScope; } private void InitializePath(ref int pathIndex) { #if !SILVERLIGHT // paths, environment vars if (!Options.IgnoreEnvironmentVariables) { string path = Environment.GetEnvironmentVariable("IRONPYTHONPATH"); if (path != null && path.Length > 0) { string[] paths = path.Split(Path.PathSeparator); foreach (string p in paths) { PythonContext.InsertIntoPath(pathIndex++, p); } } } #endif } private void InitializeModules() { string executable = ""; string prefix = null; #if !SILVERLIGHT // paths Assembly entryAssembly = Assembly.GetEntryAssembly(); //Can be null if called from unmanaged code (VS integration scenario) if (entryAssembly != null) { executable = entryAssembly.Location; prefix = Path.GetDirectoryName(executable); } // Make sure there an IronPython Lib directory, and if not keep looking up while (prefix != null && !File.Exists(Path.Combine(prefix, "Lib/os.py"))) { prefix = Path.GetDirectoryName(prefix); } #endif PythonContext.SetHostVariables(prefix ?? "", executable, null); } /// <summary> /// Loads any extension DLLs present in sys.prefix\DLLs directory and adds references to them. /// /// This provides an easy drop-in location for .NET assemblies which should be automatically referenced /// (exposed via import), COM libraries, and pre-compiled Python code. /// </summary> private void InitializeExtensionDLLs() { string dir = Path.Combine(PythonContext.InitialPrefix, "DLLs"); if (Directory.Exists(dir)) { foreach (string file in Directory.GetFiles(dir)) { if (file.ToLower().EndsWith(".dll")) { try { ClrModule.AddReference(PythonContext.SharedContext, new FileInfo(file).Name); } catch { } } } } } private void ImportSite() { if (Options.SkipImportSite) return; try { Importer.ImportModule(PythonContext.SharedContext, null, "site", false, -1); } catch (Exception e) { Console.Write(Language.FormatException(e), Style.Error); } } #endregion #region Interactive protected override int RunInteractive() { PrintLogo(); if (Scope == null) { Scope = CreateScope(); } int result = 1; try { RunStartup(); result = 0; } catch (SystemExitException pythonSystemExit) { return GetEffectiveExitCode(pythonSystemExit); } catch (Exception) { } var sys = Engine.GetSysModule(); sys.SetVariable("ps1", ">>> "); sys.SetVariable("ps2", "... "); result = RunInteractiveLoop(); return (int)result; } protected override string Prompt { get { object value; if (Engine.GetSysModule().TryGetVariable("ps1", out value)) { var context = ((PythonScopeExtension)Scope.GetExtension(Language.ContextId)).ModuleContext.GlobalContext; return PythonOps.ToString(context, value); } return ">>> "; } } public override string PromptContinuation { get { object value; if (Engine.GetSysModule().TryGetVariable("ps2", out value)) { var context = ((PythonScopeExtension)Scope.GetExtension(Language.ContextId)).ModuleContext.GlobalContext; return PythonOps.ToString(context, value); } return "... "; } } private void RunStartup() { if (Options.IgnoreEnvironmentVariables) return; #if !SILVERLIGHT // Environment.GetEnvironmentVariable string startup = Environment.GetEnvironmentVariable("IRONPYTHONSTARTUP"); if (startup != null && startup.Length > 0) { if (Options.HandleExceptions) { try { ExecuteCommand(Engine.CreateScriptSourceFromFile(startup)); } catch (Exception e) { if (e is SystemExitException) throw; Console.Write(Language.FormatException(e), Style.Error); } } else { ExecuteCommand(Engine.CreateScriptSourceFromFile(startup)); } } #endif } protected override int? TryInteractiveAction() { try { try { return TryInteractiveActionWorker(); } finally { // sys.exc_info() is normally cleared after functions exit. But interactive console enters statements // directly instead of using functions. So clear explicitly. PythonOps.ClearCurrentException(); } } catch (SystemExitException se) { return GetEffectiveExitCode(se); } } /// <summary> /// Attempts to run a single interaction and handle any language-specific /// exceptions. Base classes can override this and call the base implementation /// surrounded with their own exception handling. /// /// Returns null if successful and execution should continue, or an exit code. /// </summary> private int? TryInteractiveActionWorker() { int? result = null; try { result = RunOneInteraction(); #if !FEATURE_EXCEPTION_STATE } catch (ThreadAbortException) { #else } catch (ThreadAbortException tae) { KeyboardInterruptException pki = tae.ExceptionState as KeyboardInterruptException; if (pki != null) { Console.WriteLine(Language.FormatException(tae), Style.Error); Thread.ResetAbort(); } #endif } return result; } /// <summary> /// Parses a single interactive command and executes it. /// /// Returns null if successful and execution should continue, or the appropiate exit code. /// </summary> private int? RunOneInteraction() { bool continueInteraction; string s = ReadStatement(out continueInteraction); if (continueInteraction == false) { PythonContext.DispatchCommand(null); // Notify dispatcher that we're done return 0; } if (String.IsNullOrEmpty(s)) { // Is it an empty line? Console.Write(String.Empty, Style.Out); return null; } SourceUnit su = Language.CreateSnippet(s, "<stdin>", SourceCodeKind.InteractiveCode); PythonCompilerOptions pco = (PythonCompilerOptions)Language.GetCompilerOptions(Scope); pco.Module |= ModuleOptions.ExecOrEvalCode; Action action = delegate() { try { su.Compile(pco, ErrorSink).Run(Scope); } catch (Exception e) { if (e is SystemExitException) { throw; } // Need to handle exceptions in the delegate so that they're not wrapped // in a TargetInvocationException UnhandledException(e); } }; try { PythonContext.DispatchCommand(action); } catch (SystemExitException sx) { object dummy; return sx.GetExitCode(out dummy); } return null; } protected override ErrorSink/*!*/ ErrorSink { get { return ThrowingErrorSink.Default; } } protected override int GetNextAutoIndentSize(string text) { return Parser.GetNextAutoIndentSize(text, Options.AutoIndentSize); } #endregion #region Command protected override int RunCommand(string command) { if (Options.HandleExceptions) { try { return RunCommandWorker(command); } catch (Exception e) { Console.Write(Language.FormatException(e), Style.Error); return 1; } } return RunCommandWorker(command); } private int RunCommandWorker(string command) { ScriptCode compiledCode; ModuleOptions modOpt = ModuleOptions.Optimized | ModuleOptions.ModuleBuiltins; if (Options.SkipFirstSourceLine) { modOpt |= ModuleOptions.SkipFirstLine; } PythonModule module = PythonContext.CompileModule( "", // there is no file, it will be set to <module> "__main__", PythonContext.CreateSnippet(command, SourceCodeKind.File), modOpt, out compiledCode); PythonContext.PublishModule("__main__", module); Scope = module.Scope; try { compiledCode.Run(Scope); } catch (SystemExitException pythonSystemExit) { // disable introspection when exited: Options.Introspection = false; return GetEffectiveExitCode(pythonSystemExit); } return 0; } #endregion #region File protected override int RunFile(string/*!*/ fileName) { int result = 1; if (Options.HandleExceptions) { try { result = RunFileWorker(fileName); } catch (Exception e) { Console.Write(Language.FormatException(e), Style.Error); } } else { result = RunFileWorker(fileName); } return result; } private int RunFileWorker(string/*!*/ fileName) { try { // There is no PEP for this case, only http://bugs.python.org/issue1739468 object importer; if (Importer.TryImportMainFromZip(DefaultContext.Default, fileName, out importer)) { return 0; } if (importer != null && importer.GetType() != typeof(PythonImport.NullImporter)) { Console.WriteLine(String.Format("can't find '__main__' module in '{0}'", fileName), Style.Error); return 0; } } catch (SystemExitException pythonSystemExit) { // disable introspection when exited: Options.Introspection = false; return GetEffectiveExitCode(pythonSystemExit); } // classic file ScriptCode compiledCode; ModuleOptions modOpt = ModuleOptions.Optimized | ModuleOptions.ModuleBuiltins; if(Options.SkipFirstSourceLine) { modOpt |= ModuleOptions.SkipFirstLine; } PythonModule module = PythonContext.CompileModule( fileName, "__main__", PythonContext.CreateFileUnit(String.IsNullOrEmpty(fileName) ? null : fileName, PythonContext.DefaultEncoding), modOpt, out compiledCode); PythonContext.PublishModule("__main__", module); Scope = module.Scope; try { compiledCode.Run(Scope); } catch (SystemExitException pythonSystemExit) { // disable introspection when exited: Options.Introspection = false; return GetEffectiveExitCode(pythonSystemExit); } return 0; } #endregion public override IList<string> GetGlobals(string name) { IList<string> res = base.GetGlobals(name); foreach (object builtinName in PythonContext.BuiltinModuleInstance.__dict__.Keys) { string strName = builtinName as string; if (strName != null && strName.StartsWith(name)) { res.Add(strName); } } return res; } protected override void UnhandledException(Exception e) { PythonOps.PrintException(PythonContext.SharedContext, e, Console); } private new PythonContext Language { get { return (PythonContext)base.Language; } } } } #endif
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Orleans.GrainDirectory; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime.GrainDirectory { internal class LocalGrainDirectory : MarshalByRefObject, ILocalGrainDirectory, ISiloStatusListener { /// <summary> /// list of silo members sorted by the hash value of their address /// </summary> private readonly List<SiloAddress> membershipRingList; private readonly HashSet<SiloAddress> membershipCache; private readonly AsynchAgent maintainer; private readonly Logger log; private readonly SiloAddress seed; internal ISiloStatusOracle Membership; // Consider: move these constants into an apropriate place internal const int HOP_LIMIT = 3; // forward a remote request no more than two times private static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(5); // Pause 5 seconds between forwards to let the membership directory settle down protected SiloAddress Seed { get { return seed; } } internal Logger Logger { get { return log; } } // logger is shared with classes that manage grain directory internal bool Running; internal SiloAddress MyAddress { get; private set; } internal IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> DirectoryCache { get; private set; } internal GrainDirectoryPartition DirectoryPartition { get; private set; } public RemoteGrainDirectory RemGrainDirectory { get; private set; } public RemoteGrainDirectory CacheValidator { get; private set; } private readonly TaskCompletionSource<bool> stopPreparationResolver; public Task StopPreparationCompletion { get { return stopPreparationResolver.Task; } } internal OrleansTaskScheduler Scheduler { get; private set; } internal GrainDirectoryHandoffManager HandoffManager { get; private set; } internal ISiloStatusListener CatalogSiloStatusListener { get; set; } private readonly CounterStatistic localLookups; private readonly CounterStatistic localSuccesses; private readonly CounterStatistic fullLookups; private readonly CounterStatistic cacheLookups; private readonly CounterStatistic cacheSuccesses; private readonly CounterStatistic registrationsIssued; private readonly CounterStatistic registrationsSingleActIssued; private readonly CounterStatistic unregistrationsIssued; private readonly CounterStatistic unregistrationsManyIssued; private readonly IntValueStatistic directoryPartitionCount; internal readonly CounterStatistic RemoteLookupsSent; internal readonly CounterStatistic RemoteLookupsReceived; internal readonly CounterStatistic LocalDirectoryLookups; internal readonly CounterStatistic LocalDirectorySuccesses; internal readonly CounterStatistic CacheValidationsSent; internal readonly CounterStatistic CacheValidationsReceived; internal readonly CounterStatistic RegistrationsLocal; internal readonly CounterStatistic RegistrationsRemoteSent; internal readonly CounterStatistic RegistrationsRemoteReceived; internal readonly CounterStatistic RegistrationsSingleActLocal; internal readonly CounterStatistic RegistrationsSingleActRemoteSent; internal readonly CounterStatistic RegistrationsSingleActRemoteReceived; internal readonly CounterStatistic UnregistrationsLocal; internal readonly CounterStatistic UnregistrationsRemoteSent; internal readonly CounterStatistic UnregistrationsRemoteReceived; internal readonly CounterStatistic UnregistrationsManyRemoteSent; internal readonly CounterStatistic UnregistrationsManyRemoteReceived; public LocalGrainDirectory(Silo silo) { log = LogManager.GetLogger("Orleans.GrainDirectory.LocalGrainDirectory"); MyAddress = silo.LocalMessageCenter.MyAddress; Scheduler = silo.LocalScheduler; membershipRingList = new List<SiloAddress>(); membershipCache = new HashSet<SiloAddress>(); silo.OrleansConfig.OnConfigChange("Globals/Caching", () => { lock (membershipCache) { DirectoryCache = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCache(silo.GlobalConfig); } }); maintainer = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCacheMaintainer(this, DirectoryCache); if (silo.GlobalConfig.SeedNodes.Count > 0) { seed = silo.GlobalConfig.SeedNodes.Contains(MyAddress.Endpoint) ? MyAddress : SiloAddress.New(silo.GlobalConfig.SeedNodes[0], 0); } stopPreparationResolver = new TaskCompletionSource<bool>(); DirectoryPartition = new GrainDirectoryPartition(); HandoffManager = new GrainDirectoryHandoffManager(this, silo.GlobalConfig); RemGrainDirectory = new RemoteGrainDirectory(this, Constants.DirectoryServiceId); CacheValidator = new RemoteGrainDirectory(this, Constants.DirectoryCacheValidatorId); // add myself to the list of members AddServer(MyAddress); Func<SiloAddress, string> siloAddressPrint = (SiloAddress addr) => String.Format("{0}/{1:X}", addr.ToLongString(), addr.GetConsistentHashCode()); localLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_ISSUED); localSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_SUCCESSES); fullLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_FULL_ISSUED); RemoteLookupsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_SENT); RemoteLookupsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_RECEIVED); LocalDirectoryLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_ISSUED); LocalDirectorySuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_SUCCESSES); cacheLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_ISSUED); cacheSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_SUCCESSES); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_HITRATIO, () => { long delta1, delta2; long curr1 = cacheSuccesses.GetCurrentValueAndDelta(out delta1); long curr2 = cacheLookups.GetCurrentValueAndDelta(out delta2); return String.Format("{0}, Delta={1}", (curr2 != 0 ? (float)curr1 / (float)curr2 : 0) ,(delta2 !=0 ? (float)delta1 / (float)delta2 : 0)); }); CacheValidationsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_SENT); CacheValidationsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_RECEIVED); registrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_ISSUED); RegistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_LOCAL); RegistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_SENT); RegistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_RECEIVED); registrationsSingleActIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_ISSUED); RegistrationsSingleActLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_LOCAL); RegistrationsSingleActRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_SENT); RegistrationsSingleActRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_RECEIVED); unregistrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_ISSUED); UnregistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_LOCAL); UnregistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_SENT); UnregistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_RECEIVED); unregistrationsManyIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_ISSUED); UnregistrationsManyRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_SENT); UnregistrationsManyRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_RECEIVED); directoryPartitionCount = IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_PARTITION_SIZE, () => DirectoryPartition.Count); IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGDISTANCE, () => RingDistanceToSuccessor()); FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGPERCENTAGE, () => (((float)RingDistanceToSuccessor()) / ((float)(int.MaxValue * 2L))) * 100); FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_AVERAGERINGPERCENTAGE, () => membershipRingList.Count == 0 ? 0 : ((float)100 / (float)membershipRingList.Count)); IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_RINGSIZE, () => membershipRingList.Count); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING, () => { lock (membershipCache) { return Utils.EnumerableToString(membershipRingList, siloAddressPrint); } }); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_PREDECESSORS, () => Utils.EnumerableToString(FindPredecessors(MyAddress, 1), siloAddressPrint)); StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_SUCCESSORS, () => Utils.EnumerableToString(FindSuccessors(MyAddress, 1), siloAddressPrint)); } public void Start() { Running = true; if (maintainer != null) { maintainer.Start(); } } // Note that this implementation stops processing directory change requests (Register, Unregister, etc.) when the Stop event is raised. // This means that there may be a short period during which no silo believes that it is the owner of directory information for a set of // grains (for update purposes), which could cause application requests that require a new activation to be created to time out. // The alternative would be to allow the silo to process requests after it has handed off its partition, in which case those changes // would receive successful responses but would not be reflected in the eventual state of the directory. // It's easy to change this, if we think the trade-off is better the other way. public void Stop(bool doOnStopHandoff) { // This will cause remote write requests to be forwarded to the silo that will become the new owner. // Requests might bounce back and forth for a while as membership stabilizes, but they will either be served by the // new owner of the grain, or will wind up failing. In either case, we avoid requests succeeding at this silo after we've // begun stopping, which could cause them to not get handed off to the new owner. Running = false; if (doOnStopHandoff) { HandoffManager.ProcessSiloStoppingEvent(); } else { MarkStopPreparationCompleted(); } if (maintainer != null) { maintainer.Stop(); } DirectoryCache.Clear(); } internal void MarkStopPreparationCompleted() { stopPreparationResolver.TrySetResult(true); } internal void MarkStopPreparationFailed(Exception ex) { stopPreparationResolver.TrySetException(ex); } #region Handling membership events protected void AddServer(SiloAddress silo) { lock (membershipCache) { if (membershipCache.Contains(silo)) { // we have already cached this silo return; } membershipCache.Add(silo); // insert new silo in the sorted order long hash = silo.GetConsistentHashCode(); // Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former. // Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then // 'index' will get 0, as needed. int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1; membershipRingList.Insert(index, silo); HandoffManager.ProcessSiloAddEvent(silo); if (log.IsVerbose) log.Verbose("Silo {0} added silo {1}", MyAddress, silo); } } protected void RemoveServer(SiloAddress silo, SiloStatus status) { lock (membershipCache) { if (!membershipCache.Contains(silo)) { // we have already removed this silo return; } if (CatalogSiloStatusListener != null) { try { // only call SiloStatusChangeNotification once on the catalog and the order is important: call BEFORE updating membershipRingList. CatalogSiloStatusListener.SiloStatusChangeNotification(silo, status); } catch (Exception exc) { log.Error(ErrorCode.Directory_SiloStatusChangeNotification_Exception, String.Format("CatalogSiloStatusListener.SiloStatusChangeNotification has thrown an exception when notified about removed silo {0}.", silo.ToStringWithHashCode()), exc); } } // the call order is important HandoffManager.ProcessSiloRemoveEvent(silo); membershipCache.Remove(silo); membershipRingList.Remove(silo); AdjustLocalDirectory(silo); AdjustLocalCache(silo); if (log.IsVerbose) log.Verbose("Silo {0} removed silo {1}", MyAddress, silo); } } /// <summary> /// Adjust local directory following the removal of a silo by droping all activations located on the removed silo /// </summary> /// <param name="removedSilo"></param> protected void AdjustLocalDirectory(SiloAddress removedSilo) { var activationsToRemove = (from pair in DirectoryPartition.GetItems() from pair2 in pair.Value.Instances.Where(pair3 => pair3.Value.SiloAddress.Equals(removedSilo)) select new Tuple<GrainId, ActivationId>(pair.Key, pair2.Key)).ToList(); // drop all records of activations located on the removed silo foreach (var activation in activationsToRemove) { DirectoryPartition.RemoveActivation(activation.Item1, activation.Item2, true); } } /// Adjust local cache following the removal of a silo by droping: /// 1) entries that point to activations located on the removed silo /// 2) entries for grains that are now owned by this silo (me) /// 3) entries for grains that were owned by this removed silo - we currently do NOT do that. /// If we did 3, we need to do that BEFORE we change the membershipRingList (based on old Membership). /// We don't do that since first cache refresh handles that. /// Second, since Membership events are not guaranteed to be ordered, we may remove a cache entry that does not really point to a failed silo. /// To do that properly, we need to store for each cache entry who was the directory owner that registered this activation (the original partition owner). protected void AdjustLocalCache(SiloAddress removedSilo) { // remove all records of activations located on the removed silo foreach (Tuple<GrainId, IReadOnlyList<Tuple<SiloAddress, ActivationId>>, int> tuple in DirectoryCache.KeyValues) { // 2) remove entries now owned by me (they should be retrieved from my directory partition) if (MyAddress.Equals(CalculateTargetSilo(tuple.Item1))) { DirectoryCache.Remove(tuple.Item1); } // 1) remove entries that point to activations located on the removed silo RemoveActivations(DirectoryCache, tuple.Item1, tuple.Item2, tuple.Item3, t => t.Item1.Equals(removedSilo)); } } internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count) { lock (membershipCache) { int index = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members"); return null; } var result = new List<SiloAddress>(); int numMembers = membershipRingList.Count; for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--) { result.Add(membershipRingList[(i + numMembers) % numMembers]); } return result; } } internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count) { lock (membershipCache) { int index = membershipRingList.FindIndex(elem => elem.Equals(silo)); if (index == -1) { log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members"); return null; } var result = new List<SiloAddress>(); int numMembers = membershipRingList.Count; for (int i = index + 1; i % numMembers != index && result.Count < count; i++) { result.Add(membershipRingList[i % numMembers]); } return result; } } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { // This silo's status has changed if (Equals(updatedSilo, MyAddress)) { if (status == SiloStatus.Stopping || status.Equals(SiloStatus.ShuttingDown)) { // QueueAction up the "Stop" to run on a system turn Scheduler.QueueAction(() => Stop(true), CacheValidator.SchedulingContext).Ignore(); } else if (status == SiloStatus.Dead) { // QueueAction up the "Stop" to run on a system turn Scheduler.QueueAction(() => Stop(false), CacheValidator.SchedulingContext).Ignore(); } } else // Status change for some other silo { if (status.IsTerminating()) { // QueueAction up the "Remove" to run on a system turn Scheduler.QueueAction(() => RemoveServer(updatedSilo, status), CacheValidator.SchedulingContext).Ignore(); } else if (status.Equals(SiloStatus.Active)) // do not do anything with SiloStatus.Starting -- wait until it actually becomes active { // QueueAction up the "Remove" to run on a system turn Scheduler.QueueAction(() => AddServer(updatedSilo), CacheValidator.SchedulingContext).Ignore(); } } } private bool IsValidSilo(SiloAddress silo) { if (Membership == null) Membership = Silo.CurrentSilo.LocalSiloStatusOracle; return Membership.IsFunctionalDirectory(silo); } #endregion /// <summary> /// Finds the silo that owns the directory information for the given grain ID. /// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true, /// this is the only silo known, and this silo is stopping. /// </summary> /// <param name="grainId"></param> /// <param name="excludeThisSiloIfStopping"></param> /// <returns></returns> public SiloAddress CalculateTargetSilo(GrainId grainId, bool excludeThisSiloIfStopping = true) { // give a special treatment for special grains if (grainId.IsSystemTarget) { if (log.IsVerbose2) log.Verbose2("Silo {0} looked for a system target {1}, returned {2}", MyAddress, grainId, MyAddress); // every silo owns its system targets return MyAddress; } if (Constants.SystemMembershipTableId.Equals(grainId)) { if (Seed == null) { string grainName; if (!Constants.TryGetSystemGrainName(grainId, out grainName)) grainName = "MembershipTableGrain"; var errorMsg = grainName + " cannot run without Seed node - please check your silo configuration file and make sure it specifies a SeedNode element. " + " Alternatively, you may want to use AzureTable for LivenessType."; throw new ArgumentException(errorMsg, "grainId = " + grainId); } // Directory info for the membership table grain has to be located on the primary (seed) node, for bootstrapping if (log.IsVerbose2) log.Verbose2("Silo {0} looked for a special grain {1}, returned {2}", MyAddress, grainId, Seed); return Seed; } SiloAddress siloAddress; int hash = unchecked((int)grainId.GetUniformHashCode()); lock (membershipCache) { if (membershipRingList.Count == 0) { // If the membership ring is empty, then we're the owner by default unless we're stopping. return excludeThisSiloIfStopping && !Running ? null : MyAddress; } // excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method. bool excludeMySelf = !Running && excludeThisSiloIfStopping; // need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes siloAddress = membershipRingList.FindLast(siloAddr => (siloAddr.GetConsistentHashCode() <= hash) && (!siloAddr.Equals(MyAddress) || !excludeMySelf)); if (siloAddress == null) { // If not found in the traversal, last silo will do (we are on a ring). // We checked above to make sure that the list isn't empty, so this should always be safe. siloAddress = membershipRingList[membershipRingList.Count - 1]; // Make sure it's not us... if (siloAddress.Equals(MyAddress) && excludeMySelf) { siloAddress = membershipRingList.Count > 1 ? membershipRingList[membershipRingList.Count - 2] : null; } } } if (log.IsVerbose2) log.Verbose2("Silo {0} calculated directory partition owner silo {1} for grain {2}: {3} --> {4}", MyAddress, siloAddress, grainId, hash, siloAddress.GetConsistentHashCode()); return siloAddress; } #region Implementation of ILocalGrainDirectory public SiloAddress CheckIfShouldForward(GrainId grainId, int hopCount, string operationDescription) { SiloAddress owner = CalculateTargetSilo(grainId); if (owner == null) { // We don't know about any other silos, and we're stopping, so throw throw new InvalidOperationException("Grain directory is stopping"); } if (owner.Equals(MyAddress)) { // if I am the owner, perform the operation locally return null; } if (hopCount >= HOP_LIMIT) { // we are not forwarding because there were too many hops already throw new OrleansException(string.Format("Silo {0} is not owner of {1}, cannot forward {2} to owner {3} because hop limit is reached", MyAddress, grainId, operationDescription, owner)); } // forward to the silo that we think is the owner return owner; } public async Task<AddressAndTag> RegisterAsync(ActivationAddress address, bool singleActivation, int hopCount) { var counterStatistic = singleActivation ? (hopCount > 0 ? this.RegistrationsSingleActRemoteReceived : this.registrationsSingleActIssued) : (hopCount > 0 ? this.RegistrationsRemoteReceived : this.registrationsIssued); counterStatistic.Increment(); // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync(recheck)"); } if (forwardAddress == null) { (singleActivation ? RegistrationsSingleActLocal : RegistrationsLocal).Increment(); // we are the owner var registrar = RegistrarManager.Instance.GetRegistrarForGrain(address.Grain); return registrar.IsSynchronous ? registrar.Register(address, singleActivation) : await registrar.RegisterAsync(address, singleActivation); } else { (singleActivation ? RegistrationsSingleActRemoteSent : RegistrationsRemoteSent).Increment(); // otherwise, notify the owner AddressAndTag result = await GetDirectoryReference(forwardAddress).RegisterAsync(address, singleActivation, hopCount + 1); if (singleActivation) { // Caching optimization: // cache the result of a successfull RegisterSingleActivation call, only if it is not a duplicate activation. // this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup! if (result.Address == null) return result; if (!address.Equals(result.Address) || !IsValidSilo(address.Silo)) return result; var cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) }; // update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup. DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag); } else { if (IsValidSilo(address.Silo)) { // Caching optimization: // cache the result of a successfull RegisterActivation call, only if it is not a duplicate activation. // this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup! IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached; if (!DirectoryCache.LookUp(address.Grain, out cached)) { cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) }; } else { var newcached = new List<Tuple<SiloAddress, ActivationId>>(cached.Count + 1); newcached.AddRange(cached); newcached.Add(Tuple.Create(address.Silo, address.Activation)); cached = newcached; } // update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup. DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag); } } return result; } } public Task UnregisterConditionallyAsync(ActivationAddress addr) { // This is a no-op if the lazy registration delay is zero or negative return Silo.CurrentSilo.OrleansConfig.Globals.DirectoryLazyDeregistrationDelay <= TimeSpan.Zero ? TaskDone.Done : UnregisterAsync(addr, false, 0); } public async Task UnregisterAsync(ActivationAddress address, bool force, int hopCount) { (hopCount > 0 ? UnregistrationsRemoteReceived : unregistrationsIssued).Increment(); if (hopCount == 0) InvalidateCacheEntry(address); // see if the owner is somewhere else (returns null if we are owner) var forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardaddress != null) { await Task.Delay(RETRY_DELAY); forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync(recheck)"); } if (forwardaddress == null) { // we are the owner UnregistrationsLocal.Increment(); var registrar = RegistrarManager.Instance.GetRegistrarForGrain(address.Grain); if (registrar.IsSynchronous) registrar.Unregister(address, force); else await registrar.UnregisterAsync(address, force); } else { UnregistrationsRemoteSent.Increment(); // otherwise, notify the owner await GetDirectoryReference(forwardaddress).UnregisterAsync(address, force, hopCount + 1); } } private void AddToDictionary<K,V>(ref Dictionary<K, List<V>> dictionary, K key, V value) { if (dictionary == null) dictionary = new Dictionary<K,List<V>>(); List<V> list; if (! dictionary.TryGetValue(key, out list)) dictionary[key] = list = new List<V>(); list.Add(value); } // helper method to avoid code duplication inside UnregisterManyAsync private void UnregisterOrPutInForwardList(IEnumerable<ActivationAddress> addresses, int hopCount, ref Dictionary<SiloAddress, List<ActivationAddress>> forward, List<Task> tasks, string context) { foreach (var address in addresses) { // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, context); if (forwardAddress != null) AddToDictionary(ref forward, forwardAddress, address); else { // we are the owner UnregistrationsLocal.Increment(); var registrar = RegistrarManager.Instance.GetRegistrarForGrain(address.Grain); if (registrar.IsSynchronous) registrar.Unregister(address, true); else { tasks.Add(registrar.UnregisterAsync(address, true)); } } } } public async Task UnregisterManyAsync(List<ActivationAddress> addresses, int hopCount) { (hopCount > 0 ? UnregistrationsManyRemoteReceived : unregistrationsManyIssued).Increment(); Dictionary<SiloAddress, List<ActivationAddress>> forwardlist = null; var tasks = new List<Task>(); UnregisterOrPutInForwardList(addresses, hopCount, ref forwardlist, tasks, "UnregisterManyAsync"); // before forwarding to other silos, we insert a retry delay and re-check destination if (hopCount > 0 && forwardlist != null) { await Task.Delay(RETRY_DELAY); Dictionary<SiloAddress, List<ActivationAddress>> forwardlist2 = null; UnregisterOrPutInForwardList(forwardlist.SelectMany(kvp => kvp.Value), hopCount, ref forwardlist2, tasks, "UnregisterManyAsync(recheck)"); forwardlist = forwardlist2; } // forward the requests if (forwardlist != null) { foreach (var kvp in forwardlist) { UnregistrationsManyRemoteSent.Increment(); tasks.Add(GetDirectoryReference(kvp.Key).UnregisterManyAsync(kvp.Value, hopCount + 1)); } } // wait for all the requests to finish await Task.WhenAll(tasks); } public bool LocalLookup(GrainId grain, out AddressesAndTag result) { localLookups.Increment(); SiloAddress silo = CalculateTargetSilo(grain, false); // No need to check that silo != null since we're passing excludeThisSiloIfStopping = false if (log.IsVerbose) log.Verbose("Silo {0} tries to lookup for {1}-->{2} ({3}-->{4})", MyAddress, grain, silo, grain.GetUniformHashCode(), silo.GetConsistentHashCode()); // check if we own the grain if (silo.Equals(MyAddress)) { LocalDirectoryLookups.Increment(); result = GetLocalDirectoryData(grain); if (result.Addresses == null) { // it can happen that we cannot find the grain in our partition if there were // some recent changes in the membership if (log.IsVerbose2) log.Verbose2("LocalLookup mine {0}=null", grain); return false; } if (log.IsVerbose2) log.Verbose2("LocalLookup mine {0}={1}", grain, result.Addresses.ToStrings()); LocalDirectorySuccesses.Increment(); localSuccesses.Increment(); return true; } // handle cache result = new AddressesAndTag(); cacheLookups.Increment(); result.Addresses = GetLocalCacheData(grain); if (result.Addresses == null) { if (log.IsVerbose2) log.Verbose2("TryFullLookup else {0}=null", grain); return false; } if (log.IsVerbose2) log.Verbose2("LocalLookup cache {0}={1}", grain, result.Addresses.ToStrings()); cacheSuccesses.Increment(); localSuccesses.Increment(); return true; } public AddressesAndTag GetLocalDirectoryData(GrainId grain) { var result = DirectoryPartition.LookUpGrain(grain); if (result.Addresses != null) result.Addresses = result.Addresses.Where(addr => IsValidSilo(addr.Silo)).ToList(); return result; } public List<ActivationAddress> GetLocalCacheData(GrainId grain) { IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached; return DirectoryCache.LookUp(grain, out cached) ? cached.Select(elem => ActivationAddress.GetAddress(elem.Item1, grain, elem.Item2)).Where(addr => IsValidSilo(addr.Silo)).ToList() : null; } public async Task<AddressesAndTag> LookupAsync(GrainId grainId, int hopCount = 0) { (hopCount > 0 ? RemoteLookupsReceived : fullLookups).Increment(); // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync(recheck)"); } if (forwardAddress == null) { // we are the owner LocalDirectoryLookups.Increment(); var localResult = DirectoryPartition.LookUpGrain(grainId); if (localResult.Addresses == null) { // it can happen that we cannot find the grain in our partition if there were // some recent changes in the membership if (log.IsVerbose2) log.Verbose2("FullLookup mine {0}=none", grainId); localResult.Addresses = new List<ActivationAddress>(); localResult.VersionTag = GrainInfo.NO_ETAG; return localResult; } localResult.Addresses = localResult.Addresses.Where(addr => IsValidSilo(addr.Silo)).ToList(); if (log.IsVerbose2) log.Verbose2("FullLookup mine {0}={1}", grainId, localResult.Addresses.ToStrings()); LocalDirectorySuccesses.Increment(); return localResult; } else { // Just a optimization. Why sending a message to someone we know is not valid. if (!IsValidSilo(forwardAddress)) { throw new OrleansException(String.Format("Current directory at {0} is not stable to perform the lookup for grainId {1} (it maps to {2}, which is not a valid silo). Retry later.", MyAddress, grainId, forwardAddress)); } RemoteLookupsSent.Increment(); var result = await GetDirectoryReference(forwardAddress).LookupAsync(grainId, hopCount + 1); // update the cache result.Addresses = result.Addresses.Where(t => IsValidSilo(t.Silo)).ToList(); if (log.IsVerbose2) log.Verbose2("FullLookup remote {0}={1}", grainId, result.Addresses.ToStrings()); var entries = result.Addresses.Select(t => Tuple.Create(t.Silo, t.Activation)).ToList(); if (entries.Count > 0) DirectoryCache.AddOrUpdate(grainId, entries, result.VersionTag); return result; } } public async Task DeleteGrainAsync(GrainId grainId, int hopCount) { // see if the owner is somewhere else (returns null if we are owner) var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync"); // on all silos other than first, we insert a retry delay and recheck owner before forwarding if (hopCount > 0 && forwardAddress != null) { await Task.Delay(RETRY_DELAY); forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync(recheck)"); } if (forwardAddress == null) { // we are the owner var registrar = RegistrarManager.Instance.GetRegistrarForGrain(grainId); if (registrar.IsSynchronous) registrar.Delete(grainId); else await registrar.DeleteAsync(grainId); } else { // otherwise, notify the owner DirectoryCache.Remove(grainId); await GetDirectoryReference(forwardAddress).DeleteGrainAsync(grainId, hopCount + 1); } } public void InvalidateCacheEntry(ActivationAddress activationAddress) { int version; IReadOnlyList<Tuple<SiloAddress, ActivationId>> list; var grainId = activationAddress.Grain; var activationId = activationAddress.Activation; // look up grainId activations if (DirectoryCache.LookUp(grainId, out list, out version)) { RemoveActivations(DirectoryCache, grainId, list, version, t => t.Item2.Equals(activationId)); } } /// <summary> /// For testing purposes only. /// Returns the silo that this silo thinks is the primary owner of directory information for /// the provided grain ID. /// </summary> /// <param name="grain"></param> /// <returns></returns> public SiloAddress GetPrimaryForGrain(GrainId grain) { return CalculateTargetSilo(grain); } /// <summary> /// For testing purposes only. /// Returns the silos that this silo thinks hold copies of the directory information for /// the provided grain ID. /// </summary> /// <param name="grain"></param> /// <returns></returns> public List<SiloAddress> GetSilosHoldingDirectoryInformationForGrain(GrainId grain) { var primary = CalculateTargetSilo(grain); return FindPredecessors(primary, 1); } /// <summary> /// For testing purposes only. /// Returns the directory information held by the local silo for the provided grain ID. /// The result will be null if no information is held. /// </summary> /// <param name="grain"></param> /// <param name="isPrimary"></param> /// <returns></returns> public List<ActivationAddress> GetLocalDataForGrain(GrainId grain, out bool isPrimary) { var primary = CalculateTargetSilo(grain); List<ActivationAddress> backupData = HandoffManager.GetHandedOffInfo(grain); if (MyAddress.Equals(primary)) { log.Assert(ErrorCode.DirectoryBothPrimaryAndBackupForGrain, backupData == null, "Silo contains both primary and backup directory data for grain " + grain); isPrimary = true; return GetLocalDirectoryData(grain).Addresses; } isPrimary = false; return backupData; } #endregion public override string ToString() { var sb = new StringBuilder(); long localLookupsDelta; long localLookupsCurrent = localLookups.GetCurrentValueAndDelta(out localLookupsDelta); long localLookupsSucceededDelta; long localLookupsSucceededCurrent = localSuccesses.GetCurrentValueAndDelta(out localLookupsSucceededDelta); long fullLookupsDelta; long fullLookupsCurrent = fullLookups.GetCurrentValueAndDelta(out fullLookupsDelta); long directoryPartitionSize = directoryPartitionCount.GetCurrentValue(); sb.AppendLine("Local Grain Directory:"); sb.AppendFormat(" Local partition: {0} entries", directoryPartitionSize).AppendLine(); sb.AppendLine(" Since last call:"); sb.AppendFormat(" Local lookups: {0}", localLookupsDelta).AppendLine(); sb.AppendFormat(" Local found: {0}", localLookupsSucceededDelta).AppendLine(); if (localLookupsCurrent > 0) sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededDelta) / localLookupsDelta).AppendLine(); sb.AppendFormat(" Full lookups: {0}", fullLookupsDelta).AppendLine(); sb.AppendLine(" Since start:"); sb.AppendFormat(" Local lookups: {0}", localLookupsCurrent).AppendLine(); sb.AppendFormat(" Local found: {0}", localLookupsSucceededCurrent).AppendLine(); if (localLookupsCurrent > 0) sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededCurrent) / localLookupsCurrent).AppendLine(); sb.AppendFormat(" Full lookups: {0}", fullLookupsCurrent).AppendLine(); sb.Append(DirectoryCache.ToString()); return sb.ToString(); } private long RingDistanceToSuccessor() { long distance; List<SiloAddress> successorList = FindSuccessors(MyAddress, 1); if (successorList == null || successorList.Count == 0) { distance = 0; } else { SiloAddress successor = successorList.First(); distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor); } return distance; } private string RingDistanceToSuccessor_2() { const long ringSize = int.MaxValue * 2L; long distance; List<SiloAddress> successorList = FindSuccessors(MyAddress, 1); if (successorList == null || successorList.Count == 0) { distance = 0; } else { SiloAddress successor = successorList.First(); distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor); } double averageRingSpace = membershipRingList.Count == 0 ? 0 : (1.0 / (double)membershipRingList.Count); return string.Format("RingDistance={0:X}, %Ring Space {1:0.00000}%, Average %Ring Space {2:0.00000}%", distance, ((double)distance / (double)ringSize) * 100.0, averageRingSpace * 100.0); } private static long CalcRingDistance(SiloAddress silo1, SiloAddress silo2) { const long ringSize = int.MaxValue * 2L; long hash1 = silo1.GetConsistentHashCode(); long hash2 = silo2.GetConsistentHashCode(); if (hash2 > hash1) return hash2 - hash1; if (hash2 < hash1) return ringSize - (hash1 - hash2); return 0; } public string RingStatusToString() { var sb = new StringBuilder(); sb.AppendFormat("Silo address is {0}, silo consistent hash is {1:X}.", MyAddress, MyAddress.GetConsistentHashCode()).AppendLine(); sb.AppendLine("Ring is:"); lock (membershipCache) { foreach (var silo in membershipRingList) sb.AppendFormat(" Silo {0}, consistent hash is {1:X}", silo, silo.GetConsistentHashCode()).AppendLine(); } sb.AppendFormat("My predecessors: {0}", FindPredecessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")).AppendLine(); sb.AppendFormat("My successors: {0}", FindSuccessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")); return sb.ToString(); } internal IRemoteGrainDirectory GetDirectoryReference(SiloAddress silo) { return InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo); } private static void RemoveActivations(IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> directoryCache, GrainId key, IReadOnlyList<Tuple<SiloAddress, ActivationId>> activations, int version, Func<Tuple<SiloAddress, ActivationId>, bool> doRemove) { int removeCount = activations.Count(doRemove); if (removeCount == 0) { return; // nothing to remove, done here } if (activations.Count > removeCount) // still some left, update activation list. Note: Most of the time there should be only one activation { var newList = new List<Tuple<SiloAddress, ActivationId>>(activations.Count - removeCount); newList.AddRange(activations.Where(t => !doRemove(t))); directoryCache.AddOrUpdate(key, newList, version); } else // no activations left, remove from cache { directoryCache.Remove(key); } } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Vevo; using Vevo.Domain; using Vevo.Domain.DataInterfaces; using Vevo.Base.Domain; public partial class AdminAdvanced_MainControls_CouponList : AdminAdvancedBaseListControl { private void SetUpSearchFilter() { IList<TableSchemaItem> list = DataAccessContext.CouponRepository.GetTableSchema(); NameValueCollection renameList = new NameValueCollection(); renameList.Add( "CurrentQuantity", "Usage" ); uxSearchFilter.SetUpSchema( list, renameList, "UrlName" ); } private void PopulateControls() { if (!MainContext.IsPostBack) { RefreshGrid(); } if (uxGrid.Rows.Count > 0) { DeleteVisible( true ); uxPagingControl.Visible = true; } else { DeleteVisible( false ); uxPagingControl.Visible = false; } if (!IsAdminModifiable()) { uxAddButton.Visible = false; DeleteVisible( false ); } } private void DeleteVisible( bool value ) { uxDeleteButton.Visible = value; if (value) { if (AdminConfig.CurrentTestMode == AdminConfig.TestMode.Normal) { uxDeleteConfirmButton.TargetControlID = "uxDeleteButton"; uxConfirmModalPopup.TargetControlID = "uxDeleteButton"; } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } else { uxDeleteConfirmButton.TargetControlID = "uxDummyButton"; uxConfirmModalPopup.TargetControlID = "uxDummyButton"; } } private void SetUpGridSupportControls() { if (!MainContext.IsPostBack) { uxPagingControl.ItemsPerPages = AdminConfig.CouponItemsPerPage; SetUpSearchFilter(); } RegisterGridView( uxGrid, "CouponID" ); RegisterSearchFilter( uxSearchFilter ); RegisterPagingControl( uxPagingControl ); uxSearchFilter.BubbleEvent += new EventHandler( uxSearchFilter_BubbleEvent ); uxPagingControl.BubbleEvent += new EventHandler( uxPagingControl_BubbleEvent ); } protected void Page_Load( object sender, EventArgs e ) { SetUpGridSupportControls(); } protected void Page_PreRender( object sender, EventArgs e ) { PopulateControls(); } protected void uxDeleteButton_Click( object sender, EventArgs e ) { try { bool deleted = false; foreach (GridViewRow row in uxGrid.Rows) { CheckBox deleteCheck = (CheckBox) row.FindControl( "uxCheck" ); if (deleteCheck.Checked) { string id = row.Cells[1].Text.Trim(); DataAccessContext.CouponRepository.Delete( id ); deleted = true; } } if (deleted) { uxMessage.DisplayMessage( Resources.CouponMessages.DeleteSuccess ); } } catch (Exception ex) { uxMessage.DisplayException( ex ); } RefreshGrid(); if (uxGrid.Rows.Count == 0 && uxPagingControl.CurrentPage >= uxPagingControl.NumberOfPages) { uxPagingControl.CurrentPage = uxPagingControl.NumberOfPages; RefreshGrid(); } } protected void uxAddButton_Click( object sender, EventArgs e ) { MainContext.RedirectMainControl( "CouponAdd.ascx", "" ); } protected bool IsAmount( string discountType ) { if (discountType == "Price" || discountType == "BuyXDiscountYPrice") return true; else return false; } protected bool IsExpirationDate( string expirationType ) { if (expirationType == "Date") return true; else return false; } protected string ExpirationMessage( string expirationType, string expirationDate, string expirationQuantity, string type ) { if (expirationType == "Date" && type == "Date") return Convert.ToDateTime( expirationDate ).ToShortDateString(); else if (expirationType == "Quantity" && type == "Quantity") return expirationQuantity; else if (expirationType == "Both") { if (type == "Date") return String.Format( "{0}", Convert.ToDateTime( expirationDate ).ToShortDateString() ); else if (type == "Quantity") return String.Format( "{0}", expirationQuantity ); } return String.Empty; } protected string GetDiscountTypeText(object discountType) { String discountTypeText = discountType.ToString(); if (discountTypeText == "BuyXDiscountYPrice") discountTypeText = "Buy X Discount Y Price"; else if (discountTypeText == "BuyXDiscountYPercentage") discountTypeText = "Buy X Discount Y Percentage"; return discountTypeText; } protected string GetAmountText( object discountType, object amount, object percentage ) { if (IsAmount( discountType.ToString() )) return String.Format( "{0:n2}", amount ); else return percentage + "%"; } protected override void RefreshGrid() { int totalItems; uxGrid.DataSource = DataAccessContext.CouponRepository.SearchCoupon( GridHelper.GetFullSortText(), uxSearchFilter.SearchFilterObj, uxPagingControl.StartIndex, uxPagingControl.EndIndex, out totalItems ); uxPagingControl.NumberOfPages = (int) Math.Ceiling( (double) totalItems / uxPagingControl.ItemsPerPages ); uxGrid.DataBind(); } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Insights; using Microsoft.Azure.Management.Insights.Models; namespace Microsoft.Azure.Management.Insights { public static partial class AutoscaleOperationsExtensions { /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='autoscaleSettingName'> /// Required. The autoscale setting name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse CreateOrUpdateSetting(this IAutoscaleOperations operations, string resourceGroupName, string autoscaleSettingName, AutoscaleSettingCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAutoscaleOperations)s).CreateOrUpdateSettingAsync(resourceGroupName, autoscaleSettingName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='autoscaleSettingName'> /// Required. The autoscale setting name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CreateOrUpdateSettingAsync(this IAutoscaleOperations operations, string resourceGroupName, string autoscaleSettingName, AutoscaleSettingCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateSettingAsync(resourceGroupName, autoscaleSettingName, parameters, CancellationToken.None); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='autoscaleSettingName'> /// Required. The autoscale setting name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse DeleteSetting(this IAutoscaleOperations operations, string resourceGroupName, string autoscaleSettingName) { return Task.Factory.StartNew((object s) => { return ((IAutoscaleOperations)s).DeleteSettingAsync(resourceGroupName, autoscaleSettingName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='autoscaleSettingName'> /// Required. The autoscale setting name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteSettingAsync(this IAutoscaleOperations operations, string resourceGroupName, string autoscaleSettingName) { return operations.DeleteSettingAsync(resourceGroupName, autoscaleSettingName, CancellationToken.None); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='autoscaleSettingName'> /// Required. The autoscale setting name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AutoscaleSettingGetResponse GetSetting(this IAutoscaleOperations operations, string resourceGroupName, string autoscaleSettingName) { return Task.Factory.StartNew((object s) => { return ((IAutoscaleOperations)s).GetSettingAsync(resourceGroupName, autoscaleSettingName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='autoscaleSettingName'> /// Required. The autoscale setting name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AutoscaleSettingGetResponse> GetSettingAsync(this IAutoscaleOperations operations, string resourceGroupName, string autoscaleSettingName) { return operations.GetSettingAsync(resourceGroupName, autoscaleSettingName, CancellationToken.None); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='targetResourceUri'> /// Optional. The resource identifier of the target of the autoscale /// setting. /// </param> /// <returns> /// The List Autoscale settings operation response. /// </returns> public static AutoscaleSettingListResponse ListSettings(this IAutoscaleOperations operations, string resourceGroupName, string targetResourceUri) { return Task.Factory.StartNew((object s) => { return ((IAutoscaleOperations)s).ListSettingsAsync(resourceGroupName, targetResourceUri); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='targetResourceUri'> /// Optional. The resource identifier of the target of the autoscale /// setting. /// </param> /// <returns> /// The List Autoscale settings operation response. /// </returns> public static Task<AutoscaleSettingListResponse> ListSettingsAsync(this IAutoscaleOperations operations, string resourceGroupName, string targetResourceUri) { return operations.ListSettingsAsync(resourceGroupName, targetResourceUri, CancellationToken.None); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='autoscaleSettingName'> /// Required. The autoscale setting name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse UpdateSetting(this IAutoscaleOperations operations, string resourceGroupName, string autoscaleSettingName, AutoscaleSettingCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IAutoscaleOperations)s).UpdateSettingAsync(resourceGroupName, autoscaleSettingName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Insights.IAutoscaleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource name. /// </param> /// <param name='autoscaleSettingName'> /// Required. The autoscale setting name. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the operation. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> UpdateSettingAsync(this IAutoscaleOperations operations, string resourceGroupName, string autoscaleSettingName, AutoscaleSettingCreateOrUpdateParameters parameters) { return operations.UpdateSettingAsync(resourceGroupName, autoscaleSettingName, parameters, CancellationToken.None); } } }
// MIT License // // Copyright(c) 2022 ICARUS Consulting GmbH // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections; using System.Collections.Generic; using Yaapii.Atoms.Enumerable; using Yaapii.Atoms.Fail; using Yaapii.Atoms.List; using Yaapii.Atoms.Scalar; using Yaapii.Atoms.Text; namespace Yaapii.Atoms.Map { /// <summary> /// A dictionary whose values are retrieved only when accessing them. /// </summary> public sealed class LazyDict : IDictionary<string, string> { private readonly IDictionary<string, ScalarOf<string>> map; private readonly UnsupportedOperationException rejectReadException = new UnsupportedOperationException("Writing is not supported, it's a read-only map"); private readonly bool rejectBuildingAllValues; private readonly ScalarOf<bool> anyValueIsLazy; /// <summary> /// ctor /// </summary> public LazyDict(params IKvp[] kvps) : this(new LiveMany<IKvp>(kvps), true) { } /// <summary> /// ctor /// </summary> public LazyDict(bool rejectBuildingAllKeys, params IKvp[] kvps) : this(new LiveMany<IKvp>(kvps), rejectBuildingAllKeys) { } /// <summary> /// ctor /// </summary> public LazyDict(IEnumerable<IKvp> kvps, bool rejectBuildingAllValues = true) { this.rejectBuildingAllValues = rejectBuildingAllValues; this.map = new MapOf<ScalarOf<string>>(() => { var dict = new Dictionary<string, ScalarOf<string>>(); foreach (var kvp in kvps) { dict[kvp.Key()] = new ScalarOf<string>(() => kvp.Value()); } return dict; }); this.anyValueIsLazy = new ScalarOf<bool>(() => { bool result = false; foreach (var kvp in kvps) { if (kvp.IsLazy()) { result = true; break; } } return result; }); } /// <summary> /// Access a value by key /// </summary> /// <param name="key"></param> /// <returns></returns> public string this[string key] { get { return map[key].Value(); } set { throw this.rejectReadException; } } /// <summary> /// Access all keys /// </summary> public ICollection<string> Keys => map.Keys; /// <summary> /// Access all values /// </summary> public ICollection<string> Values { get { if (this.rejectBuildingAllValues && this.anyValueIsLazy.Value()) { throw new InvalidOperationException( "Cannot get values because this is a lazy dictionary." + " Getting the values would build all keys." + " If you need this behaviour, set the ctor param 'rejectBuildingAllValues' to false."); } return new List.Mapped<ScalarOf<string>, string>( v => v.Value(), map.Values ); } } /// <summary> /// Count entries /// </summary> public int Count => map.Count; /// <summary> /// Yes its readonly /// </summary> public bool IsReadOnly => true; /// <summary> /// Unsupported /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void Add(string key, string value) { throw this.rejectReadException; } /// <summary> /// Unsupported /// </summary> /// <param name="item"></param> public void Add(KeyValuePair<string, string> item) { throw this.rejectReadException; } /// <summary> /// Unsupported /// </summary> public void Clear() { throw this.rejectReadException; } /// <summary> /// Test if map contains entry /// </summary> /// <param name="item">item to check</param> /// <returns>true if it contains</returns> public bool Contains(KeyValuePair<string, string> item) { return this.map.ContainsKey(item.Key) && this.map[item.Key].Value().Equals(item.Value); } /// <summary> /// Test if map contains key /// </summary> /// <param name="key"></param> /// <returns></returns> public bool ContainsKey(string key) { return this.map.ContainsKey(key); } /// <summary> /// Copy this to an array /// </summary> /// <param name="array">target array</param> /// <param name="arrayIndex">index to start</param> public void CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) { if (this.rejectBuildingAllValues && this.anyValueIsLazy.Value()) { throw new InvalidOperationException("Cannot copy entries because this is a lazy dictionary." + " Copying the entries would build all values." + " If you need this behaviour, set the ctor param 'rejectBuildingAllValues' to false."); } if (arrayIndex > this.map.Count) { throw new ArgumentOutOfRangeException( new Formatted( "arrayIndex {0} is higher than the item count in the map {1}.", arrayIndex, this.map.Count ).AsString()); } new ListOf<KeyValuePair<string, string>>(this).CopyTo(array, arrayIndex); } /// <summary> /// The enumerator /// </summary> /// <returns>The enumerator</returns> public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { if (this.rejectBuildingAllValues && this.anyValueIsLazy.Value()) { throw new InvalidOperationException( "Cannot get the enumerator because this is a lazy dictionary." + " Enumerating the entries would build all values." + " If you need this behaviour, set the ctor param 'rejectBuildingAllValues' to false."); } return new Enumerable.Mapped<KeyValuePair<string, ScalarOf<string>>, KeyValuePair<string, string>>( kvp => new KeyValuePair<string, string>(kvp.Key, kvp.Value.Value()), this.map ).GetEnumerator(); } /// <summary> /// Unsupported /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Remove(string key) { throw this.rejectReadException; } /// <summary> /// Unsupported /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Remove(KeyValuePair<string, string> item) { throw this.rejectReadException; } /// <summary> /// Tries to get value /// </summary> /// <param name="key">key</param> /// <param name="value">target to store value</param> /// <returns>true if success</returns> public bool TryGetValue(string key, out string value) { var result = this.map.ContainsKey(key); if (result) { value = this.map[key].Value(); result = true; } else { value = string.Empty; } return result; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// ctor /// </summary> public static LazyDict<Value> New<Value>(params IKvp<Value>[] kvps) => new LazyDict<Value>(kvps); /// <summary> /// ctor /// </summary> public static LazyDict<Value> New<Value>(bool rejectBuildingAllValues, params IKvp<Value>[] kvps) => new LazyDict<Value>(kvps); /// <summary> /// ctor /// </summary> public static LazyDict<Value> New<Value>(IEnumerable<IKvp<Value>> kvps, bool rejectBuildingAllValues = true) => new LazyDict<Value>(kvps, rejectBuildingAllValues); /// <summary> /// ctor /// </summary> public static LazyDict<Key, Value> New<Key, Value>(params IKvp<Key, Value>[] kvps) => new LazyDict<Key, Value>(kvps); /// <summary> /// ctor /// </summary> public static LazyDict<Key, Value> New<Key, Value>(bool rejectBuildingAllValues, params IKvp<Key, Value>[] kvps) => new LazyDict<Key, Value>(rejectBuildingAllValues, kvps); /// <summary> /// ctor /// </summary> public static LazyDict<Key, Value> New<Key, Value>(IEnumerable<IKvp<Key, Value>> kvps, bool rejectBuildingAllValues = true) => new LazyDict<Key, Value>(kvps, rejectBuildingAllValues); } /// <summary> /// A dictionary whose values are retrieved only when accessing them. /// </summary> public sealed class LazyDict<Value> : IDictionary<string, Value> { private readonly IDictionary<string, ScalarOf<Value>> map; private readonly UnsupportedOperationException rejectReadException = new UnsupportedOperationException("Writing is not supported, it's a read-only map"); private readonly bool rejectBuildingAllValues; private readonly ScalarOf<bool> anyValueIsLazy; /// <summary> /// ctor /// </summary> public LazyDict(params IKvp<Value>[] kvps) : this(new LiveMany<IKvp<Value>>(kvps), true) { } /// <summary> /// ctor /// </summary> public LazyDict(bool rejectBuildingAllValues, params IKvp<Value>[] kvps) : this(new LiveMany<IKvp<Value>>(kvps), rejectBuildingAllValues) { } /// <summary> /// ctor /// </summary> public LazyDict(IEnumerable<IKvp<Value>> kvps, bool rejectBuildingAllValues = true) { this.rejectBuildingAllValues = rejectBuildingAllValues; this.map = new MapOf<ScalarOf<Value>>(() => { var dict = new Dictionary<string, ScalarOf<Value>>(); foreach (var kvp in kvps) { dict[kvp.Key()] = new ScalarOf<Value>(() => kvp.Value()); } return dict; }); this.anyValueIsLazy = new ScalarOf<bool>(() => { bool result = false; foreach (var kvp in kvps) { if (kvp.IsLazy()) { result = true; break; } } return result; }); } /// <summary> /// Access a value by key /// </summary> /// <param name="key"></param> /// <returns></returns> public Value this[string key] { get { return map[key].Value(); } set { throw this.rejectReadException; } } /// <summary> /// Access all keys /// </summary> public ICollection<string> Keys => map.Keys; /// <summary> /// Access all values /// </summary> public ICollection<Value> Values { get { if (this.rejectBuildingAllValues && this.anyValueIsLazy.Value()) { throw new InvalidOperationException( "Cannot get values because this is a lazy dictionary." + " Getting the values would build all keys." + " If you need this behaviour, set the ctor param 'rejectBuildingAllValues' to false."); } return new List.Mapped<ScalarOf<Value>, Value>( v => v.Value(), map.Values ); } } /// <summary> /// Count entries /// </summary> public int Count => map.Count; /// <summary> /// Yes its readonly /// </summary> public bool IsReadOnly => true; /// <summary> /// Unsupported /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void Add(string key, Value value) { throw this.rejectReadException; } /// <summary> /// Unsupported /// </summary> /// <param name="item"></param> public void Add(KeyValuePair<string, Value> item) { throw this.rejectReadException; } /// <summary> /// Unsupported /// </summary> public void Clear() { throw this.rejectReadException; } /// <summary> /// Test if map contains entry /// </summary> /// <param name="item">item to check</param> /// <returns>true if it contains</returns> public bool Contains(KeyValuePair<string, Value> item) { return this.map.ContainsKey(item.Key) && this.map[item.Key].Value().Equals(item.Value); } /// <summary> /// Test if map contains key /// </summary> /// <param name="key"></param> /// <returns></returns> public bool ContainsKey(string key) { return this.map.ContainsKey(key); } /// <summary> /// Copy this to an array /// </summary> /// <param name="array">target array</param> /// <param name="arrayIndex">index to start</param> public void CopyTo(KeyValuePair<string, Value>[] array, int arrayIndex) { if (this.rejectBuildingAllValues && this.anyValueIsLazy.Value()) { throw new InvalidOperationException("Cannot copy entries because this is a lazy dictionary." + " Copying the entries would build all values." + " If you need this behaviour, set the ctor param 'rejectBuildingAllValues' to false."); } if (arrayIndex > this.map.Count) { throw new ArgumentOutOfRangeException( new Formatted( "arrayIndex {0} is higher than the item count in the map {1}.", arrayIndex, this.map.Count ).AsString()); } new ListOf<KeyValuePair<string, Value>>(this).CopyTo(array, arrayIndex); } /// <summary> /// The enumerator /// </summary> /// <returns>The enumerator</returns> public IEnumerator<KeyValuePair<string, Value>> GetEnumerator() { if (this.rejectBuildingAllValues && this.anyValueIsLazy.Value()) { throw new InvalidOperationException( "Cannot get the enumerator because this is a lazy dictionary." + " Enumerating the entries would build all values." + " If you need this behaviour, set the ctor param 'rejectBuildingAllValues' to false."); } return new Enumerable.Mapped<KeyValuePair<string, ScalarOf<Value>>, KeyValuePair<string, Value>>( kvp => new KeyValuePair<string, Value>(kvp.Key, kvp.Value.Value()), this.map ).GetEnumerator(); } /// <summary> /// Unsupported /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Remove(string key) { throw this.rejectReadException; } /// <summary> /// Unsupported /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Remove(KeyValuePair<string, Value> item) { throw this.rejectReadException; } /// <summary> /// Tries to get value /// </summary> /// <param name="key">key</param> /// <param name="value">target to store value</param> /// <returns>true if success</returns> public bool TryGetValue(string key, out Value value) { var result = this.map.ContainsKey(key); if (result) { value = this.map[key].Value(); result = true; } else { value = default(Value); } return result; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } /// <summary> /// A dictionary whose values are retrieved only when accessing them. /// </summary> public sealed class LazyDict<Key, Value> : IDictionary<Key, Value> { private readonly IDictionary<Key, ScalarOf<Value>> map; private readonly UnsupportedOperationException rejectReadException = new UnsupportedOperationException("Writing is not supported, it's a read-only map"); private readonly bool rejectBuildingAllValues; private readonly ScalarOf<bool> anyValueIsLazy; /// <summary> /// ctor /// </summary> public LazyDict(params IKvp<Key, Value>[] kvps) : this(new ManyOf<IKvp<Key, Value>>(kvps), true) { } /// <summary> /// ctor /// </summary> public LazyDict(bool rejectBuildingAllValues, params IKvp<Key, Value>[] kvps) : this(new LiveMany<IKvp<Key, Value>>(kvps), rejectBuildingAllValues) { } /// <summary> /// ctor /// </summary> public LazyDict(IEnumerable<IKvp<Key, Value>> kvps, bool rejectBuildingAllValues = true) { this.rejectBuildingAllValues = rejectBuildingAllValues; this.map = new MapOf<Key, ScalarOf<Value>>(() => { var dict = new Dictionary<Key, ScalarOf<Value>>(); foreach (var kvp in kvps) { dict[kvp.Key()] = new ScalarOf<Value>(() => kvp.Value()); } return dict; }); this.anyValueIsLazy = new ScalarOf<bool>(() => { bool result = false; foreach (var kvp in kvps) { if (kvp.IsLazy()) { result = true; break; } } return result; }); } /// <summary> /// Access a value by key /// </summary> /// <param name="key"></param> /// <returns></returns> public Value this[Key key] { get { return map[key].Value(); } set { throw this.rejectReadException; } } /// <summary> /// Access all keys /// </summary> public ICollection<Key> Keys => map.Keys; /// <summary> /// Access all values /// </summary> public ICollection<Value> Values { get { if (this.rejectBuildingAllValues && this.anyValueIsLazy.Value()) { throw new InvalidOperationException( "Cannot get all values because this is a lazy dictionary." + " Getting the values would build all keys." + " If you need this behaviour, set the ctor param 'rejectBuildingAllValues' to false."); } return new List.Mapped<ScalarOf<Value>, Value>( v => v.Value(), map.Values ); } } /// <summary> /// Count entries /// </summary> public int Count => map.Count; /// <summary> /// Yes its readonly /// </summary> public bool IsReadOnly => true; /// <summary> /// Unsupported /// </summary> /// <param name="key"></param> /// <param name="value"></param> public void Add(Key key, Value value) { throw this.rejectReadException; } /// <summary> /// Unsupported /// </summary> /// <param name="item"></param> public void Add(KeyValuePair<Key, Value> item) { throw this.rejectReadException; } /// <summary> /// Unsupported /// </summary> public void Clear() { throw this.rejectReadException; } /// <summary> /// Test if map contains entry /// </summary> /// <param name="item">item to check</param> /// <returns>true if it contains</returns> public bool Contains(KeyValuePair<Key, Value> item) { return this.map.ContainsKey(item.Key) && this.map[item.Key].Value().Equals(item.Value); } /// <summary> /// Test if map contains key /// </summary> /// <param name="key"></param> /// <returns></returns> public bool ContainsKey(Key key) { return this.map.ContainsKey(key); } /// <summary> /// Copy this to an array /// </summary> /// <param name="array">target array</param> /// <param name="arrayIndex">index to start</param> public void CopyTo(KeyValuePair<Key, Value>[] array, int arrayIndex) { if (this.rejectBuildingAllValues && this.anyValueIsLazy.Value()) { throw new InvalidOperationException( "Cannot copy entries because this is a lazy dictionary." + " Copying the entries would build all values." + " If you need this behaviour, set the ctor param 'rejectBuildingAllValues' to false."); } if (arrayIndex > this.map.Count) { throw new ArgumentOutOfRangeException( new Formatted( "arrayIndex {0} is higher than the item count in the map {1}.", arrayIndex, this.map.Count ).AsString()); } new ListOf<KeyValuePair<Key, Value>>(this).CopyTo(array, arrayIndex); } /// <summary> /// The enumerator /// </summary> /// <returns>The enumerator</returns> public IEnumerator<KeyValuePair<Key, Value>> GetEnumerator() { if (this.rejectBuildingAllValues && this.anyValueIsLazy.Value()) { throw new InvalidOperationException( "Cannot get the enumerator because this is a lazy dictionary." + " Enumerating the entries would build all values." + " If you need this behaviour, set the ctor param 'rejectBuildingAllValues' to false."); } return new Enumerable.Mapped<KeyValuePair<Key, ScalarOf<Value>>, KeyValuePair<Key, Value>>( kvp => new KeyValuePair<Key, Value>(kvp.Key, kvp.Value.Value()), this.map ).GetEnumerator(); } /// <summary> /// Unsupported /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Remove(Key key) { throw this.rejectReadException; } /// <summary> /// Unsupported /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Remove(KeyValuePair<Key, Value> item) { throw this.rejectReadException; } /// <summary> /// Tries to get value /// </summary> /// <param name="key">key</param> /// <param name="value">target to store value</param> /// <returns>true if success</returns> public bool TryGetValue(Key key, out Value value) { var result = this.map.ContainsKey(key); if (result) { value = this.map[key].Value(); result = true; } else { value = default(Value); } return result; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ using System; using System.Data; using System.Data.Common; using NUnit.Framework; namespace Pivotal.Data.GemFireXD.Tests { /// <summary> /// Ported from Mono's SqlParameterTest for System.Data.SqlClient. /// </summary> [TestFixture] public class ParameterTest : TestBase { #region Setup/TearDown methods protected override string[] CommonTablesToCreate() { return new string[] { "datetime_family" }; } protected override string[] GetProceduresToDrop() { return new string[] { "sp_bug382635", "sp_bug382539" }; } protected override string[] GetTablesToDrop() { return new string[] { "text1", "Bug382635", "datetime_family", "Bug526794" }; } #endregion #region Tests [Test] // bug #324840 public void ParameterSizeTest() { string longstring = new string('x', 20480); DbParameter prm; m_cmd = m_conn.CreateCommand(); m_cmd.CommandText = "create table text1 (ID int not null, Val1 clob)"; m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "INSERT INTO text1 (ID, Val1) VALUES (:ID, ?)"; prm = m_cmd.CreateParameter(); prm.Value = longstring; prm.DbType = DbType.String; m_cmd.Parameters.Add(prm); prm = m_cmd.CreateParameter(); prm.ParameterName = "ID"; prm.Value = 1; m_cmd.Parameters.Add(prm); m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "select length(Val1) from text1"; m_cmd.Parameters.Clear(); Assert.AreEqual(20480, m_cmd.ExecuteScalar(), "#1"); m_cmd.CommandText = "INSERT INTO text1 (ID, Val1) VALUES (?, :Val1)"; prm.ParameterName = null; prm.Value = 1; m_cmd.Parameters.Add(prm); prm = m_cmd.CreateParameter(); prm.ParameterName = "Val1"; prm.Value = longstring; // no type set m_cmd.Parameters.Add(prm); m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "select length(Val1) from text1"; m_cmd.Parameters.Clear(); Assert.AreEqual(20480, m_cmd.ExecuteScalar(), "#2"); m_cmd.CommandText = "INSERT INTO text1 (ID, Val1) VALUES (:ID, ?)"; prm = m_cmd.CreateParameter(); prm.ParameterName = "Val1"; prm.Value = longstring; prm.DbType = DbType.AnsiString; m_cmd.Parameters.Add(prm); prm = m_cmd.CreateParameter(); prm.ParameterName = "ID"; prm.Value = 1; m_cmd.Parameters.Add(prm); m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "select length(Val1) from text1"; m_cmd.Parameters.Clear(); Assert.AreEqual(20480, m_cmd.ExecuteScalar(), "#3"); } [Test] // bug #382635 public void ParameterSize_compatibility_Test() { string longstring = "abcdefghijklmnopqrstuvwxyz"; m_cmd = m_conn.CreateCommand(); m_cmd.CommandText = "create table bug382635 (description varchar(20))"; m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "CREATE PROCEDURE sp_bug382635 (descr varchar(20))" + " language java parameter style java external name" + " 'tests.TestProcedures.bug382635'"; m_cmd.CommandType = CommandType.Text; m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "INSERT INTO bug382635 (description)" + " VALUES ('Verifies bug #382635')"; m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "call sp_bug382635(:Desc)"; m_cmd.CommandType = CommandType.StoredProcedure; DbParameter p1 = m_cmd.CreateParameter(); // first test for exception with a non-matching parameter name p1.ParameterName = "@Desc"; p1.Value = longstring; p1.Size = 15; m_cmd.Parameters.Add(p1); try { m_cmd.ExecuteNonQuery(); Assert.Fail("#1"); } catch (DbException ex) { Assert.IsTrue(ex.Message.Contains("42886"), "#2: " + ex.Message); } // next check successful run with correct parameter name p1.ParameterName = "Desc"; m_cmd.Parameters.Clear(); m_cmd.Parameters.Add(p1); m_cmd.ExecuteNonQuery(); // cancel should not throw any unneeded exception (e.g. unimplemented) m_cmd.Cancel(); // Test for truncation DbCommand selectCmd = m_conn.CreateCommand(); selectCmd.CommandText = "SELECT LENGTH(description), description from bug382635"; using (DbDataReader rdr = selectCmd.ExecuteReader()) { Assert.IsTrue(rdr.Read(), "#A1"); Assert.AreEqual(15, rdr.GetValue(0), "#A2"); Assert.AreEqual(longstring.Substring(0, 15), rdr.GetValue(1), "#A3"); Assert.AreEqual(longstring, p1.Value, "#A4"); rdr.Close(); } // Test to ensure truncation is not done in the Value getter/setter p1.Size = 12; p1.Value = longstring.Substring(0, 22); p1.Size = 14; m_cmd.ExecuteNonQuery(); using (DbDataReader rdr = selectCmd.ExecuteReader()) { Assert.IsTrue(rdr.Read(), "#B1"); Assert.AreEqual(14, rdr.GetValue(0), "#B2"); Assert.AreEqual(longstring.Substring(0, 14), rdr.GetValue(1), "#B3"); Assert.AreEqual(longstring.Substring(0, 22), p1.Value, "#B4"); rdr.Close(); } // Size exceeds size of value p1.Size = 40; m_cmd.ExecuteNonQuery(); using (DbDataReader rdr = selectCmd.ExecuteReader()) { Assert.IsTrue(rdr.Read(), "#C1"); Assert.AreEqual(20, rdr.GetValue(0), "#C2"); Assert.AreEqual(longstring.Substring(0, 20), rdr.GetValue(1), "#C3"); rdr.Close(); } } [Test] public void ConversionToSqlTypeInvalid() { string insert_data = "insert into datetime_family (id, type_datetime)" + " values (6000, ?)"; string delete_data = "delete from datetime_family where id = 6000"; m_cmd = m_conn.CreateCommand(); object[] values = new object[] { 5, true, 40L, "invalid date" }; try { for (int index = 0; index < values.Length; index++) { object val = values[index]; m_cmd.CommandText = insert_data; DbParameter param = m_cmd.CreateParameter(); param.DbType = DbType.DateTime2; param.Value = val; m_cmd.Parameters.Add(param); m_cmd.Prepare(); try { m_cmd.ExecuteNonQuery(); Assert.Fail("#1: " + index); } catch (InvalidCastException) { // expected } catch (FormatException) { // expected } } } finally { m_cmd.CommandText = delete_data; m_cmd.Parameters.Clear(); m_cmd.ExecuteNonQuery(); } } [Test] // bug #382589 public void DecimalMinMaxAsParamValueTest() { string create_sp = "CREATE PROCEDURE sp_bug382539" + " (inout decval decimal(29, 0)) language java parameter style java" + " external name 'tests.TestProcedures.bug382539'"; m_cmd = m_conn.CreateCommand(); m_cmd.CommandText = create_sp; m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "sp_bug382539"; m_cmd.CommandType = CommandType.StoredProcedure; // check for Decimal.MaxValue DbParameter pValue = m_cmd.CreateParameter(); pValue.Value = Decimal.MaxValue; pValue.Direction = ParameterDirection.InputOutput; m_cmd.Parameters.Add(pValue); Assert.AreEqual(Decimal.MaxValue, pValue.Value, "Parameter initialization value mismatch"); m_cmd.ExecuteNonQuery(); Assert.AreEqual(102m, pValue.Value, "Parameter value mismatch"); // now check for Decimal.MinValue m_cmd.Parameters.Clear(); pValue.Value = Decimal.MinValue; pValue.Direction = ParameterDirection.InputOutput; m_cmd.Parameters.Add(pValue); Assert.AreEqual(Decimal.MinValue, pValue.Value, "Parameter initialization value mismatch"); m_cmd.ExecuteNonQuery(); Assert.AreEqual(102m, pValue.Value, "Parameter value mismatch"); } [Test] // bug #382589 public void DecimalMinMaxAsParamValueExceptionTest() { string create_sp = "CREATE PROCEDURE sp_bug382539" + " (inout decval decimal(29,10)) language java parameter style java" + " external name 'tests.TestProcedures.bug382539'"; m_cmd = m_conn.CreateCommand(); m_cmd.CommandText = create_sp; m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "sp_bug382539"; m_cmd.CommandType = CommandType.StoredProcedure; // check exception for Decimal.MaxValue DbParameter pValue = m_cmd.CreateParameter(); pValue.Value = Decimal.MaxValue; pValue.Direction = ParameterDirection.InputOutput; m_cmd.Parameters.Add(pValue); Assert.AreEqual(Decimal.MaxValue, pValue.Value, "Parameter initialization value mismatch"); try { m_cmd.ExecuteNonQuery(); Assert.Fail("#A1"); } catch (DbException ex) { // Error converting data type numeric to decimal Assert.IsNotNull(ex.Message, "#A2"); Assert.IsTrue(ex.Message.Contains("22003"), "#A3: " + ex.Message); } // now check for Decimal.MinValue m_cmd.Parameters.Clear(); pValue.Value = Decimal.MinValue; pValue.Direction = ParameterDirection.InputOutput; m_cmd.Parameters.Add(pValue); try { m_cmd.ExecuteNonQuery(); Assert.Fail("#B1"); } catch (DbException ex) { // Error converting data type numeric to decimal Assert.IsNotNull(ex.Message, "#B2"); Assert.IsTrue(ex.Message.Contains("22003"), "#B3: " + ex.Message); } } [Test] // bug #526794 public void ZeroLengthString() { m_cmd = m_conn.CreateCommand(); m_cmd.CommandText = "create table bug526794 (name varchar(20) NULL)"; m_cmd.ExecuteNonQuery(); DbParameter param = m_cmd.CreateParameter(); param.DbType = DbType.AnsiString; param.Value = string.Empty; m_cmd.CommandText = "insert into bug526794 values (?)"; m_cmd.Parameters.Add(param); m_cmd.ExecuteNonQuery(); m_cmd.CommandText = "select * from bug526794"; m_cmd.Parameters.Clear(); using (DbDataReader rdr = m_cmd.ExecuteReader()) { Assert.IsTrue(rdr.Read(), "#A1"); Assert.AreEqual(string.Empty, rdr.GetValue(0), "#A2"); rdr.Close(); } m_cmd.CommandText = "insert into bug526794 values (?)"; param.DbType = DbType.Int32; param.Value = string.Empty; m_cmd.Parameters.Add(param); try { m_cmd.ExecuteNonQuery(); Assert.Fail("#B1"); } catch (FormatException ex) { // Failed to convert parameter value from a String to a Int32 Assert.IsNotNull(ex.Message, "#B2"); } } [Test] public void CopyToParameterCollection() { DbCommand cmd = m_conn.CreateCommand(); cmd.CommandText = "SELECT fname FROM employee WHERE fname=:fname" + " AND lname=?"; DbParameter p1Fname; DbParameter p1Lname; if (cmd is GFXDCommand) { GFXDCommand scmd = (GFXDCommand)cmd; p1Fname = scmd.Parameters.Add("fname", GFXDType.VarChar, 15); } else { p1Fname = cmd.CreateParameter(); p1Fname.ParameterName = "fname"; p1Fname.DbType = DbType.AnsiString; p1Fname.Value = 15; cmd.Parameters.Add(p1Fname); } p1Lname = cmd.CreateParameter(); p1Lname.DbType = DbType.String; p1Lname.Value = 15; cmd.Parameters.Add(p1Lname); Assert.AreEqual(2, cmd.Parameters.Count, "#1 Initialization error," + " parameter collection must contain 2 elements"); Assert.AreSame(p1Fname, cmd.Parameters["fname"], "#2 Should find the" + " same parameter as that added"); Assert.AreSame(p1Fname, cmd.Parameters[0], "#3 Should find the" + " same parameter as that added"); Assert.AreSame(p1Lname, cmd.Parameters[1], "#4 Should find the" + " same parameter as that added"); Assert.IsNull(cmd.Parameters["lname"], "#5 Expected to find a null" + " parameter for non-existing name"); DbParameter[] destinationArray = new DbParameter[4]; cmd.Parameters.CopyTo(destinationArray, 1); Assert.AreEqual(4, destinationArray.Length, "#6 The length of" + " destination array should not change"); Assert.AreEqual(null, destinationArray[0], "#7 The parameter collection" + " is copied at index 1, so the first element should not change"); Assert.AreEqual(p1Fname, destinationArray[1], "#8 The parameter" + " at index 1 must be p1Fname"); Assert.AreEqual(p1Lname, destinationArray[2], "#9 The parameter" + " at index 2 must be p1Lname"); Assert.AreEqual(null, destinationArray[3], "#10 The parameter" + " at index 3 must not change"); } #endregion } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using System.Configuration; using System.Diagnostics; namespace Ctrip.Log4.Util { /// <summary> /// /// </summary> /// <param name="source"></param> /// <param name="e"></param> public delegate void LogReceivedEventHandler(object source, LogReceivedEventArgs e); /// <summary> /// Outputs log statements from within the Ctrip assembly. /// </summary> /// <remarks> /// <para> /// Log4net components cannot make Ctrip logging calls. However, it is /// sometimes useful for the user to learn about what Ctrip is /// doing. /// </para> /// <para> /// All Ctrip internal debug calls go to the standard output stream /// whereas internal error messages are sent to the standard error output /// stream. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class LogLog { /// <summary> /// The event raised when an internal message has been received. /// </summary> public static event LogReceivedEventHandler LogReceived; private readonly Type source; private readonly DateTime timeStamp; private readonly string prefix; private readonly string message; private readonly Exception exception; /// <summary> /// The Type that generated the internal message. /// </summary> public Type Source { get { return source; } } /// <summary> /// The DateTime stamp of when the internal message was received. /// </summary> public DateTime TimeStamp { get { return timeStamp; } } /// <summary> /// A string indicating the severity of the internal message. /// </summary> /// <remarks> /// "Ctrip: ", /// "Ctrip:ERROR ", /// "Ctrip:WARN " /// </remarks> public string Prefix { get { return prefix; } } /// <summary> /// The internal log message. /// </summary> public string Message { get { return message; } } /// <summary> /// The Exception related to the message. /// </summary> /// <remarks> /// Optional. Will be null if no Exception was passed. /// </remarks> public Exception Exception { get { return exception; } } /// <summary> /// Formats Prefix, Source, and Message in the same format as the value /// sent to Console.Out and Trace.Write. /// </summary> /// <returns></returns> public override string ToString() { return Prefix + Source.Name + ": " + Message; } #region Private Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="LogLog" /> class. /// </summary> /// <param name="source"></param> /// <param name="prefix"></param> /// <param name="message"></param> /// <param name="exception"></param> public LogLog(Type source, string prefix, string message, Exception exception) { timeStamp = DateTime.Now; this.source = source; this.prefix = prefix; this.message = message; this.exception = exception; } #endregion Private Instance Constructors #region Static Constructor /// <summary> /// Static constructor that initializes logging by reading /// settings from the application configuration file. /// </summary> /// <remarks> /// <para> /// The <c>Ctrip.Internal.Debug</c> application setting /// controls internal debugging. This setting should be set /// to <c>true</c> to enable debugging. /// </para> /// <para> /// The <c>Ctrip.Internal.Quiet</c> application setting /// suppresses all internal logging including error messages. /// This setting should be set to <c>true</c> to enable message /// suppression. /// </para> /// </remarks> static LogLog() { #if !NETCF try { InternalDebugging = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("Ctrip.Internal.Debug"), false); QuietMode = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("Ctrip.Internal.Quiet"), false); EmitInternalMessages = OptionConverter.ToBoolean(SystemInfo.GetAppSetting("Ctrip.Internal.Emit"), true); } catch(Exception ex) { // If an exception is thrown here then it looks like the config file does not // parse correctly. // // We will leave debug OFF and print an Error message Error(typeof(LogLog), "Exception while reading ConfigurationSettings. Check your .config file is well formed XML.", ex); } #endif } #endregion Static Constructor #region Public Static Properties /// <summary> /// Gets or sets a value indicating whether Ctrip internal logging /// is enabled or disabled. /// </summary> /// <value> /// <c>true</c> if Ctrip internal logging is enabled, otherwise /// <c>false</c>. /// </value> /// <remarks> /// <para> /// When set to <c>true</c>, internal debug level logging will be /// displayed. /// </para> /// <para> /// This value can be set by setting the application setting /// <c>Ctrip.Internal.Debug</c> in the application configuration /// file. /// </para> /// <para> /// The default value is <c>false</c>, i.e. debugging is /// disabled. /// </para> /// </remarks> /// <example> /// <para> /// The following example enables internal debugging using the /// application configuration file : /// </para> /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="Ctrip.Internal.Debug" value="true" /> /// </appSettings> /// </configuration> /// </code> /// </example> public static bool InternalDebugging { get { return s_debugEnabled; } set { s_debugEnabled = value; } } /// <summary> /// Gets or sets a value indicating whether Ctrip should generate no output /// from internal logging, not even for errors. /// </summary> /// <value> /// <c>true</c> if Ctrip should generate no output at all from internal /// logging, otherwise <c>false</c>. /// </value> /// <remarks> /// <para> /// When set to <c>true</c> will cause internal logging at all levels to be /// suppressed. This means that no warning or error reports will be logged. /// This option overrides the <see cref="InternalDebugging"/> setting and /// disables all debug also. /// </para> /// <para>This value can be set by setting the application setting /// <c>Ctrip.Internal.Quiet</c> in the application configuration file. /// </para> /// <para> /// The default value is <c>false</c>, i.e. internal logging is not /// disabled. /// </para> /// </remarks> /// <example> /// The following example disables internal logging using the /// application configuration file : /// <code lang="XML" escaped="true"> /// <configuration> /// <appSettings> /// <add key="Ctrip.Internal.Quiet" value="true" /> /// </appSettings> /// </configuration> /// </code> /// </example> public static bool QuietMode { get { return s_quietMode; } set { s_quietMode = value; } } /// <summary> /// /// </summary> public static bool EmitInternalMessages { get { return s_emitInternalMessages; } set { s_emitInternalMessages = value; } } #endregion Public Static Properties #region Public Static Methods /// <summary> /// Raises the LogReceived event when an internal messages is received. /// </summary> /// <param name="source"></param> /// <param name="prefix"></param> /// <param name="message"></param> /// <param name="exception"></param> public static void OnLogReceived(Type source, string prefix, string message, Exception exception) { if (LogReceived != null) { LogReceived(null, new LogReceivedEventArgs(new LogLog(source, prefix, message, exception))); } } /// <summary> /// Test if LogLog.Debug is enabled for output. /// </summary> /// <value> /// <c>true</c> if Debug is enabled /// </value> /// <remarks> /// <para> /// Test if LogLog.Debug is enabled for output. /// </para> /// </remarks> public static bool IsDebugEnabled { get { return s_debugEnabled && !s_quietMode; } } /// <summary> /// Writes Ctrip internal debug messages to the /// standard output stream. /// </summary> /// <param name="source"></param> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// All internal debug messages are prepended with /// the string "Ctrip: ". /// </para> /// </remarks> public static void Debug(Type source, string message) { if (IsDebugEnabled) { if (EmitInternalMessages) { EmitOutLine(PREFIX + message); } OnLogReceived(source, PREFIX, message, null); } } /// <summary> /// Writes Ctrip internal debug messages to the /// standard output stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <param name="exception">An exception to log.</param> /// <remarks> /// <para> /// All internal debug messages are prepended with /// the string "Ctrip: ". /// </para> /// </remarks> public static void Debug(Type source, string message, Exception exception) { if (IsDebugEnabled) { if (EmitInternalMessages) { EmitOutLine(PREFIX + message); if (exception != null) { EmitOutLine(exception.ToString()); } } OnLogReceived(source, PREFIX, message, exception); } } /// <summary> /// Test if LogLog.Warn is enabled for output. /// </summary> /// <value> /// <c>true</c> if Warn is enabled /// </value> /// <remarks> /// <para> /// Test if LogLog.Warn is enabled for output. /// </para> /// </remarks> public static bool IsWarnEnabled { get { return !s_quietMode; } } /// <summary> /// Writes Ctrip internal warning messages to the /// standard error stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// All internal warning messages are prepended with /// the string "Ctrip:WARN ". /// </para> /// </remarks> public static void Warn(Type source, string message) { if (IsWarnEnabled) { if (EmitInternalMessages) { EmitErrorLine(WARN_PREFIX + message); } OnLogReceived(source, WARN_PREFIX, message, null); } } /// <summary> /// Writes Ctrip internal warning messages to the /// standard error stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <param name="exception">An exception to log.</param> /// <remarks> /// <para> /// All internal warning messages are prepended with /// the string "Ctrip:WARN ". /// </para> /// </remarks> public static void Warn(Type source, string message, Exception exception) { if (IsWarnEnabled) { if (EmitInternalMessages) { EmitErrorLine(WARN_PREFIX + message); if (exception != null) { EmitErrorLine(exception.ToString()); } } OnLogReceived(source, WARN_PREFIX, message, exception); } } /// <summary> /// Test if LogLog.Error is enabled for output. /// </summary> /// <value> /// <c>true</c> if Error is enabled /// </value> /// <remarks> /// <para> /// Test if LogLog.Error is enabled for output. /// </para> /// </remarks> public static bool IsErrorEnabled { get { return !s_quietMode; } } /// <summary> /// Writes Ctrip internal error messages to the /// standard error stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// All internal error messages are prepended with /// the string "Ctrip:ERROR ". /// </para> /// </remarks> public static void Error(Type source, string message) { if (IsErrorEnabled) { if (EmitInternalMessages) { EmitErrorLine(ERR_PREFIX + message); } OnLogReceived(source, ERR_PREFIX, message, null); } } /// <summary> /// Writes Ctrip internal error messages to the /// standard error stream. /// </summary> /// <param name="source">The Type that generated this message.</param> /// <param name="message">The message to log.</param> /// <param name="exception">An exception to log.</param> /// <remarks> /// <para> /// All internal debug messages are prepended with /// the string "Ctrip:ERROR ". /// </para> /// </remarks> public static void Error(Type source, string message, Exception exception) { if (IsErrorEnabled) { if (EmitInternalMessages) { EmitErrorLine(ERR_PREFIX + message); if (exception != null) { EmitErrorLine(exception.ToString()); } } OnLogReceived(source, ERR_PREFIX, message, exception); } } #endregion Public Static Methods /// <summary> /// Writes output to the standard output stream. /// </summary> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// Writes to both Console.Out and System.Diagnostics.Trace. /// Note that the System.Diagnostics.Trace is not supported /// on the Compact Framework. /// </para> /// <para> /// If the AppDomain is not configured with a config file then /// the call to System.Diagnostics.Trace may fail. This is only /// an issue if you are programmatically creating your own AppDomains. /// </para> /// </remarks> private static void EmitOutLine(string message) { try { #if NETCF Console.WriteLine(message); //System.Diagnostics.Debug.WriteLine(message); #else Console.Out.WriteLine(message); Trace.WriteLine(message); #endif } catch { // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller } } /// <summary> /// Writes output to the standard error stream. /// </summary> /// <param name="message">The message to log.</param> /// <remarks> /// <para> /// Writes to both Console.Error and System.Diagnostics.Trace. /// Note that the System.Diagnostics.Trace is not supported /// on the Compact Framework. /// </para> /// <para> /// If the AppDomain is not configured with a config file then /// the call to System.Diagnostics.Trace may fail. This is only /// an issue if you are programmatically creating your own AppDomains. /// </para> /// </remarks> private static void EmitErrorLine(string message) { try { #if NETCF Console.WriteLine(message); //System.Diagnostics.Debug.WriteLine(message); #else Console.Error.WriteLine(message); Trace.WriteLine(message); #endif } catch { // Ignore exception, what else can we do? Not really a good idea to propagate back to the caller } } #region Private Static Fields /// <summary> /// Default debug level /// </summary> private static bool s_debugEnabled = false; /// <summary> /// In quietMode not even errors generate any output. /// </summary> private static bool s_quietMode = false; private static bool s_emitInternalMessages = true; private const string PREFIX = "Ctrip: "; private const string ERR_PREFIX = "Ctrip:ERROR "; private const string WARN_PREFIX = "Ctrip:WARN "; #endregion Private Static Fields /// <summary> /// Subscribes to the LogLog.LogReceived event and stores messages /// to the supplied IList instance. /// </summary> public class LogReceivedAdapter : IDisposable { private readonly IList items; private readonly LogReceivedEventHandler handler; /// <summary> /// /// </summary> /// <param name="items"></param> public LogReceivedAdapter(IList items) { this.items = items; handler = new LogReceivedEventHandler(LogLog_LogReceived); LogReceived += handler; } void LogLog_LogReceived(object source, LogReceivedEventArgs e) { items.Add(e.LogLog); } /// <summary> /// /// </summary> public IList Items { get { return items; } } /// <summary> /// /// </summary> public void Dispose() { LogReceived -= handler; } } } /// <summary> /// /// </summary> public class LogReceivedEventArgs : EventArgs { private readonly LogLog loglog; /// <summary> /// /// </summary> /// <param name="loglog"></param> public LogReceivedEventArgs(LogLog loglog) { this.loglog = loglog; } /// <summary> /// /// </summary> public LogLog LogLog { get { return loglog; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** ** ** Purpose: Abstract base class for Text-only Writers. ** Subclasses will include StreamWriter & StringWriter. ** ** ===========================================================*/ using System; using System.Text; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Reflection; using System.Security.Permissions; using System.Globalization; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading.Tasks; namespace System.IO { // This abstract base class represents a writer that can write a sequential // stream of characters. A subclass must minimally implement the // Write(char) method. // // This class is intended for character output, not bytes. // There are methods on the Stream class for writing bytes. [Serializable] [ComVisible(true)] #if FEATURE_REMOTING public abstract class TextWriter : MarshalByRefObject, IDisposable { #else // FEATURE_REMOTING public abstract class TextWriter : IDisposable { #endif // FEATURE_REMOTING public static readonly TextWriter Null = new NullTextWriter(); // This should be initialized to Environment.NewLine, but // to avoid loading Environment unnecessarily so I've duplicated // the value here. #if !PLATFORM_UNIX private const String InitialNewLine = "\r\n"; protected char[] CoreNewLine = new char[] { '\r', '\n' }; #else private const String InitialNewLine = "\n"; protected char[] CoreNewLine = new char[] {'\n'}; #endif // !PLATFORM_UNIX // Can be null - if so, ask for the Thread's CurrentCulture every time. private IFormatProvider InternalFormatProvider; protected TextWriter() { InternalFormatProvider = null; // Ask for CurrentCulture all the time. } protected TextWriter(IFormatProvider formatProvider) { InternalFormatProvider = formatProvider; } public virtual IFormatProvider FormatProvider { get { if (InternalFormatProvider == null) return Thread.CurrentThread.CurrentCulture; else return InternalFormatProvider; } } // Closes this TextWriter and releases any system resources associated with the // TextWriter. Following a call to Close, any operations on the TextWriter // may raise exceptions. This default method is empty, but descendant // classes can override the method to provide the appropriate // functionality. public virtual void Close() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // Clears all buffers for this TextWriter and causes any buffered data to be // written to the underlying device. This default method is empty, but // descendant classes can override the method to provide the appropriate // functionality. public virtual void Flush() { } public abstract Encoding Encoding { get; } // Returns the line terminator string used by this TextWriter. The default line // terminator string is a carriage return followed by a line feed ("\r\n"). // // Sets the line terminator string for this TextWriter. The line terminator // string is written to the text stream whenever one of the // WriteLine methods are called. In order for text written by // the TextWriter to be readable by a TextReader, only one of the following line // terminator strings should be used: "\r", "\n", or "\r\n". // public virtual String NewLine { get { return new String(CoreNewLine); } set { if (value == null) value = InitialNewLine; CoreNewLine = value.ToCharArray(); } } [HostProtection(Synchronization=true)] public static TextWriter Synchronized(TextWriter writer) { if (writer==null) throw new ArgumentNullException("writer"); Contract.Ensures(Contract.Result<TextWriter>() != null); Contract.EndContractBlock(); if (writer is SyncTextWriter) return writer; return new SyncTextWriter(writer); } // Writes a character to the text stream. This default method is empty, // but descendant classes can override the method to provide the // appropriate functionality. // public virtual void Write(char value) { } // Writes a character array to the text stream. This default method calls // Write(char) for each of the characters in the character array. // If the character array is null, nothing is written. // public virtual void Write(char[] buffer) { if (buffer != null) Write(buffer, 0, buffer.Length); } // Writes a range of a character array to the text stream. This method will // write count characters of data into this TextWriter from the // buffer character array starting at position index. // public virtual void Write(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); for (int i = 0; i < count; i++) Write(buffer[index + i]); } // Writes the text representation of a boolean to the text stream. This // method outputs either Boolean.TrueString or Boolean.FalseString. // public virtual void Write(bool value) { Write(value ? Boolean.TrueLiteral : Boolean.FalseLiteral); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // Int32.ToString() method. // public virtual void Write(int value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an integer to the text stream. The // text representation of the given value is produced by calling the // UInt32.ToString() method. // [CLSCompliant(false)] public virtual void Write(uint value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a long to the text stream. The // text representation of the given value is produced by calling the // Int64.ToString() method. // public virtual void Write(long value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of an unsigned long to the text // stream. The text representation of the given value is produced // by calling the UInt64.ToString() method. // [CLSCompliant(false)] public virtual void Write(ulong value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a float to the text stream. The // text representation of the given value is produced by calling the // Float.toString(float) method. // public virtual void Write(float value) { Write(value.ToString(FormatProvider)); } // Writes the text representation of a double to the text stream. The // text representation of the given value is produced by calling the // Double.toString(double) method. // public virtual void Write(double value) { Write(value.ToString(FormatProvider)); } public virtual void Write(Decimal value) { Write(value.ToString(FormatProvider)); } // Writes a string to the text stream. If the given string is null, nothing // is written to the text stream. // public virtual void Write(String value) { if (value != null) Write(value.ToCharArray()); } // Writes the text representation of an object to the text stream. If the // given object is null, nothing is written to the text stream. // Otherwise, the object's ToString method is called to produce the // string representation, and the resulting string is then written to the // output stream. // public virtual void Write(Object value) { if (value != null) { IFormattable f = value as IFormattable; if (f != null) Write(f.ToString(null, FormatProvider)); else Write(value.ToString()); } } #if false // // Converts the wchar * to a string and writes this to the stream. // // // __attribute NonCLSCompliantAttribute() // public void Write(wchar *value) { // Write(new String(value)); // } // // Treats the byte* as a LPCSTR, converts it to a string, and writes it to the stream. // // // __attribute NonCLSCompliantAttribute() // public void Write(byte *value) { // Write(new String(value)); // } #endif // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(String format, Object arg0) { Write(String.Format(FormatProvider, format, arg0)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(String format, Object arg0, Object arg1) { Write(String.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(String format, Object arg0, Object arg1, Object arg2) { Write(String.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string. Uses the same semantics as // String.Format. // public virtual void Write(String format, params Object[] arg) { Write(String.Format(FormatProvider, format, arg)); } // Writes a line terminator to the text stream. The default line terminator // is a carriage return followed by a line feed ("\r\n"), but this value // can be changed by setting the NewLine property. // public virtual void WriteLine() { Write(CoreNewLine); } // Writes a character followed by a line terminator to the text stream. // public virtual void WriteLine(char value) { Write(value); WriteLine(); } // Writes an array of characters followed by a line terminator to the text // stream. // public virtual void WriteLine(char[] buffer) { Write(buffer); WriteLine(); } // Writes a range of a character array followed by a line terminator to the // text stream. // public virtual void WriteLine(char[] buffer, int index, int count) { Write(buffer, index, count); WriteLine(); } // Writes the text representation of a boolean followed by a line // terminator to the text stream. // public virtual void WriteLine(bool value) { Write(value); WriteLine(); } // Writes the text representation of an integer followed by a line // terminator to the text stream. // public virtual void WriteLine(int value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned integer followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(uint value) { Write(value); WriteLine(); } // Writes the text representation of a long followed by a line terminator // to the text stream. // public virtual void WriteLine(long value) { Write(value); WriteLine(); } // Writes the text representation of an unsigned long followed by // a line terminator to the text stream. // [CLSCompliant(false)] public virtual void WriteLine(ulong value) { Write(value); WriteLine(); } // Writes the text representation of a float followed by a line terminator // to the text stream. // public virtual void WriteLine(float value) { Write(value); WriteLine(); } // Writes the text representation of a double followed by a line terminator // to the text stream. // public virtual void WriteLine(double value) { Write(value); WriteLine(); } public virtual void WriteLine(decimal value) { Write(value); WriteLine(); } // Writes a string followed by a line terminator to the text stream. // public virtual void WriteLine(String value) { if (value==null) { WriteLine(); } else { // We'd ideally like WriteLine to be atomic, in that one call // to WriteLine equals one call to the OS (ie, so writing to // console while simultaneously calling printf will guarantee we // write out a string and new line chars, without any interference). // Additionally, we need to call ToCharArray on Strings anyways, // so allocating a char[] here isn't any worse than what we were // doing anyways. We do reduce the number of calls to the // backing store this way, potentially. int vLen = value.Length; int nlLen = CoreNewLine.Length; char[] chars = new char[vLen+nlLen]; value.CopyTo(0, chars, 0, vLen); // CoreNewLine will almost always be 2 chars, and possibly 1. if (nlLen == 2) { chars[vLen] = CoreNewLine[0]; chars[vLen+1] = CoreNewLine[1]; } else if (nlLen == 1) chars[vLen] = CoreNewLine[0]; else Buffer.InternalBlockCopy(CoreNewLine, 0, chars, vLen * 2, nlLen * 2); Write(chars, 0, vLen + nlLen); } /* Write(value); // We could call Write(String) on StreamWriter... WriteLine(); */ } // Writes the text representation of an object followed by a line // terminator to the text stream. // public virtual void WriteLine(Object value) { if (value==null) { WriteLine(); } else { // Call WriteLine(value.ToString), not Write(Object), WriteLine(). // This makes calls to WriteLine(Object) atomic. IFormattable f = value as IFormattable; if (f != null) WriteLine(f.ToString(null, FormatProvider)); else WriteLine(value.ToString()); } } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine(String format, Object arg0) { WriteLine(String.Format(FormatProvider, format, arg0)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine (String format, Object arg0, Object arg1) { WriteLine(String.Format(FormatProvider, format, arg0, arg1)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine (String format, Object arg0, Object arg1, Object arg2) { WriteLine(String.Format(FormatProvider, format, arg0, arg1, arg2)); } // Writes out a formatted string and a new line. Uses the same // semantics as String.Format. // public virtual void WriteLine (String format, params Object[] arg) { WriteLine(String.Format(FormatProvider, format, arg)); } #region Task based Async APIs [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteAsync(char value) { var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char>)state; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteAsync(String value) { var tuple = new Tuple<TextWriter, string>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, string>)state; t.Item1.Write(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task WriteAsync(char[] buffer) { if (buffer == null) return Task.CompletedTask; return WriteAsync(buffer, 0, buffer.Length); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteAsync(char[] buffer, int index, int count) { var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char[], int, int>)state; t.Item1.Write(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteLineAsync(char value) { var tuple = new Tuple<TextWriter, char>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char>)state; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteLineAsync(String value) { var tuple = new Tuple<TextWriter, string>(this, value); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, string>)state; t.Item1.WriteLine(t.Item2); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public Task WriteLineAsync(char[] buffer) { if (buffer == null) return Task.CompletedTask; return WriteLineAsync(buffer, 0, buffer.Length); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteLineAsync(char[] buffer, int index, int count) { var tuple = new Tuple<TextWriter, char[], int, int>(this, buffer, index, count); return Task.Factory.StartNew(state => { var t = (Tuple<TextWriter, char[], int, int>)state; t.Item1.WriteLine(t.Item2, t.Item3, t.Item4); }, tuple, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task WriteLineAsync() { return WriteAsync(CoreNewLine); } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public virtual Task FlushAsync() { return Task.Factory.StartNew(state => { ((TextWriter)state).Flush(); }, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } #endregion [Serializable] private sealed class NullTextWriter : TextWriter { internal NullTextWriter(): base(CultureInfo.InvariantCulture) { } public override Encoding Encoding { get { return Encoding.Default; } } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override void Write(char[] buffer, int index, int count) { } public override void Write(String value) { } // Not strictly necessary, but for perf reasons public override void WriteLine() { } // Not strictly necessary, but for perf reasons public override void WriteLine(String value) { } public override void WriteLine(Object value) { } } [Serializable] internal sealed class SyncTextWriter : TextWriter, IDisposable { private TextWriter _out; internal SyncTextWriter(TextWriter t): base(t.FormatProvider) { _out = t; } public override Encoding Encoding { get { return _out.Encoding; } } public override IFormatProvider FormatProvider { get { return _out.FormatProvider; } } public override String NewLine { [MethodImplAttribute(MethodImplOptions.Synchronized)] get { return _out.NewLine; } [MethodImplAttribute(MethodImplOptions.Synchronized)] set { _out.NewLine = value; } } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Close() { // So that any overriden Close() gets run _out.Close(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] protected override void Dispose(bool disposing) { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_out).Dispose(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Flush() { _out.Flush(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(char value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(char[] buffer) { _out.Write(buffer); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(char[] buffer, int index, int count) { _out.Write(buffer, index, count); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(bool value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(int value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(uint value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(long value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(ulong value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(float value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(double value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(Decimal value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(Object value) { _out.Write(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String format, Object arg0) { _out.Write(format, arg0); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String format, Object arg0, Object arg1) { _out.Write(format, arg0, arg1); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String format, Object arg0, Object arg1, Object arg2) { _out.Write(format, arg0, arg1, arg2); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void Write(String format, Object[] arg) { _out.Write(format, arg); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine() { _out.WriteLine(); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(char value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(decimal value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer) { _out.WriteLine(buffer); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(char[] buffer, int index, int count) { _out.WriteLine(buffer, index, count); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(bool value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(int value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(uint value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(long value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(ulong value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(float value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(double value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(Object value) { _out.WriteLine(value); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String format, Object arg0) { _out.WriteLine(format, arg0); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String format, Object arg0, Object arg1) { _out.WriteLine(format, arg0, arg1); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String format, Object arg0, Object arg1, Object arg2) { _out.WriteLine(format, arg0, arg1, arg2); } [MethodImplAttribute(MethodImplOptions.Synchronized)] public override void WriteLine(String format, Object[] arg) { _out.WriteLine(format, arg); } // // On SyncTextWriter all APIs should run synchronously, even the async ones. // [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteAsync(char value) { Write(value); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteAsync(String value) { Write(value); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteAsync(char[] buffer, int index, int count) { Write(buffer, index, count); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteLineAsync(char value) { WriteLine(value); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteLineAsync(String value) { WriteLine(value); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task WriteLineAsync(char[] buffer, int index, int count) { WriteLine(buffer, index, count); return Task.CompletedTask; } [MethodImplAttribute(MethodImplOptions.Synchronized)] [ComVisible(false)] public override Task FlushAsync() { Flush(); return Task.CompletedTask; } } } }
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 MovieHunter.API.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); 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 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.TimeZones; using NodaTime.TzdbCompiler.Tzdb; using NUnit.Framework; using System; using System.IO; namespace NodaTime.TzdbCompiler.Test.Tzdb { ///<summary> /// This is a test class for containing all of the TzdbZoneInfoParser unit tests. ///</summary> [TestFixture] public class TzdbZoneInfoParserTest { private static readonly string[] MonthNames = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; private TzdbZoneInfoParser Parser { get; set; } [TestFixtureSetUp] public void Setup() { Parser = new TzdbZoneInfoParser(); } private static Offset ToOffset(int hours, int minutes) { return Offset.FromHoursAndMinutes(hours, minutes); } private static void ValidateCounts(TzdbDatabase database, int ruleSets, int zoneLists, int links) { Assert.AreEqual(ruleSets, database.Rules.Count, "Rules"); Assert.AreEqual(zoneLists, database.ZoneLists.Count, "Zones"); Assert.AreEqual(links, database.Aliases.Count, "Links"); } /* ############################################################################### */ [Test] public void ParseDateTimeOfYear_emptyString() { var tokens = Tokens.Tokenize(string.Empty); Assert.Throws(typeof(InvalidDataException), () => Parser.ParseDateTimeOfYear(tokens, true)); } [Test] public void ParseDateTimeOfYear_missingAt_invalidForRule() { const string text = "Mar lastSun"; var tokens = Tokens.Tokenize(text); Assert.Throws(typeof(InvalidDataException), () => Parser.ParseDateTimeOfYear(tokens, true)); } [Test] public void ParseDateTimeOfYear_missingOn_invalidForRule() { const string text = "Mar"; var tokens = Tokens.Tokenize(text); Assert.Throws(typeof(InvalidDataException), () => Parser.ParseDateTimeOfYear(tokens, true)); } [Test] public void ParseDateTimeOfYear_missingAt_validForZone() { const string text = "Mar lastSun"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens, false); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_missingOn_validForZone() { const string text = "Mar"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens, false); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 1, 0, false, LocalTime.Midnight); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onAfter() { const string text = "Mar Tue>=14 2:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 14, (int)IsoDayOfWeek.Tuesday, true, new LocalTime(2, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onBefore() { const string text = "Mar Tue<=14 2:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, 14, (int)IsoDayOfWeek.Tuesday, false, new LocalTime(2, 0)); Assert.AreEqual(expected, actual); } [Test] public void ParseDateTimeOfYear_onLast() { const string text = "Mar lastTue 2:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int)IsoDayOfWeek.Tuesday, false, new LocalTime(2, 0)); Assert.AreEqual(expected, actual); } /* ############################################################################### */ [Test] public void ParseLine_comment() { const string line = "# Comment"; var database = new TzdbDatabase("version"); Parser.ParseLine(line, database); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_commentWithLeadingWhitespace() { const string line = " # Comment"; var database = new TzdbDatabase("version"); Parser.ParseLine(line, database); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_emptyString() { var database = new TzdbDatabase("version"); Parser.ParseLine(string.Empty, database); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_link() { const string line = "Link from to"; var database = new TzdbDatabase("version"); Parser.ParseLine(line, database); ValidateCounts(database, 0, 0, 1); } [Test] public void ParseLine_whiteSpace() { const string line = " \t\t\n"; var database = new TzdbDatabase("version"); Parser.ParseLine(line, database); ValidateCounts(database, 0, 0, 0); } [Test] public void ParseLine_zone() { const string line = "Zone PST 2:00 US P%sT"; var database = new TzdbDatabase("version"); Parser.ParseLine(line, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.ZoneLists[0].Count, "Zones in set"); } [Test] public void ParseLine_zonePlus() { const string line = "Zone PST 2:00 US P%sT"; var database = new TzdbDatabase("version"); Parser.ParseLine(line, database); const string line2 = " 3:00 US P%sT"; Parser.ParseLine(line2, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.ZoneLists[0].Count, "Zones in set"); } /* ############################################################################### */ [Test] public void ParseLink_emptyString_exception() { var tokens = Tokens.Tokenize(string.Empty); Assert.Throws(typeof(InvalidDataException), () => Parser.ParseLink(tokens)); } [Test] public void ParseLink_simple() { var tokens = Tokens.Tokenize("from to"); var actual = Parser.ParseLink(tokens); var expected = new ZoneAlias("from", "to"); Assert.AreEqual(expected, actual); } [Test] public void ParseLink_tooFewWords_exception() { var tokens = Tokens.Tokenize("from"); Assert.Throws(typeof(InvalidDataException), () => Parser.ParseLink(tokens)); } [Test] public void ParseMonth_emptyString_default() { Assert.AreEqual(0, TzdbZoneInfoParser.ParseMonth(string.Empty)); } [Test] public void ParseMonth_invalidMonth_default() { const string month = "Able"; Assert.AreEqual(0, TzdbZoneInfoParser.ParseMonth(month)); } [Test] public void ParseMonth_months() { for (int i = 0; i < MonthNames.Length; i++) { var month = MonthNames[i]; Assert.AreEqual(i + 1, TzdbZoneInfoParser.ParseMonth(month)); } } [Test] public void ParseMonth_nullArgument_default() { string month = null; Assert.AreEqual(0, TzdbZoneInfoParser.ParseMonth(month)); } [Test] public void ParseZone_badOffset_exception() { var tokens = Tokens.Tokenize("asd US P%sT 1969 Mar 23 14:53:27.856s"); Assert.Throws(typeof(FormatException), () => Parser.ParseZone(string.Empty, tokens)); } /* ############################################################################### */ [Test] public void ParseZone_emptyString_exception() { var tokens = Tokens.Tokenize(string.Empty); Assert.Throws(typeof(InvalidDataException), () => Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_optionalRule() { var tokens = Tokens.Tokenize("2:00 - P%sT"); var expected = new Zone(string.Empty, ToOffset(2, 0), null, "P%sT", int.MaxValue, ZoneYearOffset.StartOfYear); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_simple() { var tokens = Tokens.Tokenize("2:00 US P%sT"); var expected = new Zone(string.Empty, ToOffset(2, 0), "US", "P%sT", int.MaxValue, ZoneYearOffset.StartOfYear); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_tooFewWords1_exception() { var tokens = Tokens.Tokenize("2:00 US"); Assert.Throws(typeof(InvalidDataException), () => Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_tooFewWords2_exception() { var tokens = Tokens.Tokenize("2:00"); Assert.Throws(typeof(InvalidDataException), () => Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_withYear() { var tokens = Tokens.Tokenize("2:00 US P%sT 1969"); var expected = new Zone(string.Empty, ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 1, 1, 0, false, LocalTime.Midnight)); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_withYearMonthDay() { var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23"); var expected = new Zone(string.Empty, ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 3, 23, 0, false, LocalTime.Midnight)); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_withYearMonthDayTime() { var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23 14:53:27.856"); var expected = new Zone(string.Empty, ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 3, 23, 0, false, new LocalTime(14, 53, 27, 856))); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_withYearMonthDayTimeZone() { var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar 23 14:53:27.856s"); var expected = new Zone(string.Empty, ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Standard, 3, 23, 0, false, new LocalTime(14, 53, 27, 856))); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void ParseZone_withDayOfWeek() { var tokens = Tokens.Tokenize("2:00 US P%sT 1969 Mar lastSun"); var expected = new Zone(string.Empty, ToOffset(2, 0), "US", "P%sT", 1969, new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int) IsoDayOfWeek.Sunday, false, LocalTime.Midnight)); Assert.AreEqual(expected, Parser.ParseZone(string.Empty, tokens)); } [Test] public void Parse_emptyStream() { var reader = new StringReader(string.Empty); var database = new TzdbDatabase("version"); Parser.Parse(reader, database); ValidateCounts(database, 0, 0, 0); } [Test] public void Parse_threeLines() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT\n" + " 3:00 - P%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase("version"); Parser.Parse(reader, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.ZoneLists[0].Count, "Zones in set"); } [Test] public void Parse_threeLinesWithComment() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase("version"); Parser.Parse(reader, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(2, database.ZoneLists[0].Count, "Zones in set"); } [Test] public void Parse_twoLines() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase("version"); Parser.Parse(reader, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.ZoneLists[0].Count, "Zones in set"); } [Test] public void Parse_twoLinks() { const string text = "# First line must be a comment\n" + "Link from to\n" + "Link target source\n"; var reader = new StringReader(text); var database = new TzdbDatabase("version"); Parser.Parse(reader, database); ValidateCounts(database, 0, 0, 2); } [Test] public void Parse_twoZones() { const string text = "# A comment\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n" + " 4:00 - P%sT\n" + "Zone EST 2:00 US E%sT # An end of line comment\n" + " 3:00 - E%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase("version"); Parser.Parse(reader, database); ValidateCounts(database, 0, 2, 0); Assert.AreEqual(2, database.ZoneLists[0].Count, "Zones in set " + database.ZoneLists[0].Name); Assert.AreEqual(3, database.ZoneLists[1].Count, "Zones in set " + database.ZoneLists[1].Name); } [Test] public void Parse_twoZonesTwoRule() { const string text = "# A comment\n" + "Rule US 1987 2006 - Apr Sun>=1 2:00 1:00 D\n" + "Rule US 2007 max - Mar Sun>=8 2:00 1:00 D\n" + "Zone PST 2:00 US P%sT # An end of line comment\n" + " 3:00 - P%sT\n" + " 4:00 - P%sT\n" + "Zone EST 2:00 US E%sT # An end of line comment\n" + " 3:00 - E%sT\n"; var reader = new StringReader(text); var database = new TzdbDatabase("version"); Parser.Parse(reader, database); ValidateCounts(database, 1, 2, 0); Assert.AreEqual(2, database.ZoneLists[0].Count, "Zones in set " + database.ZoneLists[0].Name); Assert.AreEqual(3, database.ZoneLists[1].Count, "Zones in set " + database.ZoneLists[1].Name); } /* ############################################################################### */ [Test] public void Parse_2400_FromDay_AtLeast_Sunday() { const string text = "Apr Sun>=1 24:00"; var tokens = Tokens.Tokenize(text); var rule = Parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 2, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtMost_Sunday() { const string text = "Apr Sun<=7 24:00"; var tokens = Tokens.Tokenize(text); var rule = Parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 2, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtLeast_Wednesday() { const string text = "Apr Wed>=1 24:00"; var tokens = Tokens.Tokenize(text); var rule = Parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 5, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay_AtMost_Wednesday() { const string text = "Apr Wed<=14 24:00"; var tokens = Tokens.Tokenize(text); var rule = Parser.ParseDateTimeOfYear(tokens, true); var actual = rule.GetOccurrenceForYear(2012); var expected = new LocalDateTime(2012, 4, 12, 0, 0).ToLocalInstant(); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_FromDay() { const string text = "Apr Sun>=1 24:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 4, 1, (int)IsoDayOfWeek.Sunday, true, LocalTime.Midnight, true); Assert.AreEqual(expected, actual); } [Test] public void Parse_2400_Last() { const string text = "Mar lastSun 24:00"; var tokens = Tokens.Tokenize(text); var actual = Parser.ParseDateTimeOfYear(tokens, true); var expected = new ZoneYearOffset(TransitionMode.Wall, 3, -1, (int)IsoDayOfWeek.Sunday, false, LocalTime.Midnight, true); Assert.AreEqual(expected, actual); } /* ############################################################################### */ [Test] public void Parse_Fixed_Eastern() { const string text = "# A comment\n" + "Zone\tEtc/GMT-9\t9\t-\tGMT-9\n"; var reader = new StringReader(text); var database = new TzdbDatabase("version"); Parser.Parse(reader, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.ZoneLists[0].Count, "Zones in set"); var zone = database.ZoneLists[0][0]; Assert.AreEqual(Offset.FromHours(9), zone.Offset); Assert.IsNull(zone.Rules); Assert.AreEqual(int.MaxValue, zone.UntilYear); } [Test] public void Parse_Fixed_Western() { const string text = "# A comment\n" + "Zone\tEtc/GMT+9\t-9\t-\tGMT+9\n"; var reader = new StringReader(text); var database = new TzdbDatabase("version"); Parser.Parse(reader, database); ValidateCounts(database, 0, 1, 0); Assert.AreEqual(1, database.ZoneLists[0].Count, "Zones in set"); var zone = database.ZoneLists[0][0]; Assert.AreEqual(Offset.FromHours(-9), zone.Offset); Assert.IsNull(zone.Rules); Assert.AreEqual(int.MaxValue, zone.UntilYear); } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Collections; using System.Diagnostics; using Microsoft.DirectX; using Microsoft.Samples.DirectX.UtilityToolkit; using Microsoft.DirectX.DirectInput; namespace Simbiosis { /// <summary> /// User input class /// This version only uses DirectInput for joysticks. It receives mouse & kbd Windows messages via the /// sample framework's OnMsgProc() method, so that the UI works. Any messages it doesn't handle are returned. /// </summary> public static class UserInput { /// <summary> Current states of all the keys </summary> private static bool[] KeyState = new bool[256]; private const int joyThrust = 0; // joystick button for thrust private static Device joystick = null; private static JoystickState joystickState = new JoystickState(); private static Vector3 virtualJoystick = new Vector3(); // raw xyz values for mouse joystick emulation const float VIRTUALJOYSTICKRANGE = 300; // how much to scale down the mouse movements /// <summary> The mouse location when the right button went down </summary> private static Vector3 dragPoint = new Vector3(0,0,0); /// <summary> true if the right button is down (joystick emulation) </summary> private static bool dragging = false; /// <summary> The current mouse position </summary> public static Vector3 Mouse = new Vector3(0,0,0); /// <summary> true if the left mouse button is down (emulates joystick FIRE btn) </summary> public static bool leftButton = false; static UserInput() { } /// <summary> /// Once the first D3D device has been created, set up those things that couldn't be done before /// </summary> public static void OnDeviceCreated() { // Set up a joystick if available foreach (DeviceInstance instance in Manager.GetDevices(DeviceClass.GameControl,EnumDevicesFlags.AttachedOnly)) { joystick = new Device(instance.InstanceGuid); // Grab the first connected joystick break; } if (joystick!=null) { joystick.SetCooperativeLevel(Engine.Framework.Window, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.Exclusive); joystick.SetDataFormat(DeviceDataFormat.Joystick); joystick.Properties.SetRange(ParameterHow.ByDevice,0,new InputRange(-1000,1000)); // set all ranges to +/-1000 joystick.Properties.SetDeadZone(ParameterHow.ByDevice,0,2000); // we need a dead zone for stability } } /// <summary> /// Called immediately after the D3D device has been destroyed, /// which generally happens as a result of application termination or /// windowed/full screen toggles. Resources created in OnSubsequentDevices() /// should be released here, which generally includes all Pool.Managed resources. /// </summary> public static void OnDeviceLost() { if (joystick!=null) joystick.Unacquire(); } /// <summary> /// Poll the devices - call every frame /// </summary> public static void Update() { // Read any joystick try { if (joystick!=null) { joystick.Poll(); joystickState = joystick.CurrentJoystickState; } } catch { try { joystick.Acquire(); return; } catch { return; } } // If the mouse right button is down, make it emulate a joystick EmulateJoystick(); // Now we farm out the input to the right recipients ProcessInput(); } private static void ProcessInput() { // Assemble camera control commands and send them to the current camera ship TillerData tiller = new TillerData(); tiller.Joystick = ReadJoystick(); // reads joystick, or mouse/kbd emulation if (leftButton) // if left mouse btn down, full thrust tiller.Thrust = 1.0f; else if ((joystick!=null)&& (joystickState.GetButtons())[joyThrust]!=0) // or if main joystick button, full thrust tiller.Thrust = 1.0f; CameraShip.SteerShip(tiller); // send data to the current camera ship } /// <summary> /// This method emulates a joystick using the mouse. If the right button is down, dragging /// the mouse works the same as the equivalent joystick movements. /// The scroll wheel (if present) emulates the throttle. /// </summary> private static void EmulateJoystick() { if (dragging) { virtualJoystick.X = Mouse.X - dragPoint.X; virtualJoystick.Y = Mouse.Y - dragPoint.Y; // virtualJoystick.Z = Mouse.Z - dragPoint.Z; // control wheel, if present } } /// <summary> /// Read the virtual joystick if the right mouse button is down, or the real one if not. /// If the mouse button is not down and there is no joystick attached, return 0,0,0 /// </summary> /// <returns>the xyz of the joystick (z=throttle (or scrollwheel if mouse))</returns> public static Vector3 ReadJoystick() { // if the right mouse button is down, the mouse overrides any real joystick if (dragging) { Vector3 virt = virtualJoystick; virt.X /= VIRTUALJOYSTICKRANGE; virt.Y /= VIRTUALJOYSTICKRANGE; // virt.Z /= VIRTUALJOYSTICKRANGE; if (virt.X<-1.0) virt.X = -1.0f; else if (virt.X>1.0) virt.X = 1.0f; if (virt.Y<-1.0) virt.Y = -1.0f; else if (virt.Y>1.0) virt.Y = 1.0f; // if (virt.Z<-1.0) virt.Z = -1.0f; // else if (virt.Z>1.0) virt.Z = 1.0f; // include a dead zone in the centre const float dead = 0.05f; if ((virt.X>-dead)&&(virt.X<dead)) virt.X = 0; if ((virt.Y>-dead)&&(virt.Y<dead)) virt.Y = 0; return virt; } // if there's no physical joystick, return 0,0,0 if (joystick==null) { return Vector3.Empty; } // read the real joystick return new Vector3( (float)joystickState.X / 1000, (float)joystickState.Y / 1000, (float)joystickState.Rz / 1000); // HACK: my joystick has throttle on Z ROTATION. What do stick+rudder combos do??? } /// <summary> /// Handle Windows messages relating to the mouse and keyboard. /// I don't use DirectInput for this because the sample framework requires Windows mouse messages /// and DirectInput suppresses them. /// Call this from the Engine's message handler /// </summary> /// <returns>true if it handled this message</returns> public static bool OnMsgProc(IntPtr hWnd, NativeMethods.WindowMessage msg, IntPtr wParam, IntPtr lParam) { // Mouse movements are recorded (but the message is passed on to others) if (msg==NativeMethods.WindowMessage.MouseMove) { Mouse.X = NativeMethods.LoWord((uint)lParam.ToInt32()); Mouse.Y = NativeMethods.HiWord((uint)lParam.ToInt32()); if (dragging) return true; return false; } // // Mouse wheel movements // if (msg==NativeMethods.WindowMessage.MouseWheel) // { // Mouse.Z = NativeMethods.LoWord((uint)lParam.ToInt32()); // return false; // } // If the right button has been pressed, record the mouse location // so that drags can be used to drive cameras if (msg==NativeMethods.WindowMessage.RightButtonDown) { dragPoint.X = NativeMethods.LoWord((uint)lParam.ToInt32()); dragPoint.Y = NativeMethods.HiWord((uint)lParam.ToInt32()); dragPoint.Z = Mouse.Z; dragging = true; System.Windows.Forms.Cursor.Hide(); if (Engine.Framework.IsWindowed) NativeMethods.SetCapture(hWnd); return true; } // when the button is released, stop dragging the camera if (msg==NativeMethods.WindowMessage.RightButtonUp) { dragging = false; System.Windows.Forms.Cursor.Show(); if (Engine.Framework.IsWindowed) NativeMethods.ReleaseCapture(); return true; } // TODO: Left button clicks are handled here // (remember only return true if nobody else should have the msg) if (msg==NativeMethods.WindowMessage.LeftButtonDown) { // If we're not emulating a joystick, handle a click as a possible widget or 3D object selection command if (!dragging) { return LeftClick(); } // else just record the state of the button, so that the joystick emulator can treat it as the FIRE button leftButton = true; return true; } if (msg==NativeMethods.WindowMessage.LeftButtonUp) { // If we're not emulating a joystick, handle a release as a possible widget release if (!dragging) { return LeftRelease(); } // else just record the state of the button, so that the joystick emulator can treat it as the FIRE button leftButton = false; return true; } // Keydown message if (msg==NativeMethods.WindowMessage.KeyDown) { int key = wParam.ToInt32(); // System.Windows.Forms.Keys enum is wParam KeyState[key] = true; // record new state for hold-down behaviours (tested during Update()) return HandleKeypress((Keys)key); // but trigger any keypress behaviours now } // Keyup message if (msg==NativeMethods.WindowMessage.KeyUp) { int key = wParam.ToInt32(); // System.Windows.Forms.Keys enum is wParam key &= 255; // mask off the control key states KeyState[key] = false; return HandleKeyRelease((Keys)key); // but trigger any keyrelease behaviours now } return false; } /// <summary> /// Left button has been pressed (when we're not in joystick emulation mode). /// Pass this to the currently active panel (might be a clicked widget or a 3D pick of a creature) /// </summary> /// <returns></returns> private static bool LeftClick() { if (CameraShip.CurrentShip.LeftClick(Mouse) == true) return true; // TODO: Other responses to left clicks go here return false; } /// <summary> /// Left button has been released (when we're not in joystick emulation mode). /// Pass this to the currently active panel (might be releasing a widget) /// </summary> /// <returns></returns> private static bool LeftRelease() { if (CameraShip.CurrentShip.LeftRelease(Mouse) == true) return true; // TODO: Other responses to left release go here return false; } /// <summary> /// A key has been pressed - execute a command if appropriate /// </summary> /// <param name="key">the key pressed - compare to Keys.###</param> /// <returns>true if the key was handled</returns> private static bool HandleKeypress(Keys key) { // If an EditBox currently has focus, all keypresses get directed there if (EditBox.Focus != null) return EditBox.Focus.KeyPress(key); // Keypresses common to all modes... switch (key) { // Save a screenshot to disk case Keys.S: Scene.SaveScreenshot("Screenshot.bmp"); break; // Toggle fullscreen mode case Keys.W: Engine.Framework.ToggleFullscreen(); break; // DirectX settings dialogue case Keys.X: Engine.Framework.ShowSettingsDialog(!Engine.Framework.IsD3DSettingsDialogShowing); break; } // Pass all other keys to the current camera ship cockpit return CameraShip.CurrentShip.KeyPress(key); } /// <summary> /// A key has been released - pass this through to camera ship, then panel, then widgets /// </summary> /// <param name="key">the key that was released - compare to Keys.###</param> /// <returns>true if the key was handled</returns> private static bool HandleKeyRelease(Keys key) { // Pass all keys to the current camera ship cockpit return CameraShip.CurrentShip.KeyRelease(key); } /// <summary> /// Return true if the SHIFT key is currently down /// </summary> /// <returns></returns> public static bool IsShift() { return KeyState[(int)Keys.ShiftKey]; } /// <summary> /// Return true if the CTRL key is currently down /// </summary> /// <returns></returns> public static bool IsCtrl() { return KeyState[(int)Keys.ControlKey]; } } }
// 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; namespace System.Collections.Specialized.Tests { public static class StringCollectionTests { private const string ElementNotPresent = "element-not-present"; /// <summary> /// Data used for testing with Insert. /// </summary> /// Format is: /// 1. initial Collection /// 2. internal data /// 3. data to insert (ElementNotPresent or null) /// 4. location to insert (0, count / 2, count) /// <returns>Row of data</returns> public static IEnumerable<object[]> Insert_Data() { foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data())) { string[] d = (string[])(data[1]); foreach (string element in new[] { ElementNotPresent, null }) { foreach (int location in new[] { 0, d.Length / 2, d.Length }.Distinct()) { StringCollection initial = new StringCollection(); initial.AddRange(d); yield return new object[] { initial, d, element, location }; } } } }/// <summary> /// Data used for testing with RemoveAt. /// </summary> /// Format is: /// 1. initial Collection /// 2. internal data /// 3. location to remove (0, count / 2, count) /// <returns>Row of data</returns> public static IEnumerable<object[]> RemoveAt_Data() { foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data())) { string[] d = (string[])(data[1]); if (d.Length > 0) { foreach (int location in new[] { 0, d.Length / 2, d.Length - 1 }.Distinct()) { StringCollection initial = new StringCollection(); initial.AddRange(d); yield return new object[] { initial, d, location }; } } } } /// <summary> /// Data used for testing with a set of collections. /// </summary> /// Format is: /// 1. Collection /// 2. internal data /// <returns>Row of data</returns> public static IEnumerable<object[]> StringCollection_Data() { yield return ConstructRow(new string[] { /* empty */ }); yield return ConstructRow(new string[] { null }); yield return ConstructRow(new string[] { "single" }); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x.ToString()).ToArray()); for (int index = 0; index < 100; index += 25) { yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x == index ? null : x.ToString()).ToArray()); } } /// <summary> /// Data used for testing with a set of collections, where the data has duplicates. /// </summary> /// Format is: /// 1. Collection /// 2. internal data /// <returns>Row of data</returns> public static IEnumerable<object[]> StringCollection_Duplicates_Data() { yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (string)null).ToArray()); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x % 10 == 0 ? null : (x % 10).ToString()).ToArray()); yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (x % 10).ToString()).ToArray()); } private static object[] ConstructRow(string[] data) { if (data.Contains(ElementNotPresent)) throw new ArgumentException("Do not include \"" + ElementNotPresent + "\" in data."); StringCollection col = new StringCollection(); col.AddRange(data); return new object[] { col, data }; } [Fact] public static void Constructor_DefaultTest() { StringCollection sc = new StringCollection(); Assert.Equal(0, sc.Count); Assert.False(sc.Contains(null)); Assert.False(sc.Contains("")); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void AddTest(StringCollection collection, string[] data) { StringCollection added = new StringCollection(); for (int i = 0; i < data.Length; i++) { Assert.Equal(i, added.Count); Assert.Throws<ArgumentOutOfRangeException>(() => added[i]); added.Add(data[i]); Assert.Equal(data[i], added[i]); Assert.Equal(i + 1, added.Count); } Assert.Equal(collection, added); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void Add_ExplicitInterface_Test(StringCollection collection, string[] data) { IList added = new StringCollection(); for (int i = 0; i < data.Length; i++) { Assert.Equal(i, added.Count); Assert.Throws<ArgumentOutOfRangeException>(() => added[i]); added.Add(data[i]); Assert.Equal(data[i], added[i]); Assert.Equal(i + 1, added.Count); } Assert.Equal(collection, added); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void AddRangeTest(StringCollection collection, string[] data) { StringCollection added = new StringCollection(); added.AddRange(data); Assert.Equal(collection, added); added.AddRange(new string[] { /*empty*/}); Assert.Equal(collection, added); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void AddRange_NullTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentNullException>("value", () => collection.AddRange(null)); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void ClearTest(StringCollection collection, string[] data) { Assert.Equal(data.Length, collection.Count); collection.Clear(); Assert.Equal(0, collection.Count); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void CopyToTest(StringCollection collection, string[] data) { string[] full = new string[data.Length]; collection.CopyTo(full, 0); Assert.Equal(data, full); string[] large = new string[data.Length * 2]; collection.CopyTo(large, data.Length / 4); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 4 || i >= data.Length + data.Length / 4) { Assert.Null(large[i]); } else { Assert.Equal(data[i - data.Length / 4], large[i]); } } } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void CopyTo_ExplicitInterface_Test(ICollection collection, string[] data) { string[] full = new string[data.Length]; collection.CopyTo(full, 0); Assert.Equal(data, full); string[] large = new string[data.Length * 2]; collection.CopyTo(large, data.Length / 4); for (int i = 0; i < large.Length; i++) { if (i < data.Length / 4 || i >= data.Length + data.Length / 4) { Assert.Null(large[i]); } else { Assert.Equal(data[i - data.Length / 4], large[i]); } } } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void CopyTo_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(data, -1)); if (data.Length > 0) { Assert.Throws<ArgumentException>(() => collection.CopyTo(new string[0], data.Length - 1)); Assert.Throws<ArgumentException>(() => collection.CopyTo(new string[data.Length - 1], 0)); } // As explicit interface implementation Assert.Throws<ArgumentNullException>(() => ((ICollection)collection).CopyTo(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => ((ICollection)collection).CopyTo(data, -1)); if (data.Length > 0) { Assert.Throws<ArgumentException>(() => ((ICollection)collection).CopyTo(new string[0], data.Length - 1)); Assert.Throws<ArgumentException>(() => ((ICollection)collection).CopyTo(new string[data.Length - 1], 0)); } } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void CountTest(StringCollection collection, string[] data) { Assert.Equal(data.Length, collection.Count); collection.Clear(); Assert.Equal(0, collection.Count); collection.Add("one"); Assert.Equal(1, collection.Count); collection.AddRange(data); Assert.Equal(1 + data.Length, collection.Count); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void ContainsTest(StringCollection collection, string[] data) { Assert.All(data, element => Assert.True(collection.Contains(element))); Assert.All(data, element => Assert.True(((IList)collection).Contains(element))); Assert.False(collection.Contains(ElementNotPresent)); Assert.False(((IList)collection).Contains(ElementNotPresent)); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void GetEnumeratorTest(StringCollection collection, string[] data) { bool repeat = true; StringEnumerator enumerator = collection.GetEnumerator(); Assert.NotNull(enumerator); while (repeat) { Assert.Throws<InvalidOperationException>(() => enumerator.Current); foreach (string element in data) { Assert.True(enumerator.MoveNext()); Assert.Equal(element, enumerator.Current); Assert.Equal(element, enumerator.Current); } Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); Assert.False(enumerator.MoveNext()); enumerator.Reset(); enumerator.Reset(); repeat = false; } } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void GetEnumerator_ModifiedCollectionTest(StringCollection collection, string[] data) { StringEnumerator enumerator = collection.GetEnumerator(); Assert.NotNull(enumerator); if (data.Length > 0) { Assert.True(enumerator.MoveNext()); string current = enumerator.Current; Assert.Equal(data[0], current); collection.RemoveAt(0); if (data.Length > 1 && data[0] != data[1]) { Assert.NotEqual(current, collection[0]); } Assert.Equal(current, enumerator.Current); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); } else { collection.Add("newValue"); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); } } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void GetSetTest(StringCollection collection, string[] data) { for (int i = 0; i < data.Length; i++) { Assert.Equal(data[i], collection[i]); } for (int i = 0; i < data.Length / 2; i++) { string temp = collection[i]; collection[i] = collection[data.Length - i - 1]; collection[data.Length - i - 1] = temp; } for (int i = 0; i < data.Length; i++) { Assert.Equal(data[data.Length - i - 1], collection[i]); } } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void GetSet_ExplicitInterface_Test(IList collection, string[] data) { for (int i = 0; i < data.Length; i++) { Assert.Equal(data[i], collection[i]); } for (int i = 0; i < data.Length / 2; i++) { object temp = collection[i]; if (temp != null) { Assert.IsType<string>(temp); } collection[i] = collection[data.Length - i - 1]; collection[data.Length - i - 1] = temp; } for (int i = 0; i < data.Length; i++) { Assert.Equal(data[data.Length - i - 1], collection[i]); } } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void GetSet_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = null); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = null); Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length]); // As explicitly implementing the interface Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = null); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = ElementNotPresent); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = null); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1]); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length]); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void IndexOfTest(StringCollection collection, string[] data) { Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element))); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element))); Assert.Equal(-1, collection.IndexOf(ElementNotPresent)); Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent)); } [Theory] [MemberData("StringCollection_Duplicates_Data")] public static void IndexOf_DuplicateTest(StringCollection collection, string[] data) { // Only the index of the first element will be returned. data = data.Distinct().ToArray(); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element))); Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element))); Assert.Equal(-1, collection.IndexOf(ElementNotPresent)); Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent)); } [Theory] [MemberData("Insert_Data")] public static void InsertTest(StringCollection collection, string[] data, string element, int location) { collection.Insert(location, element); Assert.Equal(data.Length + 1, collection.Count); if (element == ElementNotPresent) { Assert.Equal(location, collection.IndexOf(ElementNotPresent)); } for (int i = 0; i < data.Length + 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i == location) { Assert.Equal(element, collection[i]); } else { Assert.Equal(data[i - 1], collection[i]); } } } [Theory] [MemberData("Insert_Data")] public static void Insert_ExplicitInterface_Test(IList collection, string[] data, string element, int location) { collection.Insert(location, element); Assert.Equal(data.Length + 1, collection.Count); if (element == ElementNotPresent) { Assert.Equal(location, collection.IndexOf(ElementNotPresent)); } for (int i = 0; i < data.Length + 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i == location) { Assert.Equal(element, collection[i]); } else { Assert.Equal(data[i - 1], collection[i]); } } } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void Insert_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, ElementNotPresent)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(data.Length + 1, ElementNotPresent)); // And as explicit interface implementation Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(-1, ElementNotPresent)); Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(data.Length + 1, ElementNotPresent)); } [Fact] public static void IsFixedSizeTest() { Assert.False(((IList)new StringCollection()).IsFixedSize); } [Fact] public static void IsReadOnlyTest() { Assert.False(new StringCollection().IsReadOnly); Assert.False(((IList)new StringCollection()).IsReadOnly); } [Fact] public static void IsSynchronizedTest() { Assert.False(new StringCollection().IsSynchronized); Assert.False(((IList)new StringCollection()).IsSynchronized); } [Theory] [MemberData("StringCollection_Data")] public static void RemoveTest(StringCollection collection, string[] data) { Assert.All(data, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); Assert.False(collection.Contains(element)); Assert.False(((IList)collection).Contains(element)); }); Assert.Equal(0, collection.Count); } [Theory] [MemberData("StringCollection_Data")] public static void Remove_IListTest(StringCollection collection, string[] data) { Assert.All(data, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.False(collection.Contains(element)); Assert.False(((IList)collection).Contains(element)); }); Assert.Equal(0, collection.Count); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void Remove_NotPresentTest(StringCollection collection, string[] data) { collection.Remove(ElementNotPresent); Assert.Equal(data.Length, collection.Count); ((IList)collection).Remove(ElementNotPresent); Assert.Equal(data.Length, collection.Count); } [Theory] [MemberData("StringCollection_Duplicates_Data")] public static void Remove_DuplicateTest(StringCollection collection, string[] data) { // Only the first element will be removed. string[] first = data.Distinct().ToArray(); Assert.All(first, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); }); Assert.Equal(data.Length - first.Length, collection.Count); for (int i = first.Length; i < data.Length; i++) { string element = data[i]; Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); collection.Remove(element); bool stillPresent = i < data.Length - first.Length; Assert.Equal(stillPresent, collection.Contains(element)); Assert.Equal(stillPresent, ((IList)collection).Contains(element)); } Assert.Equal(0, collection.Count); } [Theory] [MemberData("RemoveAt_Data")] public static void RemoveAtTest(StringCollection collection, string[] data, int location) { collection.RemoveAt(location); Assert.Equal(data.Length - 1, collection.Count); for (int i = 0; i < data.Length - 1; i++) { if (i < location) { Assert.Equal(data[i], collection[i]); } else if (i >= location) { Assert.Equal(data[i + 1], collection[i]); } } } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void RemoveAt_ArgumentInvalidTest(StringCollection collection, string[] data) { Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(data.Length)); } [Theory] [MemberData("StringCollection_Duplicates_Data")] public static void Remove_Duplicate_IListTest(StringCollection collection, string[] data) { // Only the first element will be removed. string[] first = data.Distinct().ToArray(); Assert.All(first, element => { Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); }); Assert.Equal(data.Length - first.Length, collection.Count); for (int i = first.Length; i < data.Length; i++) { string element = data[i]; Assert.True(collection.Contains(element)); Assert.True(((IList)collection).Contains(element)); ((IList)collection).Remove(element); bool stillPresent = i < data.Length - first.Length; Assert.Equal(stillPresent, collection.Contains(element)); Assert.Equal(stillPresent, ((IList)collection).Contains(element)); } Assert.Equal(0, collection.Count); } [Theory] [MemberData("StringCollection_Data")] [MemberData("StringCollection_Duplicates_Data")] public static void SyncRootTest(StringCollection collection, string[] data) { object syncRoot = collection.SyncRoot; Assert.NotNull(syncRoot); Assert.IsType<object>(syncRoot); Assert.Same(syncRoot, collection.SyncRoot); Assert.NotSame(syncRoot, new StringCollection().SyncRoot); StringCollection other = new StringCollection(); other.AddRange(data); Assert.NotSame(syncRoot, other.SyncRoot); } } }
/* * Copyright (C) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if UNITY_ANDROID using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using GooglePlayGames.BasicApi; using GooglePlayGames.OurUtils; using GooglePlayGames.BasicApi.Multiplayer; namespace GooglePlayGames.Android { internal class AndroidTbmpClient : ITurnBasedMultiplayerClient { AndroidClient mClient = null; int mMaxMatchDataSize = 0; // the match we got from the notification TurnBasedMatch mMatchFromNotification = null; // the match delegate we invoke when we get a match from the notification MatchDelegate mMatchDelegate = null; internal AndroidTbmpClient(AndroidClient client) { mClient = client; } // called on UI thread public void OnSignInSucceeded() { Logger.d("AndroidTbmpClient.OnSignInSucceeded"); Logger.d("Querying for max match data size..."); mMaxMatchDataSize = mClient.GHManager.CallGmsApi<int>("games.Games", "TurnBasedMultiplayer", "getMaxMatchDataSize"); Logger.d("Max match data size: " + mMaxMatchDataSize); } // called on game thread public void CreateQuickMatch(int minOpponents, int maxOpponents, int variant, Action<bool, TurnBasedMatch> callback) { Logger.d(string.Format("AndroidTbmpClient.CreateQuickMatch, opponents {0}-{1}, var {2}", minOpponents, maxOpponents, variant)); mClient.CallClientApi("tbmp create quick game", () => { ResultProxy proxy = new ResultProxy(this, "createMatch"); proxy.SetMatchCallback(callback); AndroidJavaClass tbmpUtil = JavaUtil.GetClass(JavaConsts.SupportTbmpUtilsClass); using (AndroidJavaObject pendingResult = tbmpUtil.CallStatic<AndroidJavaObject>( "createQuickMatch", mClient.GHManager.GetApiClient(), minOpponents, maxOpponents, variant)) { pendingResult.Call("setResultCallback", proxy); } }, (bool success) => { if (!success) { Logger.w("Failed to create tbmp quick match: client disconnected."); if (callback != null) { callback.Invoke(false, null); } } }); } // called on game thread public void CreateWithInvitationScreen(int minOpponents, int maxOpponents, int variant, Action<bool, TurnBasedMatch> callback) { Logger.d(string.Format("AndroidTbmpClient.CreateWithInvitationScreen, " + "opponents {0}-{1}, variant {2}", minOpponents, maxOpponents, variant)); mClient.CallClientApi("tbmp launch invitation screen", () => { AndroidJavaClass klass = JavaUtil.GetClass( JavaConsts.SupportSelectOpponentsHelperActivity); klass.CallStatic("launch", false, mClient.GetActivity(), new SelectOpponentsProxy(this, callback, variant), Logger.DebugLogEnabled, minOpponents, maxOpponents); }, (bool success) => { if (!success) { Logger.w("Failed to create tbmp w/ invite screen: client disconnected."); if (callback != null) { callback.Invoke(false, null); } } }); } // called on game thread public void AcceptFromInbox(Action<bool, TurnBasedMatch> callback) { Logger.d(string.Format("AndroidTbmpClient.AcceptFromInbox")); mClient.CallClientApi("tbmp launch inbox", () => { AndroidJavaClass klass = JavaUtil.GetClass( JavaConsts.SupportInvitationInboxHelperActivity); klass.CallStatic("launch", false, mClient.GetActivity(), new InvitationInboxProxy(this, callback), Logger.DebugLogEnabled); }, (bool success) => { if (!success) { Logger.w("Failed to accept tbmp w/ inbox: client disconnected."); if (callback != null) { callback.Invoke(false, null); } } }); } // called on game thread public void AcceptInvitation(string invitationId, Action<bool, TurnBasedMatch> callback) { Logger.d("AndroidTbmpClient.AcceptInvitation invitationId=" + invitationId); TbmpApiCall("accept invitation", "acceptInvitation", null, callback, invitationId); } // called on game thread public void DeclineInvitation(string invitationId) { Logger.d("AndroidTbmpClient.DeclineInvitation, invitationId=" + invitationId); TbmpApiCall("decline invitation", "declineInvitation", null, null, invitationId); } // called from game thread private void TbmpApiCall(string simpleDesc, string methodName, Action<bool> callback, Action<bool, TurnBasedMatch> tbmpCallback, params object[] args) { mClient.CallClientApi(simpleDesc, () => { ResultProxy proxy = new ResultProxy(this, methodName); if (callback != null) { proxy.SetSuccessCallback(callback); } if (tbmpCallback != null) { proxy.SetMatchCallback(tbmpCallback); } mClient.GHManager.CallGmsApiWithResult("games.Games", "TurnBasedMultiplayer", methodName, proxy, args); }, (bool success) => { if (!success) { Logger.w("Failed to " + simpleDesc + ": client disconnected."); if (callback != null) { callback.Invoke(false); } } }); } // called on game thread public void TakeTurn(string matchId, byte[] data, string pendingParticipantId, Action<bool> callback) { Logger.d(string.Format("AndroidTbmpClient.TakeTurn matchId={0}, data={1}, " + "pending={2}", matchId, (data == null ? "(null)" : "[" + data.Length + "bytes]"), pendingParticipantId)); TbmpApiCall("tbmp take turn", "takeTurn", callback, null, matchId, data, pendingParticipantId); } // called on game thread public int GetMaxMatchDataSize() { return mMaxMatchDataSize; } public void Finish(string matchId, byte[] data, MatchOutcome outcome, Action<bool> callback) { Logger.d(string.Format("AndroidTbmpClient.Finish matchId={0}, data={1} outcome={2}", matchId, data == null ? "(null)" : data.Length + " bytes", outcome)); Logger.d("Preparing list of participant results as Android ArrayList."); AndroidJavaObject participantResults = new AndroidJavaObject("java.util.ArrayList"); if (outcome != null) { foreach (string pid in outcome.ParticipantIds) { Logger.d("Converting participant result to Android object: " + pid); AndroidJavaObject thisParticipantResult = new AndroidJavaObject( JavaConsts.ParticipantResultClass, pid, JavaUtil.GetAndroidParticipantResult(outcome.GetResultFor(pid)), outcome.GetPlacementFor(pid)); // (yes, the return type of ArrayList.add is bool, strangely) Logger.d("Adding participant result to Android ArrayList."); participantResults.Call<bool>("add", thisParticipantResult); thisParticipantResult.Dispose(); } } TbmpApiCall("tbmp finish w/ outcome", "finishMatch", callback, null, matchId, data, participantResults); } public void AcknowledgeFinished(string matchId, Action<bool> callback) { Logger.d("AndroidTbmpClient.AcknowledgeFinished, matchId=" + matchId); TbmpApiCall("tbmp ack finish", "finishMatch", callback, null, matchId); } public void Leave(string matchId, Action<bool> callback) { Logger.d("AndroidTbmpClient.Leave, matchId=" + matchId); TbmpApiCall("tbmp leave", "leaveMatch", callback, null, matchId); } public void LeaveDuringTurn(string matchId, string pendingParticipantId, Action<bool> callback) { Logger.d("AndroidTbmpClient.LeaveDuringTurn, matchId=" + matchId + ", pending=" + pendingParticipantId); TbmpApiCall("tbmp leave during turn", "leaveMatchDuringTurn", callback, null, matchId, pendingParticipantId); } public void Cancel(string matchId, Action<bool> callback) { Logger.d("AndroidTbmpClient.Cancel, matchId=" + matchId); TbmpApiCall("tbmp cancel", "cancelMatch", callback, null, matchId); } public void Rematch(string matchId, Action<bool, TurnBasedMatch> callback) { Logger.d("AndroidTbmpClient.Rematch, matchId=" + matchId); TbmpApiCall("tbmp rematch", "rematch", null, callback, matchId); } public void RegisterMatchDelegate(MatchDelegate deleg) { Logger.d("AndroidTbmpClient.RegisterMatchDelegate"); if (deleg == null) { Logger.w("Can't register a null match delegate."); return; } mMatchDelegate = deleg; // if we have a pending match to deliver, deliver it now if (mMatchFromNotification != null) { Logger.d("Delivering pending match to the newly registered delegate."); TurnBasedMatch match = mMatchFromNotification; mMatchFromNotification = null; PlayGamesHelperObject.RunOnGameThread(() => { deleg.Invoke(match, true); }); } } private void OnSelectOpponentsResult(bool success, AndroidJavaObject opponents, bool hasAutoMatch, AndroidJavaObject autoMatchCriteria, Action<bool, TurnBasedMatch> callback, int variant) { Logger.d("AndroidTbmpClient.OnSelectOpponentsResult, success=" + success + ", hasAutoMatch=" + hasAutoMatch); if (!success) { Logger.w("Tbmp select opponents dialog terminated with failure."); if (callback != null) { Logger.d("Reporting select-opponents dialog failure to callback."); PlayGamesHelperObject.RunOnGameThread(() => { callback.Invoke(false, null); }); } return; } Logger.d("Creating TBMP match from opponents received from dialog."); mClient.CallClientApi("create match w/ opponents from dialog", () => { ResultProxy proxy = new ResultProxy(this, "createMatch"); proxy.SetMatchCallback(callback); AndroidJavaClass tbmpUtil = JavaUtil.GetClass(JavaConsts.SupportTbmpUtilsClass); using (AndroidJavaObject pendingResult = tbmpUtil.CallStatic<AndroidJavaObject>( "create", mClient.GHManager.GetApiClient(), opponents, variant, hasAutoMatch ? autoMatchCriteria : null)) { pendingResult.Call("setResultCallback", proxy); } }, (bool ok) => { if (!ok) { Logger.w("Failed to create match w/ opponents from dialog: client disconnected."); if (callback != null) { callback.Invoke(false, null); } } }); } private void OnInvitationInboxResult(bool success, string invitationId, Action<bool, TurnBasedMatch> callback) { Logger.d("AndroidTbmpClient.OnInvitationInboxResult, success=" + success + ", " + "invitationId=" + invitationId); if (!success) { Logger.w("Tbmp invitation inbox returned failure result."); if (callback != null) { Logger.d("Reporting tbmp invitation inbox failure to callback."); PlayGamesHelperObject.RunOnGameThread(() => { callback.Invoke(false, null); }); } return; } Logger.d("Accepting invite received from inbox: " + invitationId); TbmpApiCall("accept invite returned from inbox", "acceptInvitation", null, callback, invitationId); } private void OnInvitationInboxTurnBasedMatch(AndroidJavaObject matchObj, Action<bool, TurnBasedMatch> callback) { Logger.d("AndroidTbmpClient.OnInvitationTurnBasedMatch"); Logger.d("Converting received match to our format..."); TurnBasedMatch match = JavaUtil.ConvertMatch(mClient.PlayerId, matchObj); Logger.d("Resulting match: " + match); if (callback != null) { Logger.d("Invoking match callback w/ success."); PlayGamesHelperObject.RunOnGameThread(() => { callback.Invoke(true, match); }); } } internal void HandleMatchFromNotification(TurnBasedMatch match) { Logger.d("AndroidTbmpClient.HandleMatchFromNotification"); Logger.d("Got match from notification: " + match); if (mMatchDelegate != null) { Logger.d("Delivering match directly to match delegate."); MatchDelegate del = mMatchDelegate; PlayGamesHelperObject.RunOnGameThread(() => { del.Invoke(match, true); }); } else { Logger.d("Since we have no match delegate, holding on to the match until we have one."); mMatchFromNotification = match; } } private class ResultProxy : AndroidJavaProxy { private AndroidTbmpClient mOwner; private string mMethod = "?"; private Action<bool> mSuccessCallback = null; private Action<bool, TurnBasedMatch> mMatchCallback = null; private List<int> mSuccessCodes = new List<int>(); internal ResultProxy(AndroidTbmpClient owner, string method) : base(JavaConsts.ResultCallbackClass) { mOwner = owner; mSuccessCodes.Add(JavaConsts.STATUS_OK); mSuccessCodes.Add(JavaConsts.STATUS_DEFERRED); mSuccessCodes.Add(JavaConsts.STATUS_STALE_DATA); mMethod = method; } public void SetSuccessCallback(Action<bool> callback) { mSuccessCallback = callback; } public void SetMatchCallback(Action<bool, TurnBasedMatch> callback) { mMatchCallback = callback; } public void AddSuccessCodes(params int[] codes) { foreach (int code in codes) { mSuccessCodes.Add(code); } } public void onResult(AndroidJavaObject result) { Logger.d("ResultProxy got result for method: " + mMethod); int statusCode = JavaUtil.GetStatusCode(result); bool isSuccess = mSuccessCodes.Contains(statusCode); TurnBasedMatch match = null; if (isSuccess) { Logger.d("SUCCESS result from method " + mMethod + ": " + statusCode); if (mMatchCallback != null) { Logger.d("Attempting to get match from result of " + mMethod); AndroidJavaObject matchObj = JavaUtil.CallNullSafeObjectMethod(result, "getMatch"); if (matchObj != null) { Logger.d("Successfully got match from result of " + mMethod); match = JavaUtil.ConvertMatch(mOwner.mClient.PlayerId, matchObj); matchObj.Dispose(); } else { Logger.w("Got a NULL match from result of " + mMethod); } } } else { Logger.w("ERROR result from " + mMethod + ": " + statusCode); } if (mSuccessCallback != null) { Logger.d("Invoking success callback (success=" + isSuccess + ") for " + "result of method " + mMethod); PlayGamesHelperObject.RunOnGameThread(() => { mSuccessCallback.Invoke(isSuccess); }); } if (mMatchCallback != null) { Logger.d("Invoking match callback for result of method " + mMethod + ": " + "(success=" + isSuccess + ", match=" + (match == null ? "(null)" : match.ToString())); PlayGamesHelperObject.RunOnGameThread(() => { mMatchCallback.Invoke(isSuccess, match); }); } } } private class SelectOpponentsProxy : AndroidJavaProxy { AndroidTbmpClient mOwner; Action<bool, TurnBasedMatch> mCallback; int mVariant; internal SelectOpponentsProxy(AndroidTbmpClient owner, Action<bool, TurnBasedMatch> callback, int variant) : base(JavaConsts.SupportSelectOpponentsHelperActivityListener) { mOwner = owner; mCallback = callback; mVariant = variant; } public void onSelectOpponentsResult(bool success, AndroidJavaObject opponents, bool hasAutoMatch, AndroidJavaObject autoMatchCriteria) { mOwner.OnSelectOpponentsResult(success, opponents, hasAutoMatch, autoMatchCriteria, mCallback, mVariant); } } private class InvitationInboxProxy : AndroidJavaProxy { AndroidTbmpClient mOwner; Action<bool, TurnBasedMatch> mCallback; internal InvitationInboxProxy(AndroidTbmpClient owner, Action<bool, TurnBasedMatch> callback) : base(JavaConsts.SupportInvitationInboxHelperActivityListener) { mOwner = owner; mCallback = callback; } public void onInvitationInboxResult(bool success, string invitationId) { mOwner.OnInvitationInboxResult(success, invitationId, mCallback); } public void onTurnBasedMatch(AndroidJavaObject match) { mOwner.OnInvitationInboxTurnBasedMatch(match, mCallback); } } } } #endif
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders; using QuantConnect.Packets; using QuantConnect.Securities; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using QuantConnect.Configuration; using QuantConnect.Util; using Timer = System.Timers.Timer; namespace QuantConnect.Brokerages.Binance { /// <summary> /// Binance brokerage implementation /// </summary> [BrokerageFactory(typeof(BinanceBrokerageFactory))] public partial class BinanceBrokerage : BaseWebsocketsBrokerage, IDataQueueHandler { private const string WebSocketBaseUrl = "wss://stream.binance.com:9443/ws"; private readonly IAlgorithm _algorithm; private readonly SymbolPropertiesDatabaseSymbolMapper _symbolMapper = new SymbolPropertiesDatabaseSymbolMapper(Market.Binance); // Binance allows 5 messages per second, but we still get rate limited if we send a lot of messages at that rate // By sending 3 messages per second, evenly spaced out, we can keep sending messages without being limited private readonly RateGate _webSocketRateLimiter = new RateGate(1, TimeSpan.FromMilliseconds(330)); private long _lastRequestId; private LiveNodePacket _job; private readonly Timer _keepAliveTimer; private readonly Timer _reconnectTimer; private readonly BinanceRestApiClient _apiClient; private readonly BrokerageConcurrentMessageHandler<WebSocketMessage> _messageHandler; private const int MaximumSymbolsPerConnection = 512; /// <summary> /// Constructor for brokerage /// </summary> /// <param name="apiKey">api key</param> /// <param name="apiSecret">api secret</param> /// <param name="algorithm">the algorithm instance is required to retrieve account type</param> /// <param name="aggregator">the aggregator for consolidating ticks</param> /// <param name="job">The live job packet</param> public BinanceBrokerage(string apiKey, string apiSecret, IAlgorithm algorithm, IDataAggregator aggregator, LiveNodePacket job) : base(WebSocketBaseUrl, new WebSocketClientWrapper(), null, apiKey, apiSecret, "Binance") { _job = job; _algorithm = algorithm; _aggregator = aggregator; _messageHandler = new BrokerageConcurrentMessageHandler<WebSocketMessage>(OnUserMessage); var maximumWebSocketConnections = Config.GetInt("binance-maximum-websocket-connections"); var symbolWeights = maximumWebSocketConnections > 0 ? FetchSymbolWeights() : null; var subscriptionManager = new BrokerageMultiWebSocketSubscriptionManager( WebSocketBaseUrl, MaximumSymbolsPerConnection, maximumWebSocketConnections, symbolWeights, () => new BinanceWebSocketWrapper(null), Subscribe, Unsubscribe, OnDataMessage, new TimeSpan(23, 45, 0)); SubscriptionManager = subscriptionManager; _apiClient = new BinanceRestApiClient( _symbolMapper, algorithm?.Portfolio, apiKey, apiSecret); _apiClient.OrderSubmit += (s, e) => OnOrderSubmit(e); _apiClient.OrderStatusChanged += (s, e) => OnOrderEvent(e); _apiClient.Message += (s, e) => OnMessage(e); // User data streams will close after 60 minutes. It's recommended to send a ping about every 30 minutes. // Source: https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md#pingkeep-alive-a-listenkey _keepAliveTimer = new Timer { // 30 minutes Interval = 30 * 60 * 1000 }; _keepAliveTimer.Elapsed += (s, e) => _apiClient.SessionKeepAlive(); WebSocket.Open += (s, e) => { _keepAliveTimer.Start(); }; WebSocket.Closed += (s, e) => { _keepAliveTimer.Stop(); }; // A single connection to stream.binance.com is only valid for 24 hours; expect to be disconnected at the 24 hour mark // Source: https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md#general-wss-information _reconnectTimer = new Timer { // 23.5 hours Interval = 23.5 * 60 * 60 * 1000 }; _reconnectTimer.Elapsed += (s, e) => { Log.Trace("Daily websocket restart: disconnect"); Disconnect(); Log.Trace("Daily websocket restart: connect"); Connect(); }; } #region IBrokerage /// <summary> /// Checks if the websocket connection is connected or in the process of connecting /// </summary> public override bool IsConnected => WebSocket.IsOpen; /// <summary> /// Creates wss connection /// </summary> public override void Connect() { if (IsConnected) return; _apiClient.CreateListenKey(); _reconnectTimer.Start(); WebSocket.Initialize($"{WebSocketBaseUrl}/{_apiClient.SessionId}"); base.Connect(); } /// <summary> /// Closes the websockets connection /// </summary> public override void Disconnect() { _reconnectTimer.Stop(); WebSocket?.Close(); _apiClient.StopSession(); } /// <summary> /// Gets all open positions /// </summary> /// <returns></returns> public override List<Holding> GetAccountHoldings() { if (_algorithm.BrokerageModel.AccountType == AccountType.Cash) { return base.GetAccountHoldings(_job?.BrokerageData, _algorithm.Securities.Values); } return _apiClient.GetAccountHoldings(); } /// <summary> /// Gets the total account cash balance for specified account type /// </summary> /// <returns></returns> public override List<CashAmount> GetCashBalance() { var account = _apiClient.GetCashBalance(); var balances = account.Balances?.Where(balance => balance.Amount > 0).ToList(); if (balances == null || !balances.Any()) return new List<CashAmount>(); return balances .Select(b => new CashAmount(b.Amount, b.Asset.LazyToUpper())) .ToList(); } /// <summary> /// Gets all orders not yet closed /// </summary> /// <returns></returns> public override List<Order> GetOpenOrders() { var orders = _apiClient.GetOpenOrders(); List<Order> list = new List<Order>(); foreach (var item in orders) { Order order; switch (item.Type.LazyToUpper()) { case "MARKET": order = new MarketOrder { Price = item.Price }; break; case "LIMIT": case "LIMIT_MAKER": order = new LimitOrder { LimitPrice = item.Price }; break; case "STOP_LOSS": case "TAKE_PROFIT": order = new StopMarketOrder { StopPrice = item.StopPrice, Price = item.Price }; break; case "STOP_LOSS_LIMIT": case "TAKE_PROFIT_LIMIT": order = new StopLimitOrder { StopPrice = item.StopPrice, LimitPrice = item.Price }; break; default: OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Error, -1, "BinanceBrokerage.GetOpenOrders: Unsupported order type returned from brokerage: " + item.Type)); continue; } order.Quantity = item.Quantity; order.BrokerId = new List<string> { item.Id }; order.Symbol = _symbolMapper.GetLeanSymbol(item.Symbol, SecurityType.Crypto, Market.Binance); order.Time = Time.UnixMillisecondTimeStampToDateTime(item.Time); order.Status = ConvertOrderStatus(item.Status); order.Price = item.Price; if (order.Status.IsOpen()) { var cached = CachedOrderIDs.Where(c => c.Value.BrokerId.Contains(order.BrokerId.First())).ToList(); if (cached.Any()) { CachedOrderIDs[cached.First().Key] = order; } } list.Add(order); } return list; } /// <summary> /// Places a new order and assigns a new broker ID to the order /// </summary> /// <param name="order">The order to be placed</param> /// <returns>True if the request for a new order has been placed, false otherwise</returns> public override bool PlaceOrder(Order order) { var submitted = false; _messageHandler.WithLockedStream(() => { submitted = _apiClient.PlaceOrder(order); }); return submitted; } /// <summary> /// Updates the order with the same id /// </summary> /// <param name="order">The new order information</param> /// <returns>True if the request was made for the order to be updated, false otherwise</returns> public override bool UpdateOrder(Order order) { throw new NotSupportedException("BinanceBrokerage.UpdateOrder: Order update not supported. Please cancel and re-create."); } /// <summary> /// Cancels the order with the specified ID /// </summary> /// <param name="order">The order to cancel</param> /// <returns>True if the request was submitted for cancellation, false otherwise</returns> public override bool CancelOrder(Order order) { var submitted = false; _messageHandler.WithLockedStream(() => { submitted = _apiClient.CancelOrder(order); }); return submitted; } /// <summary> /// Gets the history for the requested security /// </summary> /// <param name="request">The historical data request</param> /// <returns>An enumerable of bars covering the span specified in the request</returns> public override IEnumerable<BaseData> GetHistory(Data.HistoryRequest request) { if (request.Resolution == Resolution.Tick || request.Resolution == Resolution.Second) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidResolution", $"{request.Resolution} resolution is not supported, no history returned")); yield break; } if (request.TickType != TickType.Trade) { OnMessage(new BrokerageMessageEvent(BrokerageMessageType.Warning, "InvalidTickType", $"{request.TickType} tick type not supported, no history returned")); yield break; } var period = request.Resolution.ToTimeSpan(); foreach (var kline in _apiClient.GetHistory(request)) { yield return new TradeBar() { Time = Time.UnixMillisecondTimeStampToDateTime(kline.OpenTime), Symbol = request.Symbol, Low = kline.Low, High = kline.High, Open = kline.Open, Close = kline.Close, Volume = kline.Volume, Value = kline.Close, DataType = MarketDataType.TradeBar, Period = period, EndTime = Time.UnixMillisecondTimeStampToDateTime(kline.OpenTime + (long)period.TotalMilliseconds) }; } } /// <summary> /// Wss message handler /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public override void OnMessage(object sender, WebSocketMessage e) { _messageHandler.HandleNewMessage(e); } #endregion #region IDataQueueHandler /// <summary> /// Sets the job we're subscribing for /// </summary> /// <param name="job">Job we're subscribing for</param> public void SetJob(LiveNodePacket job) { } /// <summary> /// Subscribe to the specified configuration /// </summary> /// <param name="dataConfig">defines the parameters to subscribe to a data feed</param> /// <param name="newDataAvailableHandler">handler to be fired on new data available</param> /// <returns>The new enumerator for this subscription request</returns> public IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler) { if (!CanSubscribe(dataConfig.Symbol)) { return Enumerable.Empty<BaseData>().GetEnumerator(); } var enumerator = _aggregator.Add(dataConfig, newDataAvailableHandler); SubscriptionManager.Subscribe(dataConfig); return enumerator; } /// <summary> /// Removes the specified configuration /// </summary> /// <param name="dataConfig">Subscription config to be removed</param> public void Unsubscribe(SubscriptionDataConfig dataConfig) { SubscriptionManager.Unsubscribe(dataConfig); _aggregator.Remove(dataConfig); } /// <summary> /// Checks if this brokerage supports the specified symbol /// </summary> /// <param name="symbol">The symbol</param> /// <returns>returns true if brokerage supports the specified symbol; otherwise false</returns> private static bool CanSubscribe(Symbol symbol) { return !symbol.Value.Contains("UNIVERSE") && symbol.SecurityType == SecurityType.Crypto; } #endregion /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public override void Dispose() { _keepAliveTimer.DisposeSafely(); _reconnectTimer.DisposeSafely(); _apiClient.DisposeSafely(); _webSocketRateLimiter.DisposeSafely(); } /// <summary> /// Not used /// </summary> public override void Subscribe(IEnumerable<Symbol> symbols) { // NOP } /// <summary> /// Subscribes to the requested symbol (using an individual streaming channel) /// </summary> /// <param name="webSocket">The websocket instance</param> /// <param name="symbol">The symbol to subscribe</param> private bool Subscribe(IWebSocket webSocket, Symbol symbol) { Send(webSocket, new { method = "SUBSCRIBE", @params = new[] { $"{symbol.Value.ToLowerInvariant()}@trade", $"{symbol.Value.ToLowerInvariant()}@bookTicker" }, id = GetNextRequestId() } ); return true; } /// <summary> /// Ends current subscription /// </summary> /// <param name="webSocket">The websocket instance</param> /// <param name="symbol">The symbol to unsubscribe</param> private bool Unsubscribe(IWebSocket webSocket, Symbol symbol) { Send(webSocket, new { method = "UNSUBSCRIBE", @params = new[] { $"{symbol.Value.ToLowerInvariant()}@trade", $"{symbol.Value.ToLowerInvariant()}@bookTicker" }, id = GetNextRequestId() } ); return true; } private void Send(IWebSocket webSocket, object obj) { var json = JsonConvert.SerializeObject(obj); _webSocketRateLimiter.WaitToProceed(); Log.Trace("Send: " + json); webSocket.Send(json); } private long GetNextRequestId() { return Interlocked.Increment(ref _lastRequestId); } /// <summary> /// Event invocator for the OrderFilled event /// </summary> /// <param name="e">The OrderEvent</param> private void OnOrderSubmit(BinanceOrderSubmitEventArgs e) { var brokerId = e.BrokerId; var order = e.Order; if (CachedOrderIDs.ContainsKey(order.Id)) { CachedOrderIDs[order.Id].BrokerId.Clear(); CachedOrderIDs[order.Id].BrokerId.Add(brokerId); } else { order.BrokerId.Add(brokerId); CachedOrderIDs.TryAdd(order.Id, order); } } /// <summary> /// Returns the weights for each symbol (the weight value is the count of trades in the last 24 hours) /// </summary> private static Dictionary<Symbol, int> FetchSymbolWeights() { var dict = new Dictionary<Symbol, int>(); try { const string url = "https://api.binance.com/api/v3/ticker/24hr"; var json = url.DownloadData(); foreach (var row in JArray.Parse(json)) { var ticker = row["symbol"].ToObject<string>(); var count = row["count"].ToObject<int>(); var symbol = Symbol.Create(ticker, SecurityType.Crypto, Market.Binance); dict.Add(symbol, count); } } catch (Exception exception) { Log.Error(exception); throw; } return dict; } } }
/*************************************************************************** * Album.cs * * Copyright (C) 2008 Novell * Authors: * Gabriel Burt ([email protected]) ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Mtp { public class Album : AbstractTrackList { internal static List<Album> GetAlbums (MtpDevice device) { List<Album> albums = new List<Album> (); IntPtr ptr = LIBMTP_Get_Album_List (device.Handle); while (ptr != IntPtr.Zero) { // Destroy the struct *after* we use it to ensure we don't access freed memory // for the 'tracks' variable AlbumStruct d = (AlbumStruct)Marshal.PtrToStructure(ptr, typeof(AlbumStruct)); albums.Add (new Album (device, d)); LIBMTP_destroy_album_t (ptr); ptr = d.next; } return albums; } private AlbumStruct album; public uint AlbumId { get { return Saved ? album.album_id : 0; } } public override string Name { get { return album.name; } set { album.name = value; } } public string Artist { get { return album.artist; } set { album.artist = value; } } public string Genre { get { return album.genre; } set { album.genre = value; } } public string Composer { get { return album.composer; } set { album.composer = value; } } public override uint Count { get { return album.no_tracks; } protected set { album.no_tracks = value; } } protected override IntPtr TracksPtr { get { return album.tracks; } set { album.tracks = value; } } public Album (MtpDevice device, string name, string artist, string genre, string composer) : base (device) { Name = name; Artist = artist; Genre = genre; Composer = composer; Count = 0; } internal Album (MtpDevice device, AlbumStruct album) : base (device, album.tracks, album.no_tracks) { // Once we've loaded the tracks, set the TracksPtr to NULL as it // will be freed when the Album constructor is finished. this.album = album; TracksPtr = IntPtr.Zero; } public override void Save () { Save (null, 0, 0); } public void Save (byte [] cover_art, uint width, uint height) { base.Save (); if (Saved) { if (cover_art == null) { return; } FileSampleData cover = new FileSampleData (); cover.data = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (byte)) * cover_art.Length); Marshal.Copy (cover_art, 0, cover.data, cover_art.Length); cover.size = (ulong)cover_art.Length; cover.width = width; cover.height = height; cover.filetype = FileType.JPEG; if (FileSample.LIBMTP_Send_Representative_Sample (Device.Handle, AlbumId, ref cover) != 0) { //Console.WriteLine ("Failed to send representative sample file for album {0} (id {1})", Name, AlbumId); } Marshal.FreeHGlobal (cover.data); } } protected override int Create () { return LIBMTP_Create_New_Album (Device.Handle, ref album); } protected override int Update () { return LIBMTP_Update_Album (Device.Handle, ref album); } public void Remove () { MtpDevice.LIBMTP_Delete_Object(Device.Handle, AlbumId); } public override string ToString () { return String.Format ("Album < Id: {4}, '{0}' by '{1}', genre '{2}', tracks {3} >", Name, Artist, Genre, Count, AlbumId); } public static Album GetById (MtpDevice device, uint id) { IntPtr ptr = Album.LIBMTP_Get_Album (device.Handle, id); if (ptr == IntPtr.Zero) { return null; } else { // Destroy the struct after we use it to prevent accessing freed memory // in the 'tracks' variable AlbumStruct album = (AlbumStruct) Marshal.PtrToStructure(ptr, typeof (AlbumStruct)); var ret = new Album (device, album); LIBMTP_destroy_album_t (ptr); return ret; } } //[DllImport (MtpDevice.LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)] //internal static extern IntPtr LIBMTP_new_album_t (); // LIBMTP_album_t* [DllImport (MtpDevice.LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)] static extern void LIBMTP_destroy_album_t (IntPtr album); [DllImport (MtpDevice.LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)] static extern IntPtr LIBMTP_Get_Album_List (MtpDeviceHandle handle); // LIBMTP_album_t* [DllImport (MtpDevice.LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)] static extern IntPtr LIBMTP_Get_Album (MtpDeviceHandle handle, uint albumId); // LIBMTP_album_t* [DllImport (MtpDevice.LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)] internal static extern int LIBMTP_Create_New_Album (MtpDeviceHandle handle, ref AlbumStruct album); [DllImport (MtpDevice.LibMtpLibrary, CallingConvention = CallingConvention.Cdecl)] static extern int LIBMTP_Update_Album (MtpDeviceHandle handle, ref AlbumStruct album); } [StructLayout(LayoutKind.Sequential)] internal struct AlbumStruct { public uint album_id; public uint parent_id; public uint storage_id; [MarshalAs(UnmanagedType.LPStr)] public string name; [MarshalAs(UnmanagedType.LPStr)] public string artist; [MarshalAs(UnmanagedType.LPStr)] public string composer; [MarshalAs(UnmanagedType.LPStr)] public string genre; public IntPtr tracks; public uint no_tracks; public IntPtr next; } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Mvc; using Orchard.Comments.Models; using Orchard.ContentManagement; using Orchard.DisplayManagement; using Orchard.Localization; using Orchard.Logging; using Orchard.Mvc.Extensions; using Orchard.UI.Navigation; using Orchard.UI.Notify; using Orchard.Comments.ViewModels; using Orchard.Comments.Services; using Orchard.Utility.Extensions; namespace Orchard.Comments.Controllers { using Orchard.Settings; [ValidateInput(false)] public class AdminController : Controller { private readonly ICommentService _commentService; private readonly ISiteService _siteService; public AdminController( IOrchardServices services, ICommentService commentService, ISiteService siteService, IShapeFactory shapeFactory) { _commentService = commentService; _siteService = siteService; Services = services; Logger = NullLogger.Instance; T = NullLocalizer.Instance; Shape = shapeFactory; } public IOrchardServices Services { get; set; } public ILogger Logger { get; set; } public Localizer T { get; set; } dynamic Shape { get; set; } public ActionResult Index(CommentIndexOptions options, PagerParameters pagerParameters) { Pager pager = new Pager(_siteService.GetSiteSettings(), pagerParameters); // Default options if (options == null) options = new CommentIndexOptions(); // Filtering IContentQuery<CommentPart, CommentPartRecord> comments; switch (options.Filter) { case CommentIndexFilter.All: comments = _commentService.GetComments(); break; case CommentIndexFilter.Approved: comments = _commentService.GetComments(CommentStatus.Approved); break; case CommentIndexFilter.Pending: comments = _commentService.GetComments(CommentStatus.Pending); break; case CommentIndexFilter.Spam: comments = _commentService.GetComments(CommentStatus.Spam); break; default: throw new ArgumentOutOfRangeException(); } var pagerShape = Shape.Pager(pager).TotalItemCount(comments.Count()); var entries = comments .OrderByDescending<CommentPartRecord, DateTime?>(cpr => cpr.CommentDateUtc) .Slice(pager.GetStartIndex(), pager.PageSize) .ToList() .Select(comment => CreateCommentEntry(comment.Record)); var model = new CommentsIndexViewModel { Comments = entries.ToList(), Options = options, Pager = pagerShape }; return View(model); } [HttpPost] [FormValueRequired("submit.BulkEdit")] public ActionResult Index(FormCollection input) { var viewModel = new CommentsIndexViewModel { Comments = new List<CommentEntry>(), Options = new CommentIndexOptions() }; UpdateModel(viewModel); IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked); switch (viewModel.Options.BulkAction) { case CommentIndexBulkAction.None: break; case CommentIndexBulkAction.MarkAsSpam: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult(); //TODO: Transaction foreach (CommentEntry entry in checkedEntries) { _commentService.MarkCommentAsSpam(entry.Comment.Id); } break; case CommentIndexBulkAction.Unapprove: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult(); //TODO: Transaction foreach (CommentEntry entry in checkedEntries) { _commentService.UnapproveComment(entry.Comment.Id); } break; case CommentIndexBulkAction.Approve: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult(); //TODO: Transaction foreach (CommentEntry entry in checkedEntries) { _commentService.ApproveComment(entry.Comment.Id); } break; case CommentIndexBulkAction.Delete: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) return new HttpUnauthorizedResult(); foreach (CommentEntry entry in checkedEntries) { _commentService.DeleteComment(entry.Comment.Id); } break; default: throw new ArgumentOutOfRangeException(); } return RedirectToAction("Index"); } public ActionResult Details(int id, CommentDetailsOptions options) { // Default options if (options == null) options = new CommentDetailsOptions(); // Filtering IContentQuery<CommentPart, CommentPartRecord> comments; switch (options.Filter) { case CommentDetailsFilter.All: comments = _commentService.GetCommentsForCommentedContent(id); break; case CommentDetailsFilter.Approved: comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Approved); break; case CommentDetailsFilter.Pending: comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Pending); break; case CommentDetailsFilter.Spam: comments = _commentService.GetCommentsForCommentedContent(id, CommentStatus.Spam); break; default: throw new ArgumentOutOfRangeException(); } var entries = comments.List().Select(comment => CreateCommentEntry(comment.Record)).ToList(); var model = new CommentsDetailsViewModel { Comments = entries, Options = options, DisplayNameForCommentedItem = _commentService.GetDisplayForCommentedContent(id) == null ? "" : _commentService.GetDisplayForCommentedContent(id).DisplayText, CommentedItemId = id, CommentsClosedOnItem = _commentService.CommentsDisabledForCommentedContent(id), }; return View(model); } [HttpPost] [FormValueRequired("submit.BulkEdit")] public ActionResult Details(FormCollection input) { var viewModel = new CommentsDetailsViewModel { Comments = new List<CommentEntry>(), Options = new CommentDetailsOptions() }; UpdateModel(viewModel); IEnumerable<CommentEntry> checkedEntries = viewModel.Comments.Where(c => c.IsChecked); switch (viewModel.Options.BulkAction) { case CommentDetailsBulkAction.None: break; case CommentDetailsBulkAction.MarkAsSpam: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult(); //TODO: Transaction foreach (CommentEntry entry in checkedEntries) { _commentService.MarkCommentAsSpam(entry.Comment.Id); } break; case CommentDetailsBulkAction.Unapprove: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult(); foreach (CommentEntry entry in checkedEntries) { _commentService.UnapproveComment(entry.Comment.Id); } break; case CommentDetailsBulkAction.Approve: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't moderate comment"))) return new HttpUnauthorizedResult(); foreach (CommentEntry entry in checkedEntries) { _commentService.ApproveComment(entry.Comment.Id); } break; case CommentDetailsBulkAction.Delete: if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) return new HttpUnauthorizedResult(); foreach (CommentEntry entry in checkedEntries) { _commentService.DeleteComment(entry.Comment.Id); } break; default: throw new ArgumentOutOfRangeException(); } return RedirectToAction("Index"); } [HttpPost] public ActionResult Disable(int commentedItemId, string returnUrl) { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't disable comments"))) return new HttpUnauthorizedResult(); _commentService.DisableCommentsForCommentedContent(commentedItemId); return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); } [HttpPost] public ActionResult Enable(int commentedItemId, string returnUrl) { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't enable comments"))) return new HttpUnauthorizedResult(); _commentService.EnableCommentsForCommentedContent(commentedItemId); return this.RedirectLocal(returnUrl, () => RedirectToAction("Index")); } public ActionResult Edit(int id) { CommentPart commentPart = _commentService.GetComment(id); if (commentPart == null) return new HttpNotFoundResult(); var viewModel = new CommentsEditViewModel { CommentText = commentPart.Record.CommentText, Email = commentPart.Record.Email, Id = commentPart.Record.Id, Name = commentPart.Record.Author, SiteName = commentPart.Record.SiteName, Status = commentPart.Record.Status, }; return View(viewModel); } [HttpPost] public ActionResult Edit(FormCollection input) { var viewModel = new CommentsEditViewModel(); UpdateModel(viewModel); if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't edit comment"))) return new HttpUnauthorizedResult(); _commentService.UpdateComment(viewModel.Id, viewModel.Name, viewModel.Email, viewModel.SiteName, viewModel.CommentText, viewModel.Status); return RedirectToAction("Index"); } [HttpPost] public ActionResult Approve(int id, string returnUrl) { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't approve comment"))) return new HttpUnauthorizedResult(); var commentPart = _commentService.GetComment(id); if (commentPart == null) return new HttpNotFoundResult(); int commentedOn = commentPart.Record.CommentedOn; _commentService.ApproveComment(id); return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn })); } [HttpPost] public ActionResult Unapprove(int id, string returnUrl) { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't unapprove comment"))) return new HttpUnauthorizedResult(); var commentPart = _commentService.GetComment(id); if (commentPart == null) return new HttpNotFoundResult(); int commentedOn = commentPart.Record.CommentedOn; _commentService.UnapproveComment(id); return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn })); } [HttpPost] public ActionResult MarkAsSpam(int id, string returnUrl) { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't mark comment as spam"))) return new HttpUnauthorizedResult(); var commentPart = _commentService.GetComment(id); if (commentPart == null) return new HttpNotFoundResult(); int commentedOn = commentPart.Record.CommentedOn; _commentService.MarkCommentAsSpam(id); return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn })); } [HttpPost] public ActionResult Delete(int id, string returnUrl) { if (!Services.Authorizer.Authorize(Permissions.ManageComments, T("Couldn't delete comment"))) return new HttpUnauthorizedResult(); var commentPart = _commentService.GetComment(id); if (commentPart == null) return new HttpNotFoundResult(); int commentedOn = commentPart.Record.CommentedOn; _commentService.DeleteComment(id); return this.RedirectLocal(returnUrl, () => RedirectToAction("Details", new { id = commentedOn })); } private CommentEntry CreateCommentEntry(CommentPartRecord commentPart) { return new CommentEntry { Comment = commentPart, CommentedOn = _commentService.GetCommentedContent(commentPart.CommentedOn), IsChecked = false, }; } public class FormValueRequiredAttribute : ActionMethodSelectorAttribute { private readonly string _submitButtonName; public FormValueRequiredAttribute(string submitButtonName) { _submitButtonName = submitButtonName; } public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) { var value = controllerContext.HttpContext.Request.Form[_submitButtonName]; return !string.IsNullOrEmpty(value); } } } }
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 FSL.XFApi.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 file="ControlItemHelper.cs" company="None"> // None // </copyright> // <summary> // Initializes instance of ControlItemHelper // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; using TfsWorkbench.Core.Helpers; using TfsWorkbench.Core.Interfaces; using Microsoft.TeamFoundation.WorkItemTracking.Client; using TfsWorkbench.Core.DataObjects; using TfsWorkbench.TFSDataProvider2010.Helpers; using TfsWorkbench.TFSDataProvider2010.Properties; namespace TfsWorkbench.TFSDataProvider2010 { /// <summary> /// Initializes instance of ControlItemHelper /// </summary> internal class ControlItemHelper { /// <summary> /// The control item collections map. /// </summary> private static readonly Dictionary<string, ControlItemGroup> controlItemMap = new Dictionary<string, ControlItemGroup>(); /// <summary> /// The internal xsl transform instance. /// </summary> private static XslCompiledTransform internalXslTransform; /// <summary> /// The serializer intance. /// </summary> private static SerializerInstance<ControlItemGroup> serializerIntance; /// <summary> /// Gets the XSL transform. /// </summary> /// <value>The XSL transform.</value> private static XslCompiledTransform XslTransform { get { if (internalXslTransform == null) { internalXslTransform = new XslCompiledTransform(); var assembly = Assembly.GetExecutingAssembly(); var assemblyName = assembly.GetName().Name; var streamName = string.Concat(assemblyName, ".Resources.WitdToControlItem.xslt"); var stream = assembly.GetManifestResourceStream(streamName); if (stream == null) { throw new FileNotFoundException(string.Concat(Resources.String008, streamName)); } internalXslTransform.Load(new XmlTextReader(stream)); } return internalXslTransform; } } /// <summary> /// Gets the serializer instance. /// </summary> /// <value>The serializer instance.</value> private static SerializerInstance<ControlItemGroup> SerializerInstance { get { return serializerIntance = serializerIntance ?? new SerializerInstance<ControlItemGroup>(); } } /// <summary> /// Gets the control item colelction. /// </summary> /// <param name="workbenchItem">The task board item.</param> /// <returns>A collection of control item objects.</returns> public static ControlItemGroup GetControlItemGroup(IWorkbenchItem workbenchItem) { if (workbenchItem == null) { throw new ArgumentNullException("workbenchItem"); } ControlItemGroup collection; var valueProvider = workbenchItem.ValueProvider as WorkItemValueProvider; if (valueProvider == null) { throw new ArgumentException(Resources.String013); } var compoundKey = GenerateCompondKey(valueProvider.WorkItem.Project, valueProvider.WorkItem.Type.Name); if (!controlItemMap.TryGetValue(compoundKey, out collection)) { collection = CreateCollection(valueProvider.WorkItem.Type.Export(false)); controlItemMap.Add(compoundKey, collection); } // Clone the collection in order to allow multiple instances. collection = collection.Clone(); collection.WorkbenchItem = workbenchItem; return collection; } /// <summary> /// Gets the control item collection. /// </summary> /// <param name="project">The project.</param> /// <param name="typeName">Name of the type.</param> /// <returns>A control item collection without an associated work item reference.</returns> public static IControlItemGroup GetControlItemGroup(Project project, string typeName) { if (project == null) { throw new ArgumentNullException("project"); } ControlItemGroup collection; var compoundKey = GenerateCompondKey(project, typeName); if (!controlItemMap.TryGetValue(compoundKey, out collection)) { var workItemType = project.WorkItemTypes.OfType<WorkItemType>().FirstOrDefault(w => w.Name.Equals(typeName)); if (workItemType == null) { return null; } collection = CreateCollection(workItemType.Export(false)); controlItemMap.Add(compoundKey, collection); } // Clone the collection in order to allow multiple instances. return collection.Clone(); } /// <summary> /// Clears the cache. /// </summary> public static void ClearCache() { foreach (var value in controlItemMap.Values) { value.WorkbenchItem = null; } controlItemMap.Clear(); } /// <summary> /// Creates the collection. /// </summary> /// <param name="witd">The work item template document.</param> /// <returns>A control item collection instance.</returns> private static ControlItemGroup CreateCollection(IXPathNavigable witd) { var sb = new StringBuilder(); using (var writer = XmlWriter.Create(sb, XslTransform.OutputSettings)) { var navigator = witd.CreateNavigator(); if (navigator == null) { throw new ArgumentException(Resources.String014); } using (var reader = navigator.ReadSubtree()) { reader.MoveToContent(); XslTransform.Transform(reader, writer); reader.Close(); } writer.Close(); } return SerializerInstance.Deserialize(sb.ToString()); } /// <summary> /// Generates the compond key. /// </summary> /// <param name="project">The project.</param> /// <param name="typeName">Name of the type.</param> /// <returns>The compond key for the specfied arguments.</returns> private static string GenerateCompondKey(Project project, string typeName) { return project == null ? null : string.Concat(project.Uri, " - ", typeName); } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using SensusService; using SensusService.DataStores; using SensusService.DataStores.Local; using SensusService.DataStores.Remote; using SensusUI.UiProperties; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Xamarin.Forms; using SensusUI.Inputs; namespace SensusUI { /// <summary> /// Displays a single protocol. /// </summary> public class ProtocolPage : ContentPage { private Protocol _protocol; private EventHandler<bool> _protocolRunningChangedAction; /// <summary> /// Initializes a new instance of the <see cref="SensusUI.ProtocolPage"/> class. /// </summary> /// <param name="protocol">Protocol to display.</param> public ProtocolPage(Protocol protocol) { _protocol = protocol; Title = "Protocol"; List<View> views = new List<View>(); views.AddRange(UiProperty.GetPropertyStacks(_protocol)); #region data stores string localDataStoreSize = null; try { if (protocol.LocalDataStore != null) { if (protocol.LocalDataStore is RamLocalDataStore) localDataStoreSize = (protocol.LocalDataStore as RamLocalDataStore).DataCount + " items"; else if (protocol.LocalDataStore is FileLocalDataStore) localDataStoreSize = Math.Round(SensusServiceHelper.GetDirectorySizeMB((protocol.LocalDataStore as FileLocalDataStore).StorageDirectory), 1) + " MB"; } } catch (Exception) { } Button editLocalDataStoreButton = new Button { Text = "Local Data Store" + (localDataStoreSize == null ? "" : " (" + localDataStoreSize + ")"), FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand, IsEnabled = !_protocol.Running }; editLocalDataStoreButton.Clicked += async (o, e) => { if (_protocol.LocalDataStore != null) await Navigation.PushAsync(new DataStorePage(_protocol, _protocol.LocalDataStore.Copy(), true, false)); }; Button createLocalDataStoreButton = new Button { Text = "+", FontSize = 20, HorizontalOptions = LayoutOptions.End, IsEnabled = !_protocol.Running }; createLocalDataStoreButton.Clicked += (o, e) => CreateDataStore(true); StackLayout localDataStoreStack = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { editLocalDataStoreButton, createLocalDataStoreButton } }; views.Add(localDataStoreStack); Button editRemoteDataStoreButton = new Button { Text = "Remote Data Store", FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand, IsEnabled = !_protocol.Running }; editRemoteDataStoreButton.Clicked += async (o, e) => { if (_protocol.RemoteDataStore != null) await Navigation.PushAsync(new DataStorePage(_protocol, _protocol.RemoteDataStore.Copy(), false, false)); }; Button createRemoteDataStoreButton = new Button { Text = "+", FontSize = 20, HorizontalOptions = LayoutOptions.End, IsEnabled = !_protocol.Running }; createRemoteDataStoreButton.Clicked += (o, e) => CreateDataStore(false); StackLayout remoteDataStoreStack = new StackLayout { Orientation = StackOrientation.Horizontal, HorizontalOptions = LayoutOptions.FillAndExpand, Children = { editRemoteDataStoreButton, createRemoteDataStoreButton } }; views.Add(remoteDataStoreStack); #endregion #region points of interest Button pointsOfInterestButton = new Button { Text = "Points of Interest", FontSize = 20 }; pointsOfInterestButton.Clicked += async (o, e) => { await Navigation.PushAsync(new PointsOfInterestPage(_protocol.PointsOfInterest)); }; views.Add(pointsOfInterestButton); #endregion #region view probes Button viewProbesButton = new Button { Text = "Probes", FontSize = 20 }; viewProbesButton.Clicked += async (o, e) => { await Navigation.PushAsync(new ProbesPage(_protocol)); }; views.Add(viewProbesButton); #endregion _protocolRunningChangedAction = (o, running) => { Device.BeginInvokeOnMainThread(() => { editLocalDataStoreButton.IsEnabled = createLocalDataStoreButton.IsEnabled = editRemoteDataStoreButton.IsEnabled = createRemoteDataStoreButton.IsEnabled = !running; }); }; StackLayout stack = new StackLayout { Orientation = StackOrientation.Vertical, VerticalOptions = LayoutOptions.FillAndExpand }; foreach (View view in views) stack.Children.Add(view); Button lockButton = new Button { Text = _protocol.LockPasswordHash == "" ? "Lock" : "Unlock", FontSize = 20, HorizontalOptions = LayoutOptions.FillAndExpand }; lockButton.Clicked += (o, e) => { if (lockButton.Text == "Lock") { SensusServiceHelper.Get().PromptForInputAsync( "Lock Protocol", new SingleLineTextInput("Password:", Keyboard.Text, true), null, true, null, null, null, null, false, input => { if (input == null) return; string password = input.Value as string; if (string.IsNullOrWhiteSpace(password)) SensusServiceHelper.Get().FlashNotificationAsync("Please enter a non-empty password."); else { _protocol.LockPasswordHash = SensusServiceHelper.Get().GetHash(password); Device.BeginInvokeOnMainThread(() => lockButton.Text = "Unlock"); } }); } else if (lockButton.Text == "Unlock") { _protocol.LockPasswordHash = ""; lockButton.Text = "Lock"; } }; stack.Children.Add(lockButton); Content = new ScrollView { Content = stack }; } protected override void OnAppearing() { base.OnAppearing(); _protocol.ProtocolRunningChanged += _protocolRunningChangedAction; } private async void CreateDataStore(bool local) { Type dataStoreType = local ? typeof(LocalDataStore) : typeof(RemoteDataStore); List<DataStore> dataStores = Assembly.GetExecutingAssembly() .GetTypes() .Where(t => !t.IsAbstract && t.IsSubclassOf(dataStoreType)) .Select(t => Activator.CreateInstance(t)) .Cast<DataStore>() .OrderBy(d => d.DisplayName) .ToList(); string cancelButtonName = "Cancel"; string selected = await DisplayActionSheet("Select " + (local ? "Local" : "Remote") + " Data Store", cancelButtonName, null, dataStores.Select((d, i) => (i + 1) + ") " + d.DisplayName).ToArray()); if (!string.IsNullOrWhiteSpace(selected) && selected != cancelButtonName) await Navigation.PushAsync(new DataStorePage(_protocol, dataStores[int.Parse(selected.Substring(0, selected.IndexOf(")"))) - 1], local, true)); } protected override void OnDisappearing() { base.OnDisappearing(); _protocol.ProtocolRunningChanged -= _protocolRunningChangedAction; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using NGraphics; using UIKit; namespace MusicPlayer { public static class Images { public static float MaxScreenSize; public static float AlbumArtScreenSize => Math.Max(MaxScreenSize, 640); public static Lazy<UIImage> DisclosureImage = new Lazy<UIImage>(() => "SVG/more.svg".LoadImageFromSvg(new Size(15, 15), UIImageRenderingMode.AlwaysTemplate)); public static Lazy<UIImage> DisclosureTallImage = new Lazy<UIImage>(() => "SVG/moreTall.svg".LoadImageFromSvg(new Size(15, 15), UIImageRenderingMode.AlwaysTemplate)); public static Lazy<UIImage> AccentImage = new Lazy<UIImage>(() => UIImage.FromBundle("accentColor")); static readonly Dictionary<Tuple<string, string>, UIImage> CachedGeneratedImages = new Dictionary<Tuple<string, string>, UIImage>(); public static UIImage GetDisclosureImage(double width, double height) { return GetGeneratedImage("SVG/more.svg", width,height).ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate); } public static UIImage GetRadioIcon(double width,double height) { return GetGeneratedImage("SVG/radio.svg", width,height); } public static UIImage GetDefaultSongImage(double size) { return GetGeneratedImage("SVG/songsDefault.svg", size); } public static UIImage GetDefaultAlbumArt(double size) { return GetGeneratedImage("SVG/icon.svg", size); } public static UIImage GetPlaybackButton(double size) { return GetGeneratedImage("SVG/playButton.svg", size).ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate); } public static UIImage GetBorderedPlaybackButton(double size) { return GetGeneratedImage("SVG/playButtonBordered.svg", size).ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate); } public static UIImage GetPauseButton(double size) { return GetGeneratedImage("SVG/pauseButton.svg", size).ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate); } public static UIImage GetBorderedPauseButton(double size) { return GetGeneratedImage("SVG/pauseButtonBordered.svg", size).ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate); } public static UIImage GetNextButton(double size) { return GetGeneratedImage("SVG/next.svg", size).ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate); } public static UIImage GetPreviousButton(double size) { return GetGeneratedImage("SVG/previous.svg", size).ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) ; } public static UIImage GetAirplayButton(double size) { return GetGeneratedImage("SVG/airplay.svg", size).ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate); } public static UIImage GetShuffleImage(double size) { return GetGeneratedImage("SVG/shuffle.svg", size); } public static UIImage GetRepeatImage(double size) { return GetGeneratedImage("SVG/repeat.svg", size); } public static UIImage GetRepeatOneImage(double size) { return GetGeneratedImage("SVG/repeatOne.svg", size); } public static UIImage GetThumbsUpImage(double size) { return GetGeneratedImage("SVG/thumbsUp.svg", size); } public static UIImage GetThumbsDownImage(double size) { return GetGeneratedImage("SVG/thumbsDown.svg", size); } public static UIImage GetShareIcon(double size) { return GetGeneratedImage("SVG/share.svg", size); } public static UIImage GetCloseImage(double size) { return GetGeneratedImage("SVG/close.svg", size); } public static UIImage GetPlaylistIcon(double size) { return GetGeneratedImage("SVG/playlists.svg", size); } public static UIImage GetSliderTrack() { return GetGeneratedImage("SVG/sliderTrack.svg", -1); } public static UIImage GetPlaybackSliderThumb() { return GetGeneratedImage("SVG/playbackSliderThumb.svg", 37); } public static UIImage GetMusicNotes(double size) { return GetGeneratedImage("SVG/musicalNotes.svg", size); } public static UIImage GetOfflineImage(double size) { return GetGeneratedImage("SVG/isOffline.svg",size); } public static UIImage GetVideoIcon(double size) { return GetGeneratedImage("SVG/videoIcon.svg", size); } public static UIImage GetEditIcon(double size) { return GetGeneratedImage("SVG/edit.svg", size); } public static UIImage GetDeleteIcon(double size) { return GetGeneratedImage("SVG/trash.svg", size); } public static UIImage GetCopyIcon(double size) { return GetGeneratedImage("SVG/copy.svg", size); } public static UIImage GetUndoImage(double size) { return GetGeneratedImage("SVG/undo.svg",size); } public static UIImage DiceImage => GetDiceImage(20); public static UIImage GetDiceImage(double size) => GetGeneratedImage("SVG/dice.svg", size, size); public static UIImage MenuImage => GetMenuImage (15); public static UIImage GetMenuImage (double size) => GetGeneratedImage ("SVG/menu.svg", size, size); static UIImage GetGeneratedImage(string name, double size) { return GetGeneratedImage(name, size, size); } static UIImage GetGeneratedImage(string imageName, double width, double height) { return GetGeneratedImage(imageName, new Size(width, height)); } static UIImage GetGeneratedImage(string imageName, Size size) { var tuple = new Tuple<string, string>(imageName, $"{size.Width},{size.Height}"); UIImage image; if (!CachedGeneratedImages.TryGetValue(tuple, out image)) { CachedGeneratedImages[tuple] = image = imageName.LoadImageFromSvg(size); } return image; } static UIImage GetAppBundleImage(string imageName) { var tuple = new Tuple<string, string>(imageName, imageName); UIImage image; if (!CachedGeneratedImages.TryGetValue(tuple, out image)) { CachedGeneratedImages[tuple] = image = UIImage.FromBundle(imageName); } return image; } } }
using System; using System.Diagnostics; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using System.IO; using System.ComponentModel; #pragma warning disable VSSDK002 // Visual Studio service should be used on main thread explicitly. namespace Nitra.VisualStudio { internal static class HierarchyListenerExtentions { public static void DisplayProps(this IVsHierarchy hierarchy, uint currentItem, __VSHPROPID prop) { Debug.WriteLine(">>>" + prop); object obj = GetProp(hierarchy, currentItem, prop); var extObjectProps = TypeDescriptor.GetProperties(obj); foreach (PropertyDescriptor x in extObjectProps) { var value = x.GetValue(obj); Debug.WriteLine(" Name='" + x.Name + "' Description='" + x.Description + "' DisplayName='" + x.DisplayName + "' Value='" + value + "'"); } Debug.WriteLine("<<<" + prop); } public static object GetProp(this IVsHierarchy hierarchy, uint currentItem, __VSHPROPID prop) { object obj; hierarchy.GetProperty(currentItem, (int)prop, out obj); return obj; } } class HierarchyListener : IVsHierarchyEvents, IDisposable { public IVsHierarchy Hierarchy { get; private set; } uint _cookie; /// <summary> /// Initializes a new instance of the <see cref="HierarchyListener"/> class. /// </summary> /// <param name="hierarchy">The hierarchy.</param> public HierarchyListener(IVsHierarchy hierarchy) { ErrorHelper.ThrowIsNull(hierarchy, nameof(hierarchy)); Hierarchy = hierarchy; } #region Public Methods /// <summary> /// Gets a value indicating whether this instance is listening. /// </summary> /// <value> /// <c>true</c> if this instance is listening; otherwise, <c>false</c>. /// </value> public bool IsListening { get { return (_cookie != 0); } } /// <summary> /// Starts the listening. /// </summary> /// <param name="doInitialScan">if set to <c>true</c> [do initial scan].</param> public void StartListening(bool doInitialScan) { if (_cookie == 0) { ErrorHandler.ThrowOnFailure(Hierarchy.AdviseHierarchyEvents(this, out _cookie)); if (doInitialScan) InternalScanHierarchy(VSConstants.VSITEMID_ROOT); } } /// <summary> /// Stops the listening. /// </summary> public void StopListening() { InternalStopListening(true); } #endregion #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { InternalStopListening(false); _cookie = 0; Hierarchy = null; } #endregion #region Public Events public event EventHandler<HierarchyItemEventArgs> ItemAdded; public event EventHandler<HierarchyItemEventArgs> ItemDeleted; public event EventHandler<ReferenceEventArgs> ReferenceAdded; #endregion #region IVsHierarchyEvents Members public int OnInvalidateIcon(IntPtr hicon) { // Do Nothing. // return VSConstants.S_OK; } public int OnInvalidateItems(uint itemidParent) { // TODO: Find out if this event is needed. // Debug.WriteLine("\n\tOnInvalidateItems\n"); return VSConstants.S_OK; } public int OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded) { // Check if the item is a nemerle file. // #if DEBUG string itemName; string parentName; string siblingName; Hierarchy.GetCanonicalName(itemidAdded, out itemName); Hierarchy.GetCanonicalName(itemidParent, out parentName); Hierarchy.GetCanonicalName(itemidSiblingPrev, out siblingName); Debug.WriteLine(string.Format("tr: \tOnItemsAdded '{0}' to '{1}' next to '{2}'", Path.GetFileName(itemName), Path.GetFileName(parentName), Path.GetFileName(siblingName))); #endif if (TryFierOnAddReference(itemidAdded)) return VSConstants.S_OK; string name; if (!IsFile(itemidAdded, out name)) return VSConstants.S_OK; // This item is a physical file, so we can notify that it is added to the hierarchy. // if (ItemAdded != null) { HierarchyItemEventArgs args = new HierarchyItemEventArgs(Hierarchy, itemidAdded, name); ItemAdded(this, args); } return VSConstants.S_OK; } private bool TryFierOnAddReference(uint currentItem) { if (ReferenceAdded == null) return false; int hr2; object obj; hr2 = Hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_ExtObject, out obj); if (!ErrorHelper.Succeeded(hr2)) return false; var reference = obj as VSLangProj.Reference; var projectItem = obj as EnvDTE.ProjectItem; if (reference == null && projectItem != null) reference = projectItem.Object as VSLangProj.Reference; if (reference != null) { ReferenceAdded(this, new ReferenceEventArgs(Hierarchy, currentItem, reference)); return true; } return false; } public int OnItemDeleted(uint itemid) { Debug.WriteLine("tr: \tOnItemDeleted"); // Notify that the item is deleted only if it is a nemerle file. // string name; if (!IsFile(itemid, out name)) return VSConstants.S_OK; if (ItemDeleted != null) { HierarchyItemEventArgs args = new HierarchyItemEventArgs(Hierarchy, itemid, name); ItemDeleted(this, args); } return VSConstants.S_OK; } public int OnItemsAppended(uint itemidParent) { // TODO: Find out what this event is about. // string name; Hierarchy.GetCanonicalName(itemidParent, out name); Debug.WriteLine(string.Format("tr: \tOnItemsAppended: '{0}'", Path.GetFileName(name))); return VSConstants.S_OK; } public int OnPropertyChanged(uint itemid, int propid, uint flags) { // Do Nothing. // return VSConstants.S_OK; } #endregion bool InternalStopListening(bool throwOnError) { if (null == Hierarchy || 0 == _cookie) return false; int hr = Hierarchy.UnadviseHierarchyEvents(_cookie); if (throwOnError) ErrorHandler.ThrowOnFailure(hr); _cookie = 0; return ErrorHandler.Succeeded(hr); } bool IsFile(uint itemId, out string canonicalName) { canonicalName = null; // Find out if this item is a physical file. // Guid typeGuid; int hr = Hierarchy.GetGuidProperty(itemId, (int)__VSHPROPID.VSHPROPID_TypeGuid, out typeGuid); if (ErrorHandler.Failed(hr) || VSConstants.GUID_ItemType_PhysicalFile != typeGuid) // It is not a file, we can exit now. return false; // This item is a file; find if it is a nemerle file. // hr = Hierarchy.GetCanonicalName(itemId, out canonicalName); if (ErrorHandler.Failed(hr)) return false; return true; } /// <summary> /// Do a recursive walk on the hierarchy to find all the nemerle files in /// it. It will generate an event for every file found. /// </summary> void InternalScanHierarchy(uint itemId) { uint currentItem = itemId; while (VSConstants.VSITEMID_NIL != currentItem) { // If this item is a nemerle file, then send the add item event. string itemName; if (ItemAdded != null && IsFile(currentItem, out itemName)) ItemAdded(this, new HierarchyItemEventArgs(Hierarchy, currentItem, itemName)); else TryFierOnAddReference(currentItem); // NOTE: At the moment we skip the nested hierarchies, so here we // look for the children of this node. Before looking at the children // we have to make sure that the enumeration has not side effects to // avoid unexpected behavior. // object propertyValue; bool canScanSubitems = true; int hr = Hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_HasEnumerationSideEffects, out propertyValue); if ((VSConstants.S_OK == hr) && (propertyValue is bool)) canScanSubitems = !(bool)propertyValue; // If it is allow to look at the sub-items of the current one, lets do it. // if (canScanSubitems) { object child; hr = Hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_FirstChild, out child); if (VSConstants.S_OK == hr) // There is a sub-item, call this same function on it. InternalScanHierarchy(GetItemId(child)); } // Move the current item to its first visible sibling. // object sibling; hr = Hierarchy.GetProperty(currentItem, (int)__VSHPROPID.VSHPROPID_NextSibling, out sibling); currentItem = VSConstants.S_OK != hr ? VSConstants.VSITEMID_NIL : GetItemId(sibling); } } /// <summary> /// Gets the item id. /// </summary> /// <param name="variantValue">VARIANT holding an itemid.</param> /// <returns>Item Id of the concerned node</returns> static uint GetItemId(object variantValue) { if (variantValue == null) return VSConstants.VSITEMID_NIL; if (variantValue is int) return (uint)(int)variantValue; if (variantValue is uint) return (uint)variantValue; if (variantValue is short) return (uint)(short)variantValue; if (variantValue is ushort) return (ushort)variantValue; if (variantValue is long) return (uint)(long)variantValue; return VSConstants.VSITEMID_NIL; } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.312 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // // This source code was auto-generated by wsdl, Version=2.0.50727.42. // using WebsitePanel.EnterpriseServer.Base.Scheduling; namespace WebsitePanel.EnterpriseServer { using System.Diagnostics; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Xml.Serialization; using System.Data; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name = "esSchedulerSoap", Namespace = "http://smbsaas/websitepanel/enterpriseserver")] public partial class esScheduler : Microsoft.Web.Services3.WebServicesClientProtocol { private System.Threading.SendOrPostCallback GetSchedulerTimeOperationCompleted; private System.Threading.SendOrPostCallback GetScheduleTasksOperationCompleted; private System.Threading.SendOrPostCallback GetSchedulesOperationCompleted; private System.Threading.SendOrPostCallback GetSchedulesPagedOperationCompleted; private System.Threading.SendOrPostCallback GetScheduleOperationCompleted; private System.Threading.SendOrPostCallback GetScheduleParametersOperationCompleted; private System.Threading.SendOrPostCallback GetScheduleTaskViewConfigurationsOperationCompleted; private System.Threading.SendOrPostCallback GetScheduleTaskViewConfigurationOperationCompleted; private System.Threading.SendOrPostCallback StartScheduleOperationCompleted; private System.Threading.SendOrPostCallback StopScheduleOperationCompleted; private System.Threading.SendOrPostCallback AddScheduleOperationCompleted; private System.Threading.SendOrPostCallback UpdateScheduleOperationCompleted; private System.Threading.SendOrPostCallback DeleteScheduleOperationCompleted; /// <remarks/> public esScheduler() { this.Url = "http://localhost/WebsitePanelEnterpriseServer/esScheduler.asmx"; } /// <remarks/> public event GetSchedulerTimeCompletedEventHandler GetSchedulerTimeCompleted; /// <remarks/> public event GetScheduleTasksCompletedEventHandler GetScheduleTasksCompleted; /// <remarks/> public event GetSchedulesCompletedEventHandler GetSchedulesCompleted; /// <remarks/> public event GetSchedulesPagedCompletedEventHandler GetSchedulesPagedCompleted; /// <remarks/> public event GetScheduleCompletedEventHandler GetScheduleCompleted; /// <remarks/> public event GetScheduleParametersCompletedEventHandler GetScheduleParametersCompleted; /// <remarks/> public event GetScheduleTaskViewConfigurationsCompletedEventHandler GetScheduleTaskViewConfigurationsCompleted; /// <remarks/> public event GetScheduleTaskViewConfigurationCompletedEventHandler GetScheduleTaskViewConfigurationCompleted; /// <remarks/> public event StartScheduleCompletedEventHandler StartScheduleCompleted; /// <remarks/> public event StopScheduleCompletedEventHandler StopScheduleCompleted; /// <remarks/> public event AddScheduleCompletedEventHandler AddScheduleCompleted; /// <remarks/> public event UpdateScheduleCompletedEventHandler UpdateScheduleCompleted; /// <remarks/> public event DeleteScheduleCompletedEventHandler DeleteScheduleCompleted; /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetSchedulerTime", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.DateTime GetSchedulerTime() { object[] results = this.Invoke("GetSchedulerTime", new object[0]); return ((System.DateTime)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetSchedulerTime(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetSchedulerTime", new object[0], callback, asyncState); } /// <remarks/> public System.DateTime EndGetSchedulerTime(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.DateTime)(results[0])); } /// <remarks/> public void GetSchedulerTimeAsync() { this.GetSchedulerTimeAsync(null); } /// <remarks/> public void GetSchedulerTimeAsync(object userState) { if ((this.GetSchedulerTimeOperationCompleted == null)) { this.GetSchedulerTimeOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSchedulerTimeOperationCompleted); } this.InvokeAsync("GetSchedulerTime", new object[0], this.GetSchedulerTimeOperationCompleted, userState); } private void OnGetSchedulerTimeOperationCompleted(object arg) { if ((this.GetSchedulerTimeCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetSchedulerTimeCompleted(this, new GetSchedulerTimeCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetScheduleTasks", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public ScheduleTaskInfo[] GetScheduleTasks() { object[] results = this.Invoke("GetScheduleTasks", new object[0]); return ((ScheduleTaskInfo[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetScheduleTasks(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetScheduleTasks", new object[0], callback, asyncState); } /// <remarks/> public ScheduleTaskInfo[] EndGetScheduleTasks(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((ScheduleTaskInfo[])(results[0])); } /// <remarks/> public void GetScheduleTasksAsync() { this.GetScheduleTasksAsync(null); } /// <remarks/> public void GetScheduleTasksAsync(object userState) { if ((this.GetScheduleTasksOperationCompleted == null)) { this.GetScheduleTasksOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetScheduleTasksOperationCompleted); } this.InvokeAsync("GetScheduleTasks", new object[0], this.GetScheduleTasksOperationCompleted, userState); } private void OnGetScheduleTasksOperationCompleted(object arg) { if ((this.GetScheduleTasksCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetScheduleTasksCompleted(this, new GetScheduleTasksCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetSchedules", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetSchedules(int userId) { object[] results = this.Invoke("GetSchedules", new object[] { userId}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetSchedules(int userId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetSchedules", new object[] { userId}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetSchedules(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetSchedulesAsync(int userId) { this.GetSchedulesAsync(userId, null); } /// <remarks/> public void GetSchedulesAsync(int userId, object userState) { if ((this.GetSchedulesOperationCompleted == null)) { this.GetSchedulesOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSchedulesOperationCompleted); } this.InvokeAsync("GetSchedules", new object[] { userId}, this.GetSchedulesOperationCompleted, userState); } private void OnGetSchedulesOperationCompleted(object arg) { if ((this.GetSchedulesCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetSchedulesCompleted(this, new GetSchedulesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetSchedulesPaged", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public System.Data.DataSet GetSchedulesPaged(int packageId, bool recursive, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { object[] results = this.Invoke("GetSchedulesPaged", new object[] { packageId, recursive, filterColumn, filterValue, sortColumn, startRow, maximumRows}); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetSchedulesPaged(int packageId, bool recursive, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetSchedulesPaged", new object[] { packageId, recursive, filterColumn, filterValue, sortColumn, startRow, maximumRows}, callback, asyncState); } /// <remarks/> public System.Data.DataSet EndGetSchedulesPaged(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((System.Data.DataSet)(results[0])); } /// <remarks/> public void GetSchedulesPagedAsync(int packageId, bool recursive, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { this.GetSchedulesPagedAsync(packageId, recursive, filterColumn, filterValue, sortColumn, startRow, maximumRows, null); } /// <remarks/> public void GetSchedulesPagedAsync(int packageId, bool recursive, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows, object userState) { if ((this.GetSchedulesPagedOperationCompleted == null)) { this.GetSchedulesPagedOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetSchedulesPagedOperationCompleted); } this.InvokeAsync("GetSchedulesPaged", new object[] { packageId, recursive, filterColumn, filterValue, sortColumn, startRow, maximumRows}, this.GetSchedulesPagedOperationCompleted, userState); } private void OnGetSchedulesPagedOperationCompleted(object arg) { if ((this.GetSchedulesPagedCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetSchedulesPagedCompleted(this, new GetSchedulesPagedCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetSchedule", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public ScheduleInfo GetSchedule(int scheduleId) { object[] results = this.Invoke("GetSchedule", new object[] { scheduleId}); return ((ScheduleInfo)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetSchedule(int scheduleId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetSchedule", new object[] { scheduleId}, callback, asyncState); } /// <remarks/> public ScheduleInfo EndGetSchedule(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((ScheduleInfo)(results[0])); } /// <remarks/> public void GetScheduleAsync(int scheduleId) { this.GetScheduleAsync(scheduleId, null); } /// <remarks/> public void GetScheduleAsync(int scheduleId, object userState) { if ((this.GetScheduleOperationCompleted == null)) { this.GetScheduleOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetScheduleOperationCompleted); } this.InvokeAsync("GetSchedule", new object[] { scheduleId}, this.GetScheduleOperationCompleted, userState); } private void OnGetScheduleOperationCompleted(object arg) { if ((this.GetScheduleCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetScheduleCompleted(this, new GetScheduleCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetScheduleParameters", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public ScheduleTaskParameterInfo[] GetScheduleParameters(string taskId, int scheduleId) { object[] results = this.Invoke("GetScheduleParameters", new object[] { taskId, scheduleId}); return ((ScheduleTaskParameterInfo[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetScheduleParameters(string taskId, int scheduleId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetScheduleParameters", new object[] { taskId, scheduleId}, callback, asyncState); } /// <remarks/> public ScheduleTaskParameterInfo[] EndGetScheduleParameters(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((ScheduleTaskParameterInfo[])(results[0])); } /// <remarks/> public void GetScheduleParametersAsync(string taskId, int scheduleId) { this.GetScheduleParametersAsync(taskId, scheduleId, null); } /// <remarks/> public void GetScheduleParametersAsync(string taskId, int scheduleId, object userState) { if ((this.GetScheduleParametersOperationCompleted == null)) { this.GetScheduleParametersOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetScheduleParametersOperationCompleted); } this.InvokeAsync("GetScheduleParameters", new object[] { taskId, scheduleId}, this.GetScheduleParametersOperationCompleted, userState); } private void OnGetScheduleParametersOperationCompleted(object arg) { if ((this.GetScheduleParametersCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetScheduleParametersCompleted(this, new GetScheduleParametersCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetScheduleTaskViewConfigurati" + "ons", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public ScheduleTaskViewConfiguration[] GetScheduleTaskViewConfigurations(string taskId) { object[] results = this.Invoke("GetScheduleTaskViewConfigurations", new object[] { taskId}); return ((ScheduleTaskViewConfiguration[])(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetScheduleTaskViewConfigurations(string taskId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetScheduleTaskViewConfigurations", new object[] { taskId}, callback, asyncState); } /// <remarks/> public ScheduleTaskViewConfiguration[] EndGetScheduleTaskViewConfigurations(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((ScheduleTaskViewConfiguration[])(results[0])); } /// <remarks/> public void GetScheduleTaskViewConfigurationsAsync(string taskId) { this.GetScheduleTaskViewConfigurationsAsync(taskId, null); } /// <remarks/> public void GetScheduleTaskViewConfigurationsAsync(string taskId, object userState) { if ((this.GetScheduleTaskViewConfigurationsOperationCompleted == null)) { this.GetScheduleTaskViewConfigurationsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetScheduleTaskViewConfigurationsOperationCompleted); } this.InvokeAsync("GetScheduleTaskViewConfigurations", new object[] { taskId}, this.GetScheduleTaskViewConfigurationsOperationCompleted, userState); } private void OnGetScheduleTaskViewConfigurationsOperationCompleted(object arg) { if ((this.GetScheduleTaskViewConfigurationsCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetScheduleTaskViewConfigurationsCompleted(this, new GetScheduleTaskViewConfigurationsCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/GetScheduleTaskViewConfigurati" + "on", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public ScheduleTaskViewConfiguration GetScheduleTaskViewConfiguration(string taskId, string environment) { object[] results = this.Invoke("GetScheduleTaskViewConfiguration", new object[] { taskId, environment}); return ((ScheduleTaskViewConfiguration)(results[0])); } /// <remarks/> public System.IAsyncResult BeginGetScheduleTaskViewConfiguration(string taskId, string environment, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("GetScheduleTaskViewConfiguration", new object[] { taskId, environment}, callback, asyncState); } /// <remarks/> public ScheduleTaskViewConfiguration EndGetScheduleTaskViewConfiguration(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((ScheduleTaskViewConfiguration)(results[0])); } /// <remarks/> public void GetScheduleTaskViewConfigurationAsync(string taskId, string environment) { this.GetScheduleTaskViewConfigurationAsync(taskId, environment, null); } /// <remarks/> public void GetScheduleTaskViewConfigurationAsync(string taskId, string environment, object userState) { if ((this.GetScheduleTaskViewConfigurationOperationCompleted == null)) { this.GetScheduleTaskViewConfigurationOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetScheduleTaskViewConfigurationOperationCompleted); } this.InvokeAsync("GetScheduleTaskViewConfiguration", new object[] { taskId, environment}, this.GetScheduleTaskViewConfigurationOperationCompleted, userState); } private void OnGetScheduleTaskViewConfigurationOperationCompleted(object arg) { if ((this.GetScheduleTaskViewConfigurationCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.GetScheduleTaskViewConfigurationCompleted(this, new GetScheduleTaskViewConfigurationCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/StartSchedule", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int StartSchedule(int scheduleId) { object[] results = this.Invoke("StartSchedule", new object[] { scheduleId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginStartSchedule(int scheduleId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("StartSchedule", new object[] { scheduleId}, callback, asyncState); } /// <remarks/> public int EndStartSchedule(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void StartScheduleAsync(int scheduleId) { this.StartScheduleAsync(scheduleId, null); } /// <remarks/> public void StartScheduleAsync(int scheduleId, object userState) { if ((this.StartScheduleOperationCompleted == null)) { this.StartScheduleOperationCompleted = new System.Threading.SendOrPostCallback(this.OnStartScheduleOperationCompleted); } this.InvokeAsync("StartSchedule", new object[] { scheduleId}, this.StartScheduleOperationCompleted, userState); } private void OnStartScheduleOperationCompleted(object arg) { if ((this.StartScheduleCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.StartScheduleCompleted(this, new StartScheduleCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/StopSchedule", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int StopSchedule(int scheduleId) { object[] results = this.Invoke("StopSchedule", new object[] { scheduleId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginStopSchedule(int scheduleId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("StopSchedule", new object[] { scheduleId}, callback, asyncState); } /// <remarks/> public int EndStopSchedule(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void StopScheduleAsync(int scheduleId) { this.StopScheduleAsync(scheduleId, null); } /// <remarks/> public void StopScheduleAsync(int scheduleId, object userState) { if ((this.StopScheduleOperationCompleted == null)) { this.StopScheduleOperationCompleted = new System.Threading.SendOrPostCallback(this.OnStopScheduleOperationCompleted); } this.InvokeAsync("StopSchedule", new object[] { scheduleId}, this.StopScheduleOperationCompleted, userState); } private void OnStopScheduleOperationCompleted(object arg) { if ((this.StopScheduleCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.StopScheduleCompleted(this, new StopScheduleCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/AddSchedule", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int AddSchedule(ScheduleInfo schedule) { object[] results = this.Invoke("AddSchedule", new object[] { schedule}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginAddSchedule(ScheduleInfo schedule, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("AddSchedule", new object[] { schedule}, callback, asyncState); } /// <remarks/> public int EndAddSchedule(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void AddScheduleAsync(ScheduleInfo schedule) { this.AddScheduleAsync(schedule, null); } /// <remarks/> public void AddScheduleAsync(ScheduleInfo schedule, object userState) { if ((this.AddScheduleOperationCompleted == null)) { this.AddScheduleOperationCompleted = new System.Threading.SendOrPostCallback(this.OnAddScheduleOperationCompleted); } this.InvokeAsync("AddSchedule", new object[] { schedule}, this.AddScheduleOperationCompleted, userState); } private void OnAddScheduleOperationCompleted(object arg) { if ((this.AddScheduleCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.AddScheduleCompleted(this, new AddScheduleCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/UpdateSchedule", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int UpdateSchedule(ScheduleInfo schedule) { object[] results = this.Invoke("UpdateSchedule", new object[] { schedule}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginUpdateSchedule(ScheduleInfo schedule, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("UpdateSchedule", new object[] { schedule}, callback, asyncState); } /// <remarks/> public int EndUpdateSchedule(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void UpdateScheduleAsync(ScheduleInfo schedule) { this.UpdateScheduleAsync(schedule, null); } /// <remarks/> public void UpdateScheduleAsync(ScheduleInfo schedule, object userState) { if ((this.UpdateScheduleOperationCompleted == null)) { this.UpdateScheduleOperationCompleted = new System.Threading.SendOrPostCallback(this.OnUpdateScheduleOperationCompleted); } this.InvokeAsync("UpdateSchedule", new object[] { schedule}, this.UpdateScheduleOperationCompleted, userState); } private void OnUpdateScheduleOperationCompleted(object arg) { if ((this.UpdateScheduleCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.UpdateScheduleCompleted(this, new UpdateScheduleCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://smbsaas/websitepanel/enterpriseserver/DeleteSchedule", RequestNamespace = "http://smbsaas/websitepanel/enterpriseserver", ResponseNamespace = "http://smbsaas/websitepanel/enterpriseserver", Use = System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle = System.Web.Services.Protocols.SoapParameterStyle.Wrapped)] public int DeleteSchedule(int scheduleId) { object[] results = this.Invoke("DeleteSchedule", new object[] { scheduleId}); return ((int)(results[0])); } /// <remarks/> public System.IAsyncResult BeginDeleteSchedule(int scheduleId, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("DeleteSchedule", new object[] { scheduleId}, callback, asyncState); } /// <remarks/> public int EndDeleteSchedule(System.IAsyncResult asyncResult) { object[] results = this.EndInvoke(asyncResult); return ((int)(results[0])); } /// <remarks/> public void DeleteScheduleAsync(int scheduleId) { this.DeleteScheduleAsync(scheduleId, null); } /// <remarks/> public void DeleteScheduleAsync(int scheduleId, object userState) { if ((this.DeleteScheduleOperationCompleted == null)) { this.DeleteScheduleOperationCompleted = new System.Threading.SendOrPostCallback(this.OnDeleteScheduleOperationCompleted); } this.InvokeAsync("DeleteSchedule", new object[] { scheduleId}, this.DeleteScheduleOperationCompleted, userState); } private void OnDeleteScheduleOperationCompleted(object arg) { if ((this.DeleteScheduleCompleted != null)) { System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg)); this.DeleteScheduleCompleted(this, new DeleteScheduleCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState)); } } /// <remarks/> public new void CancelAsync(object userState) { base.CancelAsync(userState); } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetSchedulerTimeCompletedEventHandler(object sender, GetSchedulerTimeCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetSchedulerTimeCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSchedulerTimeCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.DateTime Result { get { this.RaiseExceptionIfNecessary(); return ((System.DateTime)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetScheduleTasksCompletedEventHandler(object sender, GetScheduleTasksCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetScheduleTasksCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetScheduleTasksCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public ScheduleTaskInfo[] Result { get { this.RaiseExceptionIfNecessary(); return ((ScheduleTaskInfo[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetSchedulesCompletedEventHandler(object sender, GetSchedulesCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetSchedulesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSchedulesCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetSchedulesPagedCompletedEventHandler(object sender, GetSchedulesPagedCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetSchedulesPagedCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetSchedulesPagedCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public System.Data.DataSet Result { get { this.RaiseExceptionIfNecessary(); return ((System.Data.DataSet)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetScheduleCompletedEventHandler(object sender, GetScheduleCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetScheduleCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetScheduleCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public ScheduleInfo Result { get { this.RaiseExceptionIfNecessary(); return ((ScheduleInfo)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetScheduleParametersCompletedEventHandler(object sender, GetScheduleParametersCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetScheduleParametersCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetScheduleParametersCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public ScheduleTaskParameterInfo[] Result { get { this.RaiseExceptionIfNecessary(); return ((ScheduleTaskParameterInfo[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetScheduleTaskViewConfigurationsCompletedEventHandler(object sender, GetScheduleTaskViewConfigurationsCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetScheduleTaskViewConfigurationsCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetScheduleTaskViewConfigurationsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public ScheduleTaskViewConfiguration[] Result { get { this.RaiseExceptionIfNecessary(); return ((ScheduleTaskViewConfiguration[])(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void GetScheduleTaskViewConfigurationCompletedEventHandler(object sender, GetScheduleTaskViewConfigurationCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class GetScheduleTaskViewConfigurationCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal GetScheduleTaskViewConfigurationCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public ScheduleTaskViewConfiguration Result { get { this.RaiseExceptionIfNecessary(); return ((ScheduleTaskViewConfiguration)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void StartScheduleCompletedEventHandler(object sender, StartScheduleCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class StartScheduleCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal StartScheduleCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void StopScheduleCompletedEventHandler(object sender, StopScheduleCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class StopScheduleCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal StopScheduleCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void AddScheduleCompletedEventHandler(object sender, AddScheduleCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class AddScheduleCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal AddScheduleCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void UpdateScheduleCompletedEventHandler(object sender, UpdateScheduleCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class UpdateScheduleCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal UpdateScheduleCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] public delegate void DeleteScheduleCompletedEventHandler(object sender, DeleteScheduleCompletedEventArgs e); /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.42")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] public partial class DeleteScheduleCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs { private object[] results; internal DeleteScheduleCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : base(exception, cancelled, userState) { this.results = results; } /// <remarks/> public int Result { get { this.RaiseExceptionIfNecessary(); return ((int)(this.results[0])); } } } }
// StreamManipulator.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// This class allows us to retrieve a specified number of bits from /// the input buffer, as well as copy big byte blocks. /// /// It uses an int buffer to store up to 31 bits for direct /// manipulation. This guarantees that we can get at least 16 bits, /// but we only need at most 15, so this is all safe. /// /// There are some optimizations in this class, for example, you must /// never peek more than 8 bits more than needed, and you must first /// peek bits before you may drop them. This is not a general purpose /// class but optimized for the behaviour of the Inflater. /// /// authors of the original java version : John Leuner, Jochen Hoenicke /// </summary> public class StreamManipulator { #region Constructors /// <summary> /// Constructs a default StreamManipulator with all buffers empty /// </summary> public StreamManipulator() { } #endregion /// <summary> /// Get the next sequence of bits but don't increase input pointer. bitCount must be /// less or equal 16 and if this call succeeds, you must drop /// at least n - 8 bits in the next call. /// </summary> /// <param name="bitCount">The number of bits to peek.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. */ /// </returns> public int PeekBits(int bitCount) { if (bitsInBuffer_ < bitCount) { if (windowStart_ == windowEnd_) { return -1; // ok } buffer_ |= (uint)((window_[windowStart_++] & 0xff | (window_[windowStart_++] & 0xff) << 8) << bitsInBuffer_); bitsInBuffer_ += 16; } return (int)(buffer_ & ((1 << bitCount) - 1)); } /// <summary> /// Drops the next n bits from the input. You should have called PeekBits /// with a bigger or equal n before, to make sure that enough bits are in /// the bit buffer. /// </summary> /// <param name="bitCount">The number of bits to drop.</param> public void DropBits(int bitCount) { buffer_ >>= bitCount; bitsInBuffer_ -= bitCount; } /// <summary> /// Gets the next n bits and increases input pointer. This is equivalent /// to <see cref="PeekBits"/> followed by <see cref="DropBits"/>, except for correct error handling. /// </summary> /// <param name="bitCount">The number of bits to retrieve.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. /// </returns> public int GetBits(int bitCount) { int bits = PeekBits(bitCount); if (bits >= 0) { DropBits(bitCount); } return bits; } /// <summary> /// Gets the number of bits available in the bit buffer. This must be /// only called when a previous PeekBits() returned -1. /// </summary> /// <returns> /// the number of bits available. /// </returns> public int AvailableBits { get { return bitsInBuffer_; } } /// <summary> /// Gets the number of bytes available. /// </summary> /// <returns> /// The number of bytes available. /// </returns> public int AvailableBytes { get { return windowEnd_ - windowStart_ + (bitsInBuffer_ >> 3); } } /// <summary> /// Skips to the next byte boundary. /// </summary> public void SkipToByteBoundary() { buffer_ >>= (bitsInBuffer_ & 7); bitsInBuffer_ &= ~7; } /// <summary> /// Returns true when SetInput can be called /// </summary> public bool IsNeedingInput { get { return windowStart_ == windowEnd_; } } /// <summary> /// Copies bytes from input buffer to output buffer starting /// at output[offset]. You have to make sure, that the buffer is /// byte aligned. If not enough bytes are available, copies fewer /// bytes. /// </summary> /// <param name="output"> /// The buffer to copy bytes to. /// </param> /// <param name="offset"> /// The offset in the buffer at which copying starts /// </param> /// <param name="length"> /// The length to copy, 0 is allowed. /// </param> /// <returns> /// The number of bytes copied, 0 if no bytes were available. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Length is less than zero /// </exception> /// <exception cref="InvalidOperationException"> /// Bit buffer isnt byte aligned /// </exception> public int CopyBytes(byte[] output, int offset, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } if ((bitsInBuffer_ & 7) != 0) { // bits_in_buffer may only be 0 or a multiple of 8 throw new InvalidOperationException("Bit buffer is not byte aligned!"); } int count = 0; while ((bitsInBuffer_ > 0) && (length > 0)) { output[offset++] = (byte) buffer_; buffer_ >>= 8; bitsInBuffer_ -= 8; length--; count++; } if (length == 0) { return count; } int avail = windowEnd_ - windowStart_; if (length > avail) { length = avail; } System.Array.Copy(window_, windowStart_, output, offset, length); windowStart_ += length; if (((windowStart_ - windowEnd_) & 1) != 0) { // We always want an even number of bytes in input, see peekBits buffer_ = (uint)(window_[windowStart_++] & 0xff); bitsInBuffer_ = 8; } return count + length; } /// <summary> /// Resets state and empties internal buffers /// </summary> public void Reset() { buffer_ = 0; windowStart_ = windowEnd_ = bitsInBuffer_ = 0; } /// <summary> /// Add more input for consumption. /// Only call when IsNeedingInput returns true /// </summary> /// <param name="buffer">data to be input</param> /// <param name="offset">offset of first byte of input</param> /// <param name="count">number of bytes of input to add.</param> public void SetInput(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 || UNITY_WINRT throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if ( count < 0 ) { #if NETCF_1_0 || UNITY_WINRT throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if (windowStart_ < windowEnd_) { throw new InvalidOperationException("Old input was not completely processed"); } int end = offset + count; // We want to throw an ArrayIndexOutOfBoundsException early. // Note the check also handles integer wrap around. if ((offset > end) || (end > buffer.Length) ) { throw new ArgumentOutOfRangeException("count"); } if ((count & 1) != 0) { // We always want an even number of bytes in input, see PeekBits buffer_ |= (uint)((buffer[offset++] & 0xff) << bitsInBuffer_); bitsInBuffer_ += 8; } window_ = buffer; windowStart_ = offset; windowEnd_ = end; } #region Instance Fields private byte[] window_; private int windowStart_; private int windowEnd_; private uint buffer_; private int bitsInBuffer_; #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. extern alias PDB; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; using PDB::Roslyn.Test.MetadataUtilities; using PDB::Roslyn.Test.PdbUtilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests { internal sealed class Scope { internal readonly int StartOffset; internal readonly int EndOffset; internal readonly ImmutableArray<string> Locals; internal Scope(int startOffset, int endOffset, ImmutableArray<string> locals, bool isEndInclusive) { this.StartOffset = startOffset; this.EndOffset = endOffset + (isEndInclusive ? 1 : 0); this.Locals = locals; } internal int Length { get { return this.EndOffset - this.StartOffset + 1; } } internal bool Contains(int offset) { return (offset >= this.StartOffset) && (offset < this.EndOffset); } } internal static class ExpressionCompilerTestHelpers { internal static CompileResult CompileAssignment( this EvaluationContextBase context, string target, string expr, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileAssignment( target, expr, ImmutableArray<Alias>.Empty, formatter ?? DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); // This is a crude way to test the language, but it's convenient to share this test helper. var isCSharp = context.GetType().Namespace.IndexOf("csharp", StringComparison.OrdinalIgnoreCase) >= 0; var expectedFlags = error != null ? DkmClrCompilationResultFlags.None : isCSharp ? DkmClrCompilationResultFlags.PotentialSideEffect : DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult; Assert.Equal(expectedFlags, resultProperties.Flags); Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType); Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); return result; } internal static CompileResult CompileAssignment( this EvaluationContextBase context, string target, string expr, ImmutableArray<Alias> aliases, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, CultureInfo preferredUICulture, CompilationTestData testData) { var diagnostics = DiagnosticBag.GetInstance(); var result = context.CompileAssignment(target, expr, aliases, diagnostics, out resultProperties, testData); if (diagnostics.HasAnyErrors()) { bool useReferencedModulesOnly; error = context.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, EvaluationContextBase.SystemCoreIdentity, out useReferencedModulesOnly, out missingAssemblyIdentities); } else { error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; } diagnostics.Free(); return result; } internal static ReadOnlyCollection<byte> CompileGetLocals( this EvaluationContextBase context, ArrayBuilder<LocalAndMethod> locals, bool argumentsOnly, out string typeName, CompilationTestData testData, DiagnosticDescription[] expectedDiagnostics = null) { var diagnostics = DiagnosticBag.GetInstance(); var result = context.CompileGetLocals( locals, argumentsOnly, ImmutableArray<Alias>.Empty, diagnostics, out typeName, testData); diagnostics.Verify(expectedDiagnostics ?? DiagnosticDescription.None); diagnostics.Free(); return result; } internal static CompileResult CompileExpression( this EvaluationContextBase context, string expr, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; return CompileExpression(context, expr, out resultProperties, out error, testData, formatter); } internal static CompileResult CompileExpression( this EvaluationContextBase context, string expr, out ResultProperties resultProperties, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, ImmutableArray<Alias>.Empty, formatter ?? DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return result; } static internal CompileResult CompileExpression( this EvaluationContextBase evaluationContext, string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, out string error, CompilationTestData testData = null, DiagnosticFormatter formatter = null) { ResultProperties resultProperties; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = evaluationContext.CompileExpression( expr, compilationFlags, aliases, formatter ?? DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return result; } /// <summary> /// Compile C# expression and emit assembly with evaluation method. /// </summary> /// <returns> /// Result containing generated assembly, type and method names, and any format specifiers. /// </returns> static internal CompileResult CompileExpression( this EvaluationContextBase evaluationContext, string expr, DkmEvaluationFlags compilationFlags, ImmutableArray<Alias> aliases, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, CultureInfo preferredUICulture, CompilationTestData testData) { var diagnostics = DiagnosticBag.GetInstance(); var result = evaluationContext.CompileExpression(expr, compilationFlags, aliases, diagnostics, out resultProperties, testData); if (diagnostics.HasAnyErrors()) { bool useReferencedModulesOnly; error = evaluationContext.GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, EvaluationContextBase.SystemCoreIdentity, out useReferencedModulesOnly, out missingAssemblyIdentities); } else { error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; } diagnostics.Free(); return result; } internal static CompileResult CompileExpressionWithRetry( ImmutableArray<MetadataBlock> metadataBlocks, EvaluationContextBase context, ExpressionCompiler.CompileDelegate<CompileResult> compile, DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage) { return ExpressionCompiler.CompileWithRetry( metadataBlocks, DebuggerDiagnosticFormatter.Instance, (blocks, useReferencedModulesOnly) => context, compile, getMetaDataBytesPtr, out errorMessage); } internal static CompileResult CompileExpressionWithRetry( ImmutableArray<MetadataBlock> metadataBlocks, string expr, ImmutableArray<Alias> aliases, ExpressionCompiler.CreateContextDelegate createContext, DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage, out CompilationTestData testData) { var r = ExpressionCompiler.CompileWithRetry( metadataBlocks, DebuggerDiagnosticFormatter.Instance, createContext, (context, diagnostics) => { var td = new CompilationTestData(); ResultProperties resultProperties; var compileResult = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, aliases, diagnostics, out resultProperties, td); return new CompileExpressionResult(compileResult, td); }, getMetaDataBytesPtr, out errorMessage); testData = r.TestData; return r.CompileResult; } private struct CompileExpressionResult { internal readonly CompileResult CompileResult; internal readonly CompilationTestData TestData; internal CompileExpressionResult(CompileResult compileResult, CompilationTestData testData) { this.CompileResult = compileResult; this.TestData = testData; } } internal static TypeDefinition GetTypeDef(this MetadataReader reader, string typeName) { return reader.TypeDefinitions.Select(reader.GetTypeDefinition).First(t => reader.StringComparer.Equals(t.Name, typeName)); } internal static MethodDefinition GetMethodDef(this MetadataReader reader, TypeDefinition typeDef, string methodName) { return typeDef.GetMethods().Select(reader.GetMethodDefinition).First(m => reader.StringComparer.Equals(m.Name, methodName)); } internal static MethodDefinitionHandle GetMethodDefHandle(this MetadataReader reader, TypeDefinition typeDef, string methodName) { return typeDef.GetMethods().First(h => reader.StringComparer.Equals(reader.GetMethodDefinition(h).Name, methodName)); } internal static void CheckTypeParameters(this MetadataReader reader, GenericParameterHandleCollection genericParameters, params string[] expectedNames) { var actualNames = genericParameters.Select(reader.GetGenericParameter).Select(tp => reader.GetString(tp.Name)).ToArray(); Assert.True(expectedNames.SequenceEqual(actualNames)); } internal static AssemblyName GetAssemblyName(this byte[] exeBytes) { using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes))) { var metadataReader = reader.GetMetadataReader(); var def = metadataReader.GetAssemblyDefinition(); var name = metadataReader.GetString(def.Name); return new AssemblyName() { Name = name, Version = def.Version }; } } internal static Guid GetModuleVersionId(this byte[] exeBytes) { using (var reader = new PEReader(ImmutableArray.CreateRange(exeBytes))) { return reader.GetMetadataReader().GetModuleVersionId(); } } internal static ImmutableArray<string> GetLocalNames(this ISymUnmanagedReader symReader, int methodToken, int methodVersion = 1) { var method = symReader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { return ImmutableArray<string>.Empty; } var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); method.GetAllScopes(scopes); var names = ArrayBuilder<string>.GetInstance(); foreach (var scope in scopes) { foreach (var local in scope.GetLocals()) { var name = local.GetName(); int slot; local.GetAddressField1(out slot); while (names.Count <= slot) { names.Add(null); } names[slot] = name; } } scopes.Free(); return names.ToImmutableAndFree(); } internal static void VerifyIL( this byte[] assembly, int methodToken, string qualifiedName, string expectedIL, [CallerLineNumber]int expectedValueSourceLine = 0, [CallerFilePath]string expectedValueSourcePath = null) { var parts = qualifiedName.Split('.'); if (parts.Length != 2) { throw new NotImplementedException(); } using (var metadata = ModuleMetadata.CreateFromImage(assembly)) { var module = metadata.Module; var reader = module.MetadataReader; var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken); var methodDef = reader.GetMethodDefinition(methodHandle); var typeDef = reader.GetTypeDefinition(methodDef.GetDeclaringType()); Assert.True(reader.StringComparer.Equals(typeDef.Name, parts[0])); Assert.True(reader.StringComparer.Equals(methodDef.Name, parts[1])); var methodBody = module.GetMethodBodyOrThrow(methodHandle); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; var writer = new StringWriter(pooled.Builder); var visualizer = new MetadataVisualizer(reader, writer); visualizer.VisualizeMethodBody(methodBody, methodHandle, emitHeader: false); var actualIL = pooled.ToStringAndFree(); AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); } } internal static ImmutableArray<MetadataReference> GetEmittedReferences(Compilation compilation, MetadataReader mdReader) { // Determine the set of references that were actually used // and ignore any references that were dropped in emit. var referenceNames = new HashSet<string>(mdReader.AssemblyReferences.Select(h => GetAssemblyReferenceName(mdReader, h))); return ImmutableArray.CreateRange(compilation.References.Where(r => IsReferenced(r, referenceNames))); } internal static ImmutableArray<Scope> GetScopes(this ISymUnmanagedReader symReader, int methodToken, int methodVersion, bool isEndInclusive) { var method = symReader.GetMethodByVersion(methodToken, methodVersion); if (method == null) { return ImmutableArray<Scope>.Empty; } var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); method.GetAllScopes(scopes); var result = scopes.SelectAsArray(s => new Scope(s.GetStartOffset(), s.GetEndOffset(), ImmutableArray.CreateRange(s.GetLocals().Select(l => l.GetName())), isEndInclusive)); scopes.Free(); return result; } internal static Scope GetInnermostScope(this ImmutableArray<Scope> scopes, int offset) { Scope result = null; foreach (var scope in scopes) { if (scope.Contains(offset)) { if ((result == null) || (result.Length > scope.Length)) { result = scope; } } } return result; } private static string GetAssemblyReferenceName(MetadataReader reader, AssemblyReferenceHandle handle) { var reference = reader.GetAssemblyReference(handle); return reader.GetString(reference.Name); } private static bool IsReferenced(MetadataReference reference, HashSet<string> referenceNames) { var assemblyMetadata = ((PortableExecutableReference)reference).GetMetadataNoCopy() as AssemblyMetadata; if (assemblyMetadata == null) { // Netmodule. Assume it is referenced. return true; } var name = assemblyMetadata.GetAssembly().Identity.Name; return referenceNames.Contains(name); } internal static ModuleInstance ToModuleInstance(this MetadataReference reference) { return ModuleInstance.Create((PortableExecutableReference)reference); } internal static ModuleInstance ToModuleInstance( this Compilation compilation, DebugInformationFormat debugFormat = DebugInformationFormat.Pdb, bool includeLocalSignatures = true) { var pdbStream = (debugFormat != 0) ? new MemoryStream() : null; var peImage = compilation.EmitToArray(new EmitOptions(debugInformationFormat: debugFormat), pdbStream: pdbStream); var symReader = (debugFormat != 0) ? SymReaderFactory.CreateReader(pdbStream, new PEReader(peImage)) : null; return ModuleInstance.Create(peImage, symReader, includeLocalSignatures); } internal static ModuleInstance GetModuleInstanceForIL(string ilSource) { ImmutableArray<byte> peBytes; ImmutableArray<byte> pdbBytes; CommonTestBase.EmitILToArray(ilSource, appendDefaultHeader: true, includePdb: true, assemblyBytes: out peBytes, pdbBytes: out pdbBytes); return ModuleInstance.Create(peBytes, SymReaderFactory.CreateReader(pdbBytes), includeLocalSignatures: true); } internal static AssemblyIdentity GetAssemblyIdentity(this MetadataReference reference) { using (var moduleMetadata = GetManifestModuleMetadata(reference)) { return moduleMetadata.MetadataReader.ReadAssemblyIdentityOrThrow(); } } internal static Guid GetModuleVersionId(this MetadataReference reference) { using (var moduleMetadata = GetManifestModuleMetadata(reference)) { return moduleMetadata.MetadataReader.GetModuleVersionIdOrThrow(); } } private static ModuleMetadata GetManifestModuleMetadata(MetadataReference reference) { // make a copy to avoid disposing shared reference metadata: var metadata = ((MetadataImageReference)reference).GetMetadata(); return (metadata as AssemblyMetadata)?.GetModules()[0] ?? (ModuleMetadata)metadata; } internal static void VerifyLocal<TMethodSymbol>( this CompilationTestData testData, string typeName, LocalAndMethod localAndMethod, string expectedMethodName, string expectedLocalName, string expectedLocalDisplayName, DkmClrCompilationResultFlags expectedFlags, Action<TMethodSymbol> verifyTypeParameters, string expectedILOpt, bool expectedGeneric, string expectedValueSourcePath, int expectedValueSourceLine) where TMethodSymbol : IMethodSymbol { Assert.Equal(expectedLocalName, localAndMethod.LocalName); Assert.Equal(expectedLocalDisplayName, localAndMethod.LocalDisplayName); Assert.True(expectedMethodName.StartsWith(localAndMethod.MethodName, StringComparison.Ordinal), expectedMethodName + " does not start with " + localAndMethod.MethodName); // Expected name may include type arguments and parameters. Assert.Equal(expectedFlags, localAndMethod.Flags); var methodData = testData.GetMethodData(typeName + "." + expectedMethodName); verifyTypeParameters((TMethodSymbol)methodData.Method); if (expectedILOpt != null) { string actualIL = methodData.GetMethodIL(); AssertEx.AssertEqualToleratingWhitespaceDifferences( expectedILOpt, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine); } Assert.Equal(((Cci.IMethodDefinition)methodData.Method).CallingConvention, expectedGeneric ? Cci.CallingConvention.Generic : Cci.CallingConvention.Default); } internal static ISymUnmanagedReader ConstructSymReaderWithImports(ImmutableArray<byte> peImage, string methodName, params string[] importStrings) { using (var peReader = new PEReader(peImage)) { var metadataReader = peReader.GetMetadataReader(); var methodHandle = metadataReader.MethodDefinitions.Single(h => metadataReader.StringComparer.Equals(metadataReader.GetMethodDefinition(h).Name, methodName)); var methodToken = metadataReader.GetToken(methodHandle); return new MockSymUnmanagedReader(new Dictionary<int, MethodDebugInfoBytes> { { methodToken, new MethodDebugInfoBytes.Builder(new [] { importStrings }).Build() }, }.ToImmutableDictionary()); } } internal const uint NoILOffset = 0xffffffff; internal static readonly MetadataReference IntrinsicAssemblyReference = GetIntrinsicAssemblyReference(); internal static ImmutableArray<MetadataReference> AddIntrinsicAssembly(this ImmutableArray<MetadataReference> references) { var builder = ArrayBuilder<MetadataReference>.GetInstance(); builder.AddRange(references); builder.Add(IntrinsicAssemblyReference); return builder.ToImmutableAndFree(); } private static MetadataReference GetIntrinsicAssemblyReference() { var source = @".assembly extern mscorlib { } .class public Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods { .method public static object GetObjectAtAddress(uint64 address) { ldnull throw } .method public static class [mscorlib]System.Exception GetException() { ldnull throw } .method public static class [mscorlib]System.Exception GetStowedException() { ldnull throw } .method public static object GetReturnValue(int32 index) { ldnull throw } .method public static void CreateVariable(class [mscorlib]System.Type 'type', string name, valuetype [mscorlib]System.Guid customTypeInfoPayloadTypeId, uint8[] customTypeInfoPayload) { ldnull throw } .method public static object GetObjectByAlias(string name) { ldnull throw } .method public static !!T& GetVariableAddress<T>(string name) { ldnull throw } }"; return CommonTestBase.CompileIL(source); } /// <summary> /// Return MetadataReferences to the .winmd assemblies /// for the given namespaces. /// </summary> internal static ImmutableArray<MetadataReference> GetRuntimeWinMds(params string[] namespaces) { var paths = new HashSet<string>(); foreach (var @namespace in namespaces) { foreach (var path in WindowsRuntimeMetadata.ResolveNamespace(@namespace, null)) { paths.Add(path); } } return ImmutableArray.CreateRange(paths.Select(GetAssembly)); } private const string Version1_3CLRString = "WindowsRuntime 1.3;CLR v4.0.30319"; private const string Version1_3String = "WindowsRuntime 1.3"; private const string Version1_4String = "WindowsRuntime 1.4"; private static readonly int s_versionStringLength = Version1_3CLRString.Length; private static readonly byte[] s_version1_3CLRBytes = ToByteArray(Version1_3CLRString, s_versionStringLength); private static readonly byte[] s_version1_3Bytes = ToByteArray(Version1_3String, s_versionStringLength); private static readonly byte[] s_version1_4Bytes = ToByteArray(Version1_4String, s_versionStringLength); private static byte[] ToByteArray(string str, int length) { var bytes = new byte[length]; for (int i = 0; i < str.Length; i++) { bytes[i] = (byte)str[i]; } return bytes; } internal static byte[] ToVersion1_3(byte[] bytes) { return ToVersion(bytes, s_version1_3CLRBytes, s_version1_3Bytes); } internal static byte[] ToVersion1_4(byte[] bytes) { return ToVersion(bytes, s_version1_3CLRBytes, s_version1_4Bytes); } private static byte[] ToVersion(byte[] bytes, byte[] from, byte[] to) { int n = bytes.Length; var copy = new byte[n]; Array.Copy(bytes, copy, n); int index = IndexOf(copy, from); Array.Copy(to, 0, copy, index, to.Length); return copy; } private static int IndexOf(byte[] a, byte[] b) { int m = b.Length; int n = a.Length - m; for (int x = 0; x < n; x++) { var matches = true; for (int y = 0; y < m; y++) { if (a[x + y] != b[y]) { matches = false; break; } } if (matches) { return x; } } return -1; } private static MetadataReference GetAssembly(string path) { var bytes = File.ReadAllBytes(path); var metadata = ModuleMetadata.CreateFromImage(bytes); return metadata.GetReference(filePath: path); } internal static uint GetOffset(int methodToken, ISymUnmanagedReader symReader, int atLineNumber = -1) { int ilOffset; if (symReader == null) { ilOffset = 0; } else { var symMethod = symReader.GetMethod(methodToken); if (symMethod == null) { ilOffset = 0; } else { var sequencePoints = symMethod.GetSequencePoints(); ilOffset = atLineNumber < 0 ? sequencePoints.Where(sp => sp.StartLine != SequencePointList.HiddenSequencePointLine).Select(sp => sp.Offset).FirstOrDefault() : sequencePoints.First(sp => sp.StartLine == atLineNumber).Offset; } } Assert.InRange(ilOffset, 0, int.MaxValue); return (uint)ilOffset; } internal static string GetMethodOrTypeSignatureParts(string signature, out string[] parameterTypeNames) { var parameterListStart = signature.IndexOf('('); if (parameterListStart < 0) { parameterTypeNames = null; return signature; } var parameters = signature.Substring(parameterListStart + 1, signature.Length - parameterListStart - 2); var methodName = signature.Substring(0, parameterListStart); parameterTypeNames = (parameters.Length == 0) ? new string[0] : parameters.Split(','); return methodName; } internal unsafe static ModuleMetadata ToModuleMetadata(this PEMemoryBlock metadata, bool ignoreAssemblyRefs) { return ModuleMetadata.CreateFromMetadata( (IntPtr)metadata.Pointer, metadata.Length, includeEmbeddedInteropTypes: false, ignoreAssemblyRefs: ignoreAssemblyRefs); } internal unsafe static MetadataReader ToMetadataReader(this PEMemoryBlock metadata) { return new MetadataReader(metadata.Pointer, metadata.Length, MetadataReaderOptions.None); } internal static void EmitCorLibWithAssemblyReferences( Compilation comp, string pdbPath, Func<CommonPEModuleBuilder, CommonPEModuleBuilder> getModuleBuilder, out ImmutableArray<byte> peBytes, out ImmutableArray<byte> pdbBytes) { var diagnostics = DiagnosticBag.GetInstance(); var emitOptions = EmitOptions.Default.WithRuntimeMetadataVersion("0.0.0.0").WithDebugInformationFormat(DebugInformationFormat.PortablePdb); var moduleBuilder = comp.CheckOptionsAndCreateModuleBuilder( diagnostics, null, emitOptions, null, null, null, null, default(CancellationToken)); // Wrap the module builder in a module builder that // reports the "System.Object" type as having no base type. moduleBuilder = getModuleBuilder(moduleBuilder); bool result = comp.Compile( moduleBuilder, emittingPdb: pdbPath != null, diagnostics: diagnostics, filterOpt: null, cancellationToken: default(CancellationToken)); using (var peStream = new MemoryStream()) { using (var pdbStream = new MemoryStream()) { PeWriter.WritePeToStream( new EmitContext(moduleBuilder, null, diagnostics), comp.MessageProvider, () => peStream, () => pdbStream, null, null, allowMissingMethodBodies: true, isDeterministic: false, cancellationToken: default(CancellationToken)); peBytes = peStream.ToImmutable(); pdbBytes = pdbStream.ToImmutable(); } } diagnostics.Verify(); diagnostics.Free(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Reflection; namespace OpenSim.Data.MSSQL { public class MSSQLEstateStore : IEstateDataStore { private const string _migrationStore = "EstateStore"; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private MSSQLManager _Database; private string m_connectionString; private FieldInfo[] _Fields; private Dictionary<string, FieldInfo> _FieldMap = new Dictionary<string, FieldInfo>(); #region Public methods public MSSQLEstateStore() { } public MSSQLEstateStore(string connectionString) { Initialise(connectionString); } /// <summary> /// Initialises the estatedata class. /// </summary> /// <param name="connectionString">connectionString.</param> public void Initialise(string connectionString) { if (!string.IsNullOrEmpty(connectionString)) { m_connectionString = connectionString; _Database = new MSSQLManager(connectionString); } //Migration settings using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); Migration m = new Migration(conn, GetType().Assembly, "EstateStore"); m.Update(); } //Interesting way to get parameters! Maybe implement that also with other types Type t = typeof(EstateSettings); _Fields = t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly); foreach (FieldInfo f in _Fields) { if (f.Name.Substring(0, 2) == "m_") _FieldMap[f.Name.Substring(2)] = f; } } /// <summary> /// Loads the estate settings. /// </summary> /// <param name="regionID">region ID.</param> /// <returns></returns> public EstateSettings LoadEstateSettings(UUID regionID, bool create) { EstateSettings es = new EstateSettings(); string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_map left join estate_settings on estate_map.EstateID = estate_settings.EstateID where estate_settings.EstateID is not null and RegionID = @RegionID"; bool insertEstate = false; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@RegionID", regionID)); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { foreach (string name in FieldList) { FieldInfo f = _FieldMap[name]; object v = reader[name]; if (f.FieldType == typeof(bool)) { f.SetValue(es, Convert.ToInt32(v) != 0); } else if (f.FieldType == typeof(UUID)) { f.SetValue(es, new UUID((Guid)v)); // uuid); } else if (f.FieldType == typeof(string)) { f.SetValue(es, v.ToString()); } else if (f.FieldType == typeof(UInt32)) { f.SetValue(es, Convert.ToUInt32(v)); } else if (f.FieldType == typeof(Single)) { f.SetValue(es, Convert.ToSingle(v)); } else f.SetValue(es, v); } } else { insertEstate = true; } } } if (insertEstate && create) { DoCreate(es); LinkRegion(regionID, (int)es.EstateID); } LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); //Set event es.OnSave += StoreEstateSettings; return es; } public EstateSettings CreateNewEstate() { EstateSettings es = new EstateSettings(); es.OnSave += StoreEstateSettings; DoCreate(es); LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); return es; } private void DoCreate(EstateSettings es) { List<string> names = new List<string>(FieldList); names.Remove("EstateID"); string sql = string.Format("insert into estate_settings ({0}) values ( @{1})", String.Join(",", names.ToArray()), String.Join(", @", names.ToArray())); //_Log.Debug("[DB ESTATE]: SQL: " + sql); using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand insertCommand = new SqlCommand(sql, conn)) { insertCommand.CommandText = sql + " SET @ID = SCOPE_IDENTITY()"; foreach (string name in names) { insertCommand.Parameters.Add(_Database.CreateParameter("@" + name, _FieldMap[name].GetValue(es))); } SqlParameter idParameter = new SqlParameter("@ID", SqlDbType.Int); idParameter.Direction = ParameterDirection.Output; insertCommand.Parameters.Add(idParameter); conn.Open(); insertCommand.ExecuteNonQuery(); es.EstateID = Convert.ToUInt32(idParameter.Value); } //TODO check if this is needed?? es.Save(); } /// <summary> /// Stores the estate settings. /// </summary> /// <param name="es">estate settings</param> public void StoreEstateSettings(EstateSettings es) { List<string> names = new List<string>(FieldList); names.Remove("EstateID"); string sql = string.Format("UPDATE estate_settings SET "); foreach (string name in names) { sql += name + " = @" + name + ", "; } sql = sql.Remove(sql.LastIndexOf(",")); sql += " WHERE EstateID = @EstateID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { foreach (string name in names) { cmd.Parameters.Add(_Database.CreateParameter("@" + name, _FieldMap[name].GetValue(es))); } cmd.Parameters.Add(_Database.CreateParameter("@EstateID", es.EstateID)); conn.Open(); cmd.ExecuteNonQuery(); } SaveBanList(es); SaveUUIDList(es.EstateID, "estate_managers", es.EstateManagers); SaveUUIDList(es.EstateID, "estate_users", es.EstateAccess); SaveUUIDList(es.EstateID, "estate_groups", es.EstateGroups); } #endregion Public methods #region Private methods private string[] FieldList { get { return new List<string>(_FieldMap.Keys).ToArray(); } } private void LoadBanList(EstateSettings es) { es.ClearBans(); string sql = "select bannedUUID from estateban where EstateID = @EstateID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { SqlParameter idParameter = new SqlParameter("@EstateID", SqlDbType.Int); idParameter.Value = es.EstateID; cmd.Parameters.Add(idParameter); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { EstateBan eb = new EstateBan(); eb.BannedUserID = new UUID((Guid)reader["bannedUUID"]); //uuid; eb.BannedHostAddress = "0.0.0.0"; eb.BannedHostIPMask = "0.0.0.0"; es.AddBan(eb); } } } } private UUID[] LoadUUIDList(uint estateID, string table) { List<UUID> uuids = new List<UUID>(); string sql = string.Format("select uuid from {0} where EstateID = @EstateID", table); using (SqlConnection conn = new SqlConnection(m_connectionString)) using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.Add(_Database.CreateParameter("@EstateID", estateID)); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { uuids.Add(new UUID((Guid)reader["uuid"])); //uuid); } } } return uuids.ToArray(); } private void SaveBanList(EstateSettings es) { //Delete first using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "delete from estateban where EstateID = @EstateID"; cmd.Parameters.AddWithValue("@EstateID", (int)es.EstateID); cmd.ExecuteNonQuery(); //Insert after cmd.CommandText = "insert into estateban (EstateID, bannedUUID,bannedIp, bannedIpHostMask, bannedNameMask) values ( @EstateID, @bannedUUID, '','','' )"; cmd.Parameters.AddWithValue("@bannedUUID", Guid.Empty); foreach (EstateBan b in es.EstateBans) { cmd.Parameters["@bannedUUID"].Value = b.BannedUserID.Guid; cmd.ExecuteNonQuery(); } } } } private void SaveUUIDList(uint estateID, string table, UUID[] data) { using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.Parameters.AddWithValue("@EstateID", (int)estateID); cmd.CommandText = string.Format("delete from {0} where EstateID = @EstateID", table); cmd.ExecuteNonQuery(); cmd.CommandText = string.Format("insert into {0} (EstateID, uuid) values ( @EstateID, @uuid )", table); cmd.Parameters.AddWithValue("@uuid", Guid.Empty); foreach (UUID uuid in data) { cmd.Parameters["@uuid"].Value = uuid.Guid; //.ToString(); //TODO check if this works cmd.ExecuteNonQuery(); } } } } public EstateSettings LoadEstateSettings(int estateID) { EstateSettings es = new EstateSettings(); string sql = "select estate_settings." + String.Join(",estate_settings.", FieldList) + " from estate_settings where EstateID = @EstateID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@EstateID", (int)estateID); using (SqlDataReader reader = cmd.ExecuteReader()) { if (reader.Read()) { foreach (string name in FieldList) { FieldInfo f = _FieldMap[name]; object v = reader[name]; if (f.FieldType == typeof(bool)) { f.SetValue(es, Convert.ToInt32(v) != 0); } else if (f.FieldType == typeof(UUID)) { f.SetValue(es, new UUID((Guid)v)); // uuid); } else if (f.FieldType == typeof(string)) { f.SetValue(es, v.ToString()); } else if (f.FieldType == typeof(UInt32)) { f.SetValue(es, Convert.ToUInt32(v)); } else if (f.FieldType == typeof(Single)) { f.SetValue(es, Convert.ToSingle(v)); } else f.SetValue(es, v); } } } } } LoadBanList(es); es.EstateManagers = LoadUUIDList(es.EstateID, "estate_managers"); es.EstateAccess = LoadUUIDList(es.EstateID, "estate_users"); es.EstateGroups = LoadUUIDList(es.EstateID, "estate_groups"); //Set event es.OnSave += StoreEstateSettings; return es; } public List<EstateSettings> LoadEstateSettingsAll() { List<EstateSettings> allEstateSettings = new List<EstateSettings>(); List<int> allEstateIds = GetEstatesAll(); foreach (int estateId in allEstateIds) allEstateSettings.Add(LoadEstateSettings(estateId)); return allEstateSettings; } public List<int> GetEstates(string search) { List<int> result = new List<int>(); string sql = "select estateID from estate_settings where EstateName = @EstateName"; using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@EstateName", search); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } } return result; } public List<int> GetEstatesAll() { List<int> result = new List<int>(); string sql = "select estateID from estate_settings"; using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } } return result; } public List<int> GetEstatesByOwner(UUID ownerID) { List<int> result = new List<int>(); string sql = "select estateID from estate_settings where EstateOwner = @EstateOwner"; using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@EstateOwner", ownerID); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(Convert.ToInt32(reader["EstateID"])); } reader.Close(); } } } return result; } public bool LinkRegion(UUID regionID, int estateID) { string deleteSQL = "delete from estate_map where RegionID = @RegionID"; string insertSQL = "insert into estate_map values (@RegionID, @EstateID)"; using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); SqlTransaction transaction = conn.BeginTransaction(); try { using (SqlCommand cmd = new SqlCommand(deleteSQL, conn)) { cmd.Transaction = transaction; cmd.Parameters.AddWithValue("@RegionID", regionID.Guid); cmd.ExecuteNonQuery(); } using (SqlCommand cmd = new SqlCommand(insertSQL, conn)) { cmd.Transaction = transaction; cmd.Parameters.AddWithValue("@RegionID", regionID.Guid); cmd.Parameters.AddWithValue("@EstateID", estateID); int ret = cmd.ExecuteNonQuery(); if (ret != 0) transaction.Commit(); else transaction.Rollback(); return (ret != 0); } } catch (Exception ex) { m_log.Error("[REGION DB]: LinkRegion failed: " + ex.Message); transaction.Rollback(); } } return false; } public List<UUID> GetRegions(int estateID) { List<UUID> result = new List<UUID>(); string sql = "select RegionID from estate_map where EstateID = @EstateID"; using (SqlConnection conn = new SqlConnection(m_connectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@EstateID", estateID); using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { result.Add(DBGuid.FromDB(reader["RegionID"])); } reader.Close(); } } } return result; } public bool DeleteEstate(int estateID) { // TODO: Implementation! return false; } #endregion Private methods } }
using System; using System.Net.Sockets; using System.IO; using System.Threading.Tasks; using System.Net; namespace Remact.Net.TcpStream { using System.Threading; /// <summary> /// TcpStreamChannel is used for incoming and outgoing message streams on client as well as on service side. /// The streams are optimized for serialization performance. /// Data is transferred using SocketAsyncEventArgs. Buffers are reused. /// The largest outgoing message defines the memory used for the output buffer. /// Incoming messages use a buffer of fixed size. Larger incoming messages use a threadpool thread to deserialize the message. /// </summary> public class TcpStreamChannel : IDisposable { private Action<TcpStreamChannel> _onDataReceivedAction; private Action<TcpStreamChannel> _onChannelDisconnectedAction; private int _bufferSize; protected SocketAsyncEventArgs _receiveEventArgs; // used for connecting also private TcpStreamIncoming _tcpStreamIncoming; private bool _userReadsMessage; private SocketAsyncEventArgs _sendEventArgs; private TcpStreamOutgoing _tcpStreamOutgoing; /// <summary> /// Gets the underlying local socket for the connection between client and service. /// </summary> public Socket ClientSocket { get; private set; } /// <summary> /// Creates a buffered TCP stream. /// </summary> /// <param name="socket">The socket.</param> public TcpStreamChannel(Socket clientSocket) { if (clientSocket == null) { throw new ArgumentNullException("clientSocket"); } ClientSocket = clientSocket; if (clientSocket.Connected) { RemoteEndPoint = clientSocket.RemoteEndPoint; } _receiveEventArgs = new SocketAsyncEventArgs(); } /// <summary> /// Starts read/write communication on the underlaying, connected socket. /// Start must be called after a TcpStreamService has fired the onClientAccepted callback. /// </summary> /// <param name="onDataReceived">The action is called back (on a threadpool thread), when a message start is received.</param> /// <param name="onChannelDisconnected">The action is called back (on a threadpool thread), when the channel is disconnected from remote. May be null.</param> /// <param name="bufferSize">Defines size of the receive buffer and minimum size of the send buffer. Default = 1500 bytes (one ethernet frame).</param> public void Start(Action<TcpStreamChannel> onDataReceived, Action<TcpStreamChannel> onChannelDisconnected = null, int bufferSize=1500) { if (onDataReceived == null) { throw new ArgumentNullException("onDataReceived"); } if (_disposed || !ClientSocket.Connected) { DisposeSocket(ClientSocket); throw new SocketException((int)SocketError.NotConnected); } if (_onDataReceivedAction != null) { throw new InvalidOperationException("already started"); } _onDataReceivedAction = onDataReceived; _onChannelDisconnectedAction = onChannelDisconnected; _bufferSize = bufferSize; _receiveEventArgs.SetBuffer(new byte[_bufferSize], 0, _bufferSize); _receiveEventArgs.Completed += OnDataReceived; _tcpStreamIncoming = new TcpStreamIncoming(StartAsyncRead, ()=> ClientSocket.Available); _userReadsMessage = false; _sendEventArgs = new SocketAsyncEventArgs(); _sendEventArgs.Completed += OnDataSent; _tcpStreamOutgoing = new TcpStreamOutgoing(SendAsync, _bufferSize); if (!StartAsyncRead() && LatestException != null) { throw LatestException; } } /// <summary> /// A stream to deserialize incoming messages. Use it when your onDataReceived method is called back. /// </summary> public Stream InputStream { get {return _tcpStreamIncoming; }} /// <summary> /// A stream to serialize outgoing messages. Call FlushAsync() to write the message buffer to the network. /// </summary> public TcpStreamOutgoing OutputStream { get { return _tcpStreamOutgoing; } } /// <summary> /// Returns true, when the socket is connected. False otherwise. /// </summary> public bool IsConnected { get { return !_disposed && ClientSocket.Connected; } } /// <summary> /// The latest exception. Is null as long as client socket is connected. /// </summary>/ public Exception LatestException { get; internal set; } /// <summary> /// The remote endpoint address or null, when unknown. /// </summary> public EndPoint RemoteEndPoint { get; protected set; } /// <summary> /// The UserContext object may be used to provide context information in onDataReceived and onChannelDisconnected callback handlers. /// These handlers run on a threadpool thread. Therefore, only threadsafe members of the context may be accessed. /// The UserContext remains untouched by the library. /// </summary> public object UserContext { get; set; } // Starts the ReceiveEventArgs for next incoming data on server- or client side. Does not block. // Returns false, when socket is closed. // Examples: http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs%28v=vs.110%29.aspx // http://www.codeproject.com/Articles/22918/How-To-Use-the-SocketAsyncEventArgs-Class // http://netrsc.blogspot.ch/2010/05/async-socket-server-sample-in-c.html private bool StartAsyncRead() { try { if (!_disposed) { // when data arrives asynchronous, fill it into the buffer (see SetBuffer) and call OnDataReceived: if (!ClientSocket.ReceiveAsync(_receiveEventArgs)) { OnDataReceived(null, _receiveEventArgs); // data received synchronous } return true; } } catch (Exception ex) { OnSurpriseDisconnect(ex, null); } return false; } // OnDataReceived is asynchronously called on a threadpool thread. Sending is on another thread. // Only one ReceiveEventArgs exist for one stream. Therefore, no concurrency while receiving. private void OnDataReceived(object sender, SocketAsyncEventArgs e) { try { do { int receivedBytes = e.BytesTransferred; if (e.SocketError != SocketError.Success) { OnSurpriseDisconnect(new IOException("socket error (" + e.SocketError.ToString() + ") when receiving from " + RemoteEndPoint), null); return; } if (receivedBytes <= 0) { OnSurpriseDisconnect(new IOException("socket closed when receiving from " + RemoteEndPoint), null); return; } if (_userReadsMessage) { // Free the threadpool thread that is reading the message (on another thread). // When even more data must be read, StartAsyncRead is called again by _tcpStreamIncoming. _tcpStreamIncoming.DataReceived(e.Buffer, e.BytesTransferred, true); return; } // set up the stream with the first bytes of a new message _tcpStreamIncoming.DataReceived(e.Buffer, e.BytesTransferred, false); // Signal the user about an incoming message. // This threadpool thread will deserialize the message using _tcpStreamIncoming. // It may block, when more data must be awaited. _userReadsMessage = true; _onDataReceivedAction(this); _userReadsMessage = false; } while (!_disposed && !ClientSocket.ReceiveAsync(e)); // returns false, when new data has been received synchronously } catch (Exception ex) { OnSurpriseDisconnect(ex, null); } } // called from _tcpStreamOutgoing on user actor worker thread, when message has been serialized into buffer. private Task SendAsync(byte[] messageBuffer, int count, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<bool>(); // TODO cancellaton, SeekOrigin http://stackoverflow.com/questions/23618634/how-do-you-catch-cancellationtoken-register-callback-exceptions try { if (!_disposed) { _sendEventArgs.SetBuffer(messageBuffer, 0, count); _sendEventArgs.UserToken = tcs; // when data is sent, set _tcpStreamOutgoing.Position to 0: if (!ClientSocket.SendAsync(_sendEventArgs)) { OnDataSent(null, _sendEventArgs); } } else { tcs.TrySetCanceled(); } } catch (Exception ex) { OnSurpriseDisconnect(ex, tcs); } return tcs.Task; } // asynchronously called on a threadpool thread: private void OnDataSent(object sender, SocketAsyncEventArgs e) { if (_disposed) { return; } var tcs = (TaskCompletionSource<bool>)e.UserToken; try { if (e.SocketError != SocketError.Success) { OnSurpriseDisconnect(new IOException("socket error (" + e.SocketError.ToString() + ") when sending to " + RemoteEndPoint), tcs); } else if (e.BytesTransferred == 0 || e.BytesTransferred != e.Count) { OnSurpriseDisconnect(new IOException("socket closed. " + e.BytesTransferred + " of " + e.Count + " bytes sent to " + RemoteEndPoint), tcs); } else { int currentCount = (int)_tcpStreamOutgoing.Position; _tcpStreamOutgoing.Position = 0; if (e.Count == currentCount) { tcs.TrySetResult(true); } else { tcs.TrySetException(new InvalidOperationException("changed stream position from "+ e.Count + " to "+ currentCount + " when asynchronously sending to " + RemoteEndPoint)); } } } catch (Exception ex) { OnSurpriseDisconnect(ex, tcs); } } private void OnSurpriseDisconnect(Exception exception, TaskCompletionSource<bool> tcs) { if (!_disposed) { Dispose(); LatestException = exception; if (tcs != null) { tcs.TrySetException(exception); } } if (_onChannelDisconnectedAction != null) { var callback = _onChannelDisconnectedAction; _onChannelDisconnectedAction = null; callback(this); } } #region IDisposable private bool _disposed; /// <summary> /// Shuts down the underlying socket. Disposes all reserved resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { _userReadsMessage = false; if (disposing && !_disposed) { _disposed = true; if (ClientSocket != null) { if (ClientSocket.Connected) { try { ClientSocket.Shutdown(SocketShutdown.Both); } catch (Exception shutdownException) { LatestException = shutdownException; } } try { DisposeSocket(ClientSocket); } catch (Exception closeException) { LatestException = closeException; } ClientSocket = null; } if (_receiveEventArgs != null) { _receiveEventArgs.Dispose(); } if (_sendEventArgs != null) { _sendEventArgs.Dispose(); } if (_tcpStreamIncoming != null) { _tcpStreamIncoming.Dispose(); _tcpStreamIncoming = null; } if (_tcpStreamOutgoing != null) { _tcpStreamOutgoing.Dispose(); _tcpStreamOutgoing = null; } } } internal static void DisposeSocket(Socket socket) { #if (!NET35) socket.Dispose(); #else socket.Close(); #endif } #endregion } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using org.swyn.foundation.utils; namespace tdbadmin { /// <summary> /// Summary description for Country. /// </summary> public class FGrp : System.Windows.Forms.Form { private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox TDB_abgrp; private System.Windows.Forms.Button TDB_ab_clr; private System.Windows.Forms.Button TDB_ab_sel; private System.Windows.Forms.Button TDB_ab_exit; private System.Windows.Forms.Button TDB_ab_del; private System.Windows.Forms.Button TDB_ab_upd; private System.Windows.Forms.Button TDB_ab_ins; private System.Windows.Forms.Label tdb_e_id; private System.Windows.Forms.TextBox tdb_e_bez; private System.Windows.Forms.TextBox tdb_e_code; private System.Windows.Forms.TextBox tdb_e_text; private System.Windows.Forms.Label tdb_l_text; private System.Windows.Forms.Label tdb_l_code; private System.Windows.Forms.Label tdb_l_bez; private System.Windows.Forms.Label tdb_l_id; private tdbgui.GUIgrpt GT; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public FGrp() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // GT = new tdbgui.GUIgrpt(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.groupBox1 = new System.Windows.Forms.GroupBox(); this.tdb_e_id = new System.Windows.Forms.Label(); this.tdb_e_bez = new System.Windows.Forms.TextBox(); this.tdb_e_code = new System.Windows.Forms.TextBox(); this.tdb_e_text = new System.Windows.Forms.TextBox(); this.tdb_l_text = new System.Windows.Forms.Label(); this.tdb_l_code = new System.Windows.Forms.Label(); this.tdb_l_bez = new System.Windows.Forms.Label(); this.tdb_l_id = new System.Windows.Forms.Label(); this.TDB_abgrp = new System.Windows.Forms.GroupBox(); this.TDB_ab_clr = new System.Windows.Forms.Button(); this.TDB_ab_sel = new System.Windows.Forms.Button(); this.TDB_ab_exit = new System.Windows.Forms.Button(); this.TDB_ab_del = new System.Windows.Forms.Button(); this.TDB_ab_upd = new System.Windows.Forms.Button(); this.TDB_ab_ins = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.TDB_abgrp.SuspendLayout(); this.SuspendLayout(); // // groupBox1 // this.groupBox1.Controls.Add(this.tdb_e_id); this.groupBox1.Controls.Add(this.tdb_e_bez); this.groupBox1.Controls.Add(this.tdb_e_code); this.groupBox1.Controls.Add(this.tdb_e_text); this.groupBox1.Controls.Add(this.tdb_l_text); this.groupBox1.Controls.Add(this.tdb_l_code); this.groupBox1.Controls.Add(this.tdb_l_bez); this.groupBox1.Controls.Add(this.tdb_l_id); this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.groupBox1.Location = new System.Drawing.Point(0, 0); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(608, 245); this.groupBox1.TabIndex = 13; this.groupBox1.TabStop = false; this.groupBox1.Text = "Description"; // // tdb_e_id // this.tdb_e_id.Location = new System.Drawing.Point(136, 24); this.tdb_e_id.Name = "tdb_e_id"; this.tdb_e_id.Size = new System.Drawing.Size(64, 16); this.tdb_e_id.TabIndex = 9; // // tdb_e_bez // this.tdb_e_bez.Location = new System.Drawing.Point(136, 40); this.tdb_e_bez.Name = "tdb_e_bez"; this.tdb_e_bez.Size = new System.Drawing.Size(456, 20); this.tdb_e_bez.TabIndex = 0; this.tdb_e_bez.Text = ""; // // tdb_e_code // this.tdb_e_code.Location = new System.Drawing.Point(136, 64); this.tdb_e_code.Name = "tdb_e_code"; this.tdb_e_code.Size = new System.Drawing.Size(456, 20); this.tdb_e_code.TabIndex = 1; this.tdb_e_code.Text = ""; // // tdb_e_text // this.tdb_e_text.Location = new System.Drawing.Point(136, 88); this.tdb_e_text.Multiline = true; this.tdb_e_text.Name = "tdb_e_text"; this.tdb_e_text.Size = new System.Drawing.Size(456, 88); this.tdb_e_text.TabIndex = 2; this.tdb_e_text.Text = ""; // // tdb_l_text // this.tdb_l_text.Location = new System.Drawing.Point(8, 121); this.tdb_l_text.Name = "tdb_l_text"; this.tdb_l_text.RightToLeft = System.Windows.Forms.RightToLeft.No; this.tdb_l_text.TabIndex = 4; this.tdb_l_text.Text = "Description"; // // tdb_l_code // this.tdb_l_code.Location = new System.Drawing.Point(8, 63); this.tdb_l_code.Name = "tdb_l_code"; this.tdb_l_code.TabIndex = 3; this.tdb_l_code.Text = "Code"; // // tdb_l_bez // this.tdb_l_bez.Location = new System.Drawing.Point(8, 39); this.tdb_l_bez.Name = "tdb_l_bez"; this.tdb_l_bez.TabIndex = 2; this.tdb_l_bez.Text = "Title"; // // tdb_l_id // this.tdb_l_id.Location = new System.Drawing.Point(8, 21); this.tdb_l_id.Name = "tdb_l_id"; this.tdb_l_id.TabIndex = 1; this.tdb_l_id.Text = "ID"; // // TDB_abgrp // this.TDB_abgrp.Controls.Add(this.TDB_ab_clr); this.TDB_abgrp.Controls.Add(this.TDB_ab_sel); this.TDB_abgrp.Controls.Add(this.TDB_ab_exit); this.TDB_abgrp.Controls.Add(this.TDB_ab_del); this.TDB_abgrp.Controls.Add(this.TDB_ab_upd); this.TDB_abgrp.Controls.Add(this.TDB_ab_ins); this.TDB_abgrp.Dock = System.Windows.Forms.DockStyle.Bottom; this.TDB_abgrp.Location = new System.Drawing.Point(0, 192); this.TDB_abgrp.Name = "TDB_abgrp"; this.TDB_abgrp.Size = new System.Drawing.Size(608, 53); this.TDB_abgrp.TabIndex = 15; this.TDB_abgrp.TabStop = false; this.TDB_abgrp.Text = "Actions"; // // TDB_ab_clr // this.TDB_ab_clr.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_clr.Location = new System.Drawing.Point(455, 16); this.TDB_ab_clr.Name = "TDB_ab_clr"; this.TDB_ab_clr.Size = new System.Drawing.Size(75, 34); this.TDB_ab_clr.TabIndex = 10; this.TDB_ab_clr.Text = "Clear"; this.TDB_ab_clr.Click += new System.EventHandler(this.TDB_ab_clr_Click); // // TDB_ab_sel // this.TDB_ab_sel.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(192)), ((System.Byte)(255))); this.TDB_ab_sel.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_sel.Location = new System.Drawing.Point(228, 16); this.TDB_ab_sel.Name = "TDB_ab_sel"; this.TDB_ab_sel.Size = new System.Drawing.Size(80, 34); this.TDB_ab_sel.TabIndex = 8; this.TDB_ab_sel.Text = "Select"; this.TDB_ab_sel.Click += new System.EventHandler(this.TDB_ab_sel_Click); // // TDB_ab_exit // this.TDB_ab_exit.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(0)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_exit.Dock = System.Windows.Forms.DockStyle.Right; this.TDB_ab_exit.Location = new System.Drawing.Point(530, 16); this.TDB_ab_exit.Name = "TDB_ab_exit"; this.TDB_ab_exit.Size = new System.Drawing.Size(75, 34); this.TDB_ab_exit.TabIndex = 9; this.TDB_ab_exit.Text = "Exit"; this.TDB_ab_exit.Click += new System.EventHandler(this.TDB_ab_exit_Click); // // TDB_ab_del // this.TDB_ab_del.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_del.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_del.Location = new System.Drawing.Point(153, 16); this.TDB_ab_del.Name = "TDB_ab_del"; this.TDB_ab_del.Size = new System.Drawing.Size(75, 34); this.TDB_ab_del.TabIndex = 7; this.TDB_ab_del.Text = "Delete"; this.TDB_ab_del.Click += new System.EventHandler(this.TDB_ab_del_Click); // // TDB_ab_upd // this.TDB_ab_upd.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_upd.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_upd.Location = new System.Drawing.Point(78, 16); this.TDB_ab_upd.Name = "TDB_ab_upd"; this.TDB_ab_upd.Size = new System.Drawing.Size(75, 34); this.TDB_ab_upd.TabIndex = 6; this.TDB_ab_upd.Text = "Update"; this.TDB_ab_upd.Click += new System.EventHandler(this.TDB_ab_upd_Click); // // TDB_ab_ins // this.TDB_ab_ins.BackColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(192)), ((System.Byte)(192))); this.TDB_ab_ins.Dock = System.Windows.Forms.DockStyle.Left; this.TDB_ab_ins.Location = new System.Drawing.Point(3, 16); this.TDB_ab_ins.Name = "TDB_ab_ins"; this.TDB_ab_ins.Size = new System.Drawing.Size(75, 34); this.TDB_ab_ins.TabIndex = 5; this.TDB_ab_ins.Text = "Insert"; this.TDB_ab_ins.Click += new System.EventHandler(this.TDB_ab_ins_Click); // // FGrp // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(608, 245); this.Controls.Add(this.TDB_abgrp); this.Controls.Add(this.groupBox1); this.Name = "FGrp"; this.Text = "Group"; this.groupBox1.ResumeLayout(false); this.TDB_abgrp.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Form callbacks private void TDB_ab_sel_Click(object sender, System.EventArgs e) { SelForm Fsel = new SelForm(); GT.Sel(Fsel.GetLV); Fsel.Accept += new EventHandler(TDB_ab_sel_Click_Return); Fsel.ShowDialog(this); } void TDB_ab_sel_Click_Return(object sender, EventArgs e) { int id = -1, rows = 0; SelForm Fsel = (SelForm)sender; id = Fsel.GetID; GT.Get(id, ref rows); tdb_e_id.Text = GT.ObjId.ToString(); tdb_e_bez.Text = GT.ObjBez; tdb_e_code.Text = GT.ObjCode; tdb_e_text.Text = GT.ObjText; } private void TDB_ab_exit_Click(object sender, System.EventArgs e) { Close(); } private void TDB_ab_ins_Click(object sender, System.EventArgs e) { GT.InsUpd(true, tdb_e_bez.Text, tdb_e_code.Text, tdb_e_text.Text); tdb_e_id.Text = GT.ObjId.ToString(); } private void TDB_ab_upd_Click(object sender, System.EventArgs e) { GT.InsUpd(false, tdb_e_bez.Text, tdb_e_code.Text, tdb_e_text.Text); } private void TDB_ab_del_Click(object sender, System.EventArgs e) { int rows = 0; GT.Get(Convert.ToInt32(tdb_e_id.Text), ref rows); GT.Delete(); } private void TDB_ab_clr_Click(object sender, System.EventArgs e) { tdb_e_id.Text = ""; tdb_e_bez.Text = ""; tdb_e_code.Text = ""; tdb_e_text.Text = ""; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using SampSharp.GameMode.Definitions; namespace SampSharp.GameMode.Display { public class TablistDialog : Dialog, IList<IEnumerable<string>> { private readonly int _columnCount; private readonly string[] _columns; private readonly List<string> _rows = new List<string>(); /// <summary> /// Initializes a new instance of the Dialog class. /// </summary> /// <param name="caption"> /// The title at the top of the dialog. The length of the caption can not exceed more than 64 /// characters before it starts to cut off. /// </param> /// <param name="columnCount">The column count.</param> /// <param name="button1">The text on the left button.</param> /// <param name="button2">The text on the right button. Leave it blank to hide it.</param> public TablistDialog(string caption, int columnCount, string button1, string button2 = null) : base(DialogStyle.Tablist, caption, string.Empty, button1, button2) { _columnCount = columnCount; } /// <summary> /// Initializes a new instance of the Dialog class. /// </summary> /// <param name="caption"> /// The title at the top of the dialog. The length of the caption can not exceed more than 64 /// characters before it starts to cut off. /// </param> /// <param name="columns">The columns.</param> /// <param name="button1">The text on the left button.</param> /// <param name="button2">The text on the right button. Leave it blank to hide it.</param> public TablistDialog(string caption, IEnumerable<string> columns, string button1, string button2 = null) : base(DialogStyle.TablistHeaders, caption, string.Empty, button1, button2) { if (columns == null) throw new ArgumentNullException("columns"); _columns = columns.ToArray(); _columnCount = _columns.Length; } #region Overrides of Dialog /// <summary> /// Gets the message displayed. /// </summary> public override string Message { get { return (_columns == null ? string.Empty : string.Join("\t", _columns) + "\n") + string.Join("\n", _rows.Select(r => r ?? string.Empty)); } } #endregion #region Implementation of IEnumerable /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1" /> that can be used to iterate through the collection. /// </returns> public IEnumerator<IEnumerable<string>> GetEnumerator() { return _rows.Select(row => row.Split('\t')).Cast<IEnumerable<string>>().GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Implementation of ICollection<IEnumerable<string>> /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1" /> is /// read-only. /// </exception> public void Add(IEnumerable<string> item) { if (item == null) { _rows.Add(null); return; } var row = item.ToArray(); if (row.Length != _columnCount) throw new ArgumentException(string.Format("Row must contain {0} cells.", _columnCount), "item"); if (row.Any(cell => cell.Contains('\t'))) throw new ArgumentException("No cell can contain a TAB character.", "item"); _rows.Add(string.Join("\n", row)); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1" /> is /// read-only. /// </exception> public void Clear() { _rows.Clear(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1" /> contains a specific value. /// </summary> /// <returns> /// true if <paramref name="item" /> is found in the <see cref="T:System.Collections.Generic.ICollection`1" />; /// otherwise, false. /// </returns> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> public bool Contains(IEnumerable<string> item) { if (item == null) throw new ArgumentNullException("item"); return _rows.Contains(string.Join("\t", item)); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1" /> to an /// <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied /// from <see cref="T:System.Collections.Generic.ICollection`1" />. The <see cref="T:System.Array" /> must have /// zero-based indexing. /// </param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="array" /> is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex" /> is less than 0.</exception> /// <exception cref="T:System.ArgumentException"> /// The number of elements in the source /// <see cref="T:System.Collections.Generic.ICollection`1" /> is greater than the available space from /// <paramref name="arrayIndex" /> to the end of the destination <paramref name="array" />. /// </exception> public void CopyTo(IEnumerable<string>[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException("array"); if (arrayIndex < 0) throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, "arrayIndex is less than 0."); if (array.Length < arrayIndex + _rows.Count) throw new ArgumentException( "The number of elements in the collection is greater than the available space from arrayIndex to the end of the destination array.", "array"); for (var i = 0; i < _rows.Count; i++) array[i + arrayIndex] = _rows[i].Split('\t'); } /// <summary> /// Removes the first occurrence of a specific object from the /// <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <returns> /// true if <paramref name="item" /> was successfully removed from the /// <see cref="T:System.Collections.Generic.ICollection`1" />; otherwise, false. This method also returns false if /// <paramref name="item" /> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1" />. /// </returns> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1" />.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1" /> is /// read-only. /// </exception> public bool Remove(IEnumerable<string> item) { if (item == null) throw new ArgumentNullException("item"); return _rows.Remove(string.Join("\t", item)); } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </summary> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1" />. /// </returns> public int Count { get { return _rows.Count; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.ICollection`1" /> is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get { return false; } } #endregion #region Implementation of IList<IEnumerable<string>> /// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1" />. /// </summary> /// <returns> /// The index of <paramref name="item" /> if found in the list; otherwise, -1. /// </returns> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1" />.</param> public int IndexOf(IEnumerable<string> item) { if (item == null) throw new ArgumentNullException("item"); return _rows.IndexOf(string.Join("\t", item)); } /// <summary> /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1" /> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item" /> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1" />.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> is not a valid index in the /// <see cref="T:System.Collections.Generic.IList`1" />. /// </exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1" /> is read-only.</exception> public void Insert(int index, IEnumerable<string> item) { if (item == null) throw new ArgumentNullException("item"); _rows.Insert(index, string.Join("\t", item)); } /// <summary> /// Removes the <see cref="T:System.Collections.Generic.IList`1" /> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> is not a valid index in the /// <see cref="T:System.Collections.Generic.IList`1" />. /// </exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IList`1" /> is read-only.</exception> public void RemoveAt(int index) { _rows.RemoveAt(index); } /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <returns> /// The element at the specified index. /// </returns> /// <param name="index">The zero-based index of the element to get or set.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index" /> is not a valid index in the /// <see cref="T:System.Collections.Generic.IList`1" />. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The property is set and the /// <see cref="T:System.Collections.Generic.IList`1" /> is read-only. /// </exception> public IEnumerable<string> this[int index] { get { return _rows[index].Split('\t'); } set { var row = value.ToArray(); if (row.Length != _columnCount) throw new ArgumentException(string.Format("Row must contain {0} cells.", _columnCount), "item"); if (row.Any(cell => cell.Contains('\t'))) throw new ArgumentException("No cell can contain a TAB character.", "item"); _rows[index] = string.Join("\t", row); } } #endregion } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; using CrystalDecisions.Shared; namespace WebApplication2 { /// <summary> /// Summary description for frmEmergencyProcedures. /// </summary> public partial class frmProfiles : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here Load_Profiles(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.processCommand); this.DataGrid1.EditCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand); this.DataGrid1.UpdateCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_UpdateCommand); this.DataGrid1.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.Delete); } #endregion private void Load_Profiles() { if (Session["startForm"].ToString() == "frmMainControl") { DataGrid1.Columns[8].Visible = false; if (Session["ProfileType"].ToString() == "Producer") { lblContent2.Text = "Click on the button 'Update' to appoint a manager for the given profile."; } else if (Session["ProfileType"].ToString() == "Consumer") { DataGrid1.Columns[5].Visible = false; DataGrid1.Columns[6].Visible = false; } } else if (Session["startForm"].ToString() == "frmMainProfileMgr") { btnAdd.Visible = false; btnStartS.Visible = false; DataGrid1.Columns[4].Visible = false; DataGrid1.Columns[8].Visible = false; DataGrid1.Columns[11].Visible = false; if (Session["ProfileType"].ToString() == "Producer") { lblTitle.Text = "Business Models"; lblTitle1.Text = "Model Designer: " + Session["FName"].ToString() + " " + Session["Lname"].ToString(); lblContent1.Text = "Listed below are the business models for which you are the designated author." + " Click on the button 'Services Provided' to the right of the appropriate business profile" + " to review and edit the profile as needed."; DataGrid1.Columns[1].HeaderText = "Business Models"; } else if (Session["ProfileType"].ToString() == "Consumer") { lblTitle1.Text = "Household Characteristics"; DataGrid1.Columns[8].Visible = false; DataGrid1.Columns[1].HeaderText = "Characteristics"; lblContent1.Text = "Click on 'Select' for the appropriate characteristic to continue"; } } if (!IsPostBack) { loadData(); } } private void loadData() { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.Text; if (Session["CProfiles"].ToString() == "frmMainControl") { cmd.CommandText = "Select Id, Name, Description, Visibility," + " PeopleId, Status, Seq From Profiles" + " Where Type=" + "'" + Session["ProfileType"].ToString() + "'" + " Order by Seq, Name"; } else if (Session["CProfiles"].ToString() == "frmMainProfileMgr") { { cmd.CommandText = "Select Id, Name, Description, Visibility," + " PeopleId, Status, Seq From Profiles" + " Where Type=" + "'" + Session["ProfileType"].ToString() + "'" + " and PeopleId =" + "'" + Session["PeopleId"].ToString() + "'" + " Order by Seq, Name"; } } else { cmd.CommandText = "Select Id, Name, Description, Visibility," + " PeopleId, Status, Seq From Profiles" + " Where Type = " + "'Consumer'" + " Order by Seq, Name"; } cmd.Connection=this.epsDbConn; DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"Profiles"); if (ds.Tables["Profiles"].Rows.Count == 0) { if (Session["startForm"].ToString() == "frmMainProfileMgr") { DataGrid1.Visible = false; lblContent1.Text = "Sorry. You have not been designated to author any " + Session["ProfileType"].ToString() + " Profiles. Please contact your system administrator."; } } Session["ds"]=ds; DataGrid1.DataSource=ds; DataGrid1.DataBind(); refreshGrid(); } private void refreshGrid() { foreach (DataGridItem i in DataGrid1.Items) { Button bt = (Button) (i.Cells[5].FindControl ("btnServices")); TextBox tb = (TextBox)(i.Cells[10].FindControl("txtSeq")); if (Session["ProfileType"].ToString() == "Producer") { bt.Text="Services Provided"; } else { bt.Text="Select"; } if (Session["startForm"].ToString() == "frmMainControl") { if (i.Cells[9].Text == "&nbsp;") { tb.Text = "99"; } else tb.Text = i.Cells[9].Text; } } } private void updateGrid1() { foreach (DataGridItem i in DataGrid1.Items) { TextBox tb = (TextBox)(i.Cells[10].FindControl("txtSeq")); { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "wms_UpdateProfileSeqNo"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = i.Cells[0].Text; cmd.Parameters.Add("@Seq", SqlDbType.Int); cmd.Parameters["@Seq"].Value = Int32.Parse(tb.Text); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } protected void btnAdd_Click(object sender, System.EventArgs e) { if (Session["startForm"].ToString() == "frmMainControl") { updateGrid1(); } Response.Redirect (strURL + "frmUpdProfiles.aspx?" + "&btnAction=" + "Add"); } private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { Response.Redirect (strURL + "frmUpdProfiles.aspx?" + "&btnAction=" + "Update" + "&Id=" + e.Item.Cells[0].Text + "&Name=" + e.Item.Cells[1].Text + "&Desc=" + e.Item.Cells[2].Text + "&Vis=" + e.Item.Cells[3].Text + "&PeopleId=" + e.Item.Cells[6].Text + "&Households=" + e.Item.Cells[7].Text + "&Status=" + e.Item.Cells[8].Text); } private void processCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { /*if (e.CommandName == "Events") { Session["CallerEvents"]="frmProfiles"; Response.Redirect(strURL + "frmEvents.aspx?"); } else */ if (e.CommandName == "Services") { if (Session["ProfileType"] == "Consumer") { Session["ProfilesId"] = e.Item.Cells[0].Text; Session["ProfilesName"] = e.Item.Cells[1].Text; Session["CServiceTypes"] = "frmProfiles"; Response.Redirect(strURL + "frmServiceTypes.aspx?"); } else { Session["CPSTypes"] = "frmProfiles"; Session["ProfilesId"] = e.Item.Cells[0].Text; Session["ProfilesName"] = e.Item.Cells[1].Text; Response.Redirect(strURL + "frmProfileServiceTypes.aspx?"); } } else if (e.CommandName == "PRT") { Session["CPPTypes"] = "frmProfiles"; Session["ProfilesId"] = e.Item.Cells[0].Text; Session["ProfilesName"] = e.Item.Cells[1].Text; Response.Redirect(strURL + "frmProfProjectTypes.aspx?"); } else if (e.CommandName == "ProjTypes") { Session["CPPTypes"] = "frmProfiles"; Session["ProfilesId"] = e.Item.Cells[0].Text; Session["ProfilesName"] = e.Item.Cells[1].Text; Response.Redirect(strURL + "frmProfProjectTypes.aspx?"); } else if (e.CommandName == "Deliverables") { Session["CSEvents"] = "frmProfiles"; Session["ProfilesId"] = e.Item.Cells[0].Text; Session["ProfileName"] = e.Item.Cells[1].Text; Response.Redirect(strURL + "frmServiceEvents.aspx?"); } else if (e.CommandName == "Processes") { Session["CProcs"] = "frmProfiles"; Session["ProfilesId"] = e.Item.Cells[0].Text; Session["ProfileName"] = e.Item.Cells[1].Text; Response.Redirect(strURL + "frmProcs.aspx?"); } } private void Delete(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_DeleteProfile"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value=Int32.Parse (e.Item.Cells[0].Text); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); loadData(); } private void rpts() { Session["cRG"] = "frmProfiles"; Response.Redirect(strURL + "frmReportGen.aspx?"); } protected void btnExit_Click(object sender, System.EventArgs e) { if (Session["startForm"].ToString() == "frmMainControl") { updateGrid1(); } Response.Redirect (strURL + Session["CProfiles"].ToString() + ".aspx?"); } protected void btnSignoff_Click(object sender, System.EventArgs e) { Response.Redirect (strURL + "frmEnd.aspx?"); } protected void btnRpt1_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "ProfileId"; discreteval.Value = Session["ProfilesId"].ToString(); paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); ParameterField paramField1 = new ParameterField(); ParameterDiscreteValue discreteval1 = new ParameterDiscreteValue(); paramField1.ParameterFieldName = "CallerOpt"; discreteval1.Value = Session["CallerOpt"].ToString(); paramField1.CurrentValues.Add(discreteval1); paramFields.Add(paramField1); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptProfileServiceProcs.rpt"; rpts(); } protected void btnRpt2_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "ProfilesId"; discreteval.Value = Session["ProfilesId"].ToString(); paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); ParameterField paramField1 = new ParameterField(); ParameterDiscreteValue discreteval1 = new ParameterDiscreteValue(); paramField1.ParameterFieldName = "CallerOpt"; discreteval1.Value = Session["CallerOpt"].ToString(); paramField1.CurrentValues.Add(discreteval1); paramFields.Add(paramField1); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptProfileProcs.rpt"; rpts(); } protected void btnRpt3_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "ProfilesId"; discreteval.Value = Session["ProfilesId"].ToString(); paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); ParameterField paramField1 = new ParameterField(); ParameterDiscreteValue discreteval1 = new ParameterDiscreteValue(); paramField1.ParameterFieldName = "CallerOpt"; discreteval1.Value = Session["CallerOpt"].ToString(); paramField1.CurrentValues.Add(discreteval1); paramFields.Add(paramField1); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptTORs.rpt"; rpts(); } protected void btnRpt4_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "ProfilesId"; discreteval.Value = Session["ProfilesId"].ToString(); paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); ParameterField paramField1 = new ParameterField(); ParameterDiscreteValue discreteval1 = new ParameterDiscreteValue(); paramField1.ParameterFieldName = "CallerOpt"; discreteval1.Value = Session["CallerOpt"].ToString(); paramField1.CurrentValues.Add(discreteval1); paramFields.Add(paramField1); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptProfResources.rpt"; rpts(); } /*protected void btnRpt5_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "ProfilesId"; discreteval.Value = Session["ProfilesId"].ToString(); paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); ParameterField paramField1 = new ParameterField(); ParameterDiscreteValue discreteval1 = new ParameterDiscreteValue(); paramField1.ParameterFieldName = "CallerOpt"; discreteval1.Value = Session["CallerOpt"].ToString(); paramField1.CurrentValues.Add(discreteval1); paramFields.Add(paramField1); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptProfClients.rpt"; rpts(); }*/ protected void btnExit1_Click(object sender, EventArgs e) { Session["CallerOpt"] = null; lblContent1.Text = "Listed below are the business models for which you are the designated author." + " Click on the button 'Services Provided' to the right of the appropriate business profile" + " to review and edit the profile as needed."; DataGrid1.Visible = true; btnExit.Visible = true; btnExit1.Visible = false; lblProfileName.Text = ""; lblReports1.Text = ""; btnRpt1.Visible = false; btnRpt2.Visible = false; btnRpt3.Visible = false; btnRpt4.Visible = false; btnRpt6.Visible = false; } protected void btnRpt6_Click(object sender, EventArgs e) { ParameterFields paramFields = new ParameterFields(); ParameterField paramField = new ParameterField(); ParameterDiscreteValue discreteval = new ParameterDiscreteValue(); paramField.ParameterFieldName = "ProfilesId"; discreteval.Value = Int32.Parse(Session["ProfilesId"].ToString()); paramField.CurrentValues.Add(discreteval); paramFields.Add(paramField); Session["ReportParameters"] = paramFields; Session["ReportName"] = "rptBIA.rpt"; rpts(); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Media.Media3D.Vector3DCollection.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Media.Media3D { sealed public partial class Vector3DCollection : System.Windows.Freezable, IFormattable, System.Collections.IList, System.Collections.ICollection, IList<Vector3D>, ICollection<Vector3D>, IEnumerable<Vector3D>, System.Collections.IEnumerable { #region Methods and constructors public void Add(Vector3D value) { } public void Clear() { } public Vector3DCollection Clone() { return default(Vector3DCollection); } protected override void CloneCore(System.Windows.Freezable source) { } public Vector3DCollection CloneCurrentValue() { return default(Vector3DCollection); } protected override void CloneCurrentValueCore(System.Windows.Freezable source) { } public bool Contains(Vector3D value) { return default(bool); } public void CopyTo(Vector3D[] array, int index) { } protected override System.Windows.Freezable CreateInstanceCore() { return default(System.Windows.Freezable); } protected override void GetAsFrozenCore(System.Windows.Freezable source) { } protected override void GetCurrentValueAsFrozenCore(System.Windows.Freezable source) { } public Vector3DCollection.Enumerator GetEnumerator() { return default(Vector3DCollection.Enumerator); } public int IndexOf(Vector3D value) { return default(int); } public void Insert(int index, Vector3D value) { } public static Vector3DCollection Parse(string source) { return default(Vector3DCollection); } public bool Remove(Vector3D value) { return default(bool); } public void RemoveAt(int index) { } IEnumerator<Vector3D> System.Collections.Generic.IEnumerable<System.Windows.Media.Media3D.Vector3D>.GetEnumerator() { return default(IEnumerator<Vector3D>); } void System.Collections.ICollection.CopyTo(Array array, int index) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } int System.Collections.IList.Add(Object value) { return default(int); } bool System.Collections.IList.Contains(Object value) { return default(bool); } int System.Collections.IList.IndexOf(Object value) { return default(int); } void System.Collections.IList.Insert(int index, Object value) { } void System.Collections.IList.Remove(Object value) { } string System.IFormattable.ToString(string format, IFormatProvider provider) { return default(string); } public string ToString(IFormatProvider provider) { return default(string); } public Vector3DCollection(IEnumerable<Vector3D> collection) { } public Vector3DCollection(int capacity) { } public Vector3DCollection() { } #endregion #region Properties and indexers public int Count { get { return default(int); } } public Vector3D this [int index] { get { return default(Vector3D); } set { } } bool System.Collections.Generic.ICollection<System.Windows.Media.Media3D.Vector3D>.IsReadOnly { get { return default(bool); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } bool System.Collections.IList.IsFixedSize { get { return default(bool); } } bool System.Collections.IList.IsReadOnly { get { return default(bool); } } Object System.Collections.IList.this [int index] { get { return default(Object); } set { } } #endregion } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using System.IO; using System.Text; namespace log4net.DateFormatter { /// <summary> /// Formats a <see cref="DateTime"/> as <c>"HH:mm:ss,fff"</c>. /// </summary> /// <remarks> /// <para> /// Formats a <see cref="DateTime"/> in the format <c>"HH:mm:ss,fff"</c> for example, <c>"15:49:37,459"</c>. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class AbsoluteTimeDateFormatter : IDateFormatter { #region Protected Instance Methods /// <summary> /// Renders the date into a string. Format is <c>"HH:mm:ss"</c>. /// </summary> /// <param name="dateToFormat">The date to render into a string.</param> /// <param name="buffer">The string builder to write to.</param> /// <remarks> /// <para> /// Subclasses should override this method to render the date /// into a string using a precision up to the second. This method /// will be called at most once per second and the result will be /// reused if it is needed again during the same second. /// </para> /// </remarks> virtual protected void FormatDateWithoutMillis(DateTime dateToFormat, StringBuilder buffer) { int hour = dateToFormat.Hour; if (hour < 10) { buffer.Append('0'); } buffer.Append(hour); buffer.Append(':'); int mins = dateToFormat.Minute; if (mins < 10) { buffer.Append('0'); } buffer.Append(mins); buffer.Append(':'); int secs = dateToFormat.Second; if (secs < 10) { buffer.Append('0'); } buffer.Append(secs); } #endregion Protected Instance Methods #region Implementation of IDateFormatter /// <summary> /// Renders the date into a string. Format is "HH:mm:ss,fff". /// </summary> /// <param name="dateToFormat">The date to render into a string.</param> /// <param name="writer">The writer to write to.</param> /// <remarks> /// <para> /// Uses the <see cref="FormatDateWithoutMillis"/> method to generate the /// time string up to the seconds and then appends the current /// milliseconds. The results from <see cref="FormatDateWithoutMillis"/> are /// cached and <see cref="FormatDateWithoutMillis"/> is called at most once /// per second. /// </para> /// <para> /// Sub classes should override <see cref="FormatDateWithoutMillis"/> /// rather than <see cref="FormatDate"/>. /// </para> /// </remarks> virtual public void FormatDate(DateTime dateToFormat, TextWriter writer) { lock (s_lastTimeStrings) { // Calculate the current time precise only to the second long currentTimeToTheSecond = (dateToFormat.Ticks - (dateToFormat.Ticks % TimeSpan.TicksPerSecond)); string timeString = null; // Compare this time with the stored last time // If we are in the same second then append // the previously calculated time string if (s_lastTimeToTheSecond != currentTimeToTheSecond) { s_lastTimeStrings.Clear(); } else { timeString = (string) s_lastTimeStrings[GetType()]; } if (timeString == null) { // lock so that only one thread can use the buffer and // update the s_lastTimeToTheSecond and s_lastTimeStrings // PERF: Try removing this lock and using a new StringBuilder each time lock(s_lastTimeBuf) { timeString = (string) s_lastTimeStrings[GetType()]; if (timeString == null) { // We are in a new second. s_lastTimeBuf.Length = 0; // Calculate the new string for this second FormatDateWithoutMillis(dateToFormat, s_lastTimeBuf); // Render the string buffer to a string timeString = s_lastTimeBuf.ToString(); #if NET_1_1 // Ensure that the above string is written into the variable NOW on all threads. // This is only required on multiprocessor machines with weak memeory models System.Threading.Thread.MemoryBarrier(); #endif // Store the time as a string (we only have to do this once per second) s_lastTimeStrings[GetType()] = timeString; s_lastTimeToTheSecond = currentTimeToTheSecond; } } } writer.Write(timeString); // Append the current millisecond info writer.Write(','); int millis = dateToFormat.Millisecond; if (millis < 100) { writer.Write('0'); } if (millis < 10) { writer.Write('0'); } writer.Write(millis); } } #endregion Implementation of IDateFormatter #region Public Static Fields /// <summary> /// String constant used to specify AbsoluteTimeDateFormat in layouts. Current value is <b>ABSOLUTE</b>. /// </summary> public const string AbsoluteTimeDateFormat = "ABSOLUTE"; /// <summary> /// String constant used to specify DateTimeDateFormat in layouts. Current value is <b>DATE</b>. /// </summary> public const string DateAndTimeDateFormat = "DATE"; /// <summary> /// String constant used to specify ISO8601DateFormat in layouts. Current value is <b>ISO8601</b>. /// </summary> public const string Iso8601TimeDateFormat = "ISO8601"; #endregion Public Static Fields #region Private Static Fields /// <summary> /// Last stored time with precision up to the second. /// </summary> private static long s_lastTimeToTheSecond = 0; /// <summary> /// Last stored time with precision up to the second, formatted /// as a string. /// </summary> private static StringBuilder s_lastTimeBuf = new StringBuilder(); /// <summary> /// Last stored time with precision up to the second, formatted /// as a string. /// </summary> private static Hashtable s_lastTimeStrings = new Hashtable(); #endregion Private Static Fields } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Linq; using System.Reactive.Linq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; namespace Avalonia.Controls { /// <summary> /// A control scrolls its content if the content is bigger than the space available. /// </summary> public class ScrollViewer : ContentControl, IScrollable { /// <summary> /// Defines the <see cref="CanScrollHorizontally"/> property. /// </summary> public static readonly StyledProperty<bool> CanScrollHorizontallyProperty = AvaloniaProperty.Register<ScrollViewer, bool>(nameof(CanScrollHorizontally), true); /// <summary> /// Defines the <see cref="Extent"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ExtentProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Extent), o => o.Extent, (o, v) => o.Extent = v); /// <summary> /// Defines the <see cref="Offset"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Vector>( nameof(Offset), o => o.Offset, (o, v) => o.Offset = v); /// <summary> /// Defines the <see cref="Viewport"/> property. /// </summary> public static readonly DirectProperty<ScrollViewer, Size> ViewportProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, Size>(nameof(Viewport), o => o.Viewport, (o, v) => o.Viewport = v); /// <summary> /// Defines the HorizontalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarMaximum), o => o.HorizontalScrollBarMaximum); /// <summary> /// Defines the HorizontalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarValue), o => o.HorizontalScrollBarValue, (o, v) => o.HorizontalScrollBarValue = v); /// <summary> /// Defines the HorizontalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> HorizontalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(HorizontalScrollBarViewportSize), o => o.HorizontalScrollBarViewportSize); /// <summary> /// Defines the <see cref="HorizontalScrollBarVisibility"/> property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(HorizontalScrollBarVisibility), ScrollBarVisibility.Auto); /// <summary> /// Defines the VerticalScrollBarMaximum property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarMaximumProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarMaximum), o => o.VerticalScrollBarMaximum); /// <summary> /// Defines the VerticalScrollBarValue property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarValueProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarValue), o => o.VerticalScrollBarValue, (o, v) => o.VerticalScrollBarValue = v); /// <summary> /// Defines the VerticalScrollBarViewportSize property. /// </summary> /// <remarks> /// There is no public C# accessor for this property as it is intended to be bound to by a /// <see cref="ScrollContentPresenter"/> in the control's template. /// </remarks> public static readonly DirectProperty<ScrollViewer, double> VerticalScrollBarViewportSizeProperty = AvaloniaProperty.RegisterDirect<ScrollViewer, double>( nameof(VerticalScrollBarViewportSize), o => o.VerticalScrollBarViewportSize); /// <summary> /// Defines the <see cref="VerticalScrollBarVisibility"/> property. /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = AvaloniaProperty.RegisterAttached<ScrollViewer, Control, ScrollBarVisibility>( nameof(VerticalScrollBarVisibility), ScrollBarVisibility.Auto); private Size _extent; private Vector _offset; private Size _viewport; /// <summary> /// Initializes static members of the <see cref="ScrollViewer"/> class. /// </summary> static ScrollViewer() { AffectsValidation(ExtentProperty, OffsetProperty); AffectsValidation(ViewportProperty, OffsetProperty); } /// <summary> /// Initializes a new instance of the <see cref="ScrollViewer"/> class. /// </summary> public ScrollViewer() { } /// <summary> /// Gets the extent of the scrollable content. /// </summary> public Size Extent { get { return _extent; } private set { if (SetAndRaise(ExtentProperty, ref _extent, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets or sets the current scroll offset. /// </summary> public Vector Offset { get { return _offset; } set { value = ValidateOffset(this, value); if (SetAndRaise(OffsetProperty, ref _offset, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets the size of the viewport on the scrollable content. /// </summary> public Size Viewport { get { return _viewport; } private set { if (SetAndRaise(ViewportProperty, ref _viewport, value)) { CalculatedPropertiesChanged(); } } } /// <summary> /// Gets a value indicating whether the content can be scrolled horizontally. /// </summary> public bool CanScrollHorizontally { get { return GetValue(CanScrollHorizontallyProperty); } set { SetValue(CanScrollHorizontallyProperty, value); } } /// <summary> /// Gets or sets the horizontal scrollbar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get { return GetValue(HorizontalScrollBarVisibilityProperty); } set { SetValue(HorizontalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets or sets the vertical scrollbar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get { return GetValue(VerticalScrollBarVisibilityProperty); } set { SetValue(VerticalScrollBarVisibilityProperty, value); } } /// <summary> /// Gets the maximum horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarMaximum { get { return Max(_extent.Width - _viewport.Width, 0); } } /// <summary> /// Gets or sets the horizontal scrollbar value. /// </summary> protected double HorizontalScrollBarValue { get { return _offset.X; } set { if (_offset.X != value) { var old = Offset.X; Offset = Offset.WithX(value); RaisePropertyChanged(HorizontalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the horizontal scrollbar viewport. /// </summary> protected double HorizontalScrollBarViewportSize { get { return Max((_viewport.Width / _extent.Width) * (_extent.Width - _viewport.Width), 0); } } /// <summary> /// Gets the maximum vertical scrollbar value. /// </summary> protected double VerticalScrollBarMaximum { get { return Max(_extent.Height - _viewport.Height, 0); } } /// <summary> /// Gets or sets the vertical scrollbar value. /// </summary> protected double VerticalScrollBarValue { get { return _offset.Y; } set { if (_offset.Y != value) { var old = Offset.Y; Offset = Offset.WithY(value); RaisePropertyChanged(VerticalScrollBarValueProperty, old, value); } } } /// <summary> /// Gets the size of the vertical scrollbar viewport. /// </summary> protected double VerticalScrollBarViewportSize { get { return Max((_viewport.Height / _extent.Height) * (_extent.Height - _viewport.Height), 0); } } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public ScrollBarVisibility GetHorizontalScrollBarVisibility(Control control) { return control.GetValue(HorizontalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the HorizontalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public void SetHorizontalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to read the value from.</param> /// <returns>The value of the property.</returns> public ScrollBarVisibility GetVerticalScrollBarVisibility(Control control) { return control.GetValue(VerticalScrollBarVisibilityProperty); } /// <summary> /// Gets the value of the VerticalScrollBarVisibility attached property. /// </summary> /// <param name="control">The control to set the value on.</param> /// <param name="value">The value of the property.</param> public void SetVerticalScrollBarVisibility(Control control, ScrollBarVisibility value) { control.SetValue(VerticalScrollBarVisibilityProperty, value); } internal static Vector CoerceOffset(Size extent, Size viewport, Vector offset) { var maxX = Math.Max(extent.Width - viewport.Width, 0); var maxY = Math.Max(extent.Height - viewport.Height, 0); return new Vector(Clamp(offset.X, 0, maxX), Clamp(offset.Y, 0, maxY)); } private static double Clamp(double value, double min, double max) { return (value < min) ? min : (value > max) ? max : value; } private static double Max(double x, double y) { var result = Math.Max(x, y); return double.IsNaN(result) ? 0 : result; } private static Vector ValidateOffset(AvaloniaObject o, Vector value) { ScrollViewer scrollViewer = o as ScrollViewer; if (scrollViewer != null) { var extent = scrollViewer.Extent; var viewport = scrollViewer.Viewport; return CoerceOffset(extent, viewport, value); } else { return value; } } private void CalculatedPropertiesChanged() { // Pass old values of 0 here because we don't have the old values at this point, // and it shouldn't matter as only the template uses these properies. RaisePropertyChanged(HorizontalScrollBarMaximumProperty, 0, HorizontalScrollBarMaximum); RaisePropertyChanged(HorizontalScrollBarValueProperty, 0, HorizontalScrollBarValue); RaisePropertyChanged(HorizontalScrollBarViewportSizeProperty, 0, HorizontalScrollBarViewportSize); RaisePropertyChanged(VerticalScrollBarMaximumProperty, 0, VerticalScrollBarMaximum); RaisePropertyChanged(VerticalScrollBarValueProperty, 0, VerticalScrollBarValue); RaisePropertyChanged(VerticalScrollBarViewportSizeProperty, 0, VerticalScrollBarViewportSize); } } }
// 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; namespace System.Linq.Expressions { /// <summary> /// Strongly-typed and parameterized exception factory. /// </summary> internal static partial class Error { /// <summary> /// ArgumentException with message like "reducible nodes must override Expression.Reduce()" /// </summary> internal static Exception ReducibleMustOverrideReduce() { return new ArgumentException(Strings.ReducibleMustOverrideReduce); } /// <summary> /// ArgumentException with message like "node cannot reduce to itself or null" /// </summary> internal static Exception MustReduceToDifferent() { return new ArgumentException(Strings.MustReduceToDifferent); } /// <summary> /// ArgumentException with message like "cannot assign from the reduced node type to the original node type" /// </summary> internal static Exception ReducedNotCompatible() { return new ArgumentException(Strings.ReducedNotCompatible); } /// <summary> /// ArgumentException with message like "Setter must have parameters." /// </summary> internal static Exception SetterHasNoParams() { return new ArgumentException(Strings.SetterHasNoParams); } /// <summary> /// ArgumentException with message like "Property cannot have a managed pointer type." /// </summary> internal static Exception PropertyCannotHaveRefType() { return new ArgumentException(Strings.PropertyCannotHaveRefType); } /// <summary> /// ArgumentException with message like "Indexing parameters of getter and setter must match." /// </summary> internal static Exception IndexesOfSetGetMustMatch() { return new ArgumentException(Strings.IndexesOfSetGetMustMatch); } /// <summary> /// ArgumentException with message like "Accessor method should not have VarArgs." /// </summary> internal static Exception AccessorsCannotHaveVarArgs() { return new ArgumentException(Strings.AccessorsCannotHaveVarArgs); } /// <summary> /// ArgumentException with message like "Accessor indexes cannot be passed ByRef." /// </summary> internal static Exception AccessorsCannotHaveByRefArgs() { return new ArgumentException(Strings.AccessorsCannotHaveByRefArgs); } /// <summary> /// ArgumentException with message like "Bounds count cannot be less than 1" /// </summary> internal static Exception BoundsCannotBeLessThanOne() { return new ArgumentException(Strings.BoundsCannotBeLessThanOne); } /// <summary> /// ArgumentException with message like "Type must not be ByRef" /// </summary> internal static Exception TypeMustNotBeByRef() { return new ArgumentException(Strings.TypeMustNotBeByRef); } /// <summary> /// ArgumentException with message like "Type must not be a pointer type" /// </summary> internal static Exception TypeMustNotBePointer() { return new ArgumentException(Strings.TypeMustNotBePointer, "type"); } /// <summary> /// ArgumentException with message like "Type doesn't have constructor with a given signature" /// </summary> internal static Exception TypeDoesNotHaveConstructorForTheSignature() { return new ArgumentException(Strings.TypeDoesNotHaveConstructorForTheSignature); } /// <summary> /// ArgumentException with message like "Setter should have void type." /// </summary> internal static Exception SetterMustBeVoid() { return new ArgumentException(Strings.SetterMustBeVoid); } /// <summary> /// ArgumentException with message like "Property type must match the value type of setter" /// </summary> internal static Exception PropertyTypeMustMatchSetter() { return new ArgumentException(Strings.PropertyTypeMustMatchSetter); } /// <summary> /// ArgumentException with message like "Both accessors must be static." /// </summary> internal static Exception BothAccessorsMustBeStatic() { return new ArgumentException(Strings.BothAccessorsMustBeStatic); } /// <summary> /// ArgumentException with message like "Static method requires null instance, non-static method requires non-null instance." /// </summary> internal static Exception OnlyStaticMethodsHaveNullInstance() { return new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance); } /// <summary> /// ArgumentException with message like "Property cannot have a void type." /// </summary> internal static Exception PropertyTypeCannotBeVoid() { return new ArgumentException(Strings.PropertyTypeCannotBeVoid); } /// <summary> /// ArgumentException with message like "Can only unbox from an object or interface type to a value type." /// </summary> internal static Exception InvalidUnboxType() { return new ArgumentException(Strings.InvalidUnboxType); } /// <summary> /// ArgumentException with message like "Argument must not have a value type." /// </summary> internal static Exception ArgumentMustNotHaveValueType() { return new ArgumentException(Strings.ArgumentMustNotHaveValueType); } /// <summary> /// ArgumentException with message like "must be reducible node" /// </summary> internal static Exception MustBeReducible() { return new ArgumentException(Strings.MustBeReducible); } /// <summary> /// ArgumentException with message like "Default body must be supplied if case bodies are not System.Void." /// </summary> internal static Exception DefaultBodyMustBeSupplied() { return new ArgumentException(Strings.DefaultBodyMustBeSupplied); } /// <summary> /// ArgumentException with message like "MethodBuilder does not have a valid TypeBuilder" /// </summary> internal static Exception MethodBuilderDoesNotHaveTypeBuilder() { return new ArgumentException(Strings.MethodBuilderDoesNotHaveTypeBuilder); } /// <summary> /// ArgumentException with message like "Label type must be System.Void if an expression is not supplied" /// </summary> internal static Exception LabelMustBeVoidOrHaveExpression() { return new ArgumentException(Strings.LabelMustBeVoidOrHaveExpression); } /// <summary> /// ArgumentException with message like "Type must be System.Void for this label argument" /// </summary> internal static Exception LabelTypeMustBeVoid() { return new ArgumentException(Strings.LabelTypeMustBeVoid); } /// <summary> /// ArgumentException with message like "Quoted expression must be a lambda" /// </summary> internal static Exception QuotedExpressionMustBeLambda() { return new ArgumentException(Strings.QuotedExpressionMustBeLambda); } /// <summary> /// ArgumentException with message like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables." /// </summary> internal static Exception VariableMustNotBeByRef(object p0, object p1) { return new ArgumentException(Strings.VariableMustNotBeByRef(p0, p1)); } /// <summary> /// ArgumentException with message like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object." /// </summary> internal static Exception DuplicateVariable(object p0) { return new ArgumentException(Strings.DuplicateVariable(p0)); } /// <summary> /// ArgumentException with message like "Start and End must be well ordered" /// </summary> internal static Exception StartEndMustBeOrdered() { return new ArgumentException(Strings.StartEndMustBeOrdered); } /// <summary> /// ArgumentException with message like "fault cannot be used with catch or finally clauses" /// </summary> internal static Exception FaultCannotHaveCatchOrFinally() { return new ArgumentException(Strings.FaultCannotHaveCatchOrFinally); } /// <summary> /// ArgumentException with message like "try must have at least one catch, finally, or fault clause" /// </summary> internal static Exception TryMustHaveCatchFinallyOrFault() { return new ArgumentException(Strings.TryMustHaveCatchFinallyOrFault); } /// <summary> /// ArgumentException with message like "Body of catch must have the same type as body of try." /// </summary> internal static Exception BodyOfCatchMustHaveSameTypeAsBodyOfTry() { return new ArgumentException(Strings.BodyOfCatchMustHaveSameTypeAsBodyOfTry); } /// <summary> /// InvalidOperationException with message like "Extension node must override the property {0}." /// </summary> internal static Exception ExtensionNodeMustOverrideProperty(object p0) { return new InvalidOperationException(Strings.ExtensionNodeMustOverrideProperty(p0)); } /// <summary> /// ArgumentException with message like "User-defined operator method '{0}' must be static." /// </summary> internal static Exception UserDefinedOperatorMustBeStatic(object p0) { return new ArgumentException(Strings.UserDefinedOperatorMustBeStatic(p0)); } /// <summary> /// ArgumentException with message like "User-defined operator method '{0}' must not be void." /// </summary> internal static Exception UserDefinedOperatorMustNotBeVoid(object p0) { return new ArgumentException(Strings.UserDefinedOperatorMustNotBeVoid(p0)); } /// <summary> /// InvalidOperationException with message like "No coercion operator is defined between types '{0}' and '{1}'." /// </summary> internal static Exception CoercionOperatorNotDefined(object p0, object p1) { return new InvalidOperationException(Strings.CoercionOperatorNotDefined(p0, p1)); } /// <summary> /// InvalidOperationException with message like "The unary operator {0} is not defined for the type '{1}'." /// </summary> internal static Exception UnaryOperatorNotDefined(object p0, object p1) { return new InvalidOperationException(Strings.UnaryOperatorNotDefined(p0, p1)); } /// <summary> /// InvalidOperationException with message like "The binary operator {0} is not defined for the types '{1}' and '{2}'." /// </summary> internal static Exception BinaryOperatorNotDefined(object p0, object p1, object p2) { return new InvalidOperationException(Strings.BinaryOperatorNotDefined(p0, p1, p2)); } /// <summary> /// InvalidOperationException with message like "Reference equality is not defined for the types '{0}' and '{1}'." /// </summary> internal static Exception ReferenceEqualityNotDefined(object p0, object p1) { return new InvalidOperationException(Strings.ReferenceEqualityNotDefined(p0, p1)); } /// <summary> /// InvalidOperationException with message like "The operands for operator '{0}' do not match the parameters of method '{1}'." /// </summary> internal static Exception OperandTypesDoNotMatchParameters(object p0, object p1) { return new InvalidOperationException(Strings.OperandTypesDoNotMatchParameters(p0, p1)); } /// <summary> /// InvalidOperationException with message like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'." /// </summary> internal static Exception OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1) { return new InvalidOperationException(Strings.OverloadOperatorTypeDoesNotMatchConversionType(p0, p1)); } /// <summary> /// InvalidOperationException with message like "Conversion is not supported for arithmetic types without operator overloading." /// </summary> internal static Exception ConversionIsNotSupportedForArithmeticTypes() { return new InvalidOperationException(Strings.ConversionIsNotSupportedForArithmeticTypes); } /// <summary> /// ArgumentException with message like "Argument must be array" /// </summary> internal static Exception ArgumentMustBeArray() { return new ArgumentException(Strings.ArgumentMustBeArray); } /// <summary> /// ArgumentException with message like "Argument must be boolean" /// </summary> internal static Exception ArgumentMustBeBoolean() { return new ArgumentException(Strings.ArgumentMustBeBoolean); } /// <summary> /// ArgumentException with message like "The user-defined equality method '{0}' must return a boolean value." /// </summary> internal static Exception EqualityMustReturnBoolean(object p0) { return new ArgumentException(Strings.EqualityMustReturnBoolean(p0)); } /// <summary> /// ArgumentException with message like "Argument must be either a FieldInfo or PropertyInfo" /// </summary> internal static Exception ArgumentMustBeFieldInfoOrPropertyInfo() { return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertyInfo); } /// <summary> /// ArgumentException with message like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo" /// </summary> internal static Exception ArgumentMustBeFieldInfoOrPropertyInfoOrMethod() { return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod); } /// <summary> /// ArgumentException with message like "Argument must be an instance member" /// </summary> internal static Exception ArgumentMustBeInstanceMember() { return new ArgumentException(Strings.ArgumentMustBeInstanceMember); } /// <summary> /// ArgumentException with message like "Argument must be of an integer type" /// </summary> internal static Exception ArgumentMustBeInteger() { return new ArgumentException(Strings.ArgumentMustBeInteger); } /// <summary> /// ArgumentException with message like "Argument for array index must be of type Int32" /// </summary> internal static Exception ArgumentMustBeArrayIndexType() { return new ArgumentException(Strings.ArgumentMustBeArrayIndexType); } /// <summary> /// ArgumentException with message like "Argument must be single dimensional array type" /// </summary> internal static Exception ArgumentMustBeSingleDimensionalArrayType() { return new ArgumentException(Strings.ArgumentMustBeSingleDimensionalArrayType); } /// <summary> /// ArgumentException with message like "Argument types do not match" /// </summary> internal static Exception ArgumentTypesMustMatch() { return new ArgumentException(Strings.ArgumentTypesMustMatch); } /// <summary> /// InvalidOperationException with message like "Cannot auto initialize elements of value type through property '{0}', use assignment instead" /// </summary> internal static Exception CannotAutoInitializeValueTypeElementThroughProperty(object p0) { return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeElementThroughProperty(p0)); } /// <summary> /// InvalidOperationException with message like "Cannot auto initialize members of value type through property '{0}', use assignment instead" /// </summary> internal static Exception CannotAutoInitializeValueTypeMemberThroughProperty(object p0) { return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeMemberThroughProperty(p0)); } /// <summary> /// ArgumentException with message like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither" /// </summary> internal static Exception IncorrectTypeForTypeAs(object p0) { return new ArgumentException(Strings.IncorrectTypeForTypeAs(p0)); } /// <summary> /// InvalidOperationException with message like "Coalesce used with type that cannot be null" /// </summary> internal static Exception CoalesceUsedOnNonNullType() { return new InvalidOperationException(Strings.CoalesceUsedOnNonNullType); } /// <summary> /// InvalidOperationException with message like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'" /// </summary> internal static Exception ExpressionTypeCannotInitializeArrayType(object p0, object p1) { return new InvalidOperationException(Strings.ExpressionTypeCannotInitializeArrayType(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchConstructorParameter(object p0, object p1) { return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchConstructorParameter(p0, p1); } /// <summary> /// ArgumentException with message like " Argument type '{0}' does not match the corresponding member type '{1}'" /// </summary> internal static Exception ArgumentTypeDoesNotMatchMember(object p0, object p1) { return new ArgumentException(Strings.ArgumentTypeDoesNotMatchMember(p0, p1)); } /// <summary> /// ArgumentException with message like " The member '{0}' is not declared on type '{1}' being created" /// </summary> internal static Exception ArgumentMemberNotDeclOnType(object p0, object p1) { return new ArgumentException(Strings.ArgumentMemberNotDeclOnType(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchMethodParameter(object p0, object p1, object p2) { return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchMethodParameter(p0, p1, p2); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for return type '{1}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchReturn(object p0, object p1) { return new ArgumentException(Strings.ExpressionTypeDoesNotMatchReturn(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for assignment to type '{1}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchAssignment(object p0, object p1) { return new ArgumentException(Strings.ExpressionTypeDoesNotMatchAssignment(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be used for label of type '{1}'" /// </summary> internal static Exception ExpressionTypeDoesNotMatchLabel(object p0, object p1) { return new ArgumentException(Strings.ExpressionTypeDoesNotMatchLabel(p0, p1)); } /// <summary> /// ArgumentException with message like "Expression of type '{0}' cannot be invoked" /// </summary> internal static Exception ExpressionTypeNotInvocable(object p0) { return new ArgumentException(Strings.ExpressionTypeNotInvocable(p0)); } /// <summary> /// ArgumentException with message like "Field '{0}' is not defined for type '{1}'" /// </summary> internal static Exception FieldNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.FieldNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Instance field '{0}' is not defined for type '{1}'" /// </summary> internal static Exception InstanceFieldNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.InstanceFieldNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Field '{0}.{1}' is not defined for type '{2}'" /// </summary> internal static Exception FieldInfoNotDefinedForType(object p0, object p1, object p2) { return new ArgumentException(Strings.FieldInfoNotDefinedForType(p0, p1, p2)); } /// <summary> /// ArgumentException with message like "Incorrect number of indexes" /// </summary> internal static Exception IncorrectNumberOfIndexes() { return new ArgumentException(Strings.IncorrectNumberOfIndexes); } /// <summary> /// ArgumentException with message like "Incorrect number of parameters supplied for lambda declaration" /// </summary> internal static Exception IncorrectNumberOfLambdaDeclarationParameters() { return new ArgumentException(Strings.IncorrectNumberOfLambdaDeclarationParameters); } /// <summary> /// ArgumentException with message like "Incorrect number of arguments supplied for call to method '{0}'" /// </summary> internal static Exception IncorrectNumberOfMethodCallArguments(object p0) { return Dynamic.Utils.Error.IncorrectNumberOfMethodCallArguments(p0); } /// <summary> /// ArgumentException with message like "Incorrect number of arguments for constructor" /// </summary> internal static Exception IncorrectNumberOfConstructorArguments() { return Dynamic.Utils.Error.IncorrectNumberOfConstructorArguments(); } /// <summary> /// ArgumentException with message like " Incorrect number of members for constructor" /// </summary> internal static Exception IncorrectNumberOfMembersForGivenConstructor() { return new ArgumentException(Strings.IncorrectNumberOfMembersForGivenConstructor); } /// <summary> /// ArgumentException with message like "Incorrect number of arguments for the given members " /// </summary> internal static Exception IncorrectNumberOfArgumentsForMembers() { return new ArgumentException(Strings.IncorrectNumberOfArgumentsForMembers); } /// <summary> /// ArgumentException with message like "Lambda type parameter must be derived from System.MulticastDelegate" /// </summary> internal static Exception LambdaTypeMustBeDerivedFromSystemDelegate() { return new ArgumentException(Strings.LambdaTypeMustBeDerivedFromSystemDelegate); } /// <summary> /// ArgumentException with message like "Member '{0}' not field or property" /// </summary> internal static Exception MemberNotFieldOrProperty(object p0) { return new ArgumentException(Strings.MemberNotFieldOrProperty(p0)); } /// <summary> /// ArgumentException with message like "Method {0} contains generic parameters" /// </summary> internal static Exception MethodContainsGenericParameters(object p0) { return new ArgumentException(Strings.MethodContainsGenericParameters(p0)); } /// <summary> /// ArgumentException with message like "Method {0} is a generic method definition" /// </summary> internal static Exception MethodIsGeneric(object p0) { return new ArgumentException(Strings.MethodIsGeneric(p0)); } /// <summary> /// ArgumentException with message like "The method '{0}.{1}' is not a property accessor" /// </summary> internal static Exception MethodNotPropertyAccessor(object p0, object p1) { return new ArgumentException(Strings.MethodNotPropertyAccessor(p0, p1)); } /// <summary> /// ArgumentException with message like "The property '{0}' has no 'get' accessor" /// </summary> internal static Exception PropertyDoesNotHaveGetter(object p0) { return new ArgumentException(Strings.PropertyDoesNotHaveGetter(p0)); } /// <summary> /// ArgumentException with message like "The property '{0}' has no 'set' accessor" /// </summary> internal static Exception PropertyDoesNotHaveSetter(object p0) { return new ArgumentException(Strings.PropertyDoesNotHaveSetter(p0)); } /// <summary> /// ArgumentException with message like "The property '{0}' has no 'get' or 'set' accessors" /// </summary> internal static Exception PropertyDoesNotHaveAccessor(object p0) { return new ArgumentException(Strings.PropertyDoesNotHaveAccessor(p0)); } /// <summary> /// ArgumentException with message like "'{0}' is not a member of type '{1}'" /// </summary> internal static Exception NotAMemberOfType(object p0, object p1) { return new ArgumentException(Strings.NotAMemberOfType(p0, p1)); } /// <summary> /// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for type '{1}'" /// </summary> internal static Exception ExpressionNotSupportedForType(object p0, object p1) { return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForType(p0, p1)); } /// <summary> /// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for nullable type '{1}'" /// </summary> internal static Exception ExpressionNotSupportedForNullableType(object p0, object p1) { return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForNullableType(p0, p1)); } /// <summary> /// ArgumentException with message like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'" /// </summary> internal static Exception ParameterExpressionNotValidAsDelegate(object p0, object p1) { return new ArgumentException(Strings.ParameterExpressionNotValidAsDelegate(p0, p1)); } /// <summary> /// ArgumentException with message like "Property '{0}' is not defined for type '{1}'" /// </summary> internal static Exception PropertyNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.PropertyNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Instance property '{0}' is not defined for type '{1}'" /// </summary> internal static Exception InstancePropertyNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.InstancePropertyNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Instance property '{0}' that takes no argument is not defined for type '{1}'" /// </summary> internal static Exception InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1) { return new ArgumentException(Strings.InstancePropertyWithoutParameterNotDefinedForType(p0, p1)); } /// <summary> /// ArgumentException with message like "Instance property '{0}{1}' is not defined for type '{2}'" /// </summary> internal static Exception InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2) { return new ArgumentException(Strings.InstancePropertyWithSpecifiedParametersNotDefinedForType(p0, p1, p2)); } /// <summary> /// ArgumentException with message like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'" /// </summary> internal static Exception InstanceAndMethodTypeMismatch(object p0, object p1, object p2) { return new ArgumentException(Strings.InstanceAndMethodTypeMismatch(p0, p1, p2)); } /// <summary> /// ArgumentException with message like "Type '{0}' does not have a default constructor" /// </summary> internal static Exception TypeMissingDefaultConstructor(object p0) { return new ArgumentException(Strings.TypeMissingDefaultConstructor(p0)); } /// <summary> /// ArgumentException with message like "Element initializer method must be named 'Add'" /// </summary> internal static Exception ElementInitializerMethodNotAdd() { return new ArgumentException(Strings.ElementInitializerMethodNotAdd); } /// <summary> /// ArgumentException with message like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter" /// </summary> internal static Exception ElementInitializerMethodNoRefOutParam(object p0, object p1) { return new ArgumentException(Strings.ElementInitializerMethodNoRefOutParam(p0, p1)); } /// <summary> /// ArgumentException with message like "Element initializer method must have at least 1 parameter" /// </summary> internal static Exception ElementInitializerMethodWithZeroArgs() { return new ArgumentException(Strings.ElementInitializerMethodWithZeroArgs); } /// <summary> /// ArgumentException with message like "Element initializer method must be an instance method" /// </summary> internal static Exception ElementInitializerMethodStatic() { return new ArgumentException(Strings.ElementInitializerMethodStatic); } /// <summary> /// ArgumentException with message like "Type '{0}' is not IEnumerable" /// </summary> internal static Exception TypeNotIEnumerable(object p0) { return new ArgumentException(Strings.TypeNotIEnumerable(p0)); } /// <summary> /// InvalidOperationException with message like "Unexpected coalesce operator." /// </summary> internal static Exception UnexpectedCoalesceOperator() { return new InvalidOperationException(Strings.UnexpectedCoalesceOperator); } /// <summary> /// InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}" /// </summary> internal static Exception InvalidCast(object p0, object p1) { return new InvalidOperationException(Strings.InvalidCast(p0, p1)); } /// <summary> /// ArgumentException with message like "Unhandled binary: {0}" /// </summary> internal static Exception UnhandledBinary(object p0) { return new ArgumentException(Strings.UnhandledBinary(p0)); } /// <summary> /// ArgumentException with message like "Unhandled binding " /// </summary> internal static Exception UnhandledBinding() { return new ArgumentException(Strings.UnhandledBinding); } /// <summary> /// ArgumentException with message like "Unhandled Binding Type: {0}" /// </summary> internal static Exception UnhandledBindingType(object p0) { return new ArgumentException(Strings.UnhandledBindingType(p0)); } /// <summary> /// ArgumentException with message like "Unhandled convert: {0}" /// </summary> internal static Exception UnhandledConvert(object p0) { return new ArgumentException(Strings.UnhandledConvert(p0)); } /// <summary> /// ArgumentException with message like "Unhandled Expression Type: {0}" /// </summary> internal static Exception UnhandledExpressionType(object p0) { return new ArgumentException(Strings.UnhandledExpressionType(p0)); } /// <summary> /// ArgumentException with message like "Unhandled unary: {0}" /// </summary> internal static Exception UnhandledUnary(object p0) { return new ArgumentException(Strings.UnhandledUnary(p0)); } /// <summary> /// ArgumentException with message like "Unknown binding type" /// </summary> internal static Exception UnknownBindingType() { return new ArgumentException(Strings.UnknownBindingType); } /// <summary> /// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types." /// </summary> internal static Exception UserDefinedOpMustHaveConsistentTypes(object p0, object p1) { return new ArgumentException(Strings.UserDefinedOpMustHaveConsistentTypes(p0, p1)); } /// <summary> /// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type." /// </summary> internal static Exception UserDefinedOpMustHaveValidReturnType(object p0, object p1) { return new ArgumentException(Strings.UserDefinedOpMustHaveValidReturnType(p0, p1)); } /// <summary> /// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators." /// </summary> internal static Exception LogicalOperatorMustHaveBooleanOperators(object p0, object p1) { return new ArgumentException(Strings.LogicalOperatorMustHaveBooleanOperators(p0, p1)); } /// <summary> /// InvalidOperationException with message like "No method '{0}' exists on type '{1}'." /// </summary> internal static Exception MethodDoesNotExistOnType(object p0, object p1) { return new InvalidOperationException(Strings.MethodDoesNotExistOnType(p0, p1)); } /// <summary> /// InvalidOperationException with message like "No method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static Exception MethodWithArgsDoesNotExistOnType(object p0, object p1) { return new InvalidOperationException(Strings.MethodWithArgsDoesNotExistOnType(p0, p1)); } /// <summary> /// InvalidOperationException with message like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. " /// </summary> internal static Exception GenericMethodWithArgsDoesNotExistOnType(object p0, object p1) { return new InvalidOperationException(Strings.GenericMethodWithArgsDoesNotExistOnType(p0, p1)); } /// <summary> /// InvalidOperationException with message like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static Exception MethodWithMoreThanOneMatch(object p0, object p1) { return new InvalidOperationException(Strings.MethodWithMoreThanOneMatch(p0, p1)); } /// <summary> /// InvalidOperationException with message like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static Exception PropertyWithMoreThanOneMatch(object p0, object p1) { return new InvalidOperationException(Strings.PropertyWithMoreThanOneMatch(p0, p1)); } /// <summary> /// ArgumentException with message like "An incorrect number of type args were specified for the declaration of a Func type." /// </summary> internal static Exception IncorrectNumberOfTypeArgsForFunc() { return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForFunc); } /// <summary> /// ArgumentException with message like "An incorrect number of type args were specified for the declaration of an Action type." /// </summary> internal static Exception IncorrectNumberOfTypeArgsForAction() { return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForAction); } /// <summary> /// ArgumentException with message like "Argument type cannot be System.Void." /// </summary> internal static Exception ArgumentCannotBeOfTypeVoid() { return new ArgumentException(Strings.ArgumentCannotBeOfTypeVoid); } /// <summary> /// ArgumentOutOfRangeException with message like "{0} must be greater than or equal to {1}" /// </summary> internal static Exception OutOfRange(object p0, object p1) { return new ArgumentOutOfRangeException(Strings.OutOfRange(p0, p1)); } /// <summary> /// InvalidOperationException with message like "Cannot redefine label '{0}' in an inner block." /// </summary> internal static Exception LabelTargetAlreadyDefined(object p0) { return new InvalidOperationException(Strings.LabelTargetAlreadyDefined(p0)); } /// <summary> /// InvalidOperationException with message like "Cannot jump to undefined label '{0}'." /// </summary> internal static Exception LabelTargetUndefined(object p0) { return new InvalidOperationException(Strings.LabelTargetUndefined(p0)); } /// <summary> /// InvalidOperationException with message like "Control cannot leave a finally block." /// </summary> internal static Exception ControlCannotLeaveFinally() { return new InvalidOperationException(Strings.ControlCannotLeaveFinally); } /// <summary> /// InvalidOperationException with message like "Control cannot leave a filter test." /// </summary> internal static Exception ControlCannotLeaveFilterTest() { return new InvalidOperationException(Strings.ControlCannotLeaveFilterTest); } /// <summary> /// InvalidOperationException with message like "Cannot jump to ambiguous label '{0}'." /// </summary> internal static Exception AmbiguousJump(object p0) { return new InvalidOperationException(Strings.AmbiguousJump(p0)); } /// <summary> /// InvalidOperationException with message like "Control cannot enter a try block." /// </summary> internal static Exception ControlCannotEnterTry() { return new InvalidOperationException(Strings.ControlCannotEnterTry); } /// <summary> /// InvalidOperationException with message like "Control cannot enter an expression--only statements can be jumped into." /// </summary> internal static Exception ControlCannotEnterExpression() { return new InvalidOperationException(Strings.ControlCannotEnterExpression); } /// <summary> /// InvalidOperationException with message like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values." /// </summary> internal static Exception NonLocalJumpWithValue(object p0) { return new InvalidOperationException(Strings.NonLocalJumpWithValue(p0)); } /// <summary> /// InvalidOperationException with message like "Extension should have been reduced." /// </summary> internal static Exception ExtensionNotReduced() { return new InvalidOperationException(Strings.ExtensionNotReduced); } /// <summary> /// InvalidOperationException with message like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value." /// </summary> internal static Exception CannotCompileConstant(object p0) { return new InvalidOperationException(Strings.CannotCompileConstant(p0)); } /// <summary> /// NotSupportedException with message like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite." /// </summary> internal static Exception CannotCompileDynamic() { return new NotSupportedException(Strings.CannotCompileDynamic); } /// <summary> /// InvalidOperationException with message like "Invalid lvalue for assignment: {0}." /// </summary> internal static Exception InvalidLvalue(ExpressionType p0) { return new InvalidOperationException(Strings.InvalidLvalue(p0)); } /// <summary> /// InvalidOperationException with message like "Invalid member type: {0}." /// </summary> internal static Exception InvalidMemberType(object p0) { return new InvalidOperationException(Strings.InvalidMemberType(p0)); } /// <summary> /// InvalidOperationException with message like "unknown lift type: '{0}'." /// </summary> internal static Exception UnknownLiftType(object p0) { return new InvalidOperationException(Strings.UnknownLiftType(p0)); } /// <summary> /// ArgumentException with message like "Invalid output directory." /// </summary> internal static Exception InvalidOutputDir() { return new ArgumentException(Strings.InvalidOutputDir); } /// <summary> /// ArgumentException with message like "Invalid assembly name or file extension." /// </summary> internal static Exception InvalidAsmNameOrExtension() { return new ArgumentException(Strings.InvalidAsmNameOrExtension); } /// <summary> /// ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters" /// </summary> internal static Exception IllegalNewGenericParams(object p0) { return new ArgumentException(Strings.IllegalNewGenericParams(p0)); } /// <summary> /// InvalidOperationException with message like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined" /// </summary> internal static Exception UndefinedVariable(object p0, object p1, object p2) { return new InvalidOperationException(Strings.UndefinedVariable(p0, p1, p2)); } /// <summary> /// InvalidOperationException with message like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'" /// </summary> internal static Exception CannotCloseOverByRef(object p0, object p1) { return new InvalidOperationException(Strings.CannotCloseOverByRef(p0, p1)); } /// <summary> /// InvalidOperationException with message like "Unexpected VarArgs call to method '{0}'" /// </summary> internal static Exception UnexpectedVarArgsCall(object p0) { return new InvalidOperationException(Strings.UnexpectedVarArgsCall(p0)); } /// <summary> /// InvalidOperationException with message like "Rethrow statement is valid only inside a Catch block." /// </summary> internal static Exception RethrowRequiresCatch() { return new InvalidOperationException(Strings.RethrowRequiresCatch); } /// <summary> /// InvalidOperationException with message like "Try expression is not allowed inside a filter body." /// </summary> internal static Exception TryNotAllowedInFilter() { return new InvalidOperationException(Strings.TryNotAllowedInFilter); } /// <summary> /// InvalidOperationException with message like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type." /// </summary> internal static Exception MustRewriteToSameNode(object p0, object p1, object p2) { return new InvalidOperationException(Strings.MustRewriteToSameNode(p0, p1, p2)); } /// <summary> /// InvalidOperationException with message like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite." /// </summary> internal static Exception MustRewriteChildToSameType(object p0, object p1, object p2) { return new InvalidOperationException(Strings.MustRewriteChildToSameType(p0, p1, p2)); } /// <summary> /// InvalidOperationException with message like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is intentional, override '{1}' and change it to allow this rewrite." /// </summary> internal static Exception MustRewriteWithoutMethod(object p0, object p1) { return new InvalidOperationException(Strings.MustRewriteWithoutMethod(p0, p1)); } /// <summary> /// NotSupportedException with message like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static Exception TryNotSupportedForMethodsWithRefArgs(object p0) { return new NotSupportedException(Strings.TryNotSupportedForMethodsWithRefArgs(p0)); } /// <summary> /// NotSupportedException with message like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static Exception TryNotSupportedForValueTypeInstances(object p0) { return new NotSupportedException(Strings.TryNotSupportedForValueTypeInstances(p0)); } /// <summary> /// InvalidOperationException with message like "Dynamic operations can only be performed in homogeneous AppDomain." /// </summary> internal static Exception HomogeneousAppDomainRequired() { return new InvalidOperationException(Strings.HomogeneousAppDomainRequired); } /// <summary> /// ArgumentException with message like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static Exception TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return new ArgumentException(Strings.TestValueTypeDoesNotMatchComparisonMethodParameter(p0, p1)); } /// <summary> /// ArgumentException with message like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static Exception SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return new ArgumentException(Strings.SwitchValueTypeDoesNotMatchComparisonMethodParameter(p0, p1)); } /// <summary> /// NotSupportedException with message like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod." /// </summary> internal static Exception PdbGeneratorNeedsExpressionCompiler() { return new NotSupportedException(Strings.PdbGeneratorNeedsExpressionCompiler); } /// <summary> /// The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method. /// </summary> internal static Exception ArgumentOutOfRange(string paramName) { return new ArgumentOutOfRangeException(paramName); } /// <summary> /// The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality. /// </summary> internal static Exception NotSupported() { return new NotSupportedException(); } #if FEATURE_COMPILE /// <summary> /// NotImplementedException with message like "The operator '{0}' is not implemented for type '{1}'" /// </summary> internal static Exception OperatorNotImplementedForType(object p0, object p1) { return NotImplemented.ByDesignWithMessage(Strings.OperatorNotImplementedForType(p0, p1)); } #endif /// <summary> /// ArgumentException with message like "The constructor should not be static" /// </summary> internal static Exception NonStaticConstructorRequired() { return new ArgumentException(Strings.NonStaticConstructorRequired); } /// <summary> /// InvalidOperationException with message like "Can't compile a NewExpression with a constructor declared on an abstract class" /// </summary> internal static Exception NonAbstractConstructorRequired() { return new InvalidOperationException(Strings.NonAbstractConstructorRequired); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_NATIVE #if FEATURE_CORE_DLR using System.Linq.Expressions; using System.Numerics; #else using Microsoft.Scripting.Math; #endif using System; using System.Collections.Generic; using System.Dynamic; using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.Scripting; using Microsoft.Scripting.Ast; using Microsoft.Scripting.Generation; using Microsoft.Scripting.Runtime; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Binding; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Modules { /// <summary> /// Provides support for interop with native code from Python code. /// </summary> public static partial class CTypes { [PythonType("CFuncPtr")] public abstract class _CFuncPtr : CData, IDynamicMetaObjectProvider, ICodeFormattable { private readonly Delegate _delegate; private readonly int _comInterfaceIndex = -1; private object _errcheck, _restype = _noResType; private IList<object> _argtypes; private int _id; private static int _curId = 0; internal static object _noResType = new object(); // __nonzero__ /// <summary> /// Creates a new CFuncPtr object from a tuple. The 1st element of the /// tuple is the ordinal or function name. The second is an object with /// a _handle property. The _handle property is the handle of the module /// from which the function will be loaded. /// </summary> public _CFuncPtr(PythonTuple args) { if (args == null) { throw PythonOps.TypeError("expected sequence, got None"); } else if (args.Count != 2) { throw PythonOps.TypeError("argument 1 must be a sequence of length 2, not {0}", args.Count); } object nameOrOrdinal = args[0]; object dll = args[1]; IntPtr intPtrHandle = GetHandleFromObject(dll, "the _handle attribute of the second element must be an integer"); IntPtr tmpAddr; string funcName = args[0] as string; if (funcName != null) { tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, funcName); } else { tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, new IntPtr((int)nameOrOrdinal)); } if (tmpAddr == IntPtr.Zero) { if (CallingConvention == CallingConvention.StdCall && funcName != null) { // apply std call name mangling - prepend a _, append @bytes where // bytes is the number of bytes of the argument list. string mangled = "_" + funcName + "@"; for (int i = 0; i < 128 && tmpAddr == IntPtr.Zero; i += 4) { tmpAddr = NativeFunctions.LoadFunction(intPtrHandle, mangled + i); } } if (tmpAddr == IntPtr.Zero) { throw PythonOps.AttributeError("function {0} is not defined", args[0]); } } _memHolder = new MemoryHolder(IntPtr.Size); addr = tmpAddr; _id = Interlocked.Increment(ref _curId); } public _CFuncPtr() { _id = Interlocked.Increment(ref _curId); _memHolder = new MemoryHolder(IntPtr.Size); } public _CFuncPtr(CodeContext context, object function) { _memHolder = new MemoryHolder(IntPtr.Size); if (function != null) { if (!PythonOps.IsCallable(context, function)) { throw PythonOps.TypeError("argument must be called or address of function"); } _delegate = ((CFuncPtrType)DynamicHelpers.GetPythonType(this)).MakeReverseDelegate(context, function); addr = Marshal.GetFunctionPointerForDelegate(_delegate); CFuncPtrType myType = (CFuncPtrType)NativeType; PythonType resType = myType._restype; if (resType != null) { if (!(resType is INativeType) || resType is PointerType) { throw PythonOps.TypeError("invalid result type {0} for callback function", ((PythonType)resType).Name); } } } _id = Interlocked.Increment(ref _curId); } /// <summary> /// Creates a new CFuncPtr which calls a COM method. /// </summary> public _CFuncPtr(int index, string name) { _memHolder = new MemoryHolder(IntPtr.Size); _comInterfaceIndex = index; _id = Interlocked.Increment(ref _curId); } /// <summary> /// Creates a new CFuncPtr with the specfied address. /// </summary> public _CFuncPtr(int handle) { _memHolder = new MemoryHolder(IntPtr.Size); addr = new IntPtr(handle); _id = Interlocked.Increment(ref _curId); } /// <summary> /// Creates a new CFuncPtr with the specfied address. /// </summary> public _CFuncPtr([NotNull]BigInteger handle) { _memHolder = new MemoryHolder(IntPtr.Size); addr = new IntPtr((long)handle); _id = Interlocked.Increment(ref _curId); } public _CFuncPtr(IntPtr handle) { _memHolder = new MemoryHolder(IntPtr.Size); addr = handle; _id = Interlocked.Increment(ref _curId); } public bool __nonzero__() { return addr != IntPtr.Zero; } #region Public APIs [SpecialName, PropertyMethod] public object Geterrcheck() { return _errcheck; } [SpecialName, PropertyMethod] public void Seterrcheck(object value) { _errcheck = value; } [SpecialName, PropertyMethod] public void Deleteerrcheck() { _errcheck = null; _id = Interlocked.Increment(ref _curId); } [PropertyMethod, SpecialName] public object Getrestype() { if (_restype == _noResType) { return ((CFuncPtrType)NativeType)._restype; } return _restype; } [PropertyMethod, SpecialName] public void Setrestype(object value) { INativeType nt = value as INativeType; if (nt != null || value == null || PythonOps.IsCallable(((PythonType)NativeType).Context.SharedContext, value)) { _restype = value; _id = Interlocked.Increment(ref _curId); } else { throw PythonOps.TypeError("restype must be a type, a callable, or None"); } } [SpecialName, PropertyMethod] public void Deleterestype() { _restype = _noResType; _id = Interlocked.Increment(ref _curId); } public object argtypes { get { if (_argtypes != null) { return _argtypes; } if (((CFuncPtrType)NativeType)._argtypes != null) { return PythonTuple.MakeTuple(((CFuncPtrType)NativeType)._argtypes); } return null; } set { if (value != null) { IList<object> argValues = value as IList<object>; if (argValues == null) { throw PythonOps.TypeErrorForTypeMismatch("sequence", value); } foreach (object o in argValues) { if (!(o is INativeType)) { if (!PythonOps.HasAttr(DefaultContext.Default, o, "from_param")) { throw PythonOps.TypeErrorForTypeMismatch("ctype or object with from_param", o); } } } _argtypes = argValues; } else { _argtypes = null; } _id = Interlocked.Increment(ref _curId); } } #endregion #region Internal APIs internal CallingConvention CallingConvention { get { return ((CFuncPtrType)DynamicHelpers.GetPythonType(this)).CallingConvention; } } // TODO: access via PythonOps public IntPtr addr { [PythonHidden] get { return _memHolder.ReadIntPtr(0); } [PythonHidden] set { _memHolder.WriteIntPtr(0, value); } } internal int Id { get { return _id; } } #endregion #region IDynamicObject Members // needs to be public so that derived base classes can call it. [PythonHidden] public DynamicMetaObject GetMetaObject(Expression parameter) { return new Meta(parameter, this); } #endregion #region MetaObject private class Meta : MetaPythonObject { public Meta(Expression parameter, _CFuncPtr func) : base(parameter, BindingRestrictions.Empty, func) { } public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { CodeContext context = PythonContext.GetPythonContext(binder).SharedContext; ArgumentMarshaller[] signature = GetArgumentMarshallers(args); BindingRestrictions restrictions = BindingRestrictions.GetTypeRestriction( Expression, Value.GetType() ).Merge( BindingRestrictions.GetExpressionRestriction( Expression.Call( typeof(ModuleOps).GetMethod("CheckFunctionId"), Expression.Convert(Expression, typeof(_CFuncPtr)), Expression.Constant(Value.Id) ) ) ); foreach (var arg in signature) { restrictions = restrictions.Merge(arg.GetRestrictions()); } int argCount = args.Length; if (Value._comInterfaceIndex != -1) { argCount--; } // need to verify we have the correct # of args if (Value._argtypes != null) { if (argCount < Value._argtypes.Count || (Value.CallingConvention != CallingConvention.Cdecl && argCount > Value._argtypes.Count)) { return IncorrectArgCount(binder, restrictions, Value._argtypes.Count, argCount); } } else { CFuncPtrType funcType = ((CFuncPtrType)Value.NativeType); if (funcType._argtypes != null && (argCount < funcType._argtypes.Length || (Value.CallingConvention != CallingConvention.Cdecl && argCount > funcType._argtypes.Length))) { return IncorrectArgCount(binder, restrictions, funcType._argtypes.Length, argCount); } } if (Value._comInterfaceIndex != -1 && args.Length == 0) { return NoThisParam(binder, restrictions); } Expression call = MakeCall(signature, GetNativeReturnType(), Value.Getrestype() == null, GetFunctionAddress(args)); List<Expression> block = new List<Expression>(); Expression res; if (call.Type != typeof(void)) { ParameterExpression tmp = Expression.Parameter(call.Type, "ret"); block.Add(Expression.Assign(tmp, call)); AddKeepAlives(signature, block); block.Add(tmp); res = Expression.Block(new[] { tmp }, block); } else { block.Add(call); AddKeepAlives(signature, block); res = Expression.Block(block); } res = AddReturnChecks(context, args, res); return new DynamicMetaObject(Utils.Convert(res, typeof(object)), restrictions); } private Expression AddReturnChecks(CodeContext context, DynamicMetaObject[] args, Expression res) { PythonContext ctx = PythonContext.GetContext(context); object resType = Value.Getrestype(); if (resType != null) { // res type can be callable, a type with _check_retval_, or // it can be just be a type which doesn't require post-processing. INativeType nativeResType = resType as INativeType; object checkRetVal = null; if (nativeResType == null) { checkRetVal = resType; } else if (!PythonOps.TryGetBoundAttr(context, nativeResType, "_check_retval_", out checkRetVal)) { // we just wanted to try and get the value, don't need to do anything here. checkRetVal = null; } if (checkRetVal != null) { res = Expression.Dynamic( ctx.CompatInvoke(new CallInfo(1)), typeof(object), Expression.Constant(checkRetVal), res ); } } object errCheck = Value.Geterrcheck(); if (errCheck != null) { res = Expression.Dynamic( ctx.CompatInvoke(new CallInfo(3)), typeof(object), Expression.Constant(errCheck), res, Expression, Expression.Call( typeof(PythonOps).GetMethod("MakeTuple"), Expression.NewArrayInit( typeof(object), ArrayUtils.ConvertAll(args, x => Utils.Convert(x.Expression, typeof(object))) ) ) ); } return res; } private static DynamicMetaObject IncorrectArgCount(DynamicMetaObjectBinder binder, BindingRestrictions restrictions, int expected, int got) { return new DynamicMetaObject( binder.Throw( Expression.Call( typeof(PythonOps).GetMethod("TypeError"), Expression.Constant(String.Format("this function takes {0} arguments ({1} given)", expected, got)), Expression.NewArrayInit(typeof(object)) ), typeof(object) ), restrictions ); } private static DynamicMetaObject NoThisParam(DynamicMetaObjectBinder binder, BindingRestrictions restrictions) { return new DynamicMetaObject( binder.Throw( Expression.Call( typeof(PythonOps).GetMethod("ValueError"), Expression.Constant("native com method call without 'this' parameter"), Expression.NewArrayInit(typeof(object)) ), typeof(object) ), restrictions ); } /// <summary> /// we need to keep alive any methods which have arguments for the duration of the /// call. Otherwise they could be collected on the finalizer thread before we come back. /// </summary> private void AddKeepAlives(ArgumentMarshaller[] signature, List<Expression> block) { foreach (ArgumentMarshaller marshaller in signature) { Expression keepAlive = marshaller.GetKeepAlive(); if (keepAlive != null) { block.Add(keepAlive); } } } private Expression MakeCall(ArgumentMarshaller[] signature, INativeType nativeRetType, bool retVoid, Expression address) { List<object> constantPool = new List<object>(); MethodInfo interopInvoker = CreateInteropInvoker( GetCallingConvention(), signature, nativeRetType, retVoid, constantPool ); // build the args - IntPtr, user Args, constant pool Expression[] callArgs = new Expression[signature.Length + 2]; callArgs[0] = address; for (int i = 0; i < signature.Length; i++) { callArgs[i + 1] = signature[i].ArgumentExpression; } callArgs[callArgs.Length - 1] = Expression.Constant(constantPool.ToArray()); return Expression.Call(interopInvoker, callArgs); } private Expression GetFunctionAddress(DynamicMetaObject[] args) { Expression address; if (Value._comInterfaceIndex != -1) { Debug.Assert(args.Length != 0); // checked earlier address = Expression.Call( typeof(ModuleOps).GetMethod("GetInterfacePointer"), Expression.Call( typeof(ModuleOps).GetMethod("GetPointer"), args[0].Expression ), Expression.Constant(Value._comInterfaceIndex) ); } else { address = Expression.Property( Expression.Convert(Expression, typeof(_CFuncPtr)), "addr" ); } return address; } private CallingConvention GetCallingConvention() { return Value.CallingConvention; } private INativeType GetNativeReturnType() { return Value.Getrestype() as INativeType; } private ArgumentMarshaller/*!*/[]/*!*/ GetArgumentMarshallers(DynamicMetaObject/*!*/[]/*!*/ args) { CFuncPtrType funcType = ((CFuncPtrType)Value.NativeType); ArgumentMarshaller[] res = new ArgumentMarshaller[args.Length]; // first arg is taken by self if we're a com method for (int i = 0; i < args.Length; i++) { DynamicMetaObject mo = args[i]; object argType = null; if (Value._comInterfaceIndex == -1 || i != 0) { int argtypeIndex = Value._comInterfaceIndex == -1 ? i : i - 1; if (Value._argtypes != null && argtypeIndex < Value._argtypes.Count) { argType = Value._argtypes[argtypeIndex]; } else if (funcType._argtypes != null && argtypeIndex < funcType._argtypes.Length) { argType = funcType._argtypes[argtypeIndex]; } } res[i] = GetMarshaller(mo.Expression, mo.Value, i, argType); } return res; } private ArgumentMarshaller/*!*/ GetMarshaller(Expression/*!*/ expr, object value, int index, object nativeType) { if (nativeType != null) { INativeType nt = nativeType as INativeType; if (nt != null) { return new CDataMarshaller(expr, CompilerHelpers.GetType(value), nt); } return new FromParamMarshaller(expr); } CData data = value as CData; if (data != null) { return new CDataMarshaller(expr, CompilerHelpers.GetType(value), data.NativeType); } NativeArgument arg = value as NativeArgument; if (arg != null) { return new NativeArgumentMarshaller(expr); } object val; if (PythonOps.TryGetBoundAttr(value, "_as_parameter_", out val)) { throw new NotImplementedException("_as_parameter"); //return new UserDefinedMarshaller(GetMarshaller(..., value, index)); } // Marshalling primitive or an object return new PrimitiveMarshaller(expr, CompilerHelpers.GetType(value)); } public new _CFuncPtr/*!*/ Value { get { return (_CFuncPtr)base.Value; } } /// <summary> /// Creates a method for calling with the specified signature. The returned method has a signature /// of the form: /// /// (IntPtr funcAddress, arg0, arg1, ..., object[] constantPool) /// /// where IntPtr is the address of the function to be called. The arguments types are based upon /// the types that the ArgumentMarshaller requires. /// </summary> private static MethodInfo/*!*/ CreateInteropInvoker(CallingConvention convention, ArgumentMarshaller/*!*/[]/*!*/ sig, INativeType nativeRetType, bool retVoid, List<object> constantPool) { Type[] sigTypes = new Type[sig.Length + 2]; sigTypes[0] = typeof(IntPtr); for (int i = 0; i < sig.Length; i++) { sigTypes[i + 1] = sig[i].ArgumentExpression.Type; } sigTypes[sigTypes.Length - 1] = typeof(object[]); Type retType = retVoid ? typeof(void) : nativeRetType != null ? nativeRetType.GetPythonType() : typeof(int); Type calliRetType = retVoid ? typeof(void) : nativeRetType != null ? nativeRetType.GetNativeType() : typeof(int); #if !CTYPES_USE_SNIPPETS DynamicMethod dm = new DynamicMethod("InteropInvoker", retType, sigTypes, DynamicModule); #else TypeGen tg = Snippets.Shared.DefineType("InteropInvoker", typeof(object), false, false); MethodBuilder dm = tg.TypeBuilder.DefineMethod("InteropInvoker", CompilerHelpers.PublicStatic, retType, sigTypes); #endif ILGenerator method = dm.GetILGenerator(); LocalBuilder calliRetTmp = null, finalRetValue = null; if (dm.ReturnType != typeof(void)) { calliRetTmp = method.DeclareLocal(calliRetType); finalRetValue = method.DeclareLocal(dm.ReturnType); } // try { // emit all of the arguments, save their cleanups method.BeginExceptionBlock(); List<MarshalCleanup> cleanups = null; for (int i = 0; i < sig.Length; i++) { #if DEBUG method.Emit(OpCodes.Ldstr, String.Format("Argument #{0}, Marshaller: {1}, Native Type: {2}", i, sig[i], sig[i].NativeType)); method.Emit(OpCodes.Pop); #endif MarshalCleanup cleanup = sig[i].EmitCallStubArgument(method, i + 1, constantPool, sigTypes.Length - 1); if (cleanup != null) { if (cleanups == null) { cleanups = new List<MarshalCleanup>(); } cleanups.Add(cleanup); } } // emit the target function pointer and the calli #if DEBUG method.Emit(OpCodes.Ldstr, "!!! CALLI !!!"); method.Emit(OpCodes.Pop); #endif method.Emit(OpCodes.Ldarg_0); method.Emit(OpCodes.Calli, GetCalliSignature(convention, sig, calliRetType)); // if we have a return value we need to store it and marshal to Python // before we run any cleanup code. if (retType != typeof(void)) { #if DEBUG method.Emit(OpCodes.Ldstr, "!!! Return !!!"); method.Emit(OpCodes.Pop); #endif if (nativeRetType != null) { method.Emit(OpCodes.Stloc, calliRetTmp); nativeRetType.EmitReverseMarshalling(method, new Local(calliRetTmp), constantPool, sig.Length + 1); method.Emit(OpCodes.Stloc, finalRetValue); } else { Debug.Assert(retType == typeof(int)); // no marshalling necessary method.Emit(OpCodes.Stloc, finalRetValue); } } // } finally { // emit the cleanup code method.BeginFinallyBlock(); if (cleanups != null) { foreach (MarshalCleanup mc in cleanups) { mc.Cleanup(method); } } method.EndExceptionBlock(); // } // load the temporary value and return it. if (retType != typeof(void)) { method.Emit(OpCodes.Ldloc, finalRetValue); } method.Emit(OpCodes.Ret); #if CTYPES_USE_SNIPPETS return tg.TypeBuilder.CreateType().GetMethod("InteropInvoker"); #else return dm; #endif } private static SignatureHelper GetCalliSignature(CallingConvention convention, ArgumentMarshaller/*!*/[] sig, Type calliRetType) { SignatureHelper signature = SignatureHelper.GetMethodSigHelper(convention, calliRetType); foreach (ArgumentMarshaller argMarshaller in sig) { signature.AddArgument(argMarshaller.NativeType); } return signature; } #region Argument Marshalling /// <summary> /// Base class for marshalling arguments from the user provided value to the /// call stub. This class provides the logic for creating the call stub and /// calling it. /// </summary> abstract class ArgumentMarshaller { private readonly Expression/*!*/ _argExpr; public ArgumentMarshaller(Expression/*!*/ container) { _argExpr = container; } /// <summary> /// Emits the IL to get the argument for the call stub generated into /// a dynamic method. /// </summary> public abstract MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument); public abstract Type/*!*/ NativeType { get; } /// <summary> /// Gets the expression used to provide the argument. This is the expression /// from an incoming DynamicMetaObject. /// </summary> public Expression/*!*/ ArgumentExpression { get { return _argExpr; } } /// <summary> /// Gets an expression which keeps alive the argument for the duration of the call. /// /// Returns null if a keep alive is not necessary. /// </summary> public virtual Expression GetKeepAlive() { return null; } public virtual BindingRestrictions GetRestrictions() { return BindingRestrictions.Empty; } } /// <summary> /// Provides marshalling of primitive values when the function type /// has no type information or when the user has provided us with /// an explicit cdata instance. /// </summary> class PrimitiveMarshaller : ArgumentMarshaller { private readonly Type/*!*/ _type; private static MethodInfo _bigIntToInt32; private static MethodInfo BigIntToInt32 { get { if (_bigIntToInt32 == null) { #if CLR2 _bigIntToInt32 = typeof(BigInteger).GetMethod("ToInt32", ReflectionUtils.EmptyTypes); #else MemberInfo[] mis = typeof(BigInteger).GetMember( "op_Explicit", MemberTypes.Method, BindingFlags.Public | BindingFlags.Static ); foreach (MethodInfo mi in mis) { if (mi.ReturnType == typeof(int)) { _bigIntToInt32 = mi; break; } } Debug.Assert(_bigIntToInt32 != null); #endif } return _bigIntToInt32; } } public PrimitiveMarshaller(Expression/*!*/ container, Type/*!*/ type) : base(container) { _type = type; } public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { if (_type == typeof(DynamicNull)) { generator.Emit(OpCodes.Ldc_I4_0); generator.Emit(OpCodes.Conv_I); return null; } generator.Emit(OpCodes.Ldarg, argIndex); if (ArgumentExpression.Type != _type) { generator.Emit(OpCodes.Unbox_Any, _type); } if (_type == typeof(string)) { // pin the string and convert to a wchar*. We could let the CLR do this // but we need the string to be pinned longer than the duration of the the CLR's // p/invoke. This is because the function could return the same pointer back // to us and we need to create a new string from it. LocalBuilder lb = generator.DeclareLocal(typeof(string), true); generator.Emit(OpCodes.Stloc, lb); generator.Emit(OpCodes.Ldloc, lb); generator.Emit(OpCodes.Conv_I); generator.Emit(OpCodes.Ldc_I4, RuntimeHelpers.OffsetToStringData); generator.Emit(OpCodes.Add); } else if (_type == typeof(Bytes)) { LocalBuilder lb = generator.DeclareLocal(typeof(byte).MakeByRefType(), true); generator.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("GetBytes")); generator.Emit(OpCodes.Ldc_I4_0); generator.Emit(OpCodes.Ldelema, typeof(Byte)); generator.Emit(OpCodes.Stloc, lb); generator.Emit(OpCodes.Ldloc, lb); } else if (_type == typeof(BigInteger)) { generator.Emit(OpCodes.Call, BigIntToInt32); } else if (!_type.IsValueType) { generator.Emit(OpCodes.Call, typeof(CTypes).GetMethod("PyObj_ToPtr")); } return null; } public override Type NativeType { get { if (_type == typeof(BigInteger)) { return typeof(int); } else if (!_type.IsValueType) { return typeof(IntPtr); } return _type; } } public override BindingRestrictions GetRestrictions() { if (_type == typeof(DynamicNull)) { return BindingRestrictions.GetExpressionRestriction(Expression.Equal(ArgumentExpression, Expression.Constant(null))); } return BindingRestrictions.GetTypeRestriction(ArgumentExpression, _type); } } class FromParamMarshaller : ArgumentMarshaller { public FromParamMarshaller(Expression/*!*/ container) : base(container) { } public override MarshalCleanup EmitCallStubArgument(ILGenerator generator, int argIndex, List<object> constantPool, int constantPoolArgument) { throw new NotImplementedException(); } public override Type NativeType { get { throw new NotImplementedException(); } } } /// <summary> /// Provides marshalling for when the function type provide argument information. /// </summary> class CDataMarshaller : ArgumentMarshaller { private readonly Type/*!*/ _type; private readonly INativeType/*!*/ _cdataType; public CDataMarshaller(Expression/*!*/ container, Type/*!*/ type, INativeType/*!*/cdataType) : base(container) { _type = type; _cdataType = cdataType; } public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { return _cdataType.EmitMarshalling(generator, new Arg(argIndex, ArgumentExpression.Type), constantPool, constantPoolArgument); } public override Type NativeType { get { return _cdataType.GetNativeType(); } } public override Expression GetKeepAlive() { // Future possible optimization - we could just keep alive the MemoryHolder if (_type.IsValueType) { return null; } return Expression.Call( typeof(GC).GetMethod("KeepAlive"), ArgumentExpression ); } public override BindingRestrictions GetRestrictions() { // we base this off of the type marshalling which can handle anything. return BindingRestrictions.Empty; } } /// <summary> /// Provides marshalling for when the user provides a native argument object /// (usually gotten by byref or pointer) and the function type has no type information. /// </summary> class NativeArgumentMarshaller : ArgumentMarshaller { public NativeArgumentMarshaller(Expression/*!*/ container) : base(container) { } public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { // We access UnsafeAddress here but ensure the object is kept // alive via the expression returned in GetKeepAlive. generator.Emit(OpCodes.Ldarg, argIndex); generator.Emit(OpCodes.Castclass, typeof(NativeArgument)); generator.Emit(OpCodes.Call, typeof(NativeArgument).GetMethod("get__obj")); generator.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); return null; } public override Type/*!*/ NativeType { get { return typeof(IntPtr); } } public override Expression GetKeepAlive() { // Future possible optimization - we could just keep alive the MemoryHolder return Expression.Call( typeof(GC).GetMethod("KeepAlive"), ArgumentExpression ); } public override BindingRestrictions GetRestrictions() { return BindingRestrictions.GetTypeRestriction(ArgumentExpression, typeof(NativeArgument)); } } #if FALSE // TODO: not implemented yet /// <summary> /// Provides the marshalling for a user defined object which has an _as_parameter_ /// value. /// </summary> class UserDefinedMarshaller : ArgumentMarshaller { private readonly ArgumentMarshaller/*!*/ _marshaller; public UserDefinedMarshaller(Expression/*!*/ container, ArgumentMarshaller/*!*/ marshaller) : base(container) { _marshaller = marshaller; } public override Type NativeType { get { throw new NotImplementedException("user defined marshaller sig type"); } } public override MarshalCleanup EmitCallStubArgument(ILGenerator/*!*/ generator, int argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { throw new NotImplementedException("user defined marshaller"); } } #endif #endregion } #endregion public string __repr__(CodeContext context) { if (_comInterfaceIndex != -1) { return string.Format("<COM method offset {0}: {1} at {2}>", _comInterfaceIndex, DynamicHelpers.GetPythonType(this).Name, _id); } return ObjectOps.__repr__(this); } } } } #endif
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // EventSource for TPL. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Text; using System.Security; using System.Security.Permissions; using System.Runtime.CompilerServices; namespace System.Threading.Tasks { using System.Diagnostics.Tracing; /// <summary>Provides an event source for tracing TPL information.</summary> [EventSource( Name = "System.Threading.Tasks.TplEventSource", Guid = "2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5", LocalizationResources = "mscorlib")] internal sealed class TplEtwProvider : EventSource { /// Used to determine if tasks should generate Activity IDs for themselves internal bool TasksSetActivityIds; // This keyword is set internal bool Debug; private bool DebugActivityId; /// <summary> /// Get callbacks when the ETW sends us commands` /// </summary> protected override void OnEventCommand(EventCommandEventArgs command) { // To get the AsyncCausality events, we need to inform the AsyncCausalityTracer if (command.Command == EventCommand.Enable) AsyncCausalityTracer.EnableToETW(true); else if (command.Command == EventCommand.Disable) AsyncCausalityTracer.EnableToETW(false); if (IsEnabled(EventLevel.Informational, Keywords.TasksFlowActivityIds)) ActivityTracker.Instance.Enable(); else TasksSetActivityIds = IsEnabled(EventLevel.Informational, Keywords.TasksSetActivityIds); Debug = IsEnabled(EventLevel.Informational, Keywords.Debug); DebugActivityId = IsEnabled(EventLevel.Informational, Keywords.DebugActivityId); } /// <summary> /// Defines the singleton instance for the TPL ETW provider. /// The TPL Event provider GUID is {2e5dba47-a3d2-4d16-8ee0-6671ffdcd7b5}. /// </summary> public static TplEtwProvider Log = new TplEtwProvider(); /// <summary>Prevent external instantiation. All logging should go through the Log instance.</summary> private TplEtwProvider() { } /// <summary>Type of a fork/join operation.</summary> public enum ForkJoinOperationType { /// <summary>Parallel.Invoke.</summary> ParallelInvoke=1, /// <summary>Parallel.For.</summary> ParallelFor=2, /// <summary>Parallel.ForEach.</summary> ParallelForEach=3 } /// <summary>Configured behavior of a task wait operation.</summary> public enum TaskWaitBehavior : int { /// <summary>A synchronous wait.</summary> Synchronous = 1, /// <summary>An asynchronous await.</summary> Asynchronous = 2 } /// <summary>ETW tasks that have start/stop events.</summary> public class Tasks // this name is important for EventSource { /// <summary>A parallel loop.</summary> public const EventTask Loop = (EventTask)1; /// <summary>A parallel invoke.</summary> public const EventTask Invoke = (EventTask)2; /// <summary>Executing a Task.</summary> public const EventTask TaskExecute = (EventTask)3; /// <summary>Waiting on a Task.</summary> public const EventTask TaskWait = (EventTask)4; /// <summary>A fork/join task within a loop or invoke.</summary> public const EventTask ForkJoin = (EventTask)5; /// <summary>A task is scheduled to execute.</summary> public const EventTask TaskScheduled = (EventTask)6; /// <summary>An await task continuation is scheduled to execute.</summary> public const EventTask AwaitTaskContinuationScheduled = (EventTask)7; /// <summary>AsyncCausalityFunctionality.</summary> public const EventTask TraceOperation = (EventTask)8; public const EventTask TraceSynchronousWork = (EventTask)9; } public class Keywords // thisname is important for EventSource { /// <summary> /// Only the most basic information about the workings of the task library /// This sets activity IDS and logs when tasks are schedules (or waits begin) /// But are otherwise silent /// </summary> public const EventKeywords TaskTransfer = (EventKeywords) 1; /// <summary> /// TaskTranser events plus events when tasks start and stop /// </summary> public const EventKeywords Tasks = (EventKeywords) 2; /// <summary> /// Events associted with the higher level parallel APIs /// </summary> public const EventKeywords Parallel = (EventKeywords) 4; /// <summary> /// These are relatively verbose events that effectively just redirect /// the windows AsyncCausalityTracer to ETW /// </summary> public const EventKeywords AsyncCausalityOperation = (EventKeywords) 8; public const EventKeywords AsyncCausalityRelation = (EventKeywords) 0x10; public const EventKeywords AsyncCausalitySynchronousWork = (EventKeywords) 0x20; /// <summary> /// Emit the stops as well as the schedule/start events /// </summary> public const EventKeywords TaskStops = (EventKeywords) 0x40; /// <summary> /// TasksFlowActivityIds indicate that activity ID flow from one task /// to any task created by it. /// </summary> public const EventKeywords TasksFlowActivityIds = (EventKeywords) 0x80; /// <summary> /// TasksSetActivityIds will cause the task operations to set Activity Ids /// This option is incompatible with TasksFlowActivityIds flow is ignored /// if that keyword is set. This option is likley to be removed in the future /// </summary> public const EventKeywords TasksSetActivityIds = (EventKeywords) 0x10000; /// <summary> /// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future /// </summary> public const EventKeywords Debug = (EventKeywords) 0x20000; /// <summary> /// Relatively Verbose logging meant for debugging the Task library itself. Will probably be removed in the future /// </summary> public const EventKeywords DebugActivityId = (EventKeywords) 0x40000; } /// <summary>Enabled for all keywords.</summary> private const EventKeywords ALL_KEYWORDS = (EventKeywords)(-1); //----------------------------------------------------------------------------------- // // TPL Event IDs (must be unique) // /// <summary>The beginning of a parallel loop.</summary> private const int PARALLELLOOPBEGIN_ID = 1; /// <summary>The ending of a parallel loop.</summary> private const int PARALLELLOOPEND_ID = 2; /// <summary>The beginning of a parallel invoke.</summary> private const int PARALLELINVOKEBEGIN_ID = 3; /// <summary>The ending of a parallel invoke.</summary> private const int PARALLELINVOKEEND_ID = 4; /// <summary>A task entering a fork/join construct.</summary> private const int PARALLELFORK_ID = 5; /// <summary>A task leaving a fork/join construct.</summary> private const int PARALLELJOIN_ID = 6; /// <summary>A task is scheduled to a task scheduler.</summary> private const int TASKSCHEDULED_ID = 7; /// <summary>A task is about to execute.</summary> private const int TASKSTARTED_ID = 8; /// <summary>A task has finished executing.</summary> private const int TASKCOMPLETED_ID = 9; /// <summary>A wait on a task is beginning.</summary> private const int TASKWAITBEGIN_ID = 10; /// <summary>A wait on a task is ending.</summary> private const int TASKWAITEND_ID = 11; /// <summary>A continuation of a task is scheduled.</summary> private const int AWAITTASKCONTINUATIONSCHEDULED_ID = 12; /// <summary>A continuation of a taskWaitEnd is complete </summary> private const int TASKWAITCONTINUATIONCOMPLETE_ID = 13; /// <summary>A continuation of a taskWaitEnd is complete </summary> private const int TASKWAITCONTINUATIONSTARTED_ID = 19; private const int TRACEOPERATIONSTART_ID = 14; private const int TRACEOPERATIONSTOP_ID = 15; private const int TRACEOPERATIONRELATION_ID = 16; private const int TRACESYNCHRONOUSWORKSTART_ID = 17; private const int TRACESYNCHRONOUSWORKSTOP_ID = 18; //----------------------------------------------------------------------------------- // // Parallel Events // #region ParallelLoopBegin /// <summary> /// Denotes the entry point for a Parallel.For or Parallel.ForEach loop /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The loop ID.</param> /// <param name="OperationType">The kind of fork/join operation.</param> /// <param name="InclusiveFrom">The lower bound of the loop.</param> /// <param name="ExclusiveTo">The upper bound of the loop.</param> [SecuritySafeCritical] [Event(PARALLELLOOPBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive, Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Start)] public void ParallelLoopBegin( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID, ForkJoinOperationType OperationType, // PFX_FORKJOIN_COMMON_EVENT_HEADER long InclusiveFrom, long ExclusiveTo) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Parallel)) { // There is no explicit WriteEvent() overload matching this event's fields. Therefore calling // WriteEvent() would hit the "params" overload, which leads to an object allocation every time // this event is fired. To prevent that problem we will call WriteEventCore(), which works with // a stack based EventData array populated with the event fields. unsafe { EventData* eventPayload = stackalloc EventData[6]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr) (&ForkJoinContextID)); eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr) (&OperationType)); eventPayload[4].Size = sizeof(long); eventPayload[4].DataPointer = ((IntPtr) (&InclusiveFrom)); eventPayload[5].Size = sizeof(long); eventPayload[5].DataPointer = ((IntPtr) (&ExclusiveTo)); WriteEventCore(PARALLELLOOPBEGIN_ID, 6, eventPayload); } } } #endregion #region ParallelLoopEnd /// <summary> /// Denotes the end of a Parallel.For or Parallel.ForEach loop. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The loop ID.</param> /// <param name="TotalIterations">the total number of iterations processed.</param> [SecuritySafeCritical] [Event(PARALLELLOOPEND_ID, Level = EventLevel.Informational, Task = TplEtwProvider.Tasks.Loop, Opcode = EventOpcode.Stop)] public void ParallelLoopEnd( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID, long TotalIterations) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Parallel)) { // There is no explicit WriteEvent() overload matching this event's fields. // Therefore calling WriteEvent() would hit the "params" overload, which leads to an object allocation every time this event is fired. // To prevent that problem we will call WriteEventCore(), which works with a stack based EventData array populated with the event fields unsafe { EventData* eventPayload = stackalloc EventData[4]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr) (&ForkJoinContextID)); eventPayload[3].Size = sizeof(long); eventPayload[3].DataPointer = ((IntPtr) (&TotalIterations)); WriteEventCore(PARALLELLOOPEND_ID, 4, eventPayload); } } } #endregion #region ParallelInvokeBegin /// <summary>Denotes the entry point for a Parallel.Invoke call.</summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The invoke ID.</param> /// <param name="OperationType">The kind of fork/join operation.</param> /// <param name="ActionCount">The number of actions being invoked.</param> [SecuritySafeCritical] [Event(PARALLELINVOKEBEGIN_ID, Level = EventLevel.Informational, ActivityOptions=EventActivityOptions.Recursive, Task = TplEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Start)] public void ParallelInvokeBegin( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID, ForkJoinOperationType OperationType, // PFX_FORKJOIN_COMMON_EVENT_HEADER int ActionCount) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Parallel)) { // There is no explicit WriteEvent() overload matching this event's fields. // Therefore calling WriteEvent() would hit the "params" overload, which leads to an object allocation every time this event is fired. // To prevent that problem we will call WriteEventCore(), which works with a stack based EventData array populated with the event fields unsafe { EventData* eventPayload = stackalloc EventData[5]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr) (&ForkJoinContextID)); eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr) (&OperationType)); eventPayload[4].Size = sizeof(int); eventPayload[4].DataPointer = ((IntPtr) (&ActionCount)); WriteEventCore(PARALLELINVOKEBEGIN_ID, 5, eventPayload); } } } #endregion #region ParallelInvokeEnd /// <summary> /// Denotes the exit point for a Parallel.Invoke call. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The invoke ID.</param> [Event(PARALLELINVOKEEND_ID, Level = EventLevel.Informational, Task = TplEtwProvider.Tasks.Invoke, Opcode = EventOpcode.Stop)] public void ParallelInvokeEnd( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.Parallel)) { WriteEvent(PARALLELINVOKEEND_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID); } } #endregion #region ParallelFork /// <summary> /// Denotes the start of an individual task that's part of a fork/join context. /// Before this event is fired, the start of the new fork/join context will be marked /// with another event that declares a unique context ID. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The invoke ID.</param> [Event(PARALLELFORK_ID, Level = EventLevel.Verbose, ActivityOptions=EventActivityOptions.Recursive, Task = TplEtwProvider.Tasks.ForkJoin, Opcode = EventOpcode.Start)] public void ParallelFork( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID) { if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Parallel)) { WriteEvent(PARALLELFORK_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID); } } #endregion #region ParallelJoin /// <summary> /// Denotes the end of an individual task that's part of a fork/join context. /// This should match a previous ParallelFork event with a matching "OriginatingTaskID" /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="ForkJoinContextID">The invoke ID.</param> [Event(PARALLELJOIN_ID, Level = EventLevel.Verbose, Task = TplEtwProvider.Tasks.ForkJoin, Opcode = EventOpcode.Stop)] public void ParallelJoin( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ForkJoinContextID) { if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Parallel)) { WriteEvent(PARALLELJOIN_ID, OriginatingTaskSchedulerID, OriginatingTaskID, ForkJoinContextID); } } #endregion //----------------------------------------------------------------------------------- // // Task Events // // These are all verbose events, so we need to call IsEnabled(EventLevel.Verbose, ALL_KEYWORDS) // call. However since the IsEnabled(l,k) call is more expensive than IsEnabled(), we only want // to incur this cost when instrumentation is enabled. So the Task codepaths that call these // event functions still do the check for IsEnabled() #region TaskScheduled /// <summary> /// Fired when a task is queued to a TaskScheduler. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="CreatingTaskID">The task ID</param> /// <param name="TaskCreationOptions">The options used to create the task.</param> [SecuritySafeCritical] [Event(TASKSCHEDULED_ID, Task = Tasks.TaskScheduled, Version=1, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)] public void TaskScheduled( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, int CreatingTaskID, int TaskCreationOptions, int appDomain) { // IsEnabled() call is an inlined quick check that makes this very fast when provider is off if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[6]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr) (&TaskID)); eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr) (&CreatingTaskID)); eventPayload[4].Size = sizeof(int); eventPayload[4].DataPointer = ((IntPtr) (&TaskCreationOptions)); eventPayload[5].Size = sizeof(int); eventPayload[5].DataPointer = ((IntPtr) (&appDomain)); if (TasksSetActivityIds) { Guid childActivityId = CreateGuidForTaskID(TaskID); WriteEventWithRelatedActivityIdCore(TASKSCHEDULED_ID, &childActivityId, 6, eventPayload); } else WriteEventCore(TASKSCHEDULED_ID, 6, eventPayload); } } } #endregion #region TaskStarted /// <summary> /// Fired just before a task actually starts executing. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> [Event(TASKSTARTED_ID, Level = EventLevel.Informational, Keywords = Keywords.Tasks)] public void TaskStarted( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID) { if (IsEnabled(EventLevel.Informational, Keywords.Tasks)) WriteEvent(TASKSTARTED_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID); } #endregion #region TaskCompleted /// <summary> /// Fired right after a task finished executing. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="IsExceptional">Whether the task completed due to an error.</param> [SecuritySafeCritical] [Event(TASKCOMPLETED_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.TaskStops)] public void TaskCompleted( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, bool IsExceptional) { if (IsEnabled(EventLevel.Informational, Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[4]; Int32 isExceptionalInt = IsExceptional ? 1 : 0; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr) (&TaskID)); eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr) (&isExceptionalInt)); WriteEventCore(TASKCOMPLETED_ID, 4, eventPayload); } } } #endregion #region TaskWaitBegin /// <summary> /// Fired when starting to wait for a taks's completion explicitly or implicitly. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> /// <param name="Behavior">Configured behavior for the wait.</param> /// <param name="ContinueWithTaskID">If known, if 'TaskID' has a 'continueWith' task, mention give its ID here. /// 0 means unknown. This allows better visualization of the common sequential chaining case.</param> /// </summary> [SecuritySafeCritical] [Event(TASKWAITBEGIN_ID, Version=3, Task = TplEtwProvider.Tasks.TaskWait, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)] public void TaskWaitBegin( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID, TaskWaitBehavior Behavior, int ContinueWithTaskID, int appDomain) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[5]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr)(&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr)(&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr)(&TaskID)); eventPayload[3].Size = sizeof(int); eventPayload[3].DataPointer = ((IntPtr)(&Behavior)); eventPayload[4].Size = sizeof(int); eventPayload[4].DataPointer = ((IntPtr)(&ContinueWithTaskID)); if (TasksSetActivityIds) { Guid childActivityId = CreateGuidForTaskID(TaskID); WriteEventWithRelatedActivityIdCore(TASKWAITBEGIN_ID, &childActivityId, 5, eventPayload); } else WriteEventCore(TASKWAITBEGIN_ID, 5, eventPayload); } } } #endregion /// <summary> /// Fired when the wait for a tasks completion returns. /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> [Event(TASKWAITEND_ID, Level = EventLevel.Verbose, Keywords = Keywords.Tasks)] public void TaskWaitEnd( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int TaskID) { // Log an event if indicated. if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks)) WriteEvent(TASKWAITEND_ID, OriginatingTaskSchedulerID, OriginatingTaskID, TaskID); } /// <summary> /// Fired when the the work (method) associated with a TaskWaitEnd completes /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> [Event(TASKWAITCONTINUATIONCOMPLETE_ID, Level = EventLevel.Verbose, Keywords = Keywords.TaskStops)] public void TaskWaitContinuationComplete(int TaskID) { // Log an event if indicated. if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks)) WriteEvent(TASKWAITCONTINUATIONCOMPLETE_ID, TaskID); } /// <summary> /// Fired when the the work (method) associated with a TaskWaitEnd completes /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The task ID.</param> [Event(TASKWAITCONTINUATIONSTARTED_ID, Level = EventLevel.Verbose, Keywords = Keywords.TaskStops)] public void TaskWaitContinuationStarted(int TaskID) { // Log an event if indicated. if (IsEnabled() && IsEnabled(EventLevel.Verbose, Keywords.Tasks)) WriteEvent(TASKWAITCONTINUATIONSTARTED_ID, TaskID); } /// <summary> /// Fired when the an asynchronous continuation for a task is scheduled /// </summary> /// <param name="OriginatingTaskSchedulerID">The scheduler ID.</param> /// <param name="OriginatingTaskID">The task ID.</param> /// <param name="TaskID">The activityId for the continuation.</param> [SecuritySafeCritical] [Event(AWAITTASKCONTINUATIONSCHEDULED_ID, Task = Tasks.AwaitTaskContinuationScheduled, Opcode = EventOpcode.Send, Level = EventLevel.Informational, Keywords = Keywords.TaskTransfer|Keywords.Tasks)] public void AwaitTaskContinuationScheduled( int OriginatingTaskSchedulerID, int OriginatingTaskID, // PFX_COMMON_EVENT_HEADER int ContinuwWithTaskId) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.TaskTransfer|Keywords.Tasks)) { unsafe { EventData* eventPayload = stackalloc EventData[3]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr) (&OriginatingTaskSchedulerID)); eventPayload[1].Size = sizeof(int); eventPayload[1].DataPointer = ((IntPtr) (&OriginatingTaskID)); eventPayload[2].Size = sizeof(int); eventPayload[2].DataPointer = ((IntPtr) (&ContinuwWithTaskId)); if (TasksSetActivityIds) { Guid continuationActivityId = CreateGuidForTaskID(ContinuwWithTaskId); WriteEventWithRelatedActivityIdCore(AWAITTASKCONTINUATIONSCHEDULED_ID, &continuationActivityId, 3, eventPayload); } else WriteEventCore(AWAITTASKCONTINUATIONSCHEDULED_ID, 3, eventPayload); } } } [SecuritySafeCritical] [Event(TRACEOPERATIONSTART_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationBegin(int TaskID, string OperationName, long RelatedContext) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) { unsafe { fixed(char* operationNamePtr = OperationName) { EventData* eventPayload = stackalloc EventData[3]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr) (&TaskID)); eventPayload[1].Size = ((OperationName.Length + 1) * 2); eventPayload[1].DataPointer = ((IntPtr) operationNamePtr); eventPayload[2].Size = sizeof(long); eventPayload[2].DataPointer = ((IntPtr) (&RelatedContext)); WriteEventCore(TRACEOPERATIONSTART_ID, 3, eventPayload); } } } } [SecuritySafeCritical] [Event(TRACEOPERATIONRELATION_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityRelation)] public void TraceOperationRelation(int TaskID, CausalityRelation Relation) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityRelation)) WriteEvent(TRACEOPERATIONRELATION_ID, TaskID,(int) Relation); // optmized overload for this exists } [SecuritySafeCritical] [Event(TRACEOPERATIONSTOP_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalityOperation)] public void TraceOperationEnd(int TaskID, AsyncCausalityStatus Status) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalityOperation)) WriteEvent(TRACEOPERATIONSTOP_ID, TaskID,(int) Status); // optmized overload for this exists } [SecuritySafeCritical] [Event(TRACESYNCHRONOUSWORKSTART_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkBegin(int TaskID, CausalitySynchronousWork Work) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) WriteEvent(TRACESYNCHRONOUSWORKSTART_ID, TaskID,(int) Work); // optmized overload for this exists } [SecuritySafeCritical] [Event(TRACESYNCHRONOUSWORKSTOP_ID, Version=1, Level = EventLevel.Informational, Keywords = Keywords.AsyncCausalitySynchronousWork)] public void TraceSynchronousWorkEnd(CausalitySynchronousWork Work) { if (IsEnabled() && IsEnabled(EventLevel.Informational, Keywords.AsyncCausalitySynchronousWork)) { unsafe { EventData* eventPayload = stackalloc EventData[1]; eventPayload[0].Size = sizeof(int); eventPayload[0].DataPointer = ((IntPtr) (&Work)); WriteEventCore(TRACESYNCHRONOUSWORKSTOP_ID, 1, eventPayload); } } } [NonEvent, System.Security.SecuritySafeCritical] unsafe public void RunningContinuation(int TaskID, object Object) { RunningContinuation(TaskID, (long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref Object))); } [Event(20, Keywords = Keywords.Debug)] private void RunningContinuation(int TaskID, long Object) { if (Debug) WriteEvent(20, TaskID, Object); } [NonEvent, System.Security.SecuritySafeCritical] unsafe public void RunningContinuationList(int TaskID, int Index, object Object) { RunningContinuationList(TaskID, Index, (long) *((void**) JitHelpers.UnsafeCastToStackPointer(ref Object))); } [Event(21, Keywords = Keywords.Debug)] public void RunningContinuationList(int TaskID, int Index, long Object) { if (Debug) WriteEvent(21, TaskID, Index, Object); } [Event(22, Keywords = Keywords.Debug)] public void DebugMessage(string Message) { WriteEvent(22, Message); } [Event(23, Keywords = Keywords.Debug)] public void DebugFacilityMessage(string Facility, string Message) { WriteEvent(23, Facility, Message); } [Event(24, Keywords = Keywords.Debug)] public void DebugFacilityMessage1(string Facility, string Message, string Value1) { WriteEvent(24, Facility, Message, Value1); } [Event(25, Keywords = Keywords.DebugActivityId)] public void SetActivityId(Guid NewId) { if (DebugActivityId) WriteEvent(25, NewId); } [Event(26, Keywords = Keywords.Debug)] public void NewID(int TaskID) { if (Debug) WriteEvent(26, TaskID); } /// <summary> /// Activity IDs are GUIDS but task IDS are integers (and are not unique across appdomains /// This routine creates a process wide unique GUID given a task ID /// </summary> internal static Guid CreateGuidForTaskID(int taskID) { // The thread pool generated a process wide unique GUID from a task GUID by // using the taskGuid, the appdomain ID, and 8 bytes of 'randomization' chosen by // using the last 8 bytes as the provider GUID for this provider. // These were generated by CreateGuid, and are reasonably random (and thus unlikley to collide uint pid = EventSource.s_currentPid; int appDomainID = System.Threading.Thread.GetDomainID(); return new Guid(taskID, (short) appDomainID , (short) (appDomainID >> 16), (byte)pid, (byte)(pid >> 8), (byte)(pid >> 16), (byte)(pid >> 24), 0xff, 0xdc, 0xd7, 0xb5); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Pathoschild.Stardew.Common; using Pathoschild.Stardew.Common.UI; using Pathoschild.Stardew.LookupAnything.Framework.Lookups; using StardewModdingAPI; using StardewValley; using StardewValley.Menus; namespace Pathoschild.Stardew.LookupAnything.Components { /// <summary>A UI which lets the player search for subjects.</summary> internal class SearchMenu : BaseMenu, IScrollableMenu, IDisposable { /********* ** Properties *********/ /// <summary>Show a lookup menu.</summary> private readonly Action<ISubject> ShowLookup; /// <summary>Encapsulates logging and monitoring.</summary> private readonly IMonitor Monitor; /// <summary>The aspect ratio of the page background.</summary> private readonly Vector2 AspectRatio = new(Sprites.Letter.Sprite.Width, Sprites.Letter.Sprite.Height); /// <summary>The clickable 'scroll up' icon.</summary> private readonly ClickableTextureComponent ScrollUpButton; /// <summary>The clickable 'scroll down' icon.</summary> private readonly ClickableTextureComponent ScrollDownButton; /// <summary>The amount to scroll long content on each up/down scroll.</summary> private readonly int ScrollAmount; /// <summary>The maximum pixels to scroll.</summary> private int MaxScroll; /// <summary>The number of pixels to scroll.</summary> private int CurrentScroll; /// <summary>The subjects available for searching indexed by name.</summary> private readonly ILookup<string, ISubject> SearchLookup; /// <summary>The search input box.</summary> private readonly SearchTextBox SearchTextbox; /// <summary>The current search results.</summary> private IEnumerable<SearchResultComponent> SearchResults = Enumerable.Empty<SearchResultComponent>(); /// <summary>The pixel area containing search results.</summary> private Rectangle SearchResultArea; /// <summary>The spacing around the search result area.</summary> private readonly int SearchResultGutter = 15; /// <summary>The spacing around the scroll buttons.</summary> private readonly int ScrollButtonGutter = 15; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="searchSubjects">The subjects available to search.</param> /// <param name="showLookup">Show a lookup menu.</param> /// <param name="monitor">Encapsulates logging and monitoring.</param> /// <param name="scroll">The amount to scroll long content on each up/down scroll.</param> public SearchMenu(IEnumerable<ISubject> searchSubjects, Action<ISubject> showLookup, IMonitor monitor, int scroll) { // save data this.ShowLookup = showLookup; this.Monitor = monitor; this.SearchLookup = searchSubjects.ToLookup(p => p.Name, StringComparer.OrdinalIgnoreCase); this.ScrollAmount = scroll; // create components this.SearchTextbox = new SearchTextBox(Game1.smallFont, Color.Black); this.ScrollUpButton = new ClickableTextureComponent(Rectangle.Empty, CommonSprites.Icons.Sheet, CommonSprites.Icons.UpArrow, 1); this.ScrollDownButton = new ClickableTextureComponent(Rectangle.Empty, CommonSprites.Icons.Sheet, CommonSprites.Icons.DownArrow, 1); // initialise this.UpdateLayout(); this.SearchTextbox.Select(); this.SearchTextbox.OnChanged += (_, text) => this.ReceiveSearchTextboxChanged(text); } /**** ** Events ****/ /// <summary>The method invoked when the player left-clicks on the lookup UI.</summary> /// <param name="x">The X-position of the cursor.</param> /// <param name="y">The Y-position of the cursor.</param> /// <param name="playSound">Whether to enable sound.</param> public override void receiveLeftClick(int x, int y, bool playSound = true) { // search box if (this.SearchTextbox.Bounds.Contains(x, y)) this.SearchTextbox.Select(); // scroll up or down else if (this.ScrollUpButton.containsPoint(x, y)) this.ScrollUp(); else if (this.ScrollDownButton.containsPoint(x, y)) this.ScrollDown(); // search matches else if (this.SearchResultArea.Contains(x, y)) { foreach (SearchResultComponent match in this.GetResultsPossiblyOnScreen()) { if (match.containsPoint(x, y)) { this.ShowLookup(match.Subject); Game1.playSound("coin"); return; } } } } /// <summary>The method invoked when the player presses an input button.</summary> /// <param name="key">The pressed input.</param> public override void receiveKeyPress(Keys key) { // deliberately avoid calling base, which may let another key close the menu if (key.Equals(Keys.Escape)) this.exitThisMenu(); } /// <summary>The method invoked when the player scrolls the mouse wheel on the lookup UI.</summary> /// <param name="direction">The scroll direction.</param> public override void receiveScrollWheelAction(int direction) { if (direction > 0) // positive number scrolls content up this.ScrollUp(); else this.ScrollDown(); } /// <summary>The method called when the game window changes size.</summary> /// <param name="oldBounds">The former viewport.</param> /// <param name="newBounds">The new viewport.</param> public override void gameWindowSizeChanged(Rectangle oldBounds, Rectangle newBounds) { this.UpdateLayout(); } /**** ** Methods ****/ /// <summary>Render the UI.</summary> /// <param name="spriteBatch">The sprite batch being drawn.</param> public override void draw(SpriteBatch spriteBatch) { // calculate dimensions int x = this.xPositionOnScreen; int y = this.yPositionOnScreen; int gutter = this.SearchResultGutter; float leftOffset = gutter; float topOffset = gutter; float contentHeight = this.SearchResultArea.Height; // get font SpriteFont font = Game1.smallFont; float lineHeight = font.MeasureString("ABC").Y; float spaceWidth = DrawHelper.GetSpaceWidth(font); // draw background // (This uses a separate sprite batch because it needs to be drawn before the // foreground batch, and we can't use the foreground batch because the background is // outside the clipping area.) using (SpriteBatch backgroundBatch = new SpriteBatch(Game1.graphics.GraphicsDevice)) { backgroundBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp); backgroundBatch.DrawSprite(Sprites.Letter.Sheet, Sprites.Letter.Sprite, x, y, scale: this.width / (float)Sprites.Letter.Sprite.Width); backgroundBatch.End(); } // draw foreground // (This uses a separate sprite batch to set a clipping area for scrolling.) using (SpriteBatch contentBatch = new SpriteBatch(Game1.graphics.GraphicsDevice)) { GraphicsDevice device = Game1.graphics.GraphicsDevice; Rectangle prevScissorRectangle = device.ScissorRectangle; try { // begin draw device.ScissorRectangle = this.SearchResultArea; contentBatch.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.PointClamp, null, new RasterizerState { ScissorTestEnable = true }); // scroll view this.CurrentScroll = Math.Max(0, this.CurrentScroll); // don't scroll past top this.CurrentScroll = Math.Min(this.MaxScroll, this.CurrentScroll); // don't scroll past bottom topOffset -= this.CurrentScroll; // scrolled down == move text up // draw fields float wrapWidth = this.width - leftOffset - gutter; { Vector2 nameSize = contentBatch.DrawTextBlock(font, "Search", new Vector2(x + leftOffset, y + topOffset), wrapWidth, bold: true); Vector2 typeSize = contentBatch.DrawTextBlock(font, "(Lookup Anything)", new Vector2(x + leftOffset + nameSize.X + spaceWidth, y + topOffset), wrapWidth); topOffset += Math.Max(nameSize.Y, typeSize.Y); this.SearchTextbox.Bounds = new Rectangle(x: x + (int)leftOffset, y: y + (int)topOffset, width: (int)wrapWidth, height: this.SearchTextbox.Bounds.Height); this.SearchTextbox.Draw(contentBatch); topOffset += this.SearchTextbox.Bounds.Height; int mouseX = Game1.getMouseX(); int mouseY = Game1.getMouseY(); bool reachedViewport = false; bool reachedBottomOfViewport = false; bool isCursorInSearchArea = this.SearchResultArea.Contains(mouseX, mouseY) && !this.ScrollUpButton.containsPoint(mouseX, mouseY) && !this.ScrollDownButton.containsPoint(mouseX, mouseY); foreach (SearchResultComponent result in this.SearchResults) { if (!reachedViewport || !reachedBottomOfViewport) { if (this.IsResultPossiblyOnScreen(result)) { reachedViewport = true; bool isHighlighted = isCursorInSearchArea && result.containsPoint(mouseX, mouseY); result.Draw(contentBatch, new Vector2(x + leftOffset, y + topOffset), (int)wrapWidth, isHighlighted); } else if (reachedViewport) reachedBottomOfViewport = true; } topOffset += SearchResultComponent.FixedHeight; } // draw spacer topOffset += lineHeight; } // update max scroll this.MaxScroll = Math.Max(0, (int)(topOffset - contentHeight + this.CurrentScroll)); // draw scroll icons if (this.MaxScroll > 0 && this.CurrentScroll > 0) this.ScrollUpButton.draw(spriteBatch); if (this.MaxScroll > 0 && this.CurrentScroll < this.MaxScroll) this.ScrollDownButton.draw(spriteBatch); // end draw contentBatch.End(); } catch (ArgumentException ex) when (!BaseMenu.UseSafeDimensions && ex.ParamName == "value" && ex.StackTrace.Contains("Microsoft.Xna.Framework.Graphics.GraphicsDevice.set_ScissorRectangle")) { this.Monitor.Log("The viewport size seems to be inaccurate. Enabling compatibility mode; lookup menu may be misaligned.", LogLevel.Warn); this.Monitor.Log(ex.ToString()); BaseMenu.UseSafeDimensions = true; this.UpdateLayout(); } finally { device.ScissorRectangle = prevScissorRectangle; } } // draw mouse cursor this.drawMouse(Game1.spriteBatch); } /// <summary>Release all resources.</summary> public void Dispose() { this.SearchTextbox.Dispose(); } /********* ** Private methods *********/ /// <inheritdoc /> public void ScrollUp(int? amount = null) { this.CurrentScroll -= amount ?? this.ScrollAmount; } /// <inheritdoc /> public void ScrollDown(int? amount = null) { this.CurrentScroll += amount ?? this.ScrollAmount; } /// <summary>Get the search results that may be on screen.</summary> private IEnumerable<SearchResultComponent> GetResultsPossiblyOnScreen() { bool reachedViewport = false; foreach (var result in this.SearchResults) { if (!this.IsResultPossiblyOnScreen(result)) { if (reachedViewport) yield break; continue; } reachedViewport = true; yield return result; } } /// <summary>Get whether a search result may be on screen.</summary> /// <param name="result">The search result.</param> private bool IsResultPossiblyOnScreen(SearchResultComponent result) { // This is a simple approximation to optimize large lists. It doesn't need to be // precise, as long as it can't have false positives. const int resultHeight = SearchResultComponent.FixedHeight; int index = result.Index; int minY = (index - 3) * resultHeight; int maxY = (index + 3) * resultHeight; return maxY > this.CurrentScroll && minY < this.CurrentScroll + this.height; } /// <summary>The method invoked when the player changes the search text.</summary> /// <param name="search">The new search text.</param> private void ReceiveSearchTextboxChanged(string search) { // get search words string[] words = (search ?? "").Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (!words.Any()) { this.SearchResults = Enumerable.Empty<SearchResultComponent>(); return; } // get matches this.SearchResults = this.SearchLookup .Where(entry => words.All(word => entry.Key.IndexOf(word, StringComparison.OrdinalIgnoreCase) >= 0)) .SelectMany(entry => entry) .OrderBy(subject => subject.Name, StringComparer.OrdinalIgnoreCase) .Select((subject, index) => new SearchResultComponent(subject, index)) .ToArray(); } /// <summary>Update the layout dimensions based on the current game scale.</summary> private void UpdateLayout() { Point viewport = this.GetViewportSize(); // update size this.width = Math.Min(Game1.tileSize * 14, viewport.X); this.height = Math.Min((int)(this.AspectRatio.Y / this.AspectRatio.X * this.width), viewport.Y); // update position Vector2 origin = Utility.getTopLeftPositionForCenteringOnScreen(this.width, this.height); int x = this.xPositionOnScreen = (int)origin.X; int y = this.yPositionOnScreen = (int)origin.Y; int searchGutter = this.SearchResultGutter; float contentWidth = this.width - searchGutter * 2; float contentHeight = this.height - searchGutter * 2; // update scissor rectangle for search result area this.SearchResultArea = new Rectangle(x + searchGutter, y + searchGutter, (int)contentWidth, (int)contentHeight); // update up/down buttons int scrollGutter = this.ScrollButtonGutter; this.ScrollUpButton.bounds = new Rectangle(x + scrollGutter, (int)(y + contentHeight - CommonSprites.Icons.UpArrow.Height - scrollGutter - CommonSprites.Icons.DownArrow.Height), CommonSprites.Icons.UpArrow.Height, CommonSprites.Icons.UpArrow.Width); this.ScrollDownButton.bounds = new Rectangle(x + scrollGutter, (int)(y + contentHeight - CommonSprites.Icons.DownArrow.Height), CommonSprites.Icons.DownArrow.Height, CommonSprites.Icons.DownArrow.Width); } } }
using FluentAssertions; using Microsoft.EntityFrameworkCore; using Moq; using Ritter.Domain; using Ritter.Infra.Crosscutting.Specifications; using Ritter.Infra.Data.Tests.Extensions; using Ritter.Infra.Data.Tests.Mocks; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Ritter.Infra.Data.Tests.Repositories { public class Repository_Remove { [Fact] public void CallSaveChangesSuccessfullyGivenOneEntity() { List<Test> mockedTests = new List<Test>(); Mock<DbSet<Test>> mockDbSet = mockedTests .AsQueryable() .BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); mockUnitOfWork.Setup(p => p.SaveChanges()); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); Test test = new Test(); testRepository.Remove(test); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); mockUnitOfWork.Verify(x => x.SaveChanges(), Times.Once); } [Fact] public void CallSaveChangesSuccessfullyGivenOneEntityAsync() { List<Test> mockedTests = new List<Test>(); Mock<DbSet<Test>> mockDbSet = mockedTests .AsQueryable() .BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); mockUnitOfWork.Setup(p => p.SaveChangesAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(It.IsAny<int>())); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); Test test = new Test(); testRepository.RemoveAsync(test).GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); mockUnitOfWork.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once); } [Fact] public void ThrowsArgumentNullExceptionGivenNullEntity() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.Remove((Test)null); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("entity"); } [Fact] public void ThrowsArgumentNullExceptionGivenNullEntityAsync() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.RemoveAsync((Test)null).GetAwaiter().GetResult(); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("entity"); } [Fact] public void CallSaveChangesSuccessfullyGivenManyEntities() { List<Test> mockedTests = new List<Test>(); Mock<DbSet<Test>> mockDbSet = mockedTests .AsQueryable() .BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); mockUnitOfWork.Setup(p => p.SaveChanges()); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); List<Test> tests = MockTests(); testRepository.Remove(tests); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); mockUnitOfWork.Verify(x => x.SaveChanges(), Times.Once); } [Fact] public void CallSaveChangesSuccessfullyGivenManyEntitiesAsync() { List<Test> mockedTests = new List<Test>(); Mock<DbSet<Test>> mockDbSet = mockedTests .AsQueryable() .BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); mockUnitOfWork.Setup(p => p.SaveChangesAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(It.IsAny<int>())); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); List<Test> tests = MockTests(); testRepository.RemoveAsync(tests).GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Once); mockUnitOfWork.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once); } [Fact] public void ThrowsArgumentNullExceptionGivenNullEntityEnumerable() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.Remove((IEnumerable<Test>)null); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("entities"); } [Fact] public void ThrowsArgumentNullExceptionGivenNullEntityEnumerableAsync() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.RemoveAsync((IEnumerable<Test>)null).GetAwaiter().GetResult(); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("entities"); } [Fact] public void CallSaveChangesSuccessfullyGivenSpecification() { List<Test> mockedTests = MockTests(); Mock<DbSet<Test>> mockDbSet = mockedTests .AsQueryable() .BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); mockUnitOfWork.Setup(p => p.SaveChanges()); ISpecification<Test> spec = new DirectSpecification<Test>(p => p.Id == 1); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.Remove(spec); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Exactly(2)); mockUnitOfWork.Verify(x => x.SaveChanges(), Times.Once); } [Fact] public void CallSaveChangesSuccessfullyGivenSpecificationAsync() { List<Test> mockedTests = MockTests(); Mock<DbSet<Test>> mockDbSet = mockedTests .AsQueryable() .BuildMockDbSet(); Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); mockUnitOfWork.Setup(p => p.Set<Test>()).Returns(mockDbSet.Object); mockUnitOfWork.Setup(p => p.SaveChangesAsync(It.IsAny<CancellationToken>())).Returns(Task.FromResult(It.IsAny<int>())); ISpecification<Test> spec = new DirectSpecification<Test>(p => p.Id == 1); IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.RemoveAsync(spec).GetAwaiter().GetResult(); mockUnitOfWork.Verify(x => x.Set<Test>(), Times.Exactly(2)); mockUnitOfWork.Verify(x => x.SaveChangesAsync(It.IsAny<CancellationToken>()), Times.Once); } [Fact] public void ThrowsArgumentNullExceptionGivenNullSpecification() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.Remove((ISpecification<Test>)null); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("specification"); } [Fact] public void ThrowsArgumentNullExceptionGivenNullSpecificationAsync() { Mock<IEFUnitOfWork> mockUnitOfWork = new Mock<IEFUnitOfWork>(); Action act = () => { IRepository<Test> testRepository = new GenericTestRepository(mockUnitOfWork.Object); testRepository.RemoveAsync((ISpecification<Test>)null).GetAwaiter().GetResult(); }; act.Should().Throw<ArgumentNullException>().And.ParamName.Should().Be("specification"); } private static List<Test> MockTests(int count) { List<Test> tests = new List<Test>(); for (int i = 1; i <= count; i++) { tests.Add(new Test(i)); } return tests; } private static List<Test> MockTests() { return MockTests(5); } } }
//Uncomment the next line to enable debugging (also uncomment it in AstarPath.cs) //#define ProfileAstar //#define UNITY_PRO_PROFILER //Requires ProfileAstar, profiles section of astar code which will show up in the Unity Pro Profiler. using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.Profiling; namespace Pathfinding { public class AstarProfiler { public class ProfilePoint { //public DateTime lastRecorded; //public TimeSpan totalTime; public System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); public int totalCalls; public long tmpBytes; public long totalBytes; } private static Dictionary<string, ProfilePoint> profiles = new Dictionary<string, ProfilePoint>(); private static DateTime startTime = DateTime.UtcNow; public static ProfilePoint[] fastProfiles; public static string[] fastProfileNames; private AstarProfiler() { } [System.Diagnostics.Conditional ("ProfileAstar")] public static void InitializeFastProfile (string[] profileNames) { fastProfileNames = new string[profileNames.Length+2]; Array.Copy (profileNames,fastProfileNames, profileNames.Length); fastProfileNames[fastProfileNames.Length-2] = "__Control1__"; fastProfileNames[fastProfileNames.Length-1] = "__Control2__"; fastProfiles = new ProfilePoint[fastProfileNames.Length]; for (int i=0;i<fastProfiles.Length;i++) fastProfiles[i] = new ProfilePoint(); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void StartFastProfile(int tag) { //profiles.TryGetValue(tag, out point); fastProfiles[tag].watch.Start();//lastRecorded = DateTime.UtcNow; } [System.Diagnostics.Conditional ("ProfileAstar")] public static void EndFastProfile(int tag) { /*if (!profiles.ContainsKey(tag)) { Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); return; }*/ ProfilePoint point = fastProfiles[tag]; point.totalCalls++; point.watch.Stop (); //DateTime now = DateTime.UtcNow; //point.totalTime += now - point.lastRecorded; //fastProfiles[tag] = point; } [System.Diagnostics.Conditional ("UNITY_PRO_PROFILER")] public static void EndProfile () { Profiler.EndSample (); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void StartProfile(string tag) { //Console.WriteLine ("Profile Start - " + tag); ProfilePoint point; profiles.TryGetValue(tag, out point); if (point == null) { point = new ProfilePoint(); profiles[tag] = point; } point.tmpBytes = System.GC.GetTotalMemory (false); point.watch.Start(); //point.lastRecorded = DateTime.UtcNow; //Debug.Log ("Starting " + tag); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void EndProfile(string tag) { if (!profiles.ContainsKey(tag)) { Debug.LogError("Can only end profiling for a tag which has already been started (tag was " + tag + ")"); return; } //Console.WriteLine ("Profile End - " + tag); //DateTime now = DateTime.UtcNow; ProfilePoint point = profiles[tag]; //point.totalTime += now - point.lastRecorded; ++point.totalCalls; point.watch.Stop(); point.totalBytes += System.GC.GetTotalMemory (false) - point.tmpBytes; //profiles[tag] = point; //Debug.Log ("Ending " + tag); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void Reset() { profiles.Clear(); startTime = DateTime.UtcNow; if (fastProfiles != null) { for (int i=0;i<fastProfiles.Length;i++) { fastProfiles[i] = new ProfilePoint (); } } } [System.Diagnostics.Conditional ("ProfileAstar")] public static void PrintFastResults() { StartFastProfile (fastProfiles.Length-2); for (int i=0;i<1000;i++) { StartFastProfile (fastProfiles.Length-1); EndFastProfile (fastProfiles.Length-1); } EndFastProfile (fastProfiles.Length-2); double avgOverhead = fastProfiles[fastProfiles.Length-2].watch.Elapsed.TotalMilliseconds / 1000.0; TimeSpan endTime = DateTime.UtcNow - startTime; System.Text.StringBuilder output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); output.Append ("Name | Total Time | Total Calls | Avg/Call | Bytes"); //foreach(KeyValuePair<string, ProfilePoint> pair in profiles) for (int i=0;i<fastProfiles.Length;i++) { string name = fastProfileNames[i]; ProfilePoint value = fastProfiles[i]; int totalCalls = value.totalCalls; double totalTime = value.watch.Elapsed.TotalMilliseconds - avgOverhead*totalCalls; if (totalCalls < 1) continue; output.Append ("\n").Append(name.PadLeft(10)).Append("| "); output.Append (totalTime.ToString("0.0 ").PadLeft (10)).Append(value.watch.Elapsed.TotalMilliseconds.ToString("(0.0)").PadLeft(10)).Append ("| "); output.Append (totalCalls.ToString().PadLeft (10)).Append ("| "); output.Append ((totalTime / totalCalls).ToString("0.000").PadLeft(10)); /* output.Append("\nProfile"); output.Append(name); output.Append(" took \t"); output.Append(totalTime.ToString("0.0")); output.Append(" ms to complete over "); output.Append(totalCalls); output.Append(" iteration"); if (totalCalls != 1) output.Append("s"); output.Append(", averaging \t"); output.Append((totalTime / totalCalls).ToString("0.000")); output.Append(" ms per call"); */ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } [System.Diagnostics.Conditional ("ProfileAstar")] public static void PrintResults() { TimeSpan endTime = DateTime.UtcNow - startTime; System.Text.StringBuilder output = new System.Text.StringBuilder(); output.Append("============================\n\t\t\t\tProfile results:\n============================\n"); int maxLength = 5; foreach(KeyValuePair<string, ProfilePoint> pair in profiles) { maxLength = Math.Max (pair.Key.Length,maxLength); } output.Append (" Name ".PadRight (maxLength)). Append("|").Append(" Total Time ".PadRight(20)). Append("|").Append(" Total Calls ".PadRight(20)). Append("|").Append(" Avg/Call ".PadRight(20)); foreach(KeyValuePair<string, ProfilePoint> pair in profiles) { double totalTime = pair.Value.watch.Elapsed.TotalMilliseconds; int totalCalls = pair.Value.totalCalls; if (totalCalls < 1) continue; string name = pair.Key; output.Append ("\n").Append(name.PadRight(maxLength)).Append("| "); output.Append (totalTime.ToString("0.0").PadRight (20)).Append ("| "); output.Append (totalCalls.ToString().PadRight (20)).Append ("| "); output.Append ((totalTime / totalCalls).ToString("0.000").PadRight(20)); output.Append (Pathfinding.AstarMath.FormatBytesBinary ((int)pair.Value.totalBytes).PadLeft(10)); /*output.Append("\nProfile "); output.Append(pair.Key); output.Append(" took "); output.Append(totalTime.ToString("0")); output.Append(" ms to complete over "); output.Append(totalCalls); output.Append(" iteration"); if (totalCalls != 1) output.Append("s"); output.Append(", averaging "); output.Append((totalTime / totalCalls).ToString("0.0")); output.Append(" ms per call");*/ } output.Append("\n\n============================\n\t\tTotal runtime: "); output.Append(endTime.TotalSeconds.ToString("F3")); output.Append(" seconds\n============================"); Debug.Log(output.ToString()); } } }
// Copyright (c) 2014 Christian Crowhurst. All rights reserved. // see LICENSE using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using CcAcca.CacheAbstraction.Statistics; namespace CcAcca.CacheAbstraction { /// <summary> /// Registry and management of long lived caches within an application /// </summary> public class CacheAdministator { #region Member Variables private readonly ConcurrentDictionary<ICache, bool> _allCaches = new ConcurrentDictionary<ICache, bool>(); private readonly Func<CacheStatistics> _cacheStatisticsFactory; #endregion /// <summary> /// Creates an instance of a <see cref="CacheAdministator"/> with default configuration applied /// </summary> /// <remarks> /// The instance returned, when asked to <see cref="Register"/> a cache will extend the supplied cache with /// a <see cref="IStatisticsCache"/> behaviour that will use <see cref="CacheStatistics.All"/> statics /// to record cache activity /// </remarks> public CacheAdministator() : this(() => CacheStatistics.All) {} public CacheAdministator(Func<CacheStatistics> cacheStatisticsFactory) { _cacheStatisticsFactory = cacheStatisticsFactory; } #region Properties public virtual IEnumerable<CacheInfo> AllDefaultCacheInfos { get { return AllCaches.Select(ToCacheInfo) .OrderBy(info => info.CacheId) .ThenByDescending(info => info.LastUse); } } private CacheInfo ToCacheInfo(ICache cache) { var statisticsCache = cache.As<IStatisticsCache>(); CacheStatistics statistics = statisticsCache != null ? statisticsCache.Statistics : CacheStatistics.Empty; var pausableCache = cache.As<IPausableCache>(); IDictionary<string, CacheItemAccessInfo> itemStatsDictionary = statistics.SafeGetValue<IDictionary<string, CacheItemAccessInfo>>(CacheStatisticsKeys.ItemAccess) ?? new Dictionary<string, CacheItemAccessInfo>(); ICollection<CacheItemAccessInfo> itemStats = itemStatsDictionary.Values; return new CacheInfo { CacheId = cache.Id.ToString(), CacheName = cache.Id.Name, InstanceName = cache.Id.InstanceName, IsPaused = pausableCache == null || pausableCache.IsPaused, IsPausable = pausableCache != null, ItemCount = cache.Count ?? 0, LastRead = statistics.SafeGetValue<DateTimeOffset?>(CacheStatisticsKeys.LastRead), LastFlush = statistics.SafeGetValue<DateTimeOffset?>(CacheStatisticsKeys.LastFlush), LastUse = statistics.SafeGetValue<DateTimeOffset?>(CacheStatisticsKeys.LastUse), LastWrite = statistics.SafeGetValue<DateTimeOffset?>(CacheStatisticsKeys.LastWrite), CacheHitRatio = statistics.SafeGetValue<decimal?>(CacheStatisticsKeys.CacheHitRatio), ItemAccessStatistics = itemStats }; } public virtual IEnumerable<ICache> AllCaches { get { return _allCaches.Keys; } } private IEnumerable<IPausableCache> PausableCaches { get { return _allCaches.Keys.CacheOfType<IPausableCache>(); } } #endregion public virtual bool Contains(ICache cache) { return _allCaches.ContainsKey(cache); } private ICache DecorateWithStatistics(ICache cache) { var builder = new CacheDecoratorChainBuilder(); cache = builder.AddDecorators(cache, new CacheDecoratorOptions { IsStatisticsOn = true, Statistics = _cacheStatisticsFactory() }); return cache; } public virtual void PauseAllSPausableCaches() { foreach (IPausableCache cache in PausableCaches) { cache.IsPaused = true; } } public virtual void StartAllPauableCaches() { foreach (IPausableCache cache in PausableCaches) { cache.IsPaused = false; } } public virtual void FlushAll() { foreach (ICache cache in _allCaches.Keys) { cache.Flush(); } } private bool SetIsPaused(CacheIdentity cacheId, bool isPaused) { IPausableCache cache = PausableCaches.SingleOrDefault(c => c.Id == cacheId); if (cache == null) return false; cache.IsPaused = isPaused; return true; } /// <summary> /// Starts the cache /// </summary> /// <param name="cacheId">The unique id of the instance to start</param> /// <returns> /// True if a <em>pausable</em> cache was found matching the name supplied /// </returns> /// <remarks> /// <c>true</c> will be returned even if the cache is already started /// </remarks> public virtual bool StartCache(CacheIdentity cacheId) { return SetIsPaused(cacheId, false); } /// <summary> /// Pauses the cache /// </summary> /// <param name="cacheId">The unique id of the instance to pause</param> /// <returns> /// True if a <em>pausable</em> cache was found matching the name supplied /// </returns> /// <remarks> /// <c>true</c> will be returned even if the cache is already paused /// </remarks> public virtual bool PauseCache(CacheIdentity cacheId) { return SetIsPaused(cacheId, true); } /// <summary> /// Register the <paramref name="cache"/> /// </summary> /// <exception cref="ArgumentException"> /// <returns>The <paramref name="cache"/> extended with <see cref="IStatisticsCache"/> behaviour</returns> /// Where a cache with the same <see cref="ICache.Id"/> has already been registered</exception> /// <remarks> /// Any cache registered will be extended with the <see cref="IStatisticsCache"/> behaviour if not already /// </remarks> public virtual ICache Register(ICache cache) { if (cache == null) throw new ArgumentNullException("cache"); //don't add special case null instances if (cache.As<INullCache>() != null) return cache; if (AllCaches.Any(c => c.Id == cache.Id)) { throw new ArgumentException(string.Format("A cache has already been registered with the Id '{0}'", cache.Id)); } bool hasExistingStatisticsDecorator = cache.IsDecoratedWith<IStatisticsCache>(); cache = DecorateWithStatistics(cache); _allCaches[cache] = !hasExistingStatisticsDecorator; return cache; } /// <summary> /// Unregisters the <paramref name="cache"/> from this administator /// </summary> /// <returns> /// The <paramref name="cache"/> minus <see cref="IStatisticsCache"/> behaviour previously added by this administrator /// </returns> /// <remarks> /// Any <see cref="IStatisticsCache"/> behaviour added to the <paramref name="cache"/> when it was registered /// with this administrator will be removed /// </remarks> public virtual ICache Unregister(ICache cache) { bool removeStatistics; bool found = _allCaches.TryRemove(cache, out removeStatistics); if (found && removeStatistics) { var chainBuilder = new CacheDecoratorChainBuilder(); return chainBuilder.RemoveDecorators(cache, new CacheDecoratorOptions {IsStatisticsOn = false}); } else { return cache; } } /// <summary> /// Deletes the item from the cache identified by it's <see cref="ICache.Id" /> /// </summary> /// <param name="cacheId">The unique id of the cache to remove item from </param> /// <param name="key">The key associated with the cached item to be removed</param> /// <returns>True if a cache was found matching the id supplied</returns> /// <remarks> /// <c>true</c> will be returned even if the item was not in the cache /// </remarks> /// <exception cref="ArgumentException">Cache is paused</exception> public bool RemoveItem(CacheIdentity cacheId, string key) { ICache cache = AllCaches.SingleOrDefault(c => c.Id == cacheId); if (cache == null) return false; if (cache.As<IPausableCache>() != null && cache.As<IPausableCache>().IsPaused) { throw new ArgumentException(string.Format("Cannot remove item from paused cache ('{0}')", cacheId)); } cache.Remove(key); return true; } static CacheAdministator() { DefaultInstance = new CacheAdministator(); } /// <summary> /// A default, globally available, instance of a <see cref="CacheAdministator"/> for use within an /// application /// </summary> public static CacheAdministator DefaultInstance { get; set; } } }
#if !UNITY_WINRT || UNITY_EDITOR || UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Utilities; using System.Globalization; using System.Text.RegularExpressions; using System.IO; namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides <see cref="JsonSchema"/> validation. /// </summary> public class JsonValidatingReader : JsonReader, IJsonLineInfo { private class SchemaScope { private readonly JTokenType _tokenType; private readonly IList<JsonSchemaModel> _schemas; private readonly Dictionary<string, bool> _requiredProperties; public string CurrentPropertyName { get; set; } public int ArrayItemCount { get; set; } public IList<JsonSchemaModel> Schemas { get { return _schemas; } } public Dictionary<string, bool> RequiredProperties { get { return _requiredProperties; } } public JTokenType TokenType { get { return _tokenType; } } public SchemaScope(JTokenType tokenType, IList<JsonSchemaModel> schemas) { _tokenType = tokenType; _schemas = schemas; _requiredProperties = schemas.SelectMany<JsonSchemaModel, string>(GetRequiredProperties).Distinct().ToDictionary(p => p, p => false); } private IEnumerable<string> GetRequiredProperties(JsonSchemaModel schema) { if (schema == null || schema.Properties == null) return Enumerable.Empty<string>(); return schema.Properties.Where(p => p.Value.Required).Select(p => p.Key); } } private readonly JsonReader _reader; private readonly Stack<SchemaScope> _stack; private JsonSchema _schema; private JsonSchemaModel _model; private SchemaScope _currentScope; /// <summary> /// Sets an event handler for receiving schema validation errors. /// </summary> public event ValidationEventHandler ValidationEventHandler; /// <summary> /// Gets the text value of the current Json token. /// </summary> /// <value></value> public override object Value { get { return _reader.Value; } } /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public override int Depth { get { return _reader.Depth; } } /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> /// <value></value> public override char QuoteChar { get { return _reader.QuoteChar; } protected internal set { } } /// <summary> /// Gets the type of the current Json token. /// </summary> /// <value></value> public override JsonToken TokenType { get { return _reader.TokenType; } } /// <summary> /// Gets The Common Language Runtime (CLR) type for the current Json token. /// </summary> /// <value></value> public override Type ValueType { get { return _reader.ValueType; } } private void Push(SchemaScope scope) { _stack.Push(scope); _currentScope = scope; } private SchemaScope Pop() { SchemaScope poppedScope = _stack.Pop(); _currentScope = (_stack.Count != 0) ? _stack.Peek() : null; return poppedScope; } private IEnumerable<JsonSchemaModel> CurrentSchemas { get { return _currentScope.Schemas; } } private IEnumerable<JsonSchemaModel> CurrentMemberSchemas { get { if (_currentScope == null) return new List<JsonSchemaModel>(new [] { _model }); if (_currentScope.Schemas == null || _currentScope.Schemas.Count == 0) return Enumerable.Empty<JsonSchemaModel>(); switch (_currentScope.TokenType) { case JTokenType.None: return _currentScope.Schemas; case JTokenType.Object: { if (_currentScope.CurrentPropertyName == null) throw new Exception("CurrentPropertyName has not been set on scope."); IList<JsonSchemaModel> schemas = new List<JsonSchemaModel>(); foreach (JsonSchemaModel schema in CurrentSchemas) { JsonSchemaModel propertySchema; if (schema.Properties != null && schema.Properties.TryGetValue(_currentScope.CurrentPropertyName, out propertySchema)) { schemas.Add(propertySchema); } if (schema.PatternProperties != null) { foreach (KeyValuePair<string, JsonSchemaModel> patternProperty in schema.PatternProperties) { if (Regex.IsMatch(_currentScope.CurrentPropertyName, patternProperty.Key)) { schemas.Add(patternProperty.Value); } } } if (schemas.Count == 0 && schema.AllowAdditionalProperties && schema.AdditionalProperties != null) schemas.Add(schema.AdditionalProperties); } return schemas; } case JTokenType.Array: { IList<JsonSchemaModel> schemas = new List<JsonSchemaModel>(); foreach (JsonSchemaModel schema in CurrentSchemas) { if (!CollectionUtils.IsNullOrEmpty(schema.Items)) { if (schema.Items.Count == 1) schemas.Add(schema.Items[0]); if (schema.Items.Count > (_currentScope.ArrayItemCount - 1)) schemas.Add(schema.Items[_currentScope.ArrayItemCount - 1]); } if (schema.AllowAdditionalProperties && schema.AdditionalProperties != null) schemas.Add(schema.AdditionalProperties); } return schemas; } case JTokenType.Constructor: return Enumerable.Empty<JsonSchemaModel>(); default: throw new ArgumentOutOfRangeException("TokenType", "Unexpected token type: {0}".FormatWith(CultureInfo.InvariantCulture, _currentScope.TokenType)); } } } private void RaiseError(string message, JsonSchemaModel schema) { IJsonLineInfo lineInfo = this; string exceptionMessage = (lineInfo.HasLineInfo()) ? message + " Line {0}, position {1}.".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition) : message; OnValidationEvent(new JsonSchemaException(exceptionMessage, null, lineInfo.LineNumber, lineInfo.LinePosition)); } private void OnValidationEvent(JsonSchemaException exception) { ValidationEventHandler handler = ValidationEventHandler; if (handler != null) handler(this, new ValidationEventArgs(exception)); else throw exception; } /// <summary> /// Initializes a new instance of the <see cref="JsonValidatingReader"/> class that /// validates the content returned from the given <see cref="JsonReader"/>. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read from while validating.</param> public JsonValidatingReader(JsonReader reader) { ValidationUtils.ArgumentNotNull(reader, "reader"); _reader = reader; _stack = new Stack<SchemaScope>(); } /// <summary> /// Gets or sets the schema. /// </summary> /// <value>The schema.</value> public JsonSchema Schema { get { return _schema; } set { if (TokenType != JsonToken.None) throw new Exception("Cannot change schema while validating JSON."); _schema = value; _model = null; } } /// <summary> /// Gets the <see cref="JsonReader"/> used to construct this <see cref="JsonValidatingReader"/>. /// </summary> /// <value>The <see cref="JsonReader"/> specified in the constructor.</value> public JsonReader Reader { get { return _reader; } } private void ValidateInEnumAndNotDisallowed(JsonSchemaModel schema) { if (schema == null) return; JToken value = new JValue(_reader.Value); if (schema.Enum != null) { StringWriter sw = new StringWriter(CultureInfo.InvariantCulture); value.WriteTo(new JsonTextWriter(sw)); if (!schema.Enum.ContainsValue(value, new JTokenEqualityComparer())) RaiseError("Value {0} is not defined in enum.".FormatWith(CultureInfo.InvariantCulture, sw.ToString()), schema); } JsonSchemaType? currentNodeType = GetCurrentNodeSchemaType(); if (currentNodeType != null) { if (JsonSchemaGenerator.HasFlag(schema.Disallow, currentNodeType.Value)) RaiseError("Type {0} is disallowed.".FormatWith(CultureInfo.InvariantCulture, currentNodeType), schema); } } private JsonSchemaType? GetCurrentNodeSchemaType() { switch (_reader.TokenType) { case JsonToken.StartObject: return JsonSchemaType.Object; case JsonToken.StartArray: return JsonSchemaType.Array; case JsonToken.Integer: return JsonSchemaType.Integer; case JsonToken.Float: return JsonSchemaType.Float; case JsonToken.String: return JsonSchemaType.String; case JsonToken.Boolean: return JsonSchemaType.Boolean; case JsonToken.Null: return JsonSchemaType.Null; default: return null; } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="T:Byte[]"/>. /// </summary> /// <returns> /// A <see cref="T:Byte[]"/> or a null reference if the next JSON token is null. /// </returns> public override byte[] ReadAsBytes() { byte[] data = _reader.ReadAsBytes(); ValidateCurrentToken(); return data; } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>.</returns> public override decimal? ReadAsDecimal() { decimal? d = _reader.ReadAsDecimal(); ValidateCurrentToken(); return d; } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTimeOffset}"/>.</returns> public override DateTimeOffset? ReadAsDateTimeOffset() { DateTimeOffset? dateTimeOffset = _reader.ReadAsDateTimeOffset(); ValidateCurrentToken(); return dateTimeOffset; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns> /// true if the next token was read successfully; false if there are no more tokens to read. /// </returns> public override bool Read() { if (!_reader.Read()) return false; if (_reader.TokenType == JsonToken.Comment) return true; ValidateCurrentToken(); return true; } private void ValidateCurrentToken() { // first time validate has been called. build model if (_model == null) { JsonSchemaModelBuilder builder = new JsonSchemaModelBuilder(); _model = builder.Build(_schema); } //ValidateValueToken(); switch (_reader.TokenType) { case JsonToken.StartObject: ProcessValue(); IList<JsonSchemaModel> objectSchemas = CurrentMemberSchemas.Where(ValidateObject).ToList(); Push(new SchemaScope(JTokenType.Object, objectSchemas)); break; case JsonToken.StartArray: ProcessValue(); IList<JsonSchemaModel> arraySchemas = CurrentMemberSchemas.Where(ValidateArray).ToList(); Push(new SchemaScope(JTokenType.Array, arraySchemas)); break; case JsonToken.StartConstructor: Push(new SchemaScope(JTokenType.Constructor, null)); break; case JsonToken.PropertyName: foreach (JsonSchemaModel schema in CurrentSchemas) { ValidatePropertyName(schema); } break; case JsonToken.Raw: break; case JsonToken.Integer: ProcessValue(); foreach (JsonSchemaModel schema in CurrentMemberSchemas) { ValidateInteger(schema); } break; case JsonToken.Float: ProcessValue(); foreach (JsonSchemaModel schema in CurrentMemberSchemas) { ValidateFloat(schema); } break; case JsonToken.String: ProcessValue(); foreach (JsonSchemaModel schema in CurrentMemberSchemas) { ValidateString(schema); } break; case JsonToken.Boolean: ProcessValue(); foreach (JsonSchemaModel schema in CurrentMemberSchemas) { ValidateBoolean(schema); } break; case JsonToken.Null: ProcessValue(); foreach (JsonSchemaModel schema in CurrentMemberSchemas) { ValidateNull(schema); } break; case JsonToken.Undefined: break; case JsonToken.EndObject: foreach (JsonSchemaModel schema in CurrentSchemas) { ValidateEndObject(schema); } Pop(); break; case JsonToken.EndArray: foreach (JsonSchemaModel schema in CurrentSchemas) { ValidateEndArray(schema); } Pop(); break; case JsonToken.EndConstructor: Pop(); break; case JsonToken.Date: break; default: throw new ArgumentOutOfRangeException(); } } private void ValidateEndObject(JsonSchemaModel schema) { if (schema == null) return; Dictionary<string, bool> requiredProperties = _currentScope.RequiredProperties; if (requiredProperties != null) { List<string> unmatchedRequiredProperties = requiredProperties.Where(kv => !kv.Value).Select(kv => kv.Key).ToList(); if (unmatchedRequiredProperties.Count > 0) RaiseError("Required properties are missing from object: {0}.".FormatWith(CultureInfo.InvariantCulture, string.Join(", ", unmatchedRequiredProperties.ToArray())), schema); } } private void ValidateEndArray(JsonSchemaModel schema) { if (schema == null) return; int arrayItemCount = _currentScope.ArrayItemCount; if (schema.MaximumItems != null && arrayItemCount > schema.MaximumItems) RaiseError("Array item count {0} exceeds maximum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MaximumItems), schema); if (schema.MinimumItems != null && arrayItemCount < schema.MinimumItems) RaiseError("Array item count {0} is less than minimum count of {1}.".FormatWith(CultureInfo.InvariantCulture, arrayItemCount, schema.MinimumItems), schema); } private void ValidateNull(JsonSchemaModel schema) { if (schema == null) return; if (!TestType(schema, JsonSchemaType.Null)) return; ValidateInEnumAndNotDisallowed(schema); } private void ValidateBoolean(JsonSchemaModel schema) { if (schema == null) return; if (!TestType(schema, JsonSchemaType.Boolean)) return; ValidateInEnumAndNotDisallowed(schema); } private void ValidateString(JsonSchemaModel schema) { if (schema == null) return; if (!TestType(schema, JsonSchemaType.String)) return; ValidateInEnumAndNotDisallowed(schema); string value = _reader.Value.ToString(); if (schema.MaximumLength != null && value.Length > schema.MaximumLength) RaiseError("String '{0}' exceeds maximum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MaximumLength), schema); if (schema.MinimumLength != null && value.Length < schema.MinimumLength) RaiseError("String '{0}' is less than minimum length of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.MinimumLength), schema); if (schema.Patterns != null) { foreach (string pattern in schema.Patterns) { if (!Regex.IsMatch(value, pattern)) RaiseError("String '{0}' does not match regex pattern '{1}'.".FormatWith(CultureInfo.InvariantCulture, value, pattern), schema); } } } private void ValidateInteger(JsonSchemaModel schema) { if (schema == null) return; if (!TestType(schema, JsonSchemaType.Integer)) return; ValidateInEnumAndNotDisallowed(schema); long value = Convert.ToInt64(_reader.Value, CultureInfo.InvariantCulture); if (schema.Maximum != null) { if (value > schema.Maximum) RaiseError("Integer {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema); if (schema.ExclusiveMaximum && value == schema.Maximum) RaiseError("Integer {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Maximum), schema); } if (schema.Minimum != null) { if (value < schema.Minimum) RaiseError("Integer {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema); if (schema.ExclusiveMinimum && value == schema.Minimum) RaiseError("Integer {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, value, schema.Minimum), schema); } if (schema.DivisibleBy != null && !IsZero(value % schema.DivisibleBy.Value)) RaiseError("Integer {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema); } private void ProcessValue() { if (_currentScope != null && _currentScope.TokenType == JTokenType.Array) { _currentScope.ArrayItemCount++; foreach (JsonSchemaModel currentSchema in CurrentSchemas) { if (currentSchema != null && currentSchema.Items != null && currentSchema.Items.Count > 1 && _currentScope.ArrayItemCount >= currentSchema.Items.Count) RaiseError("Index {0} has not been defined and the schema does not allow additional items.".FormatWith(CultureInfo.InvariantCulture, _currentScope.ArrayItemCount), currentSchema); } } } private void ValidateFloat(JsonSchemaModel schema) { if (schema == null) return; if (!TestType(schema, JsonSchemaType.Float)) return; ValidateInEnumAndNotDisallowed(schema); double value = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture); if (schema.Maximum != null) { if (value > schema.Maximum) RaiseError("Float {0} exceeds maximum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema); if (schema.ExclusiveMaximum && value == schema.Maximum) RaiseError("Float {0} equals maximum value of {1} and exclusive maximum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Maximum), schema); } if (schema.Minimum != null) { if (value < schema.Minimum) RaiseError("Float {0} is less than minimum value of {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema); if (schema.ExclusiveMinimum && value == schema.Minimum) RaiseError("Float {0} equals minimum value of {1} and exclusive minimum is true.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.Minimum), schema); } if (schema.DivisibleBy != null && !IsZero(value % schema.DivisibleBy.Value)) RaiseError("Float {0} is not evenly divisible by {1}.".FormatWith(CultureInfo.InvariantCulture, JsonConvert.ToString(value), schema.DivisibleBy), schema); } private static bool IsZero(double value) { double epsilon = 2.2204460492503131e-016; return Math.Abs(value) < 10.0 * epsilon; } private void ValidatePropertyName(JsonSchemaModel schema) { if (schema == null) return; string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture); if (_currentScope.RequiredProperties.ContainsKey(propertyName)) _currentScope.RequiredProperties[propertyName] = true; if (!schema.AllowAdditionalProperties) { bool propertyDefinied = IsPropertyDefinied(schema, propertyName); if (!propertyDefinied) RaiseError("Property '{0}' has not been defined and the schema does not allow additional properties.".FormatWith(CultureInfo.InvariantCulture, propertyName), schema); } _currentScope.CurrentPropertyName = propertyName; } private bool IsPropertyDefinied(JsonSchemaModel schema, string propertyName) { if (schema.Properties != null && schema.Properties.ContainsKey(propertyName)) return true; if (schema.PatternProperties != null) { foreach (string pattern in schema.PatternProperties.Keys) { if (Regex.IsMatch(propertyName, pattern)) return true; } } return false; } private bool ValidateArray(JsonSchemaModel schema) { if (schema == null) return true; return (TestType(schema, JsonSchemaType.Array)); } private bool ValidateObject(JsonSchemaModel schema) { if (schema == null) return true; return (TestType(schema, JsonSchemaType.Object)); } private bool TestType(JsonSchemaModel currentSchema, JsonSchemaType currentType) { if (!JsonSchemaGenerator.HasFlag(currentSchema.Type, currentType)) { RaiseError("Invalid type. Expected {0} but got {1}.".FormatWith(CultureInfo.InvariantCulture, currentSchema.Type, currentType), currentSchema); return false; } return true; } bool IJsonLineInfo.HasLineInfo() { IJsonLineInfo lineInfo = _reader as IJsonLineInfo; return (lineInfo != null) ? lineInfo.HasLineInfo() : false; } int IJsonLineInfo.LineNumber { get { IJsonLineInfo lineInfo = _reader as IJsonLineInfo; return (lineInfo != null) ? lineInfo.LineNumber : 0; } } int IJsonLineInfo.LinePosition { get { IJsonLineInfo lineInfo = _reader as IJsonLineInfo; return (lineInfo != null) ? lineInfo.LinePosition : 0; } } } } #endif
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Network; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Service Management API includes operations for managing the virtual /// networks for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx for /// more information) /// </summary> public partial class NetworkManagementClient : ServiceClient<NetworkManagementClient>, INetworkManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IApplicationGatewayOperations _applicationGateways; /// <summary> /// The Application Gateway Management API includes operations for /// managing application gateways in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx /// for more information) /// </summary> public virtual IApplicationGatewayOperations ApplicationGateways { get { return this._applicationGateways; } } private IClientRootCertificateOperations _clientRootCertificates; /// <summary> /// The Network Management API includes operations for managing the /// client root certificates for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx /// for more information) /// </summary> public virtual IClientRootCertificateOperations ClientRootCertificates { get { return this._clientRootCertificates; } } private IGatewayOperations _gateways; /// <summary> /// The Network Management API includes operations for managing the /// gateways for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx /// for more information) /// </summary> public virtual IGatewayOperations Gateways { get { return this._gateways; } } private IIPForwardingOperations _iPForwarding; /// <summary> /// The Network Management API includes operations for managing the IP /// Forwarding for your roles and network interfaces in your /// subscription. /// </summary> public virtual IIPForwardingOperations IPForwarding { get { return this._iPForwarding; } } private INetworkOperations _networks; /// <summary> /// The Network Management API includes operations for managing the /// virtual networks for your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157182.aspx /// for more information) /// </summary> public virtual INetworkOperations Networks { get { return this._networks; } } private INetworkSecurityGroupOperations _networkSecurityGroups; /// <summary> /// The Network Management API includes operations for managing the /// Network Security Groups for your subscription. /// </summary> public virtual INetworkSecurityGroupOperations NetworkSecurityGroups { get { return this._networkSecurityGroups; } } private IReservedIPOperations _reservedIPs; /// <summary> /// The Network Management API includes operations for managing the /// reserved IPs for your subscription. /// </summary> public virtual IReservedIPOperations ReservedIPs { get { return this._reservedIPs; } } private IRouteOperations _routes; /// <summary> /// The Network Management API includes operations for managing the /// routes for your subscription. /// </summary> public virtual IRouteOperations Routes { get { return this._routes; } } private IStaticIPOperations _staticIPs; /// <summary> /// The Network Management API includes operations for managing the /// static IPs for your subscription. /// </summary> public virtual IStaticIPOperations StaticIPs { get { return this._staticIPs; } } private IVirtualIPOperations _virtualIPs; /// <summary> /// The Network Management API includes operations for managing the /// Virtual IPs for your deployment. /// </summary> public virtual IVirtualIPOperations VirtualIPs { get { return this._virtualIPs; } } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> public NetworkManagementClient() : base() { this._applicationGateways = new ApplicationGatewayOperations(this); this._clientRootCertificates = new ClientRootCertificateOperations(this); this._gateways = new GatewayOperations(this); this._iPForwarding = new IPForwardingOperations(this); this._networks = new NetworkOperations(this); this._networkSecurityGroups = new NetworkSecurityGroupOperations(this); this._reservedIPs = new ReservedIPOperations(this); this._routes = new RouteOperations(this); this._staticIPs = new StaticIPOperations(this); this._virtualIPs = new VirtualIPOperations(this); this._apiVersion = "2017-01-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public NetworkManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public NetworkManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public NetworkManagementClient(HttpClient httpClient) : base(httpClient) { this._applicationGateways = new ApplicationGatewayOperations(this); this._clientRootCertificates = new ClientRootCertificateOperations(this); this._gateways = new GatewayOperations(this); this._iPForwarding = new IPForwardingOperations(this); this._networks = new NetworkOperations(this); this._networkSecurityGroups = new NetworkSecurityGroupOperations(this); this._reservedIPs = new ReservedIPOperations(this); this._routes = new RouteOperations(this); this._staticIPs = new StaticIPOperations(this); this._virtualIPs = new VirtualIPOperations(this); this._apiVersion = "2017-01-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public NetworkManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the NetworkManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public NetworkManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// NetworkManagementClient instance /// </summary> /// <param name='client'> /// Instance of NetworkManagementClient to clone to /// </param> protected override void Clone(ServiceClient<NetworkManagementClient> client) { base.Clone(client); if (client is NetworkManagementClient) { NetworkManagementClient clonedClient = ((NetworkManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx /// for more information) /// </summary> /// <param name='requestId'> /// Required. The request ID for the request you wish to track. The /// request ID is returned in the x-ms-request-id response header for /// every request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken) { // Validate if (requestId == null) { throw new ArgumentNullException("requestId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("requestId", requestId); TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId); } url = url + "/operations/"; url = url + Uri.EscapeDataString(requestId); string baseUrl = this.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2017-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure")); if (operationElement != null) { XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * Copyright 2011 John Sample * * 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.IO; using System.Net; using System.Net.Sockets; using log4net; namespace BitSharper.Discovery { /// <summary> /// IrcDiscovery provides a way to find network peers by joining a pre-agreed rendevouz point on the LFnet IRC network. /// </summary> public class IrcDiscovery : IPeerDiscovery { private static readonly ILog _log = LogManager.GetLogger(typeof (IrcDiscovery)); private readonly string _channel; private readonly int _port; private readonly string _server; /// <summary> /// Finds a list of peers by connecting to an IRC network, joining a channel, decoding the nicks and then /// disconnecting. /// </summary> /// <param name="channel">The IRC channel to join, either "#bitcoin" or "#bitcoinTEST" for the production and test networks respectively.</param> /// <param name="server">Name or textual IP address of the IRC server to join.</param> /// <param name="port">The port of the IRC server to join.</param> public IrcDiscovery(string channel, string server = "irc.lfnet.org", int port = 6667) { _channel = channel; _server = server; _port = port; } protected virtual void OnIrcSend(string message) { if (Send != null) { Send(this, new IrcDiscoveryEventArgs(message)); } } protected virtual void OnIrcReceive(string message) { if (Receive != null) { Receive(this, new IrcDiscoveryEventArgs(message)); } } public event EventHandler<IrcDiscoveryEventArgs> Send; public event EventHandler<IrcDiscoveryEventArgs> Receive; /// <summary> /// Returns a list of peers that were found in the IRC channel. Note that just because a peer appears in the list /// does not mean it is accepting connections. /// </summary> /// <exception cref="PeerDiscoveryException"/> public IEnumerable<EndPoint> GetPeers() { var addresses = new List<EndPoint>(); using (var connection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { try { connection.Connect(_server, _port); using (var writer = new StreamWriter(new NetworkStream(connection, FileAccess.Write))) using (var reader = new StreamReader(new NetworkStream(connection, FileAccess.Read))) { // Generate a random nick for the connection. This is chosen to be clearly identifiable as coming from // BitCoinSharp but not match the standard nick format, so full peers don't try and connect to us. var nickRnd = string.Format("bcs{0}", new Random().Next(int.MaxValue)); var command = "NICK " + nickRnd; LogAndSend(writer, command); // USER <user> <mode> <unused> <realname> (RFC 2812) command = "USER " + nickRnd + " 8 *: " + nickRnd; LogAndSend(writer, command); writer.Flush(); // Wait to be logged in. Worst case we end up blocked until the server PING/PONGs us out. string currLine; while ((currLine = reader.ReadLine()) != null) { OnIrcReceive(currLine); // 004 tells us we are connected // TODO: add common exception conditions (nick already in use, etc..) // these aren't bullet proof checks but they should do for our purposes. if (CheckLineStatus("004", currLine)) { break; } } // Join the channel. LogAndSend(writer, "JOIN " + _channel); // List users in channel. LogAndSend(writer, "NAMES " + _channel); writer.Flush(); // A list of the users should be returned. Look for code 353 and parse until code 366. while ((currLine = reader.ReadLine()) != null) { OnIrcReceive(currLine); if (CheckLineStatus("353", currLine)) { // Line contains users. List follows ":" (second ":" if line starts with ":") var subIndex = 0; if (currLine.StartsWith(":")) { subIndex = 1; } var spacedList = currLine.Substring(currLine.IndexOf(":", subIndex)); addresses.AddRange(ParseUserList(spacedList.Substring(1).Split(' '))); } else if (CheckLineStatus("366", currLine)) { // End of user list. break; } } // Quit the server. LogAndSend(writer, "PART " + _channel); LogAndSend(writer, "QUIT"); writer.Flush(); } } catch (Exception e) { // Throw the original error wrapped in the discovery error. throw new PeerDiscoveryException(e.Message, e); } } return addresses.ToArray(); } private void LogAndSend(TextWriter writer, string command) { OnIrcSend(command); writer.WriteLine(command); } // Visible for testing. internal static IList<EndPoint> ParseUserList(IEnumerable<string> userNames) { var addresses = new List<EndPoint>(); foreach (var user in userNames) { // All BitCoin peers start their nicknames with a 'u' character. if (!user.StartsWith("u")) { continue; } // After "u" is stripped from the beginning array contains unsigned chars of: // 4 byte IP address, 2 byte port, 4 byte hash check (ipv4) byte[] addressBytes; try { // Strip off the "u" before decoding. Note that it's possible for anyone to join these IRC channels and // so simply beginning with "u" does not imply this is a valid BitCoin encoded address. // // decodeChecked removes the checksum from the returned bytes. addressBytes = Base58.DecodeChecked(user.Substring(1)); } catch (AddressFormatException) { _log.WarnFormat("IRC nick does not parse as base58: {0}", user); continue; } // TODO: Handle IPv6 if one day the official client uses it. It may be that IRC discovery never does. if (addressBytes.Length != 6) { continue; } var ipBytes = new[] {addressBytes[0], addressBytes[1], addressBytes[2], addressBytes[3]}; var port = Utils.ReadUint16Be(addressBytes, 4); var ip = new IPAddress(ipBytes); var address = new IPEndPoint(ip, port); addresses.Add(address); } return addresses; } private static bool CheckLineStatus(string statusCode, string response) { // Lines can either start with the status code or an optional :<source> // // All the testing shows the servers for this purpose use :<source> but plan for either. // TODO: Consider whether regex would be worth it here. if (response.StartsWith(":")) { // Look for first space. var startIndex = response.IndexOf(" ") + 1; // Next part should be status code. return response.IndexOf(statusCode + " ", startIndex) == startIndex; } return response.StartsWith(statusCode + " "); } } public class IrcDiscoveryEventArgs : EventArgs { public string Message { get; private set; } public IrcDiscoveryEventArgs(string message) { Message = message; } } }