context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Threading; using Xunit; namespace System.Linq.Parallel.Tests { public static class SequenceEqualTests { private const int DuplicateFactor = 8; // // SequenceEqual // public static IEnumerable<object[]> SequenceEqualData(int[] counts) { foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4))) { foreach (object[] right in Sources.Ranges(new[] { (int)left[1] })) { yield return new object[] { left[0], right[0], right[1] }; } } } public static IEnumerable<object[]> SequenceEqualUnequalSizeData(int[] counts) { foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4))) { foreach (object[] right in Sources.Ranges(new[] { 1, ((int)left[1] - 1) / 2 + 1, (int)left[1] * 2 + 1 }.Distinct())) { yield return new object[] { left[0], left[1], right[0], right[1] }; } } } public static IEnumerable<object[]> SequenceEqualUnequalData(int[] counts) { foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4))) { Func<int, IEnumerable<int>> items = x => new[] { 0, x / 8, x / 2, x * 7 / 8, x - 1 }.Distinct(); foreach (object[] right in Sources.Ranges(new[] { (int)left[1] }, items)) { yield return new object[] { left[0], right[0], right[1], right[2] }; } } } [Theory] [MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })] public static void SequenceEqual(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; Assert.True(leftQuery.SequenceEqual(rightQuery)); Assert.True(rightQuery.SequenceEqual(leftQuery)); Assert.True(leftQuery.SequenceEqual(leftQuery)); } [Theory] [OuterLoop] [MemberData(nameof(SequenceEqualData), new int[] { /* Sources.OuterLoopCount */ })] public static void SequenceEqual_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { SequenceEqual(left, right, count); } [Theory] [MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })] public static void SequenceEqual_CustomComparator(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; Assert.True(leftQuery.SequenceEqual(rightQuery, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(rightQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(leftQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor))); ParallelQuery<int> repeating = Enumerable.Range(0, (count + (DuplicateFactor - 1)) / DuplicateFactor).SelectMany(x => Enumerable.Range(0, DuplicateFactor)).Take(count).AsParallel().AsOrdered(); Assert.True(leftQuery.SequenceEqual(repeating, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(rightQuery.SequenceEqual(repeating, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(repeating.SequenceEqual(rightQuery, new ModularCongruenceComparer(DuplicateFactor))); Assert.True(repeating.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor))); } [Theory] [OuterLoop] [MemberData(nameof(SequenceEqualData), new int[] { /* Sources.OuterLoopCount */ })] public static void SequenceEqual_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { SequenceEqual_CustomComparator(left, right, count); } [Theory] [MemberData(nameof(SequenceEqualUnequalSizeData), new[] { 0, 4, 16 })] public static void SequenceEqual_UnequalSize(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; Assert.False(leftQuery.SequenceEqual(rightQuery)); Assert.False(rightQuery.SequenceEqual(leftQuery)); Assert.False(leftQuery.SequenceEqual(rightQuery, new ModularCongruenceComparer(2))); Assert.False(rightQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(2))); } [Theory] [OuterLoop] [MemberData(nameof(SequenceEqualUnequalSizeData), new int[] { /* Sources.OuterLoopCount */ })] public static void SequenceEqual_UnequalSize_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount) { SequenceEqual_UnequalSize(left, leftCount, right, rightCount); } [Theory] [MemberData(nameof(SequenceEqualUnequalData), new[] { 1, 2, 16 })] public static void SequenceEqual_Unequal(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count, int item) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item.Select(x => x == item ? -1 : x); Assert.False(leftQuery.SequenceEqual(rightQuery)); Assert.False(rightQuery.SequenceEqual(leftQuery)); Assert.True(leftQuery.SequenceEqual(leftQuery)); } [Theory] [OuterLoop] [MemberData(nameof(SequenceEqualUnequalData), new int[] { /* Sources.OuterLoopCount */ })] public static void SequenceEqual_Unequal_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count, int item) { SequenceEqual_Unequal(left, right, count, item); } public static void SequenceEqual_NotSupportedException() { #pragma warning disable 618 Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).SequenceEqual(Enumerable.Range(0, 1))); Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).SequenceEqual(Enumerable.Range(0, 1), null)); #pragma warning restore 618 } [Fact] public static void SequenceEqual_OperationCanceledException() { AssertThrows.EventuallyCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler))); AssertThrows.EventuallyCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler))); } [Fact] public static void SequenceEqual_AggregateException_Wraps_OperationCanceledException() { AssertThrows.OtherTokenCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler))); AssertThrows.OtherTokenCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler))); AssertThrows.SameTokenNotCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler))); AssertThrows.SameTokenNotCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler))); } [Fact] public static void SequenceEqual_OperationCanceledException_PreCanceled() { AssertThrows.AlreadyCanceled(source => source.SequenceEqual(ParallelEnumerable.Range(0, 2))); AssertThrows.AlreadyCanceled(source => source.SequenceEqual(ParallelEnumerable.Range(0, 2), new ModularCongruenceComparer(1))); AssertThrows.AlreadyCanceled(source => ParallelEnumerable.Range(0, 2).SequenceEqual(source)); AssertThrows.AlreadyCanceled(source => ParallelEnumerable.Range(0, 2).SequenceEqual(source, new ModularCongruenceComparer(1))); } [Theory] [MemberData(nameof(SequenceEqualData), new[] { 4 })] public static void SequenceEqual_AggregateException(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { AssertThrows.Wrapped<DeliberateTestException>(() => left.Item.SequenceEqual(right.Item, new FailingEqualityComparer<int>())); } [Fact] // Should not get the same setting from both operands. public static void SequenceEqual_NoDuplicateSettings() { CancellationToken t = new CancellationTokenSource().Token; Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).SequenceEqual(ParallelEnumerable.Range(0, 1).WithCancellation(t))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).SequenceEqual(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).SequenceEqual(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default))); Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).SequenceEqual(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default))); } [Fact] public static void SequenceEqual_ArgumentNullException() { Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).SequenceEqual(ParallelEnumerable.Range(0, 1))); Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).SequenceEqual((ParallelQuery<int>)null)); Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).SequenceEqual(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).SequenceEqual((ParallelQuery<int>)null, EqualityComparer<int>.Default)); } [Theory] [MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })] public static void SequenceEqual_DisposeException(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count) { ParallelQuery<int> leftQuery = left.Item; ParallelQuery<int> rightQuery = right.Item; AssertThrows.Wrapped<TestDisposeException>(() => leftQuery.SequenceEqual(new DisposeExceptionEnumerable<int>(rightQuery).AsParallel())); AssertThrows.Wrapped<TestDisposeException>(() => new DisposeExceptionEnumerable<int>(leftQuery).AsParallel().SequenceEqual(rightQuery)); } private class DisposeExceptionEnumerable<T> : IEnumerable<T> { private IEnumerable<T> _enumerable; public DisposeExceptionEnumerable(IEnumerable<T> enumerable) { _enumerable = enumerable; } public IEnumerator<T> GetEnumerator() { return new DisposeExceptionEnumerator(_enumerable.GetEnumerator()); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private class DisposeExceptionEnumerator : IEnumerator<T> { private IEnumerator<T> _enumerator; public DisposeExceptionEnumerator(IEnumerator<T> enumerator) { _enumerator = enumerator; } public T Current { get { return _enumerator.Current; } } public void Dispose() { throw new TestDisposeException(); } object IEnumerator.Current { get { return Current; } } public bool MoveNext() { return _enumerator.MoveNext(); } public void Reset() { _enumerator.Reset(); } } } private class TestDisposeException : Exception { } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors #if ENCODER && BLOCK_ENCODER using System; using Iced.Intel; using Xunit; namespace Iced.UnitTests.Intel.EncoderTests { public sealed class BlockEncoderTest64_br8 : BlockEncoderTest { const int bitness = 64; const ulong origRip = 0x8000; const ulong newRip = 0x8000000000000000; [Fact] void Br8_fwd() { var originalData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0xE2, 0x22,// loop 0000000000008026h /*0004*/ 0xB0, 0x01,// mov al,1 /*0006*/ 0x67, 0xE2, 0x1D,// loopd 0000000000008026h /*0009*/ 0xB0, 0x02,// mov al,2 /*000B*/ 0xE1, 0x19,// loope 0000000000008026h /*000D*/ 0xB0, 0x03,// mov al,3 /*000F*/ 0x67, 0xE1, 0x14,// looped 0000000000008026h /*0012*/ 0xB0, 0x04,// mov al,4 /*0014*/ 0xE0, 0x10,// loopne 0000000000008026h /*0016*/ 0xB0, 0x05,// mov al,5 /*0018*/ 0x67, 0xE0, 0x0B,// loopned 0000000000008026h /*001B*/ 0xB0, 0x06,// mov al,6 /*001D*/ 0x67, 0xE3, 0x06,// jecxz 0000000000008026h /*0020*/ 0xB0, 0x07,// mov al,7 /*0022*/ 0xE3, 0x02,// jrcxz 0000000000008026h /*0024*/ 0xB0, 0x08,// mov al,8 /*0026*/ 0x90,// nop }; var newData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0xE2, 0x22,// loop 8000000000000026h /*0004*/ 0xB0, 0x01,// mov al,1 /*0006*/ 0x67, 0xE2, 0x1D,// loopd 8000000000000026h /*0009*/ 0xB0, 0x02,// mov al,2 /*000B*/ 0xE1, 0x19,// loope 8000000000000026h /*000D*/ 0xB0, 0x03,// mov al,3 /*000F*/ 0x67, 0xE1, 0x14,// looped 8000000000000026h /*0012*/ 0xB0, 0x04,// mov al,4 /*0014*/ 0xE0, 0x10,// loopne 8000000000000026h /*0016*/ 0xB0, 0x05,// mov al,5 /*0018*/ 0x67, 0xE0, 0x0B,// loopned 8000000000000026h /*001B*/ 0xB0, 0x06,// mov al,6 /*001D*/ 0x67, 0xE3, 0x06,// jecxz 8000000000000026h /*0020*/ 0xB0, 0x07,// mov al,7 /*0022*/ 0xE3, 0x02,// jrcxz 8000000000000026h /*0024*/ 0xB0, 0x08,// mov al,8 /*0026*/ 0x90,// nop }; var expectedInstructionOffsets = new uint[] { 0x0000, 0x0002, 0x0004, 0x0006, 0x0009, 0x000B, 0x000D, 0x000F, 0x0012, 0x0014, 0x0016, 0x0018, 0x001B, 0x001D, 0x0020, 0x0022, 0x0024, 0x0026, }; var expectedRelocInfos = Array.Empty<RelocInfo>(); const BlockEncoderOptions options = BlockEncoderOptions.None; EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos); } [Fact] void Br8_bwd() { var originalData = new byte[] { /*0000*/ 0x90,// nop /*0001*/ 0xB0, 0x00,// mov al,0 /*0003*/ 0xE2, 0xFB,// loop 0000000000008000h /*0005*/ 0xB0, 0x01,// mov al,1 /*0007*/ 0x67, 0xE2, 0xF6,// loopd 0000000000008000h /*000A*/ 0xB0, 0x02,// mov al,2 /*000C*/ 0xE1, 0xF2,// loope 0000000000008000h /*000E*/ 0xB0, 0x03,// mov al,3 /*0010*/ 0x67, 0xE1, 0xED,// looped 0000000000008000h /*0013*/ 0xB0, 0x04,// mov al,4 /*0015*/ 0xE0, 0xE9,// loopne 0000000000008000h /*0017*/ 0xB0, 0x05,// mov al,5 /*0019*/ 0x67, 0xE0, 0xE4,// loopned 0000000000008000h /*001C*/ 0xB0, 0x06,// mov al,6 /*001E*/ 0x67, 0xE3, 0xDF,// jecxz 0000000000008000h /*0021*/ 0xB0, 0x07,// mov al,7 /*0023*/ 0xE3, 0xDB,// jrcxz 0000000000008000h /*0025*/ 0xB0, 0x08,// mov al,8 }; var newData = new byte[] { /*0000*/ 0x90,// nop /*0001*/ 0xB0, 0x00,// mov al,0 /*0003*/ 0xE2, 0xFB,// loop 8000000000000000h /*0005*/ 0xB0, 0x01,// mov al,1 /*0007*/ 0x67, 0xE2, 0xF6,// loopd 8000000000000000h /*000A*/ 0xB0, 0x02,// mov al,2 /*000C*/ 0xE1, 0xF2,// loope 8000000000000000h /*000E*/ 0xB0, 0x03,// mov al,3 /*0010*/ 0x67, 0xE1, 0xED,// looped 8000000000000000h /*0013*/ 0xB0, 0x04,// mov al,4 /*0015*/ 0xE0, 0xE9,// loopne 8000000000000000h /*0017*/ 0xB0, 0x05,// mov al,5 /*0019*/ 0x67, 0xE0, 0xE4,// loopned 8000000000000000h /*001C*/ 0xB0, 0x06,// mov al,6 /*001E*/ 0x67, 0xE3, 0xDF,// jecxz 8000000000000000h /*0021*/ 0xB0, 0x07,// mov al,7 /*0023*/ 0xE3, 0xDB,// jrcxz 8000000000000000h /*0025*/ 0xB0, 0x08,// mov al,8 }; var expectedInstructionOffsets = new uint[] { 0x0000, 0x0001, 0x0003, 0x0005, 0x0007, 0x000A, 0x000C, 0x000E, 0x0010, 0x0013, 0x0015, 0x0017, 0x0019, 0x001C, 0x001E, 0x0021, 0x0023, 0x0025, }; var expectedRelocInfos = Array.Empty<RelocInfo>(); const BlockEncoderOptions options = BlockEncoderOptions.None; EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos); } [Fact] void Br8_fwd_os() { var originalData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0x66, 0xE2, 0x29,// loopw 802Eh /*0005*/ 0xB0, 0x01,// mov al,1 /*0007*/ 0x66, 0x67, 0xE2, 0x23,// loopw 802Eh /*000B*/ 0xB0, 0x02,// mov al,2 /*000D*/ 0x66, 0xE1, 0x1E,// loopew 802Eh /*0010*/ 0xB0, 0x03,// mov al,3 /*0012*/ 0x66, 0x67, 0xE1, 0x18,// loopew 802Eh /*0016*/ 0xB0, 0x04,// mov al,4 /*0018*/ 0x66, 0xE0, 0x13,// loopnew 802Eh /*001B*/ 0xB0, 0x05,// mov al,5 /*001D*/ 0x66, 0x67, 0xE0, 0x0D,// loopnew 802Eh /*0021*/ 0xB0, 0x06,// mov al,6 /*0023*/ 0x66, 0x67, 0xE3, 0x07,// jcxz 802Eh /*0027*/ 0xB0, 0x07,// mov al,7 /*0029*/ 0x66, 0xE3, 0x02,// jecxz 802Eh /*002C*/ 0xB0, 0x08,// mov al,8 /*002E*/ 0x90,// nop }; var newData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0x66, 0xE2, 0x29,// loopw 802Dh /*0005*/ 0xB0, 0x01,// mov al,1 /*0007*/ 0x66, 0x67, 0xE2, 0x23,// loopw 802Dh /*000B*/ 0xB0, 0x02,// mov al,2 /*000D*/ 0x66, 0xE1, 0x1E,// loopew 802Dh /*0010*/ 0xB0, 0x03,// mov al,3 /*0012*/ 0x66, 0x67, 0xE1, 0x18,// loopew 802Dh /*0016*/ 0xB0, 0x04,// mov al,4 /*0018*/ 0x66, 0xE0, 0x13,// loopnew 802Dh /*001B*/ 0xB0, 0x05,// mov al,5 /*001D*/ 0x66, 0x67, 0xE0, 0x0D,// loopnew 802Dh /*0021*/ 0xB0, 0x06,// mov al,6 /*0023*/ 0x66, 0x67, 0xE3, 0x07,// jcxz 802Dh /*0027*/ 0xB0, 0x07,// mov al,7 /*0029*/ 0x66, 0xE3, 0x02,// jecxz 802Dh /*002C*/ 0xB0, 0x08,// mov al,8 /*002E*/ 0x90,// nop }; var expectedInstructionOffsets = new uint[] { 0x0000, 0x0002, 0x0005, 0x0007, 0x000B, 0x000D, 0x0010, 0x0012, 0x0016, 0x0018, 0x001B, 0x001D, 0x0021, 0x0023, 0x0027, 0x0029, 0x002C, 0x002E, }; var expectedRelocInfos = Array.Empty<RelocInfo>(); const BlockEncoderOptions options = BlockEncoderOptions.None; EncodeBase(bitness, origRip, originalData, origRip - 1, newData, options, decoderOptions | DecoderOptions.AMD, expectedInstructionOffsets, expectedRelocInfos); } [Fact] void Br8_short_other_short() { var originalData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0xE2, 0x22,// loop 0000000000008026h /*0004*/ 0xB0, 0x01,// mov al,1 /*0006*/ 0x67, 0xE2, 0x1D,// loopd 0000000000008026h /*0009*/ 0xB0, 0x02,// mov al,2 /*000B*/ 0xE1, 0x19,// loope 0000000000008026h /*000D*/ 0xB0, 0x03,// mov al,3 /*000F*/ 0x67, 0xE1, 0x14,// looped 0000000000008026h /*0012*/ 0xB0, 0x04,// mov al,4 /*0014*/ 0xE0, 0x10,// loopne 0000000000008026h /*0016*/ 0xB0, 0x05,// mov al,5 /*0018*/ 0x67, 0xE0, 0x0B,// loopned 0000000000008026h /*001B*/ 0xB0, 0x06,// mov al,6 /*001D*/ 0x67, 0xE3, 0x06,// jecxz 0000000000008026h /*0020*/ 0xB0, 0x07,// mov al,7 /*0022*/ 0xE3, 0x02,// jrcxz 0000000000008026h /*0024*/ 0xB0, 0x08,// mov al,8 }; var newData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0xE2, 0x23,// loop 0000000000008026h /*0004*/ 0xB0, 0x01,// mov al,1 /*0006*/ 0x67, 0xE2, 0x1E,// loopd 0000000000008026h /*0009*/ 0xB0, 0x02,// mov al,2 /*000B*/ 0xE1, 0x1A,// loope 0000000000008026h /*000D*/ 0xB0, 0x03,// mov al,3 /*000F*/ 0x67, 0xE1, 0x15,// looped 0000000000008026h /*0012*/ 0xB0, 0x04,// mov al,4 /*0014*/ 0xE0, 0x11,// loopne 0000000000008026h /*0016*/ 0xB0, 0x05,// mov al,5 /*0018*/ 0x67, 0xE0, 0x0C,// loopned 0000000000008026h /*001B*/ 0xB0, 0x06,// mov al,6 /*001D*/ 0x67, 0xE3, 0x07,// jecxz 0000000000008026h /*0020*/ 0xB0, 0x07,// mov al,7 /*0022*/ 0xE3, 0x03,// jrcxz 0000000000008026h /*0024*/ 0xB0, 0x08,// mov al,8 }; var expectedInstructionOffsets = new uint[] { 0x0000, 0x0002, 0x0004, 0x0006, 0x0009, 0x000B, 0x000D, 0x000F, 0x0012, 0x0014, 0x0016, 0x0018, 0x001B, 0x001D, 0x0020, 0x0022, 0x0024, }; var expectedRelocInfos = Array.Empty<RelocInfo>(); const BlockEncoderOptions options = BlockEncoderOptions.None; EncodeBase(bitness, origRip, originalData, origRip - 1, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos); } [Fact] void Br8_short_other_near() { var originalData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0xE2, 0x22,// loop 0000000000008026h /*0004*/ 0xB0, 0x01,// mov al,1 /*0006*/ 0x67, 0xE2, 0x1E,// loopd 0000000000008027h /*0009*/ 0xB0, 0x02,// mov al,2 /*000B*/ 0xE1, 0x1B,// loope 0000000000008028h /*000D*/ 0xB0, 0x03,// mov al,3 /*000F*/ 0x67, 0xE1, 0x17,// looped 0000000000008029h /*0012*/ 0xB0, 0x04,// mov al,4 /*0014*/ 0xE0, 0x14,// loopne 000000000000802Ah /*0016*/ 0xB0, 0x05,// mov al,5 /*0018*/ 0x67, 0xE0, 0x10,// loopned 000000000000802Bh /*001B*/ 0xB0, 0x06,// mov al,6 /*001D*/ 0x67, 0xE3, 0x0C,// jecxz 000000000000802Ch /*0020*/ 0xB0, 0x07,// mov al,7 /*0022*/ 0xE3, 0x09,// jrcxz 000000000000802Dh /*0024*/ 0xB0, 0x08,// mov al,8 }; var newData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0xE2, 0x02,// loop 0000000000009006h /*0004*/ 0xEB, 0x05,// jmp short 000000000000900Bh /*0006*/ 0xE9, 0x1B, 0xF0, 0xFF, 0xFF,// jmp near ptr 0000000000008026h /*000B*/ 0xB0, 0x01,// mov al,1 /*000D*/ 0x67, 0xE2, 0x02,// loopd 0000000000009012h /*0010*/ 0xEB, 0x05,// jmp short 0000000000009017h /*0012*/ 0xE9, 0x10, 0xF0, 0xFF, 0xFF,// jmp near ptr 0000000000008027h /*0017*/ 0xB0, 0x02,// mov al,2 /*0019*/ 0xE1, 0x02,// loope 000000000000901Dh /*001B*/ 0xEB, 0x05,// jmp short 0000000000009022h /*001D*/ 0xE9, 0x06, 0xF0, 0xFF, 0xFF,// jmp near ptr 0000000000008028h /*0022*/ 0xB0, 0x03,// mov al,3 /*0024*/ 0x67, 0xE1, 0x02,// looped 0000000000009029h /*0027*/ 0xEB, 0x05,// jmp short 000000000000902Eh /*0029*/ 0xE9, 0xFB, 0xEF, 0xFF, 0xFF,// jmp near ptr 0000000000008029h /*002E*/ 0xB0, 0x04,// mov al,4 /*0030*/ 0xE0, 0x02,// loopne 0000000000009034h /*0032*/ 0xEB, 0x05,// jmp short 0000000000009039h /*0034*/ 0xE9, 0xF1, 0xEF, 0xFF, 0xFF,// jmp near ptr 000000000000802Ah /*0039*/ 0xB0, 0x05,// mov al,5 /*003B*/ 0x67, 0xE0, 0x02,// loopned 0000000000009040h /*003E*/ 0xEB, 0x05,// jmp short 0000000000009045h /*0040*/ 0xE9, 0xE6, 0xEF, 0xFF, 0xFF,// jmp near ptr 000000000000802Bh /*0045*/ 0xB0, 0x06,// mov al,6 /*0047*/ 0x67, 0xE3, 0x02,// jecxz 000000000000904Ch /*004A*/ 0xEB, 0x05,// jmp short 0000000000009051h /*004C*/ 0xE9, 0xDB, 0xEF, 0xFF, 0xFF,// jmp near ptr 000000000000802Ch /*0051*/ 0xB0, 0x07,// mov al,7 /*0053*/ 0xE3, 0x02,// jrcxz 0000000000009057h /*0055*/ 0xEB, 0x05,// jmp short 000000000000905Ch /*0057*/ 0xE9, 0xD1, 0xEF, 0xFF, 0xFF,// jmp near ptr 000000000000802Dh /*005C*/ 0xB0, 0x08,// mov al,8 }; var expectedInstructionOffsets = new uint[] { 0x0000, uint.MaxValue, 0x000B, uint.MaxValue, 0x0017, uint.MaxValue, 0x0022, uint.MaxValue, 0x002E, uint.MaxValue, 0x0039, uint.MaxValue, 0x0045, uint.MaxValue, 0x0051, uint.MaxValue, 0x005C, }; var expectedRelocInfos = Array.Empty<RelocInfo>(); const BlockEncoderOptions options = BlockEncoderOptions.None; EncodeBase(bitness, origRip, originalData, origRip + 0x1000, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos); } [Fact] void Br8_short_other_long() { var originalData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0xE2, 0x22,// loop 123456789ABCDE26h /*0004*/ 0xB0, 0x01,// mov al,1 /*0006*/ 0x67, 0xE2, 0x1E,// loopd 123456789ABCDE27h /*0009*/ 0xB0, 0x02,// mov al,2 /*000B*/ 0xE1, 0x1B,// loope 123456789ABCDE28h /*000D*/ 0xB0, 0x03,// mov al,3 /*000F*/ 0x67, 0xE1, 0x17,// looped 123456789ABCDE29h /*0012*/ 0xB0, 0x04,// mov al,4 /*0014*/ 0xE0, 0x14,// loopne 123456789ABCDE2Ah /*0016*/ 0xB0, 0x05,// mov al,5 /*0018*/ 0x67, 0xE0, 0x10,// loopned 123456789ABCDE2Bh /*001B*/ 0xB0, 0x06,// mov al,6 /*001D*/ 0x67, 0xE3, 0x0C,// jecxz 123456789ABCDE2Ch /*0020*/ 0xB0, 0x07,// mov al,7 /*0022*/ 0xE3, 0x09,// jrcxz 123456789ABCDE2Dh /*0024*/ 0xB0, 0x08,// mov al,8 }; var newData = new byte[] { /*0000*/ 0xB0, 0x00,// mov al,0 /*0002*/ 0xE2, 0x02,// loop 8000000000000006h /*0004*/ 0xEB, 0x06,// jmp short 800000000000000Ch /*0006*/ 0xFF, 0x25, 0x5C, 0x00, 0x00, 0x00,// jmp qword ptr [8000000000000068h] /*000C*/ 0xB0, 0x01,// mov al,1 /*000E*/ 0x67, 0xE2, 0x02,// loopd 8000000000000013h /*0011*/ 0xEB, 0x06,// jmp short 8000000000000019h /*0013*/ 0xFF, 0x25, 0x57, 0x00, 0x00, 0x00,// jmp qword ptr [8000000000000070h] /*0019*/ 0xB0, 0x02,// mov al,2 /*001B*/ 0xE1, 0x02,// loope 800000000000001Fh /*001D*/ 0xEB, 0x06,// jmp short 8000000000000025h /*001F*/ 0xFF, 0x25, 0x53, 0x00, 0x00, 0x00,// jmp qword ptr [8000000000000078h] /*0025*/ 0xB0, 0x03,// mov al,3 /*0027*/ 0x67, 0xE1, 0x02,// looped 800000000000002Ch /*002A*/ 0xEB, 0x06,// jmp short 8000000000000032h /*002C*/ 0xFF, 0x25, 0x4E, 0x00, 0x00, 0x00,// jmp qword ptr [8000000000000080h] /*0032*/ 0xB0, 0x04,// mov al,4 /*0034*/ 0xE0, 0x02,// loopne 8000000000000038h /*0036*/ 0xEB, 0x06,// jmp short 800000000000003Eh /*0038*/ 0xFF, 0x25, 0x4A, 0x00, 0x00, 0x00,// jmp qword ptr [8000000000000088h] /*003E*/ 0xB0, 0x05,// mov al,5 /*0040*/ 0x67, 0xE0, 0x02,// loopned 8000000000000045h /*0043*/ 0xEB, 0x06,// jmp short 800000000000004Bh /*0045*/ 0xFF, 0x25, 0x45, 0x00, 0x00, 0x00,// jmp qword ptr [8000000000000090h] /*004B*/ 0xB0, 0x06,// mov al,6 /*004D*/ 0x67, 0xE3, 0x02,// jecxz 8000000000000052h /*0050*/ 0xEB, 0x06,// jmp short 8000000000000058h /*0052*/ 0xFF, 0x25, 0x40, 0x00, 0x00, 0x00,// jmp qword ptr [8000000000000098h] /*0058*/ 0xB0, 0x07,// mov al,7 /*005A*/ 0xE3, 0x02,// jrcxz 800000000000005Eh /*005C*/ 0xEB, 0x06,// jmp short 8000000000000064h /*005E*/ 0xFF, 0x25, 0x3C, 0x00, 0x00, 0x00,// jmp qword ptr [80000000000000A0h] /*0064*/ 0xB0, 0x08,// mov al,8 /*0066*/ 0xCC, 0xCC, /*0068*/ 0x26, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, /*0070*/ 0x27, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, /*0078*/ 0x28, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, /*0080*/ 0x29, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, /*0088*/ 0x2A, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, /*0090*/ 0x2B, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, /*0098*/ 0x2C, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, /*00A0*/ 0x2D, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12, }; var expectedInstructionOffsets = new uint[] { 0x0000, uint.MaxValue, 0x000C, uint.MaxValue, 0x0019, uint.MaxValue, 0x0025, uint.MaxValue, 0x0032, uint.MaxValue, 0x003E, uint.MaxValue, 0x004B, uint.MaxValue, 0x0058, uint.MaxValue, 0x0064, }; var expectedRelocInfos = new RelocInfo[] { new RelocInfo(RelocKind.Offset64, 0x8000000000000068), new RelocInfo(RelocKind.Offset64, 0x8000000000000070), new RelocInfo(RelocKind.Offset64, 0x8000000000000078), new RelocInfo(RelocKind.Offset64, 0x8000000000000080), new RelocInfo(RelocKind.Offset64, 0x8000000000000088), new RelocInfo(RelocKind.Offset64, 0x8000000000000090), new RelocInfo(RelocKind.Offset64, 0x8000000000000098), new RelocInfo(RelocKind.Offset64, 0x80000000000000A0), }; const BlockEncoderOptions options = BlockEncoderOptions.None; const ulong origRip = 0x123456789ABCDE00; EncodeBase(bitness, origRip, originalData, newRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos); } [Fact] void Br8_same_br() { var originalData = new byte[] { /*0000*/ 0xE2, 0xFE,// loop 8000h /*0002*/ 0xE2, 0xFC,// loop 8000h /*0004*/ 0xE2, 0xFA,// loop 8000h }; var newData = new byte[] { /*0000*/ 0xE2, 0xFE,// loop 8000h /*0002*/ 0xE2, 0xFC,// loop 8000h /*0004*/ 0xE2, 0xFA,// loop 8000h }; var expectedInstructionOffsets = new uint[] { 0x0000, 0x0002, 0x0004, }; var expectedRelocInfos = Array.Empty<RelocInfo>(); const BlockEncoderOptions options = BlockEncoderOptions.None; EncodeBase(bitness, origRip, originalData, origRip, newData, options, decoderOptions, expectedInstructionOffsets, expectedRelocInfos); } } } #endif
// // CollectionIndexer.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using DBus; using Hyena.Query; using Hyena.Data.Sqlite; using Banshee.Library; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Collection.Database; namespace Banshee.Collection.Indexer { [DBusExportable (ServiceName = "CollectionIndexer")] public class CollectionIndexerService : ICollectionIndexerService, IDBusExportable, IDisposable { private List<LibrarySource> libraries = new List<LibrarySource> (); private string [] available_export_fields; private int open_indexers; public event ActionHandler CollectionChanged; public event ActionHandler CleanupAndShutdown; private ActionHandler shutdown_handler; public ActionHandler ShutdownHandler { get { return shutdown_handler; } set { shutdown_handler = value; } } public CollectionIndexerService () { DBusConnection.Connect ("CollectionIndexer"); ServiceManager.SourceManager.SourceAdded += OnSourceAdded; ServiceManager.SourceManager.SourceRemoved += OnSourceRemoved; foreach (Source source in ServiceManager.SourceManager.Sources) { MonitorLibrary (source as LibrarySource); } } public void Dispose () { while (libraries.Count > 0) { UnmonitorLibrary (libraries[0]); } } void ICollectionIndexerService.Hello () { Hyena.Log.DebugFormat ("Hello called on {0}", GetType ()); } public void Shutdown () { lock (this) { if (open_indexers == 0 && shutdown_handler != null) { shutdown_handler (); } } } public void ForceShutdown () { Dispose (); if (shutdown_handler != null) { shutdown_handler (); } } public ICollectionIndexer CreateIndexer () { lock (this) { return new CollectionIndexer (null); } } internal void DisposeIndexer (CollectionIndexer indexer) { lock (this) { ServiceManager.DBusServiceManager.UnregisterObject (indexer); open_indexers--; } } ObjectPath ICollectionIndexerService.CreateIndexer () { lock (this) { ObjectPath path = ServiceManager.DBusServiceManager.RegisterObject (new CollectionIndexer (this)); open_indexers++; return path; } } public bool HasCollectionCountChanged (int count) { lock (this) { int total_count = 0; foreach (LibrarySource library in libraries) { total_count += library.Count; } return count != total_count; } } public bool HasCollectionLastModifiedChanged (long time) { lock (this) { long last_updated = 0; foreach (LibrarySource library in libraries) { last_updated = Math.Max (last_updated, ServiceManager.DbConnection.Query<long> ( String.Format ("SELECT MAX(CoreTracks.DateUpdatedStamp) {0}", library.DatabaseTrackModel.UnfilteredQuery))); } return last_updated > time; } } public string [] GetAvailableExportFields () { lock (this) { if (available_export_fields != null) { return available_export_fields; } List<string> fields = new List<string> (); foreach (KeyValuePair<string, System.Reflection.PropertyInfo> field in TrackInfo.GetExportableProperties ( typeof (Banshee.Collection.Database.DatabaseTrackInfo))) { fields.Add (field.Key); } available_export_fields = fields.ToArray (); return available_export_fields; } } private void MonitorLibrary (LibrarySource library) { if (library == null || !library.Indexable || libraries.Contains (library)) { return; } libraries.Add (library); library.TracksAdded += OnLibraryChanged; library.TracksDeleted += OnLibraryChanged; library.TracksChanged += OnLibraryChanged; } private void UnmonitorLibrary (LibrarySource library) { if (library == null || !libraries.Contains (library)) { return; } library.TracksAdded -= OnLibraryChanged; library.TracksDeleted -= OnLibraryChanged; library.TracksChanged -= OnLibraryChanged; libraries.Remove (library); } private void OnSourceAdded (SourceAddedArgs args) { MonitorLibrary (args.Source as LibrarySource); } private void OnSourceRemoved (SourceEventArgs args) { UnmonitorLibrary (args.Source as LibrarySource); } private void OnLibraryChanged (object o, TrackEventArgs args) { if (args.ChangedFields == null) { OnCollectionChanged (); return; } foreach (Hyena.Query.QueryField field in args.ChangedFields) { if (field != Banshee.Query.BansheeQuery.LastPlayedField && field != Banshee.Query.BansheeQuery.LastSkippedField && field != Banshee.Query.BansheeQuery.PlayCountField && field != Banshee.Query.BansheeQuery.SkipCountField) { OnCollectionChanged (); return; } } } public void RequestCleanupAndShutdown () { ActionHandler handler = CleanupAndShutdown; if (handler != null) { handler (); } } private void OnCollectionChanged () { ActionHandler handler = CollectionChanged; if (handler != null) { handler (); } } IDBusExportable IDBusExportable.Parent { get { return null; } } string IService.ServiceName { get { return "CollectionIndexerService"; } } } }
/** RatNum represents an immutable rational number. It includes all of the elements of the set of rationals, as well as the special "NaN" (not-a-number) element that results from division by zero. <p> The "NaN" element is special in many ways. Any arithmetic operation (such as addition) involving "NaN" will return "NaN". With respect to comparison operations, such as less-than, "NaN" is considered equal to itself, and larger than all other rationals. <p> Examples of RatNums include "-1/13", "53/7", "4", "NaN", and "0". */ public class RatNum { private int numer; private int denom; // Abstraction Function: // a RatNum r is NaN if r.denom = 0, ( r.numer / r.denom ) otherwise. // (An abstraction function explains what the state of the fields in a // RatNum represents. In this case, a rational number can be // understood as the result of dividing two integers, or not-a-number // if we would be dividing by zero.) // Representation invariant for every RatNum r: // ( r.denom >= 0 ) && // ( r.denom > 0 ==> there does not exist integer i > 1 such that // r.numer mod i = 0 and r.denom mod i = 0 ) // (A representation invariant tells us something that is true for all // instances of a RatNum; in this case, that the denominator is always // greater than zero and that if the denominator is non-zero, the // fraction represented is in reduced form.) /** @effects: Constructs a new RatNum = n. */ public RatNum(int n) { numer = n; denom = 1; } /** @effects: If d = 0, constructs a new RatNum = NaN. Else constructs a new RatNum = (n / d). */ public RatNum(int n, int d) { // special case for zero denominator; gcd(n,d) requires d != 0 if (d == 0) { numer = n; denom = 0; return; } // reduce ratio to lowest terms int g = gcd(n,d); numer = n / g; denom = d / g; if (denom < 0) { numer = -numer; denom = -denom; } } /** @return true iff this is NaN (not-a-number) */ public bool isNaN() { return (denom == 0); } /** @return true iff this < 0. */ public bool isNegative() { return (this.denom != 0) && (this.numer < 0); // return (compareTo( new RatNum(0) ) < 0); } /** @return true iff this > 0. */ public bool isPositive() { return (this.denom == 0) || (this.numer > 0); // return (compareTo( new RatNum(0) ) > 0); } /** @requires: rn != null @return a negative number if this < rn, 0 if this = rn, a positive number if this > rn. */ public int CompareTo(RatNum rn) { if (this.isNaN() && rn.isNaN()) { return 0; } else if (this.isNaN()) { return 1; } else if (rn.isNaN()) { return -1; } else { RatNum diff = this.sub(rn); return diff.numer; } } /** Approximates the value of this rational. @return a double approximation for this. Note that "NaN" is mapped to {@link double#NaN}, and the {@link double#NaN} value is treated in a special manner by several arithmetic operations, such as the comparison and equality operators. See the <a href="http://java.sun.com/docs/books/jls/second_edition/html/typesValues.doc.html#9208"> Java Language Specification, section 4.2.3</a>, for more details. */ public double approx() { if (isNaN()) { return double.NaN; } else { // convert int values to doubles before dividing. return ((double)numer) / ((double)denom); } } /** @return a string representing this, in reduced terms. The returned string will either be "NaN", or it will take on either of the forms "N" or "N/M", where N and M are both integers in decimal notation and M != 0. */ public string unparse() { // using '+' as string concatenation operator in this method if (isNaN()) { return "NaN"; } else if (denom != 1) { return numer + "/" + denom; } else { return numer.ToString(); } } // in the implementation comments for the following methods, <this> // is notated as "a/b" and <arg> likewise as "x/y" /** @return a new Rational equal to (0 - this). */ public RatNum negate() { return new RatNum( - this.numer , this.denom ); } /** @requires: arg != null @return a new RatNum equal to (this + arg). If either argument is NaN, then returns NaN. */ public RatNum add(RatNum arg) { // a/b + x/y = ay/by + bx/by = (ay + bx)/by return new RatNum( this.numer*arg.denom + arg.numer*this.denom, this.denom*arg.denom ); } /** @requires: arg != null @return a new RatNum equal to (this - arg). If either argument is NaN, then returns NaN. */ public RatNum sub(RatNum arg) { // a/b - x/y = a/b + -x/y return this.add( arg.negate() ); } /** @requires: arg != null @return a new RatNum equal to (this * arg). If either argument is NaN, then returns NaN. */ public RatNum mul(RatNum arg) { // (a/b) * (x/y) = ax/by return new RatNum( this.numer*arg.numer, this.denom*arg.denom ); } /** @requires: arg != null @return a new RatNum equal to (this / arg). If arg is zero, or if either argument is NaN, then returns NaN. */ public RatNum div(RatNum arg) { // (a/b) / (x/y) = ay/bx if (arg.isNaN()) { return arg; } else { return new RatNum( this.numer*arg.denom, this.denom*arg.numer ); } } /** Returns the greatest common divisor of 'a' and 'b'. @requires: b != 0 @return d such that a % d = 0 and b % d = 0 */ private static int gcd(int _a, int _b) { int a = _a, b = _b; // ESC doesn't handle modified primitive args // Euclid's method if (b == 0) return 0; while (b != 0) { int tmp = b; b = a % b; a = tmp; } return a; } /** Standard hashCode function. @return an int that all objects equal to this will also return. */ public override int GetHashCode() { return this.numer*2 + this.denom*3; } /** Standard equality operation. @return true if and only if 'obj' is an instance of a RatNum and 'this' = 'obj'. Note that NaN = NaN for RatNums. */ public override bool Equals(object obj) { if (obj is RatNum) { RatNum rn = (RatNum) obj; // special case: check if both are NaN if (this.isNaN() && rn.isNaN()) { return true; } else { return this.numer == rn.numer && this.denom == rn.denom; } } else { return false; } } /** @return implementation specific debugging string. */ public string debugPrint() { return "RatNum<numer:"+this.numer+" denom:"+this.denom+">"; } // When debugging, or when interfacing with other programs that have // specific I/O requirements, you might change this. public string toString() { return debugPrint(); } /** Makes a RatNum from a string describing it. @requires: 'ratStr' is an instance of a string, with no spaces, of the form: <UL> <LI> "NaN" <LI> "N/M", where N and M are both integers in decimal notation, and M != 0, or <LI> "N", where N is an integer in decimal notation. </UL> @returns NaN if ratStr = "NaN". Else returns a RatNum r = ( N / M ), letting M be 1 in the case where only "N" is passed in. */ public static RatNum parse(string ratStr) { int slashLoc = ratStr.IndexOf('/'); if (ratStr.Equals("NaN")) { return new RatNum(1,0); } else if (slashLoc == -1) { // not NaN, and no slash, must be an Integer return new RatNum( int.Parse( ratStr ) ); } else { // slash, need to parse the two parts seperately int n =int.Parse( ratStr.Substring(0, slashLoc) ); int d =int.Parse( ratStr.Substring(slashLoc+1) ); return new RatNum( n , d ); } } }
// 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 MassTransit.Tests { using System; using System.Diagnostics; using Exceptions; using Magnum.Extensions; using Magnum.TestFramework; using NUnit.Framework; using TestFramework; using TextFixtures; [TestFixture] public class Publishing_a_simple_request : LoopbackLocalAndRemoteTestFixture { [Test] public void Should_allow_publish_request_more_than_once() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); RemoteBus.SubscribeContextHandler<PingMessage>(x => { pingReceived.Set(x.Message); x.Respond(new PongMessage {TransactionId = x.Message.TransactionId}); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 8.Seconds(); LocalBus.PublishRequest(ping, x => { x.Handle<PongMessage>(message => { message.TransactionId.ShouldEqual(ping.TransactionId, "The response correlationId did not match"); pongReceived.Set(message); }); x.SetTimeout(timeout); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); var secondPongReceived = new FutureMessage<PongMessage>(); ping = new PingMessage(); LocalBus.PublishRequest(ping, x => { x.Handle<PongMessage>(message => { message.TransactionId.ShouldEqual(ping.TransactionId, "The response correlationId did not match"); secondPongReceived.Set(message); }); x.SetTimeout(timeout); }); secondPongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); } [Test] public void Should_allow_publish_request_with_custom_headers() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); RemoteBus.SubscribeContextHandler<PingMessage>(x => { pingReceived.Set(x.Message); var transactionIdFromHeader = new Guid(x.Headers["PingTransactionId"]); x.Respond(new PongMessage { TransactionId = transactionIdFromHeader }); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage { TransactionId = Guid.NewGuid() }; TimeSpan timeout = 8.Seconds(); LocalBus.PublishRequest(ping, x => { x.Handle<PongMessage>(message => { message.TransactionId.ShouldEqual(ping.TransactionId, "The response correlationId did not match"); pongReceived.Set(message); }); x.SetTimeout(timeout); }, ctx => { ctx.SetHeader("PingTransactionId", ping.TransactionId.ToString()); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); } [Test] public void Should_call_the_timeout_handler_and_not_throw_an_exception() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); var timeoutCalled = new FutureMessage<bool>(); RemoteBus.SubscribeHandler<PingMessage>(pingReceived.Set); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 2.Seconds(); LocalBus.PublishRequest(ping, x => { x.Handle<PongMessage>(pongReceived.Set); x.HandleTimeout(timeout, () => timeoutCalled.Set(true)); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeFalse("The pong should not have been received"); timeoutCalled.IsAvailable(timeout).ShouldBeTrue("The timeout handler was not called"); } [Test] public void Should_ignore_a_response_that_was_not_for_us() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); var badResponse = new FutureMessage<PongMessage>(); LocalBus.SubscribeHandler<PongMessage>(pongReceived.Set); RemoteBus.SubscribeContextHandler<PingMessage>(x => { RemoteBus.ShouldHaveRemoteSubscriptionFor<PongMessage>(); pingReceived.Set(x.Message); RemoteBus.Publish(new PongMessage {TransactionId = x.Message.TransactionId}); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 8.Seconds(); Assert.Throws<RequestTimeoutException>(() => { RemoteBus.Endpoint.SendRequest(ping, LocalBus, x => { x.Handle<PongMessage>(badResponse.Set); x.SetTimeout(timeout); }); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); badResponse.IsAvailable(2.Seconds()).ShouldBeFalse("Should not have received a response"); } [Test] public void Should_support_send_as_well() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); RemoteBus.SubscribeContextHandler<PingMessage>(x => { pingReceived.Set(x.Message); x.Respond(new PongMessage {TransactionId = x.Message.TransactionId}); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 8.Seconds(); RemoteBus.Endpoint.SendRequest(ping, LocalBus, x => { x.Handle<PongMessage>(message => { message.TransactionId.ShouldEqual(ping.TransactionId, "The response correlationId did not match"); pongReceived.Set(message); }); x.SetTimeout(timeout); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); } [Test] public void Should_allow_send_request_with_custom_headers() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); RemoteBus.SubscribeContextHandler<PingMessage>(x => { pingReceived.Set(x.Message); var transactionIdFromHeader = new Guid(x.Headers["PingTransactionId"]); x.Respond(new PongMessage { TransactionId = transactionIdFromHeader }); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage { TransactionId = Guid.NewGuid() }; TimeSpan timeout = 8.Seconds(); RemoteBus.Endpoint.SendRequest(ping, LocalBus, x => { x.Handle<PongMessage>(message => { message.TransactionId.ShouldEqual(ping.TransactionId, "The response correlationId did not match"); pongReceived.Set(message); }); x.SetTimeout(timeout); }, ctx => { ctx.SetHeader("PingTransactionId", ping.TransactionId.ToString()); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); } [Test, Category("NotOnTeamCity")] public void Should_support_the_asynchronous_programming_model() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); var callbackCalled = new FutureMessage<IAsyncResult>(); RemoteBus.SubscribeContextHandler<PingMessage>(x => { pingReceived.Set(x.Message); x.Respond(new PongMessage {TransactionId = x.Message.TransactionId}); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 18.Seconds(); LocalBus.BeginPublishRequest(ping, callbackCalled.Set, null, x => { x.Handle<PongMessage>(message => { message.TransactionId.ShouldEqual(ping.TransactionId, "The response correlationId did not match"); pongReceived.Set(message); }); x.SetTimeout(timeout); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); callbackCalled.IsAvailable(timeout).ShouldBeTrue("The callback was not called"); bool result = LocalBus.EndPublishRequest<PingMessage>(callbackCalled.Message); Assert.IsTrue(result, "EndRequest should be true"); } [Test] public void Should_throw_a_handler_exception_on_the_calling_thread() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); RemoteBus.SubscribeContextHandler<PingMessage>(x => { pingReceived.Set(x.Message); x.Respond(new PongMessage {TransactionId = x.Message.TransactionId}); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 24.Seconds(); var exception = Assert.Throws<RequestException>(() => { LocalBus.PublishRequest(ping, x => { x.Handle<PongMessage>(message => { pongReceived.Set(message); throw new InvalidOperationException("I got it, but I am naughty with it."); }); x.SetTimeout(timeout); }); }, "A request exception should have been thrown"); exception.Response.ShouldBeAnInstanceOf<PongMessage>(); exception.InnerException.ShouldBeAnInstanceOf<InvalidOperationException>(); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); } [Test] public void Should_throw_an_exception_if_a_fault_was_published() { var pongReceived = new FutureMessage<PongMessage>(); var faultReceived = new FutureMessage<Fault<PingMessage>>(); var pingReceived = new FutureMessage<PingMessage>(); RemoteBus.SubscribeContextHandler<PingMessage>(x => { pingReceived.Set(x.Message); throw new InvalidOperationException("This should carry over to the calling request"); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = Debugger.IsAttached ? 5.Minutes() : 24.Seconds(); LocalBus.PublishRequest(ping, x => { x.Handle<PongMessage>(pongReceived.Set); x.HandleFault(faultReceived.Set); x.SetTimeout(timeout); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); faultReceived.IsAvailable(timeout).ShouldBeTrue("The fault was not received"); pongReceived.IsAvailable(1.Seconds()).ShouldBeFalse("The pong was not received"); } [Test, Category("NotOnTeamCity")] public void Should_throw_a_handler_exception_on_the_calling_thread_using_async() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); var callbackCalled = new FutureMessage<IAsyncResult>(); RemoteBus.SubscribeContextHandler<PingMessage>(x => { pingReceived.Set(x.Message); x.Respond(new PongMessage {TransactionId = x.Message.TransactionId}); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 18.Seconds(); LocalBus.BeginPublishRequest(ping, callbackCalled.Set, null, x => { x.Handle<PongMessage>(message => { pongReceived.Set(message); throw new InvalidOperationException("I got it, but I am naughty with it."); }); x.SetTimeout(timeout); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); callbackCalled.IsAvailable(timeout).ShouldBeTrue("Called was not called"); var exception = Assert.Throws<RequestException>( () => { LocalBus.EndPublishRequest<PingMessage>(callbackCalled.Message); }, "A request exception should have been thrown"); exception.Response.ShouldBeAnInstanceOf<PongMessage>(); exception.InnerException.ShouldBeAnInstanceOf<InvalidOperationException>(); } [Test, Category("NotOnTeamCity")] public void Should_throw_a_timeout_exception_for_async_when_end_is_called() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); var callbackCalled = new FutureMessage<IAsyncResult>(); RemoteBus.SubscribeHandler<PingMessage>(pingReceived.Set); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 2.Seconds(); LocalBus.BeginPublishRequest(ping, callbackCalled.Set, null, x => { x.Handle<PongMessage>(pongReceived.Set); x.SetTimeout(timeout); }); callbackCalled.IsAvailable(8.Seconds()).ShouldBeTrue("Callback was not invoked"); Assert.Throws<RequestTimeoutException>( () => { LocalBus.EndPublishRequest<PingMessage>(callbackCalled.Message); }, "A timeout exception should have been thrown"); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeFalse("The pong should not have been received"); } [Test] public void Should_throw_a_timeout_exception_if_no_response_received() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); RemoteBus.SubscribeHandler<PingMessage>(pingReceived.Set); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 2.Seconds(); Assert.Throws<RequestTimeoutException>(() => { LocalBus.PublishRequest(ping, x => { x.Handle<PongMessage>(pongReceived.Set); x.SetTimeout(timeout); }); }, "A timeout exception should have been thrown"); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeFalse("The pong should not have been received"); } [Test] public void Should_use_a_clean_syntax_following_standard_conventions() { var pongReceived = new FutureMessage<PongMessage>(); var pingReceived = new FutureMessage<PingMessage>(); RemoteBus.SubscribeContextHandler<PingMessage>(x => { pingReceived.Set(x.Message); x.Respond(new PongMessage {TransactionId = x.Message.TransactionId}); }); LocalBus.ShouldHaveSubscriptionFor<PingMessage>(); var ping = new PingMessage(); TimeSpan timeout = 8.Seconds(); LocalBus.PublishRequest(ping, x => { x.Handle<PongMessage>(message => { message.TransactionId.ShouldEqual(ping.TransactionId, "The response correlationId did not match"); pongReceived.Set(message); }); x.SetTimeout(timeout); }); pingReceived.IsAvailable(timeout).ShouldBeTrue("The ping was not received"); pongReceived.IsAvailable(timeout).ShouldBeTrue("The pong was not received"); } class PingMessage { public Guid TransactionId { get; set; } } class PongMessage { public Guid TransactionId { get; set; } } } }
// CommandLineParser.cs using System; using System.Collections; namespace YGOSharp.SevenZip.Common { public enum SwitchType { Simple, PostMinus, LimitedPostString, UnLimitedPostString, PostChar } public class SwitchForm { public string IDString; public SwitchType Type; public bool Multi; public int MinLen; public int MaxLen; public string PostCharSet; public SwitchForm(string idString, SwitchType type, bool multi, int minLen, int maxLen, string postCharSet) { IDString = idString; Type = type; Multi = multi; MinLen = minLen; MaxLen = maxLen; PostCharSet = postCharSet; } public SwitchForm(string idString, SwitchType type, bool multi, int minLen): this(idString, type, multi, minLen, 0, "") { } public SwitchForm(string idString, SwitchType type, bool multi): this(idString, type, multi, 0) { } } public class SwitchResult { public bool ThereIs; public bool WithMinus; public ArrayList PostStrings = new ArrayList(); public int PostCharIndex; public SwitchResult() { ThereIs = false; } } public class Parser { public ArrayList NonSwitchStrings = new ArrayList(); SwitchResult[] _switches; public Parser(int numSwitches) { _switches = new SwitchResult[numSwitches]; for (int i = 0; i < numSwitches; i++) _switches[i] = new SwitchResult(); } bool ParseString(string srcString, SwitchForm[] switchForms) { int len = srcString.Length; if (len == 0) return false; int pos = 0; if (!IsItSwitchChar(srcString[pos])) return false; while (pos < len) { if (IsItSwitchChar(srcString[pos])) pos++; const int kNoLen = -1; int matchedSwitchIndex = 0; int maxLen = kNoLen; for (int switchIndex = 0; switchIndex < _switches.Length; switchIndex++) { int switchLen = switchForms[switchIndex].IDString.Length; if (switchLen <= maxLen || pos + switchLen > len) continue; if (String.Compare(switchForms[switchIndex].IDString, 0, srcString, pos, switchLen, true) == 0) { matchedSwitchIndex = switchIndex; maxLen = switchLen; } } if (maxLen == kNoLen) throw new Exception("maxLen == kNoLen"); SwitchResult matchedSwitch = _switches[matchedSwitchIndex]; SwitchForm switchForm = switchForms[matchedSwitchIndex]; if ((!switchForm.Multi) && matchedSwitch.ThereIs) throw new Exception("switch must be single"); matchedSwitch.ThereIs = true; pos += maxLen; int tailSize = len - pos; SwitchType type = switchForm.Type; switch (type) { case SwitchType.PostMinus: { if (tailSize == 0) matchedSwitch.WithMinus = false; else { matchedSwitch.WithMinus = (srcString[pos] == kSwitchMinus); if (matchedSwitch.WithMinus) pos++; } break; } case SwitchType.PostChar: { if (tailSize < switchForm.MinLen) throw new Exception("switch is not full"); string charSet = switchForm.PostCharSet; const int kEmptyCharValue = -1; if (tailSize == 0) matchedSwitch.PostCharIndex = kEmptyCharValue; else { int index = charSet.IndexOf(srcString[pos]); if (index < 0) matchedSwitch.PostCharIndex = kEmptyCharValue; else { matchedSwitch.PostCharIndex = index; pos++; } } break; } case SwitchType.LimitedPostString: case SwitchType.UnLimitedPostString: { int minLen = switchForm.MinLen; if (tailSize < minLen) throw new Exception("switch is not full"); if (type == SwitchType.UnLimitedPostString) { matchedSwitch.PostStrings.Add(srcString.Substring(pos)); return true; } String stringSwitch = srcString.Substring(pos, minLen); pos += minLen; for (int i = minLen; i < switchForm.MaxLen && pos < len; i++, pos++) { char c = srcString[pos]; if (IsItSwitchChar(c)) break; stringSwitch += c; } matchedSwitch.PostStrings.Add(stringSwitch); break; } } } return true; } public void ParseStrings(SwitchForm[] switchForms, string[] commandStrings) { int numCommandStrings = commandStrings.Length; bool stopSwitch = false; for (int i = 0; i < numCommandStrings; i++) { string s = commandStrings[i]; if (stopSwitch) NonSwitchStrings.Add(s); else if (s == kStopSwitchParsing) stopSwitch = true; else if (!ParseString(s, switchForms)) NonSwitchStrings.Add(s); } } public SwitchResult this[int index] { get { return _switches[index]; } } public static int ParseCommand(CommandForm[] commandForms, string commandString, out string postString) { for (int i = 0; i < commandForms.Length; i++) { string id = commandForms[i].IDString; if (commandForms[i].PostStringMode) { if (commandString.IndexOf(id) == 0) { postString = commandString.Substring(id.Length); return i; } } else if (commandString == id) { postString = ""; return i; } } postString = ""; return -1; } static bool ParseSubCharsCommand(int numForms, CommandSubCharsSet[] forms, string commandString, ArrayList indices) { indices.Clear(); int numUsedChars = 0; for (int i = 0; i < numForms; i++) { CommandSubCharsSet charsSet = forms[i]; int currentIndex = -1; int len = charsSet.Chars.Length; for (int j = 0; j < len; j++) { char c = charsSet.Chars[j]; int newIndex = commandString.IndexOf(c); if (newIndex >= 0) { if (currentIndex >= 0) return false; if (commandString.IndexOf(c, newIndex + 1) >= 0) return false; currentIndex = j; numUsedChars++; } } if (currentIndex == -1 && !charsSet.EmptyAllowed) return false; indices.Add(currentIndex); } return (numUsedChars == commandString.Length); } const char kSwitchID1 = '-'; const char kSwitchID2 = '/'; const char kSwitchMinus = '-'; const string kStopSwitchParsing = "--"; static bool IsItSwitchChar(char c) { return (c == kSwitchID1 || c == kSwitchID2); } } public class CommandForm { public string IDString = ""; public bool PostStringMode; public CommandForm(string idString, bool postStringMode) { IDString = idString; PostStringMode = postStringMode; } } class CommandSubCharsSet { public string Chars = ""; public bool EmptyAllowed = false; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using PartsUnlimited.Areas.Admin; using PartsUnlimited.Models; using PartsUnlimited.Queries; using PartsUnlimited.Recommendations; using PartsUnlimited.Search; using PartsUnlimited.Security; using PartsUnlimited.Telemetry; using PartsUnlimited.TextAnalytics; using PartsUnlimited.WebsiteConfiguration; using System; namespace PartsUnlimited { public class Startup { public IConfiguration Configuration { get; private set; } public Startup(IHostingEnvironment env) { //Below code demonstrates usage of multiple configuration sources. For instance a setting say 'setting1' is found in both the registered sources, //then the later source will win. By this way a Local config can be overridden by a different setting while deployed remotely. var builder = new ConfigurationBuilder() .AddJsonFile("config.json") .AddEnvironmentVariables(); //All environment variables in the process's context flow in as configuration values. Configuration = builder.Build(); } public void ConfigureServices(IServiceCollection services) { //If this type is present - we're on mono var runningOnMono = Type.GetType("Mono.Runtime") != null; var sqlConnectionString = Configuration["Data:DefaultConnection:ConnectionString"]; var useInMemoryDatabase = string.IsNullOrWhiteSpace(sqlConnectionString); // Add EF services to the services container if (useInMemoryDatabase || runningOnMono) { services.AddEntityFramework() .AddInMemoryDatabase() .AddDbContext<PartsUnlimitedContext>(options => { options.UseInMemoryDatabase(); }); } else { services.AddEntityFramework() .AddSqlServer() .AddDbContext<PartsUnlimitedContext>(options => { options.UseSqlServer(sqlConnectionString); }); } // Add Identity services to the services container services.AddIdentity<ApplicationUser, IdentityRole>() .AddEntityFrameworkStores<PartsUnlimitedContext>() .AddDefaultTokenProviders(); // Configure admin policies services.AddAuthorization(auth => { auth.AddPolicy(AdminConstants.Role, authBuilder => { authBuilder.RequireClaim(AdminConstants.ManageStore.Name, AdminConstants.ManageStore.Allowed); }); }); // Add implementations services.AddSingleton<IMemoryCache, MemoryCache>(); services.AddScoped<IOrdersQuery, OrdersQuery>(); services.AddScoped<IRaincheckQuery, RaincheckQuery>(); services.AddSingleton<ITelemetryProvider, EmptyTelemetryProvider>(); services.AddScoped<IProductSearch, StringContainsProductSearch>(); services.AddSingleton<IProductsRepository, ProductsRepository>(s => { string databaseId = Configuration["Keys:DocumentDB:Database"]; string collectionId = Configuration["Keys:DocumentDB:Collection"]; string endpoint = Configuration["Keys:DocumentDB:Endpoint"]; string authKey = Configuration["Keys:DocumentDB:AuthKey"]; return new ProductsRepository(endpoint, authKey, databaseId, collectionId); }); SetupRecommendationService(services); SetupTextAnalyticsService(services); services.AddScoped<IWebsiteOptions>(p => { var telemetry = p.GetRequiredService<ITelemetryProvider>(); return new ConfigurationWebsiteOptions(Configuration.GetSection("WebsiteOptions"), telemetry); }); services.AddScoped<IApplicationInsightsSettings>(p => { return new ConfigurationApplicationInsightsSettings(Configuration.GetSection("Keys:ApplicationInsights")); }); // Associate IPartsUnlimitedContext with context services.AddTransient<IPartsUnlimitedContext>(s => s.GetService<PartsUnlimitedContext>()); // We need access to these settings in a static extension method, so DI does not help us :( ContentDeliveryNetworkExtensions.Configuration = new ContentDeliveryNetworkConfiguration(Configuration.GetSection("CDN")); // Add MVC services to the services container services.AddMvc(); //Add all SignalR related services to IoC. services.AddSignalR(); //Add InMemoryCache services.AddSingleton<IMemoryCache, MemoryCache>(); // Add session related services. services.AddCaching(); services.AddSession(); } private void SetupRecommendationService(IServiceCollection services) { var azureMlConfig = new AzureMLRecommendationsConfig(Configuration.GetSection("Keys:AzureMLRecommendations")); // If keys are not available for Azure ML recommendation service, register an empty recommendation engine if (string.IsNullOrEmpty(azureMlConfig.AccountKey) || string.IsNullOrEmpty(azureMlConfig.ModelId)) { services.AddSingleton<IRecommendationEngine, EmptyRecommendationsEngine>(); } else { services.AddSingleton<IAzureMLAuthenticatedHttpClient, AzureMLAuthenticatedHttpClient>(); services.AddInstance<IAzureMLRecommendationsConfig>(azureMlConfig); services.AddScoped<IRecommendationEngine, AzureMLRecommendationEngine>(); } } private void SetupTextAnalyticsService(IServiceCollection services) { services.AddSingleton<ITextAnalyticsService, TextAnalyticsService>(s => { string accountKey = Configuration["Keys:TextAnalytics:AccountKey"]; return new TextAnalyticsService(accountKey); }); } //This method is invoked when KRE_ENV is 'Development' or is not defined //The allowed values are Development,Staging and Production public void ConfigureDevelopment(IApplicationBuilder app) { //Display custom error page in production when error occurs //During development use the ErrorPage middleware to display error information in the browser app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(DatabaseErrorPageExtensions.EnableAll); // Add the runtime information page that can be used by developers // to see what packages are used by the application // default path is: /runtimeinfo app.UseRuntimeInfoPage(); Configure(app); } //This method is invoked when KRE_ENV is 'Staging' //The allowed values are Development,Staging and Production public void ConfigureStaging(IApplicationBuilder app) { app.UseExceptionHandler("/Home/Error"); Configure(app); } //This method is invoked when KRE_ENV is 'Production' //The allowed values are Development,Staging and Production public void ConfigureProduction(IApplicationBuilder app) { app.UseExceptionHandler("/Home/Error"); Configure(app); } public void Configure(IApplicationBuilder app) { // Configure Session. app.UseSession(); //Configure SignalR app.UseSignalR(); // Add static files to the request pipeline app.UseStaticFiles(); // Add cookie-based authentication to the request pipeline app.UseIdentity(); // Add login providers (Microsoft/AzureAD/Google/etc). This must be done after `app.UseIdentity()` app.AddLoginProviders(new ConfigurationLoginProviders(Configuration.GetSection("Authentication"))); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "areaRoute", template: "{area:exists}/{controller}/{action}", defaults: new { action = "Index" }); routes.MapRoute( name: "default", template: "{controller}/{action}/{id?}", defaults: new { controller = "Home", action = "Index" }); routes.MapRoute( name: "api", template: "{controller}/{id?}"); }); //Populates the PartsUnlimited sample data SampleData.InitializePartsUnlimitedDatabaseAsync(app.ApplicationServices).Wait(); } } }
// Copyright 2008-2011. This work is licensed under the BSD license, available at // http://www.movesinstitute.org/licenses // // Orignal authors: DMcG, Jason Nelson // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Reflection; namespace OpenDis.Enumerations.EntityState.Appearance { /// <summary> /// Enumeration values for SubsurfacePlatformAppearance (es.appear.platform.subsurface, Platforms of the Subsurface Domain, /// section 4.3.1.4) /// The enumeration values are generated from the SISO DIS XML EBV document (R35), which was /// obtained from http://discussions.sisostds.org/default.asp?action=10&amp;fd=31 /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Serializable] public struct SubsurfacePlatformAppearance { /// <summary> /// Describes the paint scheme of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the paint scheme of an entity")] public enum PaintSchemeValue : uint { /// <summary> /// Uniform color /// </summary> UniformColor = 0, /// <summary> /// Camouflage /// </summary> Camouflage = 1 } /// <summary> /// Describes characteristics of mobility kills /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes characteristics of mobility kills")] public enum MobilityValue : uint { /// <summary> /// No mobility kill /// </summary> NoMobilityKill = 0, /// <summary> /// Mobility kill /// </summary> MobilityKill = 1 } /// <summary> /// Describes the damaged appearance of an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the damaged appearance of an entity")] public enum DamageValue : uint { /// <summary> /// No damage /// </summary> NoDamage = 0, /// <summary> /// Slight damage /// </summary> SlightDamage = 1, /// <summary> /// Moderate damage /// </summary> ModerateDamage = 2, /// <summary> /// Destroyed /// </summary> Destroyed = 3 } /// <summary> /// Describes status or location of smoke emanating from an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes status or location of smoke emanating from an entity")] public enum SmokeValue : uint { /// <summary> /// Not smoking /// </summary> NotSmoking = 0, /// <summary> /// Smoke plume rising from the entity /// </summary> SmokePlumeRisingFromTheEntity = 1, /// <summary> /// null /// </summary> Unknown = 2 } /// <summary> /// Describes the state of the hatch /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the state of the hatch")] public enum HatchValue : uint { /// <summary> /// Not applicable /// </summary> NotApplicable = 0, /// <summary> /// Hatch is closed /// </summary> HatchIsClosed = 1, /// <summary> /// null /// </summary> Unknown = 2, /// <summary> /// Hatch is open /// </summary> HatchIsOpen = 4, /// <summary> /// null /// </summary> Unknown2 = 5 } /// <summary> /// Describes whether Running Lights are on or off. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether Running Lights are on or off.")] public enum RunningLightsValue : uint { /// <summary> /// Off /// </summary> Off = 0, /// <summary> /// On /// </summary> On = 1 } /// <summary> /// Describes whether flames are rising from an entity /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes whether flames are rising from an entity")] public enum FlamingValue : uint { /// <summary> /// None /// </summary> None = 0, /// <summary> /// Flames present /// </summary> FlamesPresent = 1 } /// <summary> /// Describes the frozen status of a subsurface platform /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the frozen status of a subsurface platform")] public enum FrozenStatusValue : uint { /// <summary> /// Not frozen /// </summary> NotFrozen = 0, /// <summary> /// Frozen (Frozen entities should not be dead-reckoned, i.e. they should be displayed as fixed at the current location even if nonzero velocity, acceleration or rotation data is received from the frozen entity) /// </summary> FrozenFrozenEntitiesShouldNotBeDeadReckonedIETheyShouldBeDisplayedAsFixedAtTheCurrentLocationEvenIfNonzeroVelocityAccelerationOrRotationDataIsReceivedFromTheFrozenEntity = 1 } /// <summary> /// Describes the power-plant status of a subsurface platform /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the power-plant status of a subsurface platform")] public enum PowerPlantStatusValue : uint { /// <summary> /// Power plant off /// </summary> PowerPlantOff = 0, /// <summary> /// Power plant on /// </summary> PowerPlantOn = 1 } /// <summary> /// Describes the state of a subsurface platform /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1707:IdentifiersShouldNotContainUnderscores", Justification = "Due to SISO standardized naming.")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Justification = "Due to SISO standardized naming.")] [Description("Describes the state of a subsurface platform")] public enum StateValue : uint { /// <summary> /// Active /// </summary> Active = 0, /// <summary> /// Deactivated /// </summary> Deactivated = 1 } private SubsurfacePlatformAppearance.PaintSchemeValue paintScheme; private SubsurfacePlatformAppearance.MobilityValue mobility; private SubsurfacePlatformAppearance.DamageValue damage; private SubsurfacePlatformAppearance.SmokeValue smoke; private SubsurfacePlatformAppearance.HatchValue hatch; private SubsurfacePlatformAppearance.RunningLightsValue runningLights; private SubsurfacePlatformAppearance.FlamingValue flaming; private SubsurfacePlatformAppearance.FrozenStatusValue frozenStatus; private SubsurfacePlatformAppearance.PowerPlantStatusValue powerPlantStatus; private SubsurfacePlatformAppearance.StateValue state; /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(SubsurfacePlatformAppearance left, SubsurfacePlatformAppearance right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(SubsurfacePlatformAppearance left, SubsurfacePlatformAppearance right) { if (object.ReferenceEquals(left, right)) { return true; } // If parameters are null return false (cast to object to prevent recursive loop!) if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } /// <summary> /// Performs an explicit conversion from <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> to <see cref="System.UInt32"/>. /// </summary> /// <param name="obj">The <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> scheme instance.</param> /// <returns>The result of the conversion.</returns> public static explicit operator uint(SubsurfacePlatformAppearance obj) { return obj.ToUInt32(); } /// <summary> /// Performs an explicit conversion from <see cref="System.UInt32"/> to <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/>. /// </summary> /// <param name="value">The uint value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator SubsurfacePlatformAppearance(uint value) { return SubsurfacePlatformAppearance.FromUInt32(value); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> instance from the byte array. /// </summary> /// <param name="array">The array which holds the values for the <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/>.</param> /// <param name="index">The starting position within value.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> instance, represented by a byte array.</returns> /// <exception cref="ArgumentNullException">if the <c>array</c> is null.</exception> /// <exception cref="IndexOutOfRangeException">if the <c>index</c> is lower than 0 or greater or equal than number of elements in array.</exception> public static SubsurfacePlatformAppearance FromByteArray(byte[] array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (index < 0 || index > array.Length - 1 || index + 4 > array.Length - 1) { throw new IndexOutOfRangeException(); } return FromUInt32(BitConverter.ToUInt32(array, index)); } /// <summary> /// Creates the <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> instance from the uint value. /// </summary> /// <param name="value">The uint value which represents the <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> instance.</param> /// <returns>The <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> instance, represented by the uint value.</returns> public static SubsurfacePlatformAppearance FromUInt32(uint value) { SubsurfacePlatformAppearance ps = new SubsurfacePlatformAppearance(); uint mask0 = 0x0001; byte shift0 = 0; uint newValue0 = value & mask0 >> shift0; ps.PaintScheme = (SubsurfacePlatformAppearance.PaintSchemeValue)newValue0; uint mask1 = 0x0002; byte shift1 = 1; uint newValue1 = value & mask1 >> shift1; ps.Mobility = (SubsurfacePlatformAppearance.MobilityValue)newValue1; uint mask3 = 0x0018; byte shift3 = 3; uint newValue3 = value & mask3 >> shift3; ps.Damage = (SubsurfacePlatformAppearance.DamageValue)newValue3; uint mask4 = 0x0060; byte shift4 = 5; uint newValue4 = value & mask4 >> shift4; ps.Smoke = (SubsurfacePlatformAppearance.SmokeValue)newValue4; uint mask6 = 0x0e00; byte shift6 = 9; uint newValue6 = value & mask6 >> shift6; ps.Hatch = (SubsurfacePlatformAppearance.HatchValue)newValue6; uint mask7 = 0x1000; byte shift7 = 12; uint newValue7 = value & mask7 >> shift7; ps.RunningLights = (SubsurfacePlatformAppearance.RunningLightsValue)newValue7; uint mask9 = 0x8000; byte shift9 = 15; uint newValue9 = value & mask9 >> shift9; ps.Flaming = (SubsurfacePlatformAppearance.FlamingValue)newValue9; uint mask11 = 0x200000; byte shift11 = 21; uint newValue11 = value & mask11 >> shift11; ps.FrozenStatus = (SubsurfacePlatformAppearance.FrozenStatusValue)newValue11; uint mask12 = 0x400000; byte shift12 = 22; uint newValue12 = value & mask12 >> shift12; ps.PowerPlantStatus = (SubsurfacePlatformAppearance.PowerPlantStatusValue)newValue12; uint mask13 = 0x800000; byte shift13 = 23; uint newValue13 = value & mask13 >> shift13; ps.State = (SubsurfacePlatformAppearance.StateValue)newValue13; return ps; } /// <summary> /// Gets or sets the paintscheme. /// </summary> /// <value>The paintscheme.</value> public SubsurfacePlatformAppearance.PaintSchemeValue PaintScheme { get { return this.paintScheme; } set { this.paintScheme = value; } } /// <summary> /// Gets or sets the mobility. /// </summary> /// <value>The mobility.</value> public SubsurfacePlatformAppearance.MobilityValue Mobility { get { return this.mobility; } set { this.mobility = value; } } /// <summary> /// Gets or sets the damage. /// </summary> /// <value>The damage.</value> public SubsurfacePlatformAppearance.DamageValue Damage { get { return this.damage; } set { this.damage = value; } } /// <summary> /// Gets or sets the smoke. /// </summary> /// <value>The smoke.</value> public SubsurfacePlatformAppearance.SmokeValue Smoke { get { return this.smoke; } set { this.smoke = value; } } /// <summary> /// Gets or sets the hatch. /// </summary> /// <value>The hatch.</value> public SubsurfacePlatformAppearance.HatchValue Hatch { get { return this.hatch; } set { this.hatch = value; } } /// <summary> /// Gets or sets the runninglights. /// </summary> /// <value>The runninglights.</value> public SubsurfacePlatformAppearance.RunningLightsValue RunningLights { get { return this.runningLights; } set { this.runningLights = value; } } /// <summary> /// Gets or sets the flaming. /// </summary> /// <value>The flaming.</value> public SubsurfacePlatformAppearance.FlamingValue Flaming { get { return this.flaming; } set { this.flaming = value; } } /// <summary> /// Gets or sets the frozenstatus. /// </summary> /// <value>The frozenstatus.</value> public SubsurfacePlatformAppearance.FrozenStatusValue FrozenStatus { get { return this.frozenStatus; } set { this.frozenStatus = value; } } /// <summary> /// Gets or sets the powerplantstatus. /// </summary> /// <value>The powerplantstatus.</value> public SubsurfacePlatformAppearance.PowerPlantStatusValue PowerPlantStatus { get { return this.powerPlantStatus; } set { this.powerPlantStatus = value; } } /// <summary> /// Gets or sets the state. /// </summary> /// <value>The state.</value> public SubsurfacePlatformAppearance.StateValue State { get { return this.state; } set { this.state = value; } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { if (obj == null) { return false; } if (!(obj is SubsurfacePlatformAppearance)) { return false; } return this.Equals((SubsurfacePlatformAppearance)obj); } /// <summary> /// Determines whether the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> instance is equal to this instance. /// </summary> /// <param name="other">The <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> instance to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public bool Equals(SubsurfacePlatformAppearance other) { // If parameter is null return false (cast to object to prevent recursive loop!) if ((object)other == null) { return false; } return this.PaintScheme == other.PaintScheme && this.Mobility == other.Mobility && this.Damage == other.Damage && this.Smoke == other.Smoke && this.Hatch == other.Hatch && this.RunningLights == other.RunningLights && this.Flaming == other.Flaming && this.FrozenStatus == other.FrozenStatus && this.PowerPlantStatus == other.PowerPlantStatus && this.State == other.State; } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> to the byte array. /// </summary> /// <returns>The byte array representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> instance.</returns> public byte[] ToByteArray() { return BitConverter.GetBytes(this.ToUInt32()); } /// <summary> /// Converts the instance of <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> to the uint value. /// </summary> /// <returns>The uint value representing the current <see cref="OpenDis.Enumerations.EntityState.Appearance.SubsurfacePlatformAppearance"/> instance.</returns> public uint ToUInt32() { uint val = 0; val |= (uint)((uint)this.PaintScheme << 0); val |= (uint)((uint)this.Mobility << 1); val |= (uint)((uint)this.Damage << 3); val |= (uint)((uint)this.Smoke << 5); val |= (uint)((uint)this.Hatch << 9); val |= (uint)((uint)this.RunningLights << 12); val |= (uint)((uint)this.Flaming << 15); val |= (uint)((uint)this.FrozenStatus << 21); val |= (uint)((uint)this.PowerPlantStatus << 22); val |= (uint)((uint)this.State << 23); return val; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { int hash = 17; // Overflow is fine, just wrap unchecked { hash = (hash * 29) + this.PaintScheme.GetHashCode(); hash = (hash * 29) + this.Mobility.GetHashCode(); hash = (hash * 29) + this.Damage.GetHashCode(); hash = (hash * 29) + this.Smoke.GetHashCode(); hash = (hash * 29) + this.Hatch.GetHashCode(); hash = (hash * 29) + this.RunningLights.GetHashCode(); hash = (hash * 29) + this.Flaming.GetHashCode(); hash = (hash * 29) + this.FrozenStatus.GetHashCode(); hash = (hash * 29) + this.PowerPlantStatus.GetHashCode(); hash = (hash * 29) + this.State.GetHashCode(); } return hash; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Sensus.UI.UiProperties; using Newtonsoft.Json; using Sensus.Context; using Sensus.Callbacks; using Microsoft.AppCenter.Analytics; using Sensus.Extensions; using Sensus.Exceptions; #if __IOS__ using CoreLocation; #endif namespace Sensus.Probes { /// <summary> /// /// Polling Probes are triggered at regular intervals. When triggered, Polling Probes ask the device (and perhaps the user) for some type of /// information and store the resulting information in the <see cref="LocalDataStore"/>. /// /// # Background Considerations /// On Android, all Polling Probes are able to periodically wake up in the background, take a reading, and allow the system to go back to /// sleep. The Android operating system will occasionally delay the wake-up signal in order to batch wake-ups and thereby conserve energy; however, /// this delay is usually only 5-10 seconds. So, if you configure a Polling Probe to poll every 60 seconds, you may see actual polling delays of /// 65-70 seconds and maybe even more. This is by design within Android and cannot be changed. /// /// Polling on iOS is much less reliable. By design, iOS apps cannot perform processing in the background, with the exception of /// <see cref="Location.ListeningLocationProbe"/>. All other processing within Sensus must be halted when the user backgrounds the app. Furthermore, /// Sensus cannot wake itself up from the background in order to execute polling operations. Thus, Sensus has no reliable mechanism to support polling-style /// operations. Sensus does its best to support Polling Probes on iOS by scheduling notifications to appear when polling operations (e.g., taking /// a GPS reading) should execute. This relies on the user to open the notification from the tray and bring Sensus to the foreground so that the polling /// operation can execute. Of course, the user might not see the notification or might choose not to open it. The polling operation will not be executed /// in such cases. You should assume that Polling Probes will not produce data reliably on iOS. /// /// </summary> public abstract class PollingProbe : Probe { /// <summary> /// It's important to mitigate lag in polling operations since participation assessments are done on the basis of poll rates. /// </summary> private const bool POLL_CALLBACK_LAG = false; private int _pollingSleepDurationMS; private int _pollingTimeoutMinutes; private bool _isPolling; private List<DateTime> _pollTimes; private ScheduledCallback _pollCallback; #if __IOS__ private bool _significantChangePoll; private bool _significantChangePollOverridesScheduledPolls; private CLLocationManager _locationManager; #endif private readonly object _locker = new object(); /// <summary> /// How long to sleep (become inactive) between successive polling operations. /// </summary> /// <value>The polling sleep duration in milliseconds.</value> [EntryIntegerUiProperty("Sleep Duration (MS):", true, 5)] public virtual int PollingSleepDurationMS { get { return _pollingSleepDurationMS; } set { // we set this the same as CALLBACK_NOTIFICATION_HORIZON_THRESHOLD if (value <= 5000) { value = 5000; } _pollingSleepDurationMS = value; } } /// <summary> /// How long the <see cref="PollingProbe"/> has to complete a single poll operation before being cancelled. /// </summary> /// <value>The polling timeout minutes.</value> [EntryIntegerUiProperty("Timeout (Mins.):", true, 6)] public int PollingTimeoutMinutes { get { return _pollingTimeoutMinutes; } set { if (value < 1) { value = 1; } _pollingTimeoutMinutes = value; } } [JsonIgnore] public abstract int DefaultPollingSleepDurationMS { get; } protected override double RawParticipation { get { int oneDayMS = (int)new TimeSpan(1, 0, 0, 0).TotalMilliseconds; float pollsPerDay = oneDayMS / (float)_pollingSleepDurationMS; float fullParticipationPolls = pollsPerDay * Protocol.ParticipationHorizonDays; lock (_pollTimes) { return _pollTimes.Count(pollTime => pollTime >= Protocol.ParticipationHorizon) / fullParticipationPolls; } } } public List<DateTime> PollTimes { get { return _pollTimes; } } #if __IOS__ /// <summary> /// Available on iOS only. Whether or not to poll when a significant change in location has occurred. See /// [here](https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/LocationAwarenessPG/CoreLocation/CoreLocation.html) for /// more information on significant changes. /// </summary> /// <value><c>true</c> if significant change poll; otherwise, <c>false</c>.</value> [OnOffUiProperty("Significant Change Poll:", true, 7)] public bool SignificantChangePoll { get { return _significantChangePoll; } set { _significantChangePoll = value; } } /// <summary> /// Available on iOS only. Has no effect if significant-change polling is disabled. If significant-change polling is enabled: (1) If this /// is on, polling will only occur on significant changes. (2) If this is off, polling will occur based on <see cref="PollingSleepDurationMS"/> and /// on significant changes. /// </summary> /// <value><c>true</c> if significant change poll overrides scheduled polls; otherwise, <c>false</c>.</value> [OnOffUiProperty("Significant Change Poll Overrides Scheduled Polls:", true, 8)] public bool SignificantChangePollOverridesScheduledPolls { get { return _significantChangePollOverridesScheduledPolls; } set { _significantChangePollOverridesScheduledPolls = value; } } #endif public override string CollectionDescription { get { #if __IOS__ string significantChangeDescription = null; if (_significantChangePoll) { significantChangeDescription = "On significant changes in the device's location"; if (_significantChangePollOverridesScheduledPolls) { return DisplayName + ": " + significantChangeDescription + "."; } } #endif TimeSpan interval = new TimeSpan(0, 0, 0, 0, _pollingSleepDurationMS); double value = -1; string unit; int decimalPlaces = 0; if (interval.TotalSeconds <= 60) { value = interval.TotalSeconds; unit = "second"; decimalPlaces = 1; } else if (interval.TotalMinutes <= 60) { value = interval.TotalMinutes; unit = "minute"; } else if (interval.TotalHours <= 24) { value = interval.TotalHours; unit = "hour"; } else { value = interval.TotalDays; unit = "day"; } value = Math.Round(value, decimalPlaces); string intervalStr; if (value == 1) { intervalStr = "Once per " + unit + "."; } else { intervalStr = "Every " + value + " " + unit + "s."; } #if __IOS__ if (_significantChangePoll) { intervalStr = significantChangeDescription + "; and " + intervalStr.ToLower(); } #endif return DisplayName + ": " + intervalStr; } } protected PollingProbe() { _pollingSleepDurationMS = DefaultPollingSleepDurationMS; _pollingTimeoutMinutes = 5; _isPolling = false; _pollTimes = new List<DateTime>(); #if __IOS__ _significantChangePoll = false; _significantChangePollOverridesScheduledPolls = false; _locationManager = new CLLocationManager(); _locationManager.LocationsUpdated += async (sender, e) => { await Task.Run(async () => { try { CancellationTokenSource canceller = new CancellationTokenSource(); // if the callback specified a timeout, request cancellation at the specified time. if (_pollCallback.CallbackTimeout.HasValue) { canceller.CancelAfter(_pollCallback.CallbackTimeout.Value); } await _pollCallback.Action(_pollCallback.Id, canceller.Token, () => { }); } catch (Exception ex) { SensusException.Report("Failed significant change poll.", ex); } }); }; #endif } protected override void InternalStart() { lock (_locker) { base.InternalStart(); #if __IOS__ string userNotificationMessage = DisplayName + " data requested."; #elif __ANDROID__ string userNotificationMessage = null; #elif LOCAL_TESTS string userNotificationMessage = null; #else #warning "Unrecognized platform" string userNotificationMessage = null; #endif _pollCallback = new ScheduledCallback((callbackId, cancellationToken, letDeviceSleepCallback) => { return Task.Run(async () => { if (Running) { _isPolling = true; IEnumerable<Datum> data = null; try { SensusServiceHelper.Get().Logger.Log("Polling.", LoggingLevel.Normal, GetType()); data = Poll(cancellationToken); lock (_pollTimes) { _pollTimes.Add(DateTime.Now); _pollTimes.RemoveAll(pollTime => pollTime < Protocol.ParticipationHorizon); } } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to poll: " + ex.Message, LoggingLevel.Normal, GetType()); } if (data != null) { foreach (Datum datum in data) { if (cancellationToken.IsCancellationRequested) { break; } try { await StoreDatumAsync(datum, cancellationToken); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to store datum: " + ex.Message, LoggingLevel.Normal, GetType()); } } } _isPolling = false; } }); }, TimeSpan.Zero, TimeSpan.FromMilliseconds(_pollingSleepDurationMS), POLL_CALLBACK_LAG, GetType().FullName, Protocol.Id, Protocol, TimeSpan.FromMinutes(_pollingTimeoutMinutes), userNotificationMessage); #if __IOS__ if (_significantChangePoll) { _locationManager.RequestAlwaysAuthorization(); _locationManager.DistanceFilter = 5.0; _locationManager.PausesLocationUpdatesAutomatically = false; _locationManager.AllowsBackgroundLocationUpdates = true; if (CLLocationManager.LocationServicesEnabled) { _locationManager.StartMonitoringSignificantLocationChanges(); } else { SensusServiceHelper.Get().Logger.Log("Location services not enabled.", LoggingLevel.Normal, GetType()); } } // schedule the callback if we're not doing significant-change polling, or if we are but the latter doesn't override the former. if (!_significantChangePoll || !_significantChangePollOverridesScheduledPolls) { SensusContext.Current.CallbackScheduler.ScheduleCallback(_pollCallback); } #elif __ANDROID__ SensusContext.Current.CallbackScheduler.ScheduleCallback(_pollCallback); #endif } } protected abstract IEnumerable<Datum> Poll(CancellationToken cancellationToken); public override void Stop() { lock (_locker) { base.Stop(); #if __IOS__ if (_significantChangePoll) { _locationManager.StopMonitoringSignificantLocationChanges(); } #endif SensusContext.Current.CallbackScheduler.UnscheduleCallback(_pollCallback); _pollCallback = null; } } public override bool TestHealth(ref List<Tuple<string, Dictionary<string, string>>> events) { bool restart = base.TestHealth(ref events); if (Running) { #if __IOS__ // on ios we do significant-change polling, which can override scheduled polls. don't check for polling delays if the scheduled polls are overridden. if (_significantChangePoll && _significantChangePollOverridesScheduledPolls) { return restart; } #endif TimeSpan timeElapsedSincePreviousStore = DateTimeOffset.UtcNow - MostRecentStoreTimestamp.GetValueOrDefault(DateTimeOffset.MinValue); int allowedLagMS = 5000; if (!_isPolling && // don't raise a warning if the probe is currently trying to poll _pollingSleepDurationMS <= int.MaxValue - allowedLagMS && // some probes (iOS HealthKit for age) have polling delays set to int.MaxValue. if we add to this (as we're about to do in the next check), we'll wrap around to 0 resulting in incorrect statuses. only do the check if we won't wrap around. timeElapsedSincePreviousStore.TotalMilliseconds > (_pollingSleepDurationMS + allowedLagMS)) // system timer callbacks aren't always fired exactly as scheduled, resulting in health tests that identify warning conditions for delayed polling. allow a small fudge factor to ignore these warnings. { string eventName = TrackedEvent.Warning + ":" + GetType().Name; Dictionary<string, string> properties = new Dictionary<string, string> { { "Polling Latency", (timeElapsedSincePreviousStore.TotalMilliseconds - _pollingSleepDurationMS).Round(1000).ToString() } }; Analytics.TrackEvent(eventName, properties); events.Add(new Tuple<string, Dictionary<string, string>>(eventName, properties)); } if(!SensusContext.Current.CallbackScheduler.ContainsCallback(_pollCallback)) { string eventName = TrackedEvent.Error + ":" + GetType().Name; Dictionary<string, string> properties = new Dictionary<string, string> { { "Missing Callback", _pollCallback.Id } }; Analytics.TrackEvent(eventName, properties); events.Add(new Tuple<string, Dictionary<string, string>>(eventName, properties)); restart = true; } } return restart; } public override void Reset() { base.Reset(); _isPolling = false; _pollCallback = null; lock (_pollTimes) { _pollTimes.Clear(); } } } }
/* * Copyright 2008 ZXing 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. */ using System; using ByteMatrix = com.google.zxing.common.ByteMatrix; namespace com.google.zxing.qrcode.encoder { /// <author> satorux@google.com (Satoru Takabayashi) - creator /// </author> /// <author> dswitkin@google.com (Daniel Switkin) - ported from C++ /// </author> /// <author>www.Redivivus.in (suraj.supekar@redivivus.in) - Ported from ZXING Java Source /// </author> public sealed class MaskUtil { private MaskUtil() { // do nothing } // Apply mask penalty rule 1 and return the penalty. Find repetitive cells with the same color and // give penalty to them. Example: 00000 or 11111. public static int applyMaskPenaltyRule1(ByteMatrix matrix) { return applyMaskPenaltyRule1Internal(matrix, true) + applyMaskPenaltyRule1Internal(matrix, false); } // Apply mask penalty rule 2 and return the penalty. Find 2x2 blocks with the same color and give // penalty to them. public static int applyMaskPenaltyRule2(ByteMatrix matrix) { int penalty = 0; sbyte[][] array = matrix.Array; int width = matrix.Width; int height = matrix.Height; for (int y = 0; y < height - 1; ++y) { for (int x = 0; x < width - 1; ++x) { int value_Renamed = array[y][x]; if (value_Renamed == array[y][x + 1] && value_Renamed == array[y + 1][x] && value_Renamed == array[y + 1][x + 1]) { penalty += 3; } } } return penalty; } // Apply mask penalty rule 3 and return the penalty. Find consecutive cells of 00001011101 or // 10111010000, and give penalty to them. If we find patterns like 000010111010000, we give // penalties twice (i.e. 40 * 2). public static int applyMaskPenaltyRule3(ByteMatrix matrix) { int penalty = 0; sbyte[][] array = matrix.Array; int width = matrix.Width; int height = matrix.Height; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { // Tried to simplify following conditions but failed. if (x + 6 < width && array[y][x] == 1 && array[y][x + 1] == 0 && array[y][x + 2] == 1 && array[y][x + 3] == 1 && array[y][x + 4] == 1 && array[y][x + 5] == 0 && array[y][x + 6] == 1 && ((x + 10 < width && array[y][x + 7] == 0 && array[y][x + 8] == 0 && array[y][x + 9] == 0 && array[y][x + 10] == 0) || (x - 4 >= 0 && array[y][x - 1] == 0 && array[y][x - 2] == 0 && array[y][x - 3] == 0 && array[y][x - 4] == 0))) { penalty += 40; } if (y + 6 < height && array[y][x] == 1 && array[y + 1][x] == 0 && array[y + 2][x] == 1 && array[y + 3][x] == 1 && array[y + 4][x] == 1 && array[y + 5][x] == 0 && array[y + 6][x] == 1 && ((y + 10 < height && array[y + 7][x] == 0 && array[y + 8][x] == 0 && array[y + 9][x] == 0 && array[y + 10][x] == 0) || (y - 4 >= 0 && array[y - 1][x] == 0 && array[y - 2][x] == 0 && array[y - 3][x] == 0 && array[y - 4][x] == 0))) { penalty += 40; } } } return penalty; } // Apply mask penalty rule 4 and return the penalty. Calculate the ratio of dark cells and give // penalty if the ratio is far from 50%. It gives 10 penalty for 5% distance. Examples: // - 0% => 100 // - 40% => 20 // - 45% => 10 // - 50% => 0 // - 55% => 10 // - 55% => 20 // - 100% => 100 public static int applyMaskPenaltyRule4(ByteMatrix matrix) { int numDarkCells = 0; sbyte[][] array = matrix.Array; int width = matrix.Width; int height = matrix.Height; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { if (array[y][x] == 1) { numDarkCells += 1; } } } int numTotalCells = matrix.Height * matrix.Width; double darkRatio = (double) numDarkCells / numTotalCells; //UPGRADE_WARNING: Data types in Visual C# might be different. Verify the accuracy of narrowing conversions. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1042'" return System.Math.Abs((int) (darkRatio * 100 - 50)) / 5 * 10; } // Return the mask bit for "getMaskPattern" at "x" and "y". See 8.8 of JISX0510:2004 for mask // pattern conditions. public static bool getDataMaskBit(int maskPattern, int x, int y) { if (!QRCode.isValidMaskPattern(maskPattern)) { throw new System.ArgumentException("Invalid mask pattern"); } int intermediate, temp; switch (maskPattern) { case 0: intermediate = (y + x) & 0x1; break; case 1: intermediate = y & 0x1; break; case 2: intermediate = x % 3; break; case 3: intermediate = (y + x) % 3; break; case 4: intermediate = ((SupportClass.URShift(y, 1)) + (x / 3)) & 0x1; break; case 5: temp = y * x; intermediate = (temp & 0x1) + (temp % 3); break; case 6: temp = y * x; intermediate = (((temp & 0x1) + (temp % 3)) & 0x1); break; case 7: temp = y * x; intermediate = (((temp % 3) + ((y + x) & 0x1)) & 0x1); break; default: throw new System.ArgumentException("Invalid mask pattern: " + maskPattern); } return intermediate == 0; } // Helper function for applyMaskPenaltyRule1. We need this for doing this calculation in both // vertical and horizontal orders respectively. private static int applyMaskPenaltyRule1Internal(ByteMatrix matrix, bool isHorizontal) { int penalty = 0; int numSameBitCells = 0; int prevBit = - 1; // Horizontal mode: // for (int i = 0; i < matrix.height(); ++i) { // for (int j = 0; j < matrix.width(); ++j) { // int bit = matrix.get(i, j); // Vertical mode: // for (int i = 0; i < matrix.width(); ++i) { // for (int j = 0; j < matrix.height(); ++j) { // int bit = matrix.get(j, i); int iLimit = isHorizontal?matrix.Height:matrix.Width; int jLimit = isHorizontal?matrix.Width:matrix.Height; sbyte[][] array = matrix.Array; for (int i = 0; i < iLimit; ++i) { for (int j = 0; j < jLimit; ++j) { int bit = isHorizontal?array[i][j]:array[j][i]; if (bit == prevBit) { numSameBitCells += 1; // Found five repetitive cells with the same color (bit). // We'll give penalty of 3. if (numSameBitCells == 5) { penalty += 3; } else if (numSameBitCells > 5) { // After five repetitive cells, we'll add the penalty one // by one. penalty += 1; } } else { numSameBitCells = 1; // Include the cell itself. prevBit = bit; } } numSameBitCells = 0; // Clear at each row/column. } return penalty; } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Generic; using System.Collections; using System.Management.Automation; using System.Management.Automation.Internal; using System.Globalization; using Microsoft.PowerShell.Commands.Internal.Format; using System.Diagnostics.CodeAnalysis; namespace Microsoft.PowerShell.Commands { /// <summary> /// definitions for hash table keys /// </summary> internal static class SortObjectParameterDefinitionKeys { internal const string AscendingEntryKey = "ascending"; internal const string DescendingEntryKey = "descending"; } /// <summary> /// </summary> internal class SortObjectExpressionParameterDefinition : CommandParameterDefinition { protected override void SetEntries() { this.hashEntries.Add(new ExpressionEntryDefinition(false)); this.hashEntries.Add(new BooleanEntryDefinition(SortObjectParameterDefinitionKeys.AscendingEntryKey)); this.hashEntries.Add(new BooleanEntryDefinition(SortObjectParameterDefinitionKeys.DescendingEntryKey)); } } /// <summary> /// </summary> internal class GroupObjectExpressionParameterDefinition : CommandParameterDefinition { protected override void SetEntries() { this.hashEntries.Add(new ExpressionEntryDefinition(true)); } } /// <summary> /// Base Cmdlet for cmdlets which deal with raw objects /// </summary> public class ObjectCmdletBase : PSCmdlet { #region Parameters /// <summary> /// /// </summary> /// <value></value> [Parameter] [System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "The CultureNumber is only used if the property has been set with a hex string starting with 0x")] public string Culture { get { return _cultureInfo != null ? _cultureInfo.ToString() : null; } set { if (string.IsNullOrEmpty(value)) { _cultureInfo = null; return; } #if !CORECLR //TODO: CORECLR 'new CultureInfo(Int32)' not available yet. int cultureNumber; string trimmedValue = value.Trim(); if (trimmedValue.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) { if ((trimmedValue.Length > 2) && int.TryParse(trimmedValue.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.CurrentCulture, out cultureNumber)) { _cultureInfo = new CultureInfo(cultureNumber); return; } } else if (int.TryParse(trimmedValue, NumberStyles.AllowThousands, CultureInfo.CurrentCulture, out cultureNumber)) { _cultureInfo = new CultureInfo(cultureNumber); return; } #endif _cultureInfo = new CultureInfo(value); } } internal CultureInfo _cultureInfo = null; /// <summary> /// /// </summary> /// <value></value> [Parameter] public SwitchParameter CaseSensitive { get { return _caseSensitive; } set { _caseSensitive = value; } } private bool _caseSensitive; #endregion Parameters } /// <summary> /// Base Cmdlet for object cmdlets that deal with Grouping, Sorting and Comparison. /// </summary> public abstract class ObjectBase : ObjectCmdletBase { #region Parameters /// <summary> /// /// </summary> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set; get; } = AutomationNull.Value; /// <summary> /// Gets or Sets the Properties that would be used for Grouping, Sorting and Comparison. /// </summary> [Parameter(Position = 0)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] Property { get; set; } #endregion Parameters } /// <summary> /// Base Cmdlet for object cmdlets that deal with Ordering and Comparison. /// </summary> public class OrderObjectBase : ObjectBase { #region Internal Properties /// <summary> /// Specifies sorting order. /// </summary> internal SwitchParameter DescendingOrder { get { return !_ascending; } set { _ascending = !value; } } private bool _ascending = true; internal List<PSObject> InputObjects { get; } = new List<PSObject>(); /// <summary> /// CultureInfo converted from the Culture Cmdlet parameter /// </summary> internal CultureInfo ConvertedCulture { get { return _cultureInfo; } } #endregion Internal Properties /// <summary> /// /// Simply accumulates the incoming objects /// /// </summary> protected override void ProcessRecord() { if (InputObject != null && InputObject != AutomationNull.Value) { InputObjects.Add(InputObject); } } } internal sealed class OrderByProperty { #region Internal properties /// <summary> /// a logical matrix where each row is an input object and its property values specified by Properties /// </summary> internal List<OrderByPropertyEntry> OrderMatrix { get; } = null; internal OrderByPropertyComparer Comparer { get; } = null; internal List<MshParameter> MshParameterList { get { return _mshParameterList; } } #endregion Internal properties #region Utils // These are made static for Measure-Object's GroupBy parameter that measure the outputs of Group-Object // However, Measure-Object differs from Group-Object and Sort-Object considerably that it should not // be built on the same base class, i.e., this class. Moreover, Measure-Object's Property parameter is // a string array and allows wildcard. // Yes, the Cmdlet is needed. It's used to get the TerminatingErrorContext, WriteError and WriteDebug. #region process MshExpression and MshParameter private static void ProcessExpressionParameter( List<PSObject> inputObjects, PSCmdlet cmdlet, object[] expr, out List<MshParameter> mshParameterList) { mshParameterList = null; TerminatingErrorContext invocationContext = new TerminatingErrorContext(cmdlet); // compare-object and group-object use the same definition here ParameterProcessor processor = cmdlet is SortObjectCommand ? new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); if (expr == null && inputObjects != null && inputObjects.Count > 0) { expr = GetDefaultKeyPropertySet(inputObjects[0]); } if (expr != null) { List<MshParameter> unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); mshParameterList = ExpandExpressions(inputObjects, unexpandedParameterList); } // NOTE: if no parameters are passed, we will look at the default keys of the first // incoming object } internal void ProcessExpressionParameter( PSCmdlet cmdlet, object[] expr) { TerminatingErrorContext invocationContext = new TerminatingErrorContext(cmdlet); // compare-object and group-object use the same definition here ParameterProcessor processor = cmdlet is SortObjectCommand ? new ParameterProcessor(new SortObjectExpressionParameterDefinition()) : new ParameterProcessor(new GroupObjectExpressionParameterDefinition()); if (expr != null) { if (_unexpandedParameterList == null) { _unexpandedParameterList = processor.ProcessParameters(expr, invocationContext); foreach (MshParameter unexpandedParameter in _unexpandedParameterList) { MshExpression mshExpression = (MshExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); if (!mshExpression.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings { _mshParameterList.Add(unexpandedParameter); } else { if (_unExpandedParametersWithWildCardPattern == null) { _unExpandedParametersWithWildCardPattern = new List<MshParameter>(); } _unExpandedParametersWithWildCardPattern.Add(unexpandedParameter); } } } } } // Expand a list of (possibly wildcarded) expressions into resolved expressions that // match property names on the incoming objects. private static List<MshParameter> ExpandExpressions(List<PSObject> inputObjects, List<MshParameter> unexpandedParameterList) { List<MshParameter> expandedParameterList = new List<MshParameter>(); if (unexpandedParameterList != null) { foreach (MshParameter unexpandedParameter in unexpandedParameterList) { MshExpression ex = (MshExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); if (!ex.HasWildCardCharacters) // this special cases 1) script blocks and 2) wildcard-less strings { expandedParameterList.Add(unexpandedParameter); } else { SortedDictionary<string, MshExpression> expandedPropertyNames = new SortedDictionary<string, MshExpression>(StringComparer.OrdinalIgnoreCase); if (inputObjects != null) { foreach (object inputObject in inputObjects) { if (inputObject == null) { continue; } foreach (MshExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject))) { expandedPropertyNames[resolvedName.ToString()] = resolvedName; } } } foreach (MshExpression expandedExpression in expandedPropertyNames.Values) { MshParameter expandedParameter = new MshParameter(); expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone(); expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression; expandedParameterList.Add(expandedParameter); } } } } return expandedParameterList; } // Expand a list of (possibly wildcarded) expressions into resolved expressions that // match property names on the incoming objects. private static void ExpandExpressions(PSObject inputObject, List<MshParameter> UnexpandedParametersWithWildCardPattern, List<MshParameter> expandedParameterList) { if (UnexpandedParametersWithWildCardPattern != null) { foreach (MshParameter unexpandedParameter in UnexpandedParametersWithWildCardPattern) { MshExpression ex = (MshExpression)unexpandedParameter.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey); SortedDictionary<string, MshExpression> expandedPropertyNames = new SortedDictionary<string, MshExpression>(StringComparer.OrdinalIgnoreCase); if (inputObject == null) { continue; } foreach (MshExpression resolvedName in ex.ResolveNames(PSObject.AsPSObject(inputObject))) { expandedPropertyNames[resolvedName.ToString()] = resolvedName; } foreach (MshExpression expandedExpression in expandedPropertyNames.Values) { MshParameter expandedParameter = new MshParameter(); expandedParameter.hash = (Hashtable)unexpandedParameter.hash.Clone(); expandedParameter.hash[FormatParameterDefinitionKeys.ExpressionEntryKey] = expandedExpression; expandedParameterList.Add(expandedParameter); } } } } internal static string[] GetDefaultKeyPropertySet(PSObject mshObj) { PSMemberSet standardNames = mshObj.PSStandardMembers; if (standardNames == null) { return null; } PSPropertySet defaultKeys = standardNames.Members["DefaultKeyPropertySet"] as PSPropertySet; if (defaultKeys == null) { return null; } string[] props = new string[defaultKeys.ReferencedPropertyNames.Count]; defaultKeys.ReferencedPropertyNames.CopyTo(props, 0); return props; } #endregion process MshExpression and MshParameter internal static List<OrderByPropertyEntry> CreateOrderMatrix( PSCmdlet cmdlet, List<PSObject> inputObjects, List<MshParameter> mshParameterList ) { List<OrderByPropertyEntry> orderMatrixToCreate = new List<OrderByPropertyEntry>(); foreach (PSObject so in inputObjects) { if (so == null || so == AutomationNull.Value) continue; List<ErrorRecord> evaluationErrors = new List<ErrorRecord>(); List<string> propertyNotFoundMsgs = new List<string>(); OrderByPropertyEntry result = OrderByPropertyEntryEvaluationHelper.ProcessObject(so, mshParameterList, evaluationErrors, propertyNotFoundMsgs); foreach (ErrorRecord err in evaluationErrors) { cmdlet.WriteError(err); } foreach (string debugMsg in propertyNotFoundMsgs) { cmdlet.WriteDebug(debugMsg); } orderMatrixToCreate.Add(result); } return orderMatrixToCreate; } private static bool isOrderEntryKeyDefined(object orderEntryKey) { return orderEntryKey != null && orderEntryKey != AutomationNull.Value; } private static OrderByPropertyComparer CreateComparer( List<OrderByPropertyEntry> orderMatrix, List<MshParameter> mshParameterList, bool ascending, CultureInfo cultureInfo, bool caseSensitive) { if (orderMatrix == null || orderMatrix.Count == 0) { return null; } Nullable<bool>[] ascendingOverrides = null; if (mshParameterList != null && mshParameterList.Count != 0) { ascendingOverrides = new Nullable<bool>[mshParameterList.Count]; for (int k = 0; k < ascendingOverrides.Length; k++) { object ascendingVal = mshParameterList[k].GetEntry( SortObjectParameterDefinitionKeys.AscendingEntryKey); object descendingVal = mshParameterList[k].GetEntry( SortObjectParameterDefinitionKeys.DescendingEntryKey); bool isAscendingDefined = isOrderEntryKeyDefined(ascendingVal); bool isDescendingDefined = isOrderEntryKeyDefined(descendingVal); if (!isAscendingDefined && !isDescendingDefined) { // if neither ascending nor descending is defined ascendingOverrides[k] = null; } else if (isAscendingDefined && isDescendingDefined && (bool)ascendingVal == (bool)descendingVal) { // if both ascending and descending defined but their values conflict // they are ignored. ascendingOverrides[k] = null; } else if (isAscendingDefined) { ascendingOverrides[k] = (bool)ascendingVal; } else { ascendingOverrides[k] = !(bool)descendingVal; } } } OrderByPropertyComparer comparer = OrderByPropertyComparer.CreateComparer(orderMatrix, ascending, ascendingOverrides, cultureInfo, caseSensitive); return comparer; } internal OrderByProperty( PSCmdlet cmdlet, List<PSObject> inputObjects, object[] expr, bool ascending, CultureInfo cultureInfo, bool caseSensitive ) { Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); ProcessExpressionParameter(inputObjects, cmdlet, expr, out _mshParameterList); OrderMatrix = CreateOrderMatrix(cmdlet, inputObjects, _mshParameterList); Comparer = CreateComparer(OrderMatrix, _mshParameterList, ascending, cultureInfo, caseSensitive); } /// <summary> /// OrderByProperty constructor. /// </summary> internal OrderByProperty() { _mshParameterList = new List<MshParameter>(); OrderMatrix = new List<OrderByPropertyEntry>(); } /// <summary> /// Utility function used to create OrderByPropertyEntry for the supplied input object. /// </summary> /// <param name="cmdlet">PSCmdlet</param> /// <param name="inputObject">Input Object.</param> /// <param name="isCaseSensitive">Indicates if the Property value comparisons need to be case sensitive or not.</param> /// <param name="cultureInfo">Culture Info that needs to be used for comparison.</param> /// <returns>OrderByPropertyEntry for the supplied InputObject.</returns> internal OrderByPropertyEntry CreateOrderByPropertyEntry( PSCmdlet cmdlet, PSObject inputObject, bool isCaseSensitive, CultureInfo cultureInfo) { Diagnostics.Assert(cmdlet != null, "cmdlet must be an instance"); if (_unExpandedParametersWithWildCardPattern != null) { ExpandExpressions(inputObject, _unExpandedParametersWithWildCardPattern, _mshParameterList); } List<ErrorRecord> evaluationErrors = new List<ErrorRecord>(); List<string> propertyNotFoundMsgs = new List<string>(); OrderByPropertyEntry result = OrderByPropertyEntryEvaluationHelper.ProcessObject(inputObject, _mshParameterList, evaluationErrors, propertyNotFoundMsgs, isCaseSensitive, cultureInfo); foreach (ErrorRecord err in evaluationErrors) { cmdlet.WriteError(err); } foreach (string debugMsg in propertyNotFoundMsgs) { cmdlet.WriteDebug(debugMsg); } return result; } #endregion Utils // list of processed parameters obtained from the Expression array private List<MshParameter> _mshParameterList = null; // list of unprocessed parameters obtained from the Expression array. private List<MshParameter> _unexpandedParameterList = null; // list of unprocessed parameters with wild card patterns. private List<MshParameter> _unExpandedParametersWithWildCardPattern = null; } internal static class OrderByPropertyEntryEvaluationHelper { internal static OrderByPropertyEntry ProcessObject(PSObject inputObject, List<MshParameter> mshParameterList, List<ErrorRecord> errors, List<string> propertyNotFoundMsgs, bool isCaseSensitive = false, CultureInfo cultureInfo = null) { Diagnostics.Assert(errors != null, "errors cannot be null!"); Diagnostics.Assert(propertyNotFoundMsgs != null, "propertyNotFoundMsgs cannot be null!"); OrderByPropertyEntry entry = new OrderByPropertyEntry(); entry.inputObject = inputObject; if (mshParameterList == null || mshParameterList.Count == 0) { // we do not have a property to evaluate, we sort on $_ entry.orderValues.Add(new ObjectCommandPropertyValue(inputObject, isCaseSensitive, cultureInfo)); return entry; } // we need to compute the properties foreach (MshParameter p in mshParameterList) { string propertyNotFoundMsg = null; EvaluateSortingExpression(p, inputObject, entry.orderValues, errors, out propertyNotFoundMsg); if (!string.IsNullOrEmpty(propertyNotFoundMsg)) { propertyNotFoundMsgs.Add(propertyNotFoundMsg); } } return entry; } private static void EvaluateSortingExpression( MshParameter p, PSObject inputObject, List<ObjectCommandPropertyValue> orderValues, List<ErrorRecord> errors, out string propertyNotFoundMsg) { // NOTE: we assume globbing was not allowed in input MshExpression ex = p.GetEntry(FormatParameterDefinitionKeys.ExpressionEntryKey) as MshExpression; // get the values, but do not expand aliases List<MshExpressionResult> expressionResults = ex.GetValues(inputObject, false, true); if (expressionResults.Count == 0) { // we did not get any result out of the expression: // we enter a null as a place holder orderValues.Add(ObjectCommandPropertyValue.NonExistingProperty); propertyNotFoundMsg = StringUtil.Format(SortObjectStrings.PropertyNotFound, ex.ToString()); return; } propertyNotFoundMsg = null; // we obtained some results, enter them into the list foreach (MshExpressionResult r in expressionResults) { if (r.Exception == null) { orderValues.Add(new ObjectCommandPropertyValue(r.Result)); } else { ErrorRecord errorRecord = new ErrorRecord( r.Exception, "ExpressionEvaluation", ErrorCategory.InvalidResult, inputObject); errors.Add(errorRecord); orderValues.Add(ObjectCommandPropertyValue.ExistingNullProperty); } } } } /// <summary> /// This is the row of the OrderMatrix /// </summary> internal sealed class OrderByPropertyEntry { internal PSObject inputObject = null; internal List<ObjectCommandPropertyValue> orderValues = new List<ObjectCommandPropertyValue>(); } internal class OrderByPropertyComparer : IComparer<OrderByPropertyEntry> { internal OrderByPropertyComparer(bool[] ascending, CultureInfo cultureInfo, bool caseSensitive) { _propertyComparers = new ObjectCommandComparer[ascending.Length]; for (int k = 0; k < ascending.Length; k++) { _propertyComparers[k] = new ObjectCommandComparer(ascending[k], cultureInfo, caseSensitive); } } public int Compare(OrderByPropertyEntry firstEntry, OrderByPropertyEntry secondEntry) { // we have to take into consideration that some vectors // might be shorter than others int order = 0; for (int k = 0; k < _propertyComparers.Length; k++) { ObjectCommandPropertyValue firstValue = (k < firstEntry.orderValues.Count) ? firstEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty; ObjectCommandPropertyValue secondValue = (k < secondEntry.orderValues.Count) ? secondEntry.orderValues[k] : ObjectCommandPropertyValue.NonExistingProperty; order = _propertyComparers[k].Compare(firstValue, secondValue); if (order != 0) return order; } return order; } internal static OrderByPropertyComparer CreateComparer(List<OrderByPropertyEntry> orderMatrix, bool ascendingFlag, Nullable<bool>[] ascendingOverrides, CultureInfo cultureInfo, bool caseSensitive) { if (orderMatrix.Count == 0) return null; // create a comparer able to handle a vector of N entries, // where N is the max number of entries int maxEntries = 0; foreach (OrderByPropertyEntry entry in orderMatrix) { if (entry.orderValues.Count > maxEntries) maxEntries = entry.orderValues.Count; } if (maxEntries == 0) return null; bool[] ascending = new bool[maxEntries]; for (int k = 0; k < maxEntries; k++) { if (ascendingOverrides != null && ascendingOverrides[k].HasValue) { ascending[k] = ascendingOverrides[k].Value; } else { ascending[k] = ascendingFlag; } } // NOTE: the size of the boolean array will determine the max width of the // vectors to check return new OrderByPropertyComparer(ascending, cultureInfo, caseSensitive); } private ObjectCommandComparer[] _propertyComparers = null; } }
/* * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Microsoft.CSharp; namespace Avro { /// <summary> /// Generates C# code from Avro schemas and protocols. /// </summary> public class CodeGen { /// <summary> /// Gets object that contains all the generated types. /// </summary> /// <value> /// The code compile unit. /// </value> public CodeCompileUnit CompileUnit { get; private set; } /// <summary> /// Gets list of schemas to generate code for. /// </summary> /// <value> /// The schemas. /// </value> public IList<Schema> Schemas { get; private set; } /// <summary> /// Gets list of protocols to generate code for. /// </summary> /// <value> /// The protocols. /// </value> public IList<Protocol> Protocols { get; private set; } /// <summary> /// Gets mapping of Avro namespaces to C# namespaces. /// </summary> /// <value> /// The namespace mapping. /// </value> public IDictionary<string, string> NamespaceMapping { get; private set; } /// <summary> /// Gets list of generated namespaces. /// </summary> /// <value> /// The namespace lookup. /// </value> protected Dictionary<string, CodeNamespace> NamespaceLookup { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="CodeGen"/> class. /// </summary> public CodeGen() { Schemas = new List<Schema>(); Protocols = new List<Protocol>(); NamespaceMapping = new Dictionary<string, string>(); NamespaceLookup = new Dictionary<string, CodeNamespace>(StringComparer.Ordinal); } /// <summary> /// Initializes a new instance of the <see cref="CodeGen" /> class. /// </summary> /// <param name="namespaceLookup">The namespace lookup.</param> public CodeGen(Dictionary<string, CodeNamespace> namespaceLookup) : this() { NamespaceLookup = namespaceLookup; } /// <summary> /// Adds a protocol object to generate code for. /// </summary> /// <param name="protocol">The protocol.</param> public virtual void AddProtocol(Protocol protocol) { Protocols.Add(protocol); } /// <summary> /// Adds a schema object to generate code for. /// </summary> /// <param name="schema">schema object.</param> public virtual void AddSchema(Schema schema) { Schemas.Add(schema); } /// <summary> /// Adds a namespace object for the given name into the dictionary if it doesn't exist yet. /// </summary> /// <param name="name">name of namespace.</param> /// <returns> /// Code Namespace. /// </returns> /// <exception cref="ArgumentNullException">name - name cannot be null.</exception> protected virtual CodeNamespace AddNamespace(string name) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name), "name cannot be null."); } if (!NamespaceLookup.TryGetValue(name, out CodeNamespace ns)) { ns = NamespaceMapping.TryGetValue(name, out string csharpNamespace) ? new CodeNamespace(csharpNamespace) : new CodeNamespace(CodeGenUtil.Instance.Mangle(name)); foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports) { ns.Imports.Add(nci); } CompileUnit.Namespaces.Add(ns); NamespaceLookup.Add(name, ns); } return ns; } /// <summary> /// Adds a namespace object for the given name into the dictionary if it doesn't exist yet. /// </summary> /// <param name="name">name of namespace.</param> /// <returns> /// Code Namespace. /// </returns> /// <exception cref="ArgumentNullException">name - name cannot be null.</exception> [Obsolete("This method is deprecated and it will be removed in a future release! Please change call to AddNamespace(string name).")] protected virtual CodeNamespace addNamespace(string name) { return AddNamespace(name); } /// <summary> /// Generates code for the given protocol and schema objects. /// </summary> /// <returns> /// CodeCompileUnit object. /// </returns> public virtual CodeCompileUnit GenerateCode() { CompileUnit = new CodeCompileUnit(); ProcessSchemas(); ProcessProtocols(); return CompileUnit; } /// <summary> /// Generates code for the schema objects. /// </summary> /// <exception cref="CodeGenException">Names in schema should only be of type NamedSchema, type found " + sn.Value.Tag.</exception> protected virtual void ProcessSchemas() { foreach (Schema schema in Schemas) { SchemaNames names = GenerateNames(schema); foreach (KeyValuePair<SchemaName, NamedSchema> sn in names) { switch (sn.Value.Tag) { case Schema.Type.Enumeration: processEnum(sn.Value); break; case Schema.Type.Fixed: processFixed(sn.Value); break; case Schema.Type.Record: processRecord(sn.Value); break; case Schema.Type.Error: processRecord(sn.Value); break; default: throw new CodeGenException("Names in schema should only be of type NamedSchema, type found " + sn.Value.Tag); } } } } /// <summary> /// Generates code for the schema objects. /// </summary> /// <exception cref="CodeGenException">Names in schema should only be of type NamedSchema, type found " + sn.Value.Tag.</exception> [Obsolete("This method is deprecated and it will be removed in a future release! Please change call to ProcessSchemas().")] protected virtual void processSchemas() { ProcessSchemas(); } /// <summary> /// Generates code for the protocol objects. /// </summary> /// <exception cref="CodeGenException">Names in protocol should only be of type NamedSchema, type found {sn.Value.Tag}</exception> protected virtual void ProcessProtocols() { foreach (Protocol protocol in Protocols) { SchemaNames names = GenerateNames(protocol); foreach (KeyValuePair<SchemaName, NamedSchema> sn in names) { switch (sn.Value.Tag) { case Schema.Type.Enumeration: processEnum(sn.Value); break; case Schema.Type.Fixed: processFixed(sn.Value); break; case Schema.Type.Record: processRecord(sn.Value); break; case Schema.Type.Error: processRecord(sn.Value); break; default: throw new CodeGenException($"Names in protocol should only be of type NamedSchema, type found {sn.Value.Tag}"); } } processInterface(protocol); } } /// <summary> /// Generates code for the protocol objects. /// </summary> /// <exception cref="CodeGenException">Names in protocol should only be of type NamedSchema, type found {sn.Value.Tag}</exception> [Obsolete("This method is deprecated and it will be removed in a future release! Please change call to ProcessProtocols().")] protected virtual void processProtocols() { ProcessProtocols(); } /// <summary> /// Generate list of named schemas from given protocol. /// </summary> /// <param name="protocol">protocol to process.</param> /// <returns> /// List of named schemas. /// </returns> /// <exception cref="ArgumentNullException">protocol - Protocol can not be null.</exception> [Obsolete("This method is deprecated and it will be removed in a future release! Please use GenerateNames() instead.")] protected virtual SchemaNames generateNames(Protocol protocol) { return GenerateNames(protocol); } /// <summary> /// Generate list of named schemas from given protocol. /// </summary> /// <param name="protocol">protocol to process.</param> /// <returns> /// List of named schemas. /// </returns> /// <exception cref="ArgumentNullException">protocol - Protocol can not be null.</exception> protected virtual SchemaNames GenerateNames(Protocol protocol) { if (protocol == null) { throw new ArgumentNullException(nameof(protocol), "Protocol can not be null"); } var names = new SchemaNames(); foreach (Schema schema in protocol.Types) { addName(schema, names); } return names; } /// <summary> /// Generate list of named schemas from given schema. /// </summary> /// <param name="schema">schema to process.</param> /// <returns> /// List of named schemas. /// </returns> [Obsolete("This method is deprecated and it will be removed in a future release! Please use GenerateNames() instead.")] protected virtual SchemaNames generateNames(Schema schema) { return GenerateNames(schema); } /// <summary> /// Generate list of named schemas from given schema. /// </summary> /// <param name="schema">schema to process.</param> /// <returns> /// List of named schemas. /// </returns> protected virtual SchemaNames GenerateNames(Schema schema) { var names = new SchemaNames(); addName(schema, names); return names; } /// <summary> /// Recursively search the given schema for named schemas and adds them to the given container. /// </summary> /// <param name="schema">schema object to search.</param> /// <param name="names">list of named schemas.</param> /// <exception cref="CodeGenException">Unable to add name for " + schema.Name + " type " + schema.Tag.</exception> protected virtual void addName(Schema schema, SchemaNames names) { NamedSchema ns = schema as NamedSchema; if (ns != null && names.Contains(ns.SchemaName)) { return; } switch (schema.Tag) { case Schema.Type.Null: case Schema.Type.Boolean: case Schema.Type.Int: case Schema.Type.Long: case Schema.Type.Float: case Schema.Type.Double: case Schema.Type.Bytes: case Schema.Type.String: case Schema.Type.Logical: break; case Schema.Type.Enumeration: case Schema.Type.Fixed: names.Add(ns); break; case Schema.Type.Record: case Schema.Type.Error: var rs = schema as RecordSchema; names.Add(rs); foreach (Field field in rs.Fields) { addName(field.Schema, names); } break; case Schema.Type.Array: var asc = schema as ArraySchema; addName(asc.ItemSchema, names); break; case Schema.Type.Map: var ms = schema as MapSchema; addName(ms.ValueSchema, names); break; case Schema.Type.Union: var us = schema as UnionSchema; foreach (Schema usc in us.Schemas) { addName(usc, names); } break; default: throw new CodeGenException("Unable to add name for " + schema.Name + " type " + schema.Tag); } } /// <summary> /// Creates a class declaration for fixed schema. /// </summary> /// <param name="schema">fixed schema.</param> /// <exception cref="CodeGenException"> /// Unable to cast schema into a fixed /// or /// Namespace required for enum schema " + fixedSchema.Name. /// </exception> protected virtual void processFixed(Schema schema) { FixedSchema fixedSchema = schema as FixedSchema; if (fixedSchema == null) { throw new CodeGenException("Unable to cast schema into a fixed"); } CodeTypeDeclaration ctd = new CodeTypeDeclaration(); ctd.Name = CodeGenUtil.Instance.Mangle(fixedSchema.Name); ctd.IsClass = true; ctd.IsPartial = true; ctd.Attributes = MemberAttributes.Public; ctd.BaseTypes.Add("SpecificFixed"); if (fixedSchema.Documentation != null) { ctd.Comments.Add(createDocComment(fixedSchema.Documentation)); } // create static schema field createSchemaField(schema, ctd, true); // Add Size field string sizefname = "fixedSize"; var ctrfield = new CodeTypeReference(typeof(uint)); var codeField = new CodeMemberField(ctrfield, sizefname); codeField.Attributes = MemberAttributes.Private | MemberAttributes.Static; codeField.InitExpression = new CodePrimitiveExpression(fixedSchema.Size); ctd.Members.Add(codeField); // Add Size property var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Static; property.Name = "FixedSize"; property.Type = ctrfield; property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(schema.Name + "." + sizefname))); ctd.Members.Add(property); // create constructor to initiate base class SpecificFixed CodeConstructor cc = new CodeConstructor(); cc.Attributes = MemberAttributes.Public; cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(sizefname)); ctd.Members.Add(cc); string nspace = fixedSchema.Namespace; if (string.IsNullOrEmpty(nspace)) { throw new CodeGenException("Namespace required for enum schema " + fixedSchema.Name); } CodeNamespace codens = AddNamespace(nspace); codens.Types.Add(ctd); } /// <summary> /// Creates an enum declaration. /// </summary> /// <param name="schema">enum schema.</param> /// <exception cref="CodeGenException"> /// Unable to cast schema into an enum /// or /// Enum symbol " + symbol + " is a C# reserved keyword /// or /// Namespace required for enum schema " + enumschema.Name. /// </exception> protected virtual void processEnum(Schema schema) { EnumSchema enumschema = schema as EnumSchema; if (enumschema == null) { throw new CodeGenException("Unable to cast schema into an enum"); } CodeTypeDeclaration ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(enumschema.Name)); ctd.IsEnum = true; ctd.Attributes = MemberAttributes.Public; if (enumschema.Documentation != null) { ctd.Comments.Add(createDocComment(enumschema.Documentation)); } foreach (string symbol in enumschema.Symbols) { if (CodeGenUtil.Instance.ReservedKeywords.Contains(symbol)) { throw new CodeGenException("Enum symbol " + symbol + " is a C# reserved keyword"); } CodeMemberField field = new CodeMemberField(typeof(int), symbol); ctd.Members.Add(field); } string nspace = enumschema.Namespace; if (string.IsNullOrEmpty(nspace)) { throw new CodeGenException("Namespace required for enum schema " + enumschema.Name); } CodeNamespace codens = AddNamespace(nspace); codens.Types.Add(ctd); } /// <summary> /// Generates code for an individual protocol. /// </summary> /// <param name="protocol">Protocol to generate code for.</param> /// <exception cref="CodeGenException">Namespace required for enum schema " + nspace.</exception> protected virtual void processInterface(Protocol protocol) { // Create abstract class string protocolNameMangled = CodeGenUtil.Instance.Mangle(protocol.Name); var ctd = new CodeTypeDeclaration(protocolNameMangled); ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public; ctd.IsClass = true; ctd.BaseTypes.Add("Avro.Specific.ISpecificProtocol"); AddProtocolDocumentation(protocol, ctd); // Add static protocol field. var protocolField = new CodeMemberField(); protocolField.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final; protocolField.Name = "protocol"; protocolField.Type = new CodeTypeReference("readonly Avro.Protocol"); var cpe = new CodePrimitiveExpression(protocol.ToString()); var cmie = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Protocol)), "Parse"), new CodeExpression[] { cpe }); protocolField.InitExpression = cmie; ctd.Members.Add(protocolField); // Add overridden Protocol method. var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Name = "Protocol"; property.Type = new CodeTypeReference("Avro.Protocol"); property.HasGet = true; property.GetStatements.Add(new CodeTypeReferenceExpression("return protocol")); ctd.Members.Add(property); // var requestMethod = CreateRequestMethod(); // ctd.Members.Add(requestMethod); var requestMethod = CreateRequestMethod(); // requestMethod.Attributes |= MemberAttributes.Override; var builder = new StringBuilder(); if (protocol.Messages.Count > 0) { builder.AppendLine("switch(messageName)"); builder.Append("\t\t\t{"); foreach (var a in protocol.Messages) { builder.AppendLine().Append("\t\t\t\tcase \"").Append(a.Key).AppendLine("\":"); bool unused = false; string type = getType(a.Value.Response, false, ref unused); builder.Append("\t\t\t\trequestor.Request<") .Append(type) .AppendLine(">(messageName, args, callback);"); builder.AppendLine("\t\t\t\tbreak;"); } builder.Append("\t\t\t}"); } var cseGet = new CodeSnippetExpression(builder.ToString()); requestMethod.Statements.Add(cseGet); ctd.Members.Add(requestMethod); AddMethods(protocol, false, ctd); string nspace = protocol.Namespace; if (string.IsNullOrEmpty(nspace)) { throw new CodeGenException("Namespace required for enum schema " + nspace); } CodeNamespace codens = AddNamespace(nspace); codens.Types.Add(ctd); // Create callback abstract class ctd = new CodeTypeDeclaration(protocolNameMangled + "Callback"); ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public; ctd.IsClass = true; ctd.BaseTypes.Add(protocolNameMangled); // Need to override AddProtocolDocumentation(protocol, ctd); AddMethods(protocol, true, ctd); codens.Types.Add(ctd); } /// <summary> /// Creates the request method. /// </summary> /// <returns>A declaration for a method of a type.</returns> private static CodeMemberMethod CreateRequestMethod() { var requestMethod = new CodeMemberMethod(); requestMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; requestMethod.Name = "Request"; requestMethod.ReturnType = new CodeTypeReference(typeof(void)); { var requestor = new CodeParameterDeclarationExpression(typeof(Specific.ICallbackRequestor), "requestor"); requestMethod.Parameters.Add(requestor); var messageName = new CodeParameterDeclarationExpression(typeof(string), "messageName"); requestMethod.Parameters.Add(messageName); var args = new CodeParameterDeclarationExpression(typeof(object[]), "args"); requestMethod.Parameters.Add(args); var callback = new CodeParameterDeclarationExpression(typeof(object), "callback"); requestMethod.Parameters.Add(callback); } return requestMethod; } /// <summary> /// Adds the methods. /// </summary> /// <param name="protocol">The protocol.</param> /// <param name="generateCallback">if set to <c>true</c> [generate callback].</param> /// <param name="ctd">The CTD.</param> private static void AddMethods(Protocol protocol, bool generateCallback, CodeTypeDeclaration ctd) { foreach (var e in protocol.Messages) { var name = e.Key; var message = e.Value; var response = message.Response; if (generateCallback && message.Oneway.GetValueOrDefault()) { continue; } var messageMember = new CodeMemberMethod(); messageMember.Name = CodeGenUtil.Instance.Mangle(name); messageMember.Attributes = MemberAttributes.Public | MemberAttributes.Abstract; if (message.Doc != null && message.Doc.Trim() != string.Empty) { messageMember.Comments.Add(new CodeCommentStatement(message.Doc)); } if (message.Oneway.GetValueOrDefault() || generateCallback) { messageMember.ReturnType = new CodeTypeReference(typeof(void)); } else { bool ignored = false; string type = getType(response, false, ref ignored); messageMember.ReturnType = new CodeTypeReference(type); } foreach (Field field in message.Request.Fields) { bool ignored = false; string type = getType(field.Schema, false, ref ignored); string fieldName = CodeGenUtil.Instance.Mangle(field.Name); var parameter = new CodeParameterDeclarationExpression(type, fieldName); messageMember.Parameters.Add(parameter); } if (generateCallback) { bool unused = false; var type = getType(response, false, ref unused); var parameter = new CodeParameterDeclarationExpression("Avro.IO.ICallback<" + type + ">", "callback"); messageMember.Parameters.Add(parameter); } ctd.Members.Add(messageMember); } } /// <summary> /// Adds the protocol documentation. /// </summary> /// <param name="protocol">The protocol.</param> /// <param name="ctd">The CTD.</param> private void AddProtocolDocumentation(Protocol protocol, CodeTypeDeclaration ctd) { // Add interface documentation if (protocol.Doc != null && protocol.Doc.Trim() != string.Empty) { var interfaceDoc = createDocComment(protocol.Doc); if (interfaceDoc != null) { ctd.Comments.Add(interfaceDoc); } } } /// <summary> /// Creates a class declaration. /// </summary> /// <param name="schema">record schema.</param> /// <returns> /// A new class code type declaration. /// </returns> /// <exception cref="CodeGenException"> /// Unable to cast schema into a record /// or /// Namespace required for record schema " + recordSchema.Name. /// </exception> protected virtual CodeTypeDeclaration processRecord(Schema schema) { RecordSchema recordSchema = schema as RecordSchema; if (recordSchema == null) { throw new CodeGenException("Unable to cast schema into a record"); } bool isError = recordSchema.Tag == Schema.Type.Error; // declare the class var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name)); var baseTypeReference = new CodeTypeReference( isError ? typeof(Specific.SpecificException) : typeof(Specific.ISpecificRecord), CodeTypeReferenceOptions.GlobalReference); ctd.BaseTypes.Add(baseTypeReference); ctd.Attributes = MemberAttributes.Public; ctd.IsClass = true; ctd.IsPartial = true; if (recordSchema.Documentation != null) { ctd.Comments.Add(createDocComment(recordSchema.Documentation)); } createSchemaField(schema, ctd, isError); // declare Get() to be used by the Writer classes var cmmGet = new CodeMemberMethod(); cmmGet.Name = "Get"; cmmGet.Attributes = MemberAttributes.Public; cmmGet.ReturnType = new CodeTypeReference("System.Object"); cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)") .AppendLine().AppendLine("\t\t\t{"); // declare Put() to be used by the Reader classes var cmmPut = new CodeMemberMethod(); cmmPut.Name = "Put"; cmmPut.Attributes = MemberAttributes.Public; cmmPut.ReturnType = new CodeTypeReference(typeof(void)); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos")); cmmPut.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "fieldValue")); var putFieldStmt = new StringBuilder("switch (fieldPos)") .AppendLine().AppendLine("\t\t\t{"); if (isError) { cmmGet.Attributes |= MemberAttributes.Override; cmmPut.Attributes |= MemberAttributes.Override; } foreach (Field field in recordSchema.Fields) { // Determine type of field bool nullibleEnum = false; string baseType = getType(field.Schema, false, ref nullibleEnum); var ctrfield = new CodeTypeReference(baseType); // Create field string privFieldName = string.Concat("_", field.Name); var codeField = new CodeMemberField(ctrfield, privFieldName); codeField.Attributes = MemberAttributes.Private; if (field.Schema is EnumSchema es && es.Default != null) { codeField.InitExpression = new CodeTypeReferenceExpression($"{es.Name}.{es.Default}"); } // Process field documentation if it exist and add to the field CodeCommentStatement propertyComment = null; if (!string.IsNullOrEmpty(field.Documentation)) { propertyComment = createDocComment(field.Documentation); if (propertyComment != null) { codeField.Comments.Add(propertyComment); } } // Add field to class ctd.Members.Add(codeField); // Create reference to the field - this.fieldname var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName); var mangledName = CodeGenUtil.Instance.Mangle(field.Name); // Create field property with get and set methods var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public | MemberAttributes.Final; property.Name = mangledName; property.Type = ctrfield; property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef)); property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression())); if (propertyComment != null) { property.Comments.Add(propertyComment); } // Add field property to class ctd.Members.Add(property); // add to Get() getFieldStmt.Append("\t\t\tcase "); getFieldStmt.Append(field.Pos); getFieldStmt.Append(": return this."); getFieldStmt.Append(mangledName); getFieldStmt.AppendLine(";"); // add to Put() putFieldStmt.Append("\t\t\tcase "); putFieldStmt.Append(field.Pos); putFieldStmt.Append(": this."); putFieldStmt.Append(mangledName); if (nullibleEnum) { putFieldStmt.Append(" = fieldValue == null ? ("); putFieldStmt.Append(baseType); putFieldStmt.Append(")null : ("); string type = baseType.Remove(0, 16); // remove System.Nullable< type = type.Remove(type.Length - 1); // remove > putFieldStmt.Append(type); putFieldStmt.AppendLine(")fieldValue; break;"); } else { putFieldStmt.Append(" = ("); putFieldStmt.Append(baseType); putFieldStmt.AppendLine(")fieldValue; break;"); } } // end switch block for Get() getFieldStmt.AppendLine("\t\t\tdefault: throw new global::Avro.AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");") .Append("\t\t\t}"); var cseGet = new CodeSnippetExpression(getFieldStmt.ToString()); cmmGet.Statements.Add(cseGet); ctd.Members.Add(cmmGet); // end switch block for Put() putFieldStmt.AppendLine("\t\t\tdefault: throw new global::Avro.AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");") .Append("\t\t\t}"); var csePut = new CodeSnippetExpression(putFieldStmt.ToString()); cmmPut.Statements.Add(csePut); ctd.Members.Add(cmmPut); string nspace = recordSchema.Namespace; if (string.IsNullOrEmpty(nspace)) { throw new CodeGenException("Namespace required for record schema " + recordSchema.Name); } CodeNamespace codens = AddNamespace(nspace); codens.Types.Add(ctd); return ctd; } /// <summary> /// Gets the string representation of the schema's data type. /// </summary> /// <param name="schema">schema.</param> /// <param name="nullible">flag to indicate union with null.</param> /// <param name="nullibleEnum">This method sets this value to indicate whether the enum is nullable. True indicates /// that it is nullable. False indicates that it is not nullable.</param> /// <returns> /// Name of the schema's C# type representation. /// </returns> /// <exception cref="CodeGenException"> /// Unable to cast schema into a named schema /// or /// Unable to cast schema into a named schema /// or /// Unable to cast schema into an array schema /// or /// Unable to cast schema into a map schema /// or /// Unable to cast schema into a union schema /// or /// Unable to cast schema into a logical schema /// or /// Unable to generate CodeTypeReference for " + schema.Name + " type " + schema.Tag. /// </exception> internal static string getType(Schema schema, bool nullible, ref bool nullibleEnum) { switch (schema.Tag) { case Schema.Type.Null: return typeof(object).ToString(); case Schema.Type.Boolean: return nullible ? $"System.Nullable<{typeof(bool)}>" : typeof(bool).ToString(); case Schema.Type.Int: return nullible ? $"System.Nullable<{typeof(int)}>" : typeof(int).ToString(); case Schema.Type.Long: return nullible ? $"System.Nullable<{typeof(long)}>" : typeof(long).ToString(); case Schema.Type.Float: return nullible ? $"System.Nullable<{typeof(float)}>" : typeof(float).ToString(); case Schema.Type.Double: return nullible ? $"System.Nullable<{typeof(double)}>" : typeof(double).ToString(); case Schema.Type.Bytes: return typeof(byte[]).ToString(); case Schema.Type.String: return typeof(string).ToString(); case Schema.Type.Enumeration: var namedSchema = schema as NamedSchema; if (namedSchema == null) { throw new CodeGenException("Unable to cast schema into a named schema"); } if (nullible) { nullibleEnum = true; return "System.Nullable<" + CodeGenUtil.Instance.Mangle(namedSchema.Fullname) + ">"; } else { return CodeGenUtil.Instance.Mangle(namedSchema.Fullname); } case Schema.Type.Fixed: case Schema.Type.Record: case Schema.Type.Error: namedSchema = schema as NamedSchema; if (namedSchema == null) { throw new CodeGenException("Unable to cast schema into a named schema"); } return CodeGenUtil.Instance.Mangle(namedSchema.Fullname); case Schema.Type.Array: var arraySchema = schema as ArraySchema; if (arraySchema == null) { throw new CodeGenException("Unable to cast schema into an array schema"); } return "IList<" + getType(arraySchema.ItemSchema, false, ref nullibleEnum) + ">"; case Schema.Type.Map: var mapSchema = schema as MapSchema; if (mapSchema == null) { throw new CodeGenException("Unable to cast schema into a map schema"); } return "IDictionary<string," + getType(mapSchema.ValueSchema, false, ref nullibleEnum) + ">"; case Schema.Type.Union: var unionSchema = schema as UnionSchema; if (unionSchema == null) { throw new CodeGenException("Unable to cast schema into a union schema"); } Schema nullibleType = GetNullableType(unionSchema); return nullibleType == null ? CodeGenUtil.Object : getType(nullibleType, true, ref nullibleEnum); case Schema.Type.Logical: var logicalSchema = schema as LogicalSchema; if (logicalSchema == null) { throw new CodeGenException("Unable to cast schema into a logical schema"); } var csharpType = logicalSchema.LogicalType.GetCSharpType(nullible); return csharpType.IsGenericType && csharpType.GetGenericTypeDefinition() == typeof(Nullable<>) ? $"System.Nullable<{csharpType.GetGenericArguments()[0]}>" : csharpType.ToString(); } throw new CodeGenException("Unable to generate CodeTypeReference for " + schema.Name + " type " + schema.Tag); } /// <summary> /// Gets the schema of a union with null. /// </summary> /// <param name="schema">union schema.</param> /// <returns> /// schema that is nullable. /// </returns> /// <exception cref="ArgumentNullException">schema - UnionSchema can not be null.</exception> [Obsolete("This method is deprecated and it will be removed in a future release! Please use GetNullableType() instead.")] public static Schema getNullableType(UnionSchema schema) { return GetNullableType(schema); } /// <summary> /// Gets the schema of a union with null. /// </summary> /// <param name="schema">union schema.</param> /// <returns> /// schema that is nullable. /// </returns> /// <exception cref="ArgumentNullException">schema - UnionSchema can not be null.</exception> public static Schema GetNullableType(UnionSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema), "UnionSchema can not be null"); } if (schema.Count == 2 && !schema.Schemas.All(x => x.Tag != Schema.Type.Null)) { return schema.Schemas.FirstOrDefault(x => x.Tag != Schema.Type.Null); } return null; } /// <summary> /// Creates the static schema field for class types. /// </summary> /// <param name="schema">schema.</param> /// <param name="ctd">CodeTypeDeclaration for the class.</param> /// <param name="overrideFlag">Indicates whether we should add the <see cref="MemberAttributes.Override" /> to the /// generated property.</param> protected virtual void createSchemaField(Schema schema, CodeTypeDeclaration ctd, bool overrideFlag) { // create schema field var ctrfield = new CodeTypeReference(typeof(Schema), CodeTypeReferenceOptions.GlobalReference); string schemaFname = "_SCHEMA"; var codeField = new CodeMemberField(ctrfield, schemaFname); codeField.Attributes = MemberAttributes.Public | MemberAttributes.Static; // create function call Schema.Parse(json) var cpe = new CodePrimitiveExpression(schema.ToString()); var cmie = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(ctrfield), "Parse"), new CodeExpression[] { cpe }); codeField.InitExpression = cmie; ctd.Members.Add(codeField); // create property to get static schema field var property = new CodeMemberProperty(); property.Attributes = MemberAttributes.Public; if (overrideFlag) { property.Attributes |= MemberAttributes.Override; } property.Name = "Schema"; property.Type = ctrfield; property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(ctd.Name + "." + schemaFname))); ctd.Members.Add(property); } /// <summary> /// Creates an XML documentation for the given comment. /// </summary> /// <param name="comment">comment.</param> /// <returns> /// a statement consisting of a single comment. /// </returns> protected virtual CodeCommentStatement createDocComment(string comment) { string text = string.Format(CultureInfo.InvariantCulture, "<summary>{1} {0}{1} </summary>", comment, Environment.NewLine); return new CodeCommentStatement(text, true); } /// <summary> /// Writes the generated compile unit into one file. /// </summary> /// <param name="outputFile">name of output file to write to.</param> public virtual void WriteCompileUnit(string outputFile) { var cscp = new CSharpCodeProvider(); var opts = new CodeGeneratorOptions(); opts.BracingStyle = "C"; opts.IndentString = "\t"; opts.BlankLinesBetweenMembers = false; using (var outfile = new StreamWriter(outputFile)) { cscp.GenerateCodeFromCompileUnit(CompileUnit, outfile, opts); } } /// <summary> /// Writes each types in each namespaces into individual files. /// </summary> /// <param name="outputdir">name of directory to write to.</param> public virtual void WriteTypes(string outputdir) { var cscp = new CSharpCodeProvider(); var opts = new CodeGeneratorOptions(); opts.BracingStyle = "C"; opts.IndentString = "\t"; opts.BlankLinesBetweenMembers = false; CodeNamespaceCollection nsc = CompileUnit.Namespaces; for (int i = 0; i < nsc.Count; i++) { var ns = nsc[i]; string dir = outputdir; foreach (string name in CodeGenUtil.Instance.UnMangle(ns.Name).Split('.')) { dir = Path.Combine(dir, name); } Directory.CreateDirectory(dir); var new_ns = new CodeNamespace(ns.Name); new_ns.Comments.Add(CodeGenUtil.Instance.FileComment); foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports) { new_ns.Imports.Add(nci); } var types = ns.Types; for (int j = 0; j < types.Count; j++) { var ctd = types[j]; string file = Path.Combine(dir, Path.ChangeExtension(CodeGenUtil.Instance.UnMangle(ctd.Name), "cs")); using (var writer = new StreamWriter(file, false)) { new_ns.Types.Add(ctd); cscp.GenerateCodeFromNamespace(new_ns, writer, opts); new_ns.Types.Remove(ctd); } } } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Reflection; using Microsoft.PowerShell; using Dbg = System.Diagnostics.Debug; using System.Management.Automation.Language; namespace System.Management.Automation { /// <summary> /// This class represents the compiled metadata for a parameter set. /// </summary> public sealed class ParameterSetMetadata { #region Private Data private bool _isMandatory; private int _position; private bool _valueFromPipeline; private bool _valueFromPipelineByPropertyName; private bool _valueFromRemainingArguments; private string _helpMessage; private string _helpMessageBaseName; private string _helpMessageResourceId; #endregion #region Constructor /// <summary> /// /// </summary> /// <param name="psMD"></param> internal ParameterSetMetadata(ParameterSetSpecificMetadata psMD) { Dbg.Assert(null != psMD, "ParameterSetSpecificMetadata cannot be null"); Initialize(psMD); } /// <summary> /// A copy constructor that creates a deep copy of the <paramref name="other"/> ParameterSetMetadata object. /// </summary> /// <param name="other">object to copy</param> internal ParameterSetMetadata(ParameterSetMetadata other) { if (other == null) { throw PSTraceSource.NewArgumentNullException("other"); } _helpMessage = other._helpMessage; _helpMessageBaseName = other._helpMessageBaseName; _helpMessageResourceId = other._helpMessageResourceId; _isMandatory = other._isMandatory; _position = other._position; _valueFromPipeline = other._valueFromPipeline; _valueFromPipelineByPropertyName = other._valueFromPipelineByPropertyName; _valueFromRemainingArguments = other._valueFromRemainingArguments; } #endregion #region Public Properties /// <summary> /// Returns true if the parameter is mandatory for this parameterset, false otherwise. /// </summary> /// <value></value> public bool IsMandatory { get { return _isMandatory; } set { _isMandatory = value; } } /// <summary> /// If the parameter is allowed to be positional for this parameter set, this returns /// the position it is allowed to be in. If it is not positional, this returns int.MinValue. /// </summary> /// <value></value> public int Position { get { return _position; } set { _position = value; } } /// <summary> /// Specifies that this parameter can take values from the incoming pipeline object. /// </summary> public bool ValueFromPipeline { get { return _valueFromPipeline; } set { _valueFromPipeline = value; } } /// <summary> /// Specifies that this parameter can take values from a property from the incoming /// pipeline object with the same name as the parameter. /// </summary> public bool ValueFromPipelineByPropertyName { get { return _valueFromPipelineByPropertyName; } set { _valueFromPipelineByPropertyName = value; } } /// <summary> /// Specifies if this parameter takes all the remaining unbound /// arguments that were specified /// </summary> /// <value></value> public bool ValueFromRemainingArguments { get { return _valueFromRemainingArguments; } set { _valueFromRemainingArguments = value; } } /// <summary> /// A short description for this parameter, suitable for presentation as a tool tip. /// </summary> public string HelpMessage { get { return _helpMessage; } set { _helpMessage = value; } } /// <summary> /// The base name of the resource for a help message. /// </summary> public string HelpMessageBaseName { get { return _helpMessageBaseName; } set { _helpMessageBaseName = value; } } /// <summary> /// The Id of the resource for a help message. /// </summary> public string HelpMessageResourceId { get { return _helpMessageResourceId; } set { _helpMessageResourceId = value; } } #endregion #region Private / Internal Methods & Properties /// <summary> /// /// </summary> /// <param name="psMD"></param> internal void Initialize(ParameterSetSpecificMetadata psMD) { _isMandatory = psMD.IsMandatory; _position = psMD.Position; _valueFromPipeline = psMD.ValueFromPipeline; _valueFromPipelineByPropertyName = psMD.ValueFromPipelineByPropertyName; _valueFromRemainingArguments = psMD.ValueFromRemainingArguments; _helpMessage = psMD.HelpMessage; _helpMessageBaseName = psMD.HelpMessageBaseName; _helpMessageResourceId = psMD.HelpMessageResourceId; } /// <summary> /// Compares this instance with the supplied <paramref name="second"/>. /// </summary> /// <param name="second"> /// An object to compare this instance with /// </param> /// <returns> /// true if the metadata is same. false otherwise. /// </returns> internal bool Equals(ParameterSetMetadata second) { if ((_isMandatory != second._isMandatory) || (_position != second._position) || (_valueFromPipeline != second._valueFromPipeline) || (_valueFromPipelineByPropertyName != second._valueFromPipelineByPropertyName) || (_valueFromRemainingArguments != second._valueFromRemainingArguments) || (_helpMessage != second._helpMessage) || (_helpMessageBaseName != second._helpMessageBaseName) || (_helpMessageResourceId != second._helpMessageResourceId)) { return false; } return true; } #endregion #region Efficient serialization + rehydration logic [Flags] internal enum ParameterFlags : uint { Mandatory = 0x01, ValueFromPipeline = 0x02, ValueFromPipelineByPropertyName = 0x04, ValueFromRemainingArguments = 0x08, } internal ParameterFlags Flags { get { ParameterFlags flags = 0; if (IsMandatory) { flags = flags | ParameterFlags.Mandatory; } if (ValueFromPipeline) { flags = flags | ParameterFlags.ValueFromPipeline; } if (ValueFromPipelineByPropertyName) { flags = flags | ParameterFlags.ValueFromPipelineByPropertyName; } if (ValueFromRemainingArguments) { flags = flags | ParameterFlags.ValueFromRemainingArguments; } return flags; } set { this.IsMandatory = (ParameterFlags.Mandatory == (value & ParameterFlags.Mandatory)); this.ValueFromPipeline = (ParameterFlags.ValueFromPipeline == (value & ParameterFlags.ValueFromPipeline)); this.ValueFromPipelineByPropertyName = (ParameterFlags.ValueFromPipelineByPropertyName == (value & ParameterFlags.ValueFromPipelineByPropertyName)); this.ValueFromRemainingArguments = (ParameterFlags.ValueFromRemainingArguments == (value & ParameterFlags.ValueFromRemainingArguments)); } } /// <summary> /// Constructor used by rehydration /// </summary> internal ParameterSetMetadata( int position, ParameterFlags flags, string helpMessage) { this.Position = position; this.Flags = flags; this.HelpMessage = helpMessage; } #endregion #region Proxy Parameter Generation private const string MandatoryFormat = @"{0}Mandatory=$true"; private const string PositionFormat = @"{0}Position={1}"; private const string ValueFromPipelineFormat = @"{0}ValueFromPipeline=$true"; private const string ValueFromPipelineByPropertyNameFormat = @"{0}ValueFromPipelineByPropertyName=$true"; private const string ValueFromRemainingArgumentsFormat = @"{0}ValueFromRemainingArguments=$true"; private const string HelpMessageFormat = @"{0}HelpMessage='{1}'"; /// <summary> /// /// </summary> /// <returns></returns> internal string GetProxyParameterData() { Text.StringBuilder result = new System.Text.StringBuilder(); string prefix = ""; if (_isMandatory) { result.AppendFormat(CultureInfo.InvariantCulture, MandatoryFormat, prefix); prefix = ", "; } if (_position != Int32.MinValue) { result.AppendFormat(CultureInfo.InvariantCulture, PositionFormat, prefix, _position); prefix = ", "; } if (_valueFromPipeline) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineFormat, prefix); prefix = ", "; } if (_valueFromPipelineByPropertyName) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromPipelineByPropertyNameFormat, prefix); prefix = ", "; } if (_valueFromRemainingArguments) { result.AppendFormat(CultureInfo.InvariantCulture, ValueFromRemainingArgumentsFormat, prefix); prefix = ", "; } if (!string.IsNullOrEmpty(_helpMessage)) { result.AppendFormat( CultureInfo.InvariantCulture, HelpMessageFormat, prefix, CodeGeneration.EscapeSingleQuotedStringContent(_helpMessage)); prefix = ", "; } return result.ToString(); } #endregion } /// <summary> /// This class represents the compiled metadata for a parameter. /// </summary> public sealed class ParameterMetadata { #region Private Data private string _name; private Type _parameterType; private bool _isDynamic; private Dictionary<string, ParameterSetMetadata> _parameterSets; private Collection<string> _aliases; private Collection<Attribute> _attributes; #endregion #region Constructor /// <summary> /// Constructs a ParameterMetadata instance. /// </summary> /// <param name="name"> /// Name of the parameter. /// </param> /// <exception cref="ArgumentNullException"> /// name is null. /// </exception> public ParameterMetadata(string name) : this(name, null) { } /// <summary> /// Constructs a ParameterMetadata instance. /// </summary> /// <param name="name"> /// Name of the parameter. /// </param> /// <param name="parameterType"> /// Type of the parameter. /// </param> /// <exception cref="ArgumentNullException"> /// name is null. /// </exception> public ParameterMetadata(string name, Type parameterType) { if (string.IsNullOrEmpty(name)) { throw PSTraceSource.NewArgumentNullException("name"); } _name = name; _parameterType = parameterType; _attributes = new Collection<Attribute>(); _aliases = new Collection<string>(); _parameterSets = new Dictionary<string, ParameterSetMetadata>(); } /// <summary> /// A copy constructor that creates a deep copy of the <paramref name="other"/> ParameterMetadata object. /// Instances of Attribute and Type classes are copied by reference. /// </summary> /// <param name="other">object to copy</param> public ParameterMetadata(ParameterMetadata other) { if (other == null) { throw PSTraceSource.NewArgumentNullException("other"); } _isDynamic = other._isDynamic; _name = other._name; _parameterType = other._parameterType; // deep copy _aliases = new Collection<string>(new List<string>(other._aliases.Count)); foreach (string alias in other._aliases) { _aliases.Add(alias); } // deep copy of the collection, collection items (Attributes) copied by reference if (other._attributes == null) { _attributes = null; } else { _attributes = new Collection<Attribute>(new List<Attribute>(other._attributes.Count)); foreach (Attribute attribute in other._attributes) { _attributes.Add(attribute); } } // deep copy _parameterSets = null; if (other._parameterSets == null) { _parameterSets = null; } else { _parameterSets = new Dictionary<string, ParameterSetMetadata>(other._parameterSets.Count); foreach (KeyValuePair<string, ParameterSetMetadata> entry in other._parameterSets) { _parameterSets.Add(entry.Key, new ParameterSetMetadata(entry.Value)); } } } /// <summary> /// An internal constructor which constructs a ParameterMetadata object /// from compiled command parameter metadata. ParameterMetadata /// is a proxy written on top of CompiledCommandParameter /// </summary> /// <param name="cmdParameterMD"> /// Internal CompiledCommandParameter metadata /// </param> internal ParameterMetadata(CompiledCommandParameter cmdParameterMD) { Dbg.Assert(null != cmdParameterMD, "CompiledCommandParameter cannot be null"); Initialize(cmdParameterMD); } /// <summary> /// Constructor used by implicit remoting /// </summary> internal ParameterMetadata( Collection<string> aliases, bool isDynamic, string name, Dictionary<string, ParameterSetMetadata> parameterSets, Type parameterType) { _aliases = aliases; _isDynamic = isDynamic; _name = name; _parameterSets = parameterSets; _parameterType = parameterType; _attributes = new Collection<Attribute>(); } #endregion #region Public Methods/Properties /// <summary> /// Gets the name of the parameter /// </summary> /// public String Name { get { return _name; } set { if (string.IsNullOrEmpty(value)) { throw PSTraceSource.NewArgumentNullException("Name"); } _name = value; } } /// <summary> /// Gets the Type information of the Parameter. /// </summary> public Type ParameterType { get { return _parameterType; } set { _parameterType = value; } } /// <summary> /// Gets the ParameterSets metadata that this parameter belongs to. /// </summary> public Dictionary<string, ParameterSetMetadata> ParameterSets { get { return _parameterSets; } } /// <summary> /// Specifies if the parameter is Dynamic /// </summary> public bool IsDynamic { get { return _isDynamic; } set { _isDynamic = value; } } /// <summary> /// Specifies the alias names for this parameter /// </summary> public Collection<string> Aliases { get { return _aliases; } } /// <summary> /// A collection of the attributes found on the member. /// </summary> public Collection<Attribute> Attributes { get { return _attributes; } } /// <summary> /// Specifies if the parameter is a SwitchParameter /// </summary> public bool SwitchParameter { get { if (_parameterType != null) { return _parameterType.Equals(typeof(SwitchParameter)); } return false; } } /// <summary> /// Gets a dictionary of parameter metadata for the supplied <paramref name="type"/>. /// </summary> /// <param name="type"> /// CLR Type for which the parameter metadata is constructed. /// </param> /// <returns> /// A Dictionary of ParameterMetadata keyed by parameter name. /// null if no parameter metadata is found. /// </returns> /// <exception cref="ArgumentNullException"> /// type is null. /// </exception> public static Dictionary<string, ParameterMetadata> GetParameterMetadata(Type type) { if (null == type) { throw PSTraceSource.NewArgumentNullException("type"); } CommandMetadata cmdMetaData = new CommandMetadata(type); Dictionary<string, ParameterMetadata> result = cmdMetaData.Parameters; // early GC. cmdMetaData = null; return result; } #endregion #region Internal Methods/Properties /// <summary> /// /// </summary> /// <param name="compiledParameterMD"></param> internal void Initialize(CompiledCommandParameter compiledParameterMD) { _name = compiledParameterMD.Name; _parameterType = compiledParameterMD.Type; _isDynamic = compiledParameterMD.IsDynamic; // Create parameter set metadata _parameterSets = new Dictionary<string, ParameterSetMetadata>(StringComparer.OrdinalIgnoreCase); foreach (string key in compiledParameterMD.ParameterSetData.Keys) { ParameterSetSpecificMetadata pMD = compiledParameterMD.ParameterSetData[key]; _parameterSets.Add(key, new ParameterSetMetadata(pMD)); } // Create aliases for this parameter _aliases = new Collection<string>(); foreach (string alias in compiledParameterMD.Aliases) { _aliases.Add(alias); } // Create attributes for this parameter _attributes = new Collection<Attribute>(); foreach (var attrib in compiledParameterMD.CompiledAttributes) { _attributes.Add(attrib); } } /// <summary> /// /// </summary> /// <param name="cmdParameterMetadata"></param> /// <returns></returns> internal static Dictionary<string, ParameterMetadata> GetParameterMetadata(MergedCommandParameterMetadata cmdParameterMetadata) { Dbg.Assert(null != cmdParameterMetadata, "cmdParameterMetadata cannot be null"); Dictionary<string, ParameterMetadata> result = new Dictionary<string, ParameterMetadata>(StringComparer.OrdinalIgnoreCase); foreach (var keyValuePair in cmdParameterMetadata.BindableParameters) { var key = keyValuePair.Key; var mergedCompiledPMD = keyValuePair.Value; ParameterMetadata parameterMetaData = new ParameterMetadata(mergedCompiledPMD.Parameter); result.Add(key, parameterMetaData); } return result; } internal bool IsMatchingType(PSTypeName psTypeName) { Type dotNetType = psTypeName.Type; if (dotNetType != null) { // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. bool parameterAcceptsObjects = ((int)(LanguagePrimitives.FigureConversion(typeof(object), this.ParameterType).Rank)) >= (int)(ConversionRank.AssignableS2A); if (dotNetType.Equals(typeof(object))) { return parameterAcceptsObjects; } if (parameterAcceptsObjects) { return (psTypeName.Type != null) && (psTypeName.Type.Equals(typeof(object))); } // ConstrainedLanguage note - This conversion is analyzed, but actually invoked via regular conversion. var conversionData = LanguagePrimitives.FigureConversion(dotNetType, this.ParameterType); if (conversionData != null) { if ((int)(conversionData.Rank) >= (int)(ConversionRank.NumericImplicitS2A)) { return true; } } return false; } var wildcardPattern = WildcardPattern.Get( "*" + (psTypeName.Name ?? ""), WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); if (wildcardPattern.IsMatch(this.ParameterType.FullName)) { return true; } if (this.ParameterType.IsArray && wildcardPattern.IsMatch((this.ParameterType.GetElementType().FullName))) { return true; } if (this.Attributes != null) { PSTypeNameAttribute typeNameAttribute = this.Attributes.OfType<PSTypeNameAttribute>().FirstOrDefault(); if (typeNameAttribute != null && wildcardPattern.IsMatch(typeNameAttribute.PSTypeName)) { return true; } } return false; } #endregion #region Proxy Parameter generation // The formats are prefixed with {0} to enable easy formatting. private const string ParameterNameFormat = @"{0}${{{1}}}"; private const string ParameterTypeFormat = @"{0}[{1}]"; private const string ParameterSetNameFormat = "ParameterSetName='{0}'"; private const string AliasesFormat = @"{0}[Alias({1})]"; private const string ValidateLengthFormat = @"{0}[ValidateLength({1}, {2})]"; private const string ValidateRangeFloatFormat = @"{0}[ValidateRange({1:R}, {2:R})]"; private const string ValidateRangeFormat = @"{0}[ValidateRange({1}, {2})]"; private const string ValidatePatternFormat = "{0}[ValidatePattern('{1}')]"; private const string ValidateScriptFormat = @"{0}[ValidateScript({{ {1} }})]"; private const string ValidateCountFormat = @"{0}[ValidateCount({1}, {2})]"; private const string ValidateSetFormat = @"{0}[ValidateSet({1})]"; private const string ValidateNotNullFormat = @"{0}[ValidateNotNull()]"; private const string ValidateNotNullOrEmptyFormat = @"{0}[ValidateNotNullOrEmpty()]"; private const string AllowNullFormat = @"{0}[AllowNull()]"; private const string AllowEmptyStringFormat = @"{0}[AllowEmptyString()]"; private const string AllowEmptyCollectionFormat = @"{0}[AllowEmptyCollection()]"; private const string PSTypeNameFormat = @"{0}[PSTypeName('{1}')]"; private const string ObsoleteFormat = @"{0}[Obsolete({1})]"; private const string CredentialAttributeFormat = @"{0}[System.Management.Automation.CredentialAttribute()]"; /// <summary> /// /// </summary> /// <param name="prefix"> /// prefix that is added to every new-line. Used for tabbing content. /// </param> /// <param name="paramNameOverride"> /// The paramNameOverride is used as the parameter name if it is not null or empty. /// </param> /// <param name="isProxyForCmdlet"> /// The parameter is for a cmdlet and requires a Parameter attribute. /// </param> /// <returns></returns> internal string GetProxyParameterData(string prefix, string paramNameOverride, bool isProxyForCmdlet) { Text.StringBuilder result = new System.Text.StringBuilder(); if (_parameterSets != null && isProxyForCmdlet) { foreach (var pair in _parameterSets) { string parameterSetName = pair.Key; ParameterSetMetadata parameterSet = pair.Value; string paramSetData = parameterSet.GetProxyParameterData(); if (!string.IsNullOrEmpty(paramSetData) || !parameterSetName.Equals(ParameterAttribute.AllParameterSets)) { string separator = ""; result.Append(prefix); result.Append("[Parameter("); if (!parameterSetName.Equals(ParameterAttribute.AllParameterSets)) { result.AppendFormat( CultureInfo.InvariantCulture, ParameterSetNameFormat, CodeGeneration.EscapeSingleQuotedStringContent(parameterSetName)); separator = ", "; } if (!string.IsNullOrEmpty(paramSetData)) { result.Append(separator); result.Append(paramSetData); } result.Append(")]"); } } } if ((_aliases != null) && (_aliases.Count > 0)) { Text.StringBuilder aliasesData = new System.Text.StringBuilder(); string comma = ""; // comma is not need for the first element foreach (string alias in _aliases) { aliasesData.AppendFormat( CultureInfo.InvariantCulture, "{0}'{1}'", comma, CodeGeneration.EscapeSingleQuotedStringContent(alias)); comma = ","; } result.AppendFormat(CultureInfo.InvariantCulture, AliasesFormat, prefix, aliasesData.ToString()); } if ((_attributes != null) && (_attributes.Count > 0)) { foreach (Attribute attrib in _attributes) { string attribData = GetProxyAttributeData(attrib, prefix); if (!string.IsNullOrEmpty(attribData)) { result.Append(attribData); } } } if (SwitchParameter) { result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, "switch"); } else if (_parameterType != null) { result.AppendFormat(CultureInfo.InvariantCulture, ParameterTypeFormat, prefix, ToStringCodeMethods.Type(_parameterType)); } /* 1. CredentialAttribute needs to go after the type * 2. To avoid risk, I don't want to move other attributes to go here / after the type */ CredentialAttribute credentialAttrib = _attributes.OfType<CredentialAttribute>().FirstOrDefault(); if (credentialAttrib != null) { string attribData = string.Format(CultureInfo.InvariantCulture, CredentialAttributeFormat, prefix); if (!string.IsNullOrEmpty(attribData)) { result.Append(attribData); } } result.AppendFormat( CultureInfo.InvariantCulture, ParameterNameFormat, prefix, CodeGeneration.EscapeVariableName(string.IsNullOrEmpty(paramNameOverride) ? _name : paramNameOverride)); return result.ToString(); } /// <summary> /// Generates proxy data for attributes like ValidateLength, ValidateRange etc. /// </summary> /// <param name="attrib"> /// Attribute to process. /// </param> /// <param name="prefix"> /// Prefix string to add. /// </param> /// <returns> /// Attribute's proxy string. /// </returns> private string GetProxyAttributeData(Attribute attrib, string prefix) { string result; ValidateLengthAttribute validLengthAttrib = attrib as ValidateLengthAttribute; if (validLengthAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateLengthFormat, prefix, validLengthAttrib.MinLength, validLengthAttrib.MaxLength); return result; } ValidateRangeAttribute validRangeAttrib = attrib as ValidateRangeAttribute; if (validRangeAttrib != null) { Type rangeType = validRangeAttrib.MinRange.GetType(); string format; if (rangeType == typeof(float) || rangeType == typeof(double)) { format = ValidateRangeFloatFormat; } else { format = ValidateRangeFormat; } result = string.Format(CultureInfo.InvariantCulture, format, prefix, validRangeAttrib.MinRange, validRangeAttrib.MaxRange); return result; } AllowNullAttribute allowNullAttrib = attrib as AllowNullAttribute; if (allowNullAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, AllowNullFormat, prefix); return result; } AllowEmptyStringAttribute allowEmptyStringAttrib = attrib as AllowEmptyStringAttribute; if (allowEmptyStringAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyStringFormat, prefix); return result; } AllowEmptyCollectionAttribute allowEmptyColAttrib = attrib as AllowEmptyCollectionAttribute; if (allowEmptyColAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, AllowEmptyCollectionFormat, prefix); return result; } ValidatePatternAttribute patternAttrib = attrib as ValidatePatternAttribute; if (patternAttrib != null) { /* TODO: Validate Pattern dont support Options in ScriptCmdletText. StringBuilder regexOps = new System.Text.StringBuilder(); string or = ""; string[] regexOptionEnumValues = Enum.GetNames(typeof(System.Text.RegularExpressions.RegexOptions)); foreach(string regexOption in regexOptionEnumValues) { System.Text.RegularExpressions.RegexOptions option = (System.Text.RegularExpressions.RegexOptions) Enum.Parse( typeof(System.Text.RegularExpressions.RegexOptions), regexOption, true); if ((option & patternAttrib.Options) == option) { tracer.WriteLine("Regex option {0} found", regexOption); regexOps.AppendFormat(CultureInfo.InvariantCulture, "{0}[System.Text.RegularExpressions.RegexOptions]::{1}", or, option.ToString() ); or = "|"; } }*/ result = string.Format(CultureInfo.InvariantCulture, ValidatePatternFormat, prefix, CodeGeneration.EscapeSingleQuotedStringContent(patternAttrib.RegexPattern) /*,regexOps.ToString()*/); return result; } ValidateCountAttribute countAttrib = attrib as ValidateCountAttribute; if (countAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateCountFormat, prefix, countAttrib.MinLength, countAttrib.MaxLength); return result; } ValidateNotNullAttribute notNullAttrib = attrib as ValidateNotNullAttribute; if (notNullAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullFormat, prefix); return result; } ValidateNotNullOrEmptyAttribute notNullEmptyAttrib = attrib as ValidateNotNullOrEmptyAttribute; if (notNullEmptyAttrib != null) { result = string.Format(CultureInfo.InvariantCulture, ValidateNotNullOrEmptyFormat, prefix); return result; } ValidateSetAttribute setAttrib = attrib as ValidateSetAttribute; if (setAttrib != null) { Text.StringBuilder values = new System.Text.StringBuilder(); string comma = ""; foreach (string validValue in setAttrib.ValidValues) { values.AppendFormat( CultureInfo.InvariantCulture, "{0}'{1}'", comma, CodeGeneration.EscapeSingleQuotedStringContent(validValue)); comma = ","; } result = string.Format(CultureInfo.InvariantCulture, ValidateSetFormat, prefix, values.ToString()/*, setAttrib.IgnoreCase*/); return result; } ValidateScriptAttribute scriptAttrib = attrib as ValidateScriptAttribute; if (scriptAttrib != null) { // Talked with others and I think it is okay to use *unescaped* value from sb.ToString() // 1. implicit remoting is not bringing validation scripts across // 2. other places in code also assume that contents of a script block can be parsed // without escaping result = string.Format(CultureInfo.InvariantCulture, ValidateScriptFormat, prefix, scriptAttrib.ScriptBlock.ToString()); return result; } PSTypeNameAttribute psTypeNameAttrib = attrib as PSTypeNameAttribute; if (psTypeNameAttrib != null) { result = string.Format( CultureInfo.InvariantCulture, PSTypeNameFormat, prefix, CodeGeneration.EscapeSingleQuotedStringContent(psTypeNameAttrib.PSTypeName)); return result; } ObsoleteAttribute obsoleteAttrib = attrib as ObsoleteAttribute; if (obsoleteAttrib != null) { string parameters = string.Empty; if (obsoleteAttrib.IsError) { string message = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'"; parameters = message + ", $true"; } else if (obsoleteAttrib.Message != null) { parameters = "'" + CodeGeneration.EscapeSingleQuotedStringContent(obsoleteAttrib.Message) + "'"; } result = string.Format( CultureInfo.InvariantCulture, ObsoleteFormat, prefix, parameters); return result; } return null; } #endregion } /// <summary> /// The metadata associated with a bindable type /// </summary> /// internal class InternalParameterMetadata { #region ctor /// <summary> /// Gets or constructs an instance of the InternalParameterMetadata for the specified runtime-defined parameters. /// </summary> /// /// <param name="runtimeDefinedParameters"> /// The runtime-defined parameter collection that describes the parameters and their metadata. /// </param> /// /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// /// <param name="checkNames"> /// Check for reserved parameter names. /// </param> /// /// <returns> /// An instance of the TypeMetadata for the specified runtime-defined parameters. The metadata /// is always constructed on demand and never cached. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="runtimeDefinedParameters"/> is null. /// </exception> /// /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> /// internal static InternalParameterMetadata Get(RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { if (runtimeDefinedParameters == null) { throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter"); } return new InternalParameterMetadata(runtimeDefinedParameters, processingDynamicParameters, checkNames); } /// <summary> /// Gets or constructs an instance of the InternalParameterMetadata for the specified type. /// </summary> /// /// <param name="type"> /// The type to get the metadata for. /// </param> /// /// <param name="context"> /// The current engine context. /// </param> /// /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// /// <returns> /// An instance of the TypeMetadata for the specified type. The metadata may get /// constructed on-demand or may be retrieved from the cache. /// </returns> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="type"/> is null. /// </exception> /// /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> /// internal static InternalParameterMetadata Get(Type type, ExecutionContext context, bool processingDynamicParameters) { if (type == null) { throw PSTraceSource.NewArgumentNullException("type"); } InternalParameterMetadata result; if (context == null || !s_parameterMetadataCache.TryGetValue(type.AssemblyQualifiedName, out result)) { result = new InternalParameterMetadata(type, processingDynamicParameters); if (context != null) { s_parameterMetadataCache.TryAdd(type.AssemblyQualifiedName, result); } } return result; } // GetMetadata // /// <summary> /// Constructs an instance of the InternalParameterMetadata using the metadata in the /// runtime-defined parameter collection. /// </summary> /// /// <param name="runtimeDefinedParameters"> /// The collection of runtime-defined parameters that declare the parameters and their /// metadata. /// </param> /// /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// /// <param name="checkNames"> /// Check if the parameter name has been reserved. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="runtimeDefinedParameters"/> is null. /// </exception> /// /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> /// internal InternalParameterMetadata(RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { if (runtimeDefinedParameters == null) { throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameters"); } ConstructCompiledParametersUsingRuntimeDefinedParameters(runtimeDefinedParameters, processingDynamicParameters, checkNames); } // /// <summary> /// Constructs an instance of the InternalParameterMetadata using the reflection information retrieved /// from the enclosing bindable object type. /// </summary> /// /// <param name="type"> /// The type information for the bindable object /// </param> /// /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// /// <exception cref="ArgumentNullException"> /// If <paramref name="type"/> is null. /// </exception> /// /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> /// internal InternalParameterMetadata(Type type, bool processingDynamicParameters) { if (type == null) { throw PSTraceSource.NewArgumentNullException("type"); } _type = type; TypeName = type.Name; ConstructCompiledParametersUsingReflection(processingDynamicParameters); } #endregion ctor /// <summary> /// Gets the type name of the bindable type /// </summary> /// internal string TypeName { get; } = String.Empty; /// <summary> /// Gets a dictionary of the compiled parameter metadata for this Type. /// The dictionary keys are the names of the parameters (or aliases) and /// the values are the compiled parameter metadata. /// </summary> /// internal Dictionary<string, CompiledCommandParameter> BindableParameters { get; } = new Dictionary<string, CompiledCommandParameter>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Gets a dictionary of the parameters that have been aliased to other names. The key is /// the alias name and the value is the CompiledCommandParameter metadata. /// </summary> /// internal Dictionary<string, CompiledCommandParameter> AliasedParameters { get; } = new Dictionary<string, CompiledCommandParameter>(StringComparer.OrdinalIgnoreCase); /// <summary> /// The type information for the class that implements the bindable object. /// This member is null in all cases except when constructed with using reflection /// against the Type. /// </summary> private Type _type; /// <summary> /// The flags used when reflecting against the object to create the metadata /// </summary> internal static readonly BindingFlags metaDataBindingFlags = (BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); #region helper methods /// <summary> /// Fills in the data for an instance of this class using the specified runtime-defined parameters /// </summary> /// /// <param name="runtimeDefinedParameters"> /// A description of the parameters and their metadata. /// </param> /// /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// /// <param name="checkNames"> /// Check if the parameter name has been reserved. /// </param> /// /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> /// private void ConstructCompiledParametersUsingRuntimeDefinedParameters( RuntimeDefinedParameterDictionary runtimeDefinedParameters, bool processingDynamicParameters, bool checkNames) { Diagnostics.Assert( runtimeDefinedParameters != null, "This method should only be called when constructed with a valid runtime-defined parameter collection"); foreach (RuntimeDefinedParameter parameterDefinition in runtimeDefinedParameters.Values) { // Create the compiled parameter and add it to the bindable parameters collection // NTRAID#Windows Out Of Band Releases-926374-2005/12/22-JonN if (null == parameterDefinition) continue; CompiledCommandParameter parameter = new CompiledCommandParameter(parameterDefinition, processingDynamicParameters); AddParameter(parameter, checkNames); } } // ConstructCompiledParametersUsingRuntimeDefinedParameters /// <summary> /// Compiles the parameter using reflection against the CLR type. /// </summary> /// /// <param name="processingDynamicParameters"> /// True if dynamic parameters are being processed, or false otherwise. /// </param> /// /// <exception cref="MetadataException"> /// If a parameter defines the same parameter-set name multiple times. /// If the attributes could not be read from a property or field. /// </exception> /// private void ConstructCompiledParametersUsingReflection(bool processingDynamicParameters) { Diagnostics.Assert( _type != null, "This method should only be called when constructed with the Type"); // Get the property and field info PropertyInfo[] properties = _type.GetProperties(metaDataBindingFlags); FieldInfo[] fields = _type.GetFields(metaDataBindingFlags); foreach (PropertyInfo property in properties) { // Check whether the property is a parameter if (!IsMemberAParameter(property)) { continue; } AddParameter(property, processingDynamicParameters); } foreach (FieldInfo field in fields) { // Check whether the field is a parameter if (!IsMemberAParameter(field)) { continue; } AddParameter(field, processingDynamicParameters); } } // ConstructCompiledParametersUsingReflection private void CheckForReservedParameter(string name) { if (name.Equals("SelectProperty", StringComparison.OrdinalIgnoreCase) || name.Equals("SelectObject", StringComparison.OrdinalIgnoreCase)) { throw new MetadataException( "ReservedParameterName", null, DiscoveryExceptions.ReservedParameterName, name); } } // NTRAID#Windows Out Of Band Releases-906345-2005/06/30-JeffJon // This call verifies that the parameter is unique or // can be deemed unique. If not, an exception is thrown. // If it is unique (or deemed unique), then it is added // to the bindableParameters collection // private void AddParameter(MemberInfo member, bool processingDynamicParameters) { bool error = false; bool useExisting = false; CheckForReservedParameter(member.Name); do // false loop { CompiledCommandParameter existingParameter; if (!BindableParameters.TryGetValue(member.Name, out existingParameter)) { break; } Type existingParamDeclaringType = existingParameter.DeclaringType; if (existingParamDeclaringType == null) { error = true; break; } if (existingParamDeclaringType.IsSubclassOf(member.DeclaringType)) { useExisting = true; break; } if (member.DeclaringType.IsSubclassOf(existingParamDeclaringType)) { // Need to swap out the new member for the parameter definition // that is already defined. RemoveParameter(existingParameter); break; } error = true; } while (false); if (error) { // A duplicate parameter was found and could not be deemed unique // through inheritance. throw new MetadataException( "DuplicateParameterDefinition", null, ParameterBinderStrings.DuplicateParameterDefinition, member.Name); } if (!useExisting) { CompiledCommandParameter parameter = new CompiledCommandParameter(member, processingDynamicParameters); AddParameter(parameter, true); } } private void AddParameter(CompiledCommandParameter parameter, bool checkNames) { if (checkNames) { CheckForReservedParameter(parameter.Name); } BindableParameters.Add(parameter.Name, parameter); // Now add entries in the parameter aliases collection for any aliases. foreach (string alias in parameter.Aliases) { // NTRAID#Windows Out Of Band Releases-917356-JonN if (AliasedParameters.ContainsKey(alias)) { throw new MetadataException( "AliasDeclaredMultipleTimes", null, DiscoveryExceptions.AliasDeclaredMultipleTimes, alias); } AliasedParameters.Add(alias, parameter); } } private void RemoveParameter(CompiledCommandParameter parameter) { BindableParameters.Remove(parameter.Name); // Now add entries in the parameter aliases collection for any aliases. foreach (string alias in parameter.Aliases) { AliasedParameters.Remove(alias); } } /// <summary> /// Determines if the specified member represents a parameter based on its attributes /// </summary> /// /// <param name="member"> /// The member to check to see if it is a parameter. /// </param> /// /// <returns> /// True if at least one ParameterAttribute is declared on the member, or false otherwise. /// </returns> /// /// <exception cref="MetadataException"> /// If GetCustomAttributes fails on <paramref name="member"/>. /// </exception> /// private static bool IsMemberAParameter(MemberInfo member) { bool result = false; try { // MemberInfo.GetCustomAttributes returns IEnumerable<Attribute> in CoreCLR var attributes = member.GetCustomAttributes(typeof(ParameterAttribute), false); if (attributes.Any()) { result = true; } } catch (MetadataException metadataException) { throw new MetadataException( "GetCustomAttributesMetadataException", metadataException, Metadata.MetadataMemberInitialization, member.Name, metadataException.Message); } catch (ArgumentException argumentException) { throw new MetadataException( "GetCustomAttributesArgumentException", argumentException, Metadata.MetadataMemberInitialization, member.Name, argumentException.Message); } return result; } // IsMemberAParameter #endregion helper methods #region Metadata cache /// <summary> /// The cache of the type metadata. The key for the cache is the Type.FullName. /// Note, this is a case-sensitive dictionary because Type names are case sensitive. /// </summary> private static System.Collections.Concurrent.ConcurrentDictionary<string, InternalParameterMetadata> s_parameterMetadataCache = new System.Collections.Concurrent.ConcurrentDictionary<string, InternalParameterMetadata>(StringComparer.Ordinal); #endregion Metadata cache } // CompiledCommandParameter }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// Static class that contains static glm functions /// </summary> public static partial class glm { /// <summary> /// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy) /// </summary> public static swizzle_lvec3 swizzle(lvec3 v) => v.swizzle; /// <summary> /// Returns an array with all values /// </summary> public static long[] Values(lvec3 v) => v.Values; /// <summary> /// Returns an enumerator that iterates through all components. /// </summary> public static IEnumerator<long> GetEnumerator(lvec3 v) => v.GetEnumerator(); /// <summary> /// Returns a string representation of this vector using ', ' as a seperator. /// </summary> public static string ToString(lvec3 v) => v.ToString(); /// <summary> /// Returns a string representation of this vector using a provided seperator. /// </summary> public static string ToString(lvec3 v, string sep) => v.ToString(sep); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format provider for each component. /// </summary> public static string ToString(lvec3 v, string sep, IFormatProvider provider) => v.ToString(sep, provider); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format for each component. /// </summary> public static string ToString(lvec3 v, string sep, string format) => v.ToString(sep, format); /// <summary> /// Returns a string representation of this vector using a provided seperator and a format and format provider for each component. /// </summary> public static string ToString(lvec3 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider); /// <summary> /// Returns the number of components (3). /// </summary> public static int Count(lvec3 v) => v.Count; /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool Equals(lvec3 v, lvec3 rhs) => v.Equals(rhs); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public static bool Equals(lvec3 v, object obj) => v.Equals(obj); /// <summary> /// Returns a hash code for this instance. /// </summary> public static int GetHashCode(lvec3 v) => v.GetHashCode(); /// <summary> /// Returns a bvec3 from component-wise application of Equal (lhs == rhs). /// </summary> public static bvec3 Equal(lvec3 lhs, lvec3 rhs) => lvec3.Equal(lhs, rhs); /// <summary> /// Returns a bvec3 from component-wise application of Equal (lhs == rhs). /// </summary> public static bool Equal(long lhs, long rhs) => lhs == rhs; /// <summary> /// Returns a bvec3 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bvec3 NotEqual(lvec3 lhs, lvec3 rhs) => lvec3.NotEqual(lhs, rhs); /// <summary> /// Returns a bvec3 from component-wise application of NotEqual (lhs != rhs). /// </summary> public static bool NotEqual(long lhs, long rhs) => lhs != rhs; /// <summary> /// Returns a bvec3 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bvec3 GreaterThan(lvec3 lhs, lvec3 rhs) => lvec3.GreaterThan(lhs, rhs); /// <summary> /// Returns a bvec3 from component-wise application of GreaterThan (lhs &gt; rhs). /// </summary> public static bool GreaterThan(long lhs, long rhs) => lhs > rhs; /// <summary> /// Returns a bvec3 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bvec3 GreaterThanEqual(lvec3 lhs, lvec3 rhs) => lvec3.GreaterThanEqual(lhs, rhs); /// <summary> /// Returns a bvec3 from component-wise application of GreaterThanEqual (lhs &gt;= rhs). /// </summary> public static bool GreaterThanEqual(long lhs, long rhs) => lhs >= rhs; /// <summary> /// Returns a bvec3 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bvec3 LesserThan(lvec3 lhs, lvec3 rhs) => lvec3.LesserThan(lhs, rhs); /// <summary> /// Returns a bvec3 from component-wise application of LesserThan (lhs &lt; rhs). /// </summary> public static bool LesserThan(long lhs, long rhs) => lhs < rhs; /// <summary> /// Returns a bvec3 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bvec3 LesserThanEqual(lvec3 lhs, lvec3 rhs) => lvec3.LesserThanEqual(lhs, rhs); /// <summary> /// Returns a bvec3 from component-wise application of LesserThanEqual (lhs &lt;= rhs). /// </summary> public static bool LesserThanEqual(long lhs, long rhs) => lhs <= rhs; /// <summary> /// Returns a lvec3 from component-wise application of Abs (Math.Abs(v)). /// </summary> public static lvec3 Abs(lvec3 v) => lvec3.Abs(v); /// <summary> /// Returns a lvec3 from component-wise application of Abs (Math.Abs(v)). /// </summary> public static long Abs(long v) => Math.Abs(v); /// <summary> /// Returns a lvec3 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v). /// </summary> public static lvec3 HermiteInterpolationOrder3(lvec3 v) => lvec3.HermiteInterpolationOrder3(v); /// <summary> /// Returns a lvec3 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v). /// </summary> public static long HermiteInterpolationOrder3(long v) => (3 - 2 * v) * v * v; /// <summary> /// Returns a lvec3 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v). /// </summary> public static lvec3 HermiteInterpolationOrder5(lvec3 v) => lvec3.HermiteInterpolationOrder5(v); /// <summary> /// Returns a lvec3 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v). /// </summary> public static long HermiteInterpolationOrder5(long v) => ((6 * v - 15) * v + 10) * v * v * v; /// <summary> /// Returns a lvec3 from component-wise application of Sqr (v * v). /// </summary> public static lvec3 Sqr(lvec3 v) => lvec3.Sqr(v); /// <summary> /// Returns a lvec3 from component-wise application of Sqr (v * v). /// </summary> public static long Sqr(long v) => v * v; /// <summary> /// Returns a lvec3 from component-wise application of Pow2 (v * v). /// </summary> public static lvec3 Pow2(lvec3 v) => lvec3.Pow2(v); /// <summary> /// Returns a lvec3 from component-wise application of Pow2 (v * v). /// </summary> public static long Pow2(long v) => v * v; /// <summary> /// Returns a lvec3 from component-wise application of Pow3 (v * v * v). /// </summary> public static lvec3 Pow3(lvec3 v) => lvec3.Pow3(v); /// <summary> /// Returns a lvec3 from component-wise application of Pow3 (v * v * v). /// </summary> public static long Pow3(long v) => v * v * v; /// <summary> /// Returns a lvec3 from component-wise application of Step (v &gt;= 0 ? 1 : 0). /// </summary> public static lvec3 Step(lvec3 v) => lvec3.Step(v); /// <summary> /// Returns a lvec3 from component-wise application of Step (v &gt;= 0 ? 1 : 0). /// </summary> public static long Step(long v) => v >= 0 ? 1 : 0; /// <summary> /// Returns a lvec3 from component-wise application of Sqrt ((long)Math.Sqrt((double)v)). /// </summary> public static lvec3 Sqrt(lvec3 v) => lvec3.Sqrt(v); /// <summary> /// Returns a lvec3 from component-wise application of Sqrt ((long)Math.Sqrt((double)v)). /// </summary> public static long Sqrt(long v) => (long)Math.Sqrt((double)v); /// <summary> /// Returns a lvec3 from component-wise application of InverseSqrt ((long)(1.0 / Math.Sqrt((double)v))). /// </summary> public static lvec3 InverseSqrt(lvec3 v) => lvec3.InverseSqrt(v); /// <summary> /// Returns a lvec3 from component-wise application of InverseSqrt ((long)(1.0 / Math.Sqrt((double)v))). /// </summary> public static long InverseSqrt(long v) => (long)(1.0 / Math.Sqrt((double)v)); /// <summary> /// Returns a ivec3 from component-wise application of Sign (Math.Sign(v)). /// </summary> public static ivec3 Sign(lvec3 v) => lvec3.Sign(v); /// <summary> /// Returns a ivec3 from component-wise application of Sign (Math.Sign(v)). /// </summary> public static int Sign(long v) => Math.Sign(v); /// <summary> /// Returns a lvec3 from component-wise application of Max (Math.Max(lhs, rhs)). /// </summary> public static lvec3 Max(lvec3 lhs, lvec3 rhs) => lvec3.Max(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Max (Math.Max(lhs, rhs)). /// </summary> public static long Max(long lhs, long rhs) => Math.Max(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Min (Math.Min(lhs, rhs)). /// </summary> public static lvec3 Min(lvec3 lhs, lvec3 rhs) => lvec3.Min(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Min (Math.Min(lhs, rhs)). /// </summary> public static long Min(long lhs, long rhs) => Math.Min(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Pow ((long)Math.Pow((double)lhs, (double)rhs)). /// </summary> public static lvec3 Pow(lvec3 lhs, lvec3 rhs) => lvec3.Pow(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Pow ((long)Math.Pow((double)lhs, (double)rhs)). /// </summary> public static long Pow(long lhs, long rhs) => (long)Math.Pow((double)lhs, (double)rhs); /// <summary> /// Returns a lvec3 from component-wise application of Log ((long)Math.Log((double)lhs, (double)rhs)). /// </summary> public static lvec3 Log(lvec3 lhs, lvec3 rhs) => lvec3.Log(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Log ((long)Math.Log((double)lhs, (double)rhs)). /// </summary> public static long Log(long lhs, long rhs) => (long)Math.Log((double)lhs, (double)rhs); /// <summary> /// Returns a lvec3 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)). /// </summary> public static lvec3 Clamp(lvec3 v, lvec3 min, lvec3 max) => lvec3.Clamp(v, min, max); /// <summary> /// Returns a lvec3 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)). /// </summary> public static long Clamp(long v, long min, long max) => Math.Min(Math.Max(v, min), max); /// <summary> /// Returns a lvec3 from component-wise application of Mix (min * (1-a) + max * a). /// </summary> public static lvec3 Mix(lvec3 min, lvec3 max, lvec3 a) => lvec3.Mix(min, max, a); /// <summary> /// Returns a lvec3 from component-wise application of Mix (min * (1-a) + max * a). /// </summary> public static long Mix(long min, long max, long a) => min * (1-a) + max * a; /// <summary> /// Returns a lvec3 from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static lvec3 Lerp(lvec3 min, lvec3 max, lvec3 a) => lvec3.Lerp(min, max, a); /// <summary> /// Returns a lvec3 from component-wise application of Lerp (min * (1-a) + max * a). /// </summary> public static long Lerp(long min, long max, long a) => min * (1-a) + max * a; /// <summary> /// Returns a lvec3 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()). /// </summary> public static lvec3 Smoothstep(lvec3 edge0, lvec3 edge1, lvec3 v) => lvec3.Smoothstep(edge0, edge1, v); /// <summary> /// Returns a lvec3 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()). /// </summary> public static long Smoothstep(long edge0, long edge1, long v) => ((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3(); /// <summary> /// Returns a lvec3 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()). /// </summary> public static lvec3 Smootherstep(lvec3 edge0, lvec3 edge1, lvec3 v) => lvec3.Smootherstep(edge0, edge1, v); /// <summary> /// Returns a lvec3 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()). /// </summary> public static long Smootherstep(long edge0, long edge1, long v) => ((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5(); /// <summary> /// Returns a lvec3 from component-wise application of Fma (a * b + c). /// </summary> public static lvec3 Fma(lvec3 a, lvec3 b, lvec3 c) => lvec3.Fma(a, b, c); /// <summary> /// Returns a lvec3 from component-wise application of Fma (a * b + c). /// </summary> public static long Fma(long a, long b, long c) => a * b + c; /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static lmat2x3 OuterProduct(lvec3 c, lvec2 r) => lvec3.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static lmat3 OuterProduct(lvec3 c, lvec3 r) => lvec3.OuterProduct(c, r); /// <summary> /// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r. /// </summary> public static lmat4x3 OuterProduct(lvec3 c, lvec4 r) => lvec3.OuterProduct(c, r); /// <summary> /// Returns a lvec3 from component-wise application of Add (lhs + rhs). /// </summary> public static lvec3 Add(lvec3 lhs, lvec3 rhs) => lvec3.Add(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Add (lhs + rhs). /// </summary> public static long Add(long lhs, long rhs) => lhs + rhs; /// <summary> /// Returns a lvec3 from component-wise application of Sub (lhs - rhs). /// </summary> public static lvec3 Sub(lvec3 lhs, lvec3 rhs) => lvec3.Sub(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Sub (lhs - rhs). /// </summary> public static long Sub(long lhs, long rhs) => lhs - rhs; /// <summary> /// Returns a lvec3 from component-wise application of Mul (lhs * rhs). /// </summary> public static lvec3 Mul(lvec3 lhs, lvec3 rhs) => lvec3.Mul(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Mul (lhs * rhs). /// </summary> public static long Mul(long lhs, long rhs) => lhs * rhs; /// <summary> /// Returns a lvec3 from component-wise application of Div (lhs / rhs). /// </summary> public static lvec3 Div(lvec3 lhs, lvec3 rhs) => lvec3.Div(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Div (lhs / rhs). /// </summary> public static long Div(long lhs, long rhs) => lhs / rhs; /// <summary> /// Returns a lvec3 from component-wise application of Xor (lhs ^ rhs). /// </summary> public static lvec3 Xor(lvec3 lhs, lvec3 rhs) => lvec3.Xor(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of Xor (lhs ^ rhs). /// </summary> public static long Xor(long lhs, long rhs) => lhs ^ rhs; /// <summary> /// Returns a lvec3 from component-wise application of BitwiseOr (lhs | rhs). /// </summary> public static lvec3 BitwiseOr(lvec3 lhs, lvec3 rhs) => lvec3.BitwiseOr(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of BitwiseOr (lhs | rhs). /// </summary> public static long BitwiseOr(long lhs, long rhs) => lhs | rhs; /// <summary> /// Returns a lvec3 from component-wise application of BitwiseAnd (lhs &amp; rhs). /// </summary> public static lvec3 BitwiseAnd(lvec3 lhs, lvec3 rhs) => lvec3.BitwiseAnd(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of BitwiseAnd (lhs &amp; rhs). /// </summary> public static long BitwiseAnd(long lhs, long rhs) => lhs & rhs; /// <summary> /// Returns a lvec3 from component-wise application of LeftShift (lhs &lt;&lt; rhs). /// </summary> public static lvec3 LeftShift(lvec3 lhs, ivec3 rhs) => lvec3.LeftShift(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of LeftShift (lhs &lt;&lt; rhs). /// </summary> public static long LeftShift(long lhs, int rhs) => lhs << rhs; /// <summary> /// Returns a lvec3 from component-wise application of RightShift (lhs &gt;&gt; rhs). /// </summary> public static lvec3 RightShift(lvec3 lhs, ivec3 rhs) => lvec3.RightShift(lhs, rhs); /// <summary> /// Returns a lvec3 from component-wise application of RightShift (lhs &gt;&gt; rhs). /// </summary> public static long RightShift(long lhs, int rhs) => lhs >> rhs; /// <summary> /// Returns the minimal component of this vector. /// </summary> public static long MinElement(lvec3 v) => v.MinElement; /// <summary> /// Returns the maximal component of this vector. /// </summary> public static long MaxElement(lvec3 v) => v.MaxElement; /// <summary> /// Returns the euclidean length of this vector. /// </summary> public static double Length(lvec3 v) => v.Length; /// <summary> /// Returns the squared euclidean length of this vector. /// </summary> public static double LengthSqr(lvec3 v) => v.LengthSqr; /// <summary> /// Returns the sum of all components. /// </summary> public static long Sum(lvec3 v) => v.Sum; /// <summary> /// Returns the euclidean norm of this vector. /// </summary> public static double Norm(lvec3 v) => v.Norm; /// <summary> /// Returns the one-norm of this vector. /// </summary> public static double Norm1(lvec3 v) => v.Norm1; /// <summary> /// Returns the two-norm (euclidean length) of this vector. /// </summary> public static double Norm2(lvec3 v) => v.Norm2; /// <summary> /// Returns the max-norm of this vector. /// </summary> public static double NormMax(lvec3 v) => v.NormMax; /// <summary> /// Returns the p-norm of this vector. /// </summary> public static double NormP(lvec3 v, double p) => v.NormP(p); /// <summary> /// Returns the inner product (dot product, scalar product) of the two vectors. /// </summary> public static long Dot(lvec3 lhs, lvec3 rhs) => lvec3.Dot(lhs, rhs); /// <summary> /// Returns the euclidean distance between the two vectors. /// </summary> public static double Distance(lvec3 lhs, lvec3 rhs) => lvec3.Distance(lhs, rhs); /// <summary> /// Returns the squared euclidean distance between the two vectors. /// </summary> public static double DistanceSqr(lvec3 lhs, lvec3 rhs) => lvec3.DistanceSqr(lhs, rhs); /// <summary> /// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result). /// </summary> public static lvec3 Reflect(lvec3 I, lvec3 N) => lvec3.Reflect(I, N); /// <summary> /// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result). /// </summary> public static lvec3 Refract(lvec3 I, lvec3 N, long eta) => lvec3.Refract(I, N, eta); /// <summary> /// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N). /// </summary> public static lvec3 FaceForward(lvec3 N, lvec3 I, lvec3 Nref) => lvec3.FaceForward(N, I, Nref); /// <summary> /// Returns the outer product (cross product, vector product) of the two vectors. /// </summary> public static lvec3 Cross(lvec3 l, lvec3 r) => lvec3.Cross(l, r); /// <summary> /// Returns a lvec3 with independent and identically distributed uniform integer values between 0 (inclusive) and maxValue (exclusive). (A maxValue of 0 is allowed and returns 0.) /// </summary> public static lvec3 Random(Random random, lvec3 maxValue) => lvec3.Random(random, maxValue); /// <summary> /// Returns a lvec3 with independent and identically distributed uniform integer values between 0 (inclusive) and maxValue (exclusive). (A maxValue of 0 is allowed and returns 0.) /// </summary> public static long Random(Random random, long maxValue) => (long)random.Next((int)maxValue); /// <summary> /// Returns a lvec3 with independent and identically distributed uniform integer values between minValue (inclusive) and maxValue (exclusive). (minValue == maxValue is allowed and returns minValue. Negative values are allowed.) /// </summary> public static lvec3 Random(Random random, lvec3 minValue, lvec3 maxValue) => lvec3.Random(random, minValue, maxValue); /// <summary> /// Returns a lvec3 with independent and identically distributed uniform integer values between minValue (inclusive) and maxValue (exclusive). (minValue == maxValue is allowed and returns minValue. Negative values are allowed.) /// </summary> public static long Random(Random random, long minValue, long maxValue) => (long)random.Next((int)minValue, (int)maxValue); /// <summary> /// Returns a lvec3 with independent and identically distributed uniform integer values between minValue (inclusive) and maxValue (exclusive). (minValue == maxValue is allowed and returns minValue. Negative values are allowed.) /// </summary> public static lvec3 RandomUniform(Random random, lvec3 minValue, lvec3 maxValue) => lvec3.RandomUniform(random, minValue, maxValue); /// <summary> /// Returns a lvec3 with independent and identically distributed uniform integer values between minValue (inclusive) and maxValue (exclusive). (minValue == maxValue is allowed and returns minValue. Negative values are allowed.) /// </summary> public static long RandomUniform(Random random, long minValue, long maxValue) => (long)random.Next((int)minValue, (int)maxValue); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MergedObjectType.cs" company="KlusterKite"> // All rights reserved // </copyright> // <summary> // The merged api type description // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace KlusterKite.Web.GraphQL.Publisher.Internals { using System; using System.Collections.Generic; using System.Linq; using global::GraphQL.Language.AST; using global::GraphQL.Resolvers; using global::GraphQL.Types; using KlusterKite.API.Attributes.Authorization; using KlusterKite.API.Client; using KlusterKite.Security.Attributes; using KlusterKite.Security.Client; using KlusterKite.Web.GraphQL.Publisher.GraphTypes; using Newtonsoft.Json.Linq; /// <summary> /// The merged api type description /// </summary> internal class MergedObjectType : MergedFieldedType { /// <summary> /// Gets the name of the internal pre-calculated field to store globalId /// </summary> internal const string GlobalIdPropertyName = "__newGlobalId"; /// <summary> /// Gets the name of the internal pre-calculated field to store request data for the current object /// </summary> internal const string RequestPropertyName = "_localRequest"; /// <summary> /// the list of providers /// </summary> private readonly List<FieldProvider> providers = new List<FieldProvider>(); /// <summary> /// Initializes a new instance of the <see cref="MergedObjectType"/> class. /// </summary> /// <param name="originalTypeName"> /// The original type name. /// </param> public MergedObjectType(string originalTypeName) : base(originalTypeName) { this.Category = EnCategory.SingleApiType; } /// <summary> /// The field type category /// </summary> public enum EnCategory { /// <summary> /// This is object provided by some single api /// </summary> SingleApiType, /// <summary> /// This is object that is combined from multiple API providers (some fields provided by one API, some from other) /// </summary> MultipleApiType } /// <summary> /// Gets or sets the field category /// </summary> public EnCategory Category { get; set; } /// <summary> /// Gets combined name from all provider /// </summary> public override string ComplexTypeName { get { if (this.Providers.Any()) { var providersNames = this.Providers.Select( p => $"{EscapeName(p.Provider.Description.ApiName)}_{EscapeName(p.FieldType.TypeName)}") .Distinct() .OrderBy(s => s) .ToArray(); return string.Join("_", providersNames); } return EscapeName(this.OriginalTypeName); } } /// <inheritdoc /> public override string Description => this.Providers.Any() ? string.Join( "\n", this.Providers.Select(p => p.FieldType.Description).Distinct().OrderBy(s => s).ToArray()) : null; /// <summary> /// Gets or sets the list of providers /// </summary> public IEnumerable<FieldProvider> Providers => this.providers; /// <summary> /// Gets the globalId from source data and object id value /// </summary> /// <param name="source">The source data</param> /// <param name="id">The id value</param> /// <returns>The global id</returns> public static JArray GetGlobalId(JObject source, JToken id) { var parent = source.Parent; JArray parentGlobalId = null; var selfRequest = source.Property(RequestPropertyName)?.Value as JObject; while (parent != null) { parentGlobalId = (parent as JObject)?.Property(GlobalIdPropertyName)?.Value as JArray; if (selfRequest == null) { selfRequest = (parent as JObject)?.Property(RequestPropertyName)?.Value as JObject; } if (parentGlobalId != null) { break; } parent = parent.Parent; } if (source.Property(GlobalIdPropertyName) == null && selfRequest != null) { var globalId = parentGlobalId != null ? new JArray(parentGlobalId) : new JArray(); var selfPart = (JObject)selfRequest.DeepClone(); if (id != null) { selfPart.Add("id", id); } globalId.Add(selfPart); return globalId; } return null; } /// <summary> /// Adds a provider to the provider list /// </summary> /// <param name="provider">The provider</param> public void AddProvider(FieldProvider provider) { this.providers.Add(provider); } /// <summary> /// Adds the list of providers to the provider list /// </summary> /// <param name="newProviders">The list of providers</param> public void AddProviders(IEnumerable<FieldProvider> newProviders) { this.providers.AddRange(newProviders); } /// <summary> /// Makes a duplicate of the current object /// </summary> /// <returns>The object duplicate</returns> public virtual MergedObjectType Clone() { var mergedObjectType = new MergedObjectType(this.OriginalTypeName); this.FillWithMyFields(mergedObjectType); return mergedObjectType; } /// <inheritdoc /> public override IGraphType ExtractInterface(ApiProvider provider, NodeInterface nodeInterface) { var fieldProvider = this.providers.FirstOrDefault(fp => fp.Provider == provider); if (fieldProvider == null) { return null; } var fields = this.Fields.Where(f => f.Value.Providers.Any(fp => fp == provider)) .Select(this.ConvertApiField) .ToList(); var idField = fields.FirstOrDefault(f => f.Name == "id"); if (idField != null) { idField.Name = "__id"; } fields.Insert(0, new FieldType { Name = "id", ResolvedType = new IdGraphType() }); var apiInterface = new TypeInterface( this.GetInterfaceName(provider), fieldProvider.FieldType.Description); foreach (var field in fields) { apiInterface.AddField(field); } return apiInterface; } /// <inheritdoc /> public override string GetInterfaceName(ApiProvider provider) { var fieldProvider = this.providers.FirstOrDefault(fp => fp.Provider == provider); return fieldProvider == null ? null : $"I{EscapeName(provider.Description.ApiName)}_{EscapeName(fieldProvider.FieldType.TypeName)}"; } /// <inheritdoc /> public override IEnumerable<string> GetPossibleFragmentTypeNames() { foreach (var typeName in base.GetPossibleFragmentTypeNames()) { yield return typeName; } foreach (var fieldProvider in this.Providers) { yield return this.GetInterfaceName(fieldProvider.Provider); } yield return "Node"; } /// <summary> /// Gather request parameters for the specified api provider /// </summary> /// <param name="provider"> /// The api provider /// </param> /// <param name="contextFieldAst"> /// The request context /// </param> /// <param name="context"> /// The resolve context. /// </param> /// <returns> /// The list of api requests /// </returns> public IEnumerable<ApiRequest> GatherMultipleApiRequest( ApiProvider provider, Field contextFieldAst, ResolveFieldContext context) { if (this.KeyField != null && this.KeyField.Providers.Contains(provider)) { yield return new ApiRequest { Alias = "__id", FieldName = this.KeyField.FieldName }; } var requestedFields = GetRequestedFields(contextFieldAst.SelectionSet, context, this).ToList(); var usedFields = requestedFields.Join( this.Fields.Where(f => f.Value.Providers.Any(fp => fp == provider)), s => s.Name, fp => fp.Key, (s, fp) => new { Ast = s, Field = fp.Value }).ToList(); foreach (var usedField in usedFields) { var apiField = usedField.Field.OriginalFields[provider.Description.ApiName]; if (apiField != null && !apiField.CheckAuthorization(context.UserContext as RequestContext, EnConnectionAction.Query)) { var severity = apiField.LogAccessRules.Any() ? apiField.LogAccessRules.Max(l => l.Severity) : EnSeverity.Trivial; SecurityLog.CreateRecord( EnSecurityLogType.OperationDenied, severity, context.UserContext as RequestContext, "Unauthorized call to {ApiPath}", $"{contextFieldAst.Name}.{apiField.Name}"); continue; } var request = new ApiRequest { Arguments = usedField.Ast.Arguments.ToJson(context), Alias = usedField.Ast.Alias ?? usedField.Ast.Name, FieldName = usedField.Field.FieldName }; var endType = usedField.Field.Type as MergedObjectType; request.Fields = endType?.Category == EnCategory.MultipleApiType ? endType.GatherMultipleApiRequest(provider, usedField.Ast, context).ToList() : usedField.Field.Type.GatherSingleApiRequest(usedField.Ast, context).ToList(); yield return request; } } /// <inheritdoc /> public override IGraphType GenerateGraphType(NodeInterface nodeInterface, List<TypeInterface> interfaces) { var graphType = (VirtualGraphType)base.GenerateGraphType(nodeInterface, interfaces); var idField = graphType.Fields.FirstOrDefault(f => f.Name == "id"); if (idField != null) { idField.Name = "__id"; } graphType.AddField( new FieldType { Name = "id", ResolvedType = new IdGraphType(), Resolver = new GlobalIdResolver() }); graphType.AddResolvedInterface(nodeInterface); nodeInterface.AddImplementedType(this.ComplexTypeName, graphType); return graphType; } /// <inheritdoc /> public override object Resolve(ResolveFieldContext context) { var resolve = base.Resolve(context) as JObject; if (resolve == null) { return null; } return this.ResolveData(context, resolve); } /// <summary> /// Resolves parent data /// </summary> /// <param name="context"> /// The request context /// </param> /// <param name="source"> /// The parent data /// </param> /// <param name="setLocalRequest"> /// A value indicating whether to set "local request" bread crumbs /// </param> /// <returns> /// The resolved data /// </returns> public virtual JObject ResolveData(ResolveFieldContext context, JObject source, bool setLocalRequest = true) { if (setLocalRequest) { var localRequest = new JObject { { "f", context.FieldName } }; if (context.Arguments != null && context.Arguments.Any()) { var args = context.Arguments .OrderBy(p => p.Key) .ToDictionary(p => p.Key, p => p.Value); if (args.Any()) { var argumentsValue = JObject.FromObject(args); localRequest.Add("a", argumentsValue); } } source.Add(RequestPropertyName, localRequest); } // generating self globalId data var globalId = GetGlobalId(source, source.Property("__id")?.Value); if (globalId != null) { source.Add(GlobalIdPropertyName, globalId); } return source; } /// <summary> /// Fills the empty object with current objects fields /// </summary> /// <param name="shell">The empty object to fill</param> protected virtual void FillWithMyFields(MergedObjectType shell) { shell.AddProviders(this.providers); shell.Fields = this.Fields.ToDictionary(p => p.Key, p => p.Value.Clone()); shell.Category = this.Category; } /// <summary> /// Resolves value for global id /// </summary> private class GlobalIdResolver : IFieldResolver { /// <inheritdoc /> public object Resolve(ResolveFieldContext context) { var id = (context.Source as JObject)?.Property(GlobalIdPropertyName)?.Value; if (id == null) { // relay doesn't like null id return new JObject { { "empty", Guid.NewGuid().ToString("N") } }.PackGlobalId(); } return id.PackGlobalId(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Baseline; using Marten.Exceptions; using Marten.Internal; using Marten.Linq.Fields; using Marten.Linq.Filters; using Marten.Linq.SqlGeneration; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; using Remotion.Linq.Clauses.ResultOperators; using Remotion.Linq.Parsing; namespace Marten.Linq.Parsing { internal partial class WhereClauseParser : RelinqExpressionVisitor, IWhereFragmentHolder { private static readonly IDictionary<ExpressionType, string> _operators = new Dictionary<ExpressionType, string> { {ExpressionType.Equal, "="}, {ExpressionType.NotEqual, "!="}, {ExpressionType.GreaterThan, ">"}, {ExpressionType.GreaterThanOrEqual, ">="}, {ExpressionType.LessThan, "<"}, {ExpressionType.LessThanOrEqual, "<="} }; /// <summary> /// Used for NOT operator conversions /// </summary> public static readonly IDictionary<string, string> NotOperators = new Dictionary<string, string> { {"=", "!="}, {"!=", "="}, {">", "<="}, {">=", "<"}, {"<", ">="}, {"<=", ">"} }; /// <summary> /// Used when reordering a Binary comparison /// </summary> public static readonly IDictionary<string, string> OppositeOperators = new Dictionary<string, string> { {"=", "="}, {"!=", "!="}, {">", "<"}, {">=", "<="}, {"<", ">"}, {"<=", ">="} }; private readonly IMartenSession _session; private readonly Statement _statement; private IWhereFragmentHolder _holder; public WhereClauseParser(IMartenSession session, Statement statement) { _session = session; _statement = statement; _holder = this; } public ISqlFragment Build(WhereClause clause) { _holder = this; Where = null; Visit(clause.Predicate); if (Where == null) { throw new BadLinqExpressionException($"Unsupported Where clause: '{clause.Predicate}'"); } return Where; } public ISqlFragment Where { get; private set; } public bool InSubQuery { get; set; } void IWhereFragmentHolder.Register(ISqlFragment fragment) { Where = fragment; } protected override Expression VisitSubQuery(SubQueryExpression expression) { var parser = new SubQueryFilterParser(this, expression); var where = parser.BuildWhereFragment(); _holder.Register(where); return null; } protected override Expression VisitMethodCall(MethodCallExpression node) { var where = _session.Options.Linq.BuildWhereFragment(_statement.Fields, node, _session.Serializer); _holder.Register(where); return null; } protected override Expression VisitBinary(BinaryExpression node) { if (_operators.TryGetValue(node.NodeType, out var op)) { var binary = new BinaryExpressionVisitor(this); _holder.Register(binary.BuildWhereFragment(node, op)); return null; } switch (node.NodeType) { case ExpressionType.AndAlso: buildCompoundWhereFragment(node, "and"); break; case ExpressionType.OrElse: buildCompoundWhereFragment(node, "or"); break; default: throw new BadLinqExpressionException($"Unsupported expression type '{node.NodeType}' in binary expression"); } return null; } private void buildCompoundWhereFragment(BinaryExpression node, string separator) { var original = _holder; var compound = new CompoundWhereFragment(separator); _holder.Register(compound); _holder = compound; Visit(node.Left); _holder = compound; Visit(node.Right); _holder = original; } protected override Expression VisitUnary(UnaryExpression node) { if (node.NodeType == ExpressionType.Not) { var original = _holder; _holder = new NotWhereFragment(original); var returnValue = Visit(node.Operand); _holder = original; return returnValue; } return base.VisitUnary(node); } protected override Expression VisitMember(MemberExpression node) { if (node.Type == typeof(bool)) { var field = _statement.Fields.FieldFor(node); _holder.Register(new BooleanFieldIsTrue(field)); return null; } return base.VisitMember(node); } protected override Expression VisitConstant(ConstantExpression node) { if ((node.Type == typeof(bool))) { if (InSubQuery) { throw new BadLinqExpressionException("Unsupported Where() clause in a sub-collection expression"); } _holder.Register(new WhereFragment(node.Value.ToString().ToLower())); } return base.VisitConstant(node); } internal enum SubQueryUsage { Any, Count, Contains, Intersect } internal class SubQueryFilterParser : RelinqExpressionVisitor { private readonly WhereClauseParser _parent; private readonly SubQueryExpression _expression; #pragma warning disable 414 private bool _isDistinct; #pragma warning restore 414 private readonly WhereClause[] _wheres; private readonly Expression _contains; public SubQueryFilterParser(WhereClauseParser parent, SubQueryExpression expression) { _parent = parent; _expression = expression; foreach (var @operator in expression.QueryModel.ResultOperators) { switch (@operator) { case AnyResultOperator _: Usage = SubQueryUsage.Any; break; case CountResultOperator _: Usage = SubQueryUsage.Count; break; case LongCountResultOperator _: Usage = SubQueryUsage.Count; break; case DistinctResultOperator _: _isDistinct = true; break; case ContainsResultOperator op: Usage = op.Item is QuerySourceReferenceExpression ? SubQueryUsage.Intersect : SubQueryUsage.Contains; _contains = op.Item; break; // TODO -- add Min/Max/Avg/Sum operators? default: throw new BadLinqExpressionException($"Invalid result operator {@operator} in sub query '{expression}'"); } } _wheres = expression.QueryModel.BodyClauses.OfType<WhereClause>().ToArray(); } public SubQueryUsage Usage { get; } public ISqlFragment BuildWhereFragment() { switch (Usage) { case SubQueryUsage.Any: return buildWhereForAny(findArrayField()); case SubQueryUsage.Contains: return buildWhereForContains(findArrayField()); case SubQueryUsage.Intersect: return new WhereInArray("data", (ConstantExpression)_expression.QueryModel.MainFromClause.FromExpression); default: throw new NotImplementedException(); } } private ArrayField findArrayField() { ArrayField field; try { field = (ArrayField) _parent._statement.Fields.FieldFor(_expression.QueryModel.MainFromClause.FromExpression); } catch (Exception e) { throw new BadLinqExpressionException("The sub query is not sourced from a supported collection type", e); } return field; } private ISqlFragment buildWhereForContains(ArrayField field) { if (_contains is ConstantExpression c) { var flattened = new FlattenerStatement(field, _parent._session, _parent._statement); var idSelectorStatement = new ContainsIdSelectorStatement(flattened, _parent._session, c); return new WhereInSubQuery(idSelectorStatement.ExportName); } throw new NotImplementedException(); } private ISqlFragment buildWhereForAny(ArrayField field) { if (_wheres.Any()) { var flattened = new FlattenerStatement(field, _parent._session, _parent._statement); var itemType = _expression.QueryModel.MainFromClause.ItemType; var elementFields = _parent._session.Options.ChildTypeMappingFor(itemType); var idSelectorStatement = new IdSelectorStatement(_parent._session, elementFields, flattened); idSelectorStatement.WhereClauses.AddRange(_wheres); idSelectorStatement.CompileLocal(_parent._session); return new WhereInSubQuery(idSelectorStatement.ExportName); } return new CollectionIsNotEmpty(field); } public CountComparisonStatement BuildCountComparisonStatement() { if (Usage != SubQueryUsage.Count) { throw new BadLinqExpressionException("Invalid comparison"); } var field = findArrayField(); var flattened = new FlattenerStatement(field, _parent._session, _parent._statement); var elementFields = _parent._session.Options.ChildTypeMappingFor(field.ElementType); var statement = new CountComparisonStatement(_parent._session, field.ElementType, elementFields, flattened); if (_wheres.Any()) { statement.WhereClauses.AddRange(_wheres); statement.CompileLocal(_parent._session); } return statement; } } } }
namespace android.content.res { [global::MonoJavaBridge.JavaClass()] public partial class Resources : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Resources() { InitJNI(); } protected Resources(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class NotFoundException : java.lang.RuntimeException { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static NotFoundException() { InitJNI(); } protected NotFoundException(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _NotFoundException2286; public NotFoundException() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.res.Resources.NotFoundException.staticClass, global::android.content.res.Resources.NotFoundException._NotFoundException2286); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _NotFoundException2287; public NotFoundException(java.lang.String arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.res.Resources.NotFoundException.staticClass, global::android.content.res.Resources.NotFoundException._NotFoundException2287, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.res.Resources.NotFoundException.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/res/Resources$NotFoundException")); global::android.content.res.Resources.NotFoundException._NotFoundException2286 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.NotFoundException.staticClass, "<init>", "()V"); global::android.content.res.Resources.NotFoundException._NotFoundException2287 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.NotFoundException.staticClass, "<init>", "(Ljava/lang/String;)V"); } } [global::MonoJavaBridge.JavaClass()] public sealed partial class Theme : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static Theme() { InitJNI(); } internal Theme(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _dump2288; public void dump(int arg0, java.lang.String arg1, java.lang.String arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources.Theme._dump2288, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.Theme.staticClass, global::android.content.res.Resources.Theme._dump2288, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _obtainStyledAttributes2289; public global::android.content.res.TypedArray obtainStyledAttributes(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources.Theme._obtainStyledAttributes2289, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.TypedArray; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.Theme.staticClass, global::android.content.res.Resources.Theme._obtainStyledAttributes2289, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.TypedArray; } internal static global::MonoJavaBridge.MethodId _obtainStyledAttributes2290; public global::android.content.res.TypedArray obtainStyledAttributes(int arg0, int[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources.Theme._obtainStyledAttributes2290, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.res.TypedArray; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.Theme.staticClass, global::android.content.res.Resources.Theme._obtainStyledAttributes2290, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.res.TypedArray; } internal static global::MonoJavaBridge.MethodId _obtainStyledAttributes2291; public global::android.content.res.TypedArray obtainStyledAttributes(android.util.AttributeSet arg0, int[] arg1, int arg2, int arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources.Theme._obtainStyledAttributes2291, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.content.res.TypedArray; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.Theme.staticClass, global::android.content.res.Resources.Theme._obtainStyledAttributes2291, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.content.res.TypedArray; } internal static global::MonoJavaBridge.MethodId _setTo2292; public void setTo(android.content.res.Resources.Theme arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources.Theme._setTo2292, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.Theme.staticClass, global::android.content.res.Resources.Theme._setTo2292, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _applyStyle2293; public void applyStyle(int arg0, bool arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources.Theme._applyStyle2293, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.Theme.staticClass, global::android.content.res.Resources.Theme._applyStyle2293, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _resolveAttribute2294; public bool resolveAttribute(int arg0, android.util.TypedValue arg1, bool arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.res.Resources.Theme._resolveAttribute2294, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.res.Resources.Theme.staticClass, global::android.content.res.Resources.Theme._resolveAttribute2294, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.res.Resources.Theme.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/res/Resources$Theme")); global::android.content.res.Resources.Theme._dump2288 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.Theme.staticClass, "dump", "(ILjava/lang/String;Ljava/lang/String;)V"); global::android.content.res.Resources.Theme._obtainStyledAttributes2289 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.Theme.staticClass, "obtainStyledAttributes", "([I)Landroid/content/res/TypedArray;"); global::android.content.res.Resources.Theme._obtainStyledAttributes2290 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.Theme.staticClass, "obtainStyledAttributes", "(I[I)Landroid/content/res/TypedArray;"); global::android.content.res.Resources.Theme._obtainStyledAttributes2291 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.Theme.staticClass, "obtainStyledAttributes", "(Landroid/util/AttributeSet;[III)Landroid/content/res/TypedArray;"); global::android.content.res.Resources.Theme._setTo2292 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.Theme.staticClass, "setTo", "(Landroid/content/res/Resources$Theme;)V"); global::android.content.res.Resources.Theme._applyStyle2293 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.Theme.staticClass, "applyStyle", "(IZ)V"); global::android.content.res.Resources.Theme._resolveAttribute2294 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.Theme.staticClass, "resolveAttribute", "(ILandroid/util/TypedValue;Z)Z"); } } internal static global::MonoJavaBridge.MethodId _getBoolean2295; public virtual bool getBoolean(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.content.res.Resources._getBoolean2295, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getBoolean2295, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getValue2296; public virtual void getValue(int arg0, android.util.TypedValue arg1, bool arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources._getValue2296, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getValue2296, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getValue2297; public virtual void getValue(java.lang.String arg0, android.util.TypedValue arg1, bool arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources._getValue2297, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getValue2297, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getInteger2298; public virtual int getInteger(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.Resources._getInteger2298, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getInteger2298, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getString2299; public virtual global::java.lang.String getString(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getString2299, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getString2299, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getString2300; public virtual global::java.lang.String getString(int arg0, java.lang.Object[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getString2300, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getString2300, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getIdentifier2301; public virtual int getIdentifier(java.lang.String arg0, java.lang.String arg1, java.lang.String arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.Resources._getIdentifier2301, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getIdentifier2301, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getAssets2302; public virtual global::android.content.res.AssetManager getAssets() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getAssets2302)) as android.content.res.AssetManager; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getAssets2302)) as android.content.res.AssetManager; } internal static global::MonoJavaBridge.MethodId _getText2303; public virtual global::java.lang.CharSequence getText(int arg0, java.lang.CharSequence arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getText2303, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getText2303, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; } public java.lang.CharSequence getText(int arg0, string arg1) { return getText(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1); } internal static global::MonoJavaBridge.MethodId _getText2304; public virtual global::java.lang.CharSequence getText(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getText2304, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getText2304, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _getSystem2305; public static global::android.content.res.Resources getSystem() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.content.res.Resources.staticClass, global::android.content.res.Resources._getSystem2305)) as android.content.res.Resources; } internal static global::MonoJavaBridge.MethodId _getQuantityText2306; public virtual global::java.lang.CharSequence getQuantityText(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getQuantityText2306, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getQuantityText2306, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.CharSequence; } internal static global::MonoJavaBridge.MethodId _getQuantityString2307; public virtual global::java.lang.String getQuantityString(int arg0, int arg1, java.lang.Object[] arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getQuantityString2307, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getQuantityString2307, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getQuantityString2308; public virtual global::java.lang.String getQuantityString(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getQuantityString2308, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getQuantityString2308, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getTextArray2309; public virtual global::java.lang.CharSequence[] getTextArray(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.CharSequence>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getTextArray2309, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.CharSequence>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getTextArray2309, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.CharSequence[]; } internal static global::MonoJavaBridge.MethodId _getStringArray2310; public virtual global::java.lang.String[] getStringArray(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getStringArray2310, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getStringArray2310, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String[]; } internal static global::MonoJavaBridge.MethodId _getIntArray2311; public virtual int[] getIntArray(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getIntArray2311, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as int[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<int>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getIntArray2311, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as int[]; } internal static global::MonoJavaBridge.MethodId _obtainTypedArray2312; public virtual global::android.content.res.TypedArray obtainTypedArray(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._obtainTypedArray2312, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.TypedArray; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._obtainTypedArray2312, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.TypedArray; } internal static global::MonoJavaBridge.MethodId _getDimension2313; public virtual float getDimension(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.content.res.Resources._getDimension2313, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getDimension2313, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDimensionPixelOffset2314; public virtual int getDimensionPixelOffset(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.Resources._getDimensionPixelOffset2314, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getDimensionPixelOffset2314, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getDimensionPixelSize2315; public virtual int getDimensionPixelSize(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.Resources._getDimensionPixelSize2315, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getDimensionPixelSize2315, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getFraction2316; public virtual float getFraction(int arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.content.res.Resources._getFraction2316, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getFraction2316, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getDrawable2317; public virtual global::android.graphics.drawable.Drawable getDrawable(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getDrawable2317, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getDrawable2317, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.drawable.Drawable; } internal static global::MonoJavaBridge.MethodId _getMovie2318; public virtual global::android.graphics.Movie getMovie(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getMovie2318, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Movie; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getMovie2318, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Movie; } internal static global::MonoJavaBridge.MethodId _getColor2319; public virtual int getColor(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.content.res.Resources._getColor2319, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getColor2319, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getColorStateList2320; public virtual global::android.content.res.ColorStateList getColorStateList(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getColorStateList2320, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.ColorStateList; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getColorStateList2320, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.ColorStateList; } internal static global::MonoJavaBridge.MethodId _getLayout2321; public virtual global::android.content.res.XmlResourceParser getLayout(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.res.XmlResourceParser>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getLayout2321, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.XmlResourceParser; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.res.XmlResourceParser>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getLayout2321, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.XmlResourceParser; } internal static global::MonoJavaBridge.MethodId _getAnimation2322; public virtual global::android.content.res.XmlResourceParser getAnimation(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.res.XmlResourceParser>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getAnimation2322, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.XmlResourceParser; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.res.XmlResourceParser>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getAnimation2322, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.XmlResourceParser; } internal static global::MonoJavaBridge.MethodId _getXml2323; public virtual global::android.content.res.XmlResourceParser getXml(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.res.XmlResourceParser>(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getXml2323, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.XmlResourceParser; else return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.content.res.XmlResourceParser>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getXml2323, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.XmlResourceParser; } internal static global::MonoJavaBridge.MethodId _openRawResource2324; public virtual global::java.io.InputStream openRawResource(int arg0, android.util.TypedValue arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._openRawResource2324, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.io.InputStream; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._openRawResource2324, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.io.InputStream; } internal static global::MonoJavaBridge.MethodId _openRawResource2325; public virtual global::java.io.InputStream openRawResource(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._openRawResource2325, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.InputStream; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._openRawResource2325, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.io.InputStream; } internal static global::MonoJavaBridge.MethodId _openRawResourceFd2326; public virtual global::android.content.res.AssetFileDescriptor openRawResourceFd(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._openRawResourceFd2326, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.AssetFileDescriptor; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._openRawResourceFd2326, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.content.res.AssetFileDescriptor; } internal static global::MonoJavaBridge.MethodId _newTheme2327; public virtual global::android.content.res.Resources.Theme newTheme() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._newTheme2327)) as android.content.res.Resources.Theme; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._newTheme2327)) as android.content.res.Resources.Theme; } internal static global::MonoJavaBridge.MethodId _obtainAttributes2328; public virtual global::android.content.res.TypedArray obtainAttributes(android.util.AttributeSet arg0, int[] arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._obtainAttributes2328, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.res.TypedArray; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._obtainAttributes2328, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.content.res.TypedArray; } internal static global::MonoJavaBridge.MethodId _updateConfiguration2329; public virtual void updateConfiguration(android.content.res.Configuration arg0, android.util.DisplayMetrics arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources._updateConfiguration2329, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._updateConfiguration2329, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getDisplayMetrics2330; public virtual global::android.util.DisplayMetrics getDisplayMetrics() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getDisplayMetrics2330)) as android.util.DisplayMetrics; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getDisplayMetrics2330)) as android.util.DisplayMetrics; } internal static global::MonoJavaBridge.MethodId _getConfiguration2331; public virtual global::android.content.res.Configuration getConfiguration() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getConfiguration2331)) as android.content.res.Configuration; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getConfiguration2331)) as android.content.res.Configuration; } internal static global::MonoJavaBridge.MethodId _getResourceName2332; public virtual global::java.lang.String getResourceName(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getResourceName2332, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getResourceName2332, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getResourcePackageName2333; public virtual global::java.lang.String getResourcePackageName(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getResourcePackageName2333, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getResourcePackageName2333, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getResourceTypeName2334; public virtual global::java.lang.String getResourceTypeName(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getResourceTypeName2334, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getResourceTypeName2334, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _getResourceEntryName2335; public virtual global::java.lang.String getResourceEntryName(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.content.res.Resources._getResourceEntryName2335, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._getResourceEntryName2335, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _parseBundleExtras2336; public virtual void parseBundleExtras(android.content.res.XmlResourceParser arg0, android.os.Bundle arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources._parseBundleExtras2336, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._parseBundleExtras2336, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _parseBundleExtra2337; public virtual void parseBundleExtra(java.lang.String arg0, android.util.AttributeSet arg1, android.os.Bundle arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources._parseBundleExtra2337, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._parseBundleExtra2337, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _flushLayoutCache2338; public virtual void flushLayoutCache() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources._flushLayoutCache2338); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._flushLayoutCache2338); } internal static global::MonoJavaBridge.MethodId _finishPreloading2339; public virtual void finishPreloading() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.content.res.Resources._finishPreloading2339); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.content.res.Resources.staticClass, global::android.content.res.Resources._finishPreloading2339); } internal static global::MonoJavaBridge.MethodId _Resources2340; public Resources(android.content.res.AssetManager arg0, android.util.DisplayMetrics arg1, android.content.res.Configuration arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.res.Resources.staticClass, global::android.content.res.Resources._Resources2340, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.res.Resources.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/res/Resources")); global::android.content.res.Resources._getBoolean2295 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getBoolean", "(I)Z"); global::android.content.res.Resources._getValue2296 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getValue", "(ILandroid/util/TypedValue;Z)V"); global::android.content.res.Resources._getValue2297 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getValue", "(Ljava/lang/String;Landroid/util/TypedValue;Z)V"); global::android.content.res.Resources._getInteger2298 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getInteger", "(I)I"); global::android.content.res.Resources._getString2299 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getString", "(I)Ljava/lang/String;"); global::android.content.res.Resources._getString2300 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getString", "(I[Ljava/lang/Object;)Ljava/lang/String;"); global::android.content.res.Resources._getIdentifier2301 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getIdentifier", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I"); global::android.content.res.Resources._getAssets2302 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getAssets", "()Landroid/content/res/AssetManager;"); global::android.content.res.Resources._getText2303 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getText", "(ILjava/lang/CharSequence;)Ljava/lang/CharSequence;"); global::android.content.res.Resources._getText2304 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getText", "(I)Ljava/lang/CharSequence;"); global::android.content.res.Resources._getSystem2305 = @__env.GetStaticMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getSystem", "()Landroid/content/res/Resources;"); global::android.content.res.Resources._getQuantityText2306 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getQuantityText", "(II)Ljava/lang/CharSequence;"); global::android.content.res.Resources._getQuantityString2307 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getQuantityString", "(II[Ljava/lang/Object;)Ljava/lang/String;"); global::android.content.res.Resources._getQuantityString2308 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getQuantityString", "(II)Ljava/lang/String;"); global::android.content.res.Resources._getTextArray2309 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getTextArray", "(I)[Ljava/lang/CharSequence;"); global::android.content.res.Resources._getStringArray2310 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getStringArray", "(I)[Ljava/lang/String;"); global::android.content.res.Resources._getIntArray2311 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getIntArray", "(I)[I"); global::android.content.res.Resources._obtainTypedArray2312 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "obtainTypedArray", "(I)Landroid/content/res/TypedArray;"); global::android.content.res.Resources._getDimension2313 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getDimension", "(I)F"); global::android.content.res.Resources._getDimensionPixelOffset2314 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getDimensionPixelOffset", "(I)I"); global::android.content.res.Resources._getDimensionPixelSize2315 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getDimensionPixelSize", "(I)I"); global::android.content.res.Resources._getFraction2316 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getFraction", "(III)F"); global::android.content.res.Resources._getDrawable2317 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getDrawable", "(I)Landroid/graphics/drawable/Drawable;"); global::android.content.res.Resources._getMovie2318 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getMovie", "(I)Landroid/graphics/Movie;"); global::android.content.res.Resources._getColor2319 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getColor", "(I)I"); global::android.content.res.Resources._getColorStateList2320 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getColorStateList", "(I)Landroid/content/res/ColorStateList;"); global::android.content.res.Resources._getLayout2321 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getLayout", "(I)Landroid/content/res/XmlResourceParser;"); global::android.content.res.Resources._getAnimation2322 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getAnimation", "(I)Landroid/content/res/XmlResourceParser;"); global::android.content.res.Resources._getXml2323 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getXml", "(I)Landroid/content/res/XmlResourceParser;"); global::android.content.res.Resources._openRawResource2324 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "openRawResource", "(ILandroid/util/TypedValue;)Ljava/io/InputStream;"); global::android.content.res.Resources._openRawResource2325 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "openRawResource", "(I)Ljava/io/InputStream;"); global::android.content.res.Resources._openRawResourceFd2326 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "openRawResourceFd", "(I)Landroid/content/res/AssetFileDescriptor;"); global::android.content.res.Resources._newTheme2327 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "newTheme", "()Landroid/content/res/Resources$Theme;"); global::android.content.res.Resources._obtainAttributes2328 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "obtainAttributes", "(Landroid/util/AttributeSet;[I)Landroid/content/res/TypedArray;"); global::android.content.res.Resources._updateConfiguration2329 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "updateConfiguration", "(Landroid/content/res/Configuration;Landroid/util/DisplayMetrics;)V"); global::android.content.res.Resources._getDisplayMetrics2330 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getDisplayMetrics", "()Landroid/util/DisplayMetrics;"); global::android.content.res.Resources._getConfiguration2331 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getConfiguration", "()Landroid/content/res/Configuration;"); global::android.content.res.Resources._getResourceName2332 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getResourceName", "(I)Ljava/lang/String;"); global::android.content.res.Resources._getResourcePackageName2333 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getResourcePackageName", "(I)Ljava/lang/String;"); global::android.content.res.Resources._getResourceTypeName2334 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getResourceTypeName", "(I)Ljava/lang/String;"); global::android.content.res.Resources._getResourceEntryName2335 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "getResourceEntryName", "(I)Ljava/lang/String;"); global::android.content.res.Resources._parseBundleExtras2336 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "parseBundleExtras", "(Landroid/content/res/XmlResourceParser;Landroid/os/Bundle;)V"); global::android.content.res.Resources._parseBundleExtra2337 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "parseBundleExtra", "(Ljava/lang/String;Landroid/util/AttributeSet;Landroid/os/Bundle;)V"); global::android.content.res.Resources._flushLayoutCache2338 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "flushLayoutCache", "()V"); global::android.content.res.Resources._finishPreloading2339 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "finishPreloading", "()V"); global::android.content.res.Resources._Resources2340 = @__env.GetMethodIDNoThrow(global::android.content.res.Resources.staticClass, "<init>", "(Landroid/content/res/AssetManager;Landroid/util/DisplayMetrics;Landroid/content/res/Configuration;)V"); } } }
#region License /* * WebSocketSessionManager.cs * * The MIT License * * Copyright (c) 2012-2013 sta.blockhead * * 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 System.Timers; namespace WebSocketSharp.Server { /// <summary> /// Manages the sessions to the Websocket service. /// </summary> public class WebSocketSessionManager { #region Private Fields private object _forSweep; private Logger _logger; private Dictionary<string, WebSocketService> _sessions; private volatile bool _stopped; private volatile bool _sweeping; private Timer _sweepTimer; private object _sync; #endregion #region Internal Constructors internal WebSocketSessionManager () : this (new Logger ()) { } internal WebSocketSessionManager (Logger logger) { _logger = logger; _forSweep = new object (); _sessions = new Dictionary<string, WebSocketService> (); _stopped = false; _sweeping = false; _sync = new object (); setSweepTimer (); startSweepTimer (); } #endregion #region Internal Properties internal IEnumerable<WebSocketService> ServiceInstances { get { lock (_sync) { return _sessions.Values.ToList (); } } } #endregion #region Public Properties /// <summary> /// Gets the collection of every ID of the active sessions to the Websocket service. /// </summary> /// <value> /// An IEnumerable&lt;string&gt; that contains the collection of every ID of the active sessions. /// </value> public IEnumerable<string> ActiveIDs { get { return from result in BroadpingInternally (new byte [] {}) where result.Value select result.Key; } } /// <summary> /// Gets the number of the sessions to the Websocket service. /// </summary> /// <value> /// An <see cref="int"/> that contains the number of the sessions. /// </value> public int Count { get { lock (_sync) { return _sessions.Count; } } } /// <summary> /// Gets the collection of every ID of the sessions to the Websocket service. /// </summary> /// <value> /// An IEnumerable&lt;string&gt; that contains the collection of every ID of the sessions. /// </value> public IEnumerable<string> IDs { get { lock (_sync) { return _sessions.Keys.ToList (); } } } /// <summary> /// Gets the collection of every ID of the inactive sessions to the Websocket service. /// </summary> /// <value> /// An IEnumerable&lt;string&gt; that contains the collection of every ID of the inactive sessions. /// </value> public IEnumerable<string> InactiveIDs { get { return from result in BroadpingInternally (new byte [] {}) where !result.Value select result.Key; } } /// <summary> /// Gets the session information with the specified <paramref name="id"/>. /// </summary> /// <value> /// A <see cref="IWebSocketSession"/> instance with <paramref name="id"/> if it is successfully found; /// otherwise, <see langword="null"/>. /// </value> /// <param name="id"> /// A <see cref="string"/> that contains a session ID to find. /// </param> public IWebSocketSession this [string id] { get { var msg = id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return null; } lock (_sync) { try { return _sessions [id]; } catch { _logger.Error ( "The WebSocket session with the specified ID not found.\nID: " + id); return null; } } } } /// <summary> /// Gets a value indicating whether the manager cleans up the inactive sessions periodically. /// </summary> /// <value> /// <c>true</c> if the manager cleans up the inactive sessions every 60 seconds; /// otherwise, <c>false</c>. /// </value> public bool KeepClean { get { return _sweepTimer.Enabled; } internal set { if (value) { if (!_stopped) startSweepTimer (); } else stopSweepTimer (); } } /// <summary> /// Gets the collection of the session informations to the Websocket service. /// </summary> /// <value> /// An IEnumerable&lt;IWebSocketSession&gt; that contains the collection of the session informations. /// </value> public IEnumerable<IWebSocketSession> Sessions { get { return from IWebSocketSession session in ServiceInstances select session; } } #endregion #region Private Methods private void broadcast (byte [] data) { foreach (var service in ServiceInstances) service.Send (data); } private void broadcast (string data) { foreach (var service in ServiceInstances) service.Send (data); } private void broadcastAsync (byte [] data) { var services = ServiceInstances.GetEnumerator (); Action completed = null; completed = () => { if (services.MoveNext ()) services.Current.SendAsync (data, completed); }; if (services.MoveNext ()) services.Current.SendAsync (data, completed); } private void broadcastAsync (string data) { var services = ServiceInstances.GetEnumerator (); Action completed = null; completed = () => { if (services.MoveNext ()) services.Current.SendAsync (data, completed); }; if (services.MoveNext ()) services.Current.SendAsync (data, completed); } private static string createID () { return Guid.NewGuid ().ToString ("N"); } private void setSweepTimer () { _sweepTimer = new Timer (60 * 1000); _sweepTimer.Elapsed += (sender, e) => { Sweep (); }; } private void startSweepTimer () { if (!_sweepTimer.Enabled) _sweepTimer.Start (); } private void stopSweepTimer () { if (_sweepTimer.Enabled) _sweepTimer.Stop (); } #endregion #region Internal Methods internal string Add (WebSocketService session) { lock (_sync) { if (_stopped) return null; var id = createID (); _sessions.Add (id, session); return id; } } internal void BroadcastInternally (byte [] data) { if (_stopped) broadcast (data); else broadcastAsync (data); } internal void BroadcastInternally (string data) { if (_stopped) broadcast (data); else broadcastAsync (data); } internal Dictionary<string, bool> BroadpingInternally (byte [] data) { var result = new Dictionary<string, bool> (); foreach (var session in ServiceInstances) result.Add (session.ID, session.Context.WebSocket.Ping (data)); return result; } internal bool Remove (string id) { lock (_sync) { return _sessions.Remove (id); } } internal void Stop () { stopSweepTimer (); lock (_sync) { if (_stopped) return; _stopped = true; foreach (var session in ServiceInstances) session.Context.WebSocket.Close (); } } internal void Stop (byte [] data) { stopSweepTimer (); lock (_sync) { if (_stopped) return; _stopped = true; foreach (var session in ServiceInstances) session.Context.WebSocket.Close (data); } } internal bool TryGetServiceInstance (string id, out WebSocketService service) { lock (_sync) { return _sessions.TryGetValue (id, out service); } } #endregion #region Public Methods /// <summary> /// Broadcasts the specified array of <see cref="byte"/> to all clients of the WebSocket service. /// </summary> /// <param name="data"> /// An array of <see cref="byte"/> to broadcast. /// </param> public void Broadcast (byte [] data) { var msg = data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } BroadcastInternally (data); } /// <summary> /// Broadcasts the specified <see cref="string"/> to all clients of the WebSocket service. /// </summary> /// <param name="data"> /// A <see cref="string"/> to broadcast. /// </param> public void Broadcast (string data) { var msg = data.CheckIfValidSendData (); if (msg != null) { _logger.Error (msg); return; } BroadcastInternally (data); } /// <summary> /// Sends Pings to all clients of the WebSocket service. /// </summary> /// <returns> /// A Dictionary&lt;string, bool&gt; that contains the collection of pairs of session ID and value /// indicating whether the WebSocket service received a Pong from each client in a time. /// </returns> public Dictionary<string, bool> Broadping () { return BroadpingInternally (new byte [] {}); } /// <summary> /// Sends Pings with the specified <paramref name="message"/> to all clients of the WebSocket service. /// </summary> /// <returns> /// A Dictionary&lt;string, bool&gt; that contains the collection of pairs of session ID and value /// indicating whether the WebSocket service received a Pong from each client in a time. /// </returns> /// <param name="message"> /// A <see cref="string"/> that contains a message to send. /// </param> public Dictionary<string, bool> Broadping (string message) { if (message == null || message.Length == 0) return BroadpingInternally (new byte [] {}); var data = Encoding.UTF8.GetBytes (message); var msg = data.CheckIfValidPingData (); if (msg != null) { _logger.Error (msg); return null; } return BroadpingInternally (data); } /// <summary> /// Closes the session with the specified <paramref name="id"/>. /// </summary> /// <param name="id"> /// A <see cref="string"/> that contains a session ID to find. /// </param> public void CloseSession (string id) { var msg = id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ( "The WebSocket session with the specified ID not found.\nID: " + id); return; } session.Context.WebSocket.Close (); } /// <summary> /// Closes the session with the specified <paramref name="code"/>, <paramref name="reason"/> /// and <paramref name="id"/>. /// </summary> /// <param name="code"> /// A <see cref="ushort"/> that contains a status code indicating the reason for closure. /// </param> /// <param name="reason"> /// A <see cref="string"/> that contains the reason for closure. /// </param> /// <param name="id"> /// A <see cref="string"/> that contains a session ID to find. /// </param> public void CloseSession (ushort code, string reason, string id) { var msg = id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ( "The WebSocket session with the specified ID not found.\nID: " + id); return; } session.Context.WebSocket.Close (code, reason); } /// <summary> /// Closes the session with the specified <paramref name="code"/>, <paramref name="reason"/> /// and <paramref name="id"/>. /// </summary> /// <param name="code"> /// A <see cref="CloseStatusCode"/> that contains a status code indicating the reason for closure. /// </param> /// <param name="reason"> /// A <see cref="string"/> that contains the reason for closure. /// </param> /// <param name="id"> /// A <see cref="string"/> that contains a session ID to find. /// </param> public void CloseSession (CloseStatusCode code, string reason, string id) { var msg = id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ( "The WebSocket session with the specified ID not found.\nID: " + id); return; } session.Context.WebSocket.Close (code, reason); } /// <summary> /// Sends a Ping to the client associated with the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the WebSocket service receives a Pong from the client in a time; /// otherwise, <c>false</c>. /// </returns> /// <param name="id"> /// A <see cref="string"/> that contains a session ID that represents the destination for the Ping. /// </param> public bool PingTo (string id) { var msg = id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return false; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ( "The WebSocket session with the specified ID not found.\nID: " + id); return false; } return session.Context.WebSocket.Ping (); } /// <summary> /// Sends a Ping with the specified <paramref name="message"/> to the client associated with /// the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the WebSocket service receives a Pong from the client in a time; /// otherwise, <c>false</c>. /// </returns> /// <param name="message"> /// A <see cref="string"/> that contains a message to send. /// </param> /// <param name="id"> /// A <see cref="string"/> that contains a session ID that represents the destination for the Ping. /// </param> public bool PingTo (string message, string id) { var msg = id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return false; } WebSocketService session; if (!TryGetServiceInstance (id, out session)) { _logger.Error ( "The WebSocket session with the specified ID not found.\nID: " + id); return false; } return session.Context.WebSocket.Ping (message); } /// <summary> /// Sends a binary <paramref name="data"/> to the client associated with the specified /// <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if <paramref name="data"/> is successfully sent; otherwise, <c>false</c>. /// </returns> /// <param name="data"> /// An array of <see cref="byte"/> that contains a binary data to send. /// </param> /// <param name="id"> /// A <see cref="string"/> that contains a session ID that represents the destination for the data. /// </param> public bool SendTo (byte [] data, string id) { var msg = id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return false; } WebSocketService service; if (!TryGetServiceInstance (id, out service)) { _logger.Error ( "The WebSocket session with the specified ID not found.\nID: " + id); return false; } service.Send (data); return true; } /// <summary> /// Sends a text <paramref name="data"/> to the client associated with the specified /// <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if <paramref name="data"/> is successfully sent; otherwise, <c>false</c>. /// </returns> /// <param name="data"> /// A <see cref="string"/> that contains a text data to send. /// </param> /// <param name="id"> /// A <see cref="string"/> that contains a session ID that represents the destination for the data. /// </param> public bool SendTo (string data, string id) { var msg = id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); return false; } WebSocketService service; if (!TryGetServiceInstance (id, out service)) { _logger.Error ( "The WebSocket session with the specified ID not found.\nID: " + id); return false; } service.Send (data); return true; } /// <summary> /// Cleans up the inactive sessions. /// </summary> public void Sweep () { if (_stopped || _sweeping || Count == 0) return; lock (_forSweep) { _sweeping = true; foreach (var id in InactiveIDs) { lock (_sync) { if (_stopped) break; WebSocketService service; if (_sessions.TryGetValue (id, out service)) { var state = service.State; if (state == WebSocketState.OPEN) service.Context.WebSocket.Close (CloseStatusCode.ABNORMAL); else if (state == WebSocketState.CLOSING) continue; else _sessions.Remove (id); } } } _sweeping = false; } } /// <summary> /// Tries to get the session information with the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the session information is successfully found; /// otherwise, <c>false</c>. /// </returns> /// <param name="id"> /// A <see cref="string"/> that contains a session ID to find. /// </param> /// <param name="session"> /// When this method returns, a <see cref="IWebSocketSession"/> instance that contains the session /// information if it is successfully found; otherwise, <see langword="null"/>. /// </param> public bool TryGetSession (string id, out IWebSocketSession session) { WebSocketService service; var result = TryGetServiceInstance (id, out service); session = service; return result; } #endregion } }
/*************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Collections.Generic; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.Project { public class OleServiceProvider : IOleServiceProvider, IDisposable { #region Public Types [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public delegate object ServiceCreatorCallback(Type serviceType); #endregion #region Private Types private class ServiceData : IDisposable { private Type serviceType; private object instance; private ServiceCreatorCallback creator; private bool shouldDispose; public ServiceData(Type serviceType, object instance, ServiceCreatorCallback callback, bool shouldDispose) { if(null == serviceType) { throw new ArgumentNullException("serviceType"); } if((null == instance) && (null == callback)) { throw new ArgumentNullException("instance"); } this.serviceType = serviceType; this.instance = instance; this.creator = callback; this.shouldDispose = shouldDispose; } public object ServiceInstance { get { if(null == instance) { instance = creator(serviceType); } return instance; } } public Guid Guid { get { return serviceType.GUID; } } public void Dispose() { if((shouldDispose) && (null != instance)) { IDisposable disp = instance as IDisposable; if(null != disp) { disp.Dispose(); } instance = null; } creator = null; GC.SuppressFinalize(this); } } #endregion #region fields private Dictionary<Guid, ServiceData> services = new Dictionary<Guid, ServiceData>(); private bool isDisposed; /// <summary> /// Defines an object that will be a mutex for this object for synchronizing thread calls. /// </summary> private static volatile object Mutex = new object(); #endregion #region ctors public OleServiceProvider() { } #endregion #region IOleServiceProvider Members public int QueryService(ref Guid guidService, ref Guid riid, out IntPtr ppvObject) { ppvObject = (IntPtr)0; int hr = VSConstants.S_OK; ServiceData serviceInstance = null; if(services != null && services.ContainsKey(guidService)) { serviceInstance = services[guidService]; } if(serviceInstance == null) { return VSConstants.E_NOINTERFACE; } // Now check to see if the user asked for an IID other than // IUnknown. If so, we must do another QI. // if(riid.Equals(NativeMethods.IID_IUnknown)) { ppvObject = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance); } else { IntPtr pUnk = IntPtr.Zero; try { pUnk = Marshal.GetIUnknownForObject(serviceInstance.ServiceInstance); hr = Marshal.QueryInterface(pUnk, ref riid, out ppvObject); } finally { if(pUnk != IntPtr.Zero) { Marshal.Release(pUnk); } } } return hr; } #endregion #region Dispose /// <summary> /// The IDispose interface Dispose method for disposing the object determinastically. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion /// <summary> /// Adds the given service to the service container. /// </summary> /// <param name="serviceType">The type of the service to add.</param> /// <param name="serviceInstance">An instance of the service.</param> /// <param name="shouldDisposeServiceInstance">true if the Dipose of the service provider is allowed to dispose the sevice instance.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The services created here will be disposed in the Dispose method of this type.")] public void AddService(Type serviceType, object serviceInstance, bool shouldDisposeServiceInstance) { // Create the description of this service. Note that we don't do any validation // of the parameter here because the constructor of ServiceData will do it for us. ServiceData service = new ServiceData(serviceType, serviceInstance, null, shouldDisposeServiceInstance); // Now add the service desctription to the dictionary. AddService(service); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification="The services created here will be disposed in the Dispose method of this type.")] public void AddService(Type serviceType, ServiceCreatorCallback callback, bool shouldDisposeServiceInstance) { // Create the description of this service. Note that we don't do any validation // of the parameter here because the constructor of ServiceData will do it for us. ServiceData service = new ServiceData(serviceType, null, callback, shouldDisposeServiceInstance); // Now add the service desctription to the dictionary. AddService(service); } private void AddService(ServiceData data) { // Make sure that the collection of services is created. if(null == services) { services = new Dictionary<Guid, ServiceData>(); } // Disallow the addition of duplicate services. if(services.ContainsKey(data.Guid)) { throw new InvalidOperationException(); } services.Add(data.Guid, data); } /// <devdoc> /// Removes the given service type from the service container. /// </devdoc> public void RemoveService(Type serviceType) { if(serviceType == null) { throw new ArgumentNullException("serviceType"); } if(services.ContainsKey(serviceType.GUID)) { services.Remove(serviceType.GUID); } } #region helper methods /// <summary> /// The method that does the cleanup. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { // Everybody can go here. if(!this.isDisposed) { // Synchronize calls to the Dispose simulteniously. lock(Mutex) { if(disposing) { // Remove all our services if(services != null) { foreach(ServiceData data in services.Values) { data.Dispose(); } services.Clear(); services = null; } } this.isDisposed = true; } } } #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; namespace WebApplication2 { /// <summary> /// Summary description for frmEmergencyProcedures. /// </summary> public partial class frmProfileServiceEvents : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; protected System.Web.UI.WebControls.Label Label2; public SqlConnection epsDbConn=new SqlConnection(strDB); protected void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here if (Session["startForm"].ToString() == "frmMainProfileMgr") { if (Session["ProfileType"] == "Consumer") { lblTitle.Text = "EcoSys: Individual/Household Characteristics"; btnAddE.Text = "Add Event"; lblProfilesName.Text = "Type of Characteristic: " + Session["ProfilesName"].ToString(); lblServiceName.Text = "Stage: " + Session["ServiceName"].ToString(); lblContent1.Text = "Listed below are various events related to the above stage." + " Review the list below to ensure that it includes all events for this stage." + " Use the 'Add Events' button to add to the list as needed."; DataGrid1.Columns[3].HeaderText = "Events"; DataGrid1.Columns[4].HeaderText = "Checklist Items"; } else { lblProfilesName.Text = "Business: " + Session["ProfilesName"].ToString(); lblServiceName.Text = "Service Delivered: " + Session["ServiceName"].ToString(); lblContent1.Text="Listed below are various deliverables for the above service." + " Review the list below to ensure that it includes all deliverables for this service. Use the 'Add Deliverable'" + " button to add to the list as needed."; } } Load_Procedures(); } #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.DataGrid1_ItemCommand); } #endregion private void Load_Procedures() { if (!IsPostBack) { loadData(); } } private void loadData () { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_RetrieveProfileSEvents"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@ProfileServicesId",SqlDbType.Int); cmd.Parameters["@ProfileServicesId"].Value=Session["ProfileServicesId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter(cmd); da.Fill(ds,"ProfileSProcs"); if (ds.Tables["ProfileSProcs"].Rows.Count == 0) { DataGrid1.Visible = false; lblContent1.Text = "There are no deliverables for the above service" + " that have been identified."; } else { Session["ds"] = ds; DataGrid1.DataSource = ds; DataGrid1.DataBind(); refreshGrid(); } } private void refreshGrid() { foreach (DataGridItem i in DataGrid1.Items) { Button bt = (Button) (i.Cells[4].FindControl ("btnUpdate")); Button btP = (Button) (i.Cells[4].FindControl ("btnProcs")); TextBox tb = (TextBox) (i.Cells[2].FindControl("txtSeq")); if (i.Cells[8].Text == "&nbsp;") { tb.Text="99"; } else tb.Text=i.Cells[8].Text; if (Session["OrgId"].ToString() == i.Cells[5].Text) { bt.Visible=true; } else { bt.Visible=false; i.Cells[5].Text = "Externally Mainained"; } if (Session["startForm"].ToString() == "frmMainProfileMgr") { if (Session["ProfileType"].ToString() == "Consumer") { btP.Text = "Services"; btP.CommandName = "Services"; bt.Text = "Other"; bt.CommandName = "Other"; } } } } private void updateGrid() { foreach (DataGridItem i in DataGrid1.Items) { TextBox tb = (TextBox) (i.Cells[2].FindControl("txtSeq")); { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="wms_UpdateProfileSESeqNo"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters ["@Id"].Value=i.Cells[0].Text; cmd.Parameters.Add("@Seq", SqlDbType.Int); if (tb.Text != "") { cmd.Parameters["@Seq"].Value = Int32.Parse(tb.Text); } else { cmd.Parameters["@Seq"].Value = 0; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } } protected void btnExit_Click(object sender, System.EventArgs e) { updateGrid(); Exit(); } private void Exit() { Response.Redirect (strURL + Session["CPSEvents"].ToString() + ".aspx?"); } private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { if (e.CommandName == "Procs") { Session["ProfileSEventsId"]=e.Item.Cells[0].Text; Session["EventsName"]=e.Item.Cells[3].Text; Session["CPSEProcs"]="frmProfileServiceEvents"; Response.Redirect (strURL + "frmProfileSEProcs.aspx?"); } else if (e.CommandName == "Update") { Session["CUpdEvent"]="frmProfileserviceEvents"; Response.Redirect (strURL + "frmUpdEvent.aspx?" + "&btnAction=" + "Update" + "&Id=" + e.Item.Cells[1].Text + "&Name=" + e.Item.Cells[3].Text + "&OrgId=" + e.Item.Cells[5].Text + "&Desc=" + e.Item.Cells[6].Text + "&Vis=" + e.Item.Cells[7].Text ); } else if (e.CommandName == "Clients") { Session["CPSEPC"] = "frmProfileserviceEvents"; Session["ProfileSEventsId"] = e.Item.Cells[0].Text; Session["EventsName"] = e.Item.Cells[3].Text; Response.Redirect(strURL + "frmPSEPClient.aspx?"); } else if (e.CommandName == "Remove") { SqlCommand cmd=new SqlCommand(); cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="eps_DeleteProfileServiceEvents"; cmd.Connection=this.epsDbConn; cmd.Parameters.Add ("@Id",SqlDbType.Int); cmd.Parameters["@Id"].Value=e.Item.Cells[0].Text; cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); loadData(); } else if (e.CommandName == "Services") { Session["CPSEResources"] = "frmProfileServiceEvents"; Session["PSEId"] = e.Item.Cells[0].Text; Session["RType"] = "0"; Response.Redirect(strURL + "frmPSEResources.aspx?"); } else if (e.CommandName == "Other") { Session["CPSEResources"] = "frmProfileServiceEvents"; Session["PSEId"] = e.Item.Cells[0].Text; Session["RType"] = "1"; Response.Redirect(strURL + "frmPSEResources.aspx?"); } } protected void btnAddS_Click(object sender, System.EventArgs e) { updateGrid(); Session["CSEvents"]="frmProfileServiceEvents"; Response.Redirect (strURL + "frmServiceEvents.aspx?"); } protected void btnAddP_Click(object sender, System.EventArgs e) { Session["CEventsAll"]="frmProfileserviceEvents"; Response.Redirect (strURL + "frmProfileModels.aspx?"); } } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * 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; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Xml; using System.Text; namespace Reporting.RdlDesign { /// <summary> /// Grouping specification: used for DataRegions (List, Chart, Table, Matrix), DataSets, group instances /// </summary> internal class GroupingCtl : System.Windows.Forms.UserControl, IProperty { private DesignXmlDraw _Draw; private XmlNode _GroupingParent; private DataTable _DataTable; // private DGCBColumn dgtbGE; private DataGridTextBoxColumn dgtbGE; private System.Windows.Forms.Button bDelete; private System.Windows.Forms.DataGridTableStyle dgTableStyle; private System.Windows.Forms.Button bUp; private System.Windows.Forms.Button bDown; private System.Windows.Forms.DataGrid dgGroup; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tbName; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox cbLabelExpr; private System.Windows.Forms.ComboBox cbParentExpr; private System.Windows.Forms.CheckBox chkPBS; private System.Windows.Forms.CheckBox chkPBE; private System.Windows.Forms.CheckBox chkRepeatHeader; private System.Windows.Forms.CheckBox chkGrpHeader; private System.Windows.Forms.CheckBox chkRepeatFooter; private System.Windows.Forms.CheckBox chkGrpFooter; private System.Windows.Forms.Label lParent; private System.Windows.Forms.Button bValueExpr; private System.Windows.Forms.Button bLabelExpr; private System.Windows.Forms.Button bParentExpr; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; internal GroupingCtl(DesignXmlDraw dxDraw, XmlNode groupingParent) { _Draw = dxDraw; _GroupingParent = groupingParent; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // Initialize form using the style node values InitValues(); } private void InitValues() { // Initialize the DataGrid columns // dgtbGE = new DGCBColumn(ComboBoxStyle.DropDown); dgtbGE = new DataGridTextBoxColumn(); this.dgTableStyle.GridColumnStyles.AddRange(new DataGridColumnStyle[] { this.dgtbGE}); // // dgtbGE // dgtbGE.HeaderText = "Expression"; dgtbGE.MappingName = "Expression"; dgtbGE.Width = 175; // Get the parent's dataset name // string dataSetName = _Draw.GetDataSetNameValue(_GroupingParent); // // string[] fields = _Draw.GetFields(dataSetName, true); // if (fields != null) // dgtbGE.CB.Items.AddRange(fields); // Initialize the DataTable _DataTable = new DataTable(); _DataTable.Columns.Add(new DataColumn("Expression", typeof(string))); string[] rowValues = new string[1]; XmlNode grouping = _Draw.GetNamedChildNode(_GroupingParent, "Grouping"); // Handle the group expressions XmlNode groupingExs = _Draw.GetNamedChildNode(grouping, "GroupExpressions"); if (groupingExs != null) foreach (XmlNode gNode in groupingExs.ChildNodes) { if (gNode.NodeType != XmlNodeType.Element || gNode.Name != "GroupExpression") continue; rowValues[0] = gNode.InnerText; _DataTable.Rows.Add(rowValues); } this.dgGroup.DataSource = _DataTable; DataGridTableStyle ts = dgGroup.TableStyles[0]; // ts.PreferredRowHeight = dgtbGE.CB.Height; ts.GridColumnStyles[0].Width = 330; // if (grouping == null) { this.tbName.Text = ""; this.cbParentExpr.Text = ""; this.cbLabelExpr.Text = ""; } else { this.chkPBE.Checked = _Draw.GetElementValue(grouping, "PageBreakAtEnd", "false").ToLower() == "true"; this.chkPBS.Checked = _Draw.GetElementValue(grouping, "PageBreakAtStart", "false").ToLower() == "true"; this.tbName.Text = _Draw.GetElementAttribute(grouping, "Name", ""); this.cbParentExpr.Text = _Draw.GetElementValue(grouping, "Parent", ""); this.cbLabelExpr.Text = _Draw.GetElementValue(grouping, "Label", ""); } if (_GroupingParent.Name == "TableGroup") { XmlNode repeat; repeat = DesignXmlDraw.FindNextInHierarchy(_GroupingParent, "Header", "RepeatOnNewPage"); if (repeat != null) this.chkRepeatHeader.Checked = repeat.InnerText.ToLower() == "true"; repeat = DesignXmlDraw.FindNextInHierarchy(_GroupingParent, "Footer", "RepeatOnNewPage"); if (repeat != null) this.chkRepeatFooter.Checked = repeat.InnerText.ToLower() == "true"; this.chkGrpHeader.Checked = _Draw.GetNamedChildNode(_GroupingParent, "Header") != null; this.chkGrpFooter.Checked = _Draw.GetNamedChildNode(_GroupingParent, "Footer") != null; } else { this.chkRepeatFooter.Visible = false; this.chkRepeatHeader.Visible = false; this.chkGrpFooter.Visible = false; this.chkGrpHeader.Visible = false; } if (_GroupingParent.Name == "DynamicColumns" || _GroupingParent.Name == "DynamicRows") { this.chkPBE.Visible = this.chkPBS.Visible = false; } else if (_GroupingParent.Name == "DynamicSeries" || _GroupingParent.Name == "DynamicCategories") { this.chkPBE.Visible = this.chkPBS.Visible = false; this.cbParentExpr.Visible = this.lParent.Visible = false; this.cbLabelExpr.Text = _Draw.GetElementValue(_GroupingParent, "Label", ""); } // load label and parent controls with fields string dsn = _Draw.GetDataSetNameValue(_GroupingParent); if (dsn != null) // found it { string[] f = _Draw.GetFields(dsn, true); if (f != null) { this.cbParentExpr.Items.AddRange(f); this.cbLabelExpr.Items.AddRange(f); } } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dgGroup = new System.Windows.Forms.DataGrid(); this.dgTableStyle = new System.Windows.Forms.DataGridTableStyle(); this.bDelete = new System.Windows.Forms.Button(); this.bUp = new System.Windows.Forms.Button(); this.bDown = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.tbName = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.cbLabelExpr = new System.Windows.Forms.ComboBox(); this.cbParentExpr = new System.Windows.Forms.ComboBox(); this.lParent = new System.Windows.Forms.Label(); this.chkPBS = new System.Windows.Forms.CheckBox(); this.chkPBE = new System.Windows.Forms.CheckBox(); this.chkRepeatHeader = new System.Windows.Forms.CheckBox(); this.chkGrpHeader = new System.Windows.Forms.CheckBox(); this.chkRepeatFooter = new System.Windows.Forms.CheckBox(); this.chkGrpFooter = new System.Windows.Forms.CheckBox(); this.bValueExpr = new System.Windows.Forms.Button(); this.bLabelExpr = new System.Windows.Forms.Button(); this.bParentExpr = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.dgGroup)).BeginInit(); this.SuspendLayout(); // // dgGroup // this.dgGroup.CaptionVisible = false; this.dgGroup.DataMember = ""; this.dgGroup.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgGroup.Location = new System.Drawing.Point(8, 48); this.dgGroup.Name = "dgGroup"; this.dgGroup.Size = new System.Drawing.Size(376, 88); this.dgGroup.TabIndex = 1; this.dgGroup.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.dgTableStyle}); // // dgTableStyle // this.dgTableStyle.AllowSorting = false; this.dgTableStyle.DataGrid = this.dgGroup; this.dgTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; // // bDelete // this.bDelete.Location = new System.Drawing.Point(392, 69); this.bDelete.Name = "bDelete"; this.bDelete.Size = new System.Drawing.Size(48, 20); this.bDelete.TabIndex = 2; this.bDelete.Text = "Delete"; this.bDelete.Click += new System.EventHandler(this.bDelete_Click); // // bUp // this.bUp.Location = new System.Drawing.Point(392, 94); this.bUp.Name = "bUp"; this.bUp.Size = new System.Drawing.Size(48, 20); this.bUp.TabIndex = 3; this.bUp.Text = "Up"; this.bUp.Click += new System.EventHandler(this.bUp_Click); // // bDown // this.bDown.Location = new System.Drawing.Point(392, 119); this.bDown.Name = "bDown"; this.bDown.Size = new System.Drawing.Size(48, 20); this.bDown.TabIndex = 4; this.bDown.Text = "Down"; this.bDown.Click += new System.EventHandler(this.bDown_Click); // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(48, 23); this.label1.TabIndex = 5; this.label1.Text = "Name"; // // tbName // this.tbName.Location = new System.Drawing.Point(56, 8); this.tbName.Name = "tbName"; this.tbName.Size = new System.Drawing.Size(328, 20); this.tbName.TabIndex = 0; this.tbName.Text = "textBox1"; this.tbName.Validating += new System.ComponentModel.CancelEventHandler(this.tbName_Validating); // // label2 // this.label2.Location = new System.Drawing.Point(8, 144); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(40, 23); this.label2.TabIndex = 7; this.label2.Text = "Label"; // // label3 // this.label3.Location = new System.Drawing.Point(8, 32); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(56, 16); this.label3.TabIndex = 9; this.label3.Text = "Group By"; // // cbLabelExpr // this.cbLabelExpr.Location = new System.Drawing.Point(48, 144); this.cbLabelExpr.Name = "cbLabelExpr"; this.cbLabelExpr.Size = new System.Drawing.Size(336, 21); this.cbLabelExpr.TabIndex = 5; this.cbLabelExpr.Text = "comboBox1"; // // cbParentExpr // this.cbParentExpr.Location = new System.Drawing.Point(48, 176); this.cbParentExpr.Name = "cbParentExpr"; this.cbParentExpr.Size = new System.Drawing.Size(336, 21); this.cbParentExpr.TabIndex = 6; this.cbParentExpr.Text = "comboBox1"; // // lParent // this.lParent.Location = new System.Drawing.Point(8, 176); this.lParent.Name = "lParent"; this.lParent.Size = new System.Drawing.Size(40, 23); this.lParent.TabIndex = 11; this.lParent.Text = "Parent"; // // chkPBS // this.chkPBS.Location = new System.Drawing.Point(8, 208); this.chkPBS.Name = "chkPBS"; this.chkPBS.Size = new System.Drawing.Size(136, 24); this.chkPBS.TabIndex = 7; this.chkPBS.Text = "Page Break at Start"; // // chkPBE // this.chkPBE.Location = new System.Drawing.Point(232, 208); this.chkPBE.Name = "chkPBE"; this.chkPBE.Size = new System.Drawing.Size(136, 24); this.chkPBE.TabIndex = 8; this.chkPBE.Text = "Page Break at End"; // // chkRepeatHeader // this.chkRepeatHeader.Location = new System.Drawing.Point(232, 232); this.chkRepeatHeader.Name = "chkRepeatHeader"; this.chkRepeatHeader.Size = new System.Drawing.Size(136, 24); this.chkRepeatHeader.TabIndex = 13; this.chkRepeatHeader.Text = "Repeat group header"; // // chkGrpHeader // this.chkGrpHeader.Location = new System.Drawing.Point(8, 232); this.chkGrpHeader.Name = "chkGrpHeader"; this.chkGrpHeader.Size = new System.Drawing.Size(136, 24); this.chkGrpHeader.TabIndex = 12; this.chkGrpHeader.Text = "Include group header"; // // chkRepeatFooter // this.chkRepeatFooter.Location = new System.Drawing.Point(232, 256); this.chkRepeatFooter.Name = "chkRepeatFooter"; this.chkRepeatFooter.Size = new System.Drawing.Size(136, 24); this.chkRepeatFooter.TabIndex = 15; this.chkRepeatFooter.Text = "Repeat group footer"; // // chkGrpFooter // this.chkGrpFooter.Location = new System.Drawing.Point(8, 256); this.chkGrpFooter.Name = "chkGrpFooter"; this.chkGrpFooter.Size = new System.Drawing.Size(136, 24); this.chkGrpFooter.TabIndex = 14; this.chkGrpFooter.Text = "Include group footer"; // // bValueExpr // this.bValueExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bValueExpr.Location = new System.Drawing.Point(392, 48); this.bValueExpr.Name = "bValueExpr"; this.bValueExpr.Size = new System.Drawing.Size(24, 21); this.bValueExpr.TabIndex = 16; this.bValueExpr.Tag = "value"; this.bValueExpr.Text = "fx"; this.bValueExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bValueExpr.Click += new System.EventHandler(this.bValueExpr_Click); // // bLabelExpr // this.bLabelExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bLabelExpr.Location = new System.Drawing.Point(392, 144); this.bLabelExpr.Name = "bLabelExpr"; this.bLabelExpr.Size = new System.Drawing.Size(24, 21); this.bLabelExpr.TabIndex = 17; this.bLabelExpr.Tag = "label"; this.bLabelExpr.Text = "fx"; this.bLabelExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bLabelExpr.Click += new System.EventHandler(this.bExpr_Click); // // bParentExpr // this.bParentExpr.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bParentExpr.Location = new System.Drawing.Point(392, 176); this.bParentExpr.Name = "bParentExpr"; this.bParentExpr.Size = new System.Drawing.Size(24, 21); this.bParentExpr.TabIndex = 18; this.bParentExpr.Tag = "parent"; this.bParentExpr.Text = "fx"; this.bParentExpr.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.bParentExpr.Click += new System.EventHandler(this.bExpr_Click); // // GroupingCtl // this.Controls.Add(this.bParentExpr); this.Controls.Add(this.bLabelExpr); this.Controls.Add(this.bValueExpr); this.Controls.Add(this.chkRepeatFooter); this.Controls.Add(this.chkGrpFooter); this.Controls.Add(this.chkRepeatHeader); this.Controls.Add(this.chkGrpHeader); this.Controls.Add(this.chkPBE); this.Controls.Add(this.chkPBS); this.Controls.Add(this.cbParentExpr); this.Controls.Add(this.lParent); this.Controls.Add(this.cbLabelExpr); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.tbName); this.Controls.Add(this.label1); this.Controls.Add(this.bDown); this.Controls.Add(this.bUp); this.Controls.Add(this.bDelete); this.Controls.Add(this.dgGroup); this.Name = "GroupingCtl"; this.Size = new System.Drawing.Size(488, 304); ((System.ComponentModel.ISupportInitialize)(this.dgGroup)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion public bool IsValid() { // Check to see if we have an expression bool bRows=HasRows(); // If no rows and no data if (!bRows && this.tbName.Text.Trim().Length == 0) { if (_GroupingParent.Name == "Details" || _GroupingParent.Name == "List") return true; MessageBox.Show("Group must be defined.", "Grouping"); return false; } // Grouping must have name XmlNode grouping = _Draw.GetNamedChildNode(_GroupingParent, "Grouping"); string nerr = _Draw.GroupingNameCheck(grouping, this.tbName.Text); if (nerr != null) { MessageBox.Show(nerr, "Group Name in Error"); return false; } if (!bRows) { MessageBox.Show("No expressions have been defined for the group.", "Group"); return false; } if (_GroupingParent.Name != "DynamicSeries") return true; // DynamicSeries grouping must have a label for the legend if (this.cbLabelExpr.Text.Length > 0) return true; MessageBox.Show("Chart series must have label defined for the legend.", "Chart"); return false; } private bool HasRows() { bool bRows=false; foreach (DataRow dr in _DataTable.Rows) { if (dr[0] == DBNull.Value) continue; string ge = (string) dr[0]; if (ge.Length <= 0) continue; bRows = true; break; } return bRows; } public void Apply() { if (!HasRows()) // No expressions in grouping; get rid of grouping { _Draw.RemoveElement(_GroupingParent, "Grouping"); // can't have a grouping return; } // Get the group XmlNode grouping = _Draw.GetCreateNamedChildNode(_GroupingParent, "Grouping"); _Draw.SetGroupName(grouping, tbName.Text.Trim()); // Handle the label if (_GroupingParent.Name == "DynamicSeries" || _GroupingParent.Name == "DynamicCategories") { if (this.cbLabelExpr.Text.Length > 0) _Draw.SetElement(_GroupingParent, "Label", cbLabelExpr.Text); else _Draw.RemoveElement(_GroupingParent, "Label"); } else { if (this.cbLabelExpr.Text.Length > 0) _Draw.SetElement(grouping, "Label", cbLabelExpr.Text); else _Draw.RemoveElement(grouping, "Label"); _Draw.SetElement(grouping, "PageBreakAtStart", this.chkPBS.Checked? "true": "false"); _Draw.SetElement(grouping, "PageBreakAtEnd", this.chkPBE.Checked? "true": "false"); if (cbParentExpr.Text.Length > 0) _Draw.SetElement(grouping, "Parent", cbParentExpr.Text); else _Draw.RemoveElement(grouping, "Parent"); } // Loop thru and add all the group expressions XmlNode grpExprs = _Draw.GetCreateNamedChildNode(grouping, "GroupExpressions"); grpExprs.RemoveAll(); string firstexpr=null; foreach (DataRow dr in _DataTable.Rows) { if (dr[0] == DBNull.Value) continue; string ge = (string) dr[0]; if (ge.Length <= 0) continue; _Draw.CreateElement(grpExprs, "GroupExpression", ge); if (firstexpr == null) firstexpr = ge; } if (!grpExprs.HasChildNodes) { // With no group expressions there are no groups grouping.RemoveChild(grpExprs); grouping.ParentNode.RemoveChild(grouping); grouping = null; } if (_GroupingParent.Name == "TableGroup" && grouping != null) { if (this.chkGrpHeader.Checked) { XmlNode header = _Draw.GetCreateNamedChildNode(_GroupingParent, "Header"); _Draw.SetElement(header, "RepeatOnNewPage", chkRepeatHeader.Checked? "true": "false"); XmlNode tblRows = _Draw.GetCreateNamedChildNode(header, "TableRows"); if (!tblRows.HasChildNodes) { // We need to create a row _Draw.InsertTableRow(tblRows); } } else { _Draw.RemoveElement(_GroupingParent, "Header"); } if (this.chkGrpFooter.Checked) { XmlNode footer = _Draw.GetCreateNamedChildNode(_GroupingParent, "Footer"); _Draw.SetElement(footer, "RepeatOnNewPage", chkRepeatFooter.Checked? "true": "false"); XmlNode tblRows = _Draw.GetCreateNamedChildNode(footer, "TableRows"); if (!tblRows.HasChildNodes) { // We need to create a row _Draw.InsertTableRow(tblRows); } } else { _Draw.RemoveElement(_GroupingParent, "Footer"); } } else if (_GroupingParent.Name == "DynamicColumns" || _GroupingParent.Name == "DynamicRows") { XmlNode ritems = _Draw.GetNamedChildNode(_GroupingParent, "ReportItems"); if (ritems == null) ritems = _Draw.GetCreateNamedChildNode(_GroupingParent, "ReportItems"); XmlNode item = ritems.FirstChild; if (item == null) { item = _Draw.GetCreateNamedChildNode(ritems, "Textbox"); XmlNode vnode = _Draw.GetCreateNamedChildNode(item, "Value"); vnode.InnerText = firstexpr == null? "": firstexpr; } } } private void bDelete_Click(object sender, System.EventArgs e) { int cr = dgGroup.CurrentRowIndex; if (cr < 0) // already at the top return; else if (cr == 0) { DataRow dr = _DataTable.Rows[0]; dr[0] = null; } this._DataTable.Rows.RemoveAt(cr); } private void bUp_Click(object sender, System.EventArgs e) { int cr = dgGroup.CurrentRowIndex; if (cr <= 0) // already at the top return; SwapRow(_DataTable.Rows[cr-1], _DataTable.Rows[cr]); dgGroup.CurrentRowIndex = cr-1; } private void bDown_Click(object sender, System.EventArgs e) { int cr = dgGroup.CurrentRowIndex; if (cr < 0) // invalid index return; if (cr + 1 >= _DataTable.Rows.Count) return; // already at end SwapRow(_DataTable.Rows[cr+1], _DataTable.Rows[cr]); dgGroup.CurrentRowIndex = cr+1; } private void SwapRow(DataRow tdr, DataRow fdr) { // column 1 object save = tdr[0]; tdr[0] = fdr[0]; fdr[0] = save; // column 2 save = tdr[1]; tdr[1] = fdr[1]; fdr[1] = save; // column 3 save = tdr[2]; tdr[2] = fdr[2]; fdr[2] = save; return; } private void tbName_Validating(object sender, System.ComponentModel.CancelEventArgs e) { bool bRows=HasRows(); // If no rows and no data in name it's ok if (!bRows && this.tbName.Text.Trim().Length == 0) return; if (!ReportNames.IsNameValid(tbName.Text)) { e.Cancel = true; MessageBox.Show(string.Format("{0} is an invalid name.", tbName.Text), "Name"); } } private void bValueExpr_Click(object sender, System.EventArgs e) { int cr = dgGroup.CurrentRowIndex; if (cr < 0) { // No rows yet; create one string[] rowValues = new string[1]; rowValues[0] = null; _DataTable.Rows.Add(rowValues); cr = 0; } DataGridCell dgc = dgGroup.CurrentCell; int cc = dgc.ColumnNumber; DataRow dr = _DataTable.Rows[cr]; string cv = dr[cc] as string; DialogExprEditor ee = new DialogExprEditor(_Draw, cv, _GroupingParent, false); try { DialogResult dlgr = ee.ShowDialog(); if (dlgr == DialogResult.OK) dr[cc] = ee.Expression; } finally { ee.Dispose(); } } private void bExpr_Click(object sender, System.EventArgs e) { Button b = sender as Button; if (b == null) return; Control c = null; switch (b.Tag as string) { case "label": c = this.cbLabelExpr; break; case "parent": c = this.cbParentExpr; break; } if (c == null) return; DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, _GroupingParent, false); try { DialogResult dr = ee.ShowDialog(); if (dr == DialogResult.OK) c.Text = ee.Expression; } finally { ee.Dispose(); } return; } } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. using System; using SoomlaWpCore; using SoomlaWpStore.data; using SoomlaWpCore.util; using SoomlaWpStore.exceptions; using SoomlaWpStore.purchasesTypes; /** * An upgrade virtual good is one VG in a series of VGs that define an upgrade scale of an * associated <code>VirtualGood</code>. * * This type of virtual good is best explained with an example: * Let's say there's a strength attribute to one of the characters in your game and that strength is * on a scale of 1-5. You want to provide your users with the ability to upgrade that strength. * * This is what you'll need to create: * 1. <code>SingleUseVG</code> for 'strength' * 2. <code>UpgradeVG</code> for strength 'level 1' * 3. <code>UpgradeVG</code> for strength 'level 2' * 4. <code>UpgradeVG</code> for strength 'level 3' * 5. <code>UpgradeVG</code> for strength 'level 4' * 6. <code>UpgradeVG</code> for strength 'level 5' * * When the user buys this <code>UpgradeVG</code>, we check and make sure the appropriate conditions * are met and buy it for you (which actually means we upgrade the associated VirtualGood). * * NOTE: In case you want this item to be available for purchase with real money * you will need to define the item in the market (Google Play, Amazon App Store, etc...). * * Inheritance: UpgradeVG > * {@link com.soomla.store.domain.virtualGoods.VirtualGood} > * {@link com.soomla.store.domain.PurchasableVirtualItem} > * {@link com.soomla.store.domain.VirtualItem} */ namespace SoomlaWpStore.domain.virtualGoods { public class UpgradeVG : LifetimeVG { /** Constructor * * @param goodItemId the itemId of the <code>VirtualGood</code> associated with this upgrade. * @param prevItemId the itemId of the <code>UpgradeVG</code> before, or if this is the first * <code>UpgradeVG</code> in the scale then the value is null. * @param nextItemId the itemId of the <code>UpgradeVG</code> after, or if this is the last * <code>UpgradeVG</code> in the scale then the value is null. * @param mName see parent * @param mDescription see parent * @param mItemId see parent * @param purchaseType see parent */ public UpgradeVG(String goodItemId, String prevItemId, String nextItemId, String mName, String mDescription, String mItemId, PurchaseType purchaseType) : base(mName, mDescription, mItemId, purchaseType) { mGoodItemId = goodItemId; mPrevItemId = prevItemId; mNextItemId = nextItemId; } /** * Constructor * * @param jsonObject see parent * @throws JSONException */ public UpgradeVG(JSONObject jsonObject) : base(jsonObject) { mGoodItemId = jsonObject[StoreJSONConsts.VGU_GOOD_ITEMID].str; mPrevItemId = jsonObject[StoreJSONConsts.VGU_PREV_ITEMID].str; mNextItemId = jsonObject[StoreJSONConsts.VGU_NEXT_ITEMID].str; } /** * @{inheritDoc} */ public override JSONObject toJSONObject(){ JSONObject jsonObject = base.toJSONObject(); try { jsonObject.AddField(StoreJSONConsts.VGU_GOOD_ITEMID, mGoodItemId); jsonObject.AddField(StoreJSONConsts.VGU_PREV_ITEMID, String.IsNullOrEmpty(mPrevItemId) ? "" : mPrevItemId); jsonObject.AddField(StoreJSONConsts.VGU_NEXT_ITEMID, String.IsNullOrEmpty(mNextItemId) ? "" : mNextItemId); } catch (Exception e) { SoomlaUtils.LogError(TAG, "An error occurred while generating JSON object." + " " + e.Message); } return jsonObject; } /** * Assigns the current upgrade to the associated <code>VirtualGood</code> (mGood). * * NOTE: This action doesn't check anything! It just assigns the current UpgradeVG to the * associated mGood. * * @param amount is NOT USED HERE! * @return 1 if the user was given the good, 0 otherwise */ public override int give(int amount, bool notify) { SoomlaUtils.LogDebug(TAG, "Assigning " + getName() + " to: " + mGoodItemId); VirtualGood good = null; try { good = (VirtualGood)StoreInfo.getVirtualItem(mGoodItemId); } catch (VirtualItemNotFoundException e) { SoomlaUtils.LogError(TAG, "VirtualGood with itemId: " + mGoodItemId + " doesn't exist! Can't upgrade. " + e.Message); return 0; } StorageManager.getVirtualGoodsStorage().assignCurrentUpgrade(good, this, notify); return base.give(amount, notify); } /** * Takes upgrade from the user, or in other words DOWNGRADES the associated * <code>VirtualGood</code> (mGood). * Checks if the current Upgrade is really associated with the <code>VirtualGood</code> and: * * if YES - downgrades to the previous upgrade (or remove upgrades in case of null). * if NO - returns 0 (does nothing). * * @param amount is NOT USED HERE! * @param notify see parent * @return see parent */ public override int take(int amount, bool notify) { VirtualGood good = null; try { good = (VirtualGood)StoreInfo.getVirtualItem(mGoodItemId); } catch (VirtualItemNotFoundException e) { SoomlaUtils.LogError(TAG, "VirtualGood with itemId: " + mGoodItemId + " doesn't exist! Can't downgrade."+" "+e.Message); return 0; } UpgradeVG upgradeVG = StorageManager.getVirtualGoodsStorage().getCurrentUpgrade(good); // Case: Upgrade is not assigned to this Virtual Good if (upgradeVG != this) { SoomlaUtils.LogError(TAG, "You can't take an upgrade that's not currently assigned." + "The UpgradeVG " + getName() + " is not assigned to " + "the VirtualGood: " + good.getName()); return 0; } if (!String.IsNullOrEmpty(mPrevItemId)) { UpgradeVG prevUpgradeVG = null; // Case: downgrade is not possible because previous upgrade does not exist try { prevUpgradeVG = (UpgradeVG)StoreInfo.getVirtualItem(mPrevItemId); } catch (VirtualItemNotFoundException e) { SoomlaUtils.LogError(TAG, "Previous UpgradeVG with itemId: " + mPrevItemId + " doesn't exist! Can't downgrade." + " " + e.Message); return 0; } // Case: downgrade is successful! SoomlaUtils.LogDebug(TAG, "Downgrading " + good.getName() + " to: " + prevUpgradeVG.getName()); StorageManager.getVirtualGoodsStorage().assignCurrentUpgrade(good, prevUpgradeVG, notify); } // Case: first Upgrade in the series - so we downgrade to NO upgrade. else { SoomlaUtils.LogDebug(TAG, "Downgrading " + good.getName() + " to NO-UPGRADE"); StorageManager.getVirtualGoodsStorage().removeUpgrades(good, notify); } return base.take(amount, notify); } /** * Determines if the user is in a state that allows him/her to buy an <code>UpgradeVG</code> * This method enforces allowing/rejecting of upgrades here so users won't buy them when * they are not supposed to. * If you want to give your users free upgrades, use the <code>give</code> function. * * @return true if can buy, false otherwise */ protected override bool CanBuy() { VirtualGood good = null; try { good = (VirtualGood)StoreInfo.getVirtualItem(mGoodItemId); } catch (VirtualItemNotFoundException e) { SoomlaUtils.LogError(TAG, "VirtualGood with itemId: " + mGoodItemId + " doesn't exist! Returning NO (can't buy)." + " " + e.Message); return false; } UpgradeVG upgradeVG = StorageManager.getVirtualGoodsStorage().getCurrentUpgrade(good); return ((upgradeVG == null && String.IsNullOrEmpty(mPrevItemId)) || (upgradeVG != null && ((upgradeVG.getNextItemId() == getItemId()) || (upgradeVG.getPrevItemId() == getItemId())))) && base.CanBuy(); } /** Setters and Getters **/ public String getGoodItemId() { return mGoodItemId; } public String getPrevItemId() { return mPrevItemId; } public String getNextItemId() { return mNextItemId; } /** Private Members **/ private const String TAG = "SOOMLA UpgradeVG"; //used for Log messages private String mGoodItemId; //the itemId of the VirtualGood associated with this upgrade /** * The itemId of the UpgradeVG before, or if this is the first UpgradeVG in the scale then * the value is null. */ private String mPrevItemId; /** * The itemId of the UpgradeVG after, or if this is the last UpgradeVG in the scale then * the value is null. */ private String mNextItemId; } }
// 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.Diagnostics.Contracts; namespace System.Globalization { //////////////////////////////////////////////////////////////////////////// // // Rules for the Hebrew calendar: // - The Hebrew calendar is both a Lunar (months) and Solar (years) // calendar, but allows for a week of seven days. // - Days begin at sunset. // - Leap Years occur in the 3, 6, 8, 11, 14, 17, & 19th years of a // 19-year cycle. Year = leap iff ((7y+1) mod 19 < 7). // - There are 12 months in a common year and 13 months in a leap year. // - In a common year, the 6th month, Adar, has 29 days. In a leap // year, the 6th month, Adar I, has 30 days and the leap month, // Adar II, has 29 days. // - Common years have 353-355 days. Leap years have 383-385 days. // - The Hebrew new year (Rosh HaShanah) begins on the 1st of Tishri, // the 7th month in the list below. // - The new year may not begin on Sunday, Wednesday, or Friday. // - If the new year would fall on a Tuesday and the conjunction of // the following year were at midday or later, the new year is // delayed until Thursday. // - If the new year would fall on a Monday after a leap year, the // new year is delayed until Tuesday. // - The length of the 8th and 9th months vary from year to year, // depending on the overall length of the year. // - The length of a year is determined by the dates of the new // years (Tishri 1) preceding and following the year in question. // - The 2th month is long (30 days) if the year has 355 or 385 days. // - The 3th month is short (29 days) if the year has 353 or 383 days. // - The Hebrew months are: // 1. Tishri (30 days) // 2. Heshvan (29 or 30 days) // 3. Kislev (29 or 30 days) // 4. Teveth (29 days) // 5. Shevat (30 days) // 6. Adar I (30 days) // 7. Adar {II} (29 days, this only exists if that year is a leap year) // 8. Nisan (30 days) // 9. Iyyar (29 days) // 10. Sivan (30 days) // 11. Tammuz (29 days) // 12. Av (30 days) // 13. Elul (29 days) // //////////////////////////////////////////////////////////////////////////// /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1583/01/01 2239/09/29 ** Hebrew 5343/04/07 5999/13/29 */ // Includes CHebrew implemetation;i.e All the code necessary for converting // Gregorian to Hebrew Lunar from 1583 to 2239. [Serializable] public class HebrewCalendar : Calendar { public static readonly int HebrewEra = 1; internal const int DatePartYear = 0; internal const int DatePartDayOfYear = 1; internal const int DatePartMonth = 2; internal const int DatePartDay = 3; internal const int DatePartDayOfWeek = 4; // // Hebrew Translation Table. // // This table is used to get the following Hebrew calendar information for a // given Gregorian year: // 1. The day of the Hebrew month corresponding to Gregorian January 1st // for a given Gregorian year. // 2. The month of the Hebrew month corresponding to Gregorian January 1st // for a given Gregorian year. // The information is not directly in the table. Instead, the info is decoded // by special values (numbers above 29 and below 1). // 3. The type of the Hebrew year for a given Gregorian year. // /* More notes: This table includes 2 numbers for each year. The offset into the table determines the year. (offset 0 is Gregorian year 1500) 1st number determines the day of the Hebrew month coresponeds to January 1st. 2nd number determines the type of the Hebrew year. (the type determines how many days are there in the year.) normal years : 1 = 353 days 2 = 354 days 3 = 355 days. Leap years : 4 = 383 5 384 6 = 385 days. A 99 means the year is not supported for translation. for convenience the table was defined for 750 year, but only 640 years are supported. (from 1583 to 2239) the years before 1582 (starting of Georgian calander) and after 2239, are filled with 99. Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days. That's why, there no nead to specify the lunar month in the table. There are exceptions, these are coded by giving numbers above 29 and below 1. Actual decoding is takenig place whenever fetching information from the table. The function for decoding is in GetLunarMonthDay(). Example: The data for 2000 - 2005 A.D. is: 23,6,6,1,17,2,27,6,7,3, // 2000 - 2004 For year 2000, we know it has a Hebrew year type 6, which means it has 385 days. And 1/1/2000 A.D. is Hebrew year 5760, 23rd day of 4th month. */ // // Jewish Era in use today is dated from the supposed year of the // Creation with its beginning in 3761 B.C. // // The Hebrew year of Gregorian 1st year AD. // 0001/01/01 AD is Hebrew 3760/01/01 private const int HebrewYearOf1AD = 3760; // The first Gregorian year in HebrewTable. private const int FirstGregorianTableYear = 1583; // == Hebrew Year 5343 // The last Gregorian year in HebrewTable. private const int LastGregorianTableYear = 2239; // == Hebrew Year 5999 private const int TABLESIZE = (LastGregorianTableYear - FirstGregorianTableYear); private const int MinHebrewYear = HebrewYearOf1AD + FirstGregorianTableYear; // == 5343 private const int MaxHebrewYear = HebrewYearOf1AD + LastGregorianTableYear; // == 5999 private static readonly byte[] s_hebrewTable = { 7,3,17,3, // 1583-1584 (Hebrew year: 5343 - 5344) 0,4,11,2,21,6,1,3,13,2, // 1585-1589 25,4,5,3,16,2,27,6,9,1, // 1590-1594 20,2,0,6,11,3,23,4,4,2, // 1595-1599 14,3,27,4,8,2,18,3,28,6, // 1600 11,1,22,5,2,3,12,3,25,4, // 1605 6,2,16,3,26,6,8,2,20,1, // 1610 0,6,11,2,24,4,4,3,15,2, // 1615 25,6,8,1,19,2,29,6,9,3, // 1620 22,4,3,2,13,3,25,4,6,3, // 1625 17,2,27,6,7,3,19,2,31,4, // 1630 11,3,23,4,5,2,15,3,25,6, // 1635 6,2,19,1,29,6,10,2,22,4, // 1640 3,3,14,2,24,6,6,1,17,3, // 1645 28,5,8,3,20,1,32,5,12,3, // 1650 22,6,4,1,16,2,26,6,6,3, // 1655 17,2,0,4,10,3,22,4,3,2, // 1660 14,3,24,6,5,2,17,1,28,6, // 1665 9,2,19,3,31,4,13,2,23,6, // 1670 3,3,15,1,27,5,7,3,17,3, // 1675 29,4,11,2,21,6,3,1,14,2, // 1680 25,6,5,3,16,2,28,4,9,3, // 1685 20,2,0,6,12,1,23,6,4,2, // 1690 14,3,26,4,8,2,18,3,0,4, // 1695 10,3,21,5,1,3,13,1,24,5, // 1700 5,3,15,3,27,4,8,2,19,3, // 1705 29,6,10,2,22,4,3,3,14,2, // 1710 26,4,6,3,18,2,28,6,10,1, // 1715 20,6,2,2,12,3,24,4,5,2, // 1720 16,3,28,4,8,3,19,2,0,6, // 1725 12,1,23,5,3,3,14,3,26,4, // 1730 7,2,17,3,28,6,9,2,21,4, // 1735 1,3,13,2,25,4,5,3,16,2, // 1740 27,6,9,1,19,3,0,5,11,3, // 1745 23,4,4,2,14,3,25,6,7,1, // 1750 18,2,28,6,9,3,21,4,2,2, // 1755 12,3,25,4,6,2,16,3,26,6, // 1760 8,2,20,1,0,6,11,2,22,6, // 1765 4,1,15,2,25,6,6,3,18,1, // 1770 29,5,9,3,22,4,2,3,13,2, // 1775 23,6,4,3,15,2,27,4,7,3, // 1780 19,2,31,4,11,3,21,6,3,2, // 1785 15,1,25,6,6,2,17,3,29,4, // 1790 10,2,20,6,3,1,13,3,24,5, // 1795 4,3,16,1,27,5,7,3,17,3, // 1800 0,4,11,2,21,6,1,3,13,2, // 1805 25,4,5,3,16,2,29,4,9,3, // 1810 19,6,30,2,13,1,23,6,4,2, // 1815 14,3,27,4,8,2,18,3,0,4, // 1820 11,3,22,5,2,3,14,1,26,5, // 1825 6,3,16,3,28,4,10,2,20,6, // 1830 30,3,11,2,24,4,4,3,15,2, // 1835 25,6,8,1,19,2,29,6,9,3, // 1840 22,4,3,2,13,3,25,4,7,2, // 1845 17,3,27,6,9,1,21,5,1,3, // 1850 11,3,23,4,5,2,15,3,25,6, // 1855 6,2,19,1,29,6,10,2,22,4, // 1860 3,3,14,2,24,6,6,1,18,2, // 1865 28,6,8,3,20,4,2,2,12,3, // 1870 24,4,4,3,16,2,26,6,6,3, // 1875 17,2,0,4,10,3,22,4,3,2, // 1880 14,3,24,6,5,2,17,1,28,6, // 1885 9,2,21,4,1,3,13,2,23,6, // 1890 5,1,15,3,27,5,7,3,19,1, // 1895 0,5,10,3,22,4,2,3,13,2, // 1900 24,6,4,3,15,2,27,4,8,3, // 1905 20,4,1,2,11,3,22,6,3,2, // 1910 15,1,25,6,7,2,17,3,29,4, // 1915 10,2,21,6,1,3,13,1,24,5, // 1920 5,3,15,3,27,4,8,2,19,6, // 1925 1,1,12,2,22,6,3,3,14,2, // 1930 26,4,6,3,18,2,28,6,10,1, // 1935 20,6,2,2,12,3,24,4,5,2, // 1940 16,3,28,4,9,2,19,6,30,3, // 1945 12,1,23,5,3,3,14,3,26,4, // 1950 7,2,17,3,28,6,9,2,21,4, // 1955 1,3,13,2,25,4,5,3,16,2, // 1960 27,6,9,1,19,6,30,2,11,3, // 1965 23,4,4,2,14,3,27,4,7,3, // 1970 18,2,28,6,11,1,22,5,2,3, // 1975 12,3,25,4,6,2,16,3,26,6, // 1980 8,2,20,4,30,3,11,2,24,4, // 1985 4,3,15,2,25,6,8,1,18,3, // 1990 29,5,9,3,22,4,3,2,13,3, // 1995 23,6,6,1,17,2,27,6,7,3, // 2000 - 2004 20,4,1,2,11,3,23,4,5,2, // 2005 - 2009 15,3,25,6,6,2,19,1,29,6, // 2010 10,2,20,6,3,1,14,2,24,6, // 2015 4,3,17,1,28,5,8,3,20,4, // 2020 1,3,12,2,22,6,2,3,14,2, // 2025 26,4,6,3,17,2,0,4,10,3, // 2030 20,6,1,2,14,1,24,6,5,2, // 2035 15,3,28,4,9,2,19,6,1,1, // 2040 12,3,23,5,3,3,15,1,27,5, // 2045 7,3,17,3,29,4,11,2,21,6, // 2050 1,3,12,2,25,4,5,3,16,2, // 2055 28,4,9,3,19,6,30,2,12,1, // 2060 23,6,4,2,14,3,26,4,8,2, // 2065 18,3,0,4,10,3,22,5,2,3, // 2070 14,1,25,5,6,3,16,3,28,4, // 2075 9,2,20,6,30,3,11,2,23,4, // 2080 4,3,15,2,27,4,7,3,19,2, // 2085 29,6,11,1,21,6,3,2,13,3, // 2090 25,4,6,2,17,3,27,6,9,1, // 2095 20,5,30,3,10,3,22,4,3,2, // 2100 14,3,24,6,5,2,17,1,28,6, // 2105 9,2,21,4,1,3,13,2,23,6, // 2110 5,1,16,2,27,6,7,3,19,4, // 2115 30,2,11,3,23,4,3,3,14,2, // 2120 25,6,5,3,16,2,28,4,9,3, // 2125 21,4,2,2,12,3,23,6,4,2, // 2130 16,1,26,6,8,2,20,4,30,3, // 2135 11,2,22,6,4,1,14,3,25,5, // 2140 6,3,18,1,29,5,9,3,22,4, // 2145 2,3,13,2,23,6,4,3,15,2, // 2150 27,4,7,3,20,4,1,2,11,3, // 2155 21,6,3,2,15,1,25,6,6,2, // 2160 17,3,29,4,10,2,20,6,3,1, // 2165 13,3,24,5,4,3,17,1,28,5, // 2170 8,3,18,6,1,1,12,2,22,6, // 2175 2,3,14,2,26,4,6,3,17,2, // 2180 28,6,10,1,20,6,1,2,12,3, // 2185 24,4,5,2,15,3,28,4,9,2, // 2190 19,6,33,3,12,1,23,5,3,3, // 2195 13,3,25,4,6,2,16,3,26,6, // 2200 8,2,20,4,30,3,11,2,24,4, // 2205 4,3,15,2,25,6,8,1,18,6, // 2210 33,2,9,3,22,4,3,2,13,3, // 2215 25,4,6,3,17,2,27,6,9,1, // 2220 21,5,1,3,11,3,23,4,5,2, // 2225 15,3,25,6,6,2,19,4,33,3, // 2230 10,2,22,4,3,3,14,2,24,6, // 2235 6,1 // 2240 (Hebrew year: 6000) }; private const int MaxMonthPlusOne = 14; // // The lunar calendar has 6 different variations of month lengths // within a year. // private static readonly byte[] s_lunarMonthLen = { 0,00,00,00,00,00,00,00,00,00,00,00,00,0, 0,30,29,29,29,30,29,30,29,30,29,30,29,0, // 3 common year variations 0,30,29,30,29,30,29,30,29,30,29,30,29,0, 0,30,30,30,29,30,29,30,29,30,29,30,29,0, 0,30,29,29,29,30,30,29,30,29,30,29,30,29, // 3 leap year variations 0,30,29,30,29,30,30,29,30,29,30,29,30,29, 0,30,30,30,29,30,30,29,30,29,30,29,30,29 }; internal static readonly DateTime calendarMinValue = new DateTime(1583, 1, 1); // Gregorian 2239/9/29 = Hebrew 5999/13/29 (last day in Hebrew year 5999). // We can only format/parse Hebrew numbers up to 999, so we limit the max range to Hebrew year 5999. internal static readonly DateTime calendarMaxValue = new DateTime((new DateTime(2239, 9, 29, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } public override DateTime MaxSupportedDateTime { get { return (calendarMaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.LunisolarCalendar; } } public HebrewCalendar() { } internal override CalendarId ID { get { return (CalendarId.HEBREW); } } /*=================================CheckHebrewYearValue========================== **Action: Check if the Hebrew year value is supported in this class. **Returns: None. **Arguments: y Hebrew year value ** ear Hebrew era value **Exceptions: ArgumentOutOfRange_Range if the year value is not supported. **Note: ** We use a table for the Hebrew calendar calculation, so the year supported is limited. ============================================================================*/ private static void CheckHebrewYearValue(int y, int era, String varName) { CheckEraRange(era); if (y > MaxHebrewYear || y < MinHebrewYear) { throw new ArgumentOutOfRangeException( varName, String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinHebrewYear, MaxHebrewYear)); } } /*=================================CheckHebrewMonthValue========================== **Action: Check if the Hebrew month value is valid. **Returns: None. **Arguments: year Hebrew year value ** month Hebrew month value **Exceptions: ArgumentOutOfRange_Range if the month value is not valid. **Note: ** Call CheckHebrewYearValue() before calling this to verify the year value is supported. ============================================================================*/ private void CheckHebrewMonthValue(int year, int month, int era) { int monthsInYear = GetMonthsInYear(year, era); if (month < 1 || month > monthsInYear) { throw new ArgumentOutOfRangeException( nameof(month), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, monthsInYear)); } } /*=================================CheckHebrewDayValue========================== **Action: Check if the Hebrew day value is valid. **Returns: None. **Arguments: year Hebrew year value ** month Hebrew month value ** day Hebrew day value. **Exceptions: ArgumentOutOfRange_Range if the day value is not valid. **Note: ** Call CheckHebrewYearValue()/CheckHebrewMonthValue() before calling this to verify the year/month values are valid. ============================================================================*/ private void CheckHebrewDayValue(int year, int month, int day, int era) { int daysInMonth = GetDaysInMonth(year, month, era); if (day < 1 || day > daysInMonth) { throw new ArgumentOutOfRangeException( nameof(day), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, daysInMonth)); } } internal static void CheckEraRange(int era) { if (era != CurrentEra && era != HebrewEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } } private static void CheckTicksRange(long ticks) { if (ticks < calendarMinValue.Ticks || ticks > calendarMaxValue.Ticks) { throw new ArgumentOutOfRangeException( "time", // Print out the date in Gregorian using InvariantCulture since the DateTime is based on GreograinCalendar. String.Format( CultureInfo.InvariantCulture, SR.ArgumentOutOfRange_CalendarRange, calendarMinValue, calendarMaxValue)); } } internal static int GetResult(__DateBuffer result, int part) { switch (part) { case DatePartYear: return (result.year); case DatePartMonth: return (result.month); case DatePartDay: return (result.day); } throw new InvalidOperationException(SR.InvalidOperation_DateTimeParsing); } /*=================================GetLunarMonthDay========================== **Action: Using the Hebrew table (HebrewTable) to get the Hebrew month/day value for Gregorian January 1st ** in a given Gregorian year. ** Greogrian January 1st falls usually in Tevet (4th month). Tevet has always 29 days. ** That's why, there no nead to specify the lunar month in the table. There are exceptions, and these ** are coded by giving numbers above 29 and below 1. ** Actual decoding is takenig place in the switch statement below. **Returns: ** The Hebrew year type. The value is from 1 to 6. ** normal years : 1 = 353 days 2 = 354 days 3 = 355 days. ** Leap years : 4 = 383 5 384 6 = 385 days. **Arguments: ** gregorianYear The year value in Gregorian calendar. The value should be between 1500 and 2239. ** lunarDate Object to take the result of the Hebrew year/month/day. **Exceptions: ============================================================================*/ internal static int GetLunarMonthDay(int gregorianYear, __DateBuffer lunarDate) { // // Get the offset into the LunarMonthLen array and the lunar day // for January 1st. // int index = gregorianYear - FirstGregorianTableYear; if (index < 0 || index > TABLESIZE) { throw new ArgumentOutOfRangeException(nameof(gregorianYear)); } index *= 2; lunarDate.day = s_hebrewTable[index]; // Get the type of the year. The value is from 1 to 6 int LunarYearType = s_hebrewTable[index + 1]; // // Get the Lunar Month. // switch (lunarDate.day) { case (0): // 1/1 is on Shvat 1 lunarDate.month = 5; lunarDate.day = 1; break; case (30): // 1/1 is on Kislev 30 lunarDate.month = 3; break; case (31): // 1/1 is on Shvat 2 lunarDate.month = 5; lunarDate.day = 2; break; case (32): // 1/1 is on Shvat 3 lunarDate.month = 5; lunarDate.day = 3; break; case (33): // 1/1 is on Kislev 29 lunarDate.month = 3; lunarDate.day = 29; break; default: // 1/1 is on Tevet (This is the general case) lunarDate.month = 4; break; } return (LunarYearType); } // Returns a given date part of this DateTime. This method is used // to compute the year, day-of-year, month, or day part. internal virtual int GetDatePart(long ticks, int part) { // The Gregorian year, month, day value for ticks. int gregorianYear, gregorianMonth, gregorianDay; int hebrewYearType; // lunar year type long AbsoluteDate; // absolute date - absolute date 1/1/1600 // // Make sure we have a valid Gregorian date that will fit into our // Hebrew conversion limits. // CheckTicksRange(ticks); DateTime time = new DateTime(ticks); // // Save the Gregorian date values. // gregorianYear = time.Year; gregorianMonth = time.Month; gregorianDay = time.Day; __DateBuffer lunarDate = new __DateBuffer(); // lunar month and day for Jan 1 // From the table looking-up value of HebrewTable[index] (stored in lunarDate.day), we get the the // lunar month and lunar day where the Gregorian date 1/1 falls. lunarDate.year = gregorianYear + HebrewYearOf1AD; hebrewYearType = GetLunarMonthDay(gregorianYear, lunarDate); // This is the buffer used to store the result Hebrew date. __DateBuffer result = new __DateBuffer(); // // Store the values for the start of the new year - 1/1. // result.year = lunarDate.year; result.month = lunarDate.month; result.day = lunarDate.day; // // Get the absolute date from 1/1/1600. // AbsoluteDate = GregorianCalendar.GetAbsoluteDate(gregorianYear, gregorianMonth, gregorianDay); // // If the requested date was 1/1, then we're done. // if ((gregorianMonth == 1) && (gregorianDay == 1)) { return (GetResult(result, part)); } // // Calculate the number of days between 1/1 and the requested date. // long NumDays; // number of days since 1/1 NumDays = AbsoluteDate - GregorianCalendar.GetAbsoluteDate(gregorianYear, 1, 1); // // If the requested date is within the current lunar month, then // we're done. // if ((NumDays + (long)lunarDate.day) <= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month])) { result.day += (int)NumDays; return (GetResult(result, part)); } // // Adjust for the current partial month. // result.month++; result.day = 1; // // Adjust the Lunar Month and Year (if necessary) based on the number // of days between 1/1 and the requested date. // // Assumes Jan 1 can never translate to the last Lunar month, which // is true. // NumDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + lunarDate.month] - lunarDate.day); Debug.Assert(NumDays >= 1, "NumDays >= 1"); // If NumDays is 1, then we are done. Otherwise, find the correct Hebrew month // and day. if (NumDays > 1) { // // See if we're on the correct Lunar month. // while (NumDays > (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month])) { // // Adjust the number of days and move to the next month. // NumDays -= (long)(s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month++]); // // See if we need to adjust the Year. // Must handle both 12 and 13 month years. // if ((result.month > 13) || (s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + result.month] == 0)) { // // Adjust the Year. // result.year++; hebrewYearType = s_hebrewTable[(gregorianYear + 1 - FirstGregorianTableYear) * 2 + 1]; // // Adjust the Month. // result.month = 1; } } // // Found the right Lunar month. // result.day += (int)(NumDays - 1); } return (GetResult(result, part)); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { try { int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); int monthsInYear; int i; if (months >= 0) { i = m + months; while (i > (monthsInYear = GetMonthsInYear(y, CurrentEra))) { y++; i -= monthsInYear; } } else { if ((i = m + months) <= 0) { months = -months; months -= m; y--; while (months > (monthsInYear = GetMonthsInYear(y, CurrentEra))) { y--; months -= monthsInYear; } monthsInYear = GetMonthsInYear(y, CurrentEra); i = monthsInYear - months; } } int days = GetDaysInMonth(y, i); if (d > days) { d = days; } return (new DateTime(ToDateTime(y, i, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay))); } // We expect ArgumentException and ArgumentOutOfRangeException (which is subclass of ArgumentException) // If exception is thrown in the calls above, we are out of the supported range of this calendar. catch (ArgumentException) { throw new ArgumentOutOfRangeException( nameof(months), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_AddValue)); } } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { int y = GetDatePart(time.Ticks, DatePartYear); int m = GetDatePart(time.Ticks, DatePartMonth); int d = GetDatePart(time.Ticks, DatePartDay); y += years; CheckHebrewYearValue(y, Calendar.CurrentEra, nameof(years)); int months = GetMonthsInYear(y, CurrentEra); if (m > months) { m = months; } int days = GetDaysInMonth(y, m); if (d > days) { d = days; } long ticks = ToDateTime(y, m, d, 0, 0, 0, 0).Ticks + (time.Ticks % TicksPerDay); Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartDay)); } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { // If we calculate back, the Hebrew day of week for Gregorian 0001/1/1 is Monday (1). // Therfore, the fomula is: return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } internal static int GetHebrewYearType(int year, int era) { CheckHebrewYearValue(year, era, nameof(year)); // The HebrewTable is indexed by Gregorian year and starts from FirstGregorianYear. // So we need to convert year (Hebrew year value) to Gregorian Year below. return (s_hebrewTable[(year - HebrewYearOf1AD - FirstGregorianTableYear) * 2 + 1]); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { // Get Hebrew year value of the specified time. int year = GetYear(time); DateTime beginOfYearDate; if (year == 5343) { // Gregorian 1583/01/01 corresponds to Hebrew 5343/04/07 (MinSupportedDateTime) // To figure out the Gregorian date associated with Hebrew 5343/01/01, we need to // count the days from 5343/01/01 to 5343/04/07 and subtract that from Gregorian // 1583/01/01. // 1. Tishri (30 days) // 2. Heshvan (30 days since 5343 has 355 days) // 3. Kislev (30 days since 5343 has 355 days) // 96 days to get from 5343/01/01 to 5343/04/07 // Gregorian 1583/01/01 - 96 days = 1582/9/27 // the beginning of Hebrew year 5343 corresponds to Gregorian September 27, 1582. beginOfYearDate = new DateTime(1582, 9, 27); } else { // following line will fail when year is 5343 (first supported year) beginOfYearDate = ToDateTime(year, 1, 1, 0, 0, 0, 0, CurrentEra); } return ((int)((time.Ticks - beginOfYearDate.Ticks) / TicksPerDay) + 1); } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { CheckEraRange(era); int hebrewYearType = GetHebrewYearType(year, era); CheckHebrewMonthValue(year, month, era); Debug.Assert(hebrewYearType >= 1 && hebrewYearType <= 6, "hebrewYearType should be from 1 to 6, but now hebrewYearType = " + hebrewYearType + " for hebrew year " + year); int monthDays = s_lunarMonthLen[hebrewYearType * MaxMonthPlusOne + month]; if (monthDays == 0) { throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); } return (monthDays); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { CheckEraRange(era); // normal years : 1 = 353 days 2 = 354 days 3 = 355 days. // Leap years : 4 = 383 5 384 6 = 385 days. // LunarYearType is from 1 to 6 int LunarYearType = GetHebrewYearType(year, era); if (LunarYearType < 4) { // common year: LunarYearType = 1, 2, 3 return (352 + LunarYearType); } return (382 + (LunarYearType - 3)); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { return (HebrewEra); } public override int[] Eras { get { return (new int[] { HebrewEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return (GetDatePart(time.Ticks, DatePartMonth)); } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { return (IsLeapYear(year, era) ? 13 : 12); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear(DateTime time) { return (GetDatePart(time.Ticks, DatePartYear)); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { if (IsLeapMonth(year, month, era)) { // Every day in a leap month is a leap day. CheckHebrewDayValue(year, month, day, era); return (true); } else if (IsLeapYear(year, Calendar.CurrentEra)) { // There is an additional day in the 6th month in the leap year (the extra day is the 30th day in the 6th month), // so we should return true for 6/30 if that's in a leap year. if (month == 6 && day == 30) { return (true); } } CheckHebrewDayValue(year, month, day, era); return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { // Year/era values are checked in IsLeapYear(). if (IsLeapYear(year, era)) { // The 7th month in a leap year is a leap month. return (7); } return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { // Year/era values are checked in IsLeapYear(). bool isLeapYear = IsLeapYear(year, era); CheckHebrewMonthValue(year, month, era); // The 7th month in a leap year is a leap month. if (isLeapYear) { if (month == 7) { return (true); } } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { CheckHebrewYearValue(year, era, nameof(year)); return (((7 * (long)year + 1) % 19) < 7); } // (month1, day1) - (month2, day2) private static int GetDayDifference(int lunarYearType, int month1, int day1, int month2, int day2) { if (month1 == month2) { return (day1 - day2); } // Make sure that (month1, day1) < (month2, day2) bool swap = (month1 > month2); if (swap) { // (month1, day1) < (month2, day2). Swap the values. // The result will be a negative number. int tempMonth, tempDay; tempMonth = month1; tempDay = day1; month1 = month2; day1 = day2; month2 = tempMonth; day2 = tempDay; } // Get the number of days from (month1,day1) to (month1, end of month1) int days = s_lunarMonthLen[lunarYearType * MaxMonthPlusOne + month1] - day1; // Move to next month. month1++; // Add up the days. while (month1 < month2) { days += s_lunarMonthLen[lunarYearType * MaxMonthPlusOne + month1++]; } days += day2; return (swap ? days : -days); } /*=================================HebrewToGregorian========================== **Action: Convert Hebrew date to Gregorian date. **Returns: **Arguments: **Exceptions: ** The algorithm is like this: ** The hebrew year has an offset to the Gregorian year, so we can guess the Gregorian year for ** the specified Hebrew year. That is, GreogrianYear = HebrewYear - FirstHebrewYearOf1AD. ** ** From the Gregorian year and HebrewTable, we can get the Hebrew month/day value ** of the Gregorian date January 1st. Let's call this month/day value [hebrewDateForJan1] ** ** If the requested Hebrew month/day is less than [hebrewDateForJan1], we know the result ** Gregorian date falls in previous year. So we decrease the Gregorian year value, and ** retrieve the Hebrew month/day value of the Gregorian date january 1st again. ** ** Now, we get the answer of the Gregorian year. ** ** The next step is to get the number of days between the requested Hebrew month/day ** and [hebrewDateForJan1]. When we get that, we can create the DateTime by adding/subtracting ** the ticks value of the number of days. ** ============================================================================*/ private static DateTime HebrewToGregorian(int hebrewYear, int hebrewMonth, int hebrewDay, int hour, int minute, int second, int millisecond) { // Get the rough Gregorian year for the specified hebrewYear. // int gregorianYear = hebrewYear - HebrewYearOf1AD; __DateBuffer hebrewDateOfJan1 = new __DateBuffer(); // year value is unused. int lunarYearType = GetLunarMonthDay(gregorianYear, hebrewDateOfJan1); if ((hebrewMonth == hebrewDateOfJan1.month) && (hebrewDay == hebrewDateOfJan1.day)) { return (new DateTime(gregorianYear, 1, 1, hour, minute, second, millisecond)); } int days = GetDayDifference(lunarYearType, hebrewMonth, hebrewDay, hebrewDateOfJan1.month, hebrewDateOfJan1.day); DateTime gregorianNewYear = new DateTime(gregorianYear, 1, 1); return (new DateTime(gregorianNewYear.Ticks + days * TicksPerDay + TimeToTicks(hour, minute, second, millisecond))); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { CheckHebrewYearValue(year, era, nameof(year)); CheckHebrewMonthValue(year, month, era); CheckHebrewDayValue(year, month, day, era); DateTime dt = HebrewToGregorian(year, month, day, hour, minute, second, millisecond); CheckTicksRange(dt.Ticks); return (dt); } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 5790; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value == 99) { // Do nothing here. Year 99 is allowed so that TwoDitYearMax is disabled. } else { CheckHebrewYearValue(value, HebrewEra, nameof(value)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } Contract.EndContractBlock(); if (year < 100) { return (base.ToFourDigitYear(year)); } if (year > MaxHebrewYear || year < MinHebrewYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MinHebrewYear, MaxHebrewYear)); } return (year); } internal class __DateBuffer { internal int year; internal int month; internal int day; } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; public class AnimationHierarchyEditor : EditorWindow { private static int columnWidth = 300; private Animator animatorObject; private List<AnimationClip> animationClips; private ArrayList pathsKeys; private Hashtable paths; Dictionary<string, string> tempPathOverrides; private Vector2 scrollPos = Vector2.zero; [MenuItem("Window/Animation Hierarchy Editor")] static void ShowWindow() { EditorWindow.GetWindow<AnimationHierarchyEditor>(); } public AnimationHierarchyEditor(){ animationClips = new List<AnimationClip>(); tempPathOverrides = new Dictionary<string, string>(); } void OnSelectionChange() { if (Selection.objects.Length > 1 ) { Debug.Log ("Length? " + Selection.objects.Length); animationClips.Clear(); foreach ( Object o in Selection.objects ) { if ( o is AnimationClip ) animationClips.Add((AnimationClip)o); } } else if (Selection.activeObject is AnimationClip) { animationClips.Clear(); animationClips.Add((AnimationClip)Selection.activeObject); FillModel(); } else { animationClips.Clear(); } this.Repaint(); } private string sOriginalRoot = "Root"; private string sNewRoot = "SomeNewObject/Root"; private string originalPathText = ""; private string replacePathText = ""; private bool changeAllPaths = false; void OnGUI() { if (Event.current.type == EventType.ValidateCommand) { switch (Event.current.commandName) { case "UndoRedoPerformed": FillModel(); break; } } if (animationClips.Count > 0 ) { scrollPos = GUILayout.BeginScrollView(scrollPos, GUIStyle.none); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Referenced Animator (Root):", GUILayout.Width(columnWidth)); animatorObject = ((Animator)EditorGUILayout.ObjectField( animatorObject, typeof(Animator), true, GUILayout.Width(columnWidth)) ); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Animation Clip:", GUILayout.Width(columnWidth)); if ( animationClips.Count == 1 ) { animationClips[0] = ((AnimationClip)EditorGUILayout.ObjectField( animationClips[0], typeof(AnimationClip), true, GUILayout.Width(columnWidth)) ); } else { GUILayout.Label("Multiple Anim Clips: " + animationClips.Count, GUILayout.Width(columnWidth)); } EditorGUILayout.EndHorizontal(); GUILayout.Space(20); EditorGUILayout.BeginHorizontal(); sOriginalRoot = EditorGUILayout.TextField(sOriginalRoot, GUILayout.Width(columnWidth)); sNewRoot = EditorGUILayout.TextField(sNewRoot, GUILayout.Width(columnWidth)); if (GUILayout.Button("Replace Root")) { Debug.Log("O: "+sOriginalRoot+ " N: "+sNewRoot); ReplaceRoot(sOriginalRoot, sNewRoot); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Original Path Text:", GUILayout.Width(columnWidth)); GUILayout.Label("Replacement Path Text:", GUILayout.Width(columnWidth)); EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); originalPathText = EditorGUILayout.TextField(originalPathText, GUILayout.Width(columnWidth)); replacePathText = EditorGUILayout.TextField(replacePathText, GUILayout.Width(columnWidth)); if (GUILayout.Button("Replace All Paths")) { changeAllPaths = true; } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); GUILayout.Label("Reference path:", GUILayout.Width(columnWidth)); GUILayout.Label("Animated properties:", GUILayout.Width(columnWidth*0.5f)); GUILayout.Label("(Count)", GUILayout.Width(60)); GUILayout.Label("Object:", GUILayout.Width(columnWidth)); EditorGUILayout.EndHorizontal(); if (paths != null) { foreach (string path in pathsKeys) { GUICreatePathItem(path); } changeAllPaths = false; } GUILayout.Space(40); GUILayout.EndScrollView(); } else { GUILayout.Label("Please select an Animation Clip"); } } void GUICreatePathItem(string path) { string newPath = path; GameObject obj = FindObjectInRoot(path); GameObject newObj; ArrayList properties = (ArrayList)paths[path]; string pathOverride = path; if ( tempPathOverrides.ContainsKey(path) ) pathOverride = tempPathOverrides[path]; EditorGUILayout.BeginHorizontal(); if (originalPathText != "" && changeAllPaths) { pathOverride = pathOverride.Replace(originalPathText, replacePathText); } pathOverride = EditorGUILayout.TextField(pathOverride, GUILayout.Width(columnWidth)); if ( pathOverride != path ) tempPathOverrides[path] = pathOverride; if (GUILayout.Button("Change", GUILayout.Width(60)) || changeAllPaths) { newPath = pathOverride; tempPathOverrides.Remove(path); } EditorGUILayout.LabelField( properties != null ? properties.Count.ToString() : "0", GUILayout.Width(60) ); Color standardColor = GUI.color; if (obj == null && path.Contains("/Control Point")) { newPath = RenameControlPointPath(path); // Debug.Log(RenameControlPointPath(path)); } if (obj != null) { GUI.color = Color.green; } else { GUI.color = Color.red; } newObj = (GameObject)EditorGUILayout.ObjectField( obj, typeof(GameObject), true, GUILayout.Width(columnWidth) ); GUI.color = standardColor; EditorGUILayout.EndHorizontal(); try { if (obj != newObj) { UpdatePath(path, ChildPath(newObj)); } if (newPath != path) { UpdatePath(path, newPath); } } catch (UnityException ex) { Debug.LogError(ex.Message); } } void OnInspectorUpdate() { this.Repaint(); } void FillModel() { paths = new Hashtable(); pathsKeys = new ArrayList(); foreach ( AnimationClip animationClip in animationClips ) { FillModelWithCurves(AnimationUtility.GetCurveBindings(animationClip)); FillModelWithCurves(AnimationUtility.GetObjectReferenceCurveBindings(animationClip)); } } private void FillModelWithCurves(EditorCurveBinding[] curves) { foreach (EditorCurveBinding curveData in curves) { string key = curveData.path; if (paths.ContainsKey(key)) { ((ArrayList)paths[key]).Add(curveData); } else { ArrayList newProperties = new ArrayList(); newProperties.Add(curveData); paths.Add(key, newProperties); pathsKeys.Add(key); } } } string sReplacementOldRoot; string sReplacementNewRoot; void ReplaceRoot(string oldRoot, string newRoot) { float fProgress = 0.0f; sReplacementOldRoot = oldRoot; sReplacementNewRoot = newRoot; AssetDatabase.StartAssetEditing(); for ( int iCurrentClip = 0; iCurrentClip < animationClips.Count; iCurrentClip++ ) { AnimationClip animationClip = animationClips[iCurrentClip]; Undo.RecordObject(animationClip, "Animation Hierarchy Root Change"); for ( int iCurrentPath = 0; iCurrentPath < pathsKeys.Count; iCurrentPath ++) { string path = pathsKeys[iCurrentPath] as string; ArrayList curves = (ArrayList)paths[path]; for (int i = 0; i < curves.Count; i++) { EditorCurveBinding binding = (EditorCurveBinding)curves[i]; if ( path.Contains(sReplacementOldRoot) ) { if ( !path.Contains(sReplacementNewRoot) ) { string sNewPath = Regex.Replace(path, "^"+sReplacementOldRoot, sReplacementNewRoot ); AnimationCurve curve = AnimationUtility.GetEditorCurve(animationClip, binding); if ( curve != null ) { AnimationUtility.SetEditorCurve(animationClip, binding, null); binding.path = sNewPath; AnimationUtility.SetEditorCurve(animationClip, binding, curve); } else { ObjectReferenceKeyframe[] objectReferenceCurve = AnimationUtility.GetObjectReferenceCurve(animationClip, binding); AnimationUtility.SetObjectReferenceCurve(animationClip, binding, null); binding.path = sNewPath; AnimationUtility.SetObjectReferenceCurve(animationClip, binding, objectReferenceCurve); } } } } // Update the progress meter float fChunk = 1f / animationClips.Count; fProgress = (iCurrentClip * fChunk) + fChunk * ((float) iCurrentPath / (float) pathsKeys.Count); EditorUtility.DisplayProgressBar( "Animation Hierarchy Progress", "How far along the animation editing has progressed.", fProgress); } } AssetDatabase.StopAssetEditing(); EditorUtility.ClearProgressBar(); FillModel(); this.Repaint(); } string RenameControlPointPath(string oldPath) { int index = oldPath.LastIndexOf("/"); string controlPointName = oldPath.Substring(index + 1); string newPath = oldPath.Substring(0, index); index = newPath.LastIndexOf("/"); string prefixName = newPath.Substring(index + 1); newPath = newPath + "/" + prefixName + " " + controlPointName; return newPath; } void UpdatePath(string oldPath, string newPath) { if (paths[newPath] != null) { throw new UnityException("Path " + newPath + " already exists in that animation!"); } AssetDatabase.StartAssetEditing(); for ( int iCurrentClip = 0; iCurrentClip < animationClips.Count; iCurrentClip++ ) { AnimationClip animationClip = animationClips[iCurrentClip]; Undo.RecordObject(animationClip, "Animation Hierarchy Change"); //recreating all curves one by one //to maintain proper order in the editor - //slower than just removing old curve //and adding a corrected one, but it's more //user-friendly for ( int iCurrentPath = 0; iCurrentPath < pathsKeys.Count; iCurrentPath ++) { string path = pathsKeys[iCurrentPath] as string; ArrayList curves = (ArrayList)paths[path]; for (int i = 0; i < curves.Count; i++) { EditorCurveBinding binding = (EditorCurveBinding)curves[i]; AnimationCurve curve = AnimationUtility.GetEditorCurve(animationClip, binding); ObjectReferenceKeyframe[] objectReferenceCurve = AnimationUtility.GetObjectReferenceCurve(animationClip, binding); if ( curve != null ) AnimationUtility.SetEditorCurve(animationClip, binding, null); else AnimationUtility.SetObjectReferenceCurve(animationClip, binding, null); if (path == oldPath) binding.path = newPath; if ( curve != null ) AnimationUtility.SetEditorCurve(animationClip, binding, curve); else AnimationUtility.SetObjectReferenceCurve(animationClip, binding, objectReferenceCurve); float fChunk = 1f / animationClips.Count; float fProgress = (iCurrentClip * fChunk) + fChunk * ((float) iCurrentPath / (float) pathsKeys.Count); EditorUtility.DisplayProgressBar( "Animation Hierarchy Progress", "How far along the animation editing has progressed.", fProgress); } } } AssetDatabase.StopAssetEditing(); EditorUtility.ClearProgressBar(); FillModel(); this.Repaint(); } GameObject FindObjectInRoot(string path) { if (animatorObject == null) { return null; } Transform child = animatorObject.transform.Find(path); if (child != null) { return child.gameObject; } else { return null; } } string ChildPath(GameObject obj, bool sep = false) { if (animatorObject == null) { throw new UnityException("Please assign Referenced Animator (Root) first!"); } if (obj == animatorObject.gameObject) { return ""; } else { if (obj.transform.parent == null) { throw new UnityException("Object must belong to " + animatorObject.ToString() + "!"); } else { return ChildPath(obj.transform.parent.gameObject, true) + obj.name + (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. namespace System.DirectoryServices.Protocols { using System; using System.Globalization; using System.Threading; using System.Collections; using System.Diagnostics; internal class LdapPartialResultsProcessor { private ArrayList _resultList = null; private ManualResetEvent _workThreadWaitHandle = null; private bool _workToDo = false; private int _currentIndex = 0; internal LdapPartialResultsProcessor(ManualResetEvent eventHandle) { _resultList = new ArrayList(); _workThreadWaitHandle = eventHandle; } public void Add(LdapPartialAsyncResult asyncResult) { lock (this) { _resultList.Add(asyncResult); if (!_workToDo) { // need to wake up the workthread if it is not running already _workThreadWaitHandle.Set(); _workToDo = true; } } } public void Remove(LdapPartialAsyncResult asyncResult) { // called by Abort operation lock (this) { if (!_resultList.Contains(asyncResult)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult)); // remove this async operation from the list _resultList.Remove(asyncResult); } } public void RetrievingSearchResults() { int count = 0; int i = 0; LdapPartialAsyncResult asyncResult = null; AsyncCallback tmpCallback = null; lock (this) { count = _resultList.Count; if (count == 0) { // no asynchronous operation pending, begin to wait _workThreadWaitHandle.Reset(); _workToDo = false; return; } // might have work to do while (true) { if (_currentIndex >= count) { // some element is moved after last iteration _currentIndex = 0; } asyncResult = (LdapPartialAsyncResult)_resultList[_currentIndex]; i++; _currentIndex++; // have work to do if (asyncResult.resultStatus != ResultsStatus.Done) break; if (i >= count) { // all the operations are done just waiting for the user to pick up the results _workToDo = false; _workThreadWaitHandle.Reset(); return; } } // try to get the results availabe for this asynchronous operation GetResultsHelper(asyncResult); // if we are done with the asynchronous search, we need to fire callback and signal the waitable object if (asyncResult.resultStatus == ResultsStatus.Done) { asyncResult.manualResetEvent.Set(); asyncResult.completed = true; if (asyncResult.callback != null) { tmpCallback = asyncResult.callback; } } else if (asyncResult.callback != null && asyncResult.partialCallback) { // if user specify callback to be called even when partial results become available if (asyncResult.response != null && (asyncResult.response.Entries.Count > 0 || asyncResult.response.References.Count > 0)) { tmpCallback = asyncResult.callback; } } } if (tmpCallback != null) tmpCallback((IAsyncResult)asyncResult); } private void GetResultsHelper(LdapPartialAsyncResult asyncResult) { LdapConnection con = asyncResult.con; IntPtr ldapResult = (IntPtr)0; IntPtr entryMessage = (IntPtr)0; ResultAll resultType = ResultAll.LDAP_MSG_RECEIVED; if (asyncResult.resultStatus == ResultsStatus.CompleteResult) resultType = ResultAll.LDAP_MSG_POLLINGALL; try { SearchResponse response = (SearchResponse)con.ConstructResponse(asyncResult.messageID, LdapOperation.LdapSearch, resultType, asyncResult.requestTimeout, false); // this should only happen in the polling thread case if (response == null) { // only when request time out has not yet expiered if ((asyncResult.startTime.Ticks + asyncResult.requestTimeout.Ticks) > DateTime.Now.Ticks) { // this is expected, just the client does not have the result yet return; } else { // time out, now we need to throw proper exception throw new LdapException((int)LdapError.TimeOut, LdapErrorMappings.MapResultCode((int)LdapError.TimeOut)); } } if (asyncResult.response != null) AddResult(asyncResult.response, response); else asyncResult.response = response; // if search is done, set the flag if (response.searchDone) asyncResult.resultStatus = ResultsStatus.Done; } catch (Exception e) { if (e is DirectoryOperationException) { SearchResponse response = (SearchResponse)(((DirectoryOperationException)e).Response); if (asyncResult.response != null) AddResult(asyncResult.response, response); else asyncResult.response = response; // set the response back to the exception so it holds all the results up to now ((DirectoryOperationException)e).Response = asyncResult.response; } else if (e is LdapException) { LdapException ldapE = (LdapException)e; LdapError errorCode = (LdapError)ldapE.ErrorCode; if (asyncResult.response != null) { // add previous retrieved entries if available if (asyncResult.response.Entries != null) { for (int i = 0; i < asyncResult.response.Entries.Count; i++) { ldapE.results.Add(asyncResult.response.Entries[i]); } } // add previous retrieved references if available if (asyncResult.response.References != null) { for (int i = 0; i < asyncResult.response.References.Count; i++) { ldapE.results.Add(asyncResult.response.References[i]); } } } } // exception occurs, this operation is done. asyncResult.exception = e; asyncResult.resultStatus = ResultsStatus.Done; // need to abandon this request Wldap32.ldap_abandon(con.ldapHandle, asyncResult.messageID); } } public void NeedCompleteResult(LdapPartialAsyncResult asyncResult) { lock (this) { if (_resultList.Contains(asyncResult)) { // we don't need partial results anymore, polling for complete results if (asyncResult.resultStatus == ResultsStatus.PartialResult) asyncResult.resultStatus = ResultsStatus.CompleteResult; } else throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult)); } } public PartialResultsCollection GetPartialResults(LdapPartialAsyncResult asyncResult) { lock (this) { if (!_resultList.Contains(asyncResult)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult)); if (asyncResult.exception != null) { // remove this async operation // the async operation basically failed, we won't do it any more, so throw exception to the user and remove it from the list _resultList.Remove(asyncResult); throw asyncResult.exception; } PartialResultsCollection collection = new PartialResultsCollection(); if (asyncResult.response != null) { if (asyncResult.response.Entries != null) { for (int i = 0; i < asyncResult.response.Entries.Count; i++) collection.Add(asyncResult.response.Entries[i]); asyncResult.response.Entries.Clear(); } if (asyncResult.response.References != null) { for (int i = 0; i < asyncResult.response.References.Count; i++) collection.Add(asyncResult.response.References[i]); asyncResult.response.References.Clear(); } } return collection; } } public DirectoryResponse GetCompleteResult(LdapPartialAsyncResult asyncResult) { lock (this) { if (!_resultList.Contains(asyncResult)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, SR.InvalidAsyncResult)); Debug.Assert(asyncResult.resultStatus == ResultsStatus.Done); _resultList.Remove(asyncResult); if (asyncResult.exception != null) { throw asyncResult.exception; } else { return asyncResult.response; } } } private void AddResult(SearchResponse partialResults, SearchResponse newResult) { if (newResult == null) return; if (newResult.Entries != null) { for (int i = 0; i < newResult.Entries.Count; i++) { partialResults.Entries.Add(newResult.Entries[i]); } } if (newResult.References != null) { for (int i = 0; i < newResult.References.Count; i++) { partialResults.References.Add(newResult.References[i]); } } } } internal class PartialResultsRetriever { private ManualResetEvent _workThreadWaitHandle = null; private Thread _oThread = null; private LdapPartialResultsProcessor _processor = null; internal PartialResultsRetriever(ManualResetEvent eventHandle, LdapPartialResultsProcessor processor) { _workThreadWaitHandle = eventHandle; _processor = processor; _oThread = new Thread(new ThreadStart(ThreadRoutine)); _oThread.IsBackground = true; // start the thread _oThread.Start(); } private void ThreadRoutine() { while (true) { // make sure there is work to do _workThreadWaitHandle.WaitOne(); // do the real work try { _processor.RetrievingSearchResults(); } catch (Exception e) { // we catch the exception here as we don't really want our worker thread to die because it // encounter certain exception when processing a single async operation. Debug.WriteLine(e.Message); } // Voluntarily gives up the CPU time Thread.Sleep(250); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using Internal.Runtime; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; using Internal.Metadata.NativeFormat; using Internal.NativeFormat; using Internal.TypeSystem; using Internal.TypeSystem.NativeFormat; using Internal.TypeSystem.NoMetadata; namespace Internal.Runtime.TypeLoader { internal struct NativeLayoutInfo { public uint Offset; public NativeFormatModuleInfo Module; public NativeReader Reader; public NativeLayoutInfoLoadContext LoadContext; } // // TypeBuilder per-Type state. It is attached to each TypeDesc that gets involved in type building. // internal class TypeBuilderState { internal class VTableLayoutInfo { public uint VTableSlot; public RuntimeSignature MethodSignature; public bool IsSealedVTableSlot; } internal class VTableSlotMapper { private int[] _slotMap; private IntPtr[] _dictionarySlots; private int _numMappingsAssigned; public VTableSlotMapper(int numVtableSlotsInTemplateType) { _slotMap = new int[numVtableSlotsInTemplateType]; _dictionarySlots = new IntPtr[numVtableSlotsInTemplateType]; _numMappingsAssigned = 0; for (int i = 0; i < numVtableSlotsInTemplateType; i++) { _slotMap[i] = -1; _dictionarySlots[i] = IntPtr.Zero; } } public void AddMapping(int vtableSlotInTemplateType, int vtableSlotInTargetType, IntPtr dictionaryValueInSlot) { Debug.Assert(_numMappingsAssigned < _slotMap.Length); _slotMap[vtableSlotInTemplateType] = vtableSlotInTargetType; _dictionarySlots[vtableSlotInTemplateType] = dictionaryValueInSlot; _numMappingsAssigned++; } public int GetVTableSlotInTargetType(int vtableSlotInTemplateType) { Debug.Assert(vtableSlotInTemplateType < _slotMap.Length); return _slotMap[vtableSlotInTemplateType]; } public bool IsDictionarySlot(int vtableSlotInTemplateType, out IntPtr dictionaryPtrValue) { Debug.Assert(vtableSlotInTemplateType < _dictionarySlots.Length); dictionaryPtrValue = _dictionarySlots[vtableSlotInTemplateType]; return _dictionarySlots[vtableSlotInTemplateType] != IntPtr.Zero; } public int NumSlotMappings { get { return _numMappingsAssigned; } } } public TypeBuilderState(TypeDesc typeBeingBuilt) { TypeBeingBuilt = typeBeingBuilt; } public readonly TypeDesc TypeBeingBuilt; // // We cache and try to reuse the most recently used TypeSystemContext. The TypeSystemContext is used by not just type builder itself, // but also in several random other places in reflection. There can be multiple ResolutionContexts in flight at any given moment. // This check ensures that the RuntimeTypeHandle cache in the current resolution context is refreshed in case there were new // types built using a different TypeSystemContext in the meantime. // NOTE: For correctness, this value must be recomputed every time the context is recycled. This requires flushing the TypeBuilderState // from each type that has one if context is recycled. // public bool AttemptedAndFailedToRetrieveTypeHandle = false; public bool NeedsTypeHandle; public bool HasBeenPrepared; public RuntimeTypeHandle HalfBakedRuntimeTypeHandle; public IntPtr HalfBakedDictionary; public IntPtr HalfBakedSealedVTable; private bool _templateComputed; private bool _nativeLayoutTokenComputed; private TypeDesc _templateType; public TypeDesc TemplateType { get { if (!_templateComputed) { // Locate the template type and native layout info _templateType = TypeBeingBuilt.Context.TemplateLookup.TryGetTypeTemplate(TypeBeingBuilt, ref _nativeLayoutInfo); Debug.Assert(_templateType == null || !_templateType.RuntimeTypeHandle.IsNull()); _templateTypeLoaderNativeLayout = true; _templateComputed = true; if ((_templateType != null) && !_templateType.IsCanonicalSubtype(CanonicalFormKind.Universal)) _nativeLayoutTokenComputed = true; } return _templateType; } } private bool _nativeLayoutComputed = false; private bool _templateTypeLoaderNativeLayout = false; private bool _readyToRunNativeLayout = false; private NativeLayoutInfo _nativeLayoutInfo; private NativeLayoutInfo _r2rnativeLayoutInfo; private void EnsureNativeLayoutInfoComputed() { if (!_nativeLayoutComputed) { if (!_nativeLayoutTokenComputed) { if (!_templateComputed) { // Attempt to compute native layout through as a non-ReadyToRun template object temp = this.TemplateType; } if (!_nativeLayoutTokenComputed) { TypeBeingBuilt.Context.TemplateLookup.TryGetMetadataNativeLayout(TypeBeingBuilt, out _r2rnativeLayoutInfo.Module, out _r2rnativeLayoutInfo.Offset); if (_r2rnativeLayoutInfo.Module != null) _readyToRunNativeLayout = true; } _nativeLayoutTokenComputed = true; } if (_nativeLayoutInfo.Module != null) { FinishInitNativeLayoutInfo(TypeBeingBuilt, ref _nativeLayoutInfo); } if (_r2rnativeLayoutInfo.Module != null) { FinishInitNativeLayoutInfo(TypeBeingBuilt, ref _r2rnativeLayoutInfo); } _nativeLayoutComputed = true; } } /// <summary> /// Initialize the Reader and LoadContext fields of the native layout info /// </summary> /// <param name="type"></param> /// <param name="nativeLayoutInfo"></param> private static void FinishInitNativeLayoutInfo(TypeDesc type, ref NativeLayoutInfo nativeLayoutInfo) { var nativeLayoutInfoLoadContext = new NativeLayoutInfoLoadContext(); nativeLayoutInfoLoadContext._typeSystemContext = type.Context; nativeLayoutInfoLoadContext._module = nativeLayoutInfo.Module; if (type is DefType) { nativeLayoutInfoLoadContext._typeArgumentHandles = ((DefType)type).Instantiation; } else if (type is ArrayType) { nativeLayoutInfoLoadContext._typeArgumentHandles = new Instantiation(new TypeDesc[] { ((ArrayType)type).ElementType }); } else { Debug.Assert(false); } nativeLayoutInfoLoadContext._methodArgumentHandles = new Instantiation(null); nativeLayoutInfo.Reader = TypeLoaderEnvironment.Instance.GetNativeLayoutInfoReader(nativeLayoutInfo.Module.Handle); nativeLayoutInfo.LoadContext = nativeLayoutInfoLoadContext; } public NativeLayoutInfo NativeLayoutInfo { get { EnsureNativeLayoutInfoComputed(); return _nativeLayoutInfo; } } public NativeLayoutInfo R2RNativeLayoutInfo { get { EnsureNativeLayoutInfoComputed(); return _r2rnativeLayoutInfo; } } public NativeParser GetParserForNativeLayoutInfo() { EnsureNativeLayoutInfoComputed(); if (_templateTypeLoaderNativeLayout) return new NativeParser(_nativeLayoutInfo.Reader, _nativeLayoutInfo.Offset); else return default(NativeParser); } public NativeParser GetParserForReadyToRunNativeLayoutInfo() { EnsureNativeLayoutInfoComputed(); if (_readyToRunNativeLayout) return new NativeParser(_r2rnativeLayoutInfo.Reader, _r2rnativeLayoutInfo.Offset); else return default(NativeParser); } public NativeParser GetParserForUniversalNativeLayoutInfo(out NativeLayoutInfoLoadContext universalLayoutLoadContext, out NativeLayoutInfo universalLayoutInfo) { universalLayoutInfo = new NativeLayoutInfo(); universalLayoutLoadContext = null; TypeDesc universalTemplate = TypeBeingBuilt.Context.TemplateLookup.TryGetUniversalTypeTemplate(TypeBeingBuilt, ref universalLayoutInfo); if (universalTemplate == null) return new NativeParser(); FinishInitNativeLayoutInfo(TypeBeingBuilt, ref universalLayoutInfo); universalLayoutLoadContext = universalLayoutInfo.LoadContext; return new NativeParser(universalLayoutInfo.Reader, universalLayoutInfo.Offset); } // RuntimeInterfaces is the full list of interfaces that the type implements. It can include private internal implementation // detail interfaces that nothing is known about. public DefType[] RuntimeInterfaces { get { // Generic Type Definitions have no runtime interfaces if (TypeBeingBuilt.IsGenericDefinition) return null; return TypeBeingBuilt.RuntimeInterfaces; } } private bool? _hasDictionarySlotInVTable; private bool ComputeHasDictionarySlotInVTable() { if (!TypeBeingBuilt.IsGeneric() && !(TypeBeingBuilt is ArrayType)) return false; // Generic interfaces always have a dictionary slot if (TypeBeingBuilt.IsInterface) return true; return TypeBeingBuilt.CanShareNormalGenericCode(); } public bool HasDictionarySlotInVTable { get { if (_hasDictionarySlotInVTable == null) { _hasDictionarySlotInVTable = ComputeHasDictionarySlotInVTable(); } return _hasDictionarySlotInVTable.Value; } } private bool? _hasDictionaryInVTable; private bool ComputeHasDictionaryInVTable() { if (!HasDictionarySlotInVTable) return false; if (TypeBeingBuilt.RetrieveRuntimeTypeHandleIfPossible()) { // Type was already constructed return TypeBeingBuilt.RuntimeTypeHandle.GetDictionary() != IntPtr.Zero; } else { // Type is being newly constructed if (TemplateType != null) { NativeParser parser = GetParserForNativeLayoutInfo(); // Template type loader case #if GENERICS_FORCE_USG bool isTemplateUniversalCanon = state.TemplateType.IsCanonicalSubtype(CanonicalFormKind.UniversalCanonLookup); if (isTemplateUniversalCanon && type.CanShareNormalGenericCode()) { TypeBuilderState tempState = new TypeBuilderState(); tempState.NativeLayoutInfo = new NativeLayoutInfo(); tempState.TemplateType = type.Context.TemplateLookup.TryGetNonUniversalTypeTemplate(type, ref tempState.NativeLayoutInfo); if (tempState.TemplateType != null) { Debug.Assert(!tempState.TemplateType.IsCanonicalSubtype(CanonicalFormKind.UniversalCanonLookup)); parser = GetNativeLayoutInfoParser(type, ref tempState.NativeLayoutInfo); } } #endif var dictionaryLayoutParser = parser.GetParserForBagElementKind(BagElementKind.DictionaryLayout); return !dictionaryLayoutParser.IsNull; } else { NativeParser parser = GetParserForReadyToRunNativeLayoutInfo(); // ReadyToRun case // Dictionary is directly encoded instead of the NativeLayout being a collection of bags if (parser.IsNull) return false; // First unsigned value in the native layout is the number of dictionary entries return parser.GetUnsigned() != 0; } } } public bool HasDictionaryInVTable { get { if (_hasDictionaryInVTable == null) _hasDictionaryInVTable = ComputeHasDictionaryInVTable(); return _hasDictionaryInVTable.Value; } } private ushort? _numVTableSlots; private ushort ComputeNumVTableSlots() { if (TypeBeingBuilt.RetrieveRuntimeTypeHandleIfPossible()) { unsafe { return TypeBeingBuilt.RuntimeTypeHandle.ToEETypePtr()->NumVtableSlots; } } else { TypeDesc templateType = TypeBeingBuilt.ComputeTemplate(false); if (templateType != null) { // Template type loader case if (VTableSlotsMapping != null) { return checked((ushort)VTableSlotsMapping.NumSlotMappings); } else { // This should only happen for non-universal templates Debug.Assert(TypeBeingBuilt.IsTemplateCanonical()); // Canonical template type loader case unsafe { return templateType.GetRuntimeTypeHandle().ToEETypePtr()->NumVtableSlots; } } } else if (TypeBeingBuilt.IsMdArray || (TypeBeingBuilt.IsSzArray && ((ArrayType)TypeBeingBuilt).ElementType.IsPointer)) { // MDArray types and pointer arrays have the same vtable as the System.Array type they "derive" from. // They do not implement the generic interfaces that make this interesting for normal arrays. unsafe { return TypeBeingBuilt.BaseType.GetRuntimeTypeHandle().ToEETypePtr()->NumVtableSlots; } } else { // Metadata based type loading. // Generic Type Definitions have no actual vtable entries if (TypeBeingBuilt.IsGenericDefinition) return 0; // We have at least as many slots as exist on the base type. ushort numVTableSlots = 0; checked { if (TypeBeingBuilt.BaseType != null) { numVTableSlots = TypeBeingBuilt.BaseType.GetOrCreateTypeBuilderState().NumVTableSlots; } else { // Generic interfaces have a dictionary slot if (TypeBeingBuilt.IsInterface && TypeBeingBuilt.HasInstantiation) numVTableSlots = 1; } // Interfaces have actual vtable slots if (TypeBeingBuilt.IsInterface) return numVTableSlots; foreach (MethodDesc method in TypeBeingBuilt.GetMethods()) { #if SUPPORTS_NATIVE_METADATA_TYPE_LOADING if (LazyVTableResolver.MethodDefinesVTableSlot(method)) numVTableSlots++; #else Environment.FailFast("metadata type loader required"); #endif } if (HasDictionarySlotInVTable) numVTableSlots++; } return numVTableSlots; } } } public ushort NumVTableSlots { get { if (_numVTableSlots == null) _numVTableSlots = ComputeNumVTableSlots(); return _numVTableSlots.Value; } } public GenericTypeDictionary Dictionary; public int NonGcDataSize { get { DefType defType = TypeBeingBuilt as DefType; // The NonGCStatic fields hold the class constructor data if it exists in the negative space // of the memory region. The ClassConstructorOffset is negative, so it must be negated to // determine the extra space that is used. if (defType != null) { return defType.NonGCStaticFieldSize.AsInt - (HasStaticConstructor ? TypeBuilder.ClassConstructorOffset : 0); } else { return -(HasStaticConstructor ? TypeBuilder.ClassConstructorOffset : 0); } } } public int GcDataSize { get { DefType defType = TypeBeingBuilt as DefType; if (defType != null) { return defType.GCStaticFieldSize.AsInt; } else { return 0; } } } public int ThreadDataSize { get { DefType defType = TypeBeingBuilt as DefType; if (defType != null && !defType.IsGenericDefinition) { return defType.ThreadStaticFieldSize.AsInt; } else { // Non-DefType's and GenericEETypeDefinitions do not have static fields of any form return 0; } } } public bool HasStaticConstructor { get { return TypeBeingBuilt.HasStaticConstructor; } } public IntPtr? ClassConstructorPointer; public IntPtr GcStaticDesc; public IntPtr GcStaticEEType; public IntPtr ThreadStaticDesc; public bool AllocatedStaticGCDesc; public bool AllocatedThreadStaticGCDesc; public uint ThreadStaticOffset; public uint NumSealedVTableEntries; public int[] GenericVarianceFlags; // Sentinel static to allow us to initializae _instanceLayout to something // and then detect that InstanceGCLayout should return null private static LowLevelList<bool> s_emptyLayout = new LowLevelList<bool>(); private LowLevelList<bool> _instanceGCLayout; /// <summary> /// The instance gc layout of a dynamically laid out type. /// null if one of the following is true /// 1) For an array type: /// - the type is a reference array /// 2) For a generic type: /// - the type has no GC instance fields /// - the type already has a type handle /// - the type has a non-universal canonical template /// - the type has already been constructed /// /// If the type is a valuetype array, this is the layout of the valuetype held in the array if the type has GC reference fields /// Otherwise, it is the layout of the fields in the type. /// </summary> public LowLevelList<bool> InstanceGCLayout { get { if (_instanceGCLayout == null) { LowLevelList<bool> instanceGCLayout = null; if (TypeBeingBuilt is ArrayType) { if (!IsArrayOfReferenceTypes) { ArrayType arrayType = (ArrayType)TypeBeingBuilt; TypeBuilder.GCLayout elementGcLayout = GetFieldGCLayout(arrayType.ElementType); if (!elementGcLayout.IsNone) { instanceGCLayout = new LowLevelList<bool>(); elementGcLayout.WriteToBitfield(instanceGCLayout, 0); _instanceGCLayout = instanceGCLayout; } } else { // Array of reference type returns null _instanceGCLayout = s_emptyLayout; } } else if (TypeBeingBuilt.RetrieveRuntimeTypeHandleIfPossible() || TypeBeingBuilt.IsTemplateCanonical() || (TypeBeingBuilt is PointerType) || (TypeBeingBuilt is ByRefType)) { _instanceGCLayout = s_emptyLayout; } else { // Generic Type Definitions have no gc layout if (!(TypeBeingBuilt.IsGenericDefinition)) { // Copy in from base type if (!TypeBeingBuilt.IsValueType && (TypeBeingBuilt.BaseType != null)) { DefType baseType = TypeBeingBuilt.BaseType; // Capture the gc layout from the base type TypeBuilder.GCLayout baseTypeLayout = GetInstanceGCLayout(baseType); if (!baseTypeLayout.IsNone) { instanceGCLayout = new LowLevelList<bool>(); baseTypeLayout.WriteToBitfield(instanceGCLayout, IntPtr.Size /* account for the EEType pointer */); } } foreach (FieldDesc field in GetFieldsForGCLayout()) { if (field.IsStatic) continue; if (field.IsLiteral) continue; TypeBuilder.GCLayout fieldGcLayout = GetFieldGCLayout(field.FieldType); if (!fieldGcLayout.IsNone) { if (instanceGCLayout == null) instanceGCLayout = new LowLevelList<bool>(); fieldGcLayout.WriteToBitfield(instanceGCLayout, field.Offset.AsInt); } } if ((instanceGCLayout != null) && instanceGCLayout.HasSetBits()) { // When bits are set in the instance GC layout, it implies that the type contains GC refs, // which implies that the type size is pointer-aligned. In this case consumers assume that // the type size can be computed by multiplying the bitfield size by the pointer size. If // necessary, expand the bitfield to ensure that this invariant holds. // Valuetypes with gc fields must be aligned on at least pointer boundaries Debug.Assert(!TypeBeingBuilt.IsValueType || (FieldAlignment.Value >= TypeBeingBuilt.Context.Target.PointerSize)); // Valuetypes with gc fields must have a type size which is aligned on an IntPtr boundary. Debug.Assert(!TypeBeingBuilt.IsValueType || ((TypeSize.Value & (IntPtr.Size - 1)) == 0)); int impliedBitCount = (TypeSize.Value + IntPtr.Size - 1) / IntPtr.Size; Debug.Assert(instanceGCLayout.Count <= impliedBitCount); instanceGCLayout.Expand(impliedBitCount); Debug.Assert(instanceGCLayout.Count == impliedBitCount); } } if (instanceGCLayout == null) _instanceGCLayout = s_emptyLayout; else _instanceGCLayout = instanceGCLayout; } } if (_instanceGCLayout == s_emptyLayout) return null; else return _instanceGCLayout; } } public LowLevelList<bool> StaticGCLayout; public LowLevelList<bool> ThreadStaticGCLayout; private bool _staticGCLayoutPrepared; /// <summary> /// Prepare the StaticGCLayout/ThreadStaticGCLayout/GcStaticDesc/ThreadStaticDesc fields by /// reading native layout or metadata as appropriate. This method should only be called for types which /// are actually to be created. /// </summary> public void PrepareStaticGCLayout() { if (!_staticGCLayoutPrepared) { _staticGCLayoutPrepared = true; DefType defType = TypeBeingBuilt as DefType; if (defType == null) { // Array/pointer types do not have static fields } else if (defType.IsTemplateCanonical()) { // Canonical templates get their layout directly from the NativeLayoutInfo. // Parse it and pull that info out here. NativeParser typeInfoParser = GetParserForNativeLayoutInfo(); BagElementKind kind; while ((kind = typeInfoParser.GetBagElementKind()) != BagElementKind.End) { switch (kind) { case BagElementKind.GcStaticDesc: GcStaticDesc = NativeLayoutInfo.LoadContext.GetGCStaticInfo(typeInfoParser.GetUnsigned()); break; case BagElementKind.ThreadStaticDesc: ThreadStaticDesc = NativeLayoutInfo.LoadContext.GetGCStaticInfo(typeInfoParser.GetUnsigned()); break; case BagElementKind.GcStaticEEType: GcStaticEEType = NativeLayoutInfo.LoadContext.GetGCStaticInfo(typeInfoParser.GetUnsigned()); break; default: typeInfoParser.SkipInteger(); break; } } } else { // Compute GC layout boolean array from field information. IEnumerable<FieldDesc> fields = GetFieldsForGCLayout(); LowLevelList<bool> threadStaticLayout = null; LowLevelList<bool> gcStaticLayout = null; foreach (FieldDesc field in fields) { if (!field.IsStatic) continue; if (field.IsLiteral) continue; LowLevelList<bool> gcLayoutInfo = null; if (field.IsThreadStatic) { if (threadStaticLayout == null) threadStaticLayout = new LowLevelList<bool>(); gcLayoutInfo = threadStaticLayout; } else if (field.HasGCStaticBase) { if (gcStaticLayout == null) gcStaticLayout = new LowLevelList<bool>(); gcLayoutInfo = gcStaticLayout; } else { // Non-GC static no need to record information continue; } TypeBuilder.GCLayout fieldGcLayout = GetFieldGCLayout(field.FieldType); fieldGcLayout.WriteToBitfield(gcLayoutInfo, field.Offset.AsInt); } if (gcStaticLayout != null && gcStaticLayout.Count > 0) StaticGCLayout = gcStaticLayout; if (threadStaticLayout != null && threadStaticLayout.Count > 0) ThreadStaticGCLayout = threadStaticLayout; } } } /// <summary> /// Get an enumerable list of the fields used for dynamic gc layout calculation. /// </summary> private IEnumerable<FieldDesc> GetFieldsForGCLayout() { DefType defType = (DefType)TypeBeingBuilt; IEnumerable<FieldDesc> fields; if (defType.ComputeTemplate(false) != null) { // we have native layout and a template. Use the NativeLayoutFields as that is the only complete // description of the fields available. (There may be metadata fields, but those aren't guaranteed // to be a complete set of fields due to reflection reduction. NativeLayoutFieldAlgorithm.EnsureFieldLayoutLoadedForGenericType(defType); fields = defType.NativeLayoutFields; } else { // The metadata case. We're loading the type from regular metadata, so use the regular metadata fields fields = defType.GetFields(); } return fields; } // Get the GC layout of a type. Handles pre-created, universal template, and non-universal template cases // Only to be used for getting the instance layout of non-valuetypes. /// <summary> /// Get the GC layout of a type. Handles pre-created, universal template, and non-universal template cases /// Only to be used for getting the instance layout of non-valuetypes that are used as base types /// </summary> /// <param name="type"></param> /// <returns></returns> private unsafe TypeBuilder.GCLayout GetInstanceGCLayout(TypeDesc type) { Debug.Assert(!type.IsCanonicalSubtype(CanonicalFormKind.Any)); Debug.Assert(!type.IsValueType); if (type.RetrieveRuntimeTypeHandleIfPossible()) { return new TypeBuilder.GCLayout(type.RuntimeTypeHandle); } if (type.IsTemplateCanonical()) { var templateType = type.ComputeTemplate(); bool success = templateType.RetrieveRuntimeTypeHandleIfPossible(); Debug.Assert(success && !templateType.RuntimeTypeHandle.IsNull()); return new TypeBuilder.GCLayout(templateType.RuntimeTypeHandle); } else { TypeBuilderState state = type.GetOrCreateTypeBuilderState(); if (state.InstanceGCLayout == null) return TypeBuilder.GCLayout.None; else return new TypeBuilder.GCLayout(state.InstanceGCLayout, true); } } /// <summary> /// Get the GC layout of a type when used as a field. /// NOTE: if the fieldtype is a reference type, this function will return GCLayout.None /// Consumers of the api must handle that special case. /// </summary> private unsafe TypeBuilder.GCLayout GetFieldGCLayout(TypeDesc fieldType) { if (!fieldType.IsValueType) { if (fieldType.IsPointer) return TypeBuilder.GCLayout.None; else return TypeBuilder.GCLayout.SingleReference; } // Is this a type that already exists? If so, get its gclayout from the EEType directly if (fieldType.RetrieveRuntimeTypeHandleIfPossible()) { return new TypeBuilder.GCLayout(fieldType.RuntimeTypeHandle); } // The type of the field must be a valuetype that is dynamically being constructed if (fieldType.IsTemplateCanonical()) { // Pull the GC Desc from the canonical instantiation TypeDesc templateType = fieldType.ComputeTemplate(); bool success = templateType.RetrieveRuntimeTypeHandleIfPossible(); Debug.Assert(success); return new TypeBuilder.GCLayout(templateType.RuntimeTypeHandle); } else { // Use the type builder state's computed InstanceGCLayout var instanceGCLayout = fieldType.GetOrCreateTypeBuilderState().InstanceGCLayout; if (instanceGCLayout == null) return TypeBuilder.GCLayout.None; return new TypeBuilder.GCLayout(instanceGCLayout, false /* Always represents a valuetype as the reference type case is handled above with the GCLayout.SingleReference return */); } } public bool IsArrayOfReferenceTypes { get { ArrayType typeAsArrayType = TypeBeingBuilt as ArrayType; if (typeAsArrayType != null) return !typeAsArrayType.ParameterType.IsValueType && !typeAsArrayType.ParameterType.IsPointer; else return false; } } // Rank for arrays, -1 is used for an SzArray, and a positive number for a multidimensional array. public int? ArrayRank { get { if (!TypeBeingBuilt.IsArray) return null; else if (TypeBeingBuilt.IsSzArray) return -1; else { Debug.Assert(TypeBeingBuilt.IsMdArray); return ((ArrayType)TypeBeingBuilt).Rank; } } } public int? BaseTypeSize { get { if (TypeBeingBuilt.BaseType == null) { return null; } else { return TypeBeingBuilt.BaseType.InstanceByteCountUnaligned.AsInt; } } } public int? TypeSize { get { DefType defType = TypeBeingBuilt as DefType; if (defType != null) { // Generic Type Definition EETypes do not have size if (defType.IsGenericDefinition) return null; if (defType.IsValueType) { return defType.InstanceFieldSize.AsInt; } else { if (defType.IsInterface) return IntPtr.Size; return defType.InstanceByteCountUnaligned.AsInt; } } else if (TypeBeingBuilt is ArrayType) { int basicArraySize = TypeBeingBuilt.BaseType.InstanceByteCountUnaligned.AsInt; if (TypeBeingBuilt.IsMdArray) { // MD Arrays are arranged like normal arrays, but they also have 2 int's per rank for the individual dimension loBounds and range. basicArraySize += ((ArrayType)TypeBeingBuilt).Rank * sizeof(int) * 2; } return basicArraySize; } else { return null; } } } public int? UnalignedTypeSize { get { DefType defType = TypeBeingBuilt as DefType; if (defType != null) { return defType.InstanceByteCountUnaligned.AsInt; } else if (TypeBeingBuilt is ArrayType) { // Arrays use the same algorithm for TypeSize as for UnalignedTypeSize return TypeSize; } else { return 0; } } } public int? FieldAlignment { get { if (TypeBeingBuilt is DefType) { return checked((ushort)((DefType)TypeBeingBuilt).InstanceFieldAlignment.AsInt); } else if (TypeBeingBuilt is ArrayType) { ArrayType arrayType = (ArrayType)TypeBeingBuilt; if (arrayType.ElementType is DefType) { return checked((ushort)((DefType)arrayType.ElementType).InstanceFieldAlignment.AsInt); } else { return (ushort)arrayType.Context.Target.PointerSize; } } else if (TypeBeingBuilt is PointerType || TypeBeingBuilt is ByRefType) { return (ushort)TypeBeingBuilt.Context.Target.PointerSize; } else { return null; } } } public ushort? ComponentSize { get { ArrayType arrayType = TypeBeingBuilt as ArrayType; if (arrayType != null) { if (arrayType.ElementType is DefType) { uint size = (uint)((DefType)arrayType.ElementType).InstanceFieldSize.AsInt; if (size > ArrayTypesConstants.MaxSizeForValueClassInArray && arrayType.ElementType.IsValueType) ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadValueClassTooLarge, arrayType.ElementType); return checked((ushort)size); } else { return (ushort)arrayType.Context.Target.PointerSize; } } else { return null; } } } public uint NullableValueOffset { get { if (!TypeBeingBuilt.IsNullable) return 0; if (TypeBeingBuilt.IsTemplateCanonical()) { // Pull the GC Desc from the canonical instantiation TypeDesc templateType = TypeBeingBuilt.ComputeTemplate(); bool success = templateType.RetrieveRuntimeTypeHandleIfPossible(); Debug.Assert(success); unsafe { return templateType.RuntimeTypeHandle.ToEETypePtr()->NullableValueOffset; } } else { int fieldCount = 0; uint nullableValueOffset = 0; foreach (FieldDesc f in GetFieldsForGCLayout()) { if (fieldCount == 1) { nullableValueOffset = checked((uint)f.Offset.AsInt); } fieldCount++; } // Nullable<T> only has two fields. HasValue and Value Debug.Assert(fieldCount == 2); return nullableValueOffset; } } } public bool IsHFA { get { #if ARM if (TypeBeingBuilt is DefType) { return ((DefType)TypeBeingBuilt).IsHfa; } else { return false; } #else // On Non-ARM platforms, HFA'ness is not encoded in the EEType as it doesn't effect ABI return false; #endif } } public VTableLayoutInfo[] VTableMethodSignatures; public int NumSealedVTableMethodSignatures; public VTableSlotMapper VTableSlotsMapping; #if GENERICS_FORCE_USG public TypeDesc NonUniversalTemplateType; public int NonUniversalInstanceGCDescSize; public IntPtr NonUniversalInstanceGCDesc; public IntPtr NonUniversalStaticGCDesc; public IntPtr NonUniversalThreadStaticGCDesc; #endif } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsAzureSpecials { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// XMsClientRequestIdOperations operations. /// </summary> internal partial class XMsClientRequestIdOperations : IServiceOperations<AutoRestAzureSpecialParametersTestClient>, IXMsClientRequestIdOperations { /// <summary> /// Initializes a new instance of the XMsClientRequestIdOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal XMsClientRequestIdOperations(AutoRestAzureSpecialParametersTestClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestAzureSpecialParametersTestClient /// </summary> public AutoRestAzureSpecialParametersTestClient Client { get; private set; } /// <summary> /// Get method that overwrites x-ms-client-request header with value /// 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> GetWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/overwrite/x-ms-client-request-id/method/").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get method that overwrites x-ms-client-request header with value /// 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. /// </summary> /// <param name='xMsClientRequestId'> /// This should appear as a method parameter, use value /// '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> ParamGetWithHttpMessagesAsync(string xMsClientRequestId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (xMsClientRequestId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "xMsClientRequestId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("xMsClientRequestId", xMsClientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ParamGet", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "azurespecials/overwrite/x-ms-client-request-id/via-param/method/").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (xMsClientRequestId != null) { if (_httpRequest.Headers.Contains("x-ms-client-request-id")) { _httpRequest.Headers.Remove("x-ms-client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", xMsClientRequestId); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// // 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.Management.HDInsight.Job; using Microsoft.Azure.Management.HDInsight.Job.Models; namespace Microsoft.Azure.Management.HDInsight.Job { /// <summary> /// The HDInsight job client manages jobs against HDInsight clusters. /// </summary> public static partial class JobOperationsExtensions { /// <summary> /// Gets the list of jobs from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Required. The id of the job. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static JobGetResponse GetJob(this IJobOperations operations, string jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetJobAsync(jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of jobs from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Required. The id of the job. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static Task<JobGetResponse> GetJobAsync(this IJobOperations operations, string jobId) { return operations.GetJobAsync(jobId, CancellationToken.None); } /// <summary> /// Gets the list of jobs from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Required. The id of the job. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static JobGetResponse KillJob(this IJobOperations operations, string jobId) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).KillJobAsync(jobId); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of jobs from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='jobId'> /// Required. The id of the job. /// </param> /// <returns> /// The Get Job operation response. /// </returns> public static Task<JobGetResponse> KillJobAsync(this IJobOperations operations, string jobId) { return operations.KillJobAsync(jobId, CancellationToken.None); } /// <summary> /// Gets the list of jobs from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <returns> /// The List Job operation response. /// </returns> public static JobListResponse ListJobs(this IJobOperations operations) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ListJobsAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the list of jobs from the specified HDInsight cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <returns> /// The List Job operation response. /// </returns> public static Task<JobListResponse> ListJobsAsync(this IJobOperations operations) { return operations.ListJobsAsync(CancellationToken.None); } /// <summary> /// Submits an Hive job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Hive job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitHiveJob(this IJobOperations operations, HiveJobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitHiveJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits an Hive job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Hive job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitHiveJobAsync(this IJobOperations operations, HiveJobSubmissionParameters parameters) { return operations.SubmitHiveJobAsync(parameters, CancellationToken.None); } /// <summary> /// Submits a MapReduce job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. MapReduce job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitMapReduceJob(this IJobOperations operations, MapReduceJobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitMapReduceJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits a MapReduce job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. MapReduce job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitMapReduceJobAsync(this IJobOperations operations, MapReduceJobSubmissionParameters parameters) { return operations.SubmitMapReduceJobAsync(parameters, CancellationToken.None); } /// <summary> /// Submits a MapReduce streaming job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. MapReduce job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitMapReduceStreamingJob(this IJobOperations operations, MapReduceStreamingJobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitMapReduceStreamingJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits a MapReduce streaming job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. MapReduce job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitMapReduceStreamingJobAsync(this IJobOperations operations, MapReduceStreamingJobSubmissionParameters parameters) { return operations.SubmitMapReduceStreamingJobAsync(parameters, CancellationToken.None); } /// <summary> /// Submits an Hive job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Pig job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitPigJob(this IJobOperations operations, PigJobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitPigJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits an Hive job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Pig job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitPigJobAsync(this IJobOperations operations, PigJobSubmissionParameters parameters) { return operations.SubmitPigJobAsync(parameters, CancellationToken.None); } /// <summary> /// Submits an Sqoop job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Sqoop job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static JobSubmissionResponse SubmitSqoopJob(this IJobOperations operations, SqoopJobSubmissionParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).SubmitSqoopJobAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Submits an Sqoop job to an HDINSIGHT cluster. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.HDInsight.Job.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Sqoop job parameters. /// </param> /// <returns> /// The Create Job operation response. /// </returns> public static Task<JobSubmissionResponse> SubmitSqoopJobAsync(this IJobOperations operations, SqoopJobSubmissionParameters parameters) { return operations.SubmitSqoopJobAsync(parameters, CancellationToken.None); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using Microsoft.Rest.Azure; using Models; /// <summary> /// PagingOperations operations. /// </summary> public partial interface IPagingOperations { /// <summary> /// A paging operation that finishes on the first call without a /// nextlink /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetMultiplePagesOptionsInner pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that includes a nextLink in odata format that /// has 10 pages /// </summary> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetOdataMultiplePagesWithHttpMessagesAsync(string clientRequestId = default(string), PagingGetOdataMultiplePagesOptionsInner pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='pagingGetMultiplePagesWithOffsetOptions'> /// Additional parameters for the operation /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesWithOffsetWithHttpMessagesAsync(PagingGetMultiplePagesWithOffsetOptionsInner pagingGetMultiplePagesWithOffsetOptions, string clientRequestId = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that fails on the first call with 500 and then /// retries and then get a response including a nextLink that has 10 /// pages /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetryFirstWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of /// which the 2nd call fails first with 500. The client should retry /// and finish all 10 pages eventually. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetrySecondWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesFailureWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureUriWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFragmentNextLinkWithHttpMessagesAsync(string apiVersion, string tenant, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// with parameters grouped /// </summary> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFragmentWithGroupingNextLinkWithHttpMessagesAsync(CustomParameterGroupInner customParameterGroup, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='apiVersion'> /// Sets the api version to use. /// </param> /// <param name='tenant'> /// Sets the tenant to use. /// </param> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> NextFragmentWithHttpMessagesAsync(string apiVersion, string tenant, string nextLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that doesn't return a full URL, just a fragment /// </summary> /// <param name='nextLink'> /// Next link for list operation. /// </param> /// <param name='customParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> NextFragmentWithGroupingWithHttpMessagesAsync(string nextLink, CustomParameterGroupInner customParameterGroup, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that finishes on the first call without a /// nextlink /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesOptionsInner pagingGetMultiplePagesOptions = default(PagingGetMultiplePagesOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that includes a nextLink in odata format that /// has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetOdataMultiplePagesOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetOdataMultiplePagesNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetOdataMultiplePagesOptionsInner pagingGetOdataMultiplePagesOptions = default(PagingGetOdataMultiplePagesOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='clientRequestId'> /// </param> /// <param name='pagingGetMultiplePagesWithOffsetNextOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesWithOffsetNextWithHttpMessagesAsync(string nextPageLink, string clientRequestId = default(string), PagingGetMultiplePagesWithOffsetNextOptionsInner pagingGetMultiplePagesWithOffsetNextOptions = default(PagingGetMultiplePagesWithOffsetNextOptionsInner), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that fails on the first call with 500 and then /// retries and then get a response including a nextLink that has 10 /// pages /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of /// which the 2nd call fails first with 500. The client should retry /// and finish all 10 pages eventually. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetSinglePagesFailureNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Product>>> GetMultiplePagesFailureUriNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
// 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.ComponentModel; using System.IO; using System.IO.Pipes; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; namespace System.Data.SqlClient.SNI { /// <summary> /// Named Pipe connection handle /// </summary> internal class SNINpHandle : SNIHandle { internal const string DefaultPipePath = @"sql\query"; // e.g. \\HOSTNAME\pipe\sql\query private const int MAX_PIPE_INSTANCES = 255; private readonly string _targetServer; private readonly object _callbackObject; private Stream _stream; private NamedPipeClientStream _pipeStream; private SslOverTdsStream _sslOverTdsStream; private SslStream _sslStream; private SNIAsyncCallback _receiveCallback; private SNIAsyncCallback _sendCallback; private bool _validateCert = true; private readonly uint _status = TdsEnums.SNI_UNINITIALIZED; private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE; private readonly Guid _connectionId = Guid.NewGuid(); public SNINpHandle(string serverName, string pipeName, long timerExpire, object callbackObject) { _targetServer = serverName; _callbackObject = callbackObject; try { _pipeStream = new NamedPipeClientStream( serverName, pipeName, PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough); bool isInfiniteTimeOut = long.MaxValue == timerExpire; if (isInfiniteTimeOut) { _pipeStream.Connect(Threading.Timeout.Infinite); } else { TimeSpan ts = DateTime.FromFileTime(timerExpire) - DateTime.Now; ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts; _pipeStream.Connect((int)ts.TotalMilliseconds); } } catch(TimeoutException te) { SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, te); _status = TdsEnums.SNI_ERROR; return; } catch(IOException ioe) { SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe); _status = TdsEnums.SNI_ERROR; return; } if (!_pipeStream.IsConnected || !_pipeStream.CanWrite || !_pipeStream.CanRead) { SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, string.Empty); _status = TdsEnums.SNI_ERROR; return; } _sslOverTdsStream = new SslOverTdsStream(_pipeStream); _sslStream = new SslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); _stream = _pipeStream; _status = TdsEnums.SNI_SUCCESS; } public override Guid ConnectionId { get { return _connectionId; } } public override uint Status { get { return _status; } } public override uint CheckConnection() { if (!_stream.CanWrite || !_stream.CanRead) { return TdsEnums.SNI_ERROR; } else { return TdsEnums.SNI_SUCCESS; } } public override void Dispose() { lock (this) { if (_sslOverTdsStream != null) { _sslOverTdsStream.Dispose(); _sslOverTdsStream = null; } if (_sslStream != null) { _sslStream.Dispose(); _sslStream = null; } if (_pipeStream != null) { _pipeStream.Dispose(); _pipeStream = null; } //Release any references held by _stream. _stream = null; } } public override uint Receive(out SNIPacket packet, int timeout) { lock (this) { packet = null; try { packet = new SNIPacket(_bufferSize); packet.ReadFromStream(_stream); if (packet.Length == 0) { var e = new Win32Exception(); return ReportErrorAndReleasePacket(packet, (uint)e.NativeErrorCode, 0, e.Message); } } catch (ObjectDisposedException ode) { return ReportErrorAndReleasePacket(packet, ode); } catch (IOException ioe) { return ReportErrorAndReleasePacket(packet, ioe); } return TdsEnums.SNI_SUCCESS; } } public override uint ReceiveAsync(ref SNIPacket packet) { packet = new SNIPacket(_bufferSize); try { packet.ReadFromStreamAsync(_stream, _receiveCallback); return TdsEnums.SNI_SUCCESS_IO_PENDING; } catch (ObjectDisposedException ode) { return ReportErrorAndReleasePacket(packet, ode); } catch (IOException ioe) { return ReportErrorAndReleasePacket(packet, ioe); } } public override uint Send(SNIPacket packet) { lock (this) { try { packet.WriteToStream(_stream); return TdsEnums.SNI_SUCCESS; } catch (ObjectDisposedException ode) { return ReportErrorAndReleasePacket(packet, ode); } catch (IOException ioe) { return ReportErrorAndReleasePacket(packet, ioe); } } } public override uint SendAsync(SNIPacket packet, bool disposePacketAfterSendAsync, SNIAsyncCallback callback = null) { SNIAsyncCallback cb = callback ?? _sendCallback; packet.WriteToStreamAsync(_stream, cb, SNIProviders.NP_PROV, disposePacketAfterSendAsync); return TdsEnums.SNI_SUCCESS_IO_PENDING; } public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback) { _receiveCallback = receiveCallback; _sendCallback = sendCallback; } public override uint EnableSsl(uint options) { _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0; try { _sslStream.AuthenticateAsClientAsync(_targetServer).GetAwaiter().GetResult(); _sslOverTdsStream.FinishHandshake(); } catch (AuthenticationException aue) { return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, aue); } catch (InvalidOperationException ioe) { return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, ioe); } _stream = _sslStream; return TdsEnums.SNI_SUCCESS; } public override void DisableSsl() { _sslStream.Dispose(); _sslStream = null; _sslOverTdsStream.Dispose(); _sslOverTdsStream = null; _stream = _pipeStream; } /// <summary> /// Validate server certificate /// </summary> /// <param name="sender">Sender object</param> /// <param name="cert">X.509 certificate</param> /// <param name="chain">X.509 chain</param> /// <param name="policyErrors">Policy errors</param> /// <returns>true if valid</returns> private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors) { if (!_validateCert) { return true; } return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors); } /// <summary> /// Set buffer size /// </summary> /// <param name="bufferSize">Buffer size</param> public override void SetBufferSize(int bufferSize) { _bufferSize = bufferSize; } private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException) { if (packet != null) { packet.Release(); } return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, sniException); } private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage) { if (packet != null) { packet.Release(); } return SNICommon.ReportSNIError(SNIProviders.NP_PROV, nativeError, sniError, errorMessage); } #if DEBUG /// <summary> /// Test handle for killing underlying connection /// </summary> public override void KillConnection() { _pipeStream.Dispose(); _pipeStream = null; } #endif } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.Management.Infrastructure; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Cmdletization.Cim { /// <summary> /// CIM-specific ObjectModelWrapper. /// </summary> public sealed class CimCmdletAdapter : SessionBasedCmdletAdapter<CimInstance, CimSession>, IDynamicParameters { #region Special method and parameter names internal const string CreateInstance_MethodName = "cim:CreateInstance"; internal const string ModifyInstance_MethodName = "cim:ModifyInstance"; internal const string DeleteInstance_MethodName = "cim:DeleteInstance"; #endregion #region Changing Session parameter to CimSession /// <summary> /// CimSession to operate on. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [Alias("Session")] public CimSession[] CimSession { get { return base.Session; } set { base.Session = value; } } /// <summary> /// Maximum number of remote connections that can remain active at any given time. /// </summary> [Parameter] public override int ThrottleLimit { get { if (_throttleLimitIsSetExplicitly) { return base.ThrottleLimit; } return this.CmdletDefinitionContext.DefaultThrottleLimit; } set { base.ThrottleLimit = value; _throttleLimitIsSetExplicitly = true; } } private bool _throttleLimitIsSetExplicitly; #endregion #region ObjectModelWrapper overrides /// <summary> /// Creates a query builder for CIM OM. /// </summary> /// <returns>Query builder for CIM OM.</returns> public override QueryBuilder GetQueryBuilder() { return new CimQuery(); } internal CimCmdletInvocationContext CmdletInvocationContext { get { return _cmdletInvocationContext ?? (_cmdletInvocationContext = new CimCmdletInvocationContext( this.CmdletDefinitionContext, this.Cmdlet, this.GetDynamicNamespace())); } } private CimCmdletInvocationContext _cmdletInvocationContext; internal CimCmdletDefinitionContext CmdletDefinitionContext { get { if (_cmdletDefinitionContext == null) { _cmdletDefinitionContext = new CimCmdletDefinitionContext( this.ClassName, this.ClassVersion, this.ModuleVersion, this.Cmdlet.CommandInfo.CommandMetadata.SupportsShouldProcess, this.PrivateData); } return _cmdletDefinitionContext; } } private CimCmdletDefinitionContext _cmdletDefinitionContext; internal InvocationInfo CmdletInvocationInfo { get { return this.CmdletInvocationContext.CmdletInvocationInfo; } } #endregion ObjectModelWrapper overrides #region SessionBasedCmdletAdapter overrides private static long s_jobNumber; /// <summary> /// Returns a new job name to use for the parent job that handles throttling of the child jobs that actually perform querying and method invocation. /// </summary> /// <returns>Job name.</returns> protected override string GenerateParentJobName() { return "CimJob" + Interlocked.Increment(ref CimCmdletAdapter.s_jobNumber).ToString(CultureInfo.InvariantCulture); } /// <summary> /// Returns default sessions to use when the user doesn't specify the -Session cmdlet parameter. /// </summary> /// <returns>Default sessions to use when the user doesn't specify the -Session cmdlet parameter.</returns> protected override CimSession DefaultSession { get { return this.CmdletInvocationContext.GetDefaultCimSession(); } } private CimJobContext CreateJobContext(CimSession session, object targetObject) { return new CimJobContext( this.CmdletInvocationContext, session, targetObject); } /// <summary> /// Creates a <see cref="System.Management.Automation.Job"/> object that performs a query against the wrapped object model. /// </summary> /// <param name="session">Remote session to query.</param> /// <param name="baseQuery">Query parameters.</param> /// <returns><see cref="System.Management.Automation.Job"/> object that performs a query against the wrapped object model.</returns> internal override StartableJob CreateQueryJob(CimSession session, QueryBuilder baseQuery) { CimQuery query = baseQuery as CimQuery; if (query == null) { throw new ArgumentNullException("baseQuery"); } TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.CmdletInvocationInfo, isStaticCmdlet: false); if (tracker.IsSessionTerminated(session)) { return null; } if (!IsSupportedSession(session, tracker)) { return null; } CimJobContext jobContext = this.CreateJobContext(session, targetObject: null); StartableJob queryJob = query.GetQueryJob(jobContext); return queryJob; } /// <summary> /// Creates a <see cref="System.Management.Automation.Job"/> object that invokes an instance method in the wrapped object model. /// </summary> /// <param name="session">Remote session to invoke the method in.</param> /// <param name="objectInstance">The object on which to invoke the method.</param> /// <param name="methodInvocationInfo">Method invocation details.</param> /// <param name="passThru"><c>true</c> if successful method invocations should emit downstream the <paramref name="objectInstance"/> being operated on.</param> /// <returns></returns> internal override StartableJob CreateInstanceMethodInvocationJob(CimSession session, CimInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) { TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.CmdletInvocationInfo, isStaticCmdlet: false); if (tracker.IsSessionTerminated(session)) { return null; } if (!IsSupportedSession(session, tracker)) { return null; } CimJobContext jobContext = this.CreateJobContext(session, objectInstance); Dbg.Assert(objectInstance != null, "Caller should verify objectInstance != null"); StartableJob result; if (methodInvocationInfo.MethodName.Equals(CimCmdletAdapter.DeleteInstance_MethodName, StringComparison.OrdinalIgnoreCase)) { result = new DeleteInstanceJob( jobContext, passThru, objectInstance, methodInvocationInfo); } else if (methodInvocationInfo.MethodName.Equals(CimCmdletAdapter.ModifyInstance_MethodName, StringComparison.OrdinalIgnoreCase)) { result = new ModifyInstanceJob( jobContext, passThru, objectInstance, methodInvocationInfo); } else { result = new InstanceMethodInvocationJob( jobContext, passThru, objectInstance, methodInvocationInfo); } return result; } private bool IsSupportedSession(CimSession cimSession, TerminatingErrorTracker terminatingErrorTracker) { bool confirmSwitchSpecified = this.CmdletInvocationInfo.BoundParameters.ContainsKey("Confirm"); bool whatIfSwitchSpecified = this.CmdletInvocationInfo.BoundParameters.ContainsKey("WhatIf"); if (confirmSwitchSpecified || whatIfSwitchSpecified) { if (cimSession.ComputerName != null && (!cimSession.ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))) { PSPropertyInfo protocolProperty = PSObject.AsPSObject(cimSession).Properties["Protocol"]; if ((protocolProperty != null) && (protocolProperty.Value != null) && (protocolProperty.Value.ToString().Equals("DCOM", StringComparison.OrdinalIgnoreCase))) { bool sessionWasAlreadyTerminated; terminatingErrorTracker.MarkSessionAsTerminated(cimSession, out sessionWasAlreadyTerminated); if (!sessionWasAlreadyTerminated) { string nameOfUnsupportedSwitch; if (confirmSwitchSpecified) { nameOfUnsupportedSwitch = "-Confirm"; } else { Dbg.Assert(whatIfSwitchSpecified, "Confirm and WhatIf are the only detected settings"); nameOfUnsupportedSwitch = "-WhatIf"; } string errorMessage = string.Format( CultureInfo.InvariantCulture, CmdletizationResources.CimCmdletAdapter_RemoteDcomDoesntSupportExtendedSemantics, cimSession.ComputerName, nameOfUnsupportedSwitch); Exception exception = new NotSupportedException(errorMessage); ErrorRecord errorRecord = new ErrorRecord( exception, "NoExtendedSemanticsSupportInRemoteDcomProtocol", ErrorCategory.NotImplemented, cimSession); this.Cmdlet.WriteError(errorRecord); } } } } return true; } /// <summary> /// Creates a <see cref="System.Management.Automation.Job"/> object that invokes a static method /// (of the class named by <see cref="Microsoft.PowerShell.Cmdletization.CmdletAdapter&lt;TObjectInstance&gt;.ClassName"/>) /// in the wrapped object model. /// </summary> /// <param name="session">Remote session to invoke the method in.</param> /// <param name="methodInvocationInfo">Method invocation details.</param> internal override StartableJob CreateStaticMethodInvocationJob(CimSession session, MethodInvocationInfo methodInvocationInfo) { TerminatingErrorTracker tracker = TerminatingErrorTracker.GetTracker(this.CmdletInvocationInfo, isStaticCmdlet: true); if (tracker.IsSessionTerminated(session)) { return null; } if (!IsSupportedSession(session, tracker)) { return null; } CimJobContext jobContext = this.CreateJobContext(session, targetObject: null); StartableJob result; if (methodInvocationInfo.MethodName.Equals(CimCmdletAdapter.CreateInstance_MethodName, StringComparison.OrdinalIgnoreCase)) { result = new CreateInstanceJob( jobContext, methodInvocationInfo); } else { result = new StaticMethodInvocationJob( jobContext, methodInvocationInfo); } return result; } #endregion SessionBasedCmdletAdapter overrides #region Session affinity management private static readonly ConditionalWeakTable<CimInstance, CimSession> s_cimInstanceToSessionOfOrigin = new ConditionalWeakTable<CimInstance, CimSession>(); internal static void AssociateSessionOfOriginWithInstance(CimInstance cimInstance, CimSession sessionOfOrigin) { // GetValue adds value to the table, if the key is not present in the table s_cimInstanceToSessionOfOrigin.GetValue(cimInstance, _ => sessionOfOrigin); } internal static CimSession GetSessionOfOriginFromCimInstance(CimInstance instance) { CimSession result = null; if (instance != null) { s_cimInstanceToSessionOfOrigin.TryGetValue(instance, out result); } return result; } internal override CimSession GetSessionOfOriginFromInstance(CimInstance instance) { return GetSessionOfOriginFromCimInstance(instance); } #endregion #region Handling of dynamic parameters private RuntimeDefinedParameterDictionary _dynamicParameters; private const string CimNamespaceParameter = "CimNamespace"; private string GetDynamicNamespace() { if (_dynamicParameters == null) { return null; } RuntimeDefinedParameter runtimeParameter; if (!_dynamicParameters.TryGetValue(CimNamespaceParameter, out runtimeParameter)) { return null; } return runtimeParameter.Value as string; } object IDynamicParameters.GetDynamicParameters() { if (_dynamicParameters == null) { _dynamicParameters = new RuntimeDefinedParameterDictionary(); if (this.CmdletDefinitionContext.ExposeCimNamespaceParameter) { Collection<Attribute> namespaceAttributes = new Collection<Attribute>(); namespaceAttributes.Add(new ValidateNotNullOrEmptyAttribute()); namespaceAttributes.Add(new ParameterAttribute()); RuntimeDefinedParameter namespaceRuntimeParameter = new RuntimeDefinedParameter( CimNamespaceParameter, typeof(string), namespaceAttributes); _dynamicParameters.Add(CimNamespaceParameter, namespaceRuntimeParameter); } } return _dynamicParameters; } #endregion } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Forms; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Ole = Microsoft.VisualStudio.OLE.Interop; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using IServiceProvider = System.IServiceProvider; using Microsoft.VisualStudio.FSharp.LanguageService.Resources; namespace Microsoft.VisualStudio.FSharp.LanguageService { /// <summary> /// CodeWindowManager provides a default implementation of the VSIP interface IVsCodeWindowManager /// and manages the LanguageService, Source, ViewFilter, and DocumentProperties objects associated /// with the given IVsCodeWindow. It calls CreateViewFilter on your LanguageService for each new /// IVsTextView created by Visual Studio and installs the resulting filter into the command chain. /// You do not have to override this method, since a default view filter will be created. #if DOCUMENT_PROPERTIES /// If your LanguageService returns an object from CreateDocumentProperties then you will have /// properties in the Properties Window associated with your source files. #endif /// The CodeWindowManager also provides support for optional drop down combos in the IVsDropdownBar for /// listing types and members by installing the TypeAndMemberDropdownBars object returned from your /// LanguageService CreateDropDownHelper method. The default return from CreateDropDownHelper is null, /// which results in no drop down combos. /// </summary> [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(true)] public class CodeWindowManager : IVsCodeWindowManager { TypeAndMemberDropdownBars dropDownHelper; IVsCodeWindow codeWindow; ArrayList viewFilters; LanguageService service; ISource source; #if DOCUMENT_PROPERTIES DocumentProperties properties; #endif /// <summary> /// The CodeWindowManager is constructed by the base LanguageService class when VS calls /// the IVsLanguageInfo.GetCodeWindowManager method. You can override CreateCodeWindowManager /// on your LanguageService if you want to plug in a different CodeWindowManager. /// </summary> internal CodeWindowManager(LanguageService service, IVsCodeWindow codeWindow, ISource source) { this.service = service; this.codeWindow = codeWindow; this.viewFilters = new ArrayList(); this.source = source; #if DOCUMENT_PROPERTIES this.properties = service.CreateDocumentProperties(this); #endif } ~CodeWindowManager() { #if LANGTRACE Trace.WriteLine("~CodeWindowManager"); #endif } /// <summary>Closes all view filters, and the document properties window</summary> internal void Close() { #if LANGTRACE Trace.WriteLine("CodeWindowManager::Close"); #endif #if DOCUMENT_PROPERTIES if (this.properties != null) this.properties.Close(); #endif CloseFilters(); this.viewFilters = null; #if DOCUMENT_PROPERTIES properties = null; #endif service = null; source = null; this.codeWindow = null; } void CloseFilters() { if (this.viewFilters != null) { foreach (ViewFilter f in this.viewFilters) { f.Close(); } this.viewFilters.Clear(); } } /// <summary>Returns the LanguageService object that created this code window manager</summary> internal LanguageService LanguageService { get { return this.service; } } /// <summary>returns the Source object associated with the IVsTextLines buffer for this code window</summary> internal ISource Source { get { return this.source; } } /// <summary> /// Returns the ViewFilter for the given view or null if no matching filter is found. /// </summary> internal ViewFilter GetFilter(IVsTextView view) { if (this.viewFilters != null) { foreach (ViewFilter f in this.viewFilters) { if (f.TextView == view) return f; } } return null; } #if DOCUMENT_PROPERTIES /// <summary>Returns the DocumentProperties, if any. You can update this property if you want to /// change the document properties on the fly.</summary> internal DocumentProperties Properties { get { return this.properties; } set { if (this.properties != value) { if (this.properties != null) this.properties.Close(); this.properties = value; if (value != null) value.Refresh(); } } } #endif /// <summary>Return the optional TypeAndMemberDropdownBars object for the drop down combos</summary> internal TypeAndMemberDropdownBars DropDownHelper { get { return this.dropDownHelper; } } /// <summary>Return the IVsCodeWindow associated with this code window manager.</summary> internal IVsCodeWindow CodeWindow { get { return this.codeWindow; } } /// <summary>Install the optional TypeAndMemberDropdownBars, and primary and secondary view filters</summary> public virtual int AddAdornments() { #if LANGTRACE Trace.WriteLine("CodeWindowManager::AddAdornments"); #endif int hr = 0; this.service.AddCodeWindowManager(this); this.source.Open(); IVsTextView textView; NativeMethods.ThrowOnFailure(this.codeWindow.GetPrimaryView(out textView)); this.dropDownHelper = this.service.CreateDropDownHelper(textView); if (this.dropDownHelper != null) { IVsDropdownBar pBar; IVsDropdownBarManager dbm = (IVsDropdownBarManager)this.codeWindow; int rc = dbm.GetDropdownBar(out pBar); if (rc == 0 && pBar != null) NativeMethods.ThrowOnFailure(dbm.RemoveDropdownBar()); //this.dropDownHelper = new TypeAndMemberDropdownBars(this.service); this.dropDownHelper.SynchronizeDropdowns(textView, 0, 0); NativeMethods.ThrowOnFailure(dbm.AddDropdownBar(2, this.dropDownHelper)); } // attach view filter to primary view. if (textView != null) this.OnNewView(textView); // always returns S_OK. // attach view filter to secondary view. textView = null; hr = this.codeWindow.GetSecondaryView(out textView); if (hr == NativeMethods.S_OK && textView != null) this.OnNewView(textView); // always returns S_OK. return NativeMethods.S_OK; } /// <summary>Remove drop down combos, view filters, and notify the LanguageService that the Source and /// CodeWindowManager is now closed</summary> public virtual int RemoveAdornments() { #if LANGTRACE Trace.WriteLine("CodeWindowManager::RemoveAdornments"); #endif try { if (this.dropDownHelper != null) { IVsDropdownBarManager dbm = (IVsDropdownBarManager)this.codeWindow; NativeMethods.ThrowOnFailure(dbm.RemoveDropdownBar()); this.dropDownHelper.Done(); this.dropDownHelper = null; } } finally { CloseFilters(); if (this.source != null && this.source.Close()) { this.service.OnCloseSource(this.source); this.source.Dispose(); } this.source = null; service.RemoveCodeWindowManager(this); this.codeWindow = null; this.Close(); } return NativeMethods.S_OK; } /// <summary>Install a new view filter for the given view. This method calls your /// CreateViewFilter method.</summary> public virtual int OnNewView(IVsTextView newView) { #if LANGTRACE Trace.WriteLine("CodeWindowManager::OnNewView"); #endif ViewFilter filter = this.service.CreateViewFilter(this, newView); if (filter != null) this.viewFilters.Add(filter); return NativeMethods.S_OK; } public virtual void OnKillFocus(IVsTextView textView) { } /// <summary>Refresh the document properties</summary> public virtual void OnSetFocus(IVsTextView textView) { #if DOCUMENT_PROPERTIES if (this.properties != null) { this.properties.Refresh(); } #endif } } /// <summary> /// Represents the two drop down bars on the top of a text editor window that allow /// types and type members to be selected by name. /// </summary> internal abstract class TypeAndMemberDropdownBars : IVsDropdownBarClient { /// <summary>The language service object that created this object and calls its SynchronizeDropdowns method</summary> private LanguageService languageService; /// <summary>The correspoding VS object that represents the two drop down bars. The VS object uses call backs to pull information from /// this object and makes itself known to this object by calling SetDropdownBar</summary> private IVsDropdownBar dropDownBar; /// <summary>The icons that prefix the type names and member signatures</summary> private ImageList imageList; /// <summary>The current text editor window</summary> private IVsTextView textView; /// <summary>The list of types that appear in the type drop down list.</summary> private ArrayList dropDownTypes; /// <summary>The list of types that appear in the member drop down list. </summary> private ArrayList dropDownMembers; private int selectedType = -1; private int selectedMember = -1; const int DropClasses = 0; const int DropMethods = 1; protected TypeAndMemberDropdownBars(LanguageService languageService) { this.languageService = languageService; this.dropDownTypes = new ArrayList(); this.dropDownMembers = new ArrayList(); } public void Done() { //TODO: use IDisposable pattern if (this.imageList != null) { imageList.Dispose(); imageList = null; } } internal void SynchronizeDropdowns(IVsTextView textView, int line, int col) { if (this.dropDownBar == null) return; this.textView = textView; if (OnSynchronizeDropdowns(languageService, textView, line, col, this.dropDownTypes, this.dropDownMembers, ref this.selectedType, ref this.selectedMember)) { NativeMethods.ThrowOnFailure(this.dropDownBar.RefreshCombo(TypeAndMemberDropdownBars.DropClasses, this.selectedType)); NativeMethods.ThrowOnFailure(this.dropDownBar.RefreshCombo(TypeAndMemberDropdownBars.DropMethods, this.selectedMember)); } } /// <summary> /// This method is called to update the drop down bars to match the current contents of the text editor window. /// It is called during OnIdle when the caret position changes. You can provide new drop down members here. /// It is up to you to sort the ArrayLists if you want them sorted in any particular order. /// </summary> /// <param name="languageService">The language service</param> /// <param name="textView">The editor window</param> /// <param name="line">The line on which the cursor is now positioned</param> /// <param name="col">The column on which the cursor is now position</param> /// <param name="dropDownTypes">The current list of types (you can update this)</param> /// <param name="dropDownMembers">The current list of members (you can update this)</param> /// <param name="selectedType">The selected type (you can update this)</param> /// <param name="selectedMember">The selected member (you can update this)</param> /// <returns>true if something was updated</returns> public abstract bool OnSynchronizeDropdowns(LanguageService languageService, IVsTextView textView, int line, int col, ArrayList dropDownTypes, ArrayList dropDownMembers, ref int selectedType, ref int selectedMember); // IVsDropdownBarClient methods public virtual int GetComboAttributes(int combo, out uint entries, out uint entryType, out IntPtr iList) { entries = 0; entryType = 0; if (combo == TypeAndMemberDropdownBars.DropClasses && this.dropDownTypes != null) entries = (uint)this.dropDownTypes.Count; else if (this.dropDownMembers != null) entries = (uint)this.dropDownMembers.Count; entryType = (uint)(DropDownItemType.HasText | DropDownItemType.HasFontAttribute | DropDownItemType.HasImage); if (this.imageList == null) this.imageList = this.languageService.GetImageList(); iList = this.imageList.Handle; return NativeMethods.S_OK; } private enum DropDownItemType { HasText = 1, HasFontAttribute = 2, HasImage = 4 } public virtual int GetComboTipText(int combo, out string text) { if (combo == TypeAndMemberDropdownBars.DropClasses) text = SR.GetString(SR.ComboTypesTip); else text = SR.GetString(SR.ComboMembersTip); return NativeMethods.S_OK; } public virtual int GetEntryAttributes(int combo, int entry, out uint fontAttrs) { fontAttrs = (uint)DROPDOWNFONTATTR.FONTATTR_PLAIN; DropDownMember member = GetMember(combo, entry); if (!Object.ReferenceEquals(member,null)) { fontAttrs = (uint)member.FontAttr; } return NativeMethods.S_OK; } public virtual int GetEntryImage(int combo, int entry, out int imgIndex) { // this happens during drawing and has to be fast imgIndex = -1; DropDownMember member = GetMember(combo, entry); if (!Object.ReferenceEquals(member,null)) { imgIndex = member.Glyph; } return NativeMethods.S_OK; } public virtual int GetEntryText(int combo, int entry, out string text) { text = null; DropDownMember member = GetMember(combo, entry); if (!Object.ReferenceEquals(member,null)) { text = member.Label; } return NativeMethods.S_OK; } public virtual int OnComboGetFocus(int combo) { return NativeMethods.S_OK; } public DropDownMember GetMember(int combo, int entry) { if (combo == TypeAndMemberDropdownBars.DropClasses) { if (this.dropDownTypes != null && entry >= 0 && entry < this.dropDownTypes.Count) return (DropDownMember)this.dropDownTypes[entry]; } else { if (this.dropDownMembers != null && entry >= 0 && entry < this.dropDownMembers.Count) return (DropDownMember)this.dropDownMembers[entry]; } return null; } public virtual int OnItemChosen(int combo, int entry) { DropDownMember member = GetMember(combo, entry); if (!Object.ReferenceEquals(member,null)) { if (this.textView != null) { int line = member.Span.iStartLine; int col = member.Span.iStartIndex; try { // Here we don't want to throw or to check the return value. textView.CenterLines(line, 16); } catch (COMException) { } NativeMethods.ThrowOnFailure(this.textView.SetCaretPos(line, col)); NativeMethods.SetFocus(this.textView.GetWindowHandle()); this.SynchronizeDropdowns(this.textView, line, col); } } return NativeMethods.S_OK; } [DllImport("user32.dll")] static extern void SetFocus(IntPtr hwnd); public int OnItemSelected(int combo, int index) { //nop return NativeMethods.S_OK; } public int SetDropdownBar(IVsDropdownBar bar) { this.dropDownBar = bar; return NativeMethods.S_OK; } } internal class DropDownMember : IComparable { private string label; private TextSpan span; private int glyph; private DROPDOWNFONTATTR fontAttr; public string Label { get { return this.label; } set { this.label = value; } } public TextSpan Span { get { return this.span; } set { this.span = value; } } public int Glyph { get { return this.glyph; } set { this.glyph = value; } } public DROPDOWNFONTATTR FontAttr { get { return this.fontAttr; } set { this.fontAttr = value; } } public DropDownMember(string label, TextSpan span, int glyph, DROPDOWNFONTATTR fontAttribute) { if (label == null) { throw new ArgumentNullException("label"); } this.Label = label; this.Span = span; this.Glyph = glyph; this.FontAttr = fontAttribute; } public int CompareTo(object obj) { // if this overload is used then it assumes a case-sensitive current culture comparison // which allows for case-senstive languages to work return CompareTo(obj, StringComparison.CurrentCulture); } public int CompareTo(object obj, StringComparison stringComparison) { if (obj is DropDownMember) { return String.Compare(this.Label, ((DropDownMember)obj).Label, stringComparison); } return -1; } // Omitting Equals violates FxCop rule: IComparableImplementationsOverrideEquals. public override bool Equals(Object obj) { if (!(obj is DropDownMember)) return false; return (this.CompareTo(obj, StringComparison.CurrentCulture) == 0); } // Omitting getHashCode violates FxCop rule: EqualsOverridesRequireGetHashCodeOverride. public override int GetHashCode() { return this.Label.GetHashCode(); } // Omitting any of the following operator overloads // violates FxCop rule: IComparableImplementationsOverrideOperators. public static bool operator ==(DropDownMember m1, DropDownMember m2) { return m1.Equals(m2); } public static bool operator !=(DropDownMember m1, DropDownMember m2) { return !(m1 == m2); } public static bool operator <(DropDownMember m1, DropDownMember m2) { return (m1.CompareTo(m2, StringComparison.CurrentCulture) < 0); } public static bool operator >(DropDownMember m1, DropDownMember m2) { return (m1.CompareTo(m2, StringComparison.CurrentCulture) > 0); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Numerics; using System.Linq; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp.Swizzle { /// <summary> /// Temporary vector of type Complex with 2 components, used for implementing swizzling for cvec2. /// </summary> [Serializable] [DataContract(Namespace = "swizzle")] [StructLayout(LayoutKind.Sequential)] public struct swizzle_cvec2 { #region Fields /// <summary> /// x-component /// </summary> [DataMember] internal readonly Complex x; /// <summary> /// y-component /// </summary> [DataMember] internal readonly Complex y; #endregion #region Constructors /// <summary> /// Constructor for swizzle_cvec2. /// </summary> internal swizzle_cvec2(Complex x, Complex y) { this.x = x; this.y = y; } #endregion #region Properties /// <summary> /// Returns cvec2.xx swizzling. /// </summary> public cvec2 xx => new cvec2(x, x); /// <summary> /// Returns cvec2.rr swizzling (equivalent to cvec2.xx). /// </summary> public cvec2 rr => new cvec2(x, x); /// <summary> /// Returns cvec2.xxx swizzling. /// </summary> public cvec3 xxx => new cvec3(x, x, x); /// <summary> /// Returns cvec2.rrr swizzling (equivalent to cvec2.xxx). /// </summary> public cvec3 rrr => new cvec3(x, x, x); /// <summary> /// Returns cvec2.xxxx swizzling. /// </summary> public cvec4 xxxx => new cvec4(x, x, x, x); /// <summary> /// Returns cvec2.rrrr swizzling (equivalent to cvec2.xxxx). /// </summary> public cvec4 rrrr => new cvec4(x, x, x, x); /// <summary> /// Returns cvec2.xxxy swizzling. /// </summary> public cvec4 xxxy => new cvec4(x, x, x, y); /// <summary> /// Returns cvec2.rrrg swizzling (equivalent to cvec2.xxxy). /// </summary> public cvec4 rrrg => new cvec4(x, x, x, y); /// <summary> /// Returns cvec2.xxy swizzling. /// </summary> public cvec3 xxy => new cvec3(x, x, y); /// <summary> /// Returns cvec2.rrg swizzling (equivalent to cvec2.xxy). /// </summary> public cvec3 rrg => new cvec3(x, x, y); /// <summary> /// Returns cvec2.xxyx swizzling. /// </summary> public cvec4 xxyx => new cvec4(x, x, y, x); /// <summary> /// Returns cvec2.rrgr swizzling (equivalent to cvec2.xxyx). /// </summary> public cvec4 rrgr => new cvec4(x, x, y, x); /// <summary> /// Returns cvec2.xxyy swizzling. /// </summary> public cvec4 xxyy => new cvec4(x, x, y, y); /// <summary> /// Returns cvec2.rrgg swizzling (equivalent to cvec2.xxyy). /// </summary> public cvec4 rrgg => new cvec4(x, x, y, y); /// <summary> /// Returns cvec2.xy swizzling. /// </summary> public cvec2 xy => new cvec2(x, y); /// <summary> /// Returns cvec2.rg swizzling (equivalent to cvec2.xy). /// </summary> public cvec2 rg => new cvec2(x, y); /// <summary> /// Returns cvec2.xyx swizzling. /// </summary> public cvec3 xyx => new cvec3(x, y, x); /// <summary> /// Returns cvec2.rgr swizzling (equivalent to cvec2.xyx). /// </summary> public cvec3 rgr => new cvec3(x, y, x); /// <summary> /// Returns cvec2.xyxx swizzling. /// </summary> public cvec4 xyxx => new cvec4(x, y, x, x); /// <summary> /// Returns cvec2.rgrr swizzling (equivalent to cvec2.xyxx). /// </summary> public cvec4 rgrr => new cvec4(x, y, x, x); /// <summary> /// Returns cvec2.xyxy swizzling. /// </summary> public cvec4 xyxy => new cvec4(x, y, x, y); /// <summary> /// Returns cvec2.rgrg swizzling (equivalent to cvec2.xyxy). /// </summary> public cvec4 rgrg => new cvec4(x, y, x, y); /// <summary> /// Returns cvec2.xyy swizzling. /// </summary> public cvec3 xyy => new cvec3(x, y, y); /// <summary> /// Returns cvec2.rgg swizzling (equivalent to cvec2.xyy). /// </summary> public cvec3 rgg => new cvec3(x, y, y); /// <summary> /// Returns cvec2.xyyx swizzling. /// </summary> public cvec4 xyyx => new cvec4(x, y, y, x); /// <summary> /// Returns cvec2.rggr swizzling (equivalent to cvec2.xyyx). /// </summary> public cvec4 rggr => new cvec4(x, y, y, x); /// <summary> /// Returns cvec2.xyyy swizzling. /// </summary> public cvec4 xyyy => new cvec4(x, y, y, y); /// <summary> /// Returns cvec2.rggg swizzling (equivalent to cvec2.xyyy). /// </summary> public cvec4 rggg => new cvec4(x, y, y, y); /// <summary> /// Returns cvec2.yx swizzling. /// </summary> public cvec2 yx => new cvec2(y, x); /// <summary> /// Returns cvec2.gr swizzling (equivalent to cvec2.yx). /// </summary> public cvec2 gr => new cvec2(y, x); /// <summary> /// Returns cvec2.yxx swizzling. /// </summary> public cvec3 yxx => new cvec3(y, x, x); /// <summary> /// Returns cvec2.grr swizzling (equivalent to cvec2.yxx). /// </summary> public cvec3 grr => new cvec3(y, x, x); /// <summary> /// Returns cvec2.yxxx swizzling. /// </summary> public cvec4 yxxx => new cvec4(y, x, x, x); /// <summary> /// Returns cvec2.grrr swizzling (equivalent to cvec2.yxxx). /// </summary> public cvec4 grrr => new cvec4(y, x, x, x); /// <summary> /// Returns cvec2.yxxy swizzling. /// </summary> public cvec4 yxxy => new cvec4(y, x, x, y); /// <summary> /// Returns cvec2.grrg swizzling (equivalent to cvec2.yxxy). /// </summary> public cvec4 grrg => new cvec4(y, x, x, y); /// <summary> /// Returns cvec2.yxy swizzling. /// </summary> public cvec3 yxy => new cvec3(y, x, y); /// <summary> /// Returns cvec2.grg swizzling (equivalent to cvec2.yxy). /// </summary> public cvec3 grg => new cvec3(y, x, y); /// <summary> /// Returns cvec2.yxyx swizzling. /// </summary> public cvec4 yxyx => new cvec4(y, x, y, x); /// <summary> /// Returns cvec2.grgr swizzling (equivalent to cvec2.yxyx). /// </summary> public cvec4 grgr => new cvec4(y, x, y, x); /// <summary> /// Returns cvec2.yxyy swizzling. /// </summary> public cvec4 yxyy => new cvec4(y, x, y, y); /// <summary> /// Returns cvec2.grgg swizzling (equivalent to cvec2.yxyy). /// </summary> public cvec4 grgg => new cvec4(y, x, y, y); /// <summary> /// Returns cvec2.yy swizzling. /// </summary> public cvec2 yy => new cvec2(y, y); /// <summary> /// Returns cvec2.gg swizzling (equivalent to cvec2.yy). /// </summary> public cvec2 gg => new cvec2(y, y); /// <summary> /// Returns cvec2.yyx swizzling. /// </summary> public cvec3 yyx => new cvec3(y, y, x); /// <summary> /// Returns cvec2.ggr swizzling (equivalent to cvec2.yyx). /// </summary> public cvec3 ggr => new cvec3(y, y, x); /// <summary> /// Returns cvec2.yyxx swizzling. /// </summary> public cvec4 yyxx => new cvec4(y, y, x, x); /// <summary> /// Returns cvec2.ggrr swizzling (equivalent to cvec2.yyxx). /// </summary> public cvec4 ggrr => new cvec4(y, y, x, x); /// <summary> /// Returns cvec2.yyxy swizzling. /// </summary> public cvec4 yyxy => new cvec4(y, y, x, y); /// <summary> /// Returns cvec2.ggrg swizzling (equivalent to cvec2.yyxy). /// </summary> public cvec4 ggrg => new cvec4(y, y, x, y); /// <summary> /// Returns cvec2.yyy swizzling. /// </summary> public cvec3 yyy => new cvec3(y, y, y); /// <summary> /// Returns cvec2.ggg swizzling (equivalent to cvec2.yyy). /// </summary> public cvec3 ggg => new cvec3(y, y, y); /// <summary> /// Returns cvec2.yyyx swizzling. /// </summary> public cvec4 yyyx => new cvec4(y, y, y, x); /// <summary> /// Returns cvec2.gggr swizzling (equivalent to cvec2.yyyx). /// </summary> public cvec4 gggr => new cvec4(y, y, y, x); /// <summary> /// Returns cvec2.yyyy swizzling. /// </summary> public cvec4 yyyy => new cvec4(y, y, y, y); /// <summary> /// Returns cvec2.gggg swizzling (equivalent to cvec2.yyyy). /// </summary> public cvec4 gggg => new cvec4(y, y, y, y); #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public class RoarManager { public class GoodInfo { public GoodInfo( string in_id, string in_ikey, string in_label ) { id = in_id; ikey = in_ikey; label = in_label; } public string id; public string ikey; public string label; }; public class PurchaseInfo { public PurchaseInfo( string in_currency, int in_price, string in_ikey, int in_quantity ) { currency = in_currency; price = in_price; ikey = in_ikey; quantity = in_quantity; } public string currency; public int price; public string ikey; public int quantity; }; public class CallInfo { public CallInfo( object xml_node, int code, string message, string call_id) { } }; public static event Action<string> logInFailedEvent; public static void OnLogInFailed( string mesg ) { if(logInFailedEvent!=null) logInFailedEvent(mesg); } public static event Action<string> createUserFailedEvent; public static void OnCreateUserFailed( string mesg ) { if(createUserFailedEvent!=null) createUserFailedEvent(mesg); } public static event Action loggedOutEvent; public static void OnLoggedOut() { if(loggedOutEvent!=null) loggedOutEvent(); } public static event Action loggedInEvent; public static void OnLoggedIn() { if(loggedInEvent!=null) loggedInEvent(); } public static event Action createdUserEvent; public static void OnCreatedUser() { if(createdUserEvent!=null) createdUserEvent(); } public static event Action<GoodInfo> goodActivatedEvent; public static void OnGoodActivated( GoodInfo info ) { if(goodActivatedEvent!=null) goodActivatedEvent(info); } public static event Action<GoodInfo> goodDeactivatedEvent; public static void OnGoodDeactivated( GoodInfo info ) { if(goodDeactivatedEvent!=null) goodDeactivatedEvent(info); } public static event Action<GoodInfo> goodUsedEvent; public static void OnGoodUsed( GoodInfo info ) { if(goodUsedEvent!=null) goodUsedEvent(info); } public static event Action<GoodInfo> goodSoldEvent; public static void OnGoodSold( GoodInfo info ) { if(goodSoldEvent!=null) goodSoldEvent(info); } /** * Fired when a shop item has been successfully purchased. */ public static event Action<PurchaseInfo> goodBoughtEvent; public static void OnGoodBought( PurchaseInfo info ) { if(goodBoughtEvent!=null) goodBoughtEvent(info); } public static event Action<IXMLNode> eventDoneEvent; public static void OnEventDone( IXMLNode eventInfo ) { if(eventDoneEvent!=null) eventDoneEvent(eventInfo); } public static event Action<string,string> dataLoadedEvent; public static void OnDataLoaded( string key, string value ) { if(dataLoadedEvent!=null) dataLoadedEvent(key, value); } public static event Action<string,string> dataSavedEvent; public static void OnDataSaved( string key, string value ) { if(dataSavedEvent!=null) dataSavedEvent(key, value); } public static event Action roarNetworkStartEvent; public static void OnRoarNetworkStart() { if(roarNetworkStartEvent!=null) roarNetworkStartEvent(); } public static event Action<string> roarNetworkEndEvent; public static void OnRoarNetworkEnd( string call_id ) { if(roarNetworkEndEvent!=null) roarNetworkEndEvent(call_id); } public static event Action<CallInfo> callCompleteEvent; public static void OnCallComplete( CallInfo info ) { if(callCompleteEvent!=null) callCompleteEvent(info); } /** * @note The object is really an XML Node. * @todo It's ugly to be using an implementation detail like this. */ public static event Action<object> roarServerAllEvent; public static void OnRoarServerAll( object info ) { if(roarServerAllEvent!=null) roarServerAllEvent(info); } /** * @todo These should be generated for each component. */ public static event Action xxxChangeEvent; public static void OnXxxChange() { if(xxxChangeEvent!=null) xxxChangeEvent(); } /** * Fired when the data have been retrieved from the server. */ public static event Action propertiesReadyEvent; public static void OnPropertiesReady() { if(propertiesReadyEvent!=null) propertiesReadyEvent(); } /** * Fired when the data have been retrieved from the server. */ public static event Action leaderboardsReadyEvent; public static void OnLeaderboardsReady() { if(leaderboardsReadyEvent!=null) leaderboardsReadyEvent(); } /** * Fired when the data have been retrieved from the server. */ public static event Action rankingReadyEvent; public static void OnRankingReady() { if(rankingReadyEvent!=null) rankingReadyEvent(); } /** * Fired when the data changes. */ public static event Action propertiesChangeEvent; public static void OnPropertiesChange() { if(propertiesChangeEvent!=null) propertiesChangeEvent(); } /** * Fired when the data have been retrieved from the server. */ public static event Action shopReadyEvent; public static void OnShopReady() { if(shopReadyEvent!=null) shopReadyEvent(); } /** * Fired when the data have been retrieved from the server. */ public static event Action leaderboardsChangeEvent; public static void OnLeaderboardsChange() { if(leaderboardsChangeEvent!=null) leaderboardsChangeEvent(); } /** * Fired when the data have been retrieved from the server. */ public static event Action rankingChangeEvent; public static void OnRankingChange() { if(rankingChangeEvent!=null) rankingChangeEvent(); } /** * Fired when the data changes. */ public static event Action shopChangeEvent; public static void OnShopChange() { if(shopChangeEvent!=null) shopChangeEvent(); } /** * Fired when the data have been retrieved from the server. */ public static event Action inventoryReadyEvent; public static void OnInventoryReady() { if(inventoryReadyEvent!=null) inventoryReadyEvent(); } /** * Fired when the data changes. */ public static event Action inventoryChangeEvent; public static void OnInventoryChange() { if(inventoryChangeEvent!=null) inventoryChangeEvent(); } /** * Fired when the data have been retrieved from the server. */ public static event Action cacheReadyEvent; public static void OnCacheReady() { if(cacheReadyEvent!=null) cacheReadyEvent(); } /** * Fired when the data changes. */ public static event Action cacheChangeEvent; public static void OnCacheChange() { if(cacheChangeEvent!=null) cacheChangeEvent(); } /** * Fired when the data have been retrieved from the server. */ public static event Action tasksReadyEvent; public static void OnTasksReady() { if(tasksReadyEvent!=null) tasksReadyEvent(); } /** * Fired when the data changes. */ public static event Action tasksChangeEvent; public static void OnTasksChange() { if(tasksChangeEvent!=null) tasksChangeEvent(); } /** * @todo Ugly to be using a hash here. * @todo Implement more server update functions. */ public static event Action<IXMLNode> roarServerUpdateEvent; public static void OnRoarServerUpdate( IXMLNode info ) { if(roarServerUpdateEvent!=null) roarServerUpdateEvent(info); } /** * @todo Ugly to be using a hash here. * @todo Implement more server update functions. */ public static event Action<IXMLNode> roarServerItemUseEvent; public static void OnRoarServerItemUse( IXMLNode info ) { if(roarServerItemUseEvent!=null) roarServerItemUseEvent(info); } /** * @todo Ugly to be using a hash here. * @todo Implement more server update functions. */ public static event Action<IXMLNode> roarServerItemLoseEvent; public static void OnRoarServerItemLose( IXMLNode info ) { if(roarServerItemLoseEvent!=null) roarServerItemLoseEvent(info); } /** * @todo Ugly to be using a hash here. * @todo Implement more server update functions. */ public static event Action<IXMLNode> roarServerInventoryChangedEvent; public static void OnRoarServerInventoryChanged( IXMLNode info ) { if(roarServerInventoryChangedEvent!=null) roarServerInventoryChangedEvent(info); } /** * @todo Ugly to be using a hash here. * @todo Implement more server update functions. */ public static event Action<IXMLNode> roarServerRegenEvent; public static void OnRoarServerRegen( IXMLNode info ) { if(roarServerRegenEvent!=null) roarServerRegenEvent(info); } /** * @todo Ugly to be using a hash here. * @todo Implement more server update functions. */ public static event Action<IXMLNode> roarServerItemAddEvent; public static void OnRoarServerItemAdd( IXMLNode info ) { if(roarServerItemAddEvent!=null) roarServerItemAddEvent(info); } /** * @todo Ugly to be using a hash here. * @todo Implement more server update functions. */ public static event Action<IXMLNode> roarServerTaskCompleteEvent; public static void OnRoarServerTaskComplete( IXMLNode info ) { if(roarServerTaskCompleteEvent!=null) roarServerTaskCompleteEvent(info); } /** * Fire the correct event for a server chunk. * * @param key the event name. * @param info the event info. **/ public static void OnServerEvent( string key, IXMLNode info ) { switch(key) { case "update": OnRoarServerUpdate(info); break; case "item_use": OnRoarServerItemUse(info); break; case "item_lose": OnRoarServerItemLose(info); break; case "inventory_changed": OnRoarServerInventoryChanged(info); break; case "regen": OnRoarServerRegen(info); break; case "item_add": OnRoarServerItemAdd(info); break; case "task_complete": OnRoarServerTaskComplete(info); break; default: Debug.Log("Server event "+key+" not yet implemented"); break; } } /** * Fire the correct event for a component change. * * @param name The name of the event. */ public static void OnComponentChange( string name ) { switch(name) { case "properties": OnPropertiesChange(); break; case "shop": OnShopChange(); break; case "inventory": OnInventoryChange(); break; case "cache": OnCacheChange(); break; case "tasks": OnTasksChange(); break; case "leaderboards": OnLeaderboardsChange(); break; case "ranking": OnRankingChange(); break; default: Debug.Log ("Component change event for "+name+" not yet implemented"); break; } } /** * Fire the correct event for a component ready. * * @param name The name of the event. */ public static void OnComponentReady( string name ) { switch(name) { case "properties": OnPropertiesReady(); break; case "shop": OnShopReady(); break; case "inventory": OnInventoryReady(); break; case "cache": OnCacheReady(); break; case "tasks": OnTasksReady(); break; case "leaderboards": OnLeaderboardsReady(); break; case "ranking": OnRankingReady(); break; default: Debug.Log ("Component ready event for "+name+" not yet implemented"); break; } } /** * Fire off the events for all the contained server events. */ public static void NotifyOfServerChanges( IXMLNode node ) { if( node == null ) return; OnRoarServerAll( node ); foreach( IXMLNode nn in node.Children ) { OnServerEvent( nn.Name, nn ); } } }
///////////////////////////////////////////////////////////////////////////////// // Paint.NET (MIT,from version 3.36.7, see=> https://github.com/rivy/OpenPDN // // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. // // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. // // See src/Resources/Files/License.txt for full licensing and attribution // // details. // // . // ///////////////////////////////////////////////////////////////////////////////// //MIT, 2017-present, WinterDev using System; using System.Runtime.InteropServices; using PixelFarm.Drawing; namespace PaintFx { /// <summary> /// This is our pixel format that we will work with. It is always 32-bits / 4-bytes and is /// always laid out in BGRA order. /// Generally used with the Surface class. /// </summary> [StructLayout(LayoutKind.Explicit)] public struct ColorBgra { [FieldOffset(0)] public byte B; [FieldOffset(1)] public byte G; [FieldOffset(2)] public byte R; [FieldOffset(3)] public byte A; /// <summary> /// Lets you change B, G, R, and A at the same time. /// </summary> [FieldOffset(0)] public uint Bgra; public const int BlueChannel = 0; public const int GreenChannel = 1; public const int RedChannel = 2; public const int AlphaChannel = 3; public const int SizeOf = 4; public static ColorBgra ParseHexString(string hexString) { uint value = Convert.ToUInt32(hexString, 16); return ColorBgra.FromUInt32(value); } public string ToHexString() { int rgbNumber = (this.R << 16) | (this.G << 8) | this.B; string colorString = Convert.ToString(rgbNumber, 16); while (colorString.Length < 6) { colorString = "0" + colorString; } string alphaString = System.Convert.ToString(this.A, 16); while (alphaString.Length < 2) { alphaString = "0" + alphaString; } colorString = alphaString + colorString; return colorString.ToUpper(); } /// <summary> /// Gets or sets the byte value of the specified color channel. /// </summary> public unsafe byte this[int channel] { get { if (channel < 0 || channel > 3) { throw new ArgumentOutOfRangeException("channel", channel, "valid range is [0,3]"); } fixed (byte* p = &B) { return p[channel]; } } set { if (channel < 0 || channel > 3) { throw new ArgumentOutOfRangeException("channel", channel, "valid range is [0,3]"); } fixed (byte* p = &B) { p[channel] = value; } } } /// <summary> /// Gets the luminance intensity of the pixel based on the values of the red, green, and blue components. Alpha is ignored. /// </summary> /// <returns>A value in the range 0 to 1 inclusive.</returns> public double GetIntensity() { return ((0.114 * (double)B) + (0.587 * (double)G) + (0.299 * (double)R)) / 255.0; } /// <summary> /// Gets the luminance intensity of the pixel based on the values of the red, green, and blue components. Alpha is ignored. /// </summary> /// <returns>A value in the range 0 to 255 inclusive.</returns> public byte GetIntensityByte() { return (byte)((7471 * B + 38470 * G + 19595 * R) >> 16); } /// <summary> /// Returns the maximum value out of the B, G, and R values. Alpha is ignored. /// </summary> /// <returns></returns> public byte GetMaxColorChannelValue() { return Math.Max(this.B, Math.Max(this.G, this.R)); } /// <summary> /// Returns the average of the B, G, and R values. Alpha is ignored. /// </summary> /// <returns></returns> public byte GetAverageColorChannelValue() { return (byte)((this.B + this.G + this.R) / 3); } /// <summary> /// Compares two ColorBgra instance to determine if they are equal. /// </summary> public static bool operator ==(ColorBgra lhs, ColorBgra rhs) { return lhs.Bgra == rhs.Bgra; } /// <summary> /// Compares two ColorBgra instance to determine if they are not equal. /// </summary> public static bool operator !=(ColorBgra lhs, ColorBgra rhs) { return lhs.Bgra != rhs.Bgra; } /// <summary> /// Compares two ColorBgra instance to determine if they are equal. /// </summary> public override bool Equals(object obj) { if (obj != null && obj is ColorBgra && ((ColorBgra)obj).Bgra == this.Bgra) { return true; } else { return false; } } /// <summary> /// Returns a hash code for this color value. /// </summary> /// <returns></returns> public override int GetHashCode() { unchecked { return (int)Bgra; } } /// <summary> /// Returns a new ColorBgra with the same color values but with a new alpha component value. /// </summary> public ColorBgra NewAlpha(byte newA) { return ColorBgra.FromBgra(B, G, R, newA); } /// <summary> /// Creates a new ColorBgra instance with the given color and alpha values. /// </summary> public static ColorBgra FromBgra(byte b, byte g, byte r, byte a) { ColorBgra color = new ColorBgra(); color.Bgra = BgraToUInt32(b, g, r, a); return color; } /// <summary> /// Creates a new ColorBgra instance with the given color and alpha values. /// </summary> public static ColorBgra FromBgraClamped(int b, int g, int r, int a) { return FromBgra( PixelUtils.ClampToByte(b), PixelUtils.ClampToByte(g), PixelUtils.ClampToByte(r), PixelUtils.ClampToByte(a)); } /// <summary> /// Creates a new ColorBgra instance with the given color and alpha values. /// </summary> public static ColorBgra FromBgraClamped(float b, float g, float r, float a) { return FromBgra( PixelUtils.ClampToByte(b), PixelUtils.ClampToByte(g), PixelUtils.ClampToByte(r), PixelUtils.ClampToByte(a)); } /// <summary> /// Packs color and alpha values into a 32-bit integer. /// </summary> public static UInt32 BgraToUInt32(byte b, byte g, byte r, byte a) { return (uint)b + ((uint)g << 8) + ((uint)r << 16) + ((uint)a << 24); } /// <summary> /// Packs color and alpha values into a 32-bit integer. /// </summary> public static UInt32 BgraToUInt32(int b, int g, int r, int a) { return (uint)b + ((uint)g << 8) + ((uint)r << 16) + ((uint)a << 24); } /// <summary> /// Creates a new ColorBgra instance with the given color values, and 255 for alpha. /// </summary> public static ColorBgra FromBgr(byte b, byte g, byte r) { return FromBgra(b, g, r, 255); } /// <summary> /// Constructs a new ColorBgra instance with the given 32-bit value. /// </summary> public static ColorBgra FromUInt32(UInt32 bgra) { ColorBgra color = new ColorBgra(); color.Bgra = bgra; return color; } /// <summary> /// Constructs a new ColorBgra instance given a 32-bit signed integer that represents an R,G,B triple. /// Alpha will be initialized to 255. /// </summary> public static ColorBgra FromOpaqueInt32(Int32 bgr) { if (bgr < 0 || bgr > 0xffffff) { throw new ArgumentOutOfRangeException("bgr", "must be in the range [0, 0xffffff]"); } ColorBgra color = new ColorBgra(); color.Bgra = (uint)bgr; color.A = 255; return color; } public static int ToOpaqueInt32(ColorBgra color) { if (color.A != 255) { throw new InvalidOperationException("Alpha value must be 255 for this to work"); } return (int)(color.Bgra & 0xffffff); } /// <summary> /// Constructs a new ColorBgra instance from the values in the given Color instance. /// </summary> public static ColorBgra FromColor(Color c) { return FromBgra(c.B, c.G, c.R, c.A); } /// <summary> /// Converts this ColorBgra instance to a Color instance. /// </summary> public Color ToColor() { return Color.FromArgb(A, R, G, B); } /// <summary> /// Smoothly blends between two colors. /// </summary> public static ColorBgra Blend(ColorBgra ca, ColorBgra cb, byte cbAlpha) { uint caA = (uint)PixelUtils.FastScaleByteByByte((byte)(255 - cbAlpha), ca.A); uint cbA = (uint)PixelUtils.FastScaleByteByByte(cbAlpha, cb.A); uint cbAT = caA + cbA; uint r; uint g; uint b; if (cbAT == 0) { r = 0; g = 0; b = 0; } else { r = ((ca.R * caA) + (cb.R * cbA)) / cbAT; g = ((ca.G * caA) + (cb.G * cbA)) / cbAT; b = ((ca.B * caA) + (cb.B * cbA)) / cbAT; } return ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, (byte)cbAT); } /// <summary> /// Linearly interpolates between two color values. /// </summary> /// <param name="from">The color value that represents 0 on the lerp number line.</param> /// <param name="to">The color value that represents 1 on the lerp number line.</param> /// <param name="frac">A value in the range [0, 1].</param> /// <remarks> /// This method does a simple lerp on each color value and on the alpha channel. It does /// not properly take into account the alpha channel's effect on color blending. /// </remarks> public static ColorBgra Lerp(ColorBgra from, ColorBgra to, float frac) { ColorBgra ret = new ColorBgra(); ret.B = (byte)PixelUtils.ClampToByte(PixelUtils.Lerp(from.B, to.B, frac)); ret.G = (byte)PixelUtils.ClampToByte(PixelUtils.Lerp(from.G, to.G, frac)); ret.R = (byte)PixelUtils.ClampToByte(PixelUtils.Lerp(from.R, to.R, frac)); ret.A = (byte)PixelUtils.ClampToByte(PixelUtils.Lerp(from.A, to.A, frac)); return ret; } /// <summary> /// Linearly interpolates between two color values. /// </summary> /// <param name="from">The color value that represents 0 on the lerp number line.</param> /// <param name="to">The color value that represents 1 on the lerp number line.</param> /// <param name="frac">A value in the range [0, 1].</param> /// <remarks> /// This method does a simple lerp on each color value and on the alpha channel. It does /// not properly take into account the alpha channel's effect on color blending. /// </remarks> public static ColorBgra Lerp(ColorBgra from, ColorBgra to, double frac) { ColorBgra ret = new ColorBgra(); ret.B = (byte)PixelUtils.ClampToByte(PixelUtils.Lerp(from.B, to.B, frac)); ret.G = (byte)PixelUtils.ClampToByte(PixelUtils.Lerp(from.G, to.G, frac)); ret.R = (byte)PixelUtils.ClampToByte(PixelUtils.Lerp(from.R, to.R, frac)); ret.A = (byte)PixelUtils.ClampToByte(PixelUtils.Lerp(from.A, to.A, frac)); return ret; } /// <summary> /// Blends four colors together based on the given weight values. /// </summary> /// <returns>The blended color.</returns> /// <remarks> /// The weights should be 16-bit fixed point numbers that add up to 65536 ("1.0"). /// 4W16IP means "4 colors, weights, 16-bit integer precision" /// </remarks> public static ColorBgra BlendColors4W16IP(ColorBgra c1, uint w1, ColorBgra c2, uint w2, ColorBgra c3, uint w3, ColorBgra c4, uint w4) { #if DEBUG /* if ((w1 + w2 + w3 + w4) != 65536) { throw new ArgumentOutOfRangeException("w1 + w2 + w3 + w4 must equal 65536!"); } * */ #endif const uint ww = 32768; uint af = (c1.A * w1) + (c2.A * w2) + (c3.A * w3) + (c4.A * w4); uint a = (af + ww) >> 16; uint b; uint g; uint r; if (a == 0) { b = 0; g = 0; r = 0; } else { b = (uint)((((long)c1.A * c1.B * w1) + ((long)c2.A * c2.B * w2) + ((long)c3.A * c3.B * w3) + ((long)c4.A * c4.B * w4)) / af); g = (uint)((((long)c1.A * c1.G * w1) + ((long)c2.A * c2.G * w2) + ((long)c3.A * c3.G * w3) + ((long)c4.A * c4.G * w4)) / af); r = (uint)((((long)c1.A * c1.R * w1) + ((long)c2.A * c2.R * w2) + ((long)c3.A * c3.R * w3) + ((long)c4.A * c4.R * w4)) / af); } return ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, (byte)a); } /// <summary> /// Blends the colors based on the given weight values. /// </summary> /// <param name="c">The array of color values.</param> /// <param name="w">The array of weight values.</param> /// <returns> /// The weights should be fixed point numbers. /// The total summation of the weight values will be treated as "1.0". /// Each color will be blended in proportionally to its weight value respective to /// the total summation of the weight values. /// </returns> /// <remarks> /// "WAIP" stands for "weights, arbitrary integer precision"</remarks> public static ColorBgra BlendColorsWAIP(ColorBgra[] c, uint[] w) { if (c.Length != w.Length) { throw new ArgumentException("c.Length != w.Length"); } if (c.Length == 0) { return ColorBgra.FromUInt32(0); } long wsum = 0; long asum = 0; for (int i = 0; i < w.Length; ++i) { wsum += w[i]; asum += c[i].A * w[i]; } uint a = (uint)((asum + (wsum >> 1)) / wsum); long b; long g; long r; if (a == 0) { b = 0; g = 0; r = 0; } else { b = 0; g = 0; r = 0; for (int i = 0; i < c.Length; ++i) { b += (long)c[i].A * c[i].B * w[i]; g += (long)c[i].A * c[i].G * w[i]; r += (long)c[i].A * c[i].R * w[i]; } b /= asum; g /= asum; r /= asum; } return ColorBgra.FromUInt32((uint)b + ((uint)g << 8) + ((uint)r << 16) + ((uint)a << 24)); } /// <summary> /// Blends the colors based on the given weight values. /// </summary> /// <param name="c">The array of color values.</param> /// <param name="w">The array of weight values.</param> /// <returns> /// Each color will be blended in proportionally to its weight value respective to /// the total summation of the weight values. /// </returns> /// <remarks> /// "WAIP" stands for "weights, floating-point"</remarks> public static ColorBgra BlendColorsWFP(ColorBgra[] c, double[] w) { if (c.Length != w.Length) { throw new ArgumentException("c.Length != w.Length"); } if (c.Length == 0) { return ColorBgra.Transparent; } double wsum = 0; double asum = 0; for (int i = 0; i < w.Length; ++i) { wsum += w[i]; asum += (double)c[i].A * w[i]; } double a = asum / wsum; double aMultWsum = a * wsum; double b; double g; double r; if (asum == 0) { b = 0; g = 0; r = 0; } else { b = 0; g = 0; r = 0; for (int i = 0; i < c.Length; ++i) { b += (double)c[i].A * c[i].B * w[i]; g += (double)c[i].A * c[i].G * w[i]; r += (double)c[i].A * c[i].R * w[i]; } b /= aMultWsum; g /= aMultWsum; r /= aMultWsum; } return ColorBgra.FromBgra((byte)b, (byte)g, (byte)r, (byte)a); } public static ColorBgra Blend(ColorBgra[] colors) { unsafe { fixed (ColorBgra* pColors = colors) { return Blend(pColors, colors.Length); } } } /// <summary> /// Smoothly blends the given colors together, assuming equal weighting for each one. /// </summary> /// <param name="colors"></param> /// <param name="colorCount"></param> /// <returns></returns> public unsafe static ColorBgra Blend(ColorBgra* colors, int count) { if (count < 0) { throw new ArgumentOutOfRangeException("count must be 0 or greater"); } if (count == 0) { return ColorBgra.Transparent; } ulong aSum = 0; for (int i = 0; i < count; ++i) { aSum += (ulong)colors[i].A; } byte b = 0; byte g = 0; byte r = 0; byte a = (byte)(aSum / (ulong)count); if (aSum != 0) { ulong bSum = 0; ulong gSum = 0; ulong rSum = 0; for (int i = 0; i < count; ++i) { bSum += (ulong)(colors[i].A * colors[i].B); gSum += (ulong)(colors[i].A * colors[i].G); rSum += (ulong)(colors[i].A * colors[i].R); } b = (byte)(bSum / aSum); g = (byte)(gSum / aSum); r = (byte)(rSum / aSum); } return ColorBgra.FromBgra(b, g, r, a); } public override string ToString() { return "B: " + B + ", G: " + G + ", R: " + R + ", A: " + A; } /// <summary> /// Casts a ColorBgra to a UInt32. /// </summary> public static explicit operator UInt32(ColorBgra color) { return color.Bgra; } /// <summary> /// Casts a UInt32 to a ColorBgra. /// </summary> public static explicit operator ColorBgra(UInt32 uint32) { return ColorBgra.FromUInt32(uint32); } //// Colors: copied from System.Drawing.Color's list (don't worry I didn't type it in //// manually, I used a code generator w/ reflection ...) public static ColorBgra Transparent { get { return ColorBgra.FromBgra(255, 255, 255, 0); } } public static ColorBgra Black { get { return ColorBgra.FromBgra(0, 0, 0, 255); } } public static ColorBgra White { get { return ColorBgra.FromBgra(255, 255, 255, 255); } } public static ColorBgra Red { get { return ColorBgra.FromBgra(0, 0, 255, 255); } } public static ColorBgra Green { get { return ColorBgra.FromBgra(0, 255, 0, 255); } } public static ColorBgra Blue { get { return ColorBgra.FromBgra(255, 0, 0, 255); } } } }
using System; using System.IO; using ICSharpCode.SharpZipLib.Checksum; using ICSharpCode.SharpZipLib.Encryption; using ICSharpCode.SharpZipLib.Zip.Compression; using ICSharpCode.SharpZipLib.Zip.Compression.Streams; namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// This is an InflaterInputStream that reads the files baseInputStream an zip archive /// one after another. It has a special method to get the zip entry of /// the next file. The zip entry contains information about the file name /// size, compressed size, Crc, etc. /// It includes support for Stored and Deflated entries. /// <br/> /// <br/>Author of the original java version : Jochen Hoenicke /// </summary> /// /// <example> This sample shows how to read a zip file /// <code lang="C#"> /// using System; /// using System.Text; /// using System.IO; /// /// using ICSharpCode.SharpZipLib.Zip; /// /// class MainClass /// { /// public static void Main(string[] args) /// { /// using ( ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]))) { /// /// ZipEntry theEntry; /// const int size = 2048; /// byte[] data = new byte[2048]; /// /// while ((theEntry = s.GetNextEntry()) != null) { /// if ( entry.IsFile ) { /// Console.Write("Show contents (y/n) ?"); /// if (Console.ReadLine() == "y") { /// while (true) { /// size = s.Read(data, 0, data.Length); /// if (size > 0) { /// Console.Write(new ASCIIEncoding().GetString(data, 0, size)); /// } else { /// break; /// } /// } /// } /// } /// } /// } /// } /// } /// </code> /// </example> public class ZipInputStream : InflaterInputStream { #region Instance Fields /// <summary> /// Delegate for reading bytes from a stream. /// </summary> delegate int ReadDataHandler(byte[] b, int offset, int length); /// <summary> /// The current reader this instance. /// </summary> ReadDataHandler internalReader; Crc32 crc = new Crc32(); ZipEntry entry; long size; int method; int flags; string password; #endregion #region Constructors /// <summary> /// Creates a new Zip input stream, for reading a zip archive. /// </summary> /// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param> public ZipInputStream(Stream baseInputStream) : base(baseInputStream, new Inflater(true)) { internalReader = new ReadDataHandler(ReadingNotAvailable); } /// <summary> /// Creates a new Zip input stream, for reading a zip archive. /// </summary> /// <param name="baseInputStream">The underlying <see cref="Stream"/> providing data.</param> /// <param name="bufferSize">Size of the buffer.</param> public ZipInputStream(Stream baseInputStream, int bufferSize) : base(baseInputStream, new Inflater(true), bufferSize) { internalReader = new ReadDataHandler(ReadingNotAvailable); } #endregion /// <summary> /// Optional password used for encryption when non-null /// </summary> /// <value>A password for all encrypted <see cref="ZipEntry">entries </see> in this <see cref="ZipInputStream"/></value> public string Password { get { return password; } set { password = value; } } /// <summary> /// Gets a value indicating if there is a current entry and it can be decompressed /// </summary> /// <remarks> /// The entry can only be decompressed if the library supports the zip features required to extract it. /// See the <see cref="ZipEntry.Version">ZipEntry Version</see> property for more details. /// </remarks> public bool CanDecompressEntry { get { return (entry != null) && entry.CanDecompress; } } /// <summary> /// Advances to the next entry in the archive /// </summary> /// <returns> /// The next <see cref="ZipEntry">entry</see> in the archive or null if there are no more entries. /// </returns> /// <remarks> /// If the previous entry is still open <see cref="CloseEntry">CloseEntry</see> is called. /// </remarks> /// <exception cref="InvalidOperationException"> /// Input stream is closed /// </exception> /// <exception cref="ZipException"> /// Password is not set, password is invalid, compression method is invalid, /// version required to extract is not supported /// </exception> public ZipEntry GetNextEntry() { if (crc == null) { throw new InvalidOperationException("Closed."); } if (entry != null) { CloseEntry(); } int header = inputBuffer.ReadLeInt(); if (header == ZipConstants.CentralHeaderSignature || header == ZipConstants.EndOfCentralDirectorySignature || header == ZipConstants.CentralHeaderDigitalSignature || header == ZipConstants.ArchiveExtraDataSignature || header == ZipConstants.Zip64CentralFileHeaderSignature) { // No more individual entries exist Close(); return null; } // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found // Spanning signature is same as descriptor signature and is untested as yet. if ((header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature)) { header = inputBuffer.ReadLeInt(); } if (header != ZipConstants.LocalHeaderSignature) { throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header)); } var versionRequiredToExtract = (short)inputBuffer.ReadLeShort(); flags = inputBuffer.ReadLeShort(); method = inputBuffer.ReadLeShort(); var dostime = (uint)inputBuffer.ReadLeInt(); int crc2 = inputBuffer.ReadLeInt(); csize = inputBuffer.ReadLeInt(); size = inputBuffer.ReadLeInt(); int nameLen = inputBuffer.ReadLeShort(); int extraLen = inputBuffer.ReadLeShort(); bool isCrypted = (flags & 1) == 1; byte[] buffer = new byte[nameLen]; inputBuffer.ReadRawBuffer(buffer); string name = ZipConstants.ConvertToStringExt(flags, buffer); entry = new ZipEntry(name, versionRequiredToExtract); entry.Flags = flags; entry.CompressionMethod = (CompressionMethod)method; if ((flags & 8) == 0) { entry.Crc = crc2 & 0xFFFFFFFFL; entry.Size = size & 0xFFFFFFFFL; entry.CompressedSize = csize & 0xFFFFFFFFL; entry.CryptoCheckValue = (byte)((crc2 >> 24) & 0xff); } else { // This allows for GNU, WinZip and possibly other archives, the PKZIP spec // says these values are zero under these circumstances. if (crc2 != 0) { entry.Crc = crc2 & 0xFFFFFFFFL; } if (size != 0) { entry.Size = size & 0xFFFFFFFFL; } if (csize != 0) { entry.CompressedSize = csize & 0xFFFFFFFFL; } entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff); } entry.DosTime = dostime; // If local header requires Zip64 is true then the extended header should contain // both values. // Handle extra data if present. This can set/alter some fields of the entry. if (extraLen > 0) { byte[] extra = new byte[extraLen]; inputBuffer.ReadRawBuffer(extra); entry.ExtraData = extra; } entry.ProcessExtraData(true); if (entry.CompressedSize >= 0) { csize = entry.CompressedSize; } if (entry.Size >= 0) { size = entry.Size; } if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size))) { throw new ZipException("Stored, but compressed != uncompressed"); } // Determine how to handle reading of data if this is attempted. if (entry.IsCompressionMethodSupported()) { internalReader = new ReadDataHandler(InitialRead); } else { internalReader = new ReadDataHandler(ReadingNotSupported); } return entry; } /// <summary> /// Read data descriptor at the end of compressed data. /// </summary> void ReadDataDescriptor() { if (inputBuffer.ReadLeInt() != ZipConstants.DataDescriptorSignature) { throw new ZipException("Data descriptor signature not found"); } entry.Crc = inputBuffer.ReadLeInt() & 0xFFFFFFFFL; if (entry.LocalHeaderRequiresZip64) { csize = inputBuffer.ReadLeLong(); size = inputBuffer.ReadLeLong(); } else { csize = inputBuffer.ReadLeInt(); size = inputBuffer.ReadLeInt(); } entry.CompressedSize = csize; entry.Size = size; } /// <summary> /// Complete cleanup as the final part of closing. /// </summary> /// <param name="testCrc">True if the crc value should be tested</param> void CompleteCloseEntry(bool testCrc) { StopDecrypting(); if ((flags & 8) != 0) { ReadDataDescriptor(); } size = 0; if (testCrc && ((crc.Value & 0xFFFFFFFFL) != entry.Crc) && (entry.Crc != -1)) { throw new ZipException("CRC mismatch"); } crc.Reset(); if (method == (int)CompressionMethod.Deflated) { inf.Reset(); } entry = null; } /// <summary> /// Closes the current zip entry and moves to the next one. /// </summary> /// <exception cref="InvalidOperationException"> /// The stream is closed /// </exception> /// <exception cref="ZipException"> /// The Zip stream ends early /// </exception> public void CloseEntry() { if (crc == null) { throw new InvalidOperationException("Closed"); } if (entry == null) { return; } if (method == (int)CompressionMethod.Deflated) { if ((flags & 8) != 0) { // We don't know how much we must skip, read until end. byte[] tmp = new byte[4096]; // Read will close this entry while (Read(tmp, 0, tmp.Length) > 0) { } return; } csize -= inf.TotalIn; inputBuffer.Available += inf.RemainingInput; } if ((inputBuffer.Available > csize) && (csize >= 0)) { inputBuffer.Available = (int)((long)inputBuffer.Available - csize); } else { csize -= inputBuffer.Available; inputBuffer.Available = 0; while (csize != 0) { long skipped = Skip(csize); if (skipped <= 0) { throw new ZipException("Zip archive ends early."); } csize -= skipped; } } CompleteCloseEntry(false); } /// <summary> /// Returns 1 if there is an entry available /// Otherwise returns 0. /// </summary> public override int Available { get { return entry != null ? 1 : 0; } } /// <summary> /// Returns the current size that can be read from the current entry if available /// </summary> /// <exception cref="ZipException">Thrown if the entry size is not known.</exception> /// <exception cref="InvalidOperationException">Thrown if no entry is currently available.</exception> public override long Length { get { if (entry != null) { if (entry.Size >= 0) { return entry.Size; } else { throw new ZipException("Length not available for the current entry"); } } else { throw new InvalidOperationException("No current entry"); } } } /// <summary> /// Reads a byte from the current zip entry. /// </summary> /// <returns> /// The byte or -1 if end of stream is reached. /// </returns> public override int ReadByte() { byte[] b = new byte[1]; if (Read(b, 0, 1) <= 0) { return -1; } return b[0] & 0xff; } /// <summary> /// Handle attempts to read by throwing an <see cref="InvalidOperationException"/>. /// </summary> /// <param name="destination">The destination array to store data in.</param> /// <param name="offset">The offset at which data read should be stored.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>Returns the number of bytes actually read.</returns> int ReadingNotAvailable(byte[] destination, int offset, int count) { throw new InvalidOperationException("Unable to read from this stream"); } /// <summary> /// Handle attempts to read from this entry by throwing an exception /// </summary> int ReadingNotSupported(byte[] destination, int offset, int count) { throw new ZipException("The compression method for this entry is not supported"); } /// <summary> /// Perform the initial read on an entry which may include /// reading encryption headers and setting up inflation. /// </summary> /// <param name="destination">The destination to fill with data read.</param> /// <param name="offset">The offset to start reading at.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <returns>The actual number of bytes read.</returns> int InitialRead(byte[] destination, int offset, int count) { if (!CanDecompressEntry) { throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version + ")"); } // Handle encryption if required. if (entry.IsCrypted) { if (password == null) { throw new ZipException("No password set."); } // Generate and set crypto transform... var managed = new PkzipClassicManaged(); byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password)); inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null); byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize]; inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize); if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) { throw new ZipException("Invalid password"); } if (csize >= ZipConstants.CryptoHeaderSize) { csize -= ZipConstants.CryptoHeaderSize; } else if ((entry.Flags & (int)GeneralBitFlags.Descriptor) == 0) { throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize)); } } else { inputBuffer.CryptoTransform = null; } if ((csize > 0) || ((flags & (int)GeneralBitFlags.Descriptor) != 0)) { if ((method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0)) { inputBuffer.SetInflaterInput(inf); } internalReader = new ReadDataHandler(BodyRead); return BodyRead(destination, offset, count); } else { internalReader = new ReadDataHandler(ReadingNotAvailable); return 0; } } /// <summary> /// Read a block of bytes from the stream. /// </summary> /// <param name="buffer">The destination for the bytes.</param> /// <param name="offset">The index to start storing data.</param> /// <param name="count">The number of bytes to attempt to read.</param> /// <returns>Returns the number of bytes read.</returns> /// <remarks>Zero bytes read means end of stream.</remarks> public override int Read(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset), "Cannot be negative"); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), "Cannot be negative"); } if ((buffer.Length - offset) < count) { throw new ArgumentException("Invalid offset/count combination"); } return internalReader(buffer, offset, count); } /// <summary> /// Reads a block of bytes from the current zip entry. /// </summary> /// <returns> /// The number of bytes read (this may be less than the length requested, even before the end of stream), or 0 on end of stream. /// </returns> /// <exception name="IOException"> /// An i/o error occured. /// </exception> /// <exception cref="ZipException"> /// The deflated stream is corrupted. /// </exception> /// <exception cref="InvalidOperationException"> /// The stream is not open. /// </exception> int BodyRead(byte[] buffer, int offset, int count) { if (crc == null) { throw new InvalidOperationException("Closed"); } if ((entry == null) || (count <= 0)) { return 0; } if (offset + count > buffer.Length) { throw new ArgumentException("Offset + count exceeds buffer size"); } bool finished = false; switch (method) { case (int)CompressionMethod.Deflated: count = base.Read(buffer, offset, count); if (count <= 0) { if (!inf.IsFinished) { throw new ZipException("Inflater not finished!"); } inputBuffer.Available = inf.RemainingInput; // A csize of -1 is from an unpatched local header if ((flags & 8) == 0 && (inf.TotalIn != csize && csize != 0xFFFFFFFF && csize != -1 || inf.TotalOut != size)) { throw new ZipException("Size mismatch: " + csize + ";" + size + " <-> " + inf.TotalIn + ";" + inf.TotalOut); } inf.Reset(); finished = true; } break; case (int)CompressionMethod.Stored: if ((count > csize) && (csize >= 0)) { count = (int)csize; } if (count > 0) { count = inputBuffer.ReadClearTextBuffer(buffer, offset, count); if (count > 0) { csize -= count; size -= count; } } if (csize == 0) { finished = true; } else { if (count < 0) { throw new ZipException("EOF in stored block"); } } break; } if (count > 0) { crc.Update(buffer, offset, count); } if (finished) { CompleteCloseEntry(true); } return count; } /// <summary> /// Closes the zip input stream /// </summary> public override void Close() { internalReader = new ReadDataHandler(ReadingNotAvailable); crc = null; entry = null; base.Close(); } } }
// 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.Threading.Tasks; using System; using System.IO; using System.Text; using System.Xml; using System.Diagnostics; using System.Collections; using System.Globalization; using System.Collections.Generic; // OpenIssue : is it better to cache the current namespace decls for each elem // as the current code does, or should it just always walk the namespace stack? namespace System.Xml { internal partial class XmlWellFormedWriter : XmlWriter { public override Task WriteStartDocumentAsync() { return WriteStartDocumentImplAsync(XmlStandalone.Omit); } public override Task WriteStartDocumentAsync(bool standalone) { return WriteStartDocumentImplAsync(standalone ? XmlStandalone.Yes : XmlStandalone.No); } public override async Task WriteEndDocumentAsync() { try { // auto-close all elements while (_elemTop > 0) { await WriteEndElementAsync().ConfigureAwait(false); } State prevState = _currentState; await AdvanceStateAsync(Token.EndDocument).ConfigureAwait(false); if (prevState != State.AfterRootEle) { throw new ArgumentException(SR.Xml_NoRoot); } if (_rawWriter == null) { await _writer.WriteEndDocumentAsync().ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { try { if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } XmlConvert.VerifyQName(name, ExceptionType.XmlException); if (_conformanceLevel == ConformanceLevel.Fragment) { throw new InvalidOperationException(SR.Xml_DtdNotAllowedInFragment); } await AdvanceStateAsync(Token.Dtd).ConfigureAwait(false); if (_dtdWritten) { _currentState = State.Error; throw new InvalidOperationException(SR.Xml_DtdAlreadyWritten); } if (_conformanceLevel == ConformanceLevel.Auto) { _conformanceLevel = ConformanceLevel.Document; _stateTable = s_stateTableDocument; } int i; // check characters if (_checkCharacters) { if (pubid != null) { if ((i = _xmlCharType.IsPublicId(pubid)) >= 0) { throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(pubid, i)), "pubid"); } } if (sysid != null) { if ((i = _xmlCharType.IsOnlyCharData(sysid)) >= 0) { throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(sysid, i)), "sysid"); } } if (subset != null) { if ((i = _xmlCharType.IsOnlyCharData(subset)) >= 0) { throw new ArgumentException(SR.Format(SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(subset, i)), "subset"); } } } // write doctype await _writer.WriteDocTypeAsync(name, pubid, sysid, subset).ConfigureAwait(false); _dtdWritten = true; } catch { _currentState = State.Error; throw; } } //check if any exception before return the task private Task TryReturnTask(Task task) { if (task.IsSuccess()) { return Task.CompletedTask; } else { return _TryReturnTask(task); } } private async Task _TryReturnTask(Task task) { try { await task.ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } //call nextTaskFun after task finish. Check exception. private Task SequenceRun<TArg>(Task task, Func<TArg, Task> nextTaskFun, TArg arg) { if (task.IsSuccess()) { return TryReturnTask(nextTaskFun(arg)); } else { return _SequenceRun(task, nextTaskFun, arg); } } private async Task _SequenceRun<TArg>(Task task, Func<TArg, Task> nextTaskFun, TArg arg) { try { await task.ConfigureAwait(false); await nextTaskFun(arg).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override Task WriteStartElementAsync(string prefix, string localName, string ns) { try { // check local name if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } CheckNCName(localName); Task task = AdvanceStateAsync(Token.StartElement); if (task.IsSuccess()) { return WriteStartElementAsync_NoAdvanceState(prefix, localName, ns); } else { return WriteStartElementAsync_NoAdvanceState(task, prefix, localName, ns); } } catch { _currentState = State.Error; throw; } } private Task WriteStartElementAsync_NoAdvanceState(string prefix, string localName, string ns) { try { // lookup prefix / namespace if (prefix == null) { if (ns != null) { prefix = LookupPrefix(ns); } if (prefix == null) { prefix = string.Empty; } } else if (prefix.Length > 0) { CheckNCName(prefix); if (ns == null) { ns = LookupNamespace(prefix); } if (ns == null || (ns != null && ns.Length == 0)) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); } } if (ns == null) { ns = LookupNamespace(prefix); if (ns == null) { Debug.Assert(prefix.Length == 0); ns = string.Empty; } } if (_elemTop == 0 && _rawWriter != null) { // notify the underlying raw writer about the root level element _rawWriter.OnRootElement(_conformanceLevel); } // write start tag Task task = _writer.WriteStartElementAsync(prefix, localName, ns); if (task.IsSuccess()) { WriteStartElementAsync_FinishWrite(prefix, localName, ns); } else { return WriteStartElementAsync_FinishWrite(task, prefix, localName, ns); } return Task.CompletedTask; } catch { _currentState = State.Error; throw; } } private async Task WriteStartElementAsync_NoAdvanceState(Task task, string prefix, string localName, string ns) { try { await task.ConfigureAwait(false); await WriteStartElementAsync_NoAdvanceState(prefix, localName, ns).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } private void WriteStartElementAsync_FinishWrite(string prefix, string localName, string ns) { try { // push element on stack and add/check namespace int top = ++_elemTop; if (top == _elemScopeStack.Length) { ElementScope[] newStack = new ElementScope[top * 2]; Array.Copy(_elemScopeStack, newStack, top); _elemScopeStack = newStack; } _elemScopeStack[top].Set(prefix, localName, ns, _nsTop); PushNamespaceImplicit(prefix, ns); if (_attrCount >= MaxAttrDuplWalkCount) { _attrHashTable.Clear(); } _attrCount = 0; } catch { _currentState = State.Error; throw; } } private async Task WriteStartElementAsync_FinishWrite(Task t, string prefix, string localName, string ns) { try { await t.ConfigureAwait(false); WriteStartElementAsync_FinishWrite(prefix, localName, ns); } catch { _currentState = State.Error; throw; } } public override Task WriteEndElementAsync() { try { Task task = AdvanceStateAsync(Token.EndElement); return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_NoAdvanceState(), this); } catch { _currentState = State.Error; throw; } } private Task WriteEndElementAsync_NoAdvanceState() { try { int top = _elemTop; if (top == 0) { throw new XmlException(SR.Xml_NoStartTag, string.Empty); } Task task; // write end tag if (_rawWriter != null) { task = _elemScopeStack[top].WriteEndElementAsync(_rawWriter); } else { task = _writer.WriteEndElementAsync(); } return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_FinishWrite(), this); } catch { _currentState = State.Error; throw; } } private Task WriteEndElementAsync_FinishWrite() { try { int top = _elemTop; // pop namespaces int prevNsTop = _elemScopeStack[top].prevNSTop; if (_useNsHashtable && prevNsTop < _nsTop) { PopNamespaces(prevNsTop + 1, _nsTop); } _nsTop = prevNsTop; _elemTop = --top; // check "one root element" condition for ConformanceLevel.Document if (top == 0) { if (_conformanceLevel == ConformanceLevel.Document) { _currentState = State.AfterRootEle; } else { _currentState = State.TopLevel; } } } catch { _currentState = State.Error; throw; } return Task.CompletedTask; } public override Task WriteFullEndElementAsync() { try { Task task = AdvanceStateAsync(Token.EndElement); return SequenceRun(task, thisRef => thisRef.WriteFullEndElementAsync_NoAdvanceState(), this); } catch { _currentState = State.Error; throw; } } private Task WriteFullEndElementAsync_NoAdvanceState() { try { int top = _elemTop; if (top == 0) { throw new XmlException(SR.Xml_NoStartTag, string.Empty); } Task task; // write end tag if (_rawWriter != null) { task = _elemScopeStack[top].WriteFullEndElementAsync(_rawWriter); } else { task = _writer.WriteFullEndElementAsync(); } return SequenceRun(task, thisRef => thisRef.WriteEndElementAsync_FinishWrite(), this); } catch { _currentState = State.Error; throw; } } protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string namespaceName) { try { // check local name if (localName == null || localName.Length == 0) { if (prefix == "xmlns") { localName = "xmlns"; prefix = string.Empty; } else { throw new ArgumentException(SR.Xml_EmptyLocalName); } } CheckNCName(localName); Task task = AdvanceStateAsync(Token.StartAttribute); if (task.IsSuccess()) { return WriteStartAttributeAsync_NoAdvanceState(prefix, localName, namespaceName); } else { return WriteStartAttributeAsync_NoAdvanceState(task, prefix, localName, namespaceName); } } catch { _currentState = State.Error; throw; } } private Task WriteStartAttributeAsync_NoAdvanceState(string prefix, string localName, string namespaceName) { try { // lookup prefix / namespace if (prefix == null) { if (namespaceName != null) { // special case prefix=null/localname=xmlns if (!(localName == "xmlns" && namespaceName == XmlReservedNs.NsXmlNs)) prefix = LookupPrefix(namespaceName); } if (prefix == null) { prefix = string.Empty; } } if (namespaceName == null) { if (prefix != null && prefix.Length > 0) { namespaceName = LookupNamespace(prefix); } if (namespaceName == null) { namespaceName = string.Empty; } } if (prefix.Length == 0) { if (localName[0] == 'x' && localName == "xmlns") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs) { throw new ArgumentException(SR.Xml_XmlnsPrefix); } _curDeclPrefix = String.Empty; SetSpecialAttribute(SpecialAttribute.DefaultXmlns); goto SkipPushAndWrite; } else if (namespaceName.Length > 0) { prefix = LookupPrefix(namespaceName); if (prefix == null || prefix.Length == 0) { prefix = GeneratePrefix(); } } } else { if (prefix[0] == 'x') { if (prefix == "xmlns") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXmlNs) { throw new ArgumentException(SR.Xml_XmlnsPrefix); } _curDeclPrefix = localName; SetSpecialAttribute(SpecialAttribute.PrefixedXmlns); goto SkipPushAndWrite; } else if (prefix == "xml") { if (namespaceName.Length > 0 && namespaceName != XmlReservedNs.NsXml) { throw new ArgumentException(SR.Xml_XmlPrefix); } switch (localName) { case "space": SetSpecialAttribute(SpecialAttribute.XmlSpace); goto SkipPushAndWrite; case "lang": SetSpecialAttribute(SpecialAttribute.XmlLang); goto SkipPushAndWrite; } } } CheckNCName(prefix); if (namespaceName.Length == 0) { // attributes cannot have default namespace prefix = string.Empty; } else { string definedNs = LookupLocalNamespace(prefix); if (definedNs != null && definedNs != namespaceName) { prefix = GeneratePrefix(); } } } if (prefix.Length != 0) { PushNamespaceImplicit(prefix, namespaceName); } SkipPushAndWrite: // add attribute to the list and check for duplicates AddAttribute(prefix, localName, namespaceName); if (_specAttr == SpecialAttribute.No) { // write attribute name return TryReturnTask(_writer.WriteStartAttributeAsync(prefix, localName, namespaceName)); } return Task.CompletedTask; } catch { _currentState = State.Error; throw; } } private async Task WriteStartAttributeAsync_NoAdvanceState(Task task, string prefix, string localName, string namespaceName) { try { await task.ConfigureAwait(false); await WriteStartAttributeAsync_NoAdvanceState(prefix, localName, namespaceName).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } protected internal override Task WriteEndAttributeAsync() { try { Task task = AdvanceStateAsync(Token.EndAttribute); return SequenceRun(task, thisRef => thisRef.WriteEndAttributeAsync_NoAdvance(), this); } catch { _currentState = State.Error; throw; } } private Task WriteEndAttributeAsync_NoAdvance() { try { if (_specAttr != SpecialAttribute.No) { return WriteEndAttributeAsync_SepcialAtt(); } else { return TryReturnTask(_writer.WriteEndAttributeAsync()); } } catch { _currentState = State.Error; throw; } } private async Task WriteEndAttributeAsync_SepcialAtt() { try { string value; switch (_specAttr) { case SpecialAttribute.DefaultXmlns: value = _attrValueCache.StringValue; if (PushNamespaceExplicit(string.Empty, value)) { // returns true if the namespace declaration should be written out if (_rawWriter != null) { if (_rawWriter.SupportsNamespaceDeclarationInChunks) { await _rawWriter.WriteStartNamespaceDeclarationAsync(string.Empty).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_rawWriter).ConfigureAwait(false); await _rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false); } else { await _rawWriter.WriteNamespaceDeclarationAsync(string.Empty, value).ConfigureAwait(false); } } else { await _writer.WriteStartAttributeAsync(string.Empty, "xmlns", XmlReservedNs.NsXmlNs).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); } } _curDeclPrefix = null; break; case SpecialAttribute.PrefixedXmlns: value = _attrValueCache.StringValue; if (value.Length == 0) { throw new ArgumentException(SR.Xml_PrefixForEmptyNs); } if (value == XmlReservedNs.NsXmlNs || (value == XmlReservedNs.NsXml && _curDeclPrefix != "xml")) { throw new ArgumentException(SR.Xml_CanNotBindToReservedNamespace); } if (PushNamespaceExplicit(_curDeclPrefix, value)) { // returns true if the namespace declaration should be written out if (_rawWriter != null) { if (_rawWriter.SupportsNamespaceDeclarationInChunks) { await _rawWriter.WriteStartNamespaceDeclarationAsync(_curDeclPrefix).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_rawWriter).ConfigureAwait(false); await _rawWriter.WriteEndNamespaceDeclarationAsync().ConfigureAwait(false); } else { await _rawWriter.WriteNamespaceDeclarationAsync(_curDeclPrefix, value).ConfigureAwait(false); } } else { await _writer.WriteStartAttributeAsync("xmlns", _curDeclPrefix, XmlReservedNs.NsXmlNs).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); } } _curDeclPrefix = null; break; case SpecialAttribute.XmlSpace: _attrValueCache.Trim(); value = _attrValueCache.StringValue; if (value == "default") { _elemScopeStack[_elemTop].xmlSpace = XmlSpace.Default; } else if (value == "preserve") { _elemScopeStack[_elemTop].xmlSpace = XmlSpace.Preserve; } else { throw new ArgumentException(SR.Format(SR.Xml_InvalidXmlSpace, value)); } await _writer.WriteStartAttributeAsync("xml", "space", XmlReservedNs.NsXml).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); break; case SpecialAttribute.XmlLang: value = _attrValueCache.StringValue; _elemScopeStack[_elemTop].xmlLang = value; await _writer.WriteStartAttributeAsync("xml", "lang", XmlReservedNs.NsXml).ConfigureAwait(false); await _attrValueCache.ReplayAsync(_writer).ConfigureAwait(false); await _writer.WriteEndAttributeAsync().ConfigureAwait(false); break; } _specAttr = SpecialAttribute.No; _attrValueCache.Clear(); } catch { _currentState = State.Error; throw; } } public override async Task WriteCDataAsync(string text) { try { if (text == null) { text = string.Empty; } await AdvanceStateAsync(Token.CData).ConfigureAwait(false); await _writer.WriteCDataAsync(text).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteCommentAsync(string text) { try { if (text == null) { text = string.Empty; } await AdvanceStateAsync(Token.Comment).ConfigureAwait(false); await _writer.WriteCommentAsync(text).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteProcessingInstructionAsync(string name, string text) { try { // check name if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } CheckNCName(name); // check text if (text == null) { text = string.Empty; } // xml declaration is a special case (not a processing instruction, but we allow WriteProcessingInstruction as a convenience) if (name.Length == 3 && string.Equals(name, "xml", StringComparison.OrdinalIgnoreCase)) { if (_currentState != State.Start) { throw new ArgumentException(_conformanceLevel == ConformanceLevel.Document ? SR.Xml_DupXmlDecl : SR.Xml_CannotWriteXmlDecl); } _xmlDeclFollows = true; await AdvanceStateAsync(Token.PI).ConfigureAwait(false); if (_rawWriter != null) { // Translate PI into an xml declaration await _rawWriter.WriteXmlDeclarationAsync(text).ConfigureAwait(false); } else { await _writer.WriteProcessingInstructionAsync(name, text).ConfigureAwait(false); } } else { await AdvanceStateAsync(Token.PI).ConfigureAwait(false); await _writer.WriteProcessingInstructionAsync(name, text).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteEntityRefAsync(string name) { try { // check name if (name == null || name.Length == 0) { throw new ArgumentException(SR.Xml_EmptyName); } CheckNCName(name); await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteEntityRef(name); } else { await _writer.WriteEntityRefAsync(name).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteCharEntityAsync(char ch) { try { if (Char.IsSurrogate(ch)) { throw new ArgumentException(SR.Xml_InvalidSurrogateMissingLowChar); } await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteCharEntity(ch); } else { await _writer.WriteCharEntityAsync(ch).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { try { if (!Char.IsSurrogatePair(highChar, lowChar)) { throw XmlConvert.CreateInvalidSurrogatePairException(lowChar, highChar); } await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteSurrogateCharEntity(lowChar, highChar); } else { await _writer.WriteSurrogateCharEntityAsync(lowChar, highChar).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteWhitespaceAsync(string ws) { try { if (ws == null) { ws = string.Empty; } if (!XmlCharType.Instance.IsOnlyWhitespace(ws)) { throw new ArgumentException(SR.Xml_NonWhitespace); } await AdvanceStateAsync(Token.Whitespace).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteWhitespace(ws); } else { await _writer.WriteWhitespaceAsync(ws).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override Task WriteStringAsync(string text) { try { if (text == null) { return Task.CompletedTask; } Task task = AdvanceStateAsync(Token.Text); if (task.IsSuccess()) { return WriteStringAsync_NoAdvanceState(text); } else { return WriteStringAsync_NoAdvanceState(task, text); } } catch { _currentState = State.Error; throw; } } private Task WriteStringAsync_NoAdvanceState(string text) { try { if (SaveAttrValue) { _attrValueCache.WriteString(text); return Task.CompletedTask; } else { return TryReturnTask(_writer.WriteStringAsync(text)); } } catch { _currentState = State.Error; throw; } } private async Task WriteStringAsync_NoAdvanceState(Task task, string text) { try { await task.ConfigureAwait(false); await WriteStringAsync_NoAdvanceState(text).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteCharsAsync(char[] buffer, int index, int count) { try { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } await AdvanceStateAsync(Token.Text).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteChars(buffer, index, count); } else { await _writer.WriteCharsAsync(buffer, index, count).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteRawAsync(char[] buffer, int index, int count) { try { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } await AdvanceStateAsync(Token.RawData).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteRaw(buffer, index, count); } else { await _writer.WriteRawAsync(buffer, index, count).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteRawAsync(string data) { try { if (data == null) { return; } await AdvanceStateAsync(Token.RawData).ConfigureAwait(false); if (SaveAttrValue) { _attrValueCache.WriteRaw(data); } else { await _writer.WriteRawAsync(data).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override Task WriteBase64Async(byte[] buffer, int index, int count) { try { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - index) { throw new ArgumentOutOfRangeException(nameof(count)); } Task task = AdvanceStateAsync(Token.Base64); if (task.IsSuccess()) { return TryReturnTask(_writer.WriteBase64Async(buffer, index, count)); } else { return WriteBase64Async_NoAdvanceState(task, buffer, index, count); } } catch { _currentState = State.Error; throw; } } private async Task WriteBase64Async_NoAdvanceState(Task task, byte[] buffer, int index, int count) { try { await task.ConfigureAwait(false); await _writer.WriteBase64Async(buffer, index, count).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task FlushAsync() { try { await _writer.FlushAsync().ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } public override async Task WriteQualifiedNameAsync(string localName, string ns) { try { if (localName == null || localName.Length == 0) { throw new ArgumentException(SR.Xml_EmptyLocalName); } CheckNCName(localName); await AdvanceStateAsync(Token.Text).ConfigureAwait(false); string prefix = String.Empty; if (ns != null && ns.Length != 0) { prefix = LookupPrefix(ns); if (prefix == null) { if (_currentState != State.Attribute) { throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns)); } prefix = GeneratePrefix(); PushNamespaceImplicit(prefix, ns); } } // if this is a special attribute, then just convert this to text // otherwise delegate to raw-writer if (SaveAttrValue || _rawWriter == null) { if (prefix.Length != 0) { await WriteStringAsync(prefix).ConfigureAwait(false); await WriteStringAsync(":").ConfigureAwait(false); } await WriteStringAsync(localName).ConfigureAwait(false); } else { await _rawWriter.WriteQualifiedNameAsync(prefix, localName, ns).ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } public override async Task WriteBinHexAsync(byte[] buffer, int index, int count) { if (IsClosedOrErrorState) { throw new InvalidOperationException(SR.Xml_ClosedOrError); } try { await AdvanceStateAsync(Token.Text).ConfigureAwait(false); await base.WriteBinHexAsync(buffer, index, count).ConfigureAwait(false); } catch { _currentState = State.Error; throw; } } private async Task WriteStartDocumentImplAsync(XmlStandalone standalone) { try { await AdvanceStateAsync(Token.StartDocument).ConfigureAwait(false); if (_conformanceLevel == ConformanceLevel.Auto) { _conformanceLevel = ConformanceLevel.Document; _stateTable = s_stateTableDocument; } else if (_conformanceLevel == ConformanceLevel.Fragment) { throw new InvalidOperationException(SR.Xml_CannotStartDocumentOnFragment); } if (_rawWriter != null) { if (!_xmlDeclFollows) { await _rawWriter.WriteXmlDeclarationAsync(standalone).ConfigureAwait(false); } } else { // We do not pass the standalone value here await _writer.WriteStartDocumentAsync().ConfigureAwait(false); } } catch { _currentState = State.Error; throw; } } //call taskFun and change state in sequence private Task AdvanceStateAsync_ReturnWhenFinish(Task task, State newState) { if (task.IsSuccess()) { _currentState = newState; return Task.CompletedTask; } else { return _AdvanceStateAsync_ReturnWhenFinish(task, newState); } } private async Task _AdvanceStateAsync_ReturnWhenFinish(Task task, State newState) { await task.ConfigureAwait(false); _currentState = newState; } private Task AdvanceStateAsync_ContinueWhenFinish(Task task, State newState, Token token) { if (task.IsSuccess()) { _currentState = newState; return AdvanceStateAsync(token); } else { return _AdvanceStateAsync_ContinueWhenFinish(task, newState, token); } } private async Task _AdvanceStateAsync_ContinueWhenFinish(Task task, State newState, Token token) { await task.ConfigureAwait(false); _currentState = newState; await AdvanceStateAsync(token).ConfigureAwait(false); } // Advance the state machine private Task AdvanceStateAsync(Token token) { if ((int)_currentState >= (int)State.Closed) { if (_currentState == State.Closed || _currentState == State.Error) { throw new InvalidOperationException(SR.Xml_ClosedOrError); } else { throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, tokenName[(int)token], GetStateName(_currentState))); } } Advance: State newState = _stateTable[((int)token << 4) + (int)_currentState]; // [ (int)token * 16 + (int)currentState ]; Task task; if ((int)newState >= (int)State.Error) { switch (newState) { case State.Error: ThrowInvalidStateTransition(token, _currentState); break; case State.StartContent: return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Content); case State.StartContentEle: return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.Element); case State.StartContentB64: return AdvanceStateAsync_ReturnWhenFinish(StartElementContentAsync(), State.B64Content); case State.StartDoc: return AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Document); case State.StartDocEle: return AdvanceStateAsync_ReturnWhenFinish(WriteStartDocumentAsync(), State.Element); case State.EndAttrSEle: task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this); return AdvanceStateAsync_ReturnWhenFinish(task, State.Element); case State.EndAttrEEle: task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this); return AdvanceStateAsync_ReturnWhenFinish(task, State.Content); case State.EndAttrSCont: task = SequenceRun(WriteEndAttributeAsync(), thisRef => thisRef.StartElementContentAsync(), this); return AdvanceStateAsync_ReturnWhenFinish(task, State.Content); case State.EndAttrSAttr: return AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.Attribute); case State.PostB64Cont: if (_rawWriter != null) { return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.Content, token); } _currentState = State.Content; goto Advance; case State.PostB64Attr: if (_rawWriter != null) { return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.Attribute, token); } _currentState = State.Attribute; goto Advance; case State.PostB64RootAttr: if (_rawWriter != null) { return AdvanceStateAsync_ContinueWhenFinish(_rawWriter.WriteEndBase64Async(), State.RootLevelAttr, token); } _currentState = State.RootLevelAttr; goto Advance; case State.StartFragEle: StartFragment(); newState = State.Element; break; case State.StartFragCont: StartFragment(); newState = State.Content; break; case State.StartFragB64: StartFragment(); newState = State.B64Content; break; case State.StartRootLevelAttr: return AdvanceStateAsync_ReturnWhenFinish(WriteEndAttributeAsync(), State.RootLevelAttr); default: Debug.Assert(false, "We should not get to this point."); break; } } _currentState = newState; return Task.CompletedTask; } // write namespace declarations private async Task StartElementContentAsync_WithNS() { int start = _elemScopeStack[_elemTop].prevNSTop; for (int i = _nsTop; i > start; i--) { if (_nsStack[i].kind == NamespaceKind.NeedToWrite) { await _nsStack[i].WriteDeclAsync(_writer, _rawWriter).ConfigureAwait(false); } } if (_rawWriter != null) { _rawWriter.StartElementContent(); } } private Task StartElementContentAsync() { if (_nsTop > _elemScopeStack[_elemTop].prevNSTop) { return StartElementContentAsync_WithNS(); } if (_rawWriter != null) { _rawWriter.StartElementContent(); } return Task.CompletedTask; } } }
using System; using DebugDiag.Native.Test.Fixtures; using DebugDiag.Native.Test.Mock; using DebugDiag.Native.Type; using DebugDiag.Native.Windbg; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DebugDiag.Native.Test { /// <summary> /// Summary description for TestNative /// </summary> [TestClass] public class TestNativeType { [ClassInitialize] public static void SetUp(TestContext ctx) { Native.Initialize(new MockX86Dump()); } [TestMethod] [ExpectedException(typeof(CommandException))] public void TestPreloadInvalidTypeQualified() { NativeType.Preload("nt!InvalidDoNotExist"); } [TestMethod] [ExpectedException(typeof(CommandException))] public void TestPreloadInvalidTypeUnqualified() { NativeType.Preload("InvalidDoNotExist"); } [TestMethod] public void TestPreloadCompoundType() { // Manually preloading a compound type is very unnatural, since templates usually have many // default parameters that windbg will always output, and requires to be explicitly specified // in order to function properly. // Usually, you should prefer getting the parent type, and navigating to the compound type using // `GetField()` or dynamic accessors. var t = NativeType.Preload(X86.PtrVector); Assert.IsNotNull(t); Assert.AreEqual(X86.PtrVector, t.TypeName); } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void TestNavigateNonInstance() { var t = NativeType.Preload("VirtualTypeDeriv"); t.GetField("POD"); } [TestMethod] public void TestAddressFormat() { var validFormats = new[] { "1234", "0x49beb8", "0x32003200", "32003200", "1234567a", "aabbccdd", "ee000000", "0x6400640064006400", "6400640064006400", "64006400`64006400", "0x64006400`64006400", "0n123", "a" }; var invalidFormats = new[] { "0x", "0n", "'''InvalidSymbols", "ghijklmno", "0xgggggggg", "-1", "null", "0n123a" }; foreach (var addr in validFormats) Assert.IsTrue(Native.AddressFormat.IsMatch(addr), "Adddress {0} should be valid.", addr); foreach (var addr in invalidFormats) Assert.IsFalse(Native.AddressFormat.IsMatch(addr), "Adddress {0} should be invalid", addr); } [TestMethod] public void TestGetFieldByName() { var t = NativeType.AtAddress(X86.VtableAddrULong); var field = t.GetField("POD"); Assert.IsTrue(field is Primitive); Assert.AreEqual(X86.VtableAddrULong + t.GetOffset("POD"), field.Address); Assert.AreEqual(8UL, field); } [TestMethod] public void TestGetIntValueField() { var t = NativeType.AtAddress(X86.VtableAddrULong); Assert.AreEqual(0x0000000200000001UL, t.GetField("MoreOffset")); Assert.AreEqual(8UL, t.GetField(0x004)); } [TestMethod] public void TestDynamicFieldAccess() { dynamic t = NativeType.AtAddress(X86.VtableAddrULong); dynamic field = t.POD; Assert.IsTrue(field is Primitive); Assert.AreEqual(8UL, field); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestInvalidDynamicFieldAccess() { dynamic t = NativeType.AtAddress(X86.VtableAddrULong); var f = t.DoesNotExist; Assert.IsNull(f); } [TestMethod] public void TestGetPrimitiveWhenNotPrimitive() { // WARN: This is not not supported // Consider using a windbg command. var t = NativeType.AtAddress(X86.VtableAddrULong); //var field = t.GetField(0x14); Assert.IsFalse(t is Primitive); Assert.AreEqual(0x0114cc84UL, t); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestGetFieldInvalidOffset() { var t = NativeType.AtAddress(X86.VtableAddrULong); t.GetField(0x10000); // This offset does not belong to that object. } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] public void TestGetFieldInvalidName() { var t = NativeType.AtAddress(X86.VtableAddrULong); t.GetField("DoesNotExist"); // This field does not belong to that object. } [TestMethod] [ExpectedException(typeof(InvalidOperationException))] public void TestGetInstanceWhenPrimitive() { // Getting a field on a primitive is an invalid operation. var t = NativeType.AtAddress(X86.VtableAddrULong); var field = t.GetField(0x4); Assert.IsTrue(field.IsInstance); Assert.IsTrue(field is Primitive); Assert.AreEqual(8UL, field); field.GetField(0x0); } [TestMethod] public void TestGetZeroOffsetWithVtable() { // A virtual type has its vtable at offset 0x000. var t = NativeType.AtAddress(X86.VtableAddrULong); Assert.IsTrue(t.HasVtable); var field = t.GetField(0x0); Assert.IsTrue(field is Pointer); // Change to Vtable once Vtable support is added. Assert.IsTrue(field.IsInstance); Assert.AreEqual("`vftable' *", field.QualifiedName); } [TestMethod] public void TestGetZeroOffsetPod() { // A POD's first member is located at offset 0x000 and can be anything. var t = NativeType.AtAddress(X86.PodTypeAddr, "PODType"); Assert.AreEqual("PODType", t.QualifiedName); var field = t.GetField(0x0); Assert.IsTrue(field is Primitive); Assert.IsTrue(field.IsInstance); Assert.AreEqual(42UL, field); } [TestMethod] public void TestStringToULongLeadingZerosHex() { Assert.AreEqual(0x12345UL, Native.StringAddrToUlong("00012345")); } [TestMethod] public void TestStringToULongLeadingZerosDecimal() { Assert.AreEqual(12345UL, Native.StringAddrToUlong("0n00012345")); } [TestMethod] public void TestStringToULong0X() { Assert.AreEqual(0x12345UL, Native.StringAddrToUlong("0x00012345")); } [TestMethod] public void TestStringToULong0N() { Assert.AreEqual(12345UL, Native.StringAddrToUlong("0n12345")); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestStringToULongInvalidAddr() { Native.StringAddrToUlong("sdlkfjsdlfd"); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestStringToULongEmptyAddr0N() { Native.StringAddrToUlong("0n"); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestStringToULongEmptyAddr0X() { Native.StringAddrToUlong("0x"); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestStringToULongEmptyAddr() { Native.StringAddrToUlong(""); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestStringToULongNullAddr() { Native.StringAddrToUlong(null); } [TestMethod] public void TestAtAddressVtableAsString() { var t = NativeType.AtAddress(X86.VtableAddr); Assert.AreEqual("VirtualTypeDeriv", t.TypeName); Assert.AreEqual("DebugDiag_Native_Test_App", t.ModuleName); Assert.AreEqual("DebugDiag_Native_Test_App!VirtualTypeDeriv", t.QualifiedName); } [TestMethod] public void TestAtAddressVtableAsULong() { var t = NativeType.AtAddress(X86.VtableAddrULong); Assert.AreEqual("VirtualTypeDeriv", t.TypeName); Assert.AreEqual("DebugDiag_Native_Test_App", t.ModuleName); Assert.AreEqual("DebugDiag_Native_Test_App!VirtualTypeDeriv", t.QualifiedName); } [TestMethod] public void TestAtAddressVtableWithoutVtable() { // This type does not have a vtable, we shouldn't be able to find it. var t = NativeType.AtAddress(X86.PodTypeAddr); Assert.IsNull(t); } [TestMethod] public void TestGetAddress() { var t = NativeType.AtAddress(X86.VtableAddrULong); Assert.AreEqual(X86.VtableAddrULong, t.Address); } [TestMethod] public void TestAtAddressNoVtableAsString() { var t = NativeType.AtAddress(X86.PodTypeAddr, "PODType"); Assert.AreEqual(X86.PodTypeAddrULong, t.Address); Assert.AreEqual("PODType", t.TypeName); Assert.AreEqual("PODType", t.QualifiedName); } [TestMethod] public void TestAtAddressNoVtableAsULong() { var t = NativeType.AtAddress(X86.PodTypeAddrULong, "PODType"); Assert.AreEqual(X86.PodTypeAddrULong, t.Address); Assert.AreEqual("PODType", t.TypeName); Assert.AreEqual("PODType", t.QualifiedName); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestAtAddressNull() { NativeType.AtAddress(0, null); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestAtAddressInvalid() { NativeType.AtAddress("notAnAddress"); } [TestMethod] public void TestParseTypeWithBitfield() { var t = NativeType.AtAddress(X86.PebAddr, "nt!_PEB"); var field = t.GetField(0x3); // PEB->BitField Assert.AreEqual(0x8UL, field); } [TestMethod] public void TestParseTypeWithMultipleVtables() { // Nested types with vtables will have more than one __VFN_table member. var t = NativeType.AtAddress(X86.MultiVtableAddr, "MultiVtable"); // No fixture for vtable discovery. Assert.IsNotNull(t); } [TestMethod] public void TestParseCorruptedVtableType() { Assert.Inconclusive("Not implemented."); } [TestMethod] public void TestParseTypeWithStaticField() { var t = NativeType.AtAddress(X86.StaticDtAddr, "HasAStaticField"); var f = t.GetField("IAmSoStatic"); Assert.IsTrue(f is Primitive); Assert.IsTrue(f.IsStatic); Assert.AreEqual(3UL, f); } // TODO: Enable this test and implement it. // Low priority since the same type shouldn't have different static values across module boundaries. //[TestMethod] //public void TestStaticInDifferentModules() //{ // Assert.Inconclusive("Not implemented."); // A static member can have different values in different modules. // This is a disgusting case, but it needs to be handled properly. // The idea is that internally we want to always use the fully qualified type. //} [TestMethod] public void TestDrillDownSubtypes() { // Retrieve the HasAStaticField object. var t = NativeType.AtAddress(X86.StaticDtAddr, "HasAStaticField"); // Drill into its VirtualType instance. var virtualType = t.GetField("subType"); Assert.IsFalse(virtualType is Primitive); Assert.IsFalse(virtualType.IsStatic); Assert.IsTrue(virtualType.IsInstance); Assert.AreEqual("VirtualTypeDeriv", virtualType.TypeName); // Drill into the VirtualType's PODType instance. var podType = virtualType.GetField("PODObject"); Assert.IsFalse(podType is Primitive); Assert.IsFalse(podType.IsStatic); Assert.IsTrue(podType.IsInstance); Assert.AreEqual("PODType", podType.TypeName); // Finally, get the PODType's Offset1 value. var offset1 = podType.GetField(0x000); Assert.AreNotSame(podType, offset1); // This will work because PODType has no vtable. Assert.AreEqual(42UL, offset1); } [TestMethod] public void TestDrillDownSubtypesDynamic() { // Retrieve the HasAStaticField object. dynamic t = NativeType.AtAddress(X86.StaticDtAddr, "HasAStaticField"); // Drill into its VirtualType instance (easily) thanks to Assert.AreEqual(42UL, t.subType.PODObject.Offset1); } [TestMethod] public void TestPrimitiveTypenameParsing() { var valids = new[] {"char", "Uchar", "int", "Int4B", "int8B", "_LARGE_INTEGER", "Uint", "UInt", "Uint2B"}; // float var invalids = new[] { "char32", "Integer", "std::list<int>", "int32_t", "Byte", "Uint3B", "Uint8b"}; foreach (var v in valids) Assert.IsTrue(Parser.PrimitiveSyntax.IsMatch(v), "Expected primitive typename match for {0}", v); foreach (var i in invalids) Assert.IsFalse(Parser.PrimitiveSyntax.IsMatch(i), "Expected non primitive match for {0}", i); } [TestMethod] [ExpectedException(typeof(ArgumentException))] public void TestGetOffsetInvalidField() { dynamic t = NativeType.AtAddress(X86.StaticDtAddr, "HasAStaticField"); t.GetOffset("thisFieldDoesNotExists"); } [TestMethod] public void TestGetOffsetThroughPointer() { Assert.Inconclusive("Unimplemented"); } } }
#pragma warning disable CS0618 using Braintree.Exceptions; using NUnit.Framework; using System.Collections.Generic; namespace Braintree.Tests { [TestFixture] public class BraintreeGraphQLServiceTest { [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_whenErrorExceptionIsNull_throwsUnexpectedException() { GraphQLError error = new GraphQLError(); GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(new GraphQLError()); Assert.Throws<UnexpectedException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_WhenErrorClassIsAuthentication_ThrowsAuthenitcationException() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass", "AUTHENTICATION"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); Assert.Throws<AuthenticationException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_whenErrorClassIsAuthorization_throwsAuthorizationException() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass", "AUTHORIZATION"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); Assert.Throws<AuthorizationException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_whenErrorClassIsNotFound_throwsNotFoundException() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass", "NOT_FOUND"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); Assert.Throws<NotFoundException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_whenErrorClassIsUnsupportedClient_throwsUnsupportedClientException() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass", "UNSUPPORTED_CLIENT"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); Assert.Throws<UpgradeRequiredException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_whenErrorClassIsResourceLimit_throwsTooManyRequestsException() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass", "RESOURCE_LIMIT"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); Assert.Throws<TooManyRequestsException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_whenErrorClassIsInternal_throwsServerException() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass", "INTERNAL"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); Assert.Throws<ServerException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_whenErrorClassIsBraintreeServiceAvailability_throwsServiceUnavailableException() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass", "SERVICE_AVAILABILITY"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); Assert.Throws<ServiceUnavailableException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_whenErrorClassIsUnknown_throwsUnexpectedException() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass", "UNKNOWN"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); Assert.Throws<UnexpectedException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasError_whenErrorClassIsNotMapped_throwsUnexpectedException() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass","FOO"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); Assert.Throws<UnexpectedException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } [Test] public void DoNotThrowExceptionIfGraphQLErrorResponseHasError_whenErrorClassIsValidation() { Dictionary<string, object> extensions = new Dictionary<string, object>(); extensions.Add("errorClass", "VALIDATION"); GraphQLError error = new GraphQLError(); error.extensions = extensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(error); BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response); } [Test] public void ThrowExceptionIfGraphQLErrorResponseHasErrors_whenValidationAndNotFoundErrorClassesExist_throwsNotFoundException() { Dictionary<string, object> validationExtensions = new Dictionary<string, object>(); validationExtensions.Add("errorClass", "VALIDATION"); Dictionary<string, object> notFoundExtensions = new Dictionary<string, object>(); notFoundExtensions.Add("errorClass", "NOT_FOUND"); GraphQLError validationError = new GraphQLError(); validationError.extensions = validationExtensions; GraphQLError notFoundError = new GraphQLError(); notFoundError.extensions = notFoundExtensions; GraphQLResponse response = new GraphQLResponse(); response.errors = new List<GraphQLError>(); response.errors.Add(validationError); response.errors.Add(notFoundError); Assert.Throws<NotFoundException> (() => BraintreeGraphQLService.ThrowExceptionIfGraphQLErrorResponseHasError(response)); } } } #pragma warning restore CS0618
// Copyright 2013 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Globalization; using NodaTime.Text; using NUnit.Framework; using System.Collections.Generic; using System.Linq; namespace NodaTime.Test.Text { public class OffsetDateTimePatternTest : PatternTestBase<OffsetDateTime> { // The standard example date/time used in all the MSDN samples, which means we can just cut and paste // the expected results of the standard patterns. We've got an offset of 1 hour though. private static readonly OffsetDateTime MsdnStandardExample = LocalDateTimePatternTest.MsdnStandardExample.WithOffset(Offset.FromHours(1)); private static readonly OffsetDateTime MsdnStandardExampleNoMillis = LocalDateTimePatternTest.MsdnStandardExampleNoMillis.WithOffset(Offset.FromHours(1)); private static readonly OffsetDateTime SampleOffsetDateTimeCoptic = LocalDateTimePatternTest.SampleLocalDateTimeCoptic.WithOffset(Offset.Zero); private static readonly Offset AthensOffset = Offset.FromHours(3); internal static readonly Data[] InvalidPatternData = { new Data { Pattern = "", Message = TextErrorMessages.FormatStringEmpty }, new Data { Pattern = "dd MM yyyy HH:MM:SS", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'M' } }, // Note incorrect use of "u" (year) instead of "y" (year of era) new Data { Pattern = "dd MM uuuu HH:mm:ss gg", Message = TextErrorMessages.EraWithoutYearOfEra }, // Era specifier and calendar specifier in the same pattern. new Data { Pattern = "dd MM yyyy HH:mm:ss gg c", Message = TextErrorMessages.CalendarAndEra }, new Data { Pattern = "g", Message = TextErrorMessages.UnknownStandardFormat, Parameters = { 'g', typeof(OffsetDateTime) } }, // Invalid patterns involving embedded values new Data { Pattern = "ld<d> yyyy", Message = TextErrorMessages.DateFieldAndEmbeddedDate }, new Data { Pattern = "l<yyyy-MM-dd HH:mm:ss> dd", Message = TextErrorMessages.DateFieldAndEmbeddedDate }, new Data { Pattern = "ld<d> ld<f>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "lt<T> HH", Message = TextErrorMessages.TimeFieldAndEmbeddedTime }, new Data { Pattern = "l<yyyy-MM-dd HH:mm:ss> HH", Message = TextErrorMessages.TimeFieldAndEmbeddedTime }, new Data { Pattern = "lt<T> lt<t>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "ld<d> l<F>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "l<F> ld<d>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "lt<T> l<F>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = "l<F> lt<T>", Message = TextErrorMessages.RepeatedFieldInPattern, Parameters = { 'l' } }, new Data { Pattern = @"l<\", Message = TextErrorMessages.EscapeAtEndOfString }, }; internal static Data[] ParseFailureData = { // Failures copied from LocalDateTimePatternTest new Data { Pattern = "dd MM yyyy HH:mm:ss", Text = "Complete mismatch", Message = TextErrorMessages.MismatchedNumber, Parameters = { "dd" }}, new Data { Pattern = "(c)", Text = "(xxx)", Message = TextErrorMessages.NoMatchingCalendarSystem }, // 24 as an hour is only valid when the time is midnight new Data { Pattern = "yyyy-MM-dd HH:mm:ss", Text = "2011-10-19 24:00:05", Message = TextErrorMessages.InvalidHour24 }, new Data { Pattern = "yyyy-MM-dd HH:mm:ss", Text = "2011-10-19 24:01:00", Message = TextErrorMessages.InvalidHour24 }, new Data { Pattern = "yyyy-MM-dd HH:mm", Text = "2011-10-19 24:01", Message = TextErrorMessages.InvalidHour24 }, new Data { Pattern = "yyyy-MM-dd HH:mm", Text = "2011-10-19 24:00", Template = new LocalDateTime(1970, 1, 1, 0, 0, 5).WithOffset(Offset.Zero), Message = TextErrorMessages.InvalidHour24}, new Data { Pattern = "yyyy-MM-dd HH", Text = "2011-10-19 24", Template = new LocalDateTime(1970, 1, 1, 0, 5, 0).WithOffset(Offset.Zero), Message = TextErrorMessages.InvalidHour24}, new Data { Pattern = "yyyy-MM-dd HH:mm:ss o<+HH>", Text = "2011-10-19 16:02 +15:00", Message = TextErrorMessages.TimeSeparatorMismatch}, }; internal static Data[] ParseOnlyData = { // Parse-only tests from LocalDateTimeTest. new Data(2011, 10, 19, 16, 05, 20) { Pattern = "dd MM yyyy", Text = "19 10 2011", Template = new LocalDateTime(2000, 1, 1, 16, 05, 20).WithOffset(Offset.Zero) }, new Data(2011, 10, 19, 16, 05, 20) { Pattern = "HH:mm:ss", Text = "16:05:20", Template = new LocalDateTime(2011, 10, 19, 0, 0, 0).WithOffset(Offset.Zero) }, // Parsing using the semi-colon "comma dot" specifier new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "yyyy-MM-dd HH:mm:ss;fff", Text = "2011-10-19 16:05:20,352" }, new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "yyyy-MM-dd HH:mm:ss;FFF", Text = "2011-10-19 16:05:20,352" }, // 24:00 meaning "start of next day" new Data(2011, 10, 20) { Pattern = "yyyy-MM-dd HH:mm:ss", Text = "2011-10-19 24:00:00" }, new Data(2011, 10, 20, 0, 0, Offset.FromHours(1)) { Pattern = "yyyy-MM-dd HH:mm:ss o<+HH>", Text = "2011-10-19 24:00:00 +01", Template = new LocalDateTime(1970, 1, 1, 0, 5, 0).WithOffset(Offset.FromHours(-5)) }, new Data(2011, 10, 20) { Pattern = "yyyy-MM-dd HH:mm", Text = "2011-10-19 24:00" }, new Data(2011, 10, 20) { Pattern = "yyyy-MM-dd HH", Text = "2011-10-19 24" }, }; internal static Data[] FormatOnlyData = { new Data(2011, 10, 19, 16, 05, 20) { Pattern = "ddd yyyy", Text = "Wed 2011" }, // Our template value has an offset of 0, but the value has an offset of 1... which is ignored by the pattern new Data(MsdnStandardExample) { Pattern = "yyyy-MM-dd HH:mm:ss.FF", Text = "2009-06-15 13:45:30.09" } }; internal static Data[] FormatAndParseData = { // Copied from LocalDateTimePatternTest // Calendar patterns are invariant new Data(MsdnStandardExample) { Pattern = "(c) uuuu-MM-dd'T'HH:mm:ss.FFFFFFF o<G>", Text = "(ISO) 2009-06-15T13:45:30.09 +01", Culture = Cultures.FrFr }, new Data(MsdnStandardExample) { Pattern = "uuuu-MM-dd(c';'o<g>)'T'HH:mm:ss.FFFFFFF", Text = "2009-06-15(ISO;+01)T13:45:30.09", Culture = Cultures.EnUs }, new Data(SampleOffsetDateTimeCoptic) { Pattern = "(c) uuuu-MM-dd'T'HH:mm:ss.FFFFFFFFF o<G>", Text = "(Coptic) 1976-06-19T21:13:34.123456789 Z", Culture = Cultures.FrFr }, new Data(SampleOffsetDateTimeCoptic) { Pattern = "uuuu-MM-dd'C'c'T'HH:mm:ss.FFFFFFFFF o<g>", Text = "1976-06-19CCopticT21:13:34.123456789 +00", Culture = Cultures.EnUs }, // Standard patterns (all invariant) new Data(MsdnStandardExampleNoMillis) { StandardPattern = OffsetDateTimePattern.GeneralIso, Pattern = "G", Text = "2009-06-15T13:45:30+01", Culture = Cultures.FrFr }, new Data(MsdnStandardExample) { StandardPattern = OffsetDateTimePattern.ExtendedIso, Pattern = "o", Text = "2009-06-15T13:45:30.09+01", Culture = Cultures.FrFr }, new Data(MsdnStandardExample) { StandardPattern = OffsetDateTimePattern.FullRoundtrip, Pattern = "r", Text = "2009-06-15T13:45:30.09+01 (ISO)", Culture = Cultures.FrFr }, // Property-only patterns new Data(MsdnStandardExample) { StandardPattern = OffsetDateTimePattern.Rfc3339, Pattern = "uuuu'-'MM'-'dd'T'HH':'mm':'ss;FFFFFFFFFo<Z+HH:mm>", Text = "2009-06-15T13:45:30.09+01:00", Culture = Cultures.FrFr }, // Custom embedded patterns (or mixture of custom and standard) new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "ld<yyyy*MM*dd>'X'lt<HH_mm_ss> o<g>", Text = "2015*10*24X11_55_30 +03" }, new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "lt<HH_mm_ss>'Y'ld<yyyy*MM*dd> o<g>", Text = "11_55_30Y2015*10*24 +03" }, new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "l<HH_mm_ss'Y'yyyy*MM*dd> o<g>", Text = "11_55_30Y2015*10*24 +03" }, new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "ld<d>'X'lt<HH_mm_ss> o<g>", Text = "10/24/2015X11_55_30 +03" }, new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "ld<yyyy*MM*dd>'X'lt<T> o<g>", Text = "2015*10*24X11:55:30 +03" }, // Standard embedded patterns. Short time versions have a seconds value of 0 so they can round-trip. new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "ld<D> lt<r> o<g>", Text = "Saturday, 24 October 2015 11:55:30 +03" }, new Data(2015, 10, 24, 11, 55, 0, AthensOffset) { Pattern = "l<f> o<g>", Text = "Saturday, 24 October 2015 11:55 +03" }, new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "l<F> o<g>", Text = "Saturday, 24 October 2015 11:55:30 +03" }, new Data(2015, 10, 24, 11, 55, 0, AthensOffset) { Pattern = "l<g> o<g>", Text = "10/24/2015 11:55 +03" }, new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "l<G> o<g>", Text = "10/24/2015 11:55:30 +03" }, // Nested embedded patterns new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "l<ld<D> lt<r>> o<g>", Text = "Saturday, 24 October 2015 11:55:30 +03" }, new Data(2015, 10, 24, 11, 55, 30, AthensOffset) { Pattern = "l<'X'lt<HH_mm_ss>'Y'ld<yyyy*MM*dd>'X'> o<g>", Text = "X11_55_30Y2015*10*24X +03" }, // Check that unquoted T still works. new Data(2012, 1, 31, 17, 36, 45) { Text = "2012-01-31T17:36:45", Pattern = "yyyy-MM-ddTHH:mm:ss" }, // Check handling of F after non-period. new Data(2012, 1, 31, 17, 36, 45, 123) { Text = "2012-01-31T17:36:45x123", Pattern = "yyyy-MM-ddTHH:mm:ss'x'FFF" }, // Fields not otherwise covered new Data(MsdnStandardExample) { Pattern = "d MMMM yyyy (g) h:mm:ss.FF tt o<g>", Text = "15 June 2009 (A.D.) 1:45:30.09 PM +01" }, }; internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData); internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData); [Test] public void CreateWithInvariantCulture() { var pattern = OffsetDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd'T'HH:mm:sso<g>"); Assert.AreSame(NodaFormatInfo.InvariantInfo, pattern.FormatInfo); var odt = new LocalDateTime(2017, 8, 23, 12, 34, 56).WithOffset(Offset.FromHours(2)); Assert.AreEqual("2017-08-23T12:34:56+02", pattern.Format(odt)); } [Test] public void CreateWithCurrentCulture() { var odt = new LocalDateTime(2017, 8, 23, 12, 34, 56).WithOffset(Offset.FromHours(2)); using (CultureSaver.SetCultures(Cultures.FrFr)) { var pattern = OffsetDateTimePattern.CreateWithCurrentCulture("l<g> o<g>"); Assert.AreEqual("23/08/2017 12:34 +02", pattern.Format(odt)); } using (CultureSaver.SetCultures(Cultures.FrCa)) { var pattern = OffsetDateTimePattern.CreateWithCurrentCulture("l<g> o<g>"); Assert.AreEqual("2017-08-23 12:34 +02", pattern.Format(odt)); } } [Test] public void WithCulture() { var pattern = OffsetDateTimePattern.CreateWithInvariantCulture("HH:mm").WithCulture(Cultures.DotTimeSeparator); var text = pattern.Format(Instant.FromUtc(2000, 1, 1, 19, 30).WithOffset(Offset.Zero)); Assert.AreEqual("19.30", text); } [Test] public void WithPatternText() { var pattern = OffsetDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd").WithPatternText("HH:mm"); var value = Instant.FromUtc(1970, 1, 1, 11, 30).WithOffset(Offset.FromHours(2)); var text = pattern.Format(value); Assert.AreEqual("13:30", text); } [Test] public void WithTemplateValue() { var pattern = OffsetDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd") .WithTemplateValue(Instant.FromUtc(1970, 1, 1, 11, 30).WithOffset(Offset.FromHours(2))); var parsed = pattern.Parse("2017-08-23").Value; // Local time of template value was 13:30 Assert.AreEqual(new LocalDateTime(2017, 8, 23, 13, 30, 0), parsed.LocalDateTime); Assert.AreEqual(Offset.FromHours(2), parsed.Offset); } [Test] public void WithCalendar() { var pattern = OffsetDateTimePattern.CreateWithInvariantCulture("yyyy-MM-dd") .WithCalendar(CalendarSystem.Coptic); var parsed = pattern.Parse("0284-08-29").Value; Assert.AreEqual(new LocalDateTime(284, 8, 29, 0, 0, CalendarSystem.Coptic), parsed.LocalDateTime); } [Test] public void ParseNull() => AssertParseNull(OffsetDateTimePattern.ExtendedIso); internal sealed class Data : PatternTestData<OffsetDateTime> { // Default to the start of the year 2000 UTC protected override OffsetDateTime DefaultTemplate => OffsetDateTimePattern.DefaultTemplateValue; /// <summary> /// Initializes a new instance of the <see cref="Data" /> class. /// </summary> /// <param name="value">The value.</param> internal Data(OffsetDateTime value) : base(value) { } internal Data(int year, int month, int day) : this(new LocalDateTime(year, month, day, 0, 0).WithOffset(Offset.Zero)) { } internal Data(int year, int month, int day, int hour, int minute, Offset offset) : this(new LocalDateTime(year, month, day, hour, minute).WithOffset(offset)) { } internal Data(int year, int month, int day, int hour, int minute, int second) : this(new LocalDateTime(year, month, day, hour, minute, second).WithOffset(Offset.Zero)) { } internal Data(int year, int month, int day, int hour, int minute, int second, Offset offset) : this(new LocalDateTime(year, month, day, hour, minute, second).WithOffset(offset)) { } internal Data(int year, int month, int day, int hour, int minute, int second, int millis) : this(new LocalDateTime(year, month, day, hour, minute, second, millis).WithOffset(Offset.Zero)) { } internal Data() : this(OffsetDateTimePattern.DefaultTemplateValue) { } internal override IPattern<OffsetDateTime> CreatePattern() => OffsetDateTimePattern.Create(Pattern!, Culture, Template); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace food_therapist.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace Irony.Parsing { //Scanner class. The Scanner's function is to transform a stream of characters into aggregates/words or lexemes, // like identifier, number, literal, etc. public class Scanner { #region Properties and Fields: Data, _source public readonly ScannerData Data; public readonly Parser Parser; Grammar _grammar; //buffered tokens can come from expanding a multi-token, when Terminal.TryMatch() returns several tokens packed into one token private ParsingContext Context { get { return Parser.Context; } } #endregion public Scanner(Parser parser) { Parser = parser; Data = parser.Language.ScannerData; _grammar = parser.Language.Grammar; //create token streams var tokenStream = GetUnfilteredTokens(); //chain all token filters Context.TokenFilters.Clear(); _grammar.CreateTokenFilters(Data.Language, Context.TokenFilters); foreach (TokenFilter filter in Context.TokenFilters) { tokenStream = filter.BeginFiltering(Context, tokenStream); } Context.FilteredTokens = tokenStream.GetEnumerator(); } internal void Reset() { } public Token GetToken() { //get new token from pipeline if (!Context.FilteredTokens.MoveNext()) return null; var token = Context.FilteredTokens.Current; if (Context.Status == ParserStatus.Previewing) Context.PreviewTokens.Push(token); else Context.CurrentParseTree.Tokens.Add(token); return token; } //This is iterator method, so it returns immediately when called directly // returns unfiltered, "raw" token stream private IEnumerable<Token> GetUnfilteredTokens() { //We don't do "while(!_source.EOF())... because on EOF() we need to continue and produce EOF token while (true) { Context.PreviousToken = Context.CurrentToken; Context.CurrentToken = null; NextToken(); Context.OnTokenCreated(); yield return Context.CurrentToken; //Don't yield break, continue returning EOF }//while }// method #region Scanning tokens private void NextToken() { //1. Check if there are buffered tokens if(Context.BufferedTokens.Count > 0) { Context.CurrentToken = Context.BufferedTokens.Pop(); return; } //2. Skip whitespace. _grammar.SkipWhitespace(Context.Source); //3. That's the token start, calc location (line and column) Context.Source.Position = Context.Source.PreviewPosition; //4. Check for EOF if (Context.Source.EOF()) { Context.CurrentToken = new Token(_grammar.Eof, Context.Source.Location, string.Empty, _grammar.Eof.Name);; return; } //5. Actually scan the source text and construct a new token ScanToken(); }//method //Scans the source text and constructs a new token private void ScanToken() { if (!MatchNonGrammarTerminals() && !MatchRegularTerminals()) { //we are in error already; try to match ANY terminal and let the parser report an error MatchAllTerminals(); //try to match any terminal out there } var token = Context.CurrentToken; //If we have normal token then return it if (token != null && !token.IsError()) { var src = Context.Source; //set position to point after the result token src.PreviewPosition = src.Position + token.Length; src.Position = src.PreviewPosition; return; } //we have an error: either error token or no token at all if (token == null) //if no token then create error token Context.CurrentToken = Context.CreateErrorToken(Resources.ErrInvalidChar, Context.Source.PreviewChar); Recover(); } private bool MatchNonGrammarTerminals() { TerminalList terms; if(!Data.NonGrammarTerminalsLookup.TryGetValue(Context.Source.PreviewChar, out terms)) return false; foreach(var term in terms) { Context.Source.PreviewPosition = Context.Source.Location.Position; Context.CurrentToken = term.TryMatch(Context, Context.Source); if (Context.CurrentToken != null) term.OnValidateToken(Context); if (Context.CurrentToken != null) { //check if we need to fire LineStart token before this token; // we do it only if the token is not a comment; comments should be ignored by the outline logic var token = Context.CurrentToken; if (token.Category == TokenCategory.Content && NeedLineStartToken(token.Location)) { Context.BufferedTokens.Push(token); //buffer current token; we'll eject LineStart instead Context.Source.Location = token.Location; //set it back to the start of the token Context.CurrentToken = Context.Source.CreateToken(_grammar.LineStartTerminal); //generate LineStart Context.PreviousLineStart = Context.Source.Location; //update LineStart } return true; }//if }//foreach term Context.Source.PreviewPosition = Context.Source.Location.Position; return false; } private bool NeedLineStartToken(SourceLocation forLocation) { return _grammar.LanguageFlags.IsSet(LanguageFlags.EmitLineStartToken) && forLocation.Line > Context.PreviousLineStart.Line; } private bool MatchRegularTerminals() { //We need to eject LineStart BEFORE we try to produce a real token; this LineStart token should reach // the parser, make it change the state and with it to change the set of expected tokens. So when we // finally move to scan the real token, the expected terminal set is correct. if (NeedLineStartToken(Context.Source.Location)) { Context.CurrentToken = Context.Source.CreateToken(_grammar.LineStartTerminal); Context.PreviousLineStart = Context.Source.Location; return true; } //Find matching terminal // First, try terminals with explicit "first-char" prefixes, selected by current char in source ComputeCurrentTerminals(); //If we have more than one candidate; let grammar method select if (Context.CurrentTerminals.Count > 1) _grammar.OnScannerSelectTerminal(Context); MatchTerminals(); //If we don't have a token from terminals, try Grammar's method if (Context.CurrentToken == null) Context.CurrentToken = _grammar.TryMatch(Context, Context.Source); if (Context.CurrentToken is MultiToken) UnpackMultiToken(); return Context.CurrentToken != null; }//method // This method is a last attempt by scanner to match ANY terminal, after regular matching (by input char) had failed. // Likely this will produce some token which is invalid for current parser state (for ex, identifier where a number // is expected); in this case the parser will report an error as "Error: expected number". // if this matching fails, the scanner will produce an error as "unexpected character." private bool MatchAllTerminals() { Context.CurrentTerminals.Clear(); Context.CurrentTerminals.AddRange(Data.Language.GrammarData.Terminals); MatchTerminals(); if (Context.CurrentToken is MultiToken) UnpackMultiToken(); return Context.CurrentToken != null; } //If token is MultiToken then push all its child tokens into _bufferdTokens and return the first token in buffer private void UnpackMultiToken() { var mtoken = Context.CurrentToken as MultiToken; if (mtoken == null) return; for (int i = mtoken.ChildTokens.Count-1; i >= 0; i--) Context.BufferedTokens.Push(mtoken.ChildTokens[i]); Context.CurrentToken = Context.BufferedTokens.Pop(); } private void ComputeCurrentTerminals() { Context.CurrentTerminals.Clear(); TerminalList termsForCurrentChar; if(!Data.TerminalsLookup.TryGetValue(Context.Source.PreviewChar, out termsForCurrentChar)) termsForCurrentChar = Data.NoPrefixTerminals; //if we are recovering, previewing or there's no parser state, then return list as is if(Context.Status == ParserStatus.Recovering || Context.Status == ParserStatus.Previewing || Context.CurrentParserState == null || _grammar.LanguageFlags.IsSet(LanguageFlags.DisableScannerParserLink) || Context.Mode == ParseMode.VsLineScan) { Context.CurrentTerminals.AddRange(termsForCurrentChar); return; } // Try filtering terms by checking with parser which terms it expects; var parserState = Context.CurrentParserState; foreach(var term in termsForCurrentChar) { //Note that we check the OutputTerminal with parser, not the term itself; //in most cases it is the same as term, but not always if (parserState.ExpectedTerminals.Contains(term.OutputTerminal) || _grammar.NonGrammarTerminals.Contains(term)) Context.CurrentTerminals.Add(term); } }//method private void MatchTerminals() { Token priorToken = null; for (int i=0; i<Context.CurrentTerminals.Count; i++) { var term = Context.CurrentTerminals[i]; // If we have priorToken from prior term in the list, check if prior term has higher priority than this term; // if term.Priority is lower then we don't need to check anymore, higher priority (in prior token) wins // Note that terminals in the list are sorted in descending priority order if (priorToken != null && priorToken.Terminal.Priority > term.Priority) return; //Reset source position and try to match Context.Source.PreviewPosition = Context.Source.Location.Position; var token = term.TryMatch(Context, Context.Source); if (token == null) continue; //skip it if it is shorter than previous token if (priorToken != null && !priorToken.IsError() && (token.Length < priorToken.Length)) continue; Context.CurrentToken = token; //now it becomes current token term.OnValidateToken(Context); //validate it if (Context.CurrentToken != null) priorToken = Context.CurrentToken; } }//method #endregion #region VS Integration methods //Use this method for VS integration; VS language package requires scanner that returns tokens one-by-one. // Start and End positions required by this scanner may be derived from Token : // start=token.Location.Position; end=start + token.Length; public Token VsReadToken(ref int state) { Context.VsLineScanState.Value = state; if (Context.Source.EOF()) return null; if (state == 0) NextToken(); else { Terminal term = Data.MultilineTerminals[Context.VsLineScanState.TerminalIndex - 1]; Context.CurrentToken = term.TryMatch(Context, Context.Source); } //set state value from context state = Context.VsLineScanState.Value; if (Context.CurrentToken != null && Context.CurrentToken.Terminal == _grammar.Eof) return null; return Context.CurrentToken; } public void VsSetSource(string text, int offset) { var line = Context.Source==null ? 0 : Context.Source.Location.Line; var newLoc = new SourceLocation(offset, line + 1, 0); Context.Source = new SourceStream(text, Context.Language.Grammar.CaseSensitive, Context.TabWidth, newLoc); } #endregion #region Error recovery //Simply skip until whitespace or delimiter character private bool Recover() { var src = Context.Source; src.PreviewPosition++; while (!Context.Source.EOF()) { if(_grammar.IsWhitespaceOrDelimiter(src.PreviewChar)) { src.Position = src.PreviewPosition; return true; } src.PreviewPosition++; } return false; } #endregion #region TokenPreview //Preview mode allows custom code in grammar to help parser decide on appropriate action in case of conflict // Preview process is simply searching for particular tokens in "preview set", and finding out which of the // tokens will come first. // In preview mode, tokens returned by FetchToken are collected in _previewTokens list; after finishing preview // the scanner "rolls back" to original position - either by directly restoring the position, or moving the preview // tokens into _bufferedTokens list, so that they will read again by parser in normal mode. // See c# grammar sample for an example of using preview methods SourceLocation _previewStartLocation; //Switches Scanner into preview mode public void BeginPreview() { Context.Status = ParserStatus.Previewing; _previewStartLocation = Context.Source.Location; Context.PreviewTokens.Clear(); } //Ends preview mode public void EndPreview(bool keepPreviewTokens) { if (keepPreviewTokens) { //insert previewed tokens into buffered list, so we don't recreate them again while (Context.PreviewTokens.Count > 0) Context.BufferedTokens.Push(Context.PreviewTokens.Pop()); } else Context.SetSourceLocation(_previewStartLocation); Context.PreviewTokens.Clear(); Context.Status = ParserStatus.Parsing; } #endregion }//class }//namespace
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using Mono.Addins; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.CoreModules.World.Wind; namespace OpenSim.Region.CoreModules.World.Wind.Plugins { [Extension(Path = "/OpenSim/WindModule", NodeName = "WindModel", Id = "ConfigurableWind")] class ConfigurableWind : Mono.Addins.TypeExtensionNode, IWindModelPlugin { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Vector2[] m_windSpeeds = new Vector2[16 * 16]; //private Random m_rndnums = new Random(Environment.TickCount); private float m_avgStrength = 5.0f; // Average magnitude of the wind vector private float m_avgDirection = 0.0f; // Average direction of the wind in degrees private float m_varStrength = 5.0f; // Max Strength Variance private float m_varDirection = 30.0f;// Max Direction Variance private float m_rateChange = 1.0f; // private Vector2 m_curPredominateWind = new Vector2(); #region IPlugin Members public string Version { get { return "1.0.0.0"; } } public string Name { get { return "ConfigurableWind"; } } public void Initialise() { } #endregion #region IDisposable Members public void Dispose() { m_windSpeeds = null; } #endregion #region IWindModelPlugin Members public void WindConfig(OpenSim.Region.Framework.Scenes.Scene scene, Nini.Config.IConfig windConfig) { if (windConfig != null) { // Uses strength value if avg_strength not specified m_avgStrength = windConfig.GetFloat("strength", 5.0F); m_avgStrength = windConfig.GetFloat("avg_strength", 5.0F); m_avgDirection = windConfig.GetFloat("avg_direction", 0.0F); m_varStrength = windConfig.GetFloat("var_strength", 5.0F); m_varDirection = windConfig.GetFloat("var_direction", 30.0F); m_rateChange = windConfig.GetFloat("rate_change", 1.0F); LogSettings(); } } public bool WindUpdate(uint frame) { double avgAng = m_avgDirection * (Math.PI/180.0f); double varDir = m_varDirection * (Math.PI/180.0f); // Prevailing wind algorithm // Inspired by Kanker Greenacre // TODO: // * This should probably be based on in-world time. // * should probably move all these local variables to class members and constants double time = DateTime.Now.TimeOfDay.Seconds / 86400.0f; double theta = time * (2 * Math.PI) * m_rateChange; double offset = Math.Sin(theta) * Math.Sin(theta*2) * Math.Sin(theta*9) * Math.Cos(theta*4); double windDir = avgAng + (varDir * offset); offset = Math.Sin(theta) * Math.Sin(theta*4) + (Math.Sin(theta*13) / 3); double windSpeed = m_avgStrength + (m_varStrength * offset); if (windSpeed < 0) windSpeed = -windSpeed; m_curPredominateWind.X = (float)Math.Cos(windDir); m_curPredominateWind.Y = (float)Math.Sin(windDir); m_curPredominateWind.Normalize(); m_curPredominateWind.X *= (float)windSpeed; m_curPredominateWind.Y *= (float)windSpeed; for (int y = 0; y < 16; y++) { for (int x = 0; x < 16; x++) { m_windSpeeds[y * 16 + x] = m_curPredominateWind; } } return true; } public Vector3 WindSpeed(float fX, float fY, float fZ) { return new Vector3(m_curPredominateWind, 0.0f); } public Vector2[] WindLLClientArray() { return m_windSpeeds; } public string Description { get { return "Provides a predominate wind direction that can change within configured variances for direction and speed."; } } public System.Collections.Generic.Dictionary<string, string> WindParams() { Dictionary<string, string> Params = new Dictionary<string, string>(); Params.Add("avgStrength", "average wind strength"); Params.Add("avgDirection", "average wind direction in degrees"); Params.Add("varStrength", "allowable variance in wind strength"); Params.Add("varDirection", "allowable variance in wind direction in +/- degrees"); Params.Add("rateChange", "rate of change"); return Params; } public void WindParamSet(string param, float value) { switch (param) { case "avgStrength": m_avgStrength = value; break; case "avgDirection": m_avgDirection = value; break; case "varStrength": m_varStrength = value; break; case "varDirection": m_varDirection = value; break; case "rateChange": m_rateChange = value; break; } } public float WindParamGet(string param) { switch (param) { case "avgStrength": return m_avgStrength; case "avgDirection": return m_avgDirection; case "varStrength": return m_varStrength; case "varDirection": return m_varDirection; case "rateChange": return m_rateChange; default: throw new Exception(String.Format("Unknown {0} parameter {1}", this.Name, param)); } } #endregion private void LogSettings() { m_log.InfoFormat("[ConfigurableWind] Average Strength : {0}", m_avgStrength); m_log.InfoFormat("[ConfigurableWind] Average Direction : {0}", m_avgDirection); m_log.InfoFormat("[ConfigurableWind] Varience Strength : {0}", m_varStrength); m_log.InfoFormat("[ConfigurableWind] Varience Direction : {0}", m_varDirection); m_log.InfoFormat("[ConfigurableWind] Rate Change : {0}", m_rateChange); } #region IWindModelPlugin Members #endregion } }
// This file is part of the C5 Generic Collection Library for C# and CLI // See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details. using NUnit.Framework; using System; using SCG = System.Collections.Generic; namespace C5.Tests.hashtable.set { using CollectionOfInt = HashSet<int>; [TestFixture] public class GenericTesters { [Test] public void TestEvents() { CollectionOfInt factory() { return new CollectionOfInt(TenEqualityComparer.Default); } new C5.Tests.Templates.Events.CollectionTester<CollectionOfInt>().Test(factory); } //[Test] //public void Extensible() //{ // C5.Tests.Templates.Extensible.Clone.Tester<CollectionOfInt>(); // C5.Tests.Templates.Extensible.Serialization.Tester<CollectionOfInt>(); //} } internal static class Factory { public static ICollection<T> New<T>() { return new HashSet<T>(); } } namespace Enumerable { [TestFixture] public class Multiops { private HashSet<int> list; private Func<int, bool> always, never, even; [SetUp] public void Init() { Debug.UseDeterministicHashing = true; list = new HashSet<int>(); always = delegate { return true; }; never = delegate { return false; }; even = delegate (int i) { return i % 2 == 0; }; } [Test] public void All() { Assert.IsTrue(list.All(always)); Assert.IsTrue(list.All(never)); Assert.IsTrue(list.All(even)); list.Add(0); Assert.IsTrue(list.All(always)); Assert.IsFalse(list.All(never)); Assert.IsTrue(list.All(even)); list.Add(5); Assert.IsTrue(list.All(always)); Assert.IsFalse(list.All(never)); Assert.IsFalse(list.All(even)); } [Test] public void Exists() { Assert.IsFalse(list.Exists(always)); Assert.IsFalse(list.Exists(never)); Assert.IsFalse(list.Exists(even)); list.Add(5); Assert.IsTrue(list.Exists(always)); Assert.IsFalse(list.Exists(never)); Assert.IsFalse(list.Exists(even)); list.Add(8); Assert.IsTrue(list.Exists(always)); Assert.IsFalse(list.Exists(never)); Assert.IsTrue(list.Exists(even)); } [Test] public void Apply() { int sum = 0; void a(int i) { sum = i + 10 * sum; } list.Apply(a); Assert.AreEqual(0, sum); sum = 0; list.Add(5); list.Add(8); list.Add(7); list.Add(5); list.Apply(a); Assert.AreEqual(758, sum); } [TearDown] public void Dispose() { Debug.UseDeterministicHashing = false; list = null; } } [TestFixture] public class GetEnumerator { private HashSet<int> hashset; [SetUp] public void Init() { hashset = new HashSet<int>(); } [Test] public void Empty() { SCG.IEnumerator<int> e = hashset.GetEnumerator(); Assert.IsFalse(e.MoveNext()); } [Test] public void Normal() { hashset.Add(5); hashset.Add(8); hashset.Add(5); hashset.Add(5); hashset.Add(10); hashset.Add(1); hashset.Add(16); hashset.Add(18); hashset.Add(17); hashset.Add(33); Assert.IsTrue(IC.SetEq(hashset, 1, 5, 8, 10, 16, 17, 18, 33)); } [Test] public void DoDispose() { hashset.Add(5); hashset.Add(8); hashset.Add(5); SCG.IEnumerator<int> e = hashset.GetEnumerator(); e.MoveNext(); e.MoveNext(); e.Dispose(); } [Test] public void MoveNextAfterUpdate() { hashset.Add(5); hashset.Add(8); hashset.Add(5); SCG.IEnumerator<int> e = hashset.GetEnumerator(); e.MoveNext(); hashset.Add(99); Assert.Throws<CollectionModifiedException>(() => e.MoveNext()); } [TearDown] public void Dispose() { hashset = null; } } } namespace CollectionOrSink { [TestFixture] public class Formatting { private ICollection<int> coll; private IFormatProvider rad16; [SetUp] public void Init() { Debug.UseDeterministicHashing = true; coll = Factory.New<int>(); rad16 = new RadixFormatProvider(16); } [TearDown] public void Dispose() { Debug.UseDeterministicHashing = false; coll = null; rad16 = null; } [Test] public void Format() { Assert.AreEqual("{ }", coll.ToString()); coll.AddAll(new int[] { -4, 28, 129, 65530 }); Assert.AreEqual("{ 65530, -4, 28, 129 }", coll.ToString()); Assert.AreEqual("{ FFFA, -4, 1C, 81 }", coll.ToString(null, rad16)); Assert.AreEqual("{ 65530, -4, ... }", coll.ToString("L14", null)); Assert.AreEqual("{ FFFA, -4, ... }", coll.ToString("L14", rad16)); } } [TestFixture] public class CollectionOrSink { private HashSet<int> hashset; [SetUp] public void Init() { hashset = new HashSet<int>(); } [Test] public void Choose() { hashset.Add(7); Assert.AreEqual(7, hashset.Choose()); } [Test] public void BadChoose() { Assert.Throws<NoSuchItemException>(() => hashset.Choose()); } [Test] public void CountEtAl() { Assert.AreEqual(0, hashset.Count); Assert.IsTrue(hashset.IsEmpty); Assert.IsFalse(hashset.AllowsDuplicates); Assert.IsTrue(hashset.Add(0)); Assert.AreEqual(1, hashset.Count); Assert.IsFalse(hashset.IsEmpty); Assert.IsTrue(hashset.Add(5)); Assert.AreEqual(2, hashset.Count); Assert.IsFalse(hashset.Add(5)); Assert.AreEqual(2, hashset.Count); Assert.IsFalse(hashset.IsEmpty); Assert.IsTrue(hashset.Add(8)); Assert.AreEqual(3, hashset.Count); } [Test] public void AddAll() { hashset.Add(3); hashset.Add(4); hashset.Add(5); HashSet<int> hashset2 = new HashSet<int>(); hashset2.AddAll(hashset); Assert.IsTrue(IC.SetEq(hashset2, 3, 4, 5)); hashset.Add(9); hashset.AddAll(hashset2); Assert.IsTrue(IC.SetEq(hashset2, 3, 4, 5)); Assert.IsTrue(IC.SetEq(hashset, 3, 4, 5, 9)); } [TearDown] public void Dispose() { hashset = null; } } [TestFixture] public class FindPredicate { private HashSet<int> list; private Func<int, bool> pred; [SetUp] public void Init() { Debug.UseDeterministicHashing = true; list = new HashSet<int>(TenEqualityComparer.Default); pred = delegate (int i) { return i % 5 == 0; }; } [TearDown] public void Dispose() { Debug.UseDeterministicHashing = false; list = null; } [Test] public void Find() { Assert.IsFalse(list.Find(pred, out int i)); list.AddAll(new int[] { 4, 22, 67, 37 }); Assert.IsFalse(list.Find(pred, out i)); list.AddAll(new int[] { 45, 122, 675, 137 }); Assert.IsTrue(list.Find(pred, out i)); Assert.AreEqual(45, i); } } [TestFixture] public class UniqueItems { private HashSet<int> list; [SetUp] public void Init() { list = new HashSet<int>(); } [TearDown] public void Dispose() { list = null; } [Test] public void Test() { Assert.IsTrue(IC.SetEq(list.UniqueItems())); Assert.IsTrue(IC.SetEq(list.ItemMultiplicities())); list.AddAll(new int[] { 7, 9, 7 }); Assert.IsTrue(IC.SetEq(list.UniqueItems(), 7, 9)); Assert.IsTrue(IC.SetEq(list.ItemMultiplicities(), 7, 1, 9, 1)); } } [TestFixture] public class ArrayTest { private HashSet<int> hashset; private int[] a; [SetUp] public void Init() { Debug.UseDeterministicHashing = true; hashset = new HashSet<int>(); a = new int[10]; for (int i = 0; i < 10; i++) { a[i] = 1000 + i; } } [TearDown] public void Dispose() { Debug.UseDeterministicHashing = false; hashset = null; } private string aeq(int[] a, params int[] b) { if (a.Length != b.Length) { return "Lengths differ: " + a.Length + " != " + b.Length; } for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) { return string.Format("{0}'th elements differ: {1} != {2}", i, a[i], b[i]); } } return "Alles klar"; } [Test] public void ToArray() { Assert.AreEqual("Alles klar", aeq(hashset.ToArray())); hashset.Add(7); hashset.Add(3); hashset.Add(10); int[] r = hashset.ToArray(); Array.Sort(r); Assert.AreEqual("Alles klar", aeq(r, 3, 7, 10)); } [Test] public void CopyTo() { //Note: for small ints the itemequalityComparer is the identity! hashset.CopyTo(a, 1); Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009)); hashset.Add(6); hashset.CopyTo(a, 2); Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 6, 1003, 1004, 1005, 1006, 1007, 1008, 1009)); hashset.Add(4); hashset.Add(9); hashset.CopyTo(a, 4); //TODO: make test independent on onterequalityComparer Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 6, 1003, 6, 9, 4, 1007, 1008, 1009)); hashset.Clear(); hashset.Add(7); hashset.CopyTo(a, 9); Assert.AreEqual("Alles klar", aeq(a, 1000, 1001, 6, 1003, 6, 9, 4, 1007, 1008, 7)); } [Test] public void CopyToBad() { Assert.Throws<ArgumentOutOfRangeException>(() => hashset.CopyTo(a, 11)); } [Test] public void CopyToBad2() { Assert.Throws<ArgumentOutOfRangeException>(() => hashset.CopyTo(a, -1)); } [Test] public void CopyToTooFar() { hashset.Add(3); hashset.Add(8); Assert.Throws<ArgumentOutOfRangeException>(() => hashset.CopyTo(a, 9)); } } } namespace EditableCollection { [TestFixture] public class Collision { private HashSet<int> hashset; [SetUp] public void Init() { hashset = new HashSet<int>(); } [Test] public void SingleCollision() { hashset.Add(7); hashset.Add(7 - 1503427877); //foreach (int cell in hashset) Console.WriteLine("A: {0}", cell); hashset.Remove(7); Assert.IsTrue(hashset.Contains(7 - 1503427877)); } [TearDown] public void Dispose() { hashset = null; } } [TestFixture] public class Searching { private HashSet<int> hashset; [SetUp] public void Init() { Debug.UseDeterministicHashing = true; hashset = new HashSet<int>(); } [Test] public void NullEqualityComparerinConstructor1() { Assert.Throws<NullReferenceException>(() => new HashSet<int>(null)); } [Test] public void NullEqualityComparerinConstructor2() { Assert.Throws<NullReferenceException>(() => new HashSet<int>(5, null)); } [Test] public void NullEqualityComparerinConstructor3() { Assert.Throws<NullReferenceException>(() => new HashSet<int>(5, 0.5, null)); } [Test] public void Contains() { Assert.IsFalse(hashset.Contains(5)); hashset.Add(5); Assert.IsTrue(hashset.Contains(5)); Assert.IsFalse(hashset.Contains(7)); hashset.Add(8); hashset.Add(10); Assert.IsTrue(hashset.Contains(5)); Assert.IsFalse(hashset.Contains(7)); Assert.IsTrue(hashset.Contains(8)); Assert.IsTrue(hashset.Contains(10)); hashset.Remove(8); Assert.IsTrue(hashset.Contains(5)); Assert.IsFalse(hashset.Contains(7)); Assert.IsFalse(hashset.Contains(8)); Assert.IsTrue(hashset.Contains(10)); hashset.Add(0); hashset.Add(16); hashset.Add(32); hashset.Add(48); hashset.Add(64); Assert.IsTrue(hashset.Contains(0)); Assert.IsTrue(hashset.Contains(16)); Assert.IsTrue(hashset.Contains(32)); Assert.IsTrue(hashset.Contains(48)); Assert.IsTrue(hashset.Contains(64)); Assert.IsTrue(hashset.Check()); int i = 0, j = i; Assert.IsTrue(hashset.Find(ref i)); Assert.AreEqual(j, i); j = i = 16; Assert.IsTrue(hashset.Find(ref i)); Assert.AreEqual(j, i); j = i = 32; Assert.IsTrue(hashset.Find(ref i)); Assert.AreEqual(j, i); j = i = 48; Assert.IsTrue(hashset.Find(ref i)); Assert.AreEqual(j, i); j = i = 64; Assert.IsTrue(hashset.Find(ref i)); Assert.AreEqual(j, i); j = i = 80; Assert.IsFalse(hashset.Find(ref i)); Assert.AreEqual(j, i); } [Test] public void Many() { int j = 7373; int[] a = new int[j]; for (int i = 0; i < j; i++) { hashset.Add(3 * i + 1); a[i] = 3 * i + 1; } Assert.IsTrue(IC.SetEq(hashset, a)); } [Test] public void ContainsCount() { Assert.AreEqual(0, hashset.ContainsCount(5)); hashset.Add(5); Assert.AreEqual(1, hashset.ContainsCount(5)); Assert.AreEqual(0, hashset.ContainsCount(7)); hashset.Add(8); Assert.AreEqual(1, hashset.ContainsCount(5)); Assert.AreEqual(0, hashset.ContainsCount(7)); Assert.AreEqual(1, hashset.ContainsCount(8)); hashset.Add(5); Assert.AreEqual(1, hashset.ContainsCount(5)); Assert.AreEqual(0, hashset.ContainsCount(7)); Assert.AreEqual(1, hashset.ContainsCount(8)); } [Test] public void RemoveAllCopies() { hashset.Add(5); hashset.Add(7); hashset.Add(5); Assert.AreEqual(1, hashset.ContainsCount(5)); Assert.AreEqual(1, hashset.ContainsCount(7)); hashset.RemoveAllCopies(5); Assert.AreEqual(0, hashset.ContainsCount(5)); Assert.AreEqual(1, hashset.ContainsCount(7)); hashset.Add(5); hashset.Add(8); hashset.Add(5); hashset.RemoveAllCopies(8); Assert.IsTrue(IC.Eq(hashset, 7, 5)); } [Test] public void ContainsAll() { HashSet<int> list2 = new HashSet<int>(); Assert.IsTrue(hashset.ContainsAll(list2)); list2.Add(4); Assert.IsFalse(hashset.ContainsAll(list2)); hashset.Add(4); Assert.IsTrue(hashset.ContainsAll(list2)); hashset.Add(5); Assert.IsTrue(hashset.ContainsAll(list2)); list2.Add(20); Assert.IsFalse(hashset.ContainsAll(list2)); hashset.Add(20); Assert.IsTrue(hashset.ContainsAll(list2)); } [Test] public void RetainAll() { HashSet<int> list2 = new HashSet<int>(); hashset.Add(4); hashset.Add(5); hashset.Add(6); list2.Add(5); list2.Add(4); list2.Add(7); hashset.RetainAll(list2); Assert.IsTrue(IC.SetEq(hashset, 4, 5)); hashset.Add(6); list2.Clear(); list2.Add(7); list2.Add(8); list2.Add(9); hashset.RetainAll(list2); Assert.IsTrue(IC.SetEq(hashset)); } //Bug in RetainAll reported by Chris Fesler //The result has different bitsc [Test] public void RetainAll2() { int LARGE_ARRAY_SIZE = 30; int LARGE_ARRAY_MID = 15; string[] _largeArrayOne = new string[LARGE_ARRAY_SIZE]; string[] _largeArrayTwo = new string[LARGE_ARRAY_SIZE]; for (int i = 0; i < LARGE_ARRAY_SIZE; i++) { _largeArrayOne[i] = "" + i; _largeArrayTwo[i] = "" + (i + LARGE_ARRAY_MID); } HashSet<string> setOne = new HashSet<string>(); setOne.AddAll(_largeArrayOne); HashSet<string> setTwo = new HashSet<string>(); setTwo.AddAll(_largeArrayTwo); setOne.RetainAll(setTwo); Assert.IsTrue(setOne.Check(), "setOne check fails"); for (int i = LARGE_ARRAY_MID; i < LARGE_ARRAY_SIZE; i++) { Assert.IsTrue(setOne.Contains(_largeArrayOne[i]), "missing " + i); } } [Test] public void RemoveAll() { HashSet<int> list2 = new HashSet<int>(); hashset.Add(4); hashset.Add(5); hashset.Add(6); list2.Add(5); list2.Add(7); list2.Add(4); hashset.RemoveAll(list2); Assert.IsTrue(IC.Eq(hashset, 6)); hashset.Add(5); hashset.Add(4); list2.Clear(); list2.Add(6); list2.Add(5); hashset.RemoveAll(list2); Assert.IsTrue(IC.Eq(hashset, 4)); list2.Clear(); list2.Add(7); list2.Add(8); list2.Add(9); hashset.RemoveAll(list2); Assert.IsTrue(IC.Eq(hashset, 4)); } [Test] public void Remove() { hashset.Add(4); hashset.Add(4); hashset.Add(5); hashset.Add(4); hashset.Add(6); Assert.IsFalse(hashset.Remove(2)); Assert.IsTrue(hashset.Remove(4)); Assert.IsTrue(IC.SetEq(hashset, 5, 6)); hashset.Add(7); hashset.Add(21); hashset.Add(37); hashset.Add(53); hashset.Add(69); hashset.Add(85); Assert.IsTrue(hashset.Remove(5)); Assert.IsTrue(IC.SetEq(hashset, 6, 7, 21, 37, 53, 69, 85)); Assert.IsFalse(hashset.Remove(165)); Assert.IsTrue(IC.SetEq(hashset, 6, 7, 21, 37, 53, 69, 85)); Assert.IsTrue(hashset.Remove(53)); Assert.IsTrue(IC.SetEq(hashset, 6, 7, 21, 37, 69, 85)); Assert.IsTrue(hashset.Remove(37)); Assert.IsTrue(IC.SetEq(hashset, 6, 7, 21, 69, 85)); Assert.IsTrue(hashset.Remove(85)); Assert.IsTrue(IC.SetEq(hashset, 6, 7, 21, 69)); } [Test] public void Clear() { hashset.Add(7); hashset.Add(7); hashset.Clear(); Assert.IsTrue(hashset.IsEmpty); } [TearDown] public void Dispose() { Debug.UseDeterministicHashing = false; hashset = null; } } [TestFixture] public class Combined { private ICollection<System.Collections.Generic.KeyValuePair<int, int>> lst; [SetUp] public void Init() { lst = new HashSet<System.Collections.Generic.KeyValuePair<int, int>>(new KeyValuePairEqualityComparer<int, int>()); for (int i = 0; i < 10; i++) { lst.Add(new System.Collections.Generic.KeyValuePair<int, int>(i, i + 30)); } } [TearDown] public void Dispose() { lst = null; } [Test] public void Find() { System.Collections.Generic.KeyValuePair<int, int> p = new System.Collections.Generic.KeyValuePair<int, int>(3, 78); Assert.IsTrue(lst.Find(ref p)); Assert.AreEqual(3, p.Key); Assert.AreEqual(33, p.Value); p = new System.Collections.Generic.KeyValuePair<int, int>(13, 78); Assert.IsFalse(lst.Find(ref p)); } [Test] public void FindOrAdd() { var p = new SCG.KeyValuePair<int, int>(3, 78); var q = new SCG.KeyValuePair<int, int>(); Assert.IsTrue(lst.FindOrAdd(ref p)); Assert.AreEqual(3, p.Key); Assert.AreEqual(33, p.Value); p = new SCG.KeyValuePair<int, int>(13, 79); Assert.IsFalse(lst.FindOrAdd(ref p)); q = new SCG.KeyValuePair<int, int>(13, q.Value); Assert.IsTrue(lst.Find(ref q)); Assert.AreEqual(13, q.Key); Assert.AreEqual(79, q.Value); } [Test] public void Update() { var p = new SCG.KeyValuePair<int, int>(3, 78); var q = new SCG.KeyValuePair<int, int>(); Assert.IsTrue(lst.Update(p)); q = new SCG.KeyValuePair<int, int>(3, q.Value); Assert.IsTrue(lst.Find(ref q)); Assert.AreEqual(3, q.Key); Assert.AreEqual(78, q.Value); p = new SCG.KeyValuePair<int, int>(13, 78); Assert.IsFalse(lst.Update(p)); } [Test] public void UpdateOrAdd1() { var p = new SCG.KeyValuePair<int, int>(3, 78); var q = new SCG.KeyValuePair<int, int>(); Assert.IsTrue(lst.UpdateOrAdd(p)); q = new SCG.KeyValuePair<int, int>(3, q.Value); Assert.IsTrue(lst.Find(ref q)); Assert.AreEqual(3, q.Key); Assert.AreEqual(78, q.Value); p = new SCG.KeyValuePair<int, int>(13, 79); Assert.IsFalse(lst.UpdateOrAdd(p)); q = new SCG.KeyValuePair<int, int>(13, q.Value); Assert.IsTrue(lst.Find(ref q)); Assert.AreEqual(13, q.Key); Assert.AreEqual(79, q.Value); } [Test] public void UpdateOrAdd2() { ICollection<string> coll = new HashSet<string>(); // s1 and s2 are distinct objects but contain the same text: string s1 = "abc", s2 = ("def" + s1).Substring(3); Assert.IsFalse(coll.UpdateOrAdd(s1, out string old)); Assert.AreEqual(null, old); Assert.IsTrue(coll.UpdateOrAdd(s2, out old)); Assert.IsTrue(object.ReferenceEquals(s1, old)); Assert.IsFalse(object.ReferenceEquals(s2, old)); } [Test] public void RemoveWithReturn() { System.Collections.Generic.KeyValuePair<int, int> p = new System.Collections.Generic.KeyValuePair<int, int>(3, 78); //System.Collections.Generic.KeyValuePair<int,int> q = new System.Collections.Generic.KeyValuePair<int,int>(); Assert.IsTrue(lst.Remove(p, out p)); Assert.AreEqual(3, p.Key); Assert.AreEqual(33, p.Value); p = new System.Collections.Generic.KeyValuePair<int, int>(13, 78); Assert.IsFalse(lst.Remove(p, out _)); } } } namespace HashingAndEquals { [TestFixture] public class IEditableCollection { private ICollection<int> dit, dat, dut; [SetUp] public void Init() { dit = new HashSet<int>(); dat = new HashSet<int>(); dut = new HashSet<int>(); } [Test] public void EmptyEmpty() { Assert.IsTrue(dit.UnsequencedEquals(dat)); } [Test] public void EmptyNonEmpty() { dit.Add(3); Assert.IsFalse(dit.UnsequencedEquals(dat)); Assert.IsFalse(dat.UnsequencedEquals(dit)); } [Test] public void HashVal() { Assert.AreEqual(CHC.UnsequencedHashCode(), dit.GetUnsequencedHashCode()); dit.Add(3); Assert.AreEqual(CHC.UnsequencedHashCode(3), dit.GetUnsequencedHashCode()); dit.Add(7); Assert.AreEqual(CHC.UnsequencedHashCode(3, 7), dit.GetUnsequencedHashCode()); Assert.AreEqual(CHC.UnsequencedHashCode(), dut.GetUnsequencedHashCode()); dut.Add(3); Assert.AreEqual(CHC.UnsequencedHashCode(3), dut.GetUnsequencedHashCode()); dut.Add(7); Assert.AreEqual(CHC.UnsequencedHashCode(7, 3), dut.GetUnsequencedHashCode()); } [Test] public void EqualHashButDifferent() { dit.Add(-1657792980); dit.Add(-1570288808); dat.Add(1862883298); dat.Add(-272461342); Assert.AreEqual(dit.GetUnsequencedHashCode(), dat.GetUnsequencedHashCode()); Assert.IsFalse(dit.UnsequencedEquals(dat)); } [Test] public void Normal() { dit.Add(3); dit.Add(7); dat.Add(3); Assert.IsFalse(dit.UnsequencedEquals(dat)); Assert.IsFalse(dat.UnsequencedEquals(dit)); dat.Add(7); Assert.IsTrue(dit.UnsequencedEquals(dat)); Assert.IsTrue(dat.UnsequencedEquals(dit)); } [Test] public void WrongOrder() { dit.Add(3); dut.Add(3); Assert.IsTrue(dit.UnsequencedEquals(dut)); Assert.IsTrue(dut.UnsequencedEquals(dit)); dit.Add(7); dut.Add(7); Assert.IsTrue(dit.UnsequencedEquals(dut)); Assert.IsTrue(dut.UnsequencedEquals(dit)); } [Test] public void Reflexive() { Assert.IsTrue(dit.UnsequencedEquals(dit)); dit.Add(3); Assert.IsTrue(dit.UnsequencedEquals(dit)); dit.Add(7); Assert.IsTrue(dit.UnsequencedEquals(dit)); } [TearDown] public void Dispose() { dit = null; dat = null; dut = null; } } [TestFixture] public class MultiLevelUnorderedOfUnOrdered { private ICollection<int> dit, dat, dut; private ICollection<ICollection<int>> Dit, Dat, Dut; [SetUp] public void Init() { dit = new HashSet<int>(); dat = new HashSet<int>(); dut = new HashSet<int>(); dit.Add(2); dit.Add(1); dat.Add(1); dat.Add(2); dut.Add(3); Dit = new HashSet<ICollection<int>>(); Dat = new HashSet<ICollection<int>>(); Dut = new HashSet<ICollection<int>>(); } [Test] public void Check() { Assert.IsTrue(dit.UnsequencedEquals(dat)); Assert.IsFalse(dit.UnsequencedEquals(dut)); } [Test] public void Multi() { Dit.Add(dit); Dit.Add(dut); Dit.Add(dit); Dat.Add(dut); Dat.Add(dit); Dat.Add(dat); Assert.IsTrue(Dit.UnsequencedEquals(Dat)); Assert.IsFalse(Dit.UnsequencedEquals(Dut)); } [TearDown] public void Dispose() { dit = dat = dut = null; Dit = Dat = Dut = null; } } [TestFixture] public class MultiLevelOrderedOfUnOrdered { private ICollection<int> dit, dat, dut; private ISequenced<ICollection<int>> Dit, Dat, Dut; [SetUp] public void Init() { dit = new HashSet<int>(); dat = new HashSet<int>(); dut = new HashSet<int>(); dit.Add(2); dit.Add(1); dat.Add(1); dat.Add(2); dut.Add(3); Dit = new LinkedList<ICollection<int>>(); Dat = new LinkedList<ICollection<int>>(); Dut = new LinkedList<ICollection<int>>(); } [Test] public void Check() { Assert.IsTrue(dit.UnsequencedEquals(dat)); Assert.IsFalse(dit.UnsequencedEquals(dut)); } [Test] public void Multi() { Dit.Add(dit); Dit.Add(dut); Dit.Add(dit); Dat.Add(dut); Dat.Add(dit); Dat.Add(dat); Dut.Add(dit); Dut.Add(dut); Dut.Add(dat); Assert.IsFalse(Dit.SequencedEquals(Dat)); Assert.IsTrue(Dit.SequencedEquals(Dut)); } [TearDown] public void Dispose() { dit = dat = dut = null; Dit = Dat = Dut = null; } } [TestFixture] public class MultiLevelUnOrderedOfOrdered { private ISequenced<int> dit, dat, dut, dot; private ICollection<ISequenced<int>> Dit, Dat, Dut, Dot; [SetUp] public void Init() { dit = new LinkedList<int>(); dat = new LinkedList<int>(); dut = new LinkedList<int>(); dot = new LinkedList<int>(); dit.Add(2); dit.Add(1); dat.Add(1); dat.Add(2); dut.Add(3); dot.Add(2); dot.Add(1); Dit = new HashSet<ISequenced<int>>(); Dat = new HashSet<ISequenced<int>>(); Dut = new HashSet<ISequenced<int>>(); Dot = new HashSet<ISequenced<int>>(); } [Test] public void Check() { Assert.IsFalse(dit.SequencedEquals(dat)); Assert.IsTrue(dit.SequencedEquals(dot)); Assert.IsFalse(dit.SequencedEquals(dut)); } [Test] public void Multi() { Dit.Add(dit); Dit.Add(dut);//Dit.Add(dit); Dat.Add(dut); Dat.Add(dit); Dat.Add(dat); Dut.Add(dot); Dut.Add(dut);//Dut.Add(dit); Dot.Add(dit); Dot.Add(dit); Dot.Add(dut); Assert.IsTrue(Dit.UnsequencedEquals(Dit)); Assert.IsTrue(Dit.UnsequencedEquals(Dut)); Assert.IsFalse(Dit.UnsequencedEquals(Dat)); Assert.IsTrue(Dit.UnsequencedEquals(Dot)); } [TearDown] public void Dispose() { dit = dat = dut = dot = null; Dit = Dat = Dut = Dot = null; } } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class ItemBuyer : IEquatable<ItemBuyer> { /// <summary> /// Initializes a new instance of the <see cref="ItemBuyer" /> class. /// Initializes a new instance of the <see cref="ItemBuyer" />class. /// </summary> /// <param name="LobId">LobId (required).</param> /// <param name="Id">Id (required).</param> /// <param name="Name">Name (required).</param> /// <param name="CustomFields">CustomFields.</param> public ItemBuyer(int? LobId = null, string Id = null, string Name = null, Dictionary<string, Object> CustomFields = null) { // to ensure "LobId" is required (not null) if (LobId == null) { throw new InvalidDataException("LobId is a required property for ItemBuyer and cannot be null"); } else { this.LobId = LobId; } // to ensure "Id" is required (not null) if (Id == null) { throw new InvalidDataException("Id is a required property for ItemBuyer and cannot be null"); } else { this.Id = Id; } // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for ItemBuyer and cannot be null"); } else { this.Name = Name; } this.CustomFields = CustomFields; } /// <summary> /// Gets or Sets LobId /// </summary> [DataMember(Name="lobId", EmitDefaultValue=false)] public int? LobId { get; set; } /// <summary> /// Gets or Sets InternalId /// </summary> [DataMember(Name="internalId", EmitDefaultValue=false)] public int? InternalId { get; private set; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public string Id { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { 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 ItemBuyer {\n"); sb.Append(" LobId: ").Append(LobId).Append("\n"); sb.Append(" InternalId: ").Append(InternalId).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).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 string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ItemBuyer); } /// <summary> /// Returns true if ItemBuyer instances are equal /// </summary> /// <param name="other">Instance of ItemBuyer to be compared</param> /// <returns>Boolean</returns> public bool Equals(ItemBuyer other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.LobId == other.LobId || this.LobId != null && this.LobId.Equals(other.LobId) ) && ( this.InternalId == other.InternalId || this.InternalId != null && this.InternalId.Equals(other.InternalId) ) && ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.LobId != null) hash = hash * 59 + this.LobId.GetHashCode(); if (this.InternalId != null) hash = hash * 59 + this.InternalId.GetHashCode(); if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); return hash; } } } }
using J2N; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Util; using System; using System.Diagnostics; namespace Lucene.Net.Analysis { /* * 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 Automaton = Lucene.Net.Util.Automaton.Automaton; using State = Lucene.Net.Util.Automaton.State; using Transition = Lucene.Net.Util.Automaton.Transition; // TODO: maybe also toFST? then we can translate atts into FST outputs/weights /// <summary> /// Consumes a <see cref="TokenStream"/> and creates an <see cref="Automaton"/> /// where the transition labels are UTF8 bytes (or Unicode /// code points if unicodeArcs is true) from the <see cref="ITermToBytesRefAttribute"/>. /// Between tokens we insert /// <see cref="POS_SEP"/> and for holes we insert <see cref="HOLE"/>. /// /// @lucene.experimental /// </summary> public class TokenStreamToAutomaton { //backing variables private bool preservePositionIncrements; private bool unicodeArcs; /// <summary> /// Sole constructor. </summary> public TokenStreamToAutomaton() { this.preservePositionIncrements = true; } /// <summary> /// Whether to generate holes in the automaton for missing positions, <c>true</c> by default. </summary> public virtual bool PreservePositionIncrements { get => this.preservePositionIncrements; // LUCENENET specific - properties should always have a getter set => this.preservePositionIncrements = value; } /// <summary> /// Whether to make transition labels Unicode code points instead of UTF8 bytes, /// <c>false</c> by default /// </summary> public virtual bool UnicodeArcs { get => this.unicodeArcs; // LUCENENET specific - properties should always have a getter set => this.unicodeArcs = value; } private class Position : RollingBuffer.IResettable { // Any tokens that ended at our position arrive to this state: internal State arriving; // Any tokens that start at our position leave from this state: internal State leaving; public void Reset() { arriving = null; leaving = null; } } private class Positions : RollingBuffer<Position> { public Positions() : base(NewPosition) { } protected override Position NewInstance() { return NewPosition(); } private static Position NewPosition() { return new Position(); } } /// <summary> /// Subclass &amp; implement this if you need to change the /// token (such as escaping certain bytes) before it's /// turned into a graph. /// </summary> protected internal virtual BytesRef ChangeToken(BytesRef @in) { return @in; } /// <summary> /// We create transition between two adjacent tokens. </summary> public const int POS_SEP = 0x001f; /// <summary> /// We add this arc to represent a hole. </summary> public const int HOLE = 0x001e; /// <summary> /// Pulls the graph (including <see cref="IPositionLengthAttribute"/> /// from the provided <see cref="TokenStream"/>, and creates the corresponding /// automaton where arcs are bytes (or Unicode code points /// if unicodeArcs = true) from each term. /// </summary> public virtual Automaton ToAutomaton(TokenStream @in) { var a = new Automaton(); bool deterministic = true; var posIncAtt = @in.AddAttribute<IPositionIncrementAttribute>(); var posLengthAtt = @in.AddAttribute<IPositionLengthAttribute>(); var offsetAtt = @in.AddAttribute<IOffsetAttribute>(); var termBytesAtt = @in.AddAttribute<ITermToBytesRefAttribute>(); BytesRef term = termBytesAtt.BytesRef; @in.Reset(); // Only temporarily holds states ahead of our current // position: RollingBuffer<Position> positions = new Positions(); int pos = -1; Position posData = null; int maxOffset = 0; while (@in.IncrementToken()) { int posInc = posIncAtt.PositionIncrement; if (!preservePositionIncrements && posInc > 1) { posInc = 1; } Debug.Assert(pos > -1 || posInc > 0); if (posInc > 0) { // New node: pos += posInc; posData = positions.Get(pos); Debug.Assert(posData.leaving == null); if (posData.arriving == null) { // No token ever arrived to this position if (pos == 0) { // OK: this is the first token posData.leaving = a.GetInitialState(); } else { // this means there's a hole (eg, StopFilter // does this): posData.leaving = new State(); AddHoles(a.GetInitialState(), positions, pos); } } else { posData.leaving = new State(); posData.arriving.AddTransition(new Transition(POS_SEP, posData.leaving)); if (posInc > 1) { // A token spanned over a hole; add holes // "under" it: AddHoles(a.GetInitialState(), positions, pos); } } positions.FreeBefore(pos); } else { // note: this isn't necessarily true. its just that we aren't surely det. // we could optimize this further (e.g. buffer and sort synonyms at a position) // but thats probably overkill. this is cheap and dirty deterministic = false; } int endPos = pos + posLengthAtt.PositionLength; termBytesAtt.FillBytesRef(); BytesRef termUTF8 = ChangeToken(term); int[] termUnicode = null; Position endPosData = positions.Get(endPos); if (endPosData.arriving == null) { endPosData.arriving = new State(); } State state = posData.leaving; int termLen = termUTF8.Length; if (unicodeArcs) { string utf16 = termUTF8.Utf8ToString(); termUnicode = new int[utf16.CodePointCount(0, utf16.Length)]; termLen = termUnicode.Length; for (int cp, i = 0, j = 0; i < utf16.Length; i += Character.CharCount(cp)) { termUnicode[j++] = cp = Character.CodePointAt(utf16, i); } } else { termLen = termUTF8.Length; } for (int byteIDX = 0; byteIDX < termLen; byteIDX++) { State nextState = byteIDX == termLen - 1 ? endPosData.arriving : new State(); int c; if (unicodeArcs) { c = termUnicode[byteIDX]; } else { c = termUTF8.Bytes[termUTF8.Offset + byteIDX] & 0xff; } state.AddTransition(new Transition(c, nextState)); state = nextState; } maxOffset = Math.Max(maxOffset, offsetAtt.EndOffset); } @in.End(); State endState = null; if (offsetAtt.EndOffset > maxOffset) { endState = new State(); endState.Accept = true; } pos++; while (pos <= positions.MaxPos) { posData = positions.Get(pos); if (posData.arriving != null) { if (endState != null) { posData.arriving.AddTransition(new Transition(POS_SEP, endState)); } else { posData.arriving.Accept = true; } } pos++; } //toDot(a); a.IsDeterministic = deterministic; return a; } // for debugging! /* private static void toDot(Automaton a) throws IOException { final String s = a.toDot(); Writer w = new OutputStreamWriter(new FileOutputStream("/tmp/out.dot")); w.write(s); w.Dispose(); System.out.println("TEST: saved to /tmp/out.dot"); } */ private static void AddHoles(State startState, RollingBuffer<Position> positions, int pos) { Position posData = positions.Get(pos); Position prevPosData = positions.Get(pos - 1); while (posData.arriving == null || prevPosData.leaving == null) { if (posData.arriving == null) { posData.arriving = new State(); posData.arriving.AddTransition(new Transition(POS_SEP, posData.leaving)); } if (prevPosData.leaving == null) { if (pos == 1) { prevPosData.leaving = startState; } else { prevPosData.leaving = new State(); } if (prevPosData.arriving != null) { prevPosData.arriving.AddTransition(new Transition(POS_SEP, prevPosData.leaving)); } } prevPosData.leaving.AddTransition(new Transition(HOLE, posData.arriving)); pos--; if (pos <= 0) { break; } posData = prevPosData; prevPosData = positions.Get(pos - 1); } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Preview.Marketplace { /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Install an Add-on for the Account specified. /// </summary> public class CreateInstalledAddOnOptions : IOptions<InstalledAddOnResource> { /// <summary> /// The SID of the AvaliableAddOn to install /// </summary> public string AvailableAddOnSid { get; } /// <summary> /// Whether the Terms of Service were accepted /// </summary> public bool? AcceptTermsOfService { get; } /// <summary> /// The JSON object representing the configuration /// </summary> public object Configuration { get; set; } /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> public string UniqueName { get; set; } /// <summary> /// Construct a new CreateInstalledAddOnOptions /// </summary> /// <param name="availableAddOnSid"> The SID of the AvaliableAddOn to install </param> /// <param name="acceptTermsOfService"> Whether the Terms of Service were accepted </param> public CreateInstalledAddOnOptions(string availableAddOnSid, bool? acceptTermsOfService) { AvailableAddOnSid = availableAddOnSid; AcceptTermsOfService = acceptTermsOfService; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (AvailableAddOnSid != null) { p.Add(new KeyValuePair<string, string>("AvailableAddOnSid", AvailableAddOnSid.ToString())); } if (AcceptTermsOfService != null) { p.Add(new KeyValuePair<string, string>("AcceptTermsOfService", AcceptTermsOfService.Value.ToString().ToLower())); } if (Configuration != null) { p.Add(new KeyValuePair<string, string>("Configuration", Serializers.JsonObject(Configuration))); } if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Remove an Add-on installation from your account /// </summary> public class DeleteInstalledAddOnOptions : IOptions<InstalledAddOnResource> { /// <summary> /// The SID of the InstalledAddOn resource to delete /// </summary> public string PathSid { get; } /// <summary> /// Construct a new DeleteInstalledAddOnOptions /// </summary> /// <param name="pathSid"> The SID of the InstalledAddOn resource to delete </param> public DeleteInstalledAddOnOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Fetch an instance of an Add-on currently installed on this Account. /// </summary> public class FetchInstalledAddOnOptions : IOptions<InstalledAddOnResource> { /// <summary> /// The SID of the InstalledAddOn resource to fetch /// </summary> public string PathSid { get; } /// <summary> /// Construct a new FetchInstalledAddOnOptions /// </summary> /// <param name="pathSid"> The SID of the InstalledAddOn resource to fetch </param> public FetchInstalledAddOnOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Update an Add-on installation for the Account specified. /// </summary> public class UpdateInstalledAddOnOptions : IOptions<InstalledAddOnResource> { /// <summary> /// The SID of the InstalledAddOn resource to update /// </summary> public string PathSid { get; } /// <summary> /// The JSON object representing the configuration /// </summary> public object Configuration { get; set; } /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> public string UniqueName { get; set; } /// <summary> /// Construct a new UpdateInstalledAddOnOptions /// </summary> /// <param name="pathSid"> The SID of the InstalledAddOn resource to update </param> public UpdateInstalledAddOnOptions(string pathSid) { PathSid = pathSid; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Configuration != null) { p.Add(new KeyValuePair<string, string>("Configuration", Serializers.JsonObject(Configuration))); } if (UniqueName != null) { p.Add(new KeyValuePair<string, string>("UniqueName", UniqueName)); } return p; } } /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// Retrieve a list of Add-ons currently installed on this Account. /// </summary> public class ReadInstalledAddOnOptions : ReadOptions<InstalledAddOnResource> { /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Diagnostics; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto { /** * A wrapper class that allows block ciphers to be used to process data in * a piecemeal fashion. The BufferedBlockCipher outputs a block only when the * buffer is full and more data is being added, or on a doFinal. * <p> * Note: in the case where the underlying cipher is either a CFB cipher or an * OFB one the last block may not be a multiple of the block size. * </p> */ public class BufferedBlockCipher : BufferedCipherBase { internal byte[] buf; internal int bufOff; internal bool forEncryption; internal IBlockCipher cipher; /** * constructor for subclasses */ protected BufferedBlockCipher() { } /** * Create a buffered block cipher without padding. * * @param cipher the underlying block cipher this buffering object wraps. * false otherwise. */ public BufferedBlockCipher( IBlockCipher cipher) { if (cipher == null) throw new ArgumentNullException("cipher"); this.cipher = cipher; buf = new byte[cipher.GetBlockSize()]; bufOff = 0; } public override string AlgorithmName { get { return cipher.AlgorithmName; } } /** * initialise the cipher. * * @param forEncryption if true the cipher is initialised for * encryption, if false for decryption. * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ // Note: This doubles as the Init in the event that this cipher is being used as an IWrapper public override void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; ParametersWithRandom pwr = parameters as ParametersWithRandom; if (pwr != null) parameters = pwr.Parameters; Reset(); cipher.Init(forEncryption, parameters); } /** * return the blocksize for the underlying cipher. * * @return the blocksize for the underlying cipher. */ public override int GetBlockSize() { return cipher.GetBlockSize(); } /** * return the size of the output buffer required for an update * an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update * with len bytes of input. */ public override int GetUpdateOutputSize( int length) { int total = length + bufOff; int leftOver = total % buf.Length; return total - leftOver; } /** * return the size of the output buffer required for an update plus a * doFinal with an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update and doFinal * with len bytes of input. */ public override int GetOutputSize( int length) { // Note: Can assume IsPartialBlockOkay is true for purposes of this calculation return length + bufOff; } /** * process a single byte, producing an output block if necessary. * * @param in the input byte. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessByte( byte input, byte[] output, int outOff) { buf[bufOff++] = input; if (bufOff == buf.Length) { if ((outOff + buf.Length) > output.Length) throw new DataLengthException("output buffer too short"); bufOff = 0; return cipher.ProcessBlock(buf, 0, output, outOff); } return 0; } public override byte[] ProcessByte( byte input) { int outLength = GetUpdateOutputSize(1); byte[] outBytes = outLength > 0 ? new byte[outLength] : null; int pos = ProcessByte(input, outBytes, 0); if (outLength > 0 && pos < outLength) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } return outBytes; } public override byte[] ProcessBytes( byte[] input, int inOff, int length) { if (input == null) throw new ArgumentNullException("input"); if (length < 1) return null; int outLength = GetUpdateOutputSize(length); byte[] outBytes = outLength > 0 ? new byte[outLength] : null; int pos = ProcessBytes(input, inOff, length, outBytes, 0); if (outLength > 0 && pos < outLength) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } return outBytes; } /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. * @param inOff the offset at which the input data starts. * @param len the number of bytes to be copied out of the input array. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessBytes( byte[] input, int inOff, int length, byte[] output, int outOff) { if (length < 1) { if (length < 0) throw new ArgumentException("Can't have a negative input length!"); return 0; } int blockSize = GetBlockSize(); int outLength = GetUpdateOutputSize(length); if (outLength > 0) { Check.OutputLength(output, outOff, outLength, "output buffer too short"); } int resultLen = 0; int gapLen = buf.Length - bufOff; if (length > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; length -= gapLen; inOff += gapLen; while (length > buf.Length) { resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen); length -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, length); bufOff += length; if (bufOff == buf.Length) { resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); bufOff = 0; } return resultLen; } public override byte[] DoFinal() { byte[] outBytes = EmptyBuffer; int length = GetOutputSize(0); if (length > 0) { outBytes = new byte[length]; int pos = DoFinal(outBytes, 0); if (pos < outBytes.Length) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } } else { Reset(); } return outBytes; } public override byte[] DoFinal( byte[] input, int inOff, int inLen) { if (input == null) throw new ArgumentNullException("input"); int length = GetOutputSize(inLen); byte[] outBytes = EmptyBuffer; if (length > 0) { outBytes = new byte[length]; int pos = (inLen > 0) ? ProcessBytes(input, inOff, inLen, outBytes, 0) : 0; pos += DoFinal(outBytes, pos); if (pos < outBytes.Length) { byte[] tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } } else { Reset(); } return outBytes; } /** * Process the last block in the buffer. * * @param out the array the block currently being held is copied into. * @param outOff the offset at which the copying starts. * @return the number of output bytes copied to out. * @exception DataLengthException if there is insufficient space in out for * the output, or the input is not block size aligned and should be. * @exception InvalidOperationException if the underlying cipher is not * initialised. * @exception InvalidCipherTextException if padding is expected and not found. * @exception DataLengthException if the input is not block size * aligned. */ public override int DoFinal( byte[] output, int outOff) { try { if (bufOff != 0) { Check.DataLength(!cipher.IsPartialBlockOkay, "data not block size aligned"); Check.OutputLength(output, outOff, bufOff, "output buffer too short for DoFinal()"); // NB: Can't copy directly, or we may write too much output cipher.ProcessBlock(buf, 0, buf, 0); Array.Copy(buf, 0, output, outOff, bufOff); } return bufOff; } finally { Reset(); } } /** * Reset the buffer and cipher. After resetting the object is in the same * state as it was after the last init (if there was one). */ public override void Reset() { Array.Clear(buf, 0, buf.Length); bufOff = 0; cipher.Reset(); } } } #endif
//--------------------------------------------------------------------- // <copyright file="Northwind.NonClr.Workspace.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace System.Data.Test.Astoria { using System; using System.Collections.Generic; using System.Data.Test.Astoria; using System.IO; [WorkspaceAttribute("Northwind", DataLayerProviderKind.NonClr, Priority = 0, Standard = true)] public class NorthwindNonClrWorkspace : System.Data.Test.Astoria.NonClrWorkspace { public NorthwindNonClrWorkspace() : base("northwind", "northwind.NonClr", "NorthwindContainer") { this.Language = WorkspaceLanguage.CSharp; } public override ServiceContainer ServiceContainer { get { if (_serviceContainer == null) { //Complex types code here //Complex types that contain other complextypes code here //Resource types here ResourceType Categories = Resource.ResourceType("Categories", "northwind.NonClr", Resource.Property("CategoryID", Clr.Types.Int32, Resource.Key()), Resource.Property("CategoryName", Clr.Types.String, NodeFacet.MaxSize(15)), Resource.Property("Description", Clr.Types.String, NodeFacet.Nullable(true),NodeFacet.Sortable(false)), Resource.Property("Picture", Clr.Types.Binary, NodeFacet.Nullable(true),NodeFacet.Sortable(false)) ); ResourceType Products = Resource.ResourceType("Products", "northwind.NonClr", Resource.Property("ProductID", Clr.Types.Int32, Resource.Key()), Resource.Property("ProductName", Clr.Types.String, NodeFacet.MaxSize(40)), Resource.Property("QuantityPerUnit", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(20)), Resource.Property("UnitPrice", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)), Resource.Property("UnitsInStock", Clr.Types.Int16, NodeFacet.Nullable(true)), Resource.Property("UnitsOnOrder", Clr.Types.Int16, NodeFacet.Nullable(true)), Resource.Property("ReorderLevel", Clr.Types.Int16, NodeFacet.Nullable(true)), Resource.Property("Discontinued", Clr.Types.Boolean) ); ResourceType Orders = Resource.ResourceType("Orders", "northwind.NonClr", Resource.Property("OrderID", Clr.Types.Int32, Resource.Key()), Resource.Property("OrderDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("RequiredDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("ShippedDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("Freight", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)), Resource.Property("ShipName", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(40)), Resource.Property("ShipAddress", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(60)), Resource.Property("ShipCity", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("ShipRegion", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("ShipPostalCode", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(10)) ); ResourceType Order_Details = Resource.ResourceType("Order_Details", "northwind.NonClr", Resource.Property("OrderID", Clr.Types.Int32, Resource.Key()), Resource.Property("ProductID", Clr.Types.Int32, Resource.Key()), Resource.Property("UnitPrice", Clr.Types.Decimal, NodeFacet.Precision(19), NodeFacet.Scale(4)), Resource.Property("Quantity", Clr.Types.Int16), Resource.Property("Discount", Clr.Types.Single) ); ResourceType Customers = Resource.ResourceType("Customers", "northwind.NonClr", Resource.Property("CustomerID", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(5), NodeFacet.FixedLength(true)), Resource.Property("CompanyName", Clr.Types.String, NodeFacet.MaxSize(40)), Resource.Property("ContactName", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(30)), Resource.Property("ContactTitle", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(30)), Resource.Property("Address", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(60)), Resource.Property("City", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("Region", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("PostalCode", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(10)), Resource.Property("Phone", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(24)), Resource.Property("Fax", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(24)) ); ResourceType CustomerDemographics = Resource.ResourceType("CustomerDemographics", "northwind.NonClr", Resource.Property("CustomerTypeID", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(10), NodeFacet.FixedLength(true)), Resource.Property("CustomerDesc", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.Sortable(false)) ); ResourceType Employees = Resource.ResourceType("Employees", "northwind.NonClr", Resource.Property("EmployeeID", Clr.Types.Int32, Resource.Key()), Resource.Property("LastName", Clr.Types.String, NodeFacet.MaxSize(20)), Resource.Property("FirstName", Clr.Types.String, NodeFacet.MaxSize(10)), Resource.Property("Title", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(30)), Resource.Property("TitleOfCourtesy", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(25)), Resource.Property("BirthDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("HireDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("Address", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(60)), Resource.Property("City", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("Region", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("PostalCode", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(10)), Resource.Property("HomePhone", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(24)), Resource.Property("Extension", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(4)), Resource.Property("Photo", Clr.Types.Binary, NodeFacet.Nullable(true), NodeFacet.Sortable(false)), Resource.Property("Notes", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.Sortable(false)), Resource.Property("PhotoPath", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(255)) ); ResourceType Territories = Resource.ResourceType("Territories", "northwind.NonClr", Resource.Property("TerritoryID", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(20)), Resource.Property("TerritoryDescription", Clr.Types.String, NodeFacet.MaxSize(50), NodeFacet.FixedLength(true)) ); ResourceType Region = Resource.ResourceType("Region", "northwind.NonClr", Resource.Property("RegionID", Clr.Types.Int32, Resource.Key()), Resource.Property("RegionDescription", Clr.Types.String, NodeFacet.MaxSize(50), NodeFacet.FixedLength(true)) ); ResourceType Shippers = Resource.ResourceType("Shippers", "northwind.NonClr", Resource.Property("ShipperID", Clr.Types.Int32, Resource.Key()), Resource.Property("CompanyName", Clr.Types.String, NodeFacet.MaxSize(40)), Resource.Property("Phone", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(24)) ); ResourceType Suppliers = Resource.ResourceType("Suppliers", "northwind.NonClr", Resource.Property("SupplierID", Clr.Types.Int32, Resource.Key()), Resource.Property("CompanyName", Clr.Types.String, NodeFacet.MaxSize(40)), Resource.Property("ContactName", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(30)), Resource.Property("ContactTitle", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(30)), Resource.Property("Address", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(60)), Resource.Property("City", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("Region", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("PostalCode", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(10)), Resource.Property("Phone", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(24)), Resource.Property("Fax", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(24)), Resource.Property("HomePage", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.Sortable(false)) ); ResourceType Alphabetical_list_of_products = Resource.ResourceType("Alphabetical_list_of_products", "northwind.NonClr", Resource.Property("ProductID", Clr.Types.Int32, Resource.Key()), Resource.Property("ProductName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("SupplierID", Clr.Types.Int32, NodeFacet.Nullable(true)), Resource.Property("CategoryID", Clr.Types.Int32, NodeFacet.Nullable(true)), Resource.Property("QuantityPerUnit", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(20)), Resource.Property("UnitPrice", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)), Resource.Property("UnitsInStock", Clr.Types.Int16, NodeFacet.Nullable(true)), Resource.Property("UnitsOnOrder", Clr.Types.Int16, NodeFacet.Nullable(true)), Resource.Property("ReorderLevel", Clr.Types.Int16, NodeFacet.Nullable(true)), Resource.Property("Discontinued", Clr.Types.Boolean, Resource.Key()), Resource.Property("CategoryName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(15)) ); ResourceType Category_Sales_for_1997 = Resource.ResourceType("Category_Sales_for_1997", "northwind.NonClr", Resource.Property("CategoryName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(15)), Resource.Property("CategorySales", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)) ); ResourceType Current_Product_List = Resource.ResourceType("Current_Product_List", "northwind.NonClr", Resource.Property("ProductID", Clr.Types.Int32, Resource.Key()), Resource.Property("ProductName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)) ); ResourceType Customer_and_Suppliers_by_City = Resource.ResourceType("Customer_and_Suppliers_by_City", "northwind.NonClr", Resource.Property("City", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("CompanyName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("ContactName", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(30)), Resource.Property("Relationship", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(9)) ); ResourceType Invoices = Resource.ResourceType("Invoices", "northwind.NonClr", Resource.Property("ShipName", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(40)), Resource.Property("ShipAddress", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(60)), Resource.Property("ShipCity", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("ShipRegion", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("ShipPostalCode", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(10)), Resource.Property("CustomerID", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(5), NodeFacet.FixedLength(true)), Resource.Property("CustomerName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("Address", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(60)), Resource.Property("City", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("Region", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("PostalCode", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(10)), Resource.Property("Salesperson", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(31)), Resource.Property("OrderID", Clr.Types.Int32, Resource.Key()), Resource.Property("OrderDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("RequiredDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("ShippedDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("ShipperName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("ProductID", Clr.Types.Int32, Resource.Key()), Resource.Property("ProductName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("UnitPrice", Clr.Types.Decimal, Resource.Key(), NodeFacet.Precision(19), NodeFacet.Scale(4)), Resource.Property("Quantity", Clr.Types.Int16, Resource.Key()), Resource.Property("Discount", Clr.Types.Single, Resource.Key()), Resource.Property("ExtendedPrice", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)), Resource.Property("Freight", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)) ); ResourceType Order_Details_Extended = Resource.ResourceType("Order_Details_Extended", "northwind.NonClr", Resource.Property("OrderID", Clr.Types.Int32, Resource.Key()), Resource.Property("ProductID", Clr.Types.Int32, Resource.Key()), Resource.Property("ProductName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("UnitPrice", Clr.Types.Decimal, Resource.Key(), NodeFacet.Precision(19), NodeFacet.Scale(4)), Resource.Property("Quantity", Clr.Types.Int16, Resource.Key()), Resource.Property("Discount", Clr.Types.Single, Resource.Key()), Resource.Property("ExtendedPrice", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)) ); ResourceType Order_Subtotals = Resource.ResourceType("Order_Subtotals", "northwind.NonClr", Resource.Property("OrderID", Clr.Types.Int32, Resource.Key()), Resource.Property("Subtotal", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)) ); ResourceType Orders_Qry = Resource.ResourceType("Orders_Qry", "northwind.NonClr", Resource.Property("OrderID", Clr.Types.Int32, Resource.Key()), Resource.Property("CustomerID", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(5), NodeFacet.FixedLength(true)), Resource.Property("EmployeeID", Clr.Types.Int32, NodeFacet.Nullable(true)), Resource.Property("OrderDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("RequiredDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("ShippedDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("ShipVia", Clr.Types.Int32, NodeFacet.Nullable(true)), Resource.Property("Freight", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)), Resource.Property("ShipName", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(40)), Resource.Property("ShipAddress", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(60)), Resource.Property("ShipCity", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("ShipRegion", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("ShipPostalCode", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(10)), Resource.Property("CompanyName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("Address", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(60)), Resource.Property("City", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("Region", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(15)), Resource.Property("PostalCode", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(10)) ); ResourceType Product_Sales_for_1997 = Resource.ResourceType("Product_Sales_for_1997", "northwind.NonClr", Resource.Property("CategoryName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(15)), Resource.Property("ProductName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("ProductSales", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)) ); ResourceType Products_Above_Average_Price = Resource.ResourceType("Products_Above_Average_Price", "northwind.NonClr", Resource.Property("ProductName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("UnitPrice", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)) ); ResourceType Products_by_Category = Resource.ResourceType("Products_by_Category", "northwind.NonClr", Resource.Property("CategoryName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(15)), Resource.Property("ProductName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("QuantityPerUnit", Clr.Types.String, NodeFacet.Nullable(true), NodeFacet.MaxSize(20)), Resource.Property("UnitsInStock", Clr.Types.Int16, NodeFacet.Nullable(true)), Resource.Property("Discontinued", Clr.Types.Boolean, Resource.Key()) ); ResourceType Sales_by_Category = Resource.ResourceType("Sales_by_Category", "northwind.NonClr", Resource.Property("CategoryID", Clr.Types.Int32, Resource.Key()), Resource.Property("CategoryName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(15)), Resource.Property("ProductName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("ProductSales", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)) ); ResourceType Sales_Totals_by_Amount = Resource.ResourceType("Sales_Totals_by_Amount", "northwind.NonClr", Resource.Property("SaleAmount", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)), Resource.Property("OrderID", Clr.Types.Int32, Resource.Key()), Resource.Property("CompanyName", Clr.Types.String, Resource.Key(), NodeFacet.MaxSize(40)), Resource.Property("ShippedDate", Clr.Types.DateTime, NodeFacet.Nullable(true)) ); ResourceType Summary_of_Sales_by_Quarter = Resource.ResourceType("Summary_of_Sales_by_Quarter", "northwind.NonClr", Resource.Property("ShippedDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("OrderID", Clr.Types.Int32, Resource.Key()), Resource.Property("Subtotal", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)) ); ResourceType Summary_of_Sales_by_Year = Resource.ResourceType("Summary_of_Sales_by_Year", "northwind.NonClr", Resource.Property("ShippedDate", Clr.Types.DateTime, NodeFacet.Nullable(true)), Resource.Property("OrderID", Clr.Types.Int32, Resource.Key()), Resource.Property("Subtotal", Clr.Types.Decimal, NodeFacet.Nullable(true), NodeFacet.Precision(19), NodeFacet.Scale(4)) ); //Explicity define Many to many relationships here ResourceAssociationEnd CategoriesRole = Resource.End("Categories", Categories, Multiplicity.Zero); ResourceAssociationEnd ProductsRole = Resource.End("Products", Products, Multiplicity.Many); ResourceAssociation FK_Products_Categories = Resource.Association("FK_Products_Categories", CategoriesRole, ProductsRole); ResourceAssociationEnd CustomersRole = Resource.End("Customers", Customers, Multiplicity.Zero); ResourceAssociationEnd OrdersRole = Resource.End("Orders", Orders, Multiplicity.Many); ResourceAssociation FK_Orders_Customers = Resource.Association("FK_Orders_Customers", CustomersRole, OrdersRole); ResourceAssociationEnd CustomerDemographicsRole = Resource.End("CustomerDemographics", CustomerDemographics, Multiplicity.Many); ResourceAssociationEnd CustomersRole11 = Resource.End("Customers", Customers, Multiplicity.Many); ResourceAssociation CustomerCustomerDemo = Resource.Association("CustomerCustomerDemo", CustomerDemographicsRole, CustomersRole11); ResourceAssociationEnd EmployeesRole = Resource.End("Employees", Employees, Multiplicity.Zero); ResourceAssociationEnd Employees1Role = Resource.End("Employees1", Employees, Multiplicity.Many); ResourceAssociation FK_Employees_Employees = Resource.Association("FK_Employees_Employees", EmployeesRole, Employees1Role); ResourceAssociationEnd EmployeesRole11 = Resource.End("Employees", Employees, Multiplicity.Zero); ResourceAssociationEnd OrdersRole11 = Resource.End("Orders", Orders, Multiplicity.Many); ResourceAssociation FK_Orders_Employees = Resource.Association("FK_Orders_Employees", EmployeesRole11, OrdersRole11); ResourceAssociationEnd RegionRole = Resource.End("Region", Region, Multiplicity.Zero); ResourceAssociationEnd TerritoriesRole = Resource.End("Territories", Territories, Multiplicity.Many); ResourceAssociation FK_Territories_Region = Resource.Association("FK_Territories_Region", RegionRole, TerritoriesRole); ResourceAssociationEnd EmployeesRole21 = Resource.End("Employees", Employees, Multiplicity.Many); ResourceAssociationEnd TerritoriesRole11 = Resource.End("Territories", Territories, Multiplicity.Many); ResourceAssociation EmployeeTerritories = Resource.Association("EmployeeTerritories", EmployeesRole21, TerritoriesRole11); ResourceAssociationEnd OrdersRole21 = Resource.End("Orders", Orders, Multiplicity.Zero); ResourceAssociationEnd Order_DetailsRole = Resource.End("Order_Details", Order_Details, Multiplicity.Many); ResourceAssociation FK_Order_Details_Orders = Resource.Association("FK_Order_Details_Orders", OrdersRole21, Order_DetailsRole); ResourceAssociationEnd ShippersRole = Resource.End("Shippers", Shippers, Multiplicity.Zero); ResourceAssociationEnd OrdersRole31 = Resource.End("Orders", Orders, Multiplicity.Many); ResourceAssociation FK_Orders_Shippers = Resource.Association("FK_Orders_Shippers", ShippersRole, OrdersRole31); ResourceAssociationEnd ProductsRole11 = Resource.End("Products", Products, Multiplicity.Zero); ResourceAssociationEnd Order_DetailsRole11 = Resource.End("Order_Details", Order_Details, Multiplicity.Many); ResourceAssociation FK_Order_Details_Products = Resource.Association("FK_Order_Details_Products", ProductsRole11, Order_DetailsRole11); ResourceAssociationEnd SuppliersRole = Resource.End("Suppliers", Suppliers, Multiplicity.Zero); ResourceAssociationEnd ProductsRole21 = Resource.End("Products", Products, Multiplicity.Many); ResourceAssociation FK_Products_Suppliers = Resource.Association("FK_Products_Suppliers", SuppliersRole, ProductsRole21); //Resource navigation properties added here Categories.Properties.Add(Resource.Property("Products", Resource.Collection(Products), FK_Products_Categories, CategoriesRole, ProductsRole)); Products.Properties.Add(Resource.Property("Categories", Categories, NodeFacet.Nullable(true), FK_Products_Categories, ProductsRole, CategoriesRole)); Products.Properties.Add(Resource.Property("Order_Details", Resource.Collection(Order_Details), FK_Order_Details_Products, ProductsRole11, Order_DetailsRole11)); Products.Properties.Add(Resource.Property("Suppliers", Suppliers, NodeFacet.Nullable(true), FK_Products_Suppliers, ProductsRole21, SuppliersRole)); Order_Details.Properties.Add(Resource.Property("Orders", Orders, FK_Order_Details_Orders, Order_DetailsRole, OrdersRole21)); Order_Details.Properties.Add(Resource.Property("Products", Products, FK_Order_Details_Products, Order_DetailsRole11, ProductsRole11)); Orders.Properties.Add(Resource.Property("Customers", Customers, NodeFacet.Nullable(true), FK_Orders_Customers, OrdersRole, CustomersRole)); Orders.Properties.Add(Resource.Property("Employees", Employees, NodeFacet.Nullable(true), FK_Orders_Employees, OrdersRole11, EmployeesRole11)); Orders.Properties.Add(Resource.Property("Order_Details", Resource.Collection(Order_Details), FK_Order_Details_Orders, OrdersRole21, Order_DetailsRole)); Orders.Properties.Add(Resource.Property("Shippers", Shippers, NodeFacet.Nullable(true), FK_Orders_Shippers, OrdersRole31, ShippersRole)); Customers.Properties.Add(Resource.Property("Orders", Resource.Collection(Orders), FK_Orders_Customers, CustomersRole, OrdersRole)); Customers.Properties.Add(Resource.Property("CustomerDemographics", Resource.Collection(CustomerDemographics), CustomerCustomerDemo, CustomersRole11, CustomerDemographicsRole)); CustomerDemographics.Properties.Add(Resource.Property("Customers", Resource.Collection(Customers), CustomerCustomerDemo, CustomerDemographicsRole, CustomersRole11)); Employees.Properties.Add(Resource.Property("Employees1", Resource.Collection(Employees), FK_Employees_Employees, EmployeesRole, Employees1Role)); Employees.Properties.Add(Resource.Property("Employees2", Employees, NodeFacet.Nullable(true), FK_Employees_Employees, Employees1Role, EmployeesRole)); Employees.Properties.Add(Resource.Property("Orders", Resource.Collection(Orders), FK_Orders_Employees, EmployeesRole11, OrdersRole11)); Employees.Properties.Add(Resource.Property("Territories", Resource.Collection(Territories), EmployeeTerritories, EmployeesRole21, TerritoriesRole11)); Territories.Properties.Add(Resource.Property("Region", Region, FK_Territories_Region, TerritoriesRole, RegionRole)); Territories.Properties.Add(Resource.Property("Employees", Resource.Collection(Employees), EmployeeTerritories, TerritoriesRole11, EmployeesRole21)); Region.Properties.Add(Resource.Property("Territories", Resource.Collection(Territories), FK_Territories_Region, RegionRole, TerritoriesRole)); Shippers.Properties.Add(Resource.Property("Orders", Resource.Collection(Orders), FK_Orders_Shippers, ShippersRole, OrdersRole31)); Suppliers.Properties.Add(Resource.Property("Products", Resource.Collection(Products), FK_Products_Suppliers, SuppliersRole, ProductsRole21)); //Mark certain Resources as not insertable Alphabetical_list_of_products.IsInsertable = false; Category_Sales_for_1997.IsInsertable = false; Customer_and_Suppliers_by_City.IsInsertable = false; Current_Product_List.IsInsertable = false; Invoices.IsInsertable = false; Order_Subtotals.IsInsertable = false; Order_Details_Extended.IsInsertable = false; Orders_Qry.IsInsertable = false; Product_Sales_for_1997.IsInsertable = false; Products_Above_Average_Price.IsInsertable = false; Products_by_Category.IsInsertable = false; Sales_by_Category.IsInsertable = false; Sales_Totals_by_Amount.IsInsertable = false; Summary_of_Sales_by_Quarter.IsInsertable = false; Summary_of_Sales_by_Year.IsInsertable = false; //Resource Containers added here _serviceContainer = Resource.ServiceContainer(this, "northwind.NonClr", Resource.ResourceContainer("Categories", Categories), Resource.ResourceContainer("CustomerDemographics", CustomerDemographics), Resource.ResourceContainer("Customers", Customers), Resource.ResourceContainer("Employees", Employees), Resource.ResourceContainer("Order_Details", Order_Details), Resource.ResourceContainer("Orders", Orders), Resource.ResourceContainer("Products", Products), Resource.ResourceContainer("Region", Region), Resource.ResourceContainer("Shippers", Shippers), Resource.ResourceContainer("Suppliers", Suppliers), Resource.ResourceContainer("Territories", Territories), Resource.ResourceContainer("Alphabetical_list_of_products", Alphabetical_list_of_products), Resource.ResourceContainer("Category_Sales_for_1997", Category_Sales_for_1997), Resource.ResourceContainer("Current_Product_List", Current_Product_List), Resource.ResourceContainer("Customer_and_Suppliers_by_City", Customer_and_Suppliers_by_City), Resource.ResourceContainer("Invoices", Invoices), Resource.ResourceContainer("Order_Details_Extended", Order_Details_Extended), Resource.ResourceContainer("Order_Subtotals", Order_Subtotals), Resource.ResourceContainer("Orders_Qry", Orders_Qry), Resource.ResourceContainer("Product_Sales_for_1997", Product_Sales_for_1997), Resource.ResourceContainer("Products_Above_Average_Price", Products_Above_Average_Price), Resource.ResourceContainer("Products_by_Category", Products_by_Category), Resource.ResourceContainer("Sales_by_Category", Sales_by_Category), Resource.ResourceContainer("Sales_Totals_by_Amount", Sales_Totals_by_Amount), Resource.ResourceContainer("Summary_of_Sales_by_Quarter", Summary_of_Sales_by_Quarter), Resource.ResourceContainer("Summary_of_Sales_by_Year", Summary_of_Sales_by_Year) ); foreach (ResourceContainer rc in _serviceContainer.ResourceContainers) { foreach (ResourceType t in rc.ResourceTypes) { t.InferAssociations(); } } } return _serviceContainer; } set { _serviceContainer = value; } } public override ResourceType LanguageDataResource() { return this.ServiceContainer.ResourceContainers["Region"].BaseType; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="BcpgOutputStream.cs"> // Copyright (c) 2014 Alexander Logger. // Copyright (c) 2000 - 2013 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org). // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.IO; using Raksha.Utilities.IO; namespace Raksha.Bcpg { /// <summary> /// Basic output stream. /// </summary> public class BcpgOutputStream : BaseOutputStream { private const int BufferSizePower = 16; // 2^16 size buffer on long files private readonly Stream _outStr; private readonly int _partialBufferLength; private readonly int _partialPower; private byte[] _partialBuffer; private int _partialOffset; /// <summary>Create a stream representing a general packet.</summary> /// <param name="outStr">Output stream to write to.</param> public BcpgOutputStream(Stream outStr) { if (outStr == null) { throw new ArgumentNullException("outStr"); } _outStr = outStr; } /// <summary>Create a stream representing an old style partial object.</summary> /// <param name="outStr">Output stream to write to.</param> /// <param name="tag">The packet tag for the object.</param> public BcpgOutputStream(Stream outStr, PacketTag tag) { if (outStr == null) { throw new ArgumentNullException("outStr"); } _outStr = outStr; WriteHeader(tag, true, true, 0); } /// <summary>Create a stream representing a general packet.</summary> /// <param name="outStr">Output stream to write to.</param> /// <param name="tag">Packet tag.</param> /// <param name="length">Size of chunks making up the packet.</param> /// <param name="oldFormat">If true, the header is written out in old format.</param> public BcpgOutputStream(Stream outStr, PacketTag tag, long length, bool oldFormat) { if (outStr == null) { throw new ArgumentNullException("outStr"); } _outStr = outStr; if (length > 0xFFFFFFFFL) { WriteHeader(tag, false, true, 0); _partialBufferLength = 1 << BufferSizePower; _partialBuffer = new byte[_partialBufferLength]; _partialPower = BufferSizePower; _partialOffset = 0; } else { WriteHeader(tag, oldFormat, false, length); } } /// <summary>Create a new style partial input stream buffered into chunks.</summary> /// <param name="outStr">Output stream to write to.</param> /// <param name="tag">Packet tag.</param> /// <param name="length">Size of chunks making up the packet.</param> public BcpgOutputStream(Stream outStr, PacketTag tag, long length) { if (outStr == null) { throw new ArgumentNullException("outStr"); } _outStr = outStr; WriteHeader(tag, false, false, length); } /// <summary>Create a new style partial input stream buffered into chunks.</summary> /// <param name="outStr">Output stream to write to.</param> /// <param name="tag">Packet tag.</param> /// <param name="buffer">Buffer to use for collecting chunks.</param> public BcpgOutputStream(Stream outStr, PacketTag tag, byte[] buffer) { if (outStr == null) { throw new ArgumentNullException("outStr"); } _outStr = outStr; WriteHeader(tag, false, true, 0); _partialBuffer = buffer; var length = (uint) _partialBuffer.Length; for (_partialPower = 0; length != 1; _partialPower++) { length >>= 1; } if (_partialPower > 30) { throw new IOException("Buffer cannot be greater than 2^30 in length."); } _partialBufferLength = 1 << _partialPower; _partialOffset = 0; } internal static BcpgOutputStream Wrap(Stream outStr) { if (outStr is BcpgOutputStream) { return (BcpgOutputStream) outStr; } return new BcpgOutputStream(outStr); } private void WriteNewPacketLength(long bodyLen) { if (bodyLen < 192) { _outStr.WriteByte((byte) bodyLen); } else if (bodyLen <= 8383) { bodyLen -= 192; _outStr.WriteByte((byte) (((bodyLen >> 8) & 0xff) + 192)); _outStr.WriteByte((byte) bodyLen); } else { _outStr.WriteByte(0xff); _outStr.WriteByte((byte) (bodyLen >> 24)); _outStr.WriteByte((byte) (bodyLen >> 16)); _outStr.WriteByte((byte) (bodyLen >> 8)); _outStr.WriteByte((byte) bodyLen); } } private void WriteHeader(PacketTag tag, bool oldPackets, bool partial, long bodyLen) { int hdr = 0x80; if (_partialBuffer != null) { PartialFlush(true); _partialBuffer = null; } if (oldPackets) { hdr |= ((int) tag) << 2; if (partial) { WriteByte((byte) (hdr | 0x03)); } else { if (bodyLen <= 0xff) { WriteByte((byte) hdr); WriteByte((byte) bodyLen); } else if (bodyLen <= 0xffff) { WriteByte((byte) (hdr | 0x01)); WriteByte((byte) (bodyLen >> 8)); WriteByte((byte) (bodyLen)); } else { WriteByte((byte) (hdr | 0x02)); WriteByte((byte) (bodyLen >> 24)); WriteByte((byte) (bodyLen >> 16)); WriteByte((byte) (bodyLen >> 8)); WriteByte((byte) bodyLen); } } } else { hdr |= 0x40 | (int) tag; WriteByte((byte) hdr); if (partial) { _partialOffset = 0; } else { WriteNewPacketLength(bodyLen); } } } private void PartialFlush(bool isLast) { if (isLast) { WriteNewPacketLength(_partialOffset); _outStr.Write(_partialBuffer, 0, _partialOffset); } else { _outStr.WriteByte((byte) (0xE0 | _partialPower)); _outStr.Write(_partialBuffer, 0, _partialBufferLength); } _partialOffset = 0; } private void WritePartial(byte b) { if (_partialOffset == _partialBufferLength) { PartialFlush(false); } _partialBuffer[_partialOffset++] = b; } private void WritePartial(byte[] buffer, int off, int len) { if (_partialOffset == _partialBufferLength) { PartialFlush(false); } if (len <= (_partialBufferLength - _partialOffset)) { Array.Copy(buffer, off, _partialBuffer, _partialOffset, len); _partialOffset += len; } else { int diff = _partialBufferLength - _partialOffset; Array.Copy(buffer, off, _partialBuffer, _partialOffset, diff); off += diff; len -= diff; PartialFlush(false); while (len > _partialBufferLength) { Array.Copy(buffer, off, _partialBuffer, 0, _partialBufferLength); off += _partialBufferLength; len -= _partialBufferLength; PartialFlush(false); } Array.Copy(buffer, off, _partialBuffer, 0, len); _partialOffset += len; } } public override void WriteByte(byte value) { if (_partialBuffer != null) { WritePartial(value); } else { _outStr.WriteByte(value); } } public override void Write(byte[] buffer, int offset, int count) { if (_partialBuffer != null) { WritePartial(buffer, offset, count); } else { _outStr.Write(buffer, offset, count); } } // Additional helper methods to write primitive types internal virtual void WriteShort(short n) { Write((byte) (n >> 8), (byte) n); } internal virtual void WriteInt(int n) { Write((byte) (n >> 24), (byte) (n >> 16), (byte) (n >> 8), (byte) n); } internal virtual void WriteLong(long n) { Write((byte) (n >> 56), (byte) (n >> 48), (byte) (n >> 40), (byte) (n >> 32), (byte) (n >> 24), (byte) (n >> 16), (byte) (n >> 8), (byte) n); } public void WritePacket(ContainedPacket p) { p.Encode(this); } internal void WritePacket(PacketTag tag, byte[] body, bool oldFormat) { WriteHeader(tag, oldFormat, false, body.Length); Write(body); } public void WriteObject(BcpgObject bcpgObject) { bcpgObject.Encode(this); } public void WriteObjects(params BcpgObject[] v) { foreach (BcpgObject o in v) { o.Encode(this); } } /// <summary>Flush the underlying stream.</summary> public override void Flush() { _outStr.Flush(); } /// <summary>Finish writing out the current packet without closing the underlying stream.</summary> public void Finish() { if (_partialBuffer != null) { PartialFlush(true); _partialBuffer = null; } } protected override void Dispose(bool disposing) { try { if (!disposing) { return; } Finish(); _outStr.Flush(); _outStr.Dispose(); } finally { base.Dispose(disposing); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.SymReaderInterop; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class EvaluationContext : EvaluationContextBase { private const string TypeName = "<>x"; private const string MethodName = "<>m0"; internal const bool IsLocalScopeEndInclusive = false; internal readonly ImmutableArray<MetadataBlock> MetadataBlocks; internal readonly MethodScope MethodScope; internal readonly CSharpCompilation Compilation; private readonly MetadataDecoder _metadataDecoder; private readonly MethodSymbol _currentFrame; private readonly ImmutableArray<LocalSymbol> _locals; private readonly ImmutableSortedSet<int> _inScopeHoistedLocalIndices; private readonly MethodDebugInfo _methodDebugInfo; private EvaluationContext( ImmutableArray<MetadataBlock> metadataBlocks, MethodScope methodScope, CSharpCompilation compilation, MetadataDecoder metadataDecoder, MethodSymbol currentFrame, ImmutableArray<LocalSymbol> locals, ImmutableSortedSet<int> inScopeHoistedLocalIndices, MethodDebugInfo methodDebugInfo) { Debug.Assert(inScopeHoistedLocalIndices != null); this.MetadataBlocks = metadataBlocks; this.MethodScope = methodScope; this.Compilation = compilation; _metadataDecoder = metadataDecoder; _currentFrame = currentFrame; _locals = locals; _inScopeHoistedLocalIndices = inScopeHoistedLocalIndices; _methodDebugInfo = methodDebugInfo; } /// <summary> /// Create a context for evaluating expressions at a type scope. /// </summary> /// <param name="previous">Previous context, if any, for possible re-use.</param> /// <param name="metadataBlocks">Module metadata</param> /// <param name="moduleVersionId">Module containing type</param> /// <param name="typeToken">Type metadata token</param> /// <returns>Evaluation context</returns> /// <remarks> /// No locals since locals are associated with methods, not types. /// </remarks> internal static EvaluationContext CreateTypeContext( CSharpMetadataContext previous, ImmutableArray<MetadataBlock> metadataBlocks, Guid moduleVersionId, int typeToken) { Debug.Assert(MetadataTokens.Handle(typeToken).Kind == HandleKind.TypeDefinition); // Re-use the previous compilation if possible. var compilation = metadataBlocks.HaveNotChanged(previous) ? previous.Compilation : metadataBlocks.ToCompilation(); MetadataDecoder metadataDecoder; var currentType = compilation.GetType(moduleVersionId, typeToken, out metadataDecoder); Debug.Assert((object)currentType != null); Debug.Assert(metadataDecoder != null); var currentFrame = new SynthesizedContextMethodSymbol(currentType); return new EvaluationContext( metadataBlocks, null, compilation, metadataDecoder, currentFrame, default(ImmutableArray<LocalSymbol>), ImmutableSortedSet<int>.Empty, default(MethodDebugInfo)); } /// <summary> /// Create a context for evaluating expressions within a method scope. /// </summary> /// <param name="previous">Previous context, if any, for possible re-use.</param> /// <param name="metadataBlocks">Module metadata</param> /// <param name="symReader"><see cref="ISymUnmanagedReader"/> for PDB associated with <paramref name="moduleVersionId"/></param> /// <param name="moduleVersionId">Module containing method</param> /// <param name="methodToken">Method metadata token</param> /// <param name="methodVersion">Method version.</param> /// <param name="ilOffset">IL offset of instruction pointer in method</param> /// <param name="localSignatureToken">Method local signature token</param> /// <returns>Evaluation context</returns> internal static EvaluationContext CreateMethodContext( CSharpMetadataContext previous, ImmutableArray<MetadataBlock> metadataBlocks, object symReader, Guid moduleVersionId, int methodToken, int methodVersion, int ilOffset, int localSignatureToken) { Debug.Assert(MetadataTokens.Handle(methodToken).Kind == HandleKind.MethodDefinition); var typedSymReader = (ISymUnmanagedReader)symReader; var scopes = ArrayBuilder<ISymUnmanagedScope>.GetInstance(); typedSymReader.GetScopes(methodToken, methodVersion, ilOffset, IsLocalScopeEndInclusive, scopes); var scope = scopes.GetMethodScope(methodToken, methodVersion); // Re-use the previous compilation if possible. CSharpCompilation compilation; if (metadataBlocks.HaveNotChanged(previous)) { // Re-use entire context if method scope has not changed. var previousContext = previous.EvaluationContext; if ((scope != null) && (previousContext != null) && scope.Equals(previousContext.MethodScope)) { return previousContext; } compilation = previous.Compilation; } else { compilation = metadataBlocks.ToCompilation(); } var localNames = scopes.GetLocalNames(); var dynamicLocalMap = ImmutableDictionary<int, ImmutableArray<bool>>.Empty; var dynamicLocalConstantMap = ImmutableDictionary<string, ImmutableArray<bool>>.Empty; var inScopeHoistedLocalIndices = ImmutableSortedSet<int>.Empty; var methodDebugInfo = default(MethodDebugInfo); if (typedSymReader != null) { try { var cdi = typedSymReader.GetCustomDebugInfoBytes(methodToken, methodVersion); if (cdi != null) { CustomDebugInfoReader.GetCSharpDynamicLocalInfo( cdi, methodToken, methodVersion, localNames.FirstOrDefault(), out dynamicLocalMap, out dynamicLocalConstantMap); inScopeHoistedLocalIndices = CustomDebugInfoReader.GetCSharpInScopeHoistedLocalIndices( cdi, methodToken, methodVersion, ilOffset); } // TODO (acasey): switch on the type of typedSymReader and call the appropriate helper. (GH #702) methodDebugInfo = typedSymReader.GetMethodDebugInfo(methodToken, methodVersion); } catch (InvalidOperationException) { // bad CDI, ignore } } var methodHandle = (MethodDefinitionHandle)MetadataTokens.Handle(methodToken); var currentFrame = compilation.GetMethod(moduleVersionId, methodHandle); Debug.Assert((object)currentFrame != null); var metadataDecoder = new MetadataDecoder((PEModuleSymbol)currentFrame.ContainingModule, currentFrame); var localInfo = metadataDecoder.GetLocalInfo(localSignatureToken); var localBuilder = ArrayBuilder<LocalSymbol>.GetInstance(); var sourceAssembly = compilation.SourceAssembly; GetLocals(localBuilder, currentFrame, localNames, localInfo, dynamicLocalMap, sourceAssembly); GetConstants(localBuilder, currentFrame, scopes.GetConstantSignatures(), metadataDecoder, dynamicLocalConstantMap, sourceAssembly); scopes.Free(); var locals = localBuilder.ToImmutableAndFree(); return new EvaluationContext( metadataBlocks, scope, compilation, metadataDecoder, currentFrame, locals, inScopeHoistedLocalIndices, methodDebugInfo); } internal CompilationContext CreateCompilationContext(CSharpSyntaxNode syntax) { return new CompilationContext( this.Compilation, _metadataDecoder, _currentFrame, _locals, _inScopeHoistedLocalIndices, _methodDebugInfo, syntax); } internal override CompileResult CompileExpression( InspectionContext inspectionContext, string expr, DkmEvaluationFlags compilationFlags, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, System.Globalization.CultureInfo preferredUICulture, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData) { resultProperties = default(ResultProperties); var diagnostics = DiagnosticBag.GetInstance(); try { ReadOnlyCollection<string> formatSpecifiers; var syntax = Parse(expr, (compilationFlags & DkmEvaluationFlags.TreatAsExpression) != 0, diagnostics, out formatSpecifiers); if (syntax == null) { error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities); return default(CompileResult); } var context = this.CreateCompilationContext(syntax); ResultProperties properties; var moduleBuilder = context.CompileExpression(inspectionContext, TypeName, MethodName, testData, diagnostics, out properties); if (moduleBuilder == null) { error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities); return default(CompileResult); } using (var stream = new MemoryStream()) { Cci.PeWriter.WritePeToStream( new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics), context.MessageProvider, stream, nativePdbWriterOpt: null, allowMissingMethodBodies: false, deterministic: false, cancellationToken: default(CancellationToken)); if (diagnostics.HasAnyErrors()) { error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities); return default(CompileResult); } resultProperties = properties; error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; return new CompileResult( stream.ToArray(), typeName: TypeName, methodName: MethodName, formatSpecifiers: formatSpecifiers); } } finally { diagnostics.Free(); } } private static CSharpSyntaxNode Parse( string expr, bool treatAsExpression, DiagnosticBag diagnostics, out ReadOnlyCollection<string> formatSpecifiers) { if (treatAsExpression) { return expr.ParseExpression(diagnostics, allowFormatSpecifiers: true, formatSpecifiers: out formatSpecifiers); } else { // Try to parse as an expression. If that fails, parse as a statement. var exprDiagnostics = DiagnosticBag.GetInstance(); ReadOnlyCollection<string> exprFormatSpecifiers; CSharpSyntaxNode syntax = expr.ParseExpression(exprDiagnostics, allowFormatSpecifiers: true, formatSpecifiers: out exprFormatSpecifiers); Debug.Assert((syntax == null) || !exprDiagnostics.HasAnyErrors()); exprDiagnostics.Free(); if (syntax != null) { Debug.Assert(!diagnostics.HasAnyErrors()); formatSpecifiers = exprFormatSpecifiers; return syntax; } formatSpecifiers = null; syntax = expr.ParseStatement(diagnostics); if ((syntax != null) && (syntax.Kind() != SyntaxKind.LocalDeclarationStatement)) { diagnostics.Add(ErrorCode.ERR_ExpressionOrDeclarationExpected, Location.None); return null; } return syntax; } } internal override CompileResult CompileAssignment( InspectionContext inspectionContext, string target, string expr, DiagnosticFormatter formatter, out ResultProperties resultProperties, out string error, out ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, System.Globalization.CultureInfo preferredUICulture, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData) { var diagnostics = DiagnosticBag.GetInstance(); try { var assignment = target.ParseAssignment(expr, diagnostics); if (assignment == null) { error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities); resultProperties = default(ResultProperties); return default(CompileResult); } var context = this.CreateCompilationContext(assignment); ResultProperties properties; var moduleBuilder = context.CompileAssignment(inspectionContext, TypeName, MethodName, testData, diagnostics, out properties); if (moduleBuilder == null) { error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities); resultProperties = default(ResultProperties); return default(CompileResult); } using (var stream = new MemoryStream()) { Cci.PeWriter.WritePeToStream( new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics), context.MessageProvider, stream, nativePdbWriterOpt: null, allowMissingMethodBodies: false, deterministic: false, cancellationToken: default(CancellationToken)); if (diagnostics.HasAnyErrors()) { error = GetErrorMessageAndMissingAssemblyIdentities(diagnostics, formatter, preferredUICulture, out missingAssemblyIdentities); resultProperties = default(ResultProperties); return default(CompileResult); } resultProperties = properties; error = null; missingAssemblyIdentities = ImmutableArray<AssemblyIdentity>.Empty; return new CompileResult( stream.ToArray(), typeName: TypeName, methodName: MethodName, formatSpecifiers: null); } } finally { diagnostics.Free(); } } private static readonly ReadOnlyCollection<byte> s_emptyBytes = new ReadOnlyCollection<byte>(new byte[0]); internal override ReadOnlyCollection<byte> CompileGetLocals( ArrayBuilder<LocalAndMethod> locals, bool argumentsOnly, out string typeName, Microsoft.CodeAnalysis.CodeGen.CompilationTestData testData = null) { var diagnostics = DiagnosticBag.GetInstance(); var context = this.CreateCompilationContext(null); var moduleBuilder = context.CompileGetLocals(TypeName, locals, argumentsOnly, testData, diagnostics); ReadOnlyCollection<byte> assembly = null; if ((moduleBuilder != null) && (locals.Count > 0)) { using (var stream = new MemoryStream()) { Cci.PeWriter.WritePeToStream( new EmitContext((Cci.IModule)moduleBuilder, null, diagnostics), context.MessageProvider, stream, nativePdbWriterOpt: null, allowMissingMethodBodies: false, deterministic: false, cancellationToken: default(CancellationToken)); if (!diagnostics.HasAnyErrors()) { assembly = new ReadOnlyCollection<byte>(stream.ToArray()); } } } diagnostics.Free(); if (assembly == null) { locals.Clear(); assembly = s_emptyBytes; } typeName = TypeName; return assembly; } /// <summary> /// Returns symbols for the locals emitted in the original method, /// based on the local signatures from the IL and the names and /// slots from the PDB. The actual locals are needed to ensure the /// local slots in the generated method match the original. /// </summary> private static void GetLocals( ArrayBuilder<LocalSymbol> builder, MethodSymbol method, ImmutableArray<string> names, ImmutableArray<LocalInfo<TypeSymbol>> localInfo, ImmutableDictionary<int, ImmutableArray<bool>> dynamicLocalMap, SourceAssemblySymbol containingAssembly) { if (localInfo.Length == 0) { // When debugging a .dmp without a heap, localInfo will be empty although // names may be non-empty if there is a PDB. Since there's no type info, the // locals are dropped. Note this means the local signature of any generated // method will not match the original signature, so new locals will overlap // original locals. That is ok since there is no live process for the debugger // to update (any modified values exist in the debugger only). return; } Debug.Assert(localInfo.Length >= names.Length); for (int i = 0; i < localInfo.Length; i++) { var name = (i < names.Length) ? names[i] : null; var info = localInfo[i]; var isPinned = info.IsPinned; LocalDeclarationKind kind; RefKind refKind; TypeSymbol type; if (info.IsByRef && isPinned) { kind = LocalDeclarationKind.FixedVariable; refKind = RefKind.None; type = new PointerTypeSymbol(info.Type); } else { kind = LocalDeclarationKind.RegularVariable; refKind = info.IsByRef ? RefKind.Ref : RefKind.None; type = info.Type; } ImmutableArray<bool> dynamicFlags; if (dynamicLocalMap.TryGetValue(i, out dynamicFlags)) { type = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags( type, containingAssembly, refKind, dynamicFlags); } // Custom modifiers can be dropped since binding ignores custom // modifiers from locals and since we only need to preserve // the type of the original local in the generated method. builder.Add(new EELocalSymbol(method, EELocalSymbol.NoLocations, name, i, kind, type, refKind, isPinned, isCompilerGenerated: false, canScheduleToStack: false)); } } private static void GetConstants( ArrayBuilder<LocalSymbol> builder, MethodSymbol method, ImmutableArray<NamedLocalConstant> constants, MetadataDecoder metadataDecoder, ImmutableDictionary<string, ImmutableArray<bool>> dynamicLocalConstantMap, SourceAssemblySymbol containingAssembly) { foreach (var constant in constants) { var info = metadataDecoder.GetLocalInfo(constant.Signature); Debug.Assert(!info.IsByRef); Debug.Assert(!info.IsPinned); var type = info.Type; ImmutableArray<bool> dynamicFlags; if (dynamicLocalConstantMap.TryGetValue(constant.Name, out dynamicFlags)) { type = DynamicTypeDecoder.TransformTypeWithoutCustomModifierFlags( type, containingAssembly, RefKind.None, dynamicFlags); } var constantValue = ReinterpretConstantValue(constant.Value, type.SpecialType); builder.Add(new EELocalConstantSymbol(method, constant.Name, type, constantValue)); } } internal override ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentities(Diagnostic diagnostic) { return GetMissingAssemblyIdentitiesHelper((ErrorCode)diagnostic.Code, diagnostic.Arguments); } /// <remarks> /// Internal for testing. /// </remarks> internal static ImmutableArray<AssemblyIdentity> GetMissingAssemblyIdentitiesHelper(ErrorCode code, IReadOnlyList<object> arguments) { switch (code) { case ErrorCode.ERR_NoTypeDef: case ErrorCode.ERR_GlobalSingleTypeNameNotFoundFwd: case ErrorCode.ERR_DottedTypeNameNotFoundInNSFwd: case ErrorCode.ERR_SingleTypeNameNotFoundFwd: case ErrorCode.ERR_NameNotInContextPossibleMissingReference: // Probably can't happen. foreach (var argument in arguments) { var identity = (argument as AssemblyIdentity) ?? (argument as AssemblySymbol)?.Identity; if (identity != null && !identity.Equals(MissingCorLibrarySymbol.Instance.Identity)) { return ImmutableArray.Create(identity); } } break; case ErrorCode.ERR_DottedTypeNameNotFoundInNS: if (arguments.Count == 2) { var namespaceName = arguments[0] as string; var containingNamespace = arguments[1] as NamespaceSymbol; if (namespaceName != null && (object)containingNamespace != null && containingNamespace.ConstituentNamespaces.Any(n => n.ContainingAssembly.Identity.IsWindowsAssemblyIdentity())) { // This is just a heuristic, but it has the advantage of being portable, particularly // across different versions of (desktop) windows. var identity = new AssemblyIdentity($"{containingNamespace.ToDisplayString()}.{namespaceName}", contentType: System.Reflection.AssemblyContentType.WindowsRuntime); return ImmutableArray.Create(identity); } } break; case ErrorCode.ERR_DynamicAttributeMissing: case ErrorCode.ERR_DynamicRequiredTypesMissing: // MSDN says these might come from System.Dynamic.Runtime case ErrorCode.ERR_QueryNoProviderStandard: case ErrorCode.ERR_ExtensionAttrNotFound: // Probably can't happen. return ImmutableArray.Create(SystemCoreIdentity); case ErrorCode.ERR_BadAwaitArg_NeedSystem: Debug.Assert(false, "Roslyn no longer produces ERR_BadAwaitArg_NeedSystem"); break; } return default(ImmutableArray<AssemblyIdentity>); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Management.Automation; using System.Management.Automation.Remoting; using System.Threading; namespace Microsoft.PowerShell.Commands { /// <summary> /// This cmdlet resumes the jobs that are Job2. Errors are added for each Job that is not Job2. /// </summary> #if !CORECLR [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] [Cmdlet(VerbsLifecycle.Resume, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210611")] #endif [OutputType(typeof(Job))] public class ResumeJobCommand : JobCmdletBase, IDisposable { #region Parameters /// <summary> /// Specifies the Jobs objects which need to be /// suspended. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = JobParameterSet)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Job[] Job { get { return _jobs; } set { _jobs = value; } } private Job[] _jobs; /// <summary> /// </summary> public override string[] Command { get { return null; } } /// <summary> /// Specifies whether to delay returning from the cmdlet until all jobs reach a running state. /// This could take significant time due to workflow throttling. /// </summary> [Parameter(ParameterSetName = ParameterAttribute.AllParameterSets)] public SwitchParameter Wait { get; set; } #endregion Parameters #region Overrides /// <summary> /// Resume the Job. /// </summary> protected override void ProcessRecord() { // List of jobs to resume List<Job> jobsToResume = null; switch (ParameterSetName) { case NameParameterSet: { jobsToResume = FindJobsMatchingByName(true, false, true, false); } break; case InstanceIdParameterSet: { jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false); } break; case SessionIdParameterSet: { jobsToResume = FindJobsMatchingBySessionId(true, false, true, false); } break; case StateParameterSet: { jobsToResume = FindJobsMatchingByState(false); } break; case FilterParameterSet: { jobsToResume = FindJobsMatchingByFilter(false); } break; default: { jobsToResume = CopyJobsToList(_jobs, false, false); } break; } _allJobsToResume.AddRange(jobsToResume); // Blue: 151804 When resuming a single suspended workflow job, Resume-job cmdlet doesn't wait for the job to be in running state // Setting Wait to true so that this cmdlet will wait for the running job state. if (_allJobsToResume.Count == 1) Wait = true; foreach (Job job in jobsToResume) { var job2 = job as Job2; // If the job is not Job2, the resume operation is not supported. if (job2 == null) { WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobResumeNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job)); continue; } string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id); if (ShouldProcess(targetString, VerbsLifecycle.Resume)) { _cleanUpActions.Add(job2, HandleResumeJobCompleted); job2.ResumeJobCompleted += HandleResumeJobCompleted; lock (_syncObject) { if (!_pendingJobs.Contains(job2.InstanceId)) { _pendingJobs.Add(job2.InstanceId); } } job2.ResumeJobAsync(); } } } private bool _warnInvalidState = false; private readonly HashSet<Guid> _pendingJobs = new HashSet<Guid>(); private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); private readonly Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>> _cleanUpActions = new Dictionary<Job2, EventHandler<AsyncCompletedEventArgs>>(); private readonly List<ErrorRecord> _errorsToWrite = new List<ErrorRecord>(); private readonly List<Job> _allJobsToResume = new List<Job>(); private readonly object _syncObject = new object(); private bool _needToCheckForWaitingJobs; private void HandleResumeJobCompleted(object sender, AsyncCompletedEventArgs eventArgs) { Job job = sender as Job; if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException) { _warnInvalidState = true; } var parentJob = job as ContainerParentJob; if (parentJob != null && parentJob.ExecutionError.Count > 0) { foreach ( var e in parentJob.ExecutionError.Where(e => e.FullyQualifiedErrorId == "ContainerParentJobResumeAsyncError") ) { if (e.Exception is InvalidJobStateException) { // if any errors were invalid job state exceptions, warn the user. // This is to support Get-Job | Resume-Job scenarios when many jobs // are Completed, etc. _warnInvalidState = true; } else { _errorsToWrite.Add(e); } } parentJob.ExecutionError.Clear(); } bool releaseWait = false; lock (_syncObject) { if (_pendingJobs.Contains(job.InstanceId)) { _pendingJobs.Remove(job.InstanceId); } if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) releaseWait = true; } // end processing has been called // set waithandle if this is the last one if (releaseWait) _waitForJobs.Set(); } /// <summary> /// End Processing. /// </summary> protected override void EndProcessing() { bool jobsPending = false; lock (_syncObject) { _needToCheckForWaitingJobs = true; if (_pendingJobs.Count > 0) jobsPending = true; } if (Wait && jobsPending) _waitForJobs.WaitOne(); if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.ResumeJobInvalidJobState); foreach (var e in _errorsToWrite) WriteError(e); foreach (var j in _allJobsToResume) WriteObject(j); base.EndProcessing(); } /// <summary> /// </summary> protected override void StopProcessing() { _waitForJobs.Set(); } #endregion Overrides #region Dispose /// <summary> /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// </summary> /// <param name="disposing"></param> protected void Dispose(bool disposing) { if (!disposing) return; foreach (var pair in _cleanUpActions) { pair.Key.ResumeJobCompleted -= pair.Value; } _waitForJobs.Dispose(); } #endregion Dispose } }
// --------------------------------------------------------------------------- // <copyright file="ConversationIndexedItemView.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the ConversationIndexedItemView class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Text; /// <summary> /// Represents the view settings in a folder search operation. /// </summary> public sealed class ConversationIndexedItemView : PagedView { private OrderByCollection orderBy = new OrderByCollection(); private ConversationQueryTraversal? traversal; private ViewFilter? viewFilter; /// <summary> /// Gets the type of service object this view applies to. /// </summary> /// <returns>A ServiceObjectType value.</returns> internal override ServiceObjectType GetServiceObjectType() { return ServiceObjectType.Conversation; } /// <summary> /// Writes the attributes to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteAttributesToXml(EwsServiceXmlWriter writer) { if (this.Traversal.HasValue) { writer.WriteAttributeValue(XmlAttributeNames.Traversal, this.Traversal); } if (this.ViewFilter.HasValue) { writer.WriteAttributeValue(XmlAttributeNames.ViewFilter, this.ViewFilter); } } /// <summary> /// Gets the name of the view XML element. /// </summary> /// <returns>XML element name.</returns> internal override string GetViewXmlElementName() { return XmlElementNames.IndexedPageItemView; } /// <summary> /// Gets the name of the view json type. /// </summary> /// <returns></returns> internal override string GetViewJsonTypeName() { return "IndexedPageView"; } /// <summary> /// Validates this view. /// </summary> /// <param name="request">The request using this view.</param> internal override void InternalValidate(ServiceRequestBase request) { base.InternalValidate(request); if (this.Traversal.HasValue) { EwsUtilities.ValidateEnumVersionValue(this.traversal, request.Service.RequestedServerVersion); } if (this.ViewFilter.HasValue) { EwsUtilities.ValidateEnumVersionValue(this.viewFilter, request.Service.RequestedServerVersion); } } /// <summary> /// Internals the write search settings to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="groupBy">The group by.</param> internal override void InternalWriteSearchSettingsToXml(EwsServiceXmlWriter writer, Grouping groupBy) { base.InternalWriteSearchSettingsToXml(writer, groupBy); } /// <summary> /// Writes OrderBy property to XML. /// </summary> /// <param name="writer">The writer</param> internal override void WriteOrderByToXml(EwsServiceXmlWriter writer) { this.orderBy.WriteToXml(writer, XmlElementNames.SortOrder); } /// <summary> /// Adds the json properties. /// </summary> /// <param name="jsonRequest">The json request.</param> /// <param name="service">The service.</param> internal override void AddJsonProperties(JsonObject jsonRequest, ExchangeService service) { jsonRequest.Add(XmlElementNames.SortOrder, ((IJsonSerializable)this.orderBy).ToJson(service)); if (this.Traversal.HasValue) { jsonRequest.Add(XmlAttributeNames.Traversal, this.Traversal); } if (this.ViewFilter.HasValue) { jsonRequest.Add(XmlAttributeNames.ViewFilter, this.ViewFilter); } } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="groupBy">The group by clause.</param> internal override void WriteToXml(EwsServiceXmlWriter writer, Grouping groupBy) { writer.WriteStartElement(XmlNamespace.Messages, this.GetViewXmlElementName()); this.InternalWriteViewToXml(writer); writer.WriteEndElement(); // this.GetViewXmlElementName() } /// <summary> /// Initializes a new instance of the <see cref="ItemView"/> class. /// </summary> /// <param name="pageSize">The maximum number of elements the search operation should return.</param> public ConversationIndexedItemView(int pageSize) : base(pageSize) { } /// <summary> /// Initializes a new instance of the <see cref="ItemView"/> class. /// </summary> /// <param name="pageSize">The maximum number of elements the search operation should return.</param> /// <param name="offset">The offset of the view from the base point.</param> public ConversationIndexedItemView(int pageSize, int offset) : base(pageSize, offset) { this.Offset = offset; } /// <summary> /// Initializes a new instance of the <see cref="ItemView"/> class. /// </summary> /// <param name="pageSize">The maximum number of elements the search operation should return.</param> /// <param name="offset">The offset of the view from the base point.</param> /// <param name="offsetBasePoint">The base point of the offset.</param> public ConversationIndexedItemView( int pageSize, int offset, OffsetBasePoint offsetBasePoint) : base(pageSize, offset, offsetBasePoint) { } /// <summary> /// Gets the properties against which the returned items should be ordered. /// </summary> public OrderByCollection OrderBy { get { return this.orderBy; } } /// <summary> /// Gets or sets the conversation query traversal mode. /// </summary> public ConversationQueryTraversal? Traversal { get { return this.traversal; } set { this.traversal = value; } } /// <summary> /// Gets or sets the view filter. /// </summary> public ViewFilter? ViewFilter { get { return this.viewFilter; } set { this.viewFilter = value; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Radiostr.Web.Areas.HelpPage.ModelDescriptions; using Radiostr.Web.Areas.HelpPage.Models; using Radiostr.Web.Areas.HelpPage.SampleGeneration; namespace Radiostr.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using Newtonsoft.Json; using QuantConnect.Interfaces; using QuantConnect.Orders.Serialization; using QuantConnect.Orders.TimeInForces; using QuantConnect.Securities; using QuantConnect.Securities.Positions; using static QuantConnect.StringExtensions; namespace QuantConnect.Orders { /// <summary> /// Order struct for placing new trade /// </summary> public abstract class Order { private volatile int _incrementalId; private decimal _quantity; private decimal _price; /// <summary> /// Order ID. /// </summary> public int Id { get; internal set; } /// <summary> /// Order id to process before processing this order. /// </summary> public int ContingentId { get; internal set; } /// <summary> /// Brokerage Id for this order for when the brokerage splits orders into multiple pieces /// </summary> public List<string> BrokerId { get; internal set; } /// <summary> /// Symbol of the Asset /// </summary> public Symbol Symbol { get; internal set; } /// <summary> /// Price of the Order. /// </summary> public decimal Price { get { return _price; } internal set { _price = value.Normalize(); } } /// <summary> /// Currency for the order price /// </summary> public string PriceCurrency { get; internal set; } /// <summary> /// Gets the utc time the order was created. /// </summary> public DateTime Time { get; internal set; } /// <summary> /// Gets the utc time this order was created. Alias for <see cref="Time"/> /// </summary> public DateTime CreatedTime => Time; /// <summary> /// Gets the utc time the last fill was received, or null if no fills have been received /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public DateTime? LastFillTime { get; internal set; } /// <summary> /// Gets the utc time this order was last updated, or null if the order has not been updated. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public DateTime? LastUpdateTime { get; internal set; } /// <summary> /// Gets the utc time this order was canceled, or null if the order was not canceled. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public DateTime? CanceledTime { get; internal set; } /// <summary> /// Number of shares to execute. /// </summary> public decimal Quantity { get { return _quantity; } internal set { _quantity = value.Normalize(); } } /// <summary> /// Order Type /// </summary> public abstract OrderType Type { get; } /// <summary> /// Status of the Order /// </summary> public OrderStatus Status { get; set; } /// <summary> /// Order Time In Force /// </summary> [JsonIgnore] public TimeInForce TimeInForce => Properties.TimeInForce; /// <summary> /// Tag the order with some custom data /// </summary> [DefaultValue(""), JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Tag { get; internal set; } /// <summary> /// Additional properties of the order /// </summary> public IOrderProperties Properties { get; private set; } /// <summary> /// The symbol's security type /// </summary> public SecurityType SecurityType => Symbol.ID.SecurityType; /// <summary> /// Order Direction Property based off Quantity. /// </summary> public OrderDirection Direction { get { if (Quantity > 0) { return OrderDirection.Buy; } if (Quantity < 0) { return OrderDirection.Sell; } return OrderDirection.Hold; } } /// <summary> /// Get the absolute quantity for this order /// </summary> [JsonIgnore] public decimal AbsoluteQuantity => Math.Abs(Quantity); /// <summary> /// Gets the executed value of this order. If the order has not yet filled, /// then this will return zero. /// </summary> public decimal Value => Quantity * Price; /// <summary> /// Gets the price data at the time the order was submitted /// </summary> public OrderSubmissionData OrderSubmissionData { get; internal set; } /// <summary> /// Returns true if the order is a marketable order. /// </summary> public bool IsMarketable { get { if (Type == OrderType.Limit) { // check if marketable limit order using bid/ask prices var limitOrder = (LimitOrder)this; return OrderSubmissionData != null && (Direction == OrderDirection.Buy && limitOrder.LimitPrice >= OrderSubmissionData.AskPrice || Direction == OrderDirection.Sell && limitOrder.LimitPrice <= OrderSubmissionData.BidPrice); } return Type == OrderType.Market; } } /// <summary> /// Added a default constructor for JSON Deserialization: /// </summary> protected Order() { Time = new DateTime(); Price = 0; PriceCurrency = string.Empty; Quantity = 0; Symbol = Symbol.Empty; Status = OrderStatus.None; Tag = ""; BrokerId = new List<string>(); ContingentId = 0; Properties = new OrderProperties(); } /// <summary> /// New order constructor /// </summary> /// <param name="symbol">Symbol asset we're seeking to trade</param> /// <param name="quantity">Quantity of the asset we're seeking to trade</param> /// <param name="time">Time the order was placed</param> /// <param name="tag">User defined data tag for this order</param> /// <param name="properties">The order properties for this order</param> protected Order(Symbol symbol, decimal quantity, DateTime time, string tag = "", IOrderProperties properties = null) { Time = time; Price = 0; PriceCurrency = string.Empty; Quantity = quantity; Symbol = symbol; Status = OrderStatus.None; Tag = tag; BrokerId = new List<string>(); ContingentId = 0; Properties = properties ?? new OrderProperties(); } /// <summary> /// Creates an enumerable containing each position resulting from executing this order. /// </summary> /// <remarks> /// This is provided in anticipation of a new combo order type that will need to override this method, /// returning a position for each 'leg' of the order. /// </remarks> /// <returns>An enumerable of positions matching the results of executing this order</returns> public virtual IEnumerable<IPosition> CreatePositions(SecurityManager securities) { var security = securities[Symbol]; yield return new Position(security, Quantity); } /// <summary> /// Gets the value of this order at the given market price in units of the account currency /// NOTE: Some order types derive value from other parameters, such as limit prices /// </summary> /// <param name="security">The security matching this order's symbol</param> /// <returns>The value of this order given the current market price</returns> public decimal GetValue(Security security) { var value = GetValueImpl(security); return value*security.QuoteCurrency.ConversionRate*security.SymbolProperties.ContractMultiplier; } /// <summary> /// Gets the order value in units of the security's quote currency for a single unit. /// A single unit here is a single share of stock, or a single barrel of oil, or the /// cost of a single share in an option contract. /// </summary> /// <param name="security">The security matching this order's symbol</param> protected abstract decimal GetValueImpl(Security security); /// <summary> /// Gets a new unique incremental id for this order /// </summary> /// <returns>Returns a new id for this order</returns> internal int GetNewId() { return Interlocked.Increment(ref _incrementalId); } /// <summary> /// Modifies the state of this order to match the update request /// </summary> /// <param name="request">The request to update this order object</param> public virtual void ApplyUpdateOrderRequest(UpdateOrderRequest request) { if (request.OrderId != Id) { throw new ArgumentException("Attempted to apply updates to the incorrect order!"); } if (request.Quantity.HasValue) { Quantity = request.Quantity.Value; } if (request.Tag != null) { Tag = request.Tag; } } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A string that represents the current object. /// </returns> /// <filterpriority>2</filterpriority> public override string ToString() { var tag = string.IsNullOrEmpty(Tag) ? string.Empty : $": {Tag}"; return Invariant($"OrderId: {Id} (BrokerId: {string.Join(",", BrokerId)}) {Status} {Type} order for {Quantity} unit{(Quantity == 1 ? "" : "s")} of {Symbol}{tag}"); } /// <summary> /// Creates a deep-copy clone of this order /// </summary> /// <returns>A copy of this order</returns> public abstract Order Clone(); /// <summary> /// Copies base Order properties to the specified order /// </summary> /// <param name="order">The target of the copy</param> protected void CopyTo(Order order) { order.Id = Id; order.Time = Time; order.LastFillTime = LastFillTime; order.LastUpdateTime = LastUpdateTime; order.CanceledTime = CanceledTime; order.BrokerId = BrokerId.ToList(); order.ContingentId = ContingentId; order.Price = Price; order.PriceCurrency = PriceCurrency; order.Quantity = Quantity; order.Status = Status; order.Symbol = Symbol; order.Tag = Tag; order.Properties = Properties.Clone(); order.OrderSubmissionData = OrderSubmissionData?.Clone(); } /// <summary> /// Creates a new Order instance from a SerializedOrder instance /// </summary> /// <remarks>Used by the <see cref="SerializedOrderJsonConverter"/></remarks> public static Order FromSerialized(SerializedOrder serializedOrder) { var sid = SecurityIdentifier.Parse(serializedOrder.Symbol); var symbol = new Symbol(sid, sid.Symbol); TimeInForce timeInForce = null; var type = System.Type.GetType($"QuantConnect.Orders.TimeInForces.{serializedOrder.TimeInForceType}", throwOnError: false, ignoreCase: true); if (type != null) { timeInForce = (TimeInForce) Activator.CreateInstance(type, true); if (timeInForce is GoodTilDateTimeInForce) { var expiry = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.TimeInForceExpiry.Value); timeInForce = new GoodTilDateTimeInForce(expiry); } } var createdTime = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.CreatedTime); var order = CreateOrder(serializedOrder.OrderId, serializedOrder.Type, symbol, serializedOrder.Quantity, DateTime.SpecifyKind(createdTime, DateTimeKind.Utc), serializedOrder.Tag, new OrderProperties { TimeInForce = timeInForce }, serializedOrder.LimitPrice ?? 0, serializedOrder.StopPrice ?? 0, serializedOrder.TriggerPrice ?? 0); order.OrderSubmissionData = new OrderSubmissionData(serializedOrder.SubmissionBidPrice, serializedOrder.SubmissionAskPrice, serializedOrder.SubmissionLastPrice); order.BrokerId = serializedOrder.BrokerId; order.ContingentId = serializedOrder.ContingentId; order.Price = serializedOrder.Price; order.PriceCurrency = serializedOrder.PriceCurrency; order.Status = serializedOrder.Status; if (serializedOrder.LastFillTime.HasValue) { var time = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.LastFillTime.Value); order.LastFillTime = DateTime.SpecifyKind(time, DateTimeKind.Utc); } if (serializedOrder.LastUpdateTime.HasValue) { var time = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.LastUpdateTime.Value); order.LastUpdateTime = DateTime.SpecifyKind(time, DateTimeKind.Utc); } if (serializedOrder.CanceledTime.HasValue) { var time = QuantConnect.Time.UnixTimeStampToDateTime(serializedOrder.CanceledTime.Value); order.CanceledTime = DateTime.SpecifyKind(time, DateTimeKind.Utc); } return order; } /// <summary> /// Creates an <see cref="Order"/> to match the specified <paramref name="request"/> /// </summary> /// <param name="request">The <see cref="SubmitOrderRequest"/> to create an order for</param> /// <returns>The <see cref="Order"/> that matches the request</returns> public static Order CreateOrder(SubmitOrderRequest request) { return CreateOrder(request.OrderId, request.OrderType, request.Symbol, request.Quantity, request.Time, request.Tag, request.OrderProperties, request.LimitPrice, request.StopPrice, request.TriggerPrice); } private static Order CreateOrder(int orderId, OrderType type, Symbol symbol, decimal quantity, DateTime time, string tag, IOrderProperties properties, decimal limitPrice, decimal stopPrice, decimal triggerPrice) { Order order; switch (type) { case OrderType.Market: order = new MarketOrder(symbol, quantity, time, tag, properties); break; case OrderType.Limit: order = new LimitOrder(symbol, quantity, limitPrice, time, tag, properties); break; case OrderType.StopMarket: order = new StopMarketOrder(symbol, quantity, stopPrice, time, tag, properties); break; case OrderType.StopLimit: order = new StopLimitOrder(symbol, quantity, stopPrice, limitPrice, time, tag, properties); break; case OrderType.LimitIfTouched: order = new LimitIfTouchedOrder(symbol, quantity, triggerPrice, limitPrice, time, tag, properties); break; case OrderType.MarketOnOpen: order = new MarketOnOpenOrder(symbol, quantity, time, tag, properties); break; case OrderType.MarketOnClose: order = new MarketOnCloseOrder(symbol, quantity, time, tag, properties); break; case OrderType.OptionExercise: order = new OptionExerciseOrder(symbol, quantity, time, tag, properties); break; default: throw new ArgumentOutOfRangeException(); } order.Status = OrderStatus.New; order.Id = orderId; return order; } } }
// 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.Runtime.InteropServices; using System.Threading; using Xunit; namespace System.IO.Tests { public class CreatedTests : FileSystemWatcherTest { [Fact] public void FileSystemWatcher_Created_File() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var watcher = new FileSystemWatcher(testDirectory.Path)) { string fileName = Path.Combine(testDirectory.Path, GetTestFileName()); watcher.Filter = Path.GetFileName(fileName); AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created); watcher.EnableRaisingEvents = true; using (var file = new TempFile(fileName)) { ExpectEvent(eventOccurred, "created"); } } } [Fact] public void FileSystemWatcher_Created_File_ForceRestart() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var watcher = new FileSystemWatcher(testDirectory.Path)) { string fileName = Path.Combine(testDirectory.Path, GetTestFileName()); watcher.Filter = Path.GetFileName(fileName); AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created); watcher.EnableRaisingEvents = true; watcher.NotifyFilter = NotifyFilters.FileName; // change filter to force restart using (var file = new TempFile(fileName)) { ExpectEvent(eventOccurred, "created"); } } } [Fact] public void FileSystemWatcher_Created_Directory() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var watcher = new FileSystemWatcher(testDirectory.Path)) { string dirName = Path.Combine(testDirectory.Path, GetTestFileName()); watcher.Filter = Path.GetFileName(dirName); AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created); watcher.EnableRaisingEvents = true; using (var dir = new TempDirectory(dirName)) { ExpectEvent(eventOccurred, "created"); } } } [Fact] [ActiveIssue(2011, PlatformID.OSX)] public void FileSystemWatcher_Created_MoveDirectory() { // create two test directories using (var testDirectory = new TempDirectory(GetTestFilePath())) using (TempDirectory originalDir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (TempDirectory targetDir = new TempDirectory(originalDir.Path + "_target")) using (var watcher = new FileSystemWatcher(testDirectory.Path)) { string testFileName = GetTestFileName(); // watch the target dir watcher.Path = Path.GetFullPath(targetDir.Path); watcher.Filter = testFileName; AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created); string sourceFile = Path.Combine(originalDir.Path, testFileName); string targetFile = Path.Combine(targetDir.Path, testFileName); // create a test file in source File.WriteAllText(sourceFile, "test content"); watcher.EnableRaisingEvents = true; // move the test file from source to target directory File.Move(sourceFile, targetFile); ExpectEvent(eventOccurred, "created"); } } [Fact] public void FileSystemWatcher_Created_Negative() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher()) { // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*.*"; AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created); // run all scenarios together to avoid unnecessary waits, // assert information is verbose enough to trace to failure cause using (var testFile = new TempFile(Path.Combine(dir.Path, "file"))) using (var testDir = new TempDirectory(Path.Combine(dir.Path, "dir"))) { // start listening after we've created these watcher.EnableRaisingEvents = true; // change a file File.WriteAllText(testFile.Path, "change"); // renaming a directory // // We don't do this on Linux because depending on the timing of MOVED_FROM and MOVED_TO events, // a rename can trigger delete + create as a deliberate handling of an edge case, and this // test is checking that no create events are raised. if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Directory.Move(testDir.Path, testDir.Path + "_rename"); } // deleting a file & directory by leaving the using block } ExpectNoEvent(eventOccurred, "created"); } } [Fact] public void FileSystemWatcher_Created_FileCreatedInNestedDirectory() { TestNestedDirectoriesHelper(GetTestFilePath(), WatcherChangeTypes.Created, (AutoResetEvent are, TempDirectory ttd) => { using (var nestedFile = new TempFile(Path.Combine(ttd.Path, "nestedFile"))) { ExpectEvent(are, "nested file created"); } }); } // This can potentially fail, depending on where the test is run from, due to // the MAX_PATH limitation. When issue 645 is closed, this shouldn't be a problem [Fact, ActiveIssue(645, PlatformID.Any)] public void FileSystemWatcher_Created_DeepDirectoryStructure() { // List of created directories List<TempDirectory> lst = new List<TempDirectory>(); using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created); // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*.*"; watcher.IncludeSubdirectories = true; watcher.EnableRaisingEvents = true; // Priming directory TempDirectory priming = new TempDirectory(Path.Combine(dir.Path, "dir")); lst.Add(priming); ExpectEvent(eventOccurred, "priming create"); // Create a deep directory structure and expect things to work for (int i = 1; i < 20; i++) { lst.Add(new TempDirectory(Path.Combine(lst[i - 1].Path, String.Format("dir{0}", i)))); ExpectEvent(eventOccurred, lst[i].Path + " create"); } // Put a file at the very bottom and expect it to raise an event using (var file = new TempFile(Path.Combine(lst[lst.Count - 1].Path, "temp file"))) { ExpectEvent(eventOccurred, "temp file create"); } } } [ConditionalFact(nameof(CanCreateSymbolicLinks))] [ActiveIssue(3215, PlatformID.OSX)] public void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFile() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var temp = new TempFile(GetTestFilePath())) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created); // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.EnableRaisingEvents = true; // Make the symlink in our path (to the temp file) and make sure an event is raised string symLinkPath = Path.Combine(dir.Path, Path.GetFileName(temp.Path)); Assert.True(CreateSymLink(temp.Path, symLinkPath, false)); Assert.True(File.Exists(symLinkPath)); ExpectEvent(eventOccurred, "symlink created"); } } [ConditionalFact(nameof(CanCreateSymbolicLinks))] public void FileSystemWatcher_Created_WatcherDoesntFollowSymLinkToFolder() { using (var testDirectory = new TempDirectory(GetTestFilePath())) using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, GetTestFileName()))) using (var temp = new TempDirectory(GetTestFilePath())) using (var watcher = new FileSystemWatcher()) { AutoResetEvent eventOccurred = WatchForEvents(watcher, WatcherChangeTypes.Created); // put everything in our own directory to avoid collisions watcher.Path = Path.GetFullPath(dir.Path); watcher.Filter = "*"; watcher.EnableRaisingEvents = true; // Make the symlink in our path (to the temp folder) and make sure an event is raised string symLinkPath = Path.Combine(dir.Path, Path.GetFileName(temp.Path)); Assert.True(CreateSymLink(temp.Path, symLinkPath, true)); Assert.True(Directory.Exists(symLinkPath)); ExpectEvent(eventOccurred, "symlink created"); } } } }
// dnlib: See LICENSE.txt for more info using System; using System.IO; namespace dnlib.DotNet.Writer { /// <summary> /// Helps <see cref="SignatureWriter"/> map <see cref="ITypeDefOrRef"/>s to tokens /// </summary> public interface ISignatureWriterHelper : IWriterError { /// <summary> /// Returns a <c>TypeDefOrRef</c> encoded token /// </summary> /// <param name="typeDefOrRef">A <c>TypeDefOrRef</c> type</param> uint ToEncodedToken(ITypeDefOrRef typeDefOrRef); } /// <summary> /// Writes signatures /// </summary> public struct SignatureWriter : IDisposable { readonly ISignatureWriterHelper helper; RecursionCounter recursionCounter; readonly MemoryStream outStream; readonly DataWriter writer; readonly bool disposeStream; /// <summary> /// Write a <see cref="TypeSig"/> signature /// </summary> /// <param name="helper">Helper</param> /// <param name="typeSig">The type</param> /// <returns>The signature as a byte array</returns> public static byte[] Write(ISignatureWriterHelper helper, TypeSig typeSig) { using (var writer = new SignatureWriter(helper)) { writer.Write(typeSig); return writer.GetResult(); } } internal static byte[] Write(ISignatureWriterHelper helper, TypeSig typeSig, DataWriterContext context) { using (var writer = new SignatureWriter(helper, context)) { writer.Write(typeSig); return writer.GetResult(); } } /// <summary> /// Write a <see cref="CallingConventionSig"/> signature /// </summary> /// <param name="helper">Helper</param> /// <param name="sig">The signature</param> /// <returns>The signature as a byte array</returns> public static byte[] Write(ISignatureWriterHelper helper, CallingConventionSig sig) { using (var writer = new SignatureWriter(helper)) { writer.Write(sig); return writer.GetResult(); } } internal static byte[] Write(ISignatureWriterHelper helper, CallingConventionSig sig, DataWriterContext context) { using (var writer = new SignatureWriter(helper, context)) { writer.Write(sig); return writer.GetResult(); } } SignatureWriter(ISignatureWriterHelper helper) { this.helper = helper; recursionCounter = new RecursionCounter(); outStream = new MemoryStream(); writer = new DataWriter(outStream); disposeStream = true; } SignatureWriter(ISignatureWriterHelper helper, DataWriterContext context) { this.helper = helper; recursionCounter = new RecursionCounter(); outStream = context.OutStream; writer = context.Writer; disposeStream = false; outStream.SetLength(0); outStream.Position = 0; } byte[] GetResult() => outStream.ToArray(); uint WriteCompressedUInt32(uint value) => writer.WriteCompressedUInt32(helper, value); int WriteCompressedInt32(int value) => writer.WriteCompressedInt32(helper, value); void Write(TypeSig typeSig) { const ElementType DEFAULT_ELEMENT_TYPE = ElementType.Boolean; if (typeSig is null) { helper.Error("TypeSig is null"); writer.WriteByte((byte)DEFAULT_ELEMENT_TYPE); return; } if (!recursionCounter.Increment()) { helper.Error("Infinite recursion"); writer.WriteByte((byte)DEFAULT_ELEMENT_TYPE); return; } uint count; switch (typeSig.ElementType) { case ElementType.Void: case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.String: case ElementType.TypedByRef: case ElementType.I: case ElementType.U: case ElementType.Object: case ElementType.Sentinel: writer.WriteByte((byte)typeSig.ElementType); break; case ElementType.Ptr: case ElementType.ByRef: case ElementType.SZArray: case ElementType.Pinned: writer.WriteByte((byte)typeSig.ElementType); Write(typeSig.Next); break; case ElementType.ValueType: case ElementType.Class: writer.WriteByte((byte)typeSig.ElementType); Write(((TypeDefOrRefSig)typeSig).TypeDefOrRef); break; case ElementType.Var: case ElementType.MVar: writer.WriteByte((byte)typeSig.ElementType); WriteCompressedUInt32(((GenericSig)typeSig).Number); break; case ElementType.Array: writer.WriteByte((byte)typeSig.ElementType); var ary = (ArraySig)typeSig; Write(ary.Next); WriteCompressedUInt32(ary.Rank); if (ary.Rank == 0) break; count = WriteCompressedUInt32((uint)ary.Sizes.Count); for (uint i = 0; i < count; i++) WriteCompressedUInt32(ary.Sizes[(int)i]); count = WriteCompressedUInt32((uint)ary.LowerBounds.Count); for (uint i = 0; i < count; i++) WriteCompressedInt32(ary.LowerBounds[(int)i]); break; case ElementType.GenericInst: writer.WriteByte((byte)typeSig.ElementType); var gis = (GenericInstSig)typeSig; Write(gis.GenericType); count = WriteCompressedUInt32((uint)gis.GenericArguments.Count); for (uint i = 0; i < count; i++) Write(gis.GenericArguments[(int)i]); break; case ElementType.ValueArray: writer.WriteByte((byte)typeSig.ElementType); Write(typeSig.Next); WriteCompressedUInt32((typeSig as ValueArraySig).Size); break; case ElementType.FnPtr: writer.WriteByte((byte)typeSig.ElementType); Write((typeSig as FnPtrSig).Signature); break; case ElementType.CModReqd: case ElementType.CModOpt: writer.WriteByte((byte)typeSig.ElementType); Write((typeSig as ModifierSig).Modifier); Write(typeSig.Next); break; case ElementType.Module: writer.WriteByte((byte)typeSig.ElementType); WriteCompressedUInt32((typeSig as ModuleSig).Index); Write(typeSig.Next); break; case ElementType.End: case ElementType.R: case ElementType.Internal: default: helper.Error("Unknown or unsupported element type"); writer.WriteByte((byte)DEFAULT_ELEMENT_TYPE); break; } recursionCounter.Decrement(); } void Write(ITypeDefOrRef tdr) { if (tdr is null) { helper.Error("TypeDefOrRef is null"); WriteCompressedUInt32(0); return; } uint encodedToken = helper.ToEncodedToken(tdr); if (encodedToken > 0x1FFFFFFF) { helper.Error("Encoded token doesn't fit in 29 bits"); encodedToken = 0; } WriteCompressedUInt32(encodedToken); } void Write(CallingConventionSig sig) { if (sig is null) { helper.Error("sig is null"); return; } if (!recursionCounter.Increment()) { helper.Error("Infinite recursion"); return; } MethodBaseSig mbs; FieldSig fs; LocalSig ls; GenericInstMethodSig gim; if ((mbs = sig as MethodBaseSig) is not null) Write(mbs); else if ((fs = sig as FieldSig) is not null) Write(fs); else if ((ls = sig as LocalSig) is not null) Write(ls); else if ((gim = sig as GenericInstMethodSig) is not null) Write(gim); else { helper.Error("Unknown calling convention sig"); writer.WriteByte((byte)sig.GetCallingConvention()); } recursionCounter.Decrement(); } void Write(MethodBaseSig sig) { if (sig is null) { helper.Error("sig is null"); return; } if (!recursionCounter.Increment()) { helper.Error("Infinite recursion"); return; } writer.WriteByte((byte)sig.GetCallingConvention()); if (sig.Generic) WriteCompressedUInt32(sig.GenParamCount); uint numParams = (uint)sig.Params.Count; if (sig.ParamsAfterSentinel is not null) numParams += (uint)sig.ParamsAfterSentinel.Count; uint count = WriteCompressedUInt32(numParams); Write(sig.RetType); for (uint i = 0; i < count && i < (uint)sig.Params.Count; i++) Write(sig.Params[(int)i]); if (sig.ParamsAfterSentinel is not null && sig.ParamsAfterSentinel.Count > 0) { writer.WriteByte((byte)ElementType.Sentinel); for (uint i = 0, j = (uint)sig.Params.Count; i < (uint)sig.ParamsAfterSentinel.Count && j < count; i++, j++) Write(sig.ParamsAfterSentinel[(int)i]); } recursionCounter.Decrement(); } void Write(FieldSig sig) { if (sig is null) { helper.Error("sig is null"); return; } if (!recursionCounter.Increment()) { helper.Error("Infinite recursion"); return; } writer.WriteByte((byte)sig.GetCallingConvention()); Write(sig.Type); recursionCounter.Decrement(); } void Write(LocalSig sig) { if (sig is null) { helper.Error("sig is null"); return; } if (!recursionCounter.Increment()) { helper.Error("Infinite recursion"); return; } writer.WriteByte((byte)sig.GetCallingConvention()); uint count = WriteCompressedUInt32((uint)sig.Locals.Count); if (count >= 0x10000) { // ldloc 0xFFFF is invalid, see the ldloc documentation helper.Error("Too many locals, max number of locals is 65535 (0xFFFF)"); } for (uint i = 0; i < count; i++) Write(sig.Locals[(int)i]); recursionCounter.Decrement(); } void Write(GenericInstMethodSig sig) { if (sig is null) { helper.Error("sig is null"); return; } if (!recursionCounter.Increment()) { helper.Error("Infinite recursion"); return; } writer.WriteByte((byte)sig.GetCallingConvention()); uint count = WriteCompressedUInt32((uint)sig.GenericArguments.Count); for (uint i = 0; i < count; i++) Write(sig.GenericArguments[(int)i]); recursionCounter.Decrement(); } /// <inheritdoc/> public void Dispose() { if (!disposeStream) return; if (outStream is not null) outStream.Dispose(); } } }
#region License /* * TcpListenerWebSocketContext.cs * * The MIT License * * Copyright (c) 2012-2016 sta.blockhead * * 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 #region Contributors /* * Contributors: * - Liryna <liryna.stark@gmail.com> */ #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net.Security; using System.Net.Sockets; using System.Security.Principal; using System.Text; namespace CustomWebSocketSharp.Net.WebSockets { /// <summary> /// Provides the properties used to access the information in /// a WebSocket handshake request received by the <see cref="TcpListener"/>. /// </summary> internal class TcpListenerWebSocketContext : WebSocketContext { #region Private Fields private CookieCollection _cookies; private Logger _logger; private NameValueCollection _queryString; private HttpRequest _request; private bool _secure; private Stream _stream; private TcpClient _tcpClient; private Uri _uri; private IPrincipal _user; private WebSocket _websocket; #endregion #region Internal Constructors internal TcpListenerWebSocketContext ( TcpClient tcpClient, string protocol, bool secure, ServerSslConfiguration sslConfig, Logger logger ) { _tcpClient = tcpClient; _secure = secure; _logger = logger; var netStream = tcpClient.GetStream (); if (secure) { var sslStream = new SslStream (netStream, false, sslConfig.ClientCertificateValidationCallback); sslStream.AuthenticateAsServer ( sslConfig.ServerCertificate, sslConfig.ClientCertificateRequired, sslConfig.EnabledSslProtocols, sslConfig.CheckCertificateRevocation ); _stream = sslStream; } else { _stream = netStream; } _request = HttpRequest.Read (_stream, 90000); _uri = HttpUtility.CreateRequestUrl ( _request.RequestUri, _request.Headers["Host"], _request.IsWebSocketRequest, secure ); _websocket = new WebSocket (this, protocol); } #endregion #region Internal Properties internal Logger Log { get { return _logger; } } internal Stream Stream { get { return _stream; } } #endregion #region Public Properties /// <summary> /// Gets the HTTP cookies included in the request. /// </summary> /// <value> /// A <see cref="CustomWebSocketSharp.Net.CookieCollection"/> that contains the cookies. /// </value> public override CookieCollection CookieCollection { get { return _cookies ?? (_cookies = _request.Cookies); } } /// <summary> /// Gets the HTTP headers included in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the headers. /// </value> public override NameValueCollection Headers { get { return _request.Headers; } } /// <summary> /// Gets the value of the Host header included in the request. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Host header. /// </value> public override string Host { get { return _request.Headers["Host"]; } } /// <summary> /// Gets a value indicating whether the client is authenticated. /// </summary> /// <value> /// <c>true</c> if the client is authenticated; otherwise, <c>false</c>. /// </value> public override bool IsAuthenticated { get { return _user != null; } } /// <summary> /// Gets a value indicating whether the client connected from the local computer. /// </summary> /// <value> /// <c>true</c> if the client connected from the local computer; otherwise, <c>false</c>. /// </value> public override bool IsLocal { get { return UserEndPoint.Address.IsLocal (); } } /// <summary> /// Gets a value indicating whether the WebSocket connection is secured. /// </summary> /// <value> /// <c>true</c> if the connection is secured; otherwise, <c>false</c>. /// </value> public override bool IsSecureConnection { get { return _secure; } } /// <summary> /// Gets a value indicating whether the request is a WebSocket handshake request. /// </summary> /// <value> /// <c>true</c> if the request is a WebSocket handshake request; otherwise, <c>false</c>. /// </value> public override bool IsWebSocketRequest { get { return _request.IsWebSocketRequest; } } /// <summary> /// Gets the value of the Origin header included in the request. /// </summary> /// <value> /// A <see cref="string"/> that represents the value of the Origin header. /// </value> public override string Origin { get { return _request.Headers["Origin"]; } } /// <summary> /// Gets the query string included in the request. /// </summary> /// <value> /// A <see cref="NameValueCollection"/> that contains the query string parameters. /// </value> public override NameValueCollection QueryString { get { return _queryString ?? ( _queryString = HttpUtility.InternalParseQueryString ( _uri != null ? _uri.Query : null, Encoding.UTF8 ) ); } } /// <summary> /// Gets the URI requested by the client. /// </summary> /// <value> /// A <see cref="Uri"/> that represents the requested URI. /// </value> public override Uri RequestUri { get { return _uri; } } /// <summary> /// Gets the value of the Sec-WebSocket-Key header included in the request. /// </summary> /// <remarks> /// This property provides a part of the information used by the server to prove that /// it received a valid WebSocket handshake request. /// </remarks> /// <value> /// A <see cref="string"/> that represents the value of the Sec-WebSocket-Key header. /// </value> public override string SecWebSocketKey { get { return _request.Headers["Sec-WebSocket-Key"]; } } /// <summary> /// Gets the values of the Sec-WebSocket-Protocol header included in the request. /// </summary> /// <remarks> /// This property represents the subprotocols requested by the client. /// </remarks> /// <value> /// An <see cref="T:System.Collections.Generic.IEnumerable{string}"/> instance that provides /// an enumerator which supports the iteration over the values of the Sec-WebSocket-Protocol /// header. /// </value> public override IEnumerable<string> SecWebSocketProtocols { get { var protocols = _request.Headers["Sec-WebSocket-Protocol"]; if (protocols != null) { foreach (var protocol in protocols.Split (',')) yield return protocol.Trim (); } } } /// <summary> /// Gets the value of the Sec-WebSocket-Version header included in the request. /// </summary> /// <remarks> /// This property represents the WebSocket protocol version. /// </remarks> /// <value> /// A <see cref="string"/> that represents the value of the Sec-WebSocket-Version header. /// </value> public override string SecWebSocketVersion { get { return _request.Headers["Sec-WebSocket-Version"]; } } /// <summary> /// Gets the server endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the server endpoint. /// </value> public override System.Net.IPEndPoint ServerEndPoint { get { return (System.Net.IPEndPoint) _tcpClient.Client.LocalEndPoint; } } /// <summary> /// Gets the client information (identity, authentication, and security roles). /// </summary> /// <value> /// A <see cref="IPrincipal"/> instance that represents the client information. /// </value> public override IPrincipal User { get { return _user; } } /// <summary> /// Gets the client endpoint as an IP address and a port number. /// </summary> /// <value> /// A <see cref="System.Net.IPEndPoint"/> that represents the client endpoint. /// </value> public override System.Net.IPEndPoint UserEndPoint { get { return (System.Net.IPEndPoint) _tcpClient.Client.RemoteEndPoint; } } /// <summary> /// Gets the <see cref="CustomWebSocketSharp.WebSocket"/> instance used for /// two-way communication between client and server. /// </summary> /// <value> /// A <see cref="CustomWebSocketSharp.WebSocket"/>. /// </value> public override WebSocket WebSocket { get { return _websocket; } } #endregion #region Internal Methods internal bool Authenticate ( AuthenticationSchemes scheme, string realm, Func<IIdentity, NetworkCredential> credentialsFinder ) { if (scheme == AuthenticationSchemes.Anonymous) return true; if (scheme == AuthenticationSchemes.None) { Close (HttpStatusCode.Forbidden); return false; } var chal = new AuthenticationChallenge (scheme, realm).ToString (); var retry = -1; Func<bool> auth = null; auth = () => { retry++; if (retry > 99) { Close (HttpStatusCode.Forbidden); return false; } var user = HttpUtility.CreateUser ( _request.Headers["Authorization"], scheme, realm, _request.HttpMethod, credentialsFinder ); if (user == null || !user.Identity.IsAuthenticated) { SendAuthenticationChallenge (chal); return auth (); } _user = user; return true; }; return auth (); } internal void Close () { _stream.Close (); _tcpClient.Close (); } internal void Close (HttpStatusCode code) { _websocket.Close (HttpResponse.CreateCloseResponse (code)); } internal void SendAuthenticationChallenge (string challenge) { var buff = HttpResponse.CreateUnauthorizedResponse (challenge).ToByteArray (); _stream.Write (buff, 0, buff.Length); _request = HttpRequest.Read (_stream, 15000); } #endregion #region Public Methods /// <summary> /// Returns a <see cref="string"/> that represents /// the current <see cref="TcpListenerWebSocketContext"/>. /// </summary> /// <returns> /// A <see cref="string"/> that represents /// the current <see cref="TcpListenerWebSocketContext"/>. /// </returns> public override string ToString () { return _request.ToString (); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.ComponentModel; using Microsoft.Ccr.Core; using Microsoft.Dss.Core; using Microsoft.Dss.Core.Attributes; using Microsoft.Dss.ServiceModel.Dssp; using Microsoft.Dss.ServiceModel.DsspServiceBase; using Microsoft.Dss.Core.DsspHttp; using Microsoft.Dss.Core.DsspHttpUtilities; using W3C.Soap; using System.Net; using submgr = Microsoft.Dss.Services.SubscriptionManager; // Pololu "Mini Maestro 12" is used here to control the servos. See PololuDLLs folder for dlls. Need to install driver too from Pololu. using Pololu.Usc; using Pololu.UsbWrapper; namespace TrackRoamer.Robotics.Hardware.PololuMaestroService { [Contract(Contract.Identifier)] [DisplayName("(User) Pololu Maestro Service")] [Description("Pololu Maestro Service service controls servos and reads analog signals")] class PololuMaestroService : DsspServiceBase { private const string _configFile = ServicePaths.Store + "/PololuMaestroService.user.config.xml"; // we are using Pololu Maestro Mini 12 http://www.pololu.com/catalog/product/1352 private const int CHANNELS_PER_DEVICE = 12; /// <summary> /// Service state /// </summary> [ServiceState(StateTransform = "TrackRoamer.Robotics.Hardware.PololuMaestroService.TrackRoamer.Robotics.Hardware.PololuMaestroService.xslt")] [InitialStatePartner(Optional = true, ServiceUri = _configFile)] private PololuMaestroServiceState _state = new PololuMaestroServiceState(); /// <summary> /// Main service port /// </summary> [ServicePort("/PololuMaestroService", AllowMultipleInstances = false)] PololuMaestroServiceOperations _mainPort = new PololuMaestroServiceOperations(); [SubscriptionManagerPartner] submgr.SubscriptionManagerPort _submgrPort = new submgr.SubscriptionManagerPort(); /// <summary> /// Service constructor /// </summary> public PololuMaestroService(DsspServiceCreationPort creationPort) : base(creationPort) { } /// <summary> /// Service start /// </summary> protected override void Start() { try { bool stateChanged = false; if (_state == null) { _state = new PololuMaestroServiceState(); stateChanged = true; } if (_state.SafePositions == null) { _state.SafePositions = new List<SafePosition>(); //_state.SafePositions.Add(new SafePosition() { channel = 4, positionUs = 1000 }); stateChanged = true; } if(stateChanged) { SaveState(_state); } SetSafePositions(); } catch (Exception exception) { // Fatal exception during startup, shutdown service LogError(LogGroups.Activation, exception); DefaultDropHandler(new DsspDefaultDrop()); return; } base.Start(); } private void SetSafePositions() { Console.WriteLine("Set Safe Positions: " + _state.SafePositions.Count); foreach (SafePosition safePosition in _state.SafePositions) { Console.WriteLine(" channel: {0} target: {1} us", safePosition.channel, safePosition.positionUs); TrySetTarget(safePosition.channel, (ushort)(safePosition.positionUs << 2)); } } /// <summary> /// Pololu Maestro Command Handler /// </summary> /// <param name="cmd"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Exclusive)] public virtual IEnumerator<ITask> PololuMaestroCommandHandler(SendPololuMaestroCommand cmd) { //Console.WriteLine("PololuMaestroCommand: " + cmd.Body); TrySetTarget(cmd.Body.ChannelValues); cmd.ResponsePort.Post(DefaultUpdateResponseType.Instance); yield break; } #region Operation Handlers /// <summary> /// Get Handler /// </summary> /// <param name="get"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Concurrent)] public virtual IEnumerator<ITask> GetHandler(Get get) { get.ResponsePort.Post(_state); yield break; } /// <summary> /// Http Get Handler /// </summary> /// <param name="httpGet"></param> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Concurrent)] public virtual IEnumerator<ITask> HttpGetHandler(HttpGet httpGet) { HttpListenerRequest request = httpGet.Body.Context.Request; HttpListenerResponse response = httpGet.Body.Context.Response; HttpResponseType rsp = null; rsp = new HttpResponseType(HttpStatusCode.OK, _state, base.StateTransformPath); //rsp = new HttpResponseType(HttpStatusCode.OK, _state, _transformPololuMaestroData); httpGet.ResponsePort.Post(rsp); yield break; } /// <summary> /// Handles Subscribe messages /// </summary> /// <param name="subscribe">the subscribe request</param> [ServiceHandler] public void SubscribeHandler(Subscribe subscribe) { SubscribeHelper(_submgrPort, subscribe.Body, subscribe.ResponsePort); } /// <summary> /// Shut down the service, put everything in safe positions /// </summary> /// <returns></returns> [ServiceHandler(ServiceHandlerBehavior.Teardown)] public virtual IEnumerator<ITask> DropHandler(DsspDefaultDrop drop) { SetSafePositions(); base.DefaultDropHandler(drop); yield break; } #endregion // Operation Handlers #region Servo controls /// <summary> /// Attempts to set the target (width of pulses sent) of a channel. /// </summary> /// <param name="channel">Channel number - from 0 to 23.</param> /// <param name="target"> /// Target, in units of quarter microseconds. For typical servos, /// 6000 is neutral and the acceptable range is 4000-8000. /// A good servo will take 880 to 2200 us (3520 to 8800 in quarters) /// </param> private void TrySetTarget(Byte channel, UInt16 target) { try { int index = channel / CHANNELS_PER_DEVICE; channel = (byte)(channel % CHANNELS_PER_DEVICE); using (Usc device = connectToDevice(index)) // Find a device and temporarily connect. { //Console.WriteLine(" (s) device: {0} channel: {1} target: {2}", device.getSerialNumber(), channel, target); device.setTarget(channel, target); // device.Dispose() is called automatically when the "using" block ends, // allowing other functions and processes to use the device. } } catch (Exception exception) // Handle exceptions by displaying them to the user. { Console.WriteLine(exception); } } private void TrySetTarget(List<ChannelValuePair> channelValues) { try { var groupedByDevice = from a in channelValues group a by a.Channel / CHANNELS_PER_DEVICE into g select new { deviceIndex = g.Key, deviceChannelValues = g }; foreach (var devGrp in groupedByDevice) { using (Usc device = connectToDevice(devGrp.deviceIndex)) // Find a device and temporarily connect. { foreach (ChannelValuePair cvp in devGrp.deviceChannelValues) { byte channel = (byte)(cvp.Channel % CHANNELS_PER_DEVICE); //Console.WriteLine(" (m) device: {0} channel: {1} target: {2}", device.getSerialNumber(), channel, cvp.Target); device.setTarget(channel, cvp.Target); } // device.Dispose() is called automatically when the "using" block ends, // allowing other functions and processes to use the device. } } } catch (Exception exception) // Handle exceptions by displaying them to the user. { Console.WriteLine(exception); } } private void TryGetTarget(Byte channel) { try { int index = channel / CHANNELS_PER_DEVICE; channel = (byte)(channel % CHANNELS_PER_DEVICE); using (Usc device = connectToDevice(index)) // Find a device and temporarily connect. { ServoStatus[] servos; device.getVariables(out servos); // device.Dispose() is called automatically when the "using" block ends, // allowing other functions and processes to use the device. } } catch (Exception exception) // Handle exceptions by displaying them to the user. { Console.WriteLine(exception); } } // we assume that devices serial numbers are in increasing sequence: Comparison<DeviceListItem> deviceComparer = new Comparison<DeviceListItem>((a, b) => int.Parse(a.serialNumber) - int.Parse(b.serialNumber)); /// <summary> /// Connects to a Maestro using native USB and returns the Usc object /// representing that connection. When you are done with the /// connection, you should close it using the Dispose() method so that /// other processes or functions can connect to the device later. The /// "using" statement can do this automatically for you. /// </summary> private Usc connectToDevice(int index) { // Get a list of all connected devices of this type. List<DeviceListItem> connectedDevices = Usc.getConnectedDevices(); connectedDevices.Sort(deviceComparer); // we must have all three devices online, or we will be commanding a wrong device. if (connectedDevices.Count() != 3) { throw new Exception("Not all Pololu devices are online - found " + connectedDevices.Count() + " expected 3"); } DeviceListItem dli = connectedDevices[index]; //foreach (DeviceListItem dli in connectedDevices) { // If you have multiple devices connected and want to select a particular // device by serial number, you could simply add a line like this: // if (dli.serialNumber != "00012345"){ continue; } Usc device = new Usc(dli); // Connect to the device. return device; // Return the device. } throw new Exception("Could not find Pololu device.\r\nMake sure it's plugged into USB\r\nCheck your Device Manager.\r\nPololu Mini Maestro 12 needed."); } #endregion // Servo controls } }
// 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.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableListBuilderTest : ImmutableListTestBase { [Fact] public void CreateBuilder() { ImmutableList<string>.Builder builder = ImmutableList.CreateBuilder<string>(); Assert.NotNull(builder); } [Fact] public void ToBuilder() { var builder = ImmutableList<int>.Empty.ToBuilder(); builder.Add(3); builder.Add(5); builder.Add(5); Assert.Equal(3, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var list = builder.ToImmutable(); Assert.Equal(builder.Count, list.Count); builder.Add(8); Assert.Equal(4, builder.Count); Assert.Equal(3, list.Count); Assert.True(builder.Contains(8)); Assert.False(list.Contains(8)); } [Fact] public void BuilderFromList() { var list = ImmutableList<int>.Empty.Add(1); var builder = list.ToBuilder(); Assert.True(builder.Contains(1)); builder.Add(3); builder.Add(5); builder.Add(5); Assert.Equal(4, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var list2 = builder.ToImmutable(); Assert.Equal(builder.Count, list2.Count); Assert.True(list2.Contains(1)); builder.Add(8); Assert.Equal(5, builder.Count); Assert.Equal(4, list2.Count); Assert.True(builder.Contains(8)); Assert.False(list.Contains(8)); Assert.False(list2.Contains(8)); } [Fact] public void SeveralChanges() { var mutable = ImmutableList<int>.Empty.ToBuilder(); var immutable1 = mutable.ToImmutable(); Assert.Same(immutable1, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences."); mutable.Add(1); var immutable2 = mutable.ToImmutable(); Assert.NotSame(immutable1, immutable2); //, "Mutating the collection did not reset the Immutable property."); Assert.Same(immutable2, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences."); Assert.Equal(1, immutable2.Count); } [Fact] public void EnumerateBuilderWhileMutating() { var builder = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 10)).ToBuilder(); Assert.Equal(Enumerable.Range(1, 10), builder); var enumerator = builder.GetEnumerator(); Assert.True(enumerator.MoveNext()); builder.Add(11); // Verify that a new enumerator will succeed. Assert.Equal(Enumerable.Range(1, 11), builder); // Try enumerating further with the previous enumerable now that we've changed the collection. Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.Reset(); enumerator.MoveNext(); // resetting should fix the problem. // Verify that by obtaining a new enumerator, we can enumerate all the contents. Assert.Equal(Enumerable.Range(1, 11), builder); } [Fact] public void BuilderReusesUnchangedImmutableInstances() { var collection = ImmutableList<int>.Empty.Add(1); var builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // no changes at all. builder.Add(2); var newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. } [Fact] public void Insert() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.Insert(0, 1); mutable.Insert(0, 0); mutable.Insert(2, 3); Assert.Equal(new[] { 0, 1, 3 }, mutable); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(-1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.Insert(4, 0)); } [Fact] public void InsertRange() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.InsertRange(0, new[] { 1, 4, 5 }); Assert.Equal(new[] { 1, 4, 5 }, mutable); mutable.InsertRange(1, new[] { 2, 3 }); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, mutable); mutable.InsertRange(5, new[] { 6 }); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable); mutable.InsertRange(5, new int[0]); Assert.Equal(new[] { 1, 2, 3, 4, 5, 6 }, mutable); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(-1, new int[0])); Assert.Throws<ArgumentOutOfRangeException>(() => mutable.InsertRange(mutable.Count + 1, new int[0])); } [Fact] public void AddRange() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.AddRange(new[] { 1, 4, 5 }); Assert.Equal(new[] { 1, 4, 5 }, mutable); mutable.AddRange(new[] { 2, 3 }); Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable); mutable.AddRange(new int[0]); Assert.Equal(new[] { 1, 4, 5, 2, 3 }, mutable); AssertExtensions.Throws<ArgumentNullException>("items", () => mutable.AddRange(null)); } [Fact] public void Remove() { var mutable = ImmutableList<int>.Empty.ToBuilder(); Assert.False(mutable.Remove(5)); mutable.Add(1); mutable.Add(2); mutable.Add(3); Assert.True(mutable.Remove(2)); Assert.Equal(new[] { 1, 3 }, mutable); Assert.True(mutable.Remove(1)); Assert.Equal(new[] { 3 }, mutable); Assert.True(mutable.Remove(3)); Assert.Equal(new int[0], mutable); Assert.False(mutable.Remove(5)); } [Fact] public void RemoveAt() { var mutable = ImmutableList<int>.Empty.ToBuilder(); mutable.Add(1); mutable.Add(2); mutable.Add(3); mutable.RemoveAt(2); Assert.Equal(new[] { 1, 2 }, mutable); mutable.RemoveAt(0); Assert.Equal(new[] { 2 }, mutable); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1)); mutable.RemoveAt(0); Assert.Equal(new int[0], mutable); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable.RemoveAt(1)); } [Fact] public void Reverse() { var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); mutable.Reverse(); Assert.Equal(Enumerable.Range(1, 3).Reverse(), mutable); } [Fact] public void Clear() { var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); mutable.Clear(); Assert.Equal(0, mutable.Count); // Do it again for good measure. :) mutable.Clear(); Assert.Equal(0, mutable.Count); } [Fact] public void IsReadOnly() { ICollection<int> builder = ImmutableList.Create<int>().ToBuilder(); Assert.False(builder.IsReadOnly); } [Fact] public void Indexer() { var mutable = ImmutableList.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); Assert.Equal(2, mutable[1]); mutable[1] = 5; Assert.Equal(5, mutable[1]); mutable[0] = -2; mutable[2] = -3; Assert.Equal(new[] { -2, 5, -3 }, mutable); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[3] = 4); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1] = 4); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[3]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => mutable[-1]); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => ImmutableList.CreateRange(seq).ToBuilder(), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => ImmutableList.CreateRange(seq).ToBuilder(), (b, v) => b.LastIndexOf(v), (b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void GetEnumeratorExplicit() { ICollection<int> builder = ImmutableList.Create<int>().ToBuilder(); var enumerator = builder.GetEnumerator(); Assert.NotNull(enumerator); } [Fact] public void IsSynchronized() { ICollection collection = ImmutableList.Create<int>().ToBuilder(); Assert.False(collection.IsSynchronized); } [Fact] public void IListMembers() { IList list = ImmutableList.Create<int>().ToBuilder(); Assert.False(list.IsReadOnly); Assert.False(list.IsFixedSize); Assert.Equal(0, list.Add(5)); Assert.Equal(1, list.Add(8)); Assert.True(list.Contains(5)); Assert.False(list.Contains(7)); list.Insert(1, 6); Assert.Equal(6, list[1]); list.Remove(5); list[0] = 9; Assert.Equal(new[] { 9, 8 }, list.Cast<int>().ToArray()); list.Clear(); Assert.Equal(0, list.Count); } [Fact] public void IList_Remove_NullArgument() { this.AssertIListBaseline(RemoveFunc, 1, null); this.AssertIListBaseline(RemoveFunc, "item", null); this.AssertIListBaseline(RemoveFunc, new int?(1), null); this.AssertIListBaseline(RemoveFunc, new int?(), null); } [Fact] public void IList_Remove_ArgTypeMismatch() { this.AssertIListBaseline(RemoveFunc, "first item", new object()); this.AssertIListBaseline(RemoveFunc, 1, 1.0); this.AssertIListBaseline(RemoveFunc, new int?(1), 1); this.AssertIListBaseline(RemoveFunc, new int?(1), new int?(1)); this.AssertIListBaseline(RemoveFunc, new int?(1), string.Empty); } [Fact] public void IList_Remove_EqualsOverride() { this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), "foo"); this.AssertIListBaseline(RemoveFunc, new ProgrammaticEquals(v => v is string), 3); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableList.CreateBuilder<int>()); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(ImmutableList.CreateBuilder<string>()); } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { return ImmutableList<T>.Empty.AddRange(contents).ToBuilder(); } protected override void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test) { var builder = list.ToBuilder(); var bcl = list.ToList(); int expected = bcl.RemoveAll(test); var actual = builder.RemoveAll(test); Assert.Equal(expected, actual); Assert.Equal<T>(bcl, builder.ToList()); } protected override void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count) { var expected = list.ToList(); expected.Reverse(index, count); var builder = list.ToBuilder(); builder.Reverse(index, count); Assert.Equal<T>(expected, builder.ToList()); } internal override IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list) { return list.ToBuilder(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list) { var builder = list.ToBuilder(); builder.Sort(); return builder.ToImmutable().ToList(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison) { var builder = list.ToBuilder(); builder.Sort(comparison); return builder.ToImmutable().ToList(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer) { var builder = list.ToBuilder(); builder.Sort(comparer); return builder.ToImmutable().ToList(); } protected override List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer) { var builder = list.ToBuilder(); builder.Sort(index, count, comparer); return builder.ToImmutable().ToList(); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using Xunit; using System.Collections.Generic; using System.Collections; namespace System.Json.Tests { public class JsonArrayTests { public static IEnumerable<object[]> JsonValues_TestData() { yield return new object[] { new JsonValue[0] }; yield return new object[] { new JsonValue[] { null } }; } [Theory] [MemberData(nameof(JsonValues_TestData))] public void Ctor(JsonValue[] items) { VerifyJsonArray(new JsonArray(items), items); VerifyJsonArray(new JsonArray((IEnumerable<JsonValue>)items), items); } private static void VerifyJsonArray(JsonArray array, JsonValue[] values) { Assert.Equal(values.Length, array.Count); for (int i = 0; i < values.Length; i++) { Assert.Equal(values[i], array[i]); } } [Fact] public void Ctor_Array_Works() { // Workaround xunit/xunit#987: InvalidOperationException thrown if this is in MemberData JsonValue[] items = new JsonValue[] { new JsonPrimitive(true) }; JsonArray array = new JsonArray(items); Assert.Equal(1, array.Count); Assert.Same(items[0], array[0]); } [Fact] public void Ctor_IEnumerable_Works() { // Workaround xunit/xunit#987: InvalidOperationException thrown if this is in MemberData JsonValue[] items = new JsonValue[] { new JsonPrimitive(true) }; JsonArray array = new JsonArray((IEnumerable<JsonValue>)items); Assert.Equal(1, array.Count); Assert.Same(items[0], array[0]); } [Fact] public void Ctor_NullArray_Works() { JsonArray array = new JsonArray(null); Assert.Equal(0, array.Count); } [Fact] public void Ctor_NullIEnumerable_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("items", () => new JsonArray((IEnumerable<JsonValue>)null)); } [Fact] public void Item_Get_InvalidIndex_ThrowsArgumentOutOfRangeException() { JsonArray array = new JsonArray(new JsonPrimitive(true)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array[-1]); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array[1]); } [Fact] public void Item_Set_Get() { JsonArray array = new JsonArray(new JsonPrimitive(true)); JsonPrimitive value = new JsonPrimitive(false); array[0] = value; Assert.Same(value, array[0]); } [Fact] public void Item_Set_InvalidIndex_ThrowsArgumentOutOfRangeException() { JsonArray array = new JsonArray(new JsonPrimitive(true)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array[-1] = false); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array[1] = false); } [Fact] public void IsReadOnly_Get_ReturnsFalse() { Assert.False(new JsonArray().IsReadOnly); } [Fact] public void JsonType_ReturnsArray() { Assert.Equal(JsonType.Array, new JsonArray().JsonType); } [Fact] public void Add() { JsonArray array = new JsonArray(); JsonValue value = new JsonPrimitive(true); array.Add(value); Assert.Equal(1, array.Count); Assert.Same(value, array[0]); } [Fact] public void Add_NullItem_ThrowsArgumentNullException() { JsonArray array = new JsonArray(); AssertExtensions.Throws<ArgumentNullException>("item", () => array.Add(null)); } [Fact] public void AddRange_Array() { JsonArray array = new JsonArray(); JsonValue[] values = new JsonValue[] { null, new JsonPrimitive(true) }; array.AddRange(values); Assert.Equal(2, array.Count); Assert.Same(values[0], array[0]); Assert.Same(values[1], array[1]); } [Fact] public void AddRange_IEnumerable() { JsonArray array = new JsonArray(); JsonValue[] values = new JsonValue[] { null, new JsonPrimitive(true) }; array.AddRange((IEnumerable<JsonValue>)values); Assert.Equal(2, array.Count); Assert.Same(values[0], array[0]); Assert.Same(values[1], array[1]); } [Fact] public void AddRange_NullArray_Works() { JsonArray array = new JsonArray(); array.AddRange(null); Assert.Equal(0, array.Count); } [Fact] public void AddRange_NullIEnumerable_ThrowsArgumentNullException() { JsonArray array = new JsonArray(); AssertExtensions.Throws<ArgumentNullException>("items", () => array.AddRange((IEnumerable<JsonValue>)null)); } [Fact] public void Insert() { JsonArray array = new JsonArray(new JsonPrimitive(true)); JsonPrimitive value = new JsonPrimitive(false); array.Insert(1, value); Assert.Equal(2, array.Count); Assert.Same(value, array[1]); } [Fact] public void Insert_InvalidIndex_ThrowsArgumentOutOfRangeException() { JsonArray array = new JsonArray(new JsonPrimitive(true)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.Insert(-1, new JsonPrimitive(false))); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.Insert(2, new JsonPrimitive(false))); } [Fact] public void IndexOf() { JsonValue[] items = new JsonValue[] { new JsonPrimitive(true) }; JsonArray array = new JsonArray((IEnumerable<JsonValue>)items); Assert.Equal(0, array.IndexOf(items[0])); Assert.Equal(-1, array.IndexOf(new JsonPrimitive(false))); } [Fact] public void Contains() { JsonValue[] items = new JsonValue[] { new JsonPrimitive(true) }; JsonArray array = new JsonArray((IEnumerable<JsonValue>)items); Assert.True(array.Contains(items[0])); Assert.False(array.Contains(new JsonPrimitive(false))); } [Theory] [InlineData(0)] [InlineData(1)] public void CopyTo(int arrayIndex) { JsonArray array = new JsonArray(new JsonPrimitive(true)); JsonValue[] copy = new JsonValue[array.Count + arrayIndex]; array.CopyTo(copy, arrayIndex); for (int i = 0; i < arrayIndex; i++) { Assert.Null(copy[i]); } for (int i = arrayIndex; i < copy.Length; i++) { Assert.Same(array[i - arrayIndex], copy[i]); } } [Fact] public void Remove() { JsonValue[] items = new JsonValue[] { new JsonPrimitive(true) }; JsonArray array = new JsonArray((IEnumerable<JsonValue>)items); array.Remove(items[0]); Assert.Equal(0, array.Count); array.Remove(items[0]); Assert.Equal(0, array.Count); } [Fact] public void RemoveAt() { JsonValue[] items = new JsonValue[] { new JsonPrimitive(true) }; JsonArray array = new JsonArray((IEnumerable<JsonValue>)items); array.RemoveAt(0); Assert.Equal(0, array.Count); } [Fact] public void RemoveAt_InvalidIndex_ThrowsArgumentOutOfRangeException() { JsonArray array = new JsonArray(new JsonPrimitive(true)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.RemoveAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => array.RemoveAt(1)); } [Fact] public void Clear() { JsonArray array = new JsonArray(new JsonValue[3]); array.Clear(); Assert.Equal(0, array.Count); array.Clear(); Assert.Equal(0, array.Count); } [Fact] public void Save_Stream() { JsonArray array = new JsonArray(new JsonPrimitive(true), null); using (MemoryStream stream = new MemoryStream()) { array.Save(stream); string result = Encoding.UTF8.GetString(stream.ToArray()); Assert.Equal("[true, null]", result); } } [Fact] public void Save_TextWriter() { JsonArray array = new JsonArray(new JsonPrimitive(true), null); using (StringWriter writer = new StringWriter()) { array.Save(writer); Assert.Equal("[true, null]", writer.ToString()); } } [Fact] public void Save_NullStream_ThrowsArgumentNullException() { JsonArray array = new JsonArray(); AssertExtensions.Throws<ArgumentNullException>("stream", () => array.Save((Stream)null)); AssertExtensions.Throws<ArgumentNullException>("textWriter", () => array.Save((TextWriter)null)); } [Fact] public void GetEnumerator_GenericIEnumerable() { JsonArray array = new JsonArray(new JsonPrimitive(true)); IEnumerator<JsonValue> enumerator = ((IEnumerable<JsonValue>)array).GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Same(array[counter], enumerator.Current); counter++; } Assert.Equal(array.Count, counter); enumerator.Reset(); } } [Fact] public void GetEnumerator_NonGenericIEnumerable() { JsonArray array = new JsonArray(new JsonPrimitive(true)); IEnumerator enumerator = ((IEnumerable)array).GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Same(array[counter], enumerator.Current); counter++; } Assert.Equal(array.Count, counter); enumerator.Reset(); } } } }
using System; using System.IO; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using MailKit.Net.Smtp; using MailKit.Security; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using MimeKit; namespace OrchardCore.Email.Services { /// <summary> /// Represents a SMTP service that allows to send emails. /// </summary> public class SmtpService : ISmtpService { private const string EmailExtension = ".eml"; private static readonly char[] EmailsSeparator = new char[] { ',', ';' }; private readonly SmtpSettings _options; private readonly ILogger _logger; private readonly IStringLocalizer S; /// <summary> /// Initializes a new instance of a <see cref="SmtpService"/>. /// </summary> /// <param name="options">The <see cref="IOptions{SmtpSettings}"/>.</param> /// <param name="logger">The <see cref="ILogger{SmtpService}"/>.</param> /// <param name="stringLocalizer">The <see cref="IStringLocalizer{SmtpService}"/>.</param> public SmtpService( IOptions<SmtpSettings> options, ILogger<SmtpService> logger, IStringLocalizer<SmtpService> stringLocalizer ) { _options = options.Value; _logger = logger; S = stringLocalizer; } /// <summary> /// Sends the specified message to an SMTP server for delivery. /// </summary> /// <param name="message">The message to be sent.</param> /// <returns>A <see cref="SmtpResult"/> that holds information about the sent message, for instance if it has sent successfully or if it has failed.</returns> /// <remarks>This method allows to send an email without setting <see cref="MailMessage.To"/> if <see cref="MailMessage.Cc"/> or <see cref="MailMessage.Bcc"/> is provided.</remarks> public async Task<SmtpResult> SendAsync(MailMessage message) { if (_options == null) { return SmtpResult.Failed(S["SMTP settings must be configured before an email can be sent."]); } SmtpResult result; var response = default(string); try { // Set the MailMessage.From, to avoid the confusion between _options.DefaultSender (Author) and submitter (Sender) var senderAddress = String.IsNullOrWhiteSpace(message.From) ? _options.DefaultSender : message.From; if (!String.IsNullOrWhiteSpace(senderAddress)) { message.From = senderAddress; } var mimeMessage = FromMailMessage(message); if (mimeMessage.From.Count == 0 && mimeMessage.Cc.Count == 0 && mimeMessage.Bcc.Count == 0) { return SmtpResult.Failed(S["The mail message should have at least one of these headers: To, Cc or Bcc."]); } switch (_options.DeliveryMethod) { case SmtpDeliveryMethod.Network: response = await SendOnlineMessage(mimeMessage); break; case SmtpDeliveryMethod.SpecifiedPickupDirectory: await SendOfflineMessage(mimeMessage, _options.PickupDirectoryLocation); break; default: throw new NotSupportedException($"The '{_options.DeliveryMethod}' delivery method is not supported."); } result = SmtpResult.Success; } catch (Exception ex) { result = SmtpResult.Failed(S["An error occurred while sending an email: '{0}'", ex.Message]); } result.Response = response; return result; } private MimeMessage FromMailMessage(MailMessage message) { var submitterAddress = String.IsNullOrWhiteSpace(message.Sender) ? _options.DefaultSender : message.Sender; var mimeMessage = new MimeMessage(); if (!String.IsNullOrEmpty(submitterAddress)) { mimeMessage.Sender = MailboxAddress.Parse(submitterAddress); } if (!string.IsNullOrWhiteSpace(message.From)) { foreach (var address in message.From.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries)) { mimeMessage.From.Add(MailboxAddress.Parse(address)); } } if (!string.IsNullOrWhiteSpace(message.To)) { foreach (var address in message.To.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries)) { mimeMessage.To.Add(MailboxAddress.Parse(address)); } } if (!string.IsNullOrWhiteSpace(message.Cc)) { foreach (var address in message.Cc.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries)) { mimeMessage.Cc.Add(MailboxAddress.Parse(address)); } } if (!string.IsNullOrWhiteSpace(message.Bcc)) { foreach (var address in message.Bcc.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries)) { mimeMessage.Bcc.Add(MailboxAddress.Parse(address)); } } if (string.IsNullOrWhiteSpace(message.ReplyTo)) { foreach (var address in mimeMessage.From) { mimeMessage.ReplyTo.Add(address); } } else { foreach (var address in message.ReplyTo.Split(EmailsSeparator, StringSplitOptions.RemoveEmptyEntries)) { mimeMessage.ReplyTo.Add(MailboxAddress.Parse(address)); } } mimeMessage.Subject = message.Subject; var body = new BodyBuilder(); if (message.IsBodyHtml) { body.HtmlBody = message.Body; } if (message.IsBodyText) { body.TextBody = message.BodyText; } foreach (var attachment in message.Attachments) { // Stream must not be null, otherwise it would try to get the filesystem path if (attachment.Stream != null) { body.Attachments.Add(attachment.Filename, attachment.Stream); } } mimeMessage.Body = body.ToMessageBody(); return mimeMessage; } private bool CertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; _logger.LogError(string.Concat("SMTP Server's certificate {CertificateSubject} issued by {CertificateIssuer} ", "with thumbprint {CertificateThumbprint} and expiration date {CertificateExpirationDate} ", "is considered invalid with {SslPolicyErrors} policy errors"), certificate.Subject, certificate.Issuer, certificate.GetCertHashString(), certificate.GetExpirationDateString(), sslPolicyErrors); if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) && chain?.ChainStatus != null) { foreach (var chainStatus in chain.ChainStatus) { _logger.LogError("Status: {Status} - {StatusInformation}", chainStatus.Status, chainStatus.StatusInformation); } } return false; } private async Task<string> SendOnlineMessage(MimeMessage message) { var secureSocketOptions = SecureSocketOptions.Auto; if (!_options.AutoSelectEncryption) { switch (_options.EncryptionMethod) { case SmtpEncryptionMethod.None: secureSocketOptions = SecureSocketOptions.None; break; case SmtpEncryptionMethod.SSLTLS: secureSocketOptions = SecureSocketOptions.SslOnConnect; break; case SmtpEncryptionMethod.STARTTLS: secureSocketOptions = SecureSocketOptions.StartTls; break; default: break; } } using (var client = new SmtpClient()) { client.ServerCertificateValidationCallback = CertificateValidationCallback; await client.ConnectAsync(_options.Host, _options.Port, secureSocketOptions); var useDefaultCredentials = _options.RequireCredentials && _options.UseDefaultCredentials; if (_options.RequireCredentials) { if (_options.UseDefaultCredentials) { // There's no notion of 'UseDefaultCredentials' in MailKit, so empty credentials is passed in await client.AuthenticateAsync(String.Empty, String.Empty); } else if (!String.IsNullOrWhiteSpace(_options.UserName)) { await client.AuthenticateAsync(_options.UserName, _options.Password); } } var response = await client.SendAsync(message); await client.DisconnectAsync(true); return response; } } private async Task SendOfflineMessage(MimeMessage message, string pickupDirectory) { var mailPath = Path.Combine(pickupDirectory, Guid.NewGuid().ToString() + EmailExtension); await message.WriteToAsync(mailPath, CancellationToken.None); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.DocumentAI.V1.Snippets { using Google.LongRunning; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedDocumentProcessorServiceClientSnippets { /// <summary>Snippet for ProcessDocument</summary> public void ProcessDocumentRequestObject() { // Snippet: ProcessDocument(ProcessRequest, CallSettings) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = DocumentProcessorServiceClient.Create(); // Initialize request argument(s) ProcessRequest request = new ProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), SkipHumanReview = false, InlineDocument = new Document(), }; // Make the request ProcessResponse response = documentProcessorServiceClient.ProcessDocument(request); // End snippet } /// <summary>Snippet for ProcessDocumentAsync</summary> public async Task ProcessDocumentRequestObjectAsync() { // Snippet: ProcessDocumentAsync(ProcessRequest, CallSettings) // Additional: ProcessDocumentAsync(ProcessRequest, CancellationToken) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync(); // Initialize request argument(s) ProcessRequest request = new ProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), SkipHumanReview = false, InlineDocument = new Document(), }; // Make the request ProcessResponse response = await documentProcessorServiceClient.ProcessDocumentAsync(request); // End snippet } /// <summary>Snippet for ProcessDocument</summary> public void ProcessDocument() { // Snippet: ProcessDocument(string, CallSettings) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = DocumentProcessorServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/processors/[PROCESSOR]"; // Make the request ProcessResponse response = documentProcessorServiceClient.ProcessDocument(name); // End snippet } /// <summary>Snippet for ProcessDocumentAsync</summary> public async Task ProcessDocumentAsync() { // Snippet: ProcessDocumentAsync(string, CallSettings) // Additional: ProcessDocumentAsync(string, CancellationToken) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/processors/[PROCESSOR]"; // Make the request ProcessResponse response = await documentProcessorServiceClient.ProcessDocumentAsync(name); // End snippet } /// <summary>Snippet for ProcessDocument</summary> public void ProcessDocumentResourceNames() { // Snippet: ProcessDocument(ProcessorName, CallSettings) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = DocumentProcessorServiceClient.Create(); // Initialize request argument(s) ProcessorName name = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"); // Make the request ProcessResponse response = documentProcessorServiceClient.ProcessDocument(name); // End snippet } /// <summary>Snippet for ProcessDocumentAsync</summary> public async Task ProcessDocumentResourceNamesAsync() { // Snippet: ProcessDocumentAsync(ProcessorName, CallSettings) // Additional: ProcessDocumentAsync(ProcessorName, CancellationToken) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync(); // Initialize request argument(s) ProcessorName name = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"); // Make the request ProcessResponse response = await documentProcessorServiceClient.ProcessDocumentAsync(name); // End snippet } /// <summary>Snippet for BatchProcessDocuments</summary> public void BatchProcessDocumentsRequestObject() { // Snippet: BatchProcessDocuments(BatchProcessRequest, CallSettings) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = DocumentProcessorServiceClient.Create(); // Initialize request argument(s) BatchProcessRequest request = new BatchProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), SkipHumanReview = false, InputDocuments = new BatchDocumentsInputConfig(), DocumentOutputConfig = new DocumentOutputConfig(), }; // Make the request Operation<BatchProcessResponse, BatchProcessMetadata> response = documentProcessorServiceClient.BatchProcessDocuments(request); // Poll until the returned long-running operation is complete Operation<BatchProcessResponse, BatchProcessMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result BatchProcessResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchProcessResponse, BatchProcessMetadata> retrievedResponse = documentProcessorServiceClient.PollOnceBatchProcessDocuments(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchProcessResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchProcessDocumentsAsync</summary> public async Task BatchProcessDocumentsRequestObjectAsync() { // Snippet: BatchProcessDocumentsAsync(BatchProcessRequest, CallSettings) // Additional: BatchProcessDocumentsAsync(BatchProcessRequest, CancellationToken) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync(); // Initialize request argument(s) BatchProcessRequest request = new BatchProcessRequest { ProcessorName = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), SkipHumanReview = false, InputDocuments = new BatchDocumentsInputConfig(), DocumentOutputConfig = new DocumentOutputConfig(), }; // Make the request Operation<BatchProcessResponse, BatchProcessMetadata> response = await documentProcessorServiceClient.BatchProcessDocumentsAsync(request); // Poll until the returned long-running operation is complete Operation<BatchProcessResponse, BatchProcessMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result BatchProcessResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchProcessResponse, BatchProcessMetadata> retrievedResponse = await documentProcessorServiceClient.PollOnceBatchProcessDocumentsAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchProcessResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchProcessDocuments</summary> public void BatchProcessDocuments() { // Snippet: BatchProcessDocuments(string, CallSettings) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = DocumentProcessorServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/processors/[PROCESSOR]"; // Make the request Operation<BatchProcessResponse, BatchProcessMetadata> response = documentProcessorServiceClient.BatchProcessDocuments(name); // Poll until the returned long-running operation is complete Operation<BatchProcessResponse, BatchProcessMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result BatchProcessResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchProcessResponse, BatchProcessMetadata> retrievedResponse = documentProcessorServiceClient.PollOnceBatchProcessDocuments(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchProcessResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchProcessDocumentsAsync</summary> public async Task BatchProcessDocumentsAsync() { // Snippet: BatchProcessDocumentsAsync(string, CallSettings) // Additional: BatchProcessDocumentsAsync(string, CancellationToken) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/processors/[PROCESSOR]"; // Make the request Operation<BatchProcessResponse, BatchProcessMetadata> response = await documentProcessorServiceClient.BatchProcessDocumentsAsync(name); // Poll until the returned long-running operation is complete Operation<BatchProcessResponse, BatchProcessMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result BatchProcessResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchProcessResponse, BatchProcessMetadata> retrievedResponse = await documentProcessorServiceClient.PollOnceBatchProcessDocumentsAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchProcessResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchProcessDocuments</summary> public void BatchProcessDocumentsResourceNames() { // Snippet: BatchProcessDocuments(ProcessorName, CallSettings) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = DocumentProcessorServiceClient.Create(); // Initialize request argument(s) ProcessorName name = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"); // Make the request Operation<BatchProcessResponse, BatchProcessMetadata> response = documentProcessorServiceClient.BatchProcessDocuments(name); // Poll until the returned long-running operation is complete Operation<BatchProcessResponse, BatchProcessMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result BatchProcessResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchProcessResponse, BatchProcessMetadata> retrievedResponse = documentProcessorServiceClient.PollOnceBatchProcessDocuments(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchProcessResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for BatchProcessDocumentsAsync</summary> public async Task BatchProcessDocumentsResourceNamesAsync() { // Snippet: BatchProcessDocumentsAsync(ProcessorName, CallSettings) // Additional: BatchProcessDocumentsAsync(ProcessorName, CancellationToken) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync(); // Initialize request argument(s) ProcessorName name = ProcessorName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"); // Make the request Operation<BatchProcessResponse, BatchProcessMetadata> response = await documentProcessorServiceClient.BatchProcessDocumentsAsync(name); // Poll until the returned long-running operation is complete Operation<BatchProcessResponse, BatchProcessMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result BatchProcessResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<BatchProcessResponse, BatchProcessMetadata> retrievedResponse = await documentProcessorServiceClient.PollOnceBatchProcessDocumentsAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result BatchProcessResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for ReviewDocument</summary> public void ReviewDocumentRequestObject() { // Snippet: ReviewDocument(ReviewDocumentRequest, CallSettings) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = DocumentProcessorServiceClient.Create(); // Initialize request argument(s) ReviewDocumentRequest request = new ReviewDocumentRequest { HumanReviewConfigAsHumanReviewConfigName = HumanReviewConfigName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), EnableSchemaValidation = false, InlineDocument = new Document(), Priority = ReviewDocumentRequest.Types.Priority.Default, }; // Make the request Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> response = documentProcessorServiceClient.ReviewDocument(request); // Poll until the returned long-running operation is complete Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result ReviewDocumentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> retrievedResponse = documentProcessorServiceClient.PollOnceReviewDocument(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ReviewDocumentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for ReviewDocumentAsync</summary> public async Task ReviewDocumentRequestObjectAsync() { // Snippet: ReviewDocumentAsync(ReviewDocumentRequest, CallSettings) // Additional: ReviewDocumentAsync(ReviewDocumentRequest, CancellationToken) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync(); // Initialize request argument(s) ReviewDocumentRequest request = new ReviewDocumentRequest { HumanReviewConfigAsHumanReviewConfigName = HumanReviewConfigName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"), EnableSchemaValidation = false, InlineDocument = new Document(), Priority = ReviewDocumentRequest.Types.Priority.Default, }; // Make the request Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> response = await documentProcessorServiceClient.ReviewDocumentAsync(request); // Poll until the returned long-running operation is complete Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result ReviewDocumentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> retrievedResponse = await documentProcessorServiceClient.PollOnceReviewDocumentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ReviewDocumentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for ReviewDocument</summary> public void ReviewDocument() { // Snippet: ReviewDocument(string, CallSettings) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = DocumentProcessorServiceClient.Create(); // Initialize request argument(s) string humanReviewConfig = "projects/[PROJECT]/locations/[LOCATION]/processors/[PROCESSOR]/humanReviewConfig"; // Make the request Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> response = documentProcessorServiceClient.ReviewDocument(humanReviewConfig); // Poll until the returned long-running operation is complete Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result ReviewDocumentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> retrievedResponse = documentProcessorServiceClient.PollOnceReviewDocument(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ReviewDocumentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for ReviewDocumentAsync</summary> public async Task ReviewDocumentAsync() { // Snippet: ReviewDocumentAsync(string, CallSettings) // Additional: ReviewDocumentAsync(string, CancellationToken) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync(); // Initialize request argument(s) string humanReviewConfig = "projects/[PROJECT]/locations/[LOCATION]/processors/[PROCESSOR]/humanReviewConfig"; // Make the request Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> response = await documentProcessorServiceClient.ReviewDocumentAsync(humanReviewConfig); // Poll until the returned long-running operation is complete Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result ReviewDocumentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> retrievedResponse = await documentProcessorServiceClient.PollOnceReviewDocumentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ReviewDocumentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for ReviewDocument</summary> public void ReviewDocumentResourceNames() { // Snippet: ReviewDocument(HumanReviewConfigName, CallSettings) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = DocumentProcessorServiceClient.Create(); // Initialize request argument(s) HumanReviewConfigName humanReviewConfig = HumanReviewConfigName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"); // Make the request Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> response = documentProcessorServiceClient.ReviewDocument(humanReviewConfig); // Poll until the returned long-running operation is complete Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result ReviewDocumentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> retrievedResponse = documentProcessorServiceClient.PollOnceReviewDocument(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ReviewDocumentResponse retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for ReviewDocumentAsync</summary> public async Task ReviewDocumentResourceNamesAsync() { // Snippet: ReviewDocumentAsync(HumanReviewConfigName, CallSettings) // Additional: ReviewDocumentAsync(HumanReviewConfigName, CancellationToken) // Create client DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync(); // Initialize request argument(s) HumanReviewConfigName humanReviewConfig = HumanReviewConfigName.FromProjectLocationProcessor("[PROJECT]", "[LOCATION]", "[PROCESSOR]"); // Make the request Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> response = await documentProcessorServiceClient.ReviewDocumentAsync(humanReviewConfig); // Poll until the returned long-running operation is complete Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result ReviewDocumentResponse result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<ReviewDocumentResponse, ReviewDocumentOperationMetadata> retrievedResponse = await documentProcessorServiceClient.PollOnceReviewDocumentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result ReviewDocumentResponse retrievedResult = retrievedResponse.Result; } // End snippet } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Infrastructure; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.SignalR.Messaging { public class MessageBus : IMessageBus, IDisposable { private readonly MessageBroker _broker; // The size of the messages store we allocate per topic. private readonly uint _messageStoreSize; // By default, topics are cleaned up after having no subscribers and after // an interval based on the disconnect timeout has passed. While this works in normal cases // it's an issue when the rate of incoming connections is too high. // This is the maximum number of un-expired topics with no subscribers // we'll leave hanging around. The rest will be cleaned up on an the gc interval. private readonly int _maxTopicsWithNoSubscriptions; private readonly IStringMinifier _stringMinifier; private readonly ILogger _logger; private readonly ILoggerFactory _loggerFactory; private Timer _gcTimer; private int _gcRunning; private static readonly TimeSpan _gcInterval = TimeSpan.FromSeconds(5); private readonly TimeSpan _topicTtl; // For unit testing internal Action<string, Topic> BeforeTopicGarbageCollected; internal Action<string, Topic> AfterTopicGarbageCollected; internal Action<string, Topic> BeforeTopicMarked; internal Action<string> BeforeTopicCreated; internal Action<string, Topic> AfterTopicMarkedSuccessfully; internal Action<string, Topic, int> AfterTopicMarked; private readonly Func<string, Topic> _createTopic; private readonly Action<ISubscriber, string> _addEvent; private readonly Action<ISubscriber, string> _removeEvent; private readonly Action<object> _disposeSubscription; [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The message broker is disposed when the bus is disposed.")] public MessageBus(IStringMinifier stringMinifier, ILoggerFactory loggerFactory, IPerformanceCounterManager performanceCounterManager, IOptions<MessageBusOptions> optionsAccessor) { if (stringMinifier == null) { throw new ArgumentNullException("stringMinifier"); } if (loggerFactory == null) { throw new ArgumentNullException("traceManager"); } if (performanceCounterManager == null) { throw new ArgumentNullException("performanceCounterManager"); } if (optionsAccessor == null) { throw new ArgumentNullException("optionsAccessor"); } var options = optionsAccessor.Value; if (options.MessageBufferSize < 0) { throw new ArgumentOutOfRangeException(Resources.Error_BufferSizeOutOfRange); } _stringMinifier = stringMinifier; _loggerFactory = loggerFactory; Counters = performanceCounterManager; _logger = _loggerFactory.CreateLogger<MessageBus>(); _maxTopicsWithNoSubscriptions = options.MaxTopicsWithNoSubscriptions; _gcTimer = new Timer(_ => GarbageCollectTopics(), state: null, dueTime: _gcInterval, period: _gcInterval); _broker = new MessageBroker(Counters) { Logger = _logger }; // The default message store size _messageStoreSize = (uint)options.MessageBufferSize; _topicTtl = options.TopicTTL; _createTopic = CreateTopic; _addEvent = AddEvent; _removeEvent = RemoveEvent; _disposeSubscription = o => DisposeSubscription(o); Topics = new TopicLookup(); } protected internal TopicLookup Topics { get; private set; } protected IPerformanceCounterManager Counters { get; private set; } /// <summary> /// Publishes a new message to the specified event on the bus. /// </summary> /// <param name="message">The message to publish.</param> public virtual Task Publish(Message message) { if (message == null) { throw new ArgumentNullException("message"); } Topic topic; if (Topics.TryGetValue(message.Key, out topic)) { topic.Store.Add(message); ScheduleTopic(topic); } Counters.MessageBusMessagesPublishedTotal.Increment(); Counters.MessageBusMessagesPublishedPerSec.Increment(); return TaskAsyncHelper.Empty; } protected ulong Save(Message message) { if (message == null) { throw new ArgumentNullException("message"); } // GetTopic will return a topic for the given key. If topic exists and is Dying, // it will revive it and mark it as NoSubscriptions Topic topic = GetTopic(message.Key); // Mark the topic as used so it doesn't immediately expire (if it was in that state before). topic.MarkUsed(); return topic.Store.Add(message); } /// <summary> /// /// </summary> /// <param name="subscriber"></param> /// <param name="cursor"></param> /// <param name="callback"></param> /// <param name="maxMessages"></param> /// <param name="state"></param> /// <returns></returns> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The disposable object is returned to the caller")] public virtual IDisposable Subscribe(ISubscriber subscriber, string cursor, Func<MessageResult, object, Task<bool>> callback, int maxMessages, object state) { if (subscriber == null) { throw new ArgumentNullException("subscriber"); } if (callback == null) { throw new ArgumentNullException("callback"); } Subscription subscription = CreateSubscription(subscriber, cursor, callback, maxMessages, state); // Set the subscription for this subscriber subscriber.Subscription = subscription; var topics = new HashSet<Topic>(); foreach (var key in subscriber.EventKeys) { // Create or retrieve topic and set it as HasSubscriptions Topic topic = SubscribeTopic(key); // Set the subscription for this topic subscription.SetEventTopic(key, topic); topics.Add(topic); } subscriber.EventKeyAdded += _addEvent; subscriber.EventKeyRemoved += _removeEvent; subscriber.WriteCursor = subscription.WriteCursor; var subscriptionState = new SubscriptionState(subscriber); var disposable = new DisposableAction(_disposeSubscription, subscriptionState); // When the subscription itself is disposed then dispose it subscription.Disposable = disposable; // Add the subscription when it's all set and can be scheduled // for work. It's important to do this after everything is wired up for the // subscription so that publishes can schedule work at the right time. foreach (var topic in topics) { topic.AddSubscription(subscription); } subscriptionState.Initialized.Set(); // If there's a cursor then schedule work for this subscription if (!String.IsNullOrEmpty(cursor)) { _broker.Schedule(subscription); } return disposable; } [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Justification = "Called from derived class")] protected virtual Subscription CreateSubscription(ISubscriber subscriber, string cursor, Func<MessageResult, object, Task<bool>> callback, int messageBufferSize, object state) { return new DefaultSubscription(subscriber.Identity, subscriber.EventKeys, Topics, cursor, callback, messageBufferSize, _stringMinifier, Counters, state); } protected void ScheduleEvent(string eventKey) { Topic topic; if (Topics.TryGetValue(eventKey, out topic)) { ScheduleTopic(topic); } } private void ScheduleTopic(Topic topic) { try { topic.SubscriptionLock.EnterReadLock(); for (int i = 0; i < topic.Subscriptions.Count; i++) { ISubscription subscription = topic.Subscriptions[i]; _broker.Schedule(subscription); } } finally { topic.SubscriptionLock.ExitReadLock(); } } /// <summary> /// Creates a topic for the specified key. /// </summary> /// <param name="key">The key to create the topic for.</param> /// <returns>A <see cref="Topic"/> for the specified key.</returns> protected virtual Topic CreateTopic(string key) { // REVIEW: This can be called multiple times, should we guard against it? Counters.MessageBusTopicsCurrent.Increment(); return new Topic(_messageStoreSize, _topicTtl); } protected virtual void Dispose(bool disposing) { if (disposing && _gcRunning != GCState.Disposed) { // Stop the broker from doing any work _broker.Dispose(); // Spin while we wait for the timer to finish if it's currently running while (Interlocked.CompareExchange(ref _gcRunning, GCState.Disposed, GCState.Idle) == GCState.Running) { Thread.Sleep(250); } // Remove all topics Topics.Clear(); if (_gcTimer != null) { _gcTimer.Dispose(); } } } public void Dispose() { Dispose(true); } internal void GarbageCollectTopics() { if (Interlocked.CompareExchange(ref _gcRunning, GCState.Running, GCState.Idle) != GCState.Idle) { return; } int topicsWithNoSubs = 0; foreach (var pair in Topics) { if (pair.Value.IsExpired) { if (BeforeTopicGarbageCollected != null) { BeforeTopicGarbageCollected(pair.Key, pair.Value); } // Mark the topic as dead DestroyTopic(pair.Key, pair.Value); } else if (pair.Value.State == TopicState.NoSubscriptions) { // Keep track of the number of topics with no subscriptions topicsWithNoSubs++; } } int overflow = topicsWithNoSubs - _maxTopicsWithNoSubscriptions; if (overflow > 0) { // If we've overflowed the max the collect topics that don't have // subscribers var candidates = new List<KeyValuePair<string, Topic>>(); foreach (var pair in Topics) { if (pair.Value.State == TopicState.NoSubscriptions) { candidates.Add(pair); } } // We want to remove the overflow but oldest first candidates.Sort((leftPair, rightPair) => leftPair.Value.LastUsed.CompareTo(rightPair.Value.LastUsed)); // Clear up to the overflow and stay within bounds for (int i = 0; i < overflow && i < candidates.Count; i++) { var pair = candidates[i]; // We only want to kill the topic if it's in the NoSubscriptions or Dying state. if (InterlockedHelper.CompareExchangeOr(ref pair.Value.State, TopicState.Dead, TopicState.NoSubscriptions, TopicState.Dying)) { // Kill it DestroyTopicCore(pair.Key, pair.Value); } } } Interlocked.CompareExchange(ref _gcRunning, GCState.Idle, GCState.Running); } private void DestroyTopic(string key, Topic topic) { // The goal of this function is to destroy topics after 2 garbage collect cycles // This first if statement will transition a topic into the dying state on the first GC cycle // but it will prevent the code path from hitting the second if statement if (Interlocked.CompareExchange(ref topic.State, TopicState.Dying, TopicState.NoSubscriptions) == TopicState.Dying) { // If we've hit this if statement we're on the second GC cycle with this soon to be // destroyed topic. At this point we move the Topic State into the Dead state as // long as it has not been revived from the dying state. We check if the state is // still dying again to ensure that the topic has not been transitioned into a new // state since we've decided to destroy it. if (Interlocked.CompareExchange(ref topic.State, TopicState.Dead, TopicState.Dying) == TopicState.Dying) { DestroyTopicCore(key, topic); } } } private void DestroyTopicCore(string key, Topic topic) { Topics.TryRemove(key); _stringMinifier.RemoveUnminified(key); Counters.MessageBusTopicsCurrent.Decrement(); _logger.LogInformation("RemoveTopic(" + key + ")"); if (AfterTopicGarbageCollected != null) { AfterTopicGarbageCollected(key, topic); } } internal Topic GetTopic(string key) { Topic topic; int oldState; do { if (BeforeTopicCreated != null) { BeforeTopicCreated(key); } topic = Topics.GetOrAdd(key, _createTopic); if (BeforeTopicMarked != null) { BeforeTopicMarked(key, topic); } // If the topic was dying revive it to the NoSubscriptions state. This is used to ensure // that in the scaleout case that even if we're publishing to a topic with no subscriptions // that we keep it around in case a user hops nodes. oldState = Interlocked.CompareExchange(ref topic.State, TopicState.NoSubscriptions, TopicState.Dying); if (AfterTopicMarked != null) { AfterTopicMarked(key, topic, topic.State); } // If the topic is currently dead then we're racing with the DestroyTopicCore function, therefore // loop around until we're able to create a new topic } while (oldState == TopicState.Dead); if (AfterTopicMarkedSuccessfully != null) { AfterTopicMarkedSuccessfully(key, topic); } return topic; } internal Topic SubscribeTopic(string key) { Topic topic; do { if (BeforeTopicCreated != null) { BeforeTopicCreated(key); } topic = Topics.GetOrAdd(key, _createTopic); if (BeforeTopicMarked != null) { BeforeTopicMarked(key, topic); } // Transition into the HasSubscriptions state as long as the topic is not dead InterlockedHelper.CompareExchangeOr(ref topic.State, TopicState.HasSubscriptions, TopicState.NoSubscriptions, TopicState.Dying); if (AfterTopicMarked != null) { AfterTopicMarked(key, topic, topic.State); } // If we were unable to transition into the HasSubscription state that means we're in the Dead state. // Loop around until we're able to create the topic new } while (topic.State != TopicState.HasSubscriptions); if (AfterTopicMarkedSuccessfully != null) { AfterTopicMarkedSuccessfully(key, topic); } return topic; } private void AddEvent(ISubscriber subscriber, string eventKey) { Topic topic = SubscribeTopic(eventKey); // Add or update the cursor (in case it already exists) if (subscriber.Subscription.AddEvent(eventKey, topic)) { // Add it to the list of subs topic.AddSubscription(subscriber.Subscription); } } private void RemoveEvent(ISubscriber subscriber, string eventKey) { Topic topic; if (Topics.TryGetValue(eventKey, out topic)) { topic.RemoveSubscription(subscriber.Subscription); subscriber.Subscription.RemoveEvent(eventKey); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Failure to invoke the callback should be ignored")] private void DisposeSubscription(object state) { var subscriptionState = (SubscriptionState)state; var subscriber = subscriptionState.Subscriber; // This will stop work from continuting to happen subscriber.Subscription.Dispose(); try { // Invoke the terminal callback subscriber.Subscription.Invoke(MessageResult.TerminalMessage).Wait(); } catch { // We failed to talk to the subscriber because they are already gone // so the terminal message isn't required. } subscriptionState.Initialized.Wait(); subscriber.EventKeyAdded -= _addEvent; subscriber.EventKeyRemoved -= _removeEvent; subscriber.WriteCursor = null; for (int i = subscriber.EventKeys.Count - 1; i >= 0; i--) { string eventKey = subscriber.EventKeys[i]; RemoveEvent(subscriber, eventKey); } } private class SubscriptionState { public ISubscriber Subscriber { get; private set; } public ManualResetEventSlim Initialized { get; private set; } public SubscriptionState(ISubscriber subscriber) { Initialized = new ManualResetEventSlim(); Subscriber = subscriber; } } private static class GCState { public const int Idle = 0; public const int Running = 1; public const int Disposed = 2; } } }
// 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; #pragma warning disable 0067 // Unused event namespace System.Reflection.Tests { public class TypeInfoMethodTests { // Verify AsType() method [Fact] public static void TestAsType1() { Type runtimeType = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = runtimeType.GetTypeInfo(); Type type = typeInfo.AsType(); Assert.Equal(runtimeType, type); } // Verify AsType() method [Fact] public static void TestAsType2() { Type runtimeType = typeof(MethodPublicClass.PublicNestedType).Project(); TypeInfo typeInfo = runtimeType.GetTypeInfo(); Type type = typeInfo.AsType(); Assert.Equal(runtimeType, type); } // Verify GetArrayRank() method [Fact] public static void TestGetArrayRank1() { int[] myArray = { 1, 2, 3, 4, 5, 6, 7 }; int expectedRank = 1; Type type = myArray.GetType(); TypeInfo typeInfo = type.GetTypeInfo(); int rank = typeInfo.GetArrayRank(); Assert.Equal(expectedRank, rank); } // Verify GetArrayRank() method [Fact] public static void TestGetArrayRank2() { string[] myArray = { "hello" }; int expectedRank = 1; Type type = myArray.GetType(); TypeInfo typeInfo = type.GetTypeInfo(); int rank = typeInfo.GetArrayRank(); Assert.Equal(expectedRank, rank); } // Verify GetDeclaredEvent() method [Fact] public static void TestGetDeclaredEvent1() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); VerifyGetDeclaredEvent(typeInfo, "EventPublic"); } // Verify GetDeclaredEvent() method [Fact] public static void TestGetDeclaredEvent2() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); EventInfo ei = typeInfo.GetDeclaredEvent("NoSuchEvent"); Assert.Null(ei); } // Verify GetDeclaredEvent() method [Fact] public static void TestGetDeclaredEvent3() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); Assert.Throws<ArgumentNullException>(() => { EventInfo ei = typeInfo.GetDeclaredEvent(null); }); } // Verify GetDeclaredField() method [Fact] public static void TestGetDeclaredField1() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); VerifyGetDeclaredField(typeInfo, "PublicField"); } // Verify GetDeclaredField() method [Fact] public static void TestGetDeclaredField2() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); VerifyGetDeclaredField(typeInfo, "PublicStaticField"); } // Verify GetDeclaredField() method [Fact] public static void TestGetDeclaredField3() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); FieldInfo fi = typeInfo.GetDeclaredField("NoSuchField"); Assert.Null(fi); } // Verify GetDeclaredField() method [Fact] public static void TestGetDeclaredField4() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); Assert.Throws<ArgumentNullException>(() => { FieldInfo fi = typeInfo.GetDeclaredField(null); }); } // Verify GetDeclaredMethod() method [Fact] public static void TestGetDeclaredMethod1() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); VerifyGetDeclaredMethod(typeInfo, "PublicMethod"); } // Verify GetDeclaredMethod() method [Fact] public static void TestGetDeclaredMethod2() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); VerifyGetDeclaredMethod(typeInfo, "PublicStaticMethod"); } // Verify GetDeclaredMethod() method [Fact] public static void TestGetDeclaredMethod3() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); MethodInfo mi = typeInfo.GetDeclaredMethod("NoSuchMethod"); Assert.Null(mi); } // Verify GetDeclaredMethod() method [Fact] public static void TestGetDeclaredMethod4() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); Assert.Throws<ArgumentNullException>(() => { MethodInfo mi = typeInfo.GetDeclaredMethod(null); }); } // Verify GetDeclaredMethods() method [Fact] public static void TestGetDeclaredMethods1() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); VerifyGetDeclaredMethods(typeInfo, "overRiddenMethod", 4); } // Verify GetDeclaredMethods() method [Fact] public static void TestGetDeclaredMethods2() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); VerifyGetDeclaredMethods(typeInfo, "NoSuchMethod", 0); } // Verify GetDeclaredNestedType() method [Fact] public static void TestGetDeclaredNestedType1() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); VerifyGetDeclaredNestedType(typeInfo, "PublicNestedType"); } // Verify GetDeclaredNestedType() method [Fact] public static void TestGetDeclaredNestedType2() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); TypeInfo nested_ti = typeInfo.GetDeclaredNestedType("NoSuchType"); Assert.Null(nested_ti); } // Verify GetDeclaredNestedType() method [Fact] public static void TestGetDeclaredNestedType3() { Type type = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = type.GetTypeInfo(); Assert.Throws<ArgumentNullException>(() => { TypeInfo nested_ti = typeInfo.GetDeclaredNestedType(null); }); } // Verify GetElementType() method [Fact] public static void TestGetElementType1() { Type runtimeType = typeof(MethodPublicClass).Project(); TypeInfo typeInfo = runtimeType.GetTypeInfo(); Type type = typeInfo.GetElementType(); Assert.Null(type); } // Verify GetElementType() method [Fact] public static void TestGetElementType2() { string[] myArray = { "a", "b", "c" }; Type runtimeType = myArray.GetType(); TypeInfo typeInfo = runtimeType.GetTypeInfo(); Type type = typeInfo.GetElementType(); Assert.NotNull(type); Assert.Equal(typeof(string).Project().Name, type.Name); } // Verify GetElementType() method [Fact] public static void TestGetElementType3() { int[] myArray = { 1, 2, 3, 4 }; Type runtimeType = myArray.GetType(); TypeInfo typeInfo = runtimeType.GetTypeInfo(); Type type = typeInfo.GetElementType(); Assert.NotNull(type); Assert.Equal(typeof(int).Project().Name, type.Name); } // Verify GetGenericParameterConstraints() method [Fact] public static void TestGetGenericParameterConstraints1() { Type def = typeof(TypeInfoMethodClassWithConstraints<,>).Project(); TypeInfo ti = def.GetTypeInfo(); Type[] defparams = ti.GenericTypeParameters; Assert.Equal(2, defparams.Length); Type[] tpConstraints = defparams[0].GetTypeInfo().GetGenericParameterConstraints(); Assert.Equal(2, tpConstraints.Length); Assert.Equal(typeof(TypeInfoMethodBase).Project(), tpConstraints[0]); Assert.Equal(typeof(MethodITest).Project(), tpConstraints[1]); } // Verify GetGenericParameterConstraints() method [Fact] public static void TestGetGenericParameterConstraints2() { Type def = typeof(TypeInfoMethodClassWithConstraints<,>).Project(); TypeInfo ti = def.GetTypeInfo(); Type[] defparams = ti.GenericTypeParameters; Assert.Equal(2, defparams.Length); Type[] tpConstraints = defparams[1].GetTypeInfo().GetGenericParameterConstraints(); Assert.Equal(0, tpConstraints.Length); } // Verify GetGenericTypeDefinition() method [Fact] public static void TestGetGenericTypeDefinition() { TypeInfoMethodGenericClass<int> genericObj = new TypeInfoMethodGenericClass<int>(); Type type = genericObj.GetType().Project(); Type generictype = type.GetTypeInfo().GetGenericTypeDefinition(); Assert.NotNull(generictype); Assert.Equal(typeof(TypeInfoMethodGenericClass<>).Project(), generictype); } // Verify IsSubClassOf() method [Fact] public static void TestIsSubClassOf1() { TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo(); TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo(); bool isSubClass = t1.IsSubclassOf(t2.AsType()); Assert.False(isSubClass); } // Verify IsSubClassOf() method [Fact] public static void TestIsSubClassOf2() { TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo(); TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo(); bool isSubClass = t2.IsSubclassOf(t1.AsType()); Assert.True(isSubClass, "Failed! isSubClass returned False when this class derives from input class "); } // Verify IsAssignableFrom() method [Fact] public static void TestIsAssignableFrom1() { TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo(); TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo(); bool isAssignable = t1.IsAssignableFrom(t2); Assert.True(isAssignable, "Failed! IsAssignableFrom returned False"); } // Verify IsAssignableFrom() method [Fact] public static void TestIsAssignableFrom2() { TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo(); TypeInfo t2 = typeof(TypeInfoMethodDerived).Project().GetTypeInfo(); bool isAssignable = t2.IsAssignableFrom(t1); Assert.False(isAssignable, "Failed! IsAssignableFrom returned True"); } // Verify IsAssignableFrom() method [Fact] public static void TestIsAssignableFrom3() { TypeInfo t1 = typeof(TypeInfoMethodBase).Project().GetTypeInfo(); TypeInfo t2 = typeof(TypeInfoMethodBase).Project().GetTypeInfo(); bool isAssignable = t2.IsAssignableFrom(t2); Assert.True(isAssignable, "Failed! IsAssignableFrom returned False for same Type"); } // Verify IsAssignableFrom() method [Fact] public static void TestIsAssignableFrom4() { TypeInfo t1 = typeof(MethodITest).Project().GetTypeInfo(); TypeInfo t2 = typeof(TypeInfoMethodImplClass).Project().GetTypeInfo(); bool isAssignable = t1.IsAssignableFrom(t2); Assert.True(isAssignable, "Failed! IsAssignableFrom returned False"); } // Verify MakeArrayType() method [Fact] public static void TestMakeArrayType1() { TypeInfo ti = typeof(string).Project().GetTypeInfo(); Type arraytype = ti.MakeArrayType(); string[] strArray = { "a", "b", "c" }; Assert.NotNull(arraytype); Assert.Equal(strArray.GetType().Project(), arraytype); } // Verify MakeArrayType() method [Fact] public static void TestMakeArrayType2() { TypeInfo ti = typeof(int).Project().GetTypeInfo(); Type arraytype = ti.MakeArrayType(); int[] intArray = { 1, 2, 3 }; Assert.NotNull(arraytype); Assert.Equal(intArray.GetType().Project(), arraytype); } // Verify MakeArrayType(int rank) method [Fact] public static void TestMakeArrayTypeWithRank1() { TypeInfo ti = typeof(string).Project().GetTypeInfo(); Type arraytype = ti.MakeArrayType(1); Assert.NotNull(arraytype); Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array"); } // Verify MakeArrayType(int rank) method [Fact] public static void TestMakeArrayTypeWithRank2() { GC.KeepAlive(typeof(int[,]).Project()); TypeInfo ti = typeof(int).Project().GetTypeInfo(); Type arraytype = ti.MakeArrayType(2); Assert.NotNull(arraytype); Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array"); } // Verify MakeArrayType() method [Fact] public static void TestMakeArrayOfPointerType1() { TypeInfo ti = typeof(char*).Project().GetTypeInfo(); Type arraytype = ti.MakeArrayType(3); Assert.NotNull(arraytype); Assert.True(arraytype.IsArray); Assert.Equal(3, arraytype.GetArrayRank()); Assert.Equal(arraytype.GetElementType(), typeof(char*).Project()); } // Verify MakeArrayType(int rank) method [Fact] public static void TestMakeArrayTypeWithRank3() { GC.KeepAlive(typeof(int[,,]).Project()); TypeInfo ti = typeof(int).Project().GetTypeInfo(); Type arraytype = ti.MakeArrayType(3); Assert.NotNull(arraytype); Assert.True(arraytype.IsArray, "Failed!! MakeArrayType() returned type that is not Array"); } // Verify MakeByRefType method [Fact] public static void TestMakeByRefType1() { TypeInfo ti = typeof(int).Project().GetTypeInfo(); Type byreftype = ti.MakeByRefType(); Assert.NotNull(byreftype); Assert.True(byreftype.IsByRef, "Failed!! MakeByRefType() returned type that is not ByRef"); } // Verify MakeByRefType method [Fact] public static void TestMakeByRefType2() { TypeInfo ti = typeof(string).Project().GetTypeInfo(); Type byreftype = ti.MakeByRefType(); Assert.NotNull(byreftype); Assert.True(byreftype.IsByRef, "Failed!! MakeByRefType() returned type that is not ByRef"); } // Verify MakePointerType method [Fact] public static void TestMakePointerType1() { TypeInfo ti = typeof(int).Project().GetTypeInfo(); Type ptrtype = ti.MakePointerType(); Assert.NotNull(ptrtype); Assert.True(ptrtype.IsPointer, "Failed!! MakePointerType() returned type that is not Pointer"); } // Verify MakePointerType method [Fact] public static void TestMakePointerType2() { TypeInfo ti = typeof(string).Project().GetTypeInfo(); Type ptrtype = ti.MakePointerType(); Assert.NotNull(ptrtype); Assert.True(ptrtype.IsPointer, "Failed!! MakePointerType() returned type that is not Pointer"); } // Verify MakeGenericType() method [Fact] public static void TestMakeGenericType() { Type type = typeof(List<>).Project(); Type[] typeArgs = { typeof(string).Project() }; TypeInfo typeInfo = type.GetTypeInfo(); Type generictype = typeInfo.MakeGenericType(typeArgs); Assert.NotNull(generictype); Assert.True(generictype.GetTypeInfo().IsGenericType, "Failed!! MakeGenericType() returned type that is not generic"); } // Verify ToString() method [Fact] public static void TestToString1() { Type type = typeof(string).Project(); TypeInfo typeInfo = type.GetTypeInfo(); Assert.Equal("System.String", typeInfo.ToString()); } // Verify ToString() method [Fact] public static void TestToString2() { Type type = typeof(int).Project(); TypeInfo typeInfo = type.GetTypeInfo(); Assert.Equal("System.Int32", typeInfo.ToString()); } //Private Helper Methods private static void VerifyGetDeclaredEvent(TypeInfo ti, string eventName) { EventInfo ei = ti.GetDeclaredEvent(eventName); Assert.NotNull(ei); Assert.Equal(eventName, ei.Name); } private static void VerifyGetDeclaredField(TypeInfo ti, string fieldName) { FieldInfo fi = ti.GetDeclaredField(fieldName); Assert.NotNull(fi); Assert.Equal(fieldName, fi.Name); } private static void VerifyGetDeclaredMethod(TypeInfo ti, string methodName) { MethodInfo mi = ti.GetDeclaredMethod(methodName); Assert.NotNull(mi); Assert.Equal(methodName, mi.Name); } private static void VerifyGetDeclaredMethods(TypeInfo ti, string methodName, int count) { IEnumerator<MethodInfo> alldefinedMethods = ti.GetDeclaredMethods(methodName).GetEnumerator(); MethodInfo mi = null; int numMethods = 0; while (alldefinedMethods.MoveNext()) { mi = alldefinedMethods.Current; Assert.Equal(methodName, mi.Name); numMethods++; } Assert.Equal(count, numMethods); } private static void VerifyGetDeclaredNestedType(TypeInfo ti, string name) { TypeInfo nested_ti = ti.GetDeclaredNestedType(name); Assert.NotNull(nested_ti); Assert.Equal(name, nested_ti.Name); } private static void VerifyGetDeclaredProperty(TypeInfo ti, string name) { PropertyInfo pi = ti.GetDeclaredProperty(name); Assert.NotNull(pi); Assert.Equal(name, pi.Name); } } //Metadata for Reflection public class MethodPublicClass { public int PublicField; public static int PublicStaticField; public MethodPublicClass() { } public void PublicMethod() { } public void overRiddenMethod() { } public void overRiddenMethod(int i) { } public void overRiddenMethod(string s) { } public void overRiddenMethod(object o) { } public static void PublicStaticMethod() { } public class PublicNestedType { } public int PublicProperty { get { return default(int); } set { } } public event System.EventHandler EventPublic; } public interface MethodITest { } public class TypeInfoMethodBase { } public class TypeInfoMethodDerived : TypeInfoMethodBase { } public class TypeInfoMethodImplClass : MethodITest { } public class TypeInfoMethodGenericClass<T> { } public class TypeInfoMethodClassWithConstraints<T, U> where T : TypeInfoMethodBase, MethodITest where U : class, new() { } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.3.34. Three double precision floating point values, x, y, and z /// </summary> [Serializable] [XmlRoot] public partial class Vector3Double { /// <summary> /// X value /// </summary> private double _x; /// <summary> /// Y value /// </summary> private double _y; /// <summary> /// Z value /// </summary> private double _z; /// <summary> /// Initializes a new instance of the <see cref="Vector3Double"/> class. /// </summary> public Vector3Double() { } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(Vector3Double left, Vector3Double right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(Vector3Double left, Vector3Double right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 8; // this._x marshalSize += 8; // this._y marshalSize += 8; // this._z return marshalSize; } /// <summary> /// Gets or sets the X value /// </summary> [XmlElement(Type = typeof(double), ElementName = "x")] public double X { get { return this._x; } set { this._x = value; } } /// <summary> /// Gets or sets the Y value /// </summary> [XmlElement(Type = typeof(double), ElementName = "y")] public double Y { get { return this._y; } set { this._y = value; } } /// <summary> /// Gets or sets the Z value /// </summary> [XmlElement(Type = typeof(double), ElementName = "z")] public double Z { get { return this._z; } set { this._z = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { dos.WriteDouble((double)this._x); dos.WriteDouble((double)this._y); dos.WriteDouble((double)this._z); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { this._x = dis.ReadDouble(); this._y = dis.ReadDouble(); this._z = dis.ReadDouble(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public virtual void Reflection(StringBuilder sb) { sb.AppendLine("<Vector3Double>"); try { sb.AppendLine("<x type=\"double\">" + this._x.ToString(CultureInfo.InvariantCulture) + "</x>"); sb.AppendLine("<y type=\"double\">" + this._y.ToString(CultureInfo.InvariantCulture) + "</y>"); sb.AppendLine("<z type=\"double\">" + this._z.ToString(CultureInfo.InvariantCulture) + "</z>"); sb.AppendLine("</Vector3Double>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as Vector3Double; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(Vector3Double obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (this._x != obj._x) { ivarsEqual = false; } if (this._y != obj._y) { ivarsEqual = false; } if (this._z != obj._z) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ this._x.GetHashCode(); result = GenerateHash(result) ^ this._y.GetHashCode(); result = GenerateHash(result) ^ this._z.GetHashCode(); return result; } } }
// 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 ConvertToInt64Vector128Int64() { var test = new SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Int64(); 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(); // 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(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Int64 { private struct TestStruct { public Vector128<Int64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); return testStruct; } public void RunStructFldScenario(SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Int64 testClass) { var result = Sse2.X64.ConvertToInt64(_fld); testClass.ValidateResult(_fld, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector128<Int64> _clsVar; private Vector128<Int64> _fld; private SimdScalarUnaryOpTest__DataTable<Int64> _dataTable; static SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Int64() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); } public SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Int64() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimdScalarUnaryOpTest__DataTable<Int64>(_data, LargestVectorSize); } public bool IsSupported => Sse2.X64.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.X64.ConvertToInt64( Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.X64.ConvertToInt64( Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.X64.ConvertToInt64( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)) ); ValidateResult(_dataTable.inArrayPtr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertToInt64), new Type[] { typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr) }); ValidateResult(_dataTable.inArrayPtr, (Int64)(result)); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertToInt64), new Type[] { typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)) }); ValidateResult(_dataTable.inArrayPtr, (Int64)(result)); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertToInt64), new Type[] { typeof(Vector128<Int64>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)) }); ValidateResult(_dataTable.inArrayPtr, (Int64)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.X64.ConvertToInt64( _clsVar ); ValidateResult(_clsVar, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Int64>>(_dataTable.inArrayPtr); var result = Sse2.X64.ConvertToInt64(firstOp); ValidateResult(firstOp, result); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse2.X64.ConvertToInt64(firstOp); ValidateResult(firstOp, result); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArrayPtr)); var result = Sse2.X64.ConvertToInt64(firstOp); ValidateResult(firstOp, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimdScalarUnaryOpConvertTest__ConvertToInt64Vector128Int64(); var result = Sse2.X64.ConvertToInt64(test._fld); ValidateResult(test._fld, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.X64.ConvertToInt64(_fld); ValidateResult(_fld, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.X64.ConvertToInt64(test._fld); ValidateResult(test._fld, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(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<Int64> firstOp, Int64 result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); ValidateResult(inArray, result, method); } private void ValidateResult(void* firstOp, Int64 result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, result, method); } private void ValidateResult(Int64[] firstOp, Int64 result, [CallerMemberName] string method = "") { bool succeeded = true; if (firstOp[0] != result) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2.X64)}.{nameof(Sse2.X64.ConvertToInt64)}<Int64>(Vector128<Int64>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: result"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using GeckoUBL.Ubl21.Udt; namespace GeckoUBL.Ubl21.Cac { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] [System.Xml.Serialization.XmlRootAttribute("AttachedTransportEquipment", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable=false)] public class TransportEquipmentType { /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType ID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ReferencedConsignmentID", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType[] ReferencedConsignmentID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType TransportEquipmentTypeCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType ProviderTypeCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType OwnerTypeCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType SizeTypeCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType DispositionCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType FullnessIndicationCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType RefrigerationOnIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Information", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType[] Information { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType ReturnabilityIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType LegalStatusIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public PercentType AirFlowPercent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public PercentType HumidityPercent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType AnimalFoodApprovedIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType HumanFoodApprovedIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType DangerousGoodsApprovedIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType RefrigeratedIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType Characteristics { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("DamageRemarks", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType[] DamageRemarks { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Description", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType[] Description { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("SpecialTransportRequirements", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType[] SpecialTransportRequirements { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public MeasureType GrossWeightMeasure { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public MeasureType GrossVolumeMeasure { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public MeasureType TareWeightMeasure { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType TrackingDeviceCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType PowerIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType TraceID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("MeasurementDimension")] public DimensionType[] MeasurementDimension { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("TransportEquipmentSeal")] public TransportEquipmentSealType[] TransportEquipmentSeal { get; set; } /// <remarks/> public TemperatureType MinimumTemperature { get; set; } /// <remarks/> public TemperatureType MaximumTemperature { get; set; } /// <remarks/> public PartyType ProviderParty { get; set; } /// <remarks/> public PartyType LoadingProofParty { get; set; } /// <remarks/> public SupplierPartyType SupplierParty { get; set; } /// <remarks/> public PartyType OwnerParty { get; set; } /// <remarks/> public PartyType OperatingParty { get; set; } /// <remarks/> public LocationType1 LoadingLocation { get; set; } /// <remarks/> public LocationType1 UnloadingLocation { get; set; } /// <remarks/> public LocationType1 StorageLocation { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("PositioningTransportEvent")] public TransportEventType[] PositioningTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("QuarantineTransportEvent")] public TransportEventType[] QuarantineTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("DeliveryTransportEvent")] public TransportEventType[] DeliveryTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("PickupTransportEvent")] public TransportEventType[] PickupTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("HandlingTransportEvent")] public TransportEventType[] HandlingTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("LoadingTransportEvent")] public TransportEventType[] LoadingTransportEvent { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("TransportEvent")] public TransportEventType[] TransportEvent { get; set; } /// <remarks/> public TransportMeansType ApplicableTransportMeans { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("HaulageTradingTerms")] public TradingTermsType[] HaulageTradingTerms { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("HazardousGoodsTransit")] public HazardousGoodsTransitType[] HazardousGoodsTransit { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("PackagedTransportHandlingUnit")] public TransportHandlingUnitType[] PackagedTransportHandlingUnit { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ServiceAllowanceCharge")] public AllowanceChargeType[] ServiceAllowanceCharge { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("FreightAllowanceCharge")] public AllowanceChargeType[] FreightAllowanceCharge { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("AttachedTransportEquipment")] public TransportEquipmentType[] AttachedTransportEquipment { get; set; } /// <remarks/> public DeliveryType Delivery { get; set; } /// <remarks/> public PickupType Pickup { get; set; } /// <remarks/> public DespatchType Despatch { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ShipmentDocumentReference")] public DocumentReferenceType[] ShipmentDocumentReference { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ContainedInTransportEquipment")] public TransportEquipmentType[] ContainedInTransportEquipment { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Package")] public PackageType[] Package { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("GoodsItem")] public GoodsItemType[] GoodsItem { get; set; } } }
using System; using System.Threading.Tasks; using EasyNetQ.Consumer; using EasyNetQ.FluentConfiguration; using EasyNetQ.Producer; using EasyNetQ.Topology; using System.Linq; using EasyNetQ.Internals; namespace EasyNetQ { public class RabbitBus : IBus { private readonly IConventions conventions; private readonly IAdvancedBus advancedBus; private readonly IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy; private readonly IMessageDeliveryModeStrategy messageDeliveryModeStrategy; private readonly IRpc rpc; private readonly ISendReceive sendReceive; private readonly ConnectionConfiguration connectionConfiguration; public RabbitBus( IConventions conventions, IAdvancedBus advancedBus, IPublishExchangeDeclareStrategy publishExchangeDeclareStrategy, IMessageDeliveryModeStrategy messageDeliveryModeStrategy, IRpc rpc, ISendReceive sendReceive, ConnectionConfiguration connectionConfiguration) { Preconditions.CheckNotNull(conventions, "conventions"); Preconditions.CheckNotNull(advancedBus, "advancedBus"); Preconditions.CheckNotNull(publishExchangeDeclareStrategy, "publishExchangeDeclareStrategy"); Preconditions.CheckNotNull(rpc, "rpc"); Preconditions.CheckNotNull(sendReceive, "sendReceive"); Preconditions.CheckNotNull(connectionConfiguration, "connectionConfiguration"); this.conventions = conventions; this.advancedBus = advancedBus; this.publishExchangeDeclareStrategy = publishExchangeDeclareStrategy; this.messageDeliveryModeStrategy = messageDeliveryModeStrategy; this.rpc = rpc; this.sendReceive = sendReceive; this.connectionConfiguration = connectionConfiguration; } public virtual void Publish<T>(T message) where T : class { Preconditions.CheckNotNull(message, "message"); Publish(message, conventions.TopicNamingConvention(typeof(T))); } public virtual void Publish<T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); var messageType = typeof(T); var easyNetQMessage = new Message<T>(message) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType) } }; var exchange = publishExchangeDeclareStrategy.DeclareExchange(advancedBus, messageType, ExchangeType.Topic); advancedBus.Publish(exchange, topic, false, false, easyNetQMessage); } public virtual Task PublishAsync<T>(T message) where T : class { Preconditions.CheckNotNull(message, "message"); return PublishAsync(message, conventions.TopicNamingConvention(typeof(T))); } public virtual async Task PublishAsync<T>(T message, string topic) where T : class { Preconditions.CheckNotNull(message, "message"); Preconditions.CheckNotNull(topic, "topic"); var messageType = typeof (T); var easyNetQMessage = new Message<T>(message) { Properties = { DeliveryMode = messageDeliveryModeStrategy.GetDeliveryMode(messageType) } }; var exchange = await publishExchangeDeclareStrategy.DeclareExchangeAsync(advancedBus, messageType, ExchangeType.Topic).ConfigureAwait(false); await advancedBus.PublishAsync(exchange, topic, false, false, easyNetQMessage).ConfigureAwait(false); } public virtual ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage) where T : class { return Subscribe(subscriptionId, onMessage, x => { }); } public virtual ISubscriptionResult Subscribe<T>(string subscriptionId, Action<T> onMessage, Action<ISubscriptionConfiguration> configure) where T : class { Preconditions.CheckNotNull(subscriptionId, "subscriptionId"); Preconditions.CheckNotNull(onMessage, "onMessage"); Preconditions.CheckNotNull(configure, "configure"); return SubscribeAsync<T>(subscriptionId, msg => TaskHelpers.ExecuteSynchronously(() => onMessage(msg)), configure); } public virtual ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage) where T : class { return SubscribeAsync(subscriptionId, onMessage, x => { }); } public virtual ISubscriptionResult SubscribeAsync<T>(string subscriptionId, Func<T, Task> onMessage, Action<ISubscriptionConfiguration> configure) where T : class { Preconditions.CheckNotNull(subscriptionId, "subscriptionId"); Preconditions.CheckNotNull(onMessage, "onMessage"); Preconditions.CheckNotNull(configure, "configure"); var configuration = new SubscriptionConfiguration(connectionConfiguration.PrefetchCount); configure(configuration); var queueName = conventions.QueueNamingConvention(typeof(T), subscriptionId); var exchangeName = conventions.ExchangeNamingConvention(typeof(T)); var queue = advancedBus.QueueDeclare(queueName, autoDelete: configuration.AutoDelete, expires: configuration.Expires); var exchange = advancedBus.ExchangeDeclare(exchangeName, ExchangeType.Topic); foreach (var topic in configuration.Topics.DefaultIfEmpty("#")) { advancedBus.Bind(exchange, queue, topic); } var consumerCancellation = advancedBus.Consume<T>( queue, (message, messageReceivedInfo) => onMessage(message.Body), x => { x.WithPriority(configuration.Priority) .WithCancelOnHaFailover(configuration.CancelOnHaFailover) .WithPrefetchCount(configuration.PrefetchCount); if (configuration.IsExclusive) { x.AsExclusive(); } }); return new SubscriptionResult(exchange, queue, consumerCancellation); } public virtual TResponse Request<TRequest, TResponse>(TRequest request) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(request, "request"); var task = RequestAsync<TRequest, TResponse>(request); task.Wait(); return task.Result; } public virtual Task<TResponse> RequestAsync<TRequest, TResponse>(TRequest request) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(request, "request"); return rpc.Request<TRequest, TResponse>(request); } public virtual IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(responder, "responder"); Func<TRequest, Task<TResponse>> taskResponder = request => Task<TResponse>.Factory.StartNew(_ => responder(request), null); return RespondAsync(taskResponder); } public IDisposable Respond<TRequest, TResponse>(Func<TRequest, TResponse> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class { Func<TRequest, Task<TResponse>> taskResponder = request => Task<TResponse>.Factory.StartNew(_ => responder(request), null); return RespondAsync(taskResponder, configure); } public virtual IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder) where TRequest : class where TResponse : class { return RespondAsync(responder, c => { }); } public IDisposable RespondAsync<TRequest, TResponse>(Func<TRequest, Task<TResponse>> responder, Action<IResponderConfiguration> configure) where TRequest : class where TResponse : class { Preconditions.CheckNotNull(responder, "responder"); Preconditions.CheckNotNull(configure, "configure"); return rpc.Respond(responder, configure); } public virtual void Send<T>(string queue, T message) where T : class { sendReceive.Send(queue, message); } public virtual Task SendAsync<T>(string queue, T message) where T : class { return sendReceive.SendAsync(queue, message); } public virtual IDisposable Receive<T>(string queue, Action<T> onMessage) where T : class { return sendReceive.Receive(queue, onMessage); } public virtual IDisposable Receive<T>(string queue, Action<T> onMessage, Action<IConsumerConfiguration> configure) where T : class { return sendReceive.Receive(queue, onMessage, configure); } public virtual IDisposable Receive<T>(string queue, Func<T, Task> onMessage) where T : class { return sendReceive.Receive(queue, onMessage); } public virtual IDisposable Receive<T>(string queue, Func<T, Task> onMessage, Action<IConsumerConfiguration> configure) where T : class { return sendReceive.Receive(queue, onMessage, configure); } public virtual IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers) { return sendReceive.Receive(queue, addHandlers); } public virtual IDisposable Receive(string queue, Action<IReceiveRegistration> addHandlers, Action<IConsumerConfiguration> configure) { return sendReceive.Receive(queue, addHandlers, configure); } public virtual bool IsConnected { get { return advancedBus.IsConnected; } } public virtual IAdvancedBus Advanced { get { return advancedBus; } } public virtual void Dispose() { advancedBus.Dispose(); } } }
using Signum.Entities.Workflow; using Signum.Engine.Operations; using Signum.Entities; using Signum.Entities.Reflection; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using System.Linq.Expressions; using System.Xml; using Signum.Entities.UserAssets; using System.Globalization; using System.Xml.Schema; using Microsoft.Extensions.Azure; using System.Reflection.Metadata; using Signum.Entities.Basics; namespace Signum.Engine.Workflow { public class WorkflowImportExport { private WorkflowEntity workflow; Dictionary<string, WorkflowConnectionEntity> connections; Dictionary<string, WorkflowEventEntity> events; Dictionary<string, WorkflowActivityEntity> activities; Dictionary<string, WorkflowGatewayEntity> gateways; Dictionary<string, WorkflowLaneEntity> lanes; Dictionary<string, WorkflowPoolEntity> pools; public IEnumerable<IWorkflowNodeEntity> Activities => activities.Values.Cast<IWorkflowNodeEntity>() .Concat(events.Values.Where(a => a.Type == WorkflowEventType.IntermediateTimer)); public WorkflowImportExport(WorkflowEntity wf) { using (HeavyProfiler.Log("WorkflowBuilder")) using (new EntityCache()) { this.workflow = wf; this.connections = wf.IsNew ? new Dictionary<string, WorkflowConnectionEntity>() : wf.WorkflowConnections().ToDictionaryEx(a => a.BpmnElementId); this.events = wf.IsNew ? new Dictionary<string, WorkflowEventEntity>() : wf.WorkflowEvents().ToDictionaryEx(a => a.BpmnElementId); this.activities = wf.IsNew ? new Dictionary<string, WorkflowActivityEntity>() : wf.WorkflowActivities().ToDictionaryEx(a => a.BpmnElementId); this.gateways = wf.IsNew ? new Dictionary<string, WorkflowGatewayEntity>() : wf.WorkflowGateways().ToDictionaryEx(a => a.BpmnElementId); this.lanes = wf.IsNew ? new Dictionary<string, WorkflowLaneEntity>() : wf.WorkflowPools().SelectMany(a => a.WorkflowLanes()).ToDictionaryEx(a => a.BpmnElementId); this.pools = wf.IsNew ? new Dictionary<string, WorkflowPoolEntity>() : wf.WorkflowPools().ToDictionaryEx(a => a.BpmnElementId); } } public XElement ToXml(IToXmlContext ctx) { return new XElement("Workflow", new XAttribute("Guid", workflow.Guid), new XAttribute("Name", workflow.Name), new XAttribute("MainEntityType", ctx.TypeToName(workflow.MainEntityType.ToLite())), new XAttribute("MainEntityStrategies", workflow.MainEntityStrategies.ToString(",")), workflow.ExpirationDate == null ? null! : new XAttribute("ExpirationDate", workflow.ExpirationDate.Value.ToString("o", CultureInfo.InvariantCulture)), this.pools.Values.Select(p => new XElement("Pool", new XAttribute("BpmnElementId", p.BpmnElementId), new XAttribute("Name", p.Name), p.Xml.ToXml())), this.lanes.Values.Select(la => new XElement("Lane", new XAttribute("BpmnElementId", la.BpmnElementId), new XAttribute("Name", la.Name), new XAttribute("Pool", la.Pool.BpmnElementId), la.Actors.IsEmpty() ? null! : new XElement("Actors", la.Actors.Select(a => new XElement("Actor", a.KeyLong()!))), la.ActorsEval == null ? null! : new XElement("ActorsEval", new XCData(la.ActorsEval.Script)), la.Xml.ToXml())), this.activities.Values.Select(a => new XElement("Activity", new XAttribute("BpmnElementId", a.BpmnElementId), new XAttribute("Lane", a.Lane.BpmnElementId), new XAttribute("Name", a.Name), new XAttribute("Type", a.Type.ToString()), a.RequiresOpen == false ? null! : new XAttribute("RequiresOpen", a.RequiresOpen), a.EstimatedDuration == null ? null! : new XAttribute("EstimatedDuration", a.EstimatedDuration), string.IsNullOrEmpty(a.ViewName) ? null! : new XAttribute("ViewName", a.ViewName), string.IsNullOrEmpty(a.Comments) ? null! : new XElement("Comments", a.Comments), !a.ViewNameProps.Any() ? null! : new XElement("ViewNameProps", a.ViewNameProps.Select(vnp => new XElement("ViewNameProp", new XAttribute("Name", vnp.Name), new XCData(vnp.Expression!))) ), !a.DecisionOptions.Any() ? null! : new XElement("DecisionOptions", a.DecisionOptions.Select(cdo => cdo.ToXml("DecisionOption"))), a.CustomNextButton?.ToXml("CustomNextButton")!, string.IsNullOrEmpty(a.UserHelp) ? null! : new XElement("UserHelp", new XCData(a.UserHelp)), a.SubWorkflow == null ? null! : new XElement("SubWorkflow", new XAttribute("Workflow", ctx.Include(a.SubWorkflow.Workflow)), new XElement("SubEntitiesEval", new XCData(a.SubWorkflow.SubEntitiesEval.Script)) ), a.Script == null ? null! : new XElement("Script", new XAttribute("Script", ctx.Include(a.Script.Script)), a.Script.RetryStrategy == null ? null! : new XAttribute("RetryStrategy", ctx.Include(a.Script.RetryStrategy)) ), a.Xml.ToXml() )), this.gateways.Values.Select(g => new XElement("Gateway", new XAttribute("BpmnElementId", g.BpmnElementId), g.Name.HasText() ? new XAttribute("Name", g.Name) : null!, new XAttribute("Lane", g.Lane.BpmnElementId), new XAttribute("Type", g.Type.ToString()), new XAttribute("Direction", g.Direction.ToString()), g.Xml.ToXml())), this.events.Values.Select(e => new XElement("Event", new XAttribute("BpmnElementId", e.BpmnElementId), e.Name.HasText() ? new XAttribute("Name", e.Name) : null!, new XAttribute("Lane", e.Lane.BpmnElementId), new XAttribute("Type", e.Type.ToString()), e.Timer == null ? null! : new XElement("Timer", e.Timer.Duration?.ToXml("Duration")!, e.Timer.Condition == null ? null! : new XAttribute("Condition", ctx.Include(e.Timer.Condition))), e.BoundaryOf == null ? null! : new XAttribute("BoundaryOf", this.activities.Values.SingleEx(a => a.Is(e.BoundaryOf)).BpmnElementId), e.Xml.ToXml()) ), this.connections.Values.Select(c => new XElement("Connection", new XAttribute("BpmnElementId", c.BpmnElementId), c.Name.HasText() ? new XAttribute("Name", c.Name) : null!, new XAttribute("Type", c.Type.ToString()), new XAttribute("From", c.From.BpmnElementId), new XAttribute("To", c.To.BpmnElementId), c.DecisionOptionName == null ? null! : new XAttribute("CustomDecisionName", c.DecisionOptionName!), c.Condition == null ? null! : new XAttribute("Condition", ctx.Include(c.Condition)), c.Action == null ? null! : new XAttribute("Action", ctx.Include(c.Action)), c.Order == null ? null! : new XAttribute("Order", c.Order), c.Xml.ToXml())) ); } public IDisposable Sync<T>(Dictionary<string, T> entityDic, IEnumerable<XElement> elements, IFromXmlContext ctx, ExecuteSymbol<T> saveOperation, DeleteSymbol<T> deleteOperation, Action<T, XElement> setXml) where T : Entity, IWorkflowObjectEntity, new() { var xmlDic = elements.ToDictionaryEx(a => a.Attribute("BpmnElementId")!.Value); Synchronizer.Synchronize( xmlDic, entityDic, createNew: (bpmnId, xml) => { var entity = new T(); entity.BpmnElementId = xml.Attribute("BpmnElementId")!.Value; setXml(entity, xml); SaveOrMark<T>(entity, saveOperation, ctx); entityDic.Add(bpmnId, entity); }, removeOld: null, merge: null); return new Disposable(() => { Synchronizer.Synchronize( xmlDic, entityDic, createNew: null, removeOld: (bpmnId, entity) => { entityDic.Remove(bpmnId); DeleteOrMark<T>(entity, deleteOperation, ctx); }, merge: (bpmnId, xml, entity) => { setXml(entity, xml); SaveOrMark<T>(entity, saveOperation, ctx); }); }); } public bool HasChanges; public WorkflowReplacementModel? ReplacementModel { get; internal set; } public void SaveOrMark<T>(T entity, ExecuteSymbol<T> saveOperation, IFromXmlContext ctx) where T : Entity { if (ctx.IsPreview) { if (GraphExplorer.IsGraphModified(entity)) HasChanges = true; } else { if (GraphExplorer.IsGraphModified(entity)) entity.Execute(saveOperation); } } public void DeleteOrMark<T>(T entity, DeleteSymbol<T> deleteOperation, IFromXmlContext ctx) where T : Entity { IWorkflowNodeEntity? act = entity is WorkflowActivityEntity wa ? wa : entity is WorkflowEventEntity we && we.Type == WorkflowEventType.IntermediateTimer ? we : (IWorkflowNodeEntity?)null; if (ctx.IsPreview) { HasChanges = true; if (act != null && act.CaseActivities().Any()) { var rm = this.ReplacementModel ?? (this.ReplacementModel = new WorkflowReplacementModel()); this.ReplacementModel.Replacements.Add(new WorkflowReplacementItemEmbedded { OldNode = act.ToLite(), SubWorkflow = act is WorkflowActivityEntity wae ? wae.SubWorkflow?.Workflow.ToLite() : null, }); } } else { if (act != null && act.CaseActivities().Any()) { var replacementItem = ReplacementModel?.Replacements.SingleOrDefaultEx(a => a.OldNode.Is(act.ToLite())); if (replacementItem == null) throw new InvalidOperationException($"Unable to delete '{entity}' without a replacement for the Case Activities"); var replacement = this.activities.GetOrThrow(replacementItem.NewNode); act.CaseActivities() .Where(a => a.State == CaseActivityState.Done) .UnsafeUpdate() .Set(ca => ca.WorkflowActivity, ca => replacement) .Execute(); var running = act.CaseActivities().Where(a => a.State == CaseActivityState.Pending).ToList(); running.ForEach(a => { a.Notifications().UnsafeDelete(); a.WorkflowActivity = replacement; a.Save(); CaseActivityLogic.InsertCaseActivityNotifications(a); }); } entity.Delete(deleteOperation); } } public void FromXml(XElement element, IFromXmlContext ctx) { this.workflow.Name = element.Attribute("Name")!.Value; this.workflow.MainEntityType = ctx.GetType(element.Attribute("MainEntityType")!.Value); this.workflow.MainEntityStrategies.Synchronize(element.Attribute("MainEntityStrategies")!.Value.SplitNoEmpty(",").Select(a => a.Trim().ToEnum<WorkflowMainEntityStrategy>()).ToList()); this.workflow.ExpirationDate = element.Attribute("ExpirationDate")?.Let(ed => DateTime.ParseExact(ed.Value, "o", CultureInfo.InvariantCulture)); if(!ctx.IsPreview) { if (this.workflow.IsNew) { using (OperationLogic.AllowSave<WorkflowEntity>()) this.workflow.Save(); } } else { if (GraphExplorer.HasChanges(this.workflow)) HasChanges = true; } using (Sync(this.pools, element.Elements("Pool"), ctx, WorkflowPoolOperation.Save, WorkflowPoolOperation.Delete, (pool, xml) => { pool.Name = xml.Attribute("Name")!.Value; pool.Workflow = this.workflow; SetXmlDiagram(pool, xml); })) { using (Sync(this.lanes, element.Elements("Lane"), ctx, WorkflowLaneOperation.Save, WorkflowLaneOperation.Delete, (lane, xml) => { lane.Name = xml.Attribute("Name")!.Value; lane.Pool = this.pools.GetOrThrow(xml.Attribute("Pool")!.Value); lane.Actors.Synchronize((xml.Element("Actors")?.Elements("Actor")).EmptyIfNull().Select(a => Lite.Parse(a.Value)).ToMList()); lane.ActorsEval = lane.ActorsEval.CreateOrAssignEmbedded(xml.Element("ActorsEval"), (ae, aex) => { ae.Script = aex.Value; }); SetXmlDiagram(lane, xml); })) { using (Sync(this.activities, element.Elements("Activity"), ctx, WorkflowActivityOperation.Save, WorkflowActivityOperation.Delete, (activity, xml) => { activity.Lane = this.lanes.GetOrThrow(xml.Attribute("Lane")!.Value); activity.Name = xml.Attribute("Name")!.Value; activity.Type = xml.Attribute("Type")!.Value.ToEnum<WorkflowActivityType>(); activity.Comments = xml.Element("Comments")?.Value; activity.RequiresOpen = (bool?)xml.Attribute("RequiresOpen") ?? false; activity.EstimatedDuration = (double?)xml.Attribute("EstimatedDuration"); activity.ViewName = (string?)xml.Attribute("ViewName"); activity.ViewNameProps.Synchronize(xml.Element("ViewNameProps")?.Elements("ViewNameProp").ToList(), (vnpe, elem) => { vnpe.Name = elem.Value; }); activity.DecisionOptions.Synchronize(xml.Element("DecisionOptions")?.Elements("DecisionOption").ToList(), (cdoe, elem) => { cdoe.FromXml(elem); }); activity.CustomNextButton = activity.CustomNextButton.CreateOrAssignEmbedded(xml.Element("CustomNextButton"), (cnb, elem) => { cnb.FromXml(elem); }); activity.UserHelp = xml.Element("UserHelp")?.Value; activity.SubWorkflow = activity.SubWorkflow.CreateOrAssignEmbedded(xml.Element("SubWorkflow"), (swe, elem) => { swe.Workflow = (WorkflowEntity)ctx.GetEntity((Guid)elem.Attribute("Workflow")!); swe.SubEntitiesEval = swe.SubEntitiesEval.CreateOrAssignEmbedded(elem.Element("SubEntitiesEval"), (se, x) => { se.Script = x.Value; })!; }); activity.Script = activity.Script.CreateOrAssignEmbedded(xml.Element("Script"), (swe, elem) => { swe.Script = ((WorkflowScriptEntity)ctx.GetEntity((Guid)elem.Attribute("Script")!)).ToLiteFat(); swe.RetryStrategy = elem.Attribute("RetryStrategy")?.Let(a => (WorkflowScriptRetryStrategyEntity)ctx.GetEntity((Guid)a)); }); SetXmlDiagram(activity, xml); })) { using (Sync(this.events, element.Elements("Event"), ctx, WorkflowEventOperation.Save, WorkflowEventOperation.Delete, (ev, xml) => { ev.Name = xml.Attribute("Name")?.Value; ev.Lane = this.lanes.GetOrThrow(xml.Attribute("Lane")!.Value); ev.Type = xml.Attribute("Type")!.Value.ToEnum<WorkflowEventType>(); ev.Timer = ev.Timer.CreateOrAssignEmbedded(xml.Element("Timer"), (time, xml) => { time.Duration = time.Duration.CreateOrAssignEmbedded(xml.Element("Duration"), (ts, xml) => ts.FromXml(xml)); time.Condition = xml.Attribute("Condition")?.Let(a => ((WorkflowTimerConditionEntity)ctx.GetEntity((Guid)a)).ToLiteFat()); }); ev.BoundaryOf = xml.Attribute("BoundaryOf")?.Let(a =>activities.GetOrThrow(a.Value).ToLiteFat()); SetXmlDiagram(ev, xml); })) { using (Sync(this.gateways, element.Elements("Gateway"), ctx, WorkflowGatewayOperation.Save, WorkflowGatewayOperation.Delete, (gw, xml) => { gw.Name = xml.Attribute("Name")?.Value; gw.Lane = this.lanes.GetOrThrow(xml.Attribute("Lane")!.Value); gw.Type = xml.Attribute("Type")!.Value.ToEnum<WorkflowGatewayType>(); gw.Direction = xml.Attribute("Direction")!.Value.ToEnum<WorkflowGatewayDirection>(); SetXmlDiagram(gw, xml); })) { using (Sync(this.connections, element.Elements("Connection"), ctx, WorkflowConnectionOperation.Save, WorkflowConnectionOperation.Delete, (conn, xml) => { conn.Name = xml.Attribute("Name")?.Value; conn.DecisionOptionName = xml.Attribute("CustomDecisionName")?.Value; conn.Type = xml.Attribute("Type")!.Value.ToEnum<ConnectionType>(); conn.From = GetNode(xml.Attribute("From")!.Value); conn.To = GetNode(xml.Attribute("To")!.Value); conn.Condition = xml.Attribute("Condition")?.Let(a => ((WorkflowConditionEntity)ctx.GetEntity((Guid)a)).ToLiteFat()); conn.Action = xml.Attribute("Action")?.Let(a => ((WorkflowActionEntity)ctx.GetEntity((Guid)a)).ToLiteFat()); conn.Order = (int?)xml.Attribute("Order"); SetXmlDiagram(conn, xml); })) { //Identation vertigo :) } } } } } } if (this.HasChanges && !ctx.IsPreview) this.workflow.Execute(WorkflowOperation.Save); } public IWorkflowNodeEntity GetNode(string bpmnElementId) { return (IWorkflowNodeEntity?)this.activities.TryGetC(bpmnElementId) ?? (IWorkflowNodeEntity?)this.events.TryGetC(bpmnElementId) ?? (IWorkflowNodeEntity?)this.gateways.TryGetC(bpmnElementId) ?? throw new InvalidOperationException("No Workflow node wound with BpmnElementId: " + bpmnElementId); } void SetXmlDiagram(IWorkflowObjectEntity entity, XElement xml) { if (entity.Xml == null) entity.Xml = new WorkflowXmlEmbedded(); var newValue = xml.Element("DiagramXml")!.Value; if (!Enumerable.SequenceEqual((entity.Xml.DiagramXml ?? "").Lines(), newValue.Lines())) entity.Xml.DiagramXml = newValue; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using Vectrosity; public class Pedestrian : MonoBehaviour { Vector3 start; Vector3 target; //float movement_time_total; //float movement_time_elapsed; private float speed; //int densityReload; //int densityReloadInterval = 10; //int id; private List<PedestrianPosition> positions = new List<PedestrianPosition> (); private Color myColor; //bool trajectoryVisible; //VectorLine trajectory; //private InfoText it; //private PedestrianLoader pl; private PlaybackControl pc; private Renderer r; //private GeometryLoader gl; //private Groundplane gp; //GameObject tile; private AgentView agentView = null; #pragma warning disable 108 private Animation animation; #pragma warning restore 108 private LODGroup lodGroup; private int index; private bool targetReached = true; void Start () { gameObject.AddComponent<BoxCollider>(); // TODO what for? transform.Rotate (0, 90, 0); myColor = new Color (Random.value, Random.value, Random.value); //GetComponentInChildren<Renderer>().materials[1].color = myColor; //addTile (); //it = GameObject.Find ("InfoText").GetComponent<InfoText> (); //pl = GameObject.Find ("PedestrianLoader").GetComponent<PedestrianLoader> (); pc = GameObject.Find ("PlaybackControl").GetComponent<PlaybackControl> (); animation = GetComponentInChildren<Animation> (); lodGroup = GetComponentInChildren<LODGroup> (); if (lodGroup == null) { // "Pedestrian" model r = GetComponentInChildren<Renderer>() as Renderer; r.materials [1].color = myColor; } else { // "LOD_Ped" model Transform PedModelsTransform = transform.GetChild (0).transform; PedModelsTransform.GetChild (0).GetComponent<Renderer> ().materials [1].color = myColor; PedModelsTransform.GetChild (1).GetComponent<Renderer> ().materials [1].color = myColor; } //gl = GameObject.Find ("GeometryLoader").GetComponent<GeometryLoader> (); //gp = gl.groundplane; AgentView agentViewComponent = GameObject.Find("CameraMode").GetComponent<AgentView>(); if (agentViewComponent.enabled) agentView = agentViewComponent; resetPedestrian (); } internal void dev() { foreach (PedestrianPosition pos in positions) { Debug.Log(pos.getTime() + ": " + pos.getX() + ", " + pos.getY() + ", " + pos.getZ()); } } public int getPositionsCount() { return positions.Count; } public void init(int id, PedestrianPosition pos) { this.name = "Pedestrian_" + id; addOrderedPos(pos); } public void addPos(PedestrianPosition pos) { //if(!positions[positions.Count - 1].equals(pos)) // add only if pos is different to the previously added one addOrderedPos(pos); } private void addOrderedPos(PedestrianPosition pos) { if (positions.Count == 0) { positions.Add(pos); return; } int i = 0; while (i < positions.Count && positions[i].getTime() < pos.getTime()) { i += 1; } positions.Insert(i, pos); } /* void OnMouseDown(){ if (Cursor.lockState != CursorLockMode.None && !trajectoryVisible && !pc.drawLine && hideFlags!=HideFlags.HideInHierarchy) { showTrajectory(); } else if (Cursor.lockState != CursorLockMode.None && trajectoryVisible && !pc.drawLine && hideFlags!=HideFlags.HideInHierarchy) { hideTrajectory(); } } public void hideTrajectory() { VectorLine.Destroy(ref trajectory); trajectoryVisible = false; } public void showTrajectory() { VectorLine.SetCamera (GameObject.Find ("Flycam").GetComponent<Camera>()); List <Vector3> points = new List<Vector3>(); for (int i = 0; i<positions.Count-1; i++) { PedestrianPosition a = (PedestrianPosition)positions.GetByIndex (i); points.Add (new Vector3 (a.getX (), 0.01f, a.getY ())); } trajectory = VectorLine.SetLine3D (myColor, points.ToArray()); trajectory.lineWidth = 3.0f; pc.trajectoriesShown = true; trajectoryVisible = true; } void addTile() { float side = 1.0f; tile = new GameObject ("tile"+id, typeof(MeshFilter), typeof(MeshRenderer)); MeshFilter mesh_filter = tile.GetComponent<MeshFilter> (); tile.GetComponent<Renderer>().material = (Material) Resources.Load("Tilematerial", typeof(Material)); tile.GetComponent<Renderer>().material.color = Color.red; Mesh mesh = new Mesh(); mesh.vertices = new Vector3[] {new Vector3 (-side/2, 0.01f, -side/2),new Vector3 (side/2, 0.01f, -side/2),new Vector3 (-side/2, 0.01f, side/2),new Vector3 (side/2, 0.01f, side/2)}; mesh.triangles = new int[] {2,1,0,1,2,3}; Vector2[] uvs = new Vector2[mesh.vertices.Length]; int i = 0; while (i < uvs.Length) { uvs[i] = new Vector2(mesh.vertices[i].x, mesh.vertices[i].z); i++; } mesh.uv = uvs; mesh.RecalculateNormals(); mesh.RecalculateBounds(); mesh_filter.mesh = mesh; tile.transform.position = gameObject.transform.position; tile.transform.parent = gameObject.transform; } */ public void resetPedestrian() { index = 0; rendererEnabled (true); targetReached = false; PedestrianPosition pos = positions[0]; transform.position = new Vector3 (pos.getX (), pos.getZ(), pos.getY ()); } private void rendererEnabled(bool truefalse) { if (lodGroup == null) r.enabled = truefalse; else lodGroup.enabled = truefalse; if (truefalse) animation.Play (); } private bool showPed() { if (agentView != null) return agentView.getCurrentPed () != gameObject; return true; } void Update () { if (!targetReached) { if (showPed ()) rendererEnabled (true); else rendererEnabled (false); /* updateCalls ++; float dist = Vector3.Distance (gameObject.transform.position, Camera.main.transform.position); [...] if (r.enabled) // pc.playing && animation.Play (); else animation.Stop (); int index = _getTrait(positions, pc.current_time); if (pc.current_time > positions [index + 1].getTime () && index != positions.Count - 2) { index += 1; } if (index < positions.Count - 2 && pc.current_time > positions[index + 1].getTime()) { index += 1; } if (index < positions.Count - 1) { */ while (index <= positions.Count - 2 && pc.current_time >= positions [index + 1].getTime ()) // && index < positions.Count - 2 index += 1; PedestrianPosition pos = (PedestrianPosition)positions [index]; PedestrianPosition pos2 = (PedestrianPosition)positions [index + 1]; start = new Vector3 (pos.getX (), pos.getZ(), pos.getY ()); // the y-coord in Unity is the z-coord from the kernel: the up and down direction target = new Vector3 (pos2.getX (), pos2.getZ(), pos2.getY ()); float time = (float)pc.current_time; float timeStepLength = Mathf.Clamp ((float)pos2.getTime () - (float)pos.getTime (), 0.1f, 50f); // We don't want to divide by zero. OTOH, this results in pedestrians never standing still. float movement_percentage = ((float)time - (float)pos.getTime ()) / timeStepLength; Vector3 newPosition = Vector3.Lerp (start, target, movement_percentage); Vector3 relativePos = target - start; speed = relativePos.magnitude; animation ["walking"].speed = speed / timeStepLength; if (start != target) transform.rotation = Quaternion.LookRotation (relativePos); transform.position = newPosition; if (index >= positions.Count - 2) { // = target reached rendererEnabled (false); animation.Stop (); targetReached = true; } } /* //check if line is crossed if (gp.point1active && gp.point2active) { if (FasterLineSegmentIntersection(new Vector2(gp.point1.x,gp.point1.z), new Vector2(gp.point2.x,gp.point2.z), new Vector2(transform.position.x, transform.position.z), new Vector2(newPosition.x, newPosition.z))) { gp.lineCross(speed); } } //Tile coloring if (pc.tileColoringMode != TileColoringMode.TileColoringNone) { tile.GetComponent<Renderer>().enabled = true; if (pc.tileColoringMode == TileColoringMode.TileColoringSpeed) { tile.GetComponent<Renderer>().material.color = ColorHelper.ColorForSpeed(getSpeed()); //it.updateSpeed(speed); } else if (pc.tileColoringMode == TileColoringMode.TileColoringDensity) { densityReload = (densityReload+1)%densityReloadInterval; if (densityReload==0) { getDensity(); } float density = getDensity(); if (density>=pc.threshold) { tile.GetComponent<Renderer>().material.color = ColorHelper.ColorForDensity(density); } else { tile.GetComponent<Renderer>().enabled = false; } } else { tile.GetComponent<Renderer>().enabled = false; } gameObject.hideFlags = HideFlags.None; } } else { showPed = false; //r.enabled = false; //tile.GetComponent<Renderer>().enabled = false; //gameObject.hideFlags = HideFlags.HideInHierarchy; } //r.enabled = showPed; //if (agentView.getCurrentPed() == gameObject) //showPed = false; } else GetComponent <Animation> ().Stop ();*/ } /* public float getDensity() { if (hideFlags==HideFlags.HideInHierarchy) return -1; int nearbys = 0; float radius = 2.0f; foreach (GameObject p in pl.pedestrians) { if (p!=this && Vector3.Distance(transform.position,p.transform.position)<radius && p.hideFlags!=HideFlags.HideInHierarchy) { nearbys++; } } float density = nearbys/(radius*radius*Mathf.PI); it.updateDensity(density); return density; } public float getDensityF() { if (hideFlags==HideFlags.HideInHierarchy) return -1; List<float> nearbys = new List<float>(); foreach (GameObject p in pl.pedestrians) { if (p!=this && p.hideFlags!=HideFlags.HideInHierarchy) { float distance = Vector3.Distance(transform.position,p.transform.position); if (nearbys.Count == 0) nearbys.Add(distance); else if (nearbys[0]>distance) {nearbys.Insert(0,distance);} else {nearbys.Add (distance);} } } float density = 8/(nearbys[7]*nearbys[7]*Mathf.PI); it.updateDensity(density); return density; } // http://www.stefanbader.ch/faster-line-segment-intersection-for-unity3dc/ bool FasterLineSegmentIntersection(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4) { Vector2 a = p2 - p1; Vector2 b = p3 - p4; Vector2 c = p1 - p3; float alphaNumerator = b.y*c.x - b.x*c.y; float alphaDenominator = a.y*b.x - a.x*b.y; float betaNumerator = a.x*c.y - a.y*c.x; float betaDenominator = alphaDenominator; //2013/07/05, fix by Deniz bool doIntersect = true; if (alphaDenominator == 0 || betaDenominator == 0) { doIntersect = false; } else { if (alphaDenominator > 0) { if (alphaNumerator < 0 || alphaNumerator > alphaDenominator) { doIntersect = false; } } else if (alphaNumerator > 0 || alphaNumerator < alphaDenominator) { doIntersect = false; } if (doIntersect && betaDenominator > 0) { if (betaNumerator < 0 || betaNumerator > betaDenominator) { doIntersect = false; } } else if (betaNumerator > 0 || betaNumerator < betaDenominator) { doIntersect = false; } } return doIntersect; } private int _getTrait(SortedList thisList, decimal thisValue) { for (int i = 0; i < thisList.Count; i ++) { if ((decimal) thisList.GetKey(i) > thisValue) return i - 1; } return -1;*/ /* // Check to see if we need to search the list. if (thisList == null || thisList.Count <= 0) { return -1; } if (thisList.Count == 1) { return 0; } // Setup the variables needed to find the closest index int lower = 0; int upper = thisList.Count - 1; int index = (lower + upper) / 2; // Find the closest index (rounded down) bool searching = true; while (searching) { int comparisonResult = decimal.Compare(thisValue, (decimal) thisList.GetKey(index)); if (comparisonResult == 0) { return index; } else if (comparisonResult < 0) { upper = index - 1; } else { lower = index + 1; } Debug.Log (thisValue + " : " + (decimal) thisList.GetKey(index)); index = (lower + upper) / 2; if (lower > upper) { searching = false; } } // Check to see if we are under or over the max values. if (index >= thisList.Count - 1) { return thisList.Count - 1; } if (index < 0) { return 0; } // Check to see if we should have rounded up instead //if (thisList.Keys[index + 1] - thisValue < thisValue - (thisList.Keys[index])) { index++; } // Return the correct/closest string return index; //} public void setID(int id) { //this.id = id; //densityReload = id % densityReloadInterval; this.name = "Pedestrian " + id; } public void setPositions(List<PedestrianPosition> p) { // comes in sorted here //positions.Clear(); positions = p; PedestrianPosition pos = (PedestrianPosition) p[0]; transform.position = new Vector3 (pos.getX(), 0, pos.getY()); } */ }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using CSScriptLibrary; using Quartz; using Quartz.Impl; using Quartz.Impl.Triggers; namespace Cronshop { public class CronshopScheduler : ICronshopScheduler { internal const string CronshopDefaultGroup = "Job"; private readonly IScriptCatalog _catalog; private readonly IDictionary<JobKey, JobInfo> _jobs = new Dictionary<JobKey, JobInfo>(); private readonly IScheduler _scheduler; static CronshopScheduler() { // for now -- this is less painful on temp files and file locks. CSScript.CacheEnabled = false; CSScript.GlobalSettings.InMemoryAsssembly = true; } public CronshopScheduler(IScriptCatalog catalog) { _catalog = catalog; _catalog.CatalogChanged += CatalogChanged; ISchedulerFactory factory = new StdSchedulerFactory(); _scheduler = factory.GetScheduler(); Scheduler.JobFactory = new SafeJobFactory(); Scheduler.ListenerManager.AddJobListener(new MainJobMonitor(_jobs)); LoadJobsFromCatalog(); } protected internal IScheduler Scheduler { get { return _scheduler; } } #region ICronshopScheduler Members public void Dispose() { Scheduler.Shutdown(true); _catalog.CatalogChanged -= CatalogChanged; } public IEnumerable<JobInfo> Jobs { get { return _jobs.Values; } } public void Start() { Scheduler.Start(); } public void Stop() { Scheduler.Standby(); } public object ExecuteJob(JobKey jobKey) { IJobDetail detail = Scheduler.GetJobDetail(jobKey); if (detail == null) { return null; } try { using (var instance = (CronshopJob) Activator.CreateInstance(detail.JobType)) { return instance.ExecuteJob(null); } } catch { return null; } } public void InterruptJob(JobKey jobKey) { Scheduler.Interrupt(jobKey); } public void Pause(JobKey jobKey = null) { if (jobKey == null) { Scheduler.PauseAll(); } else { Scheduler.PauseJob(jobKey); } } public void Resume(JobKey jobKey = null) { if (jobKey == null) { Scheduler.ResumeAll(); } else { Scheduler.ResumeJob(jobKey); } } #endregion private void CatalogChanged(object sender, CatalogChangedEventArgs e) { foreach (var change in e.Changes) { Console.Write("change: " + change.Item1); Console.WriteLine(" -> " + change.Item2); } while (e.Changes.Count > 0) { Tuple<CronshopScript, CatalogChange> change = e.Changes.Dequeue(); if (change.Item2 == CatalogChange.Deleted) { UnscheduleScript(change.Item1); } else if (change.Item2 == CatalogChange.Created) { ScheduleScript(change.Item1); } else if (change.Item2 == CatalogChange.Modified) { UnscheduleScript(change.Item1); ScheduleScript(change.Item1); } } } private void LoadJobsFromCatalog() { CronshopScript[] scripts = _catalog.Scripts.ToArray(); foreach (CronshopScript script in scripts) { ScheduleScript(script); } } private void ScheduleScript(CronshopScript script) { Assembly assembly = LoadAssembly(script); if (assembly == null) { return; } // find implementations of CronshopJob IEnumerable<Type> types = assembly.GetTypes() .Where(t => typeof (CronshopJob).IsAssignableFrom(t) && !t.IsAbstract); foreach (Type type in types) { JobConfigurator configurator; // create the instance to get the schedule using (var instance = (CronshopJob) Activator.CreateInstance(type)) { configurator = new JobConfigurator(); instance.Configure(configurator); } string name = JobInfo.BuildJobName(script, type); var detail = new JobDetailImpl(name, CronshopDefaultGroup, type) {Durable = true}; Scheduler.AddJob(detail, false); Console.WriteLine("ScheduleJob: " + detail.Key); var triggers = new List<ITrigger>(); foreach (string cron in configurator.Crons) { var trigger = new CronTriggerImpl(name + @"." + Guid.NewGuid(), CronshopDefaultGroup, cron) { JobKey = detail.Key, MisfireInstruction = MisfireInstruction.CronTrigger.DoNothing, }; triggers.Add(trigger); Scheduler.ScheduleJob(trigger); } _jobs.Add(detail.Key, new JobInfo(script, detail, triggers)); } } private static Assembly LoadAssembly(CronshopScript script) { try { return CSScript.Load(script.FullPath); } catch (Exception e) { Console.WriteLine(e); } return null; } private void UnscheduleScript(CronshopScript script) { KeyValuePair<JobKey, JobInfo>[] keys = _jobs .Where(x => x.Value.Script.FullPath == script.FullPath) .ToArray(); foreach (KeyValuePair<JobKey, JobInfo> tuple in keys) { bool success = Scheduler.DeleteJob(tuple.Value.JobDetail.Key); Console.WriteLine("DeleteJob: " + tuple.Value.JobDetail.Key + " " + (success ? "success" : "FAILED")); _jobs.Remove(tuple.Key); } } } }
using System.Net; using System.Net.Http; using System.Threading.Tasks; using FluentAssertions; using JsonApiDotNetCore.Serialization.Objects; using JsonApiDotNetCoreTests.IntegrationTests.ResourceInheritance.Models; using Microsoft.EntityFrameworkCore; using TestBuildingBlocks; using Xunit; namespace JsonApiDotNetCoreTests.IntegrationTests.ResourceInheritance { public sealed class InheritanceTests : IClassFixture<IntegrationTestContext<TestableStartup<InheritanceDbContext>, InheritanceDbContext>> { private readonly IntegrationTestContext<TestableStartup<InheritanceDbContext>, InheritanceDbContext> _testContext; public InheritanceTests(IntegrationTestContext<TestableStartup<InheritanceDbContext>, InheritanceDbContext> testContext) { _testContext = testContext; testContext.UseController<MenController>(); } [Fact] public async Task Can_create_resource_with_inherited_attributes() { // Arrange var newMan = new Man { FamilyName = "Smith", IsRetired = true, HasBeard = true }; var requestBody = new { data = new { type = "men", attributes = new { familyName = newMan.FamilyName, isRetired = newMan.IsRetired, hasBeard = newMan.HasBeard } } }; const string route = "/men"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); responseDocument.Data.SingleValue.Type.Should().Be("men"); responseDocument.Data.SingleValue.Attributes["familyName"].Should().Be(newMan.FamilyName); responseDocument.Data.SingleValue.Attributes["isRetired"].Should().Be(newMan.IsRetired); responseDocument.Data.SingleValue.Attributes["hasBeard"].Should().Be(newMan.HasBeard); int newManId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { Man manInDatabase = await dbContext.Men.FirstWithIdAsync(newManId); manInDatabase.FamilyName.Should().Be(newMan.FamilyName); manInDatabase.IsRetired.Should().Be(newMan.IsRetired); manInDatabase.HasBeard.Should().Be(newMan.HasBeard); }); } [Fact] public async Task Can_create_resource_with_ToOne_relationship() { // Arrange var existingInsurance = new CompanyHealthInsurance(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTableAsync<CompanyHealthInsurance>(); dbContext.CompanyHealthInsurances.Add(existingInsurance); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "men", relationships = new { healthInsurance = new { data = new { type = "companyHealthInsurances", id = existingInsurance.StringId } } } } }; const string route = "/men"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); int newManId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { Man manInDatabase = await dbContext.Men.Include(man => man.HealthInsurance).FirstWithIdAsync(newManId); manInDatabase.HealthInsurance.Should().BeOfType<CompanyHealthInsurance>(); manInDatabase.HealthInsurance.Id.Should().Be(existingInsurance.Id); }); } [Fact] public async Task Can_update_resource() { // Arrange var existingMan = new Man { FamilyName = "Smith", IsRetired = false, HasBeard = true }; var newMan = new Man { FamilyName = "Jackson", IsRetired = true, HasBeard = false }; await _testContext.RunOnDatabaseAsync(async dbContext => { dbContext.Men.Add(existingMan); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "men", id = existingMan.StringId, attributes = new { familyName = newMan.FamilyName, isRetired = newMan.IsRetired, hasBeard = newMan.HasBeard } } }; string route = $"/men/{existingMan.StringId}"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Man manInDatabase = await dbContext.Men.FirstWithIdAsync(existingMan.Id); manInDatabase.FamilyName.Should().Be(newMan.FamilyName); manInDatabase.IsRetired.Should().Be(newMan.IsRetired); manInDatabase.HasBeard.Should().Be(newMan.HasBeard); }); } [Fact] public async Task Can_assign_ToOne_relationship() { // Arrange var existingMan = new Man(); var existingInsurance = new CompanyHealthInsurance(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTablesAsync<Man, CompanyHealthInsurance>(); dbContext.AddInRange(existingMan, existingInsurance); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "companyHealthInsurances", id = existingInsurance.StringId } }; string route = $"/men/{existingMan.StringId}/relationships/healthInsurance"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Man manInDatabase = await dbContext.Men.Include(man => man.HealthInsurance).FirstWithIdAsync(existingMan.Id); manInDatabase.HealthInsurance.Should().BeOfType<CompanyHealthInsurance>(); manInDatabase.HealthInsurance.Id.Should().Be(existingInsurance.Id); }); } [Fact] public async Task Can_create_resource_with_OneToMany_relationship() { // Arrange var existingFather = new Man(); var existingMother = new Woman(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTablesAsync<Woman, Man>(); dbContext.Humans.AddRange(existingFather, existingMother); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "men", relationships = new { parents = new { data = new[] { new { type = "men", id = existingFather.StringId }, new { type = "women", id = existingMother.StringId } } } } } }; const string route = "/men"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); int newManId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { Man manInDatabase = await dbContext.Men.Include(man => man.Parents).FirstWithIdAsync(newManId); manInDatabase.Parents.Should().HaveCount(2); manInDatabase.Parents.Should().ContainSingle(human => human is Man); manInDatabase.Parents.Should().ContainSingle(human => human is Woman); }); } [Fact] public async Task Can_assign_OneToMany_relationship() { // Arrange var existingChild = new Man(); var existingFather = new Man(); var existingMother = new Woman(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTablesAsync<Woman, Man>(); dbContext.Humans.AddRange(existingChild, existingFather, existingMother); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "men", id = existingFather.StringId }, new { type = "women", id = existingMother.StringId } } }; string route = $"/men/{existingChild.StringId}/relationships/parents"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Man manInDatabase = await dbContext.Men.Include(man => man.Parents).FirstWithIdAsync(existingChild.Id); manInDatabase.Parents.Should().HaveCount(2); manInDatabase.Parents.Should().ContainSingle(human => human is Man); manInDatabase.Parents.Should().ContainSingle(human => human is Woman); }); } [Fact] public async Task Can_create_resource_with_ManyToMany_relationship() { // Arrange var existingBook = new Book(); var existingVideo = new Video(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTablesAsync<Book, Video, Man>(); dbContext.ContentItems.AddRange(existingBook, existingVideo); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new { type = "men", relationships = new { favoriteContent = new { data = new[] { new { type = "books", id = existingBook.StringId }, new { type = "videos", id = existingVideo.StringId } } } } } }; const string route = "/men"; // Act (HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecutePostAsync<Document>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.Created); responseDocument.Data.SingleValue.Should().NotBeNull(); int newManId = int.Parse(responseDocument.Data.SingleValue.Id); await _testContext.RunOnDatabaseAsync(async dbContext => { Man manInDatabase = await dbContext.Men.Include(man => man.FavoriteContent).FirstWithIdAsync(newManId); manInDatabase.FavoriteContent.Should().HaveCount(2); manInDatabase.FavoriteContent.Should().ContainSingle(item => item is Book && item.Id == existingBook.Id); manInDatabase.FavoriteContent.Should().ContainSingle(item => item is Video && item.Id == existingVideo.Id); }); } [Fact] public async Task Can_assign_ManyToMany_relationship() { // Arrange var existingBook = new Book(); var existingVideo = new Video(); var existingMan = new Man(); await _testContext.RunOnDatabaseAsync(async dbContext => { await dbContext.ClearTablesAsync<Book, Video, Man>(); dbContext.AddInRange(existingBook, existingVideo, existingMan); await dbContext.SaveChangesAsync(); }); var requestBody = new { data = new[] { new { type = "books", id = existingBook.StringId }, new { type = "videos", id = existingVideo.StringId } } }; string route = $"/men/{existingMan.StringId}/relationships/favoriteContent"; // Act (HttpResponseMessage httpResponse, string responseDocument) = await _testContext.ExecutePatchAsync<string>(route, requestBody); // Assert httpResponse.Should().HaveStatusCode(HttpStatusCode.NoContent); responseDocument.Should().BeEmpty(); await _testContext.RunOnDatabaseAsync(async dbContext => { Man manInDatabase = await dbContext.Men.Include(man => man.FavoriteContent).FirstWithIdAsync(existingMan.Id); manInDatabase.FavoriteContent.Should().HaveCount(2); manInDatabase.FavoriteContent.Should().ContainSingle(item => item is Book && item.Id == existingBook.Id); manInDatabase.FavoriteContent.Should().ContainSingle(item => item is Video && item.Id == existingVideo.Id); }); } } }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using System.CodeDom.Compiler; using System.Collections.Specialized; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using SubSonic.Utilities; namespace SubSonic { /// <summary> /// Summary for the TurboCompiler class /// </summary> public class TurboCompiler { private static readonly Regex regLineFix = new Regex(@"[\r\n]+", RegexOptions.Compiled); private static readonly Regex regNamespace = new Regex(@"^\bnamespace\b", RegexOptions.Compiled); private readonly TurboTemplateCollection templates = new TurboTemplateCollection(); private CompilerParameters codeCompilerParameters; private CodeDomProvider codeProvider; internal StringBuilder errMsg = new StringBuilder(); internal ICodeLanguage Language = new CSharpCodeLanguage(); internal StringCollection References = new StringCollection(); /// <summary> /// Gets the templates. /// </summary> /// <value>The templates.</value> public TurboTemplateCollection Templates { get { return templates; } } /// <summary> /// Gets the code provider. /// </summary> /// <value>The code provider.</value> private CodeDomProvider CodeProvider { get { if(codeProvider == null) codeProvider = Language.CreateCodeProvider(); return codeProvider; } } /// <summary> /// Gets the code compiler parameters. /// </summary> /// <value>The code compiler parameters.</value> private CompilerParameters CodeCompilerParameters { get { if(codeCompilerParameters == null) { codeCompilerParameters = new CompilerParameters { CompilerOptions = "/target:library", GenerateExecutable = false, GenerateInMemory = true, IncludeDebugInformation = false }; codeCompilerParameters.ReferencedAssemblies.Add("mscorlib.dll"); foreach(string s in References) codeCompilerParameters.ReferencedAssemblies.Add(s); } return codeCompilerParameters; } } /// <summary> /// Adds the template. /// </summary> /// <param name="template">The template.</param> public void AddTemplate(TurboTemplate template) { if(template != null) { if(templates.Count == 0) { References = template.References; Language = template.CompileLanguage; } template.EntryPoint = "Render"; template.GeneratedRenderType = String.Concat("Parser", Templates.Count); template.TemplateText = Utility.FastReplace(template.TemplateText, "#TEMPLATENUMBER#", Templates.Count.ToString(), StringComparison.InvariantCultureIgnoreCase); templates.Add(template); } } /// <summary> /// Resets this instance. /// </summary> public void Reset() { templates.Clear(); } /// <summary> /// Runs the and execute. /// </summary> /// <param name="sourceCode">The source code.</param> /// <param name="methodName">Name of the method.</param> public void RunAndExecute(string sourceCode, string methodName) { // TODO: And what again is methodName doing? It's not used anywhere... // Utility.WriteTrace("Compiling migration code..."); // string[] source = new string[1]; // source[0] = sourceCode; // CompilerResults results = CodeProvider.CompileAssemblyFromSource(CodeCompilerParameters, source); // Utility.WriteTrace("Done!"); // MethodInfo method=results.CompiledAssembly.GetType().GetMethod(methodName); // method.Invoke(); } /// <summary> /// Runs the and execute. /// </summary> /// <param name="sourceCode">The source code.</param> public void RunAndExecute(string sourceCode) { RunAndExecute(sourceCode, "Main"); } /// <summary> /// Runs this instance. /// </summary> public void Run() { int templateCount = Templates.Count; if(templateCount > 0) { ClearErrorMessages(); string[] templateArray = new string[templateCount]; for(int i = 0; i < templateCount; i++) templateArray[i] = Templates[i].TemplateText; Utility.WriteTrace("Compiling assembly..."); CompilerResults results = CodeProvider.CompileAssemblyFromSource(CodeCompilerParameters, templateArray); Utility.WriteTrace("Done!"); if(results.Errors.Count > 0 || results.CompiledAssembly == null) { if(results.Errors.Count > 0) { foreach(CompilerError error in results.Errors) LogErrorMessages("Compile Error: " + error.ErrorText); } if(results.CompiledAssembly == null) { const string errorMessage = "Error generating template code: This usually indicates an error in template itself, such as use of reserved words. Detail: "; Utility.WriteTrace(errorMessage + errMsg); string sMessage = errorMessage + Environment.NewLine + errMsg; throw new Exception(sMessage); } return; } Utility.WriteTrace("Extracting code from assembly and scrubbing output..."); CallEntry(results.CompiledAssembly); Utility.WriteTrace("Done!"); } } /// <summary> /// Scrubs the output. /// </summary> /// <param name="result">The result.</param> /// <param name="language">The language.</param> /// <returns></returns> private static string ScrubOutput(string result, ICodeLanguage language) { if(!String.IsNullOrEmpty(result)) { // the generator has an issue with adding extra lines. Trim them out result = regLineFix.Replace(result, "\r\n"); // now, for readability, add a space after the end of the method/class if(language is CSharpCodeLanguage) { result = regNamespace.Replace(result, "\r\nnamespace"); result = Utility.FastReplace(result, "public class ", "\r\npublic class ", StringComparison.InvariantCulture); } else { // trailing space needed to address class names that begin with "Class" result = Utility.FastReplace(result, "Public Class ", "\r\nPublic Class ", StringComparison.InvariantCulture); } result = Utility.FastReplace(result, "[<]", "<", StringComparison.InvariantCultureIgnoreCase); result = Utility.FastReplace(result, "[>]", ">", StringComparison.InvariantCultureIgnoreCase); // This is should be executed last. While this value will ultimately be removed, it can be inserted in a template to keep an earlier operation from executing. // For example: <System.ComponentModel.DataObject()> Public Class MyController would normally wrap to a second line due upstream processing, which would // result in VB code that won't compile. However, <System.ComponentModel.DataObject()> Public [MONKEY_WRENCH]Class MyController, would not. // Nice Eric... :P // result = Utility.FastReplace(result, "[MONKEY_WRENCH]", String.Empty, StringComparison.InvariantCultureIgnoreCase); // Not currently used, but please leave in case we need it in the future! } return result; } /// <summary> /// Calls the entry. /// </summary> /// <param name="assembly">The assembly.</param> private void CallEntry(Assembly assembly) { int templateCount = Templates.Count; Module mod = assembly.GetModules(false)[0]; for(int i = 0; i < templateCount; i++) { Type type = mod.GetType(Templates[i].GeneratedRenderType); if(type != null) { MethodInfo mi = type.GetMethod(Templates[i].EntryPoint, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); if(mi != null) { StringBuilder returnText = new StringBuilder(); string resultMessage = String.Format("Successfully generated {0}", Templates[i].TemplateName); if(Templates[i].AddUsingBlock) { Utility.WriteTrace("Adding Custom Using Blocks"); returnText.Append(Templates[i].RenderLanguage.DefaultUsingStatements); returnText.Append(Templates[i].CustomUsingBlock); } try { returnText.Append((string)mi.Invoke(null, null)); } catch(Exception ex) { resultMessage = "An Exception occured in template " + Templates[i].TemplateName + ": " + ex.Message; } Templates[i].FinalCode = ScrubOutput(returnText.ToString(), Templates[i].RenderLanguage); Utility.WriteTrace(resultMessage); } } } } /// <summary> /// Logs the error messages. /// </summary> /// <param name="customMessage">The custom message.</param> internal void LogErrorMessages(string customMessage) { LogErrorMessages(customMessage, null); } /// <summary> /// Logs the error messages. /// </summary> /// <param name="customMessage">The custom message.</param> /// <param name="ex">The ex.</param> internal void LogErrorMessages(string customMessage, Exception ex) { // put the error message into builder errMsg.Append("\r\n").Append(customMessage).Append(Environment.NewLine); // get all the exceptions and add their error messages while(ex != null) { errMsg.Append("\t").Append(ex.Message).Append(Environment.NewLine); ex = ex.InnerException; } } /// <summary> /// Clears the error messages. /// </summary> internal void ClearErrorMessages() { errMsg.Remove(0, errMsg.Length); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace SharpCompress { internal static class Utility { public static ReadOnlyCollection<T> ToReadOnly<T>(this IEnumerable<T> items) { return new ReadOnlyCollection<T>(items.ToList()); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static int URShift(int number, int bits) { if (number >= 0) return number >> bits; else return (number >> bits) + (2 << ~bits); } /// <summary> /// Performs an unsigned bitwise right shift with the specified number /// </summary> /// <param name="number">Number to operate on</param> /// <param name="bits">Ammount of bits to shift</param> /// <returns>The resulting number from the shift operation</returns> public static long URShift(long number, int bits) { if (number >= 0) return number >> bits; else return (number >> bits) + (2L << ~bits); } /// <summary> /// Fills the array with an specific value from an specific index to an specific index. /// </summary> /// <param name="array">The array to be filled.</param> /// <param name="fromindex">The first index to be filled.</param> /// <param name="toindex">The last index to be filled.</param> /// <param name="val">The value to fill the array with.</param> public static void Fill<T>(T[] array, int fromindex, int toindex, T val) where T : struct { if (array.Length == 0) { throw new NullReferenceException(); } if (fromindex > toindex) { throw new ArgumentException(); } if ((fromindex < 0) || ((System.Array)array).Length < toindex) { throw new IndexOutOfRangeException(); } for (int index = (fromindex > 0) ? fromindex-- : fromindex; index < toindex; index++) { array[index] = val; } } /// <summary> /// Fills the array with an specific value. /// </summary> /// <param name="array">The array to be filled.</param> /// <param name="val">The value to fill the array with.</param> public static void Fill<T>(T[] array, T val) where T : struct { Fill(array, 0, array.Length, val); } public static void SetSize(this List<byte> list, int count) { if (count > list.Count) { for (int i = list.Count; i < count; i++) { list.Add(0x0); } } else { byte[] temp = new byte[count]; list.CopyTo(temp, 0); list.Clear(); list.AddRange(temp); } } public static void AddRange<T>(this ICollection<T> destination, IEnumerable<T> source) { foreach (T item in source) { destination.Add(item); } } public static void ForEach<T>(this IEnumerable<T> items, Action<T> action) { foreach (T item in items) { action(item); } } public static IEnumerable<T> AsEnumerable<T>(this T item) { yield return item; } public static void CheckNotNull(this object obj, string name) { if (obj == null) { throw new ArgumentNullException(name); } } public static void CheckNotNullOrEmpty(this string obj, string name) { obj.CheckNotNull(name); if (obj.Length == 0) { throw new ArgumentException("String is empty."); } } public static void Skip(this Stream source, long advanceAmount) { byte[] buffer = new byte[32 * 1024]; int read = 0; int readCount = 0; do { readCount = buffer.Length; if (readCount > advanceAmount) { readCount = (int)advanceAmount; } read = source.Read(buffer, 0, readCount); if (read <= 0) { break; } advanceAmount -= read; if (advanceAmount == 0) { break; } } while (true); } public static void SkipAll(this Stream source) { byte[] buffer = new byte[32 * 1024]; do { } while (source.Read(buffer, 0, buffer.Length) == buffer.Length); } public static DateTime DosDateToDateTime(UInt16 iDate, UInt16 iTime) { int year = iDate / 512 + 1980; int month = iDate % 512 / 32; int day = iDate % 512 % 32; int hour = iTime / 2048; int minute = iTime % 2048 / 32; int second = iTime % 2048 % 32 * 2; if (iDate == UInt16.MaxValue || month == 0 || day == 0) { year = 1980; month = 1; day = 1; } if (iTime == UInt16.MaxValue) { hour = minute = second = 0; } DateTime dt; try { dt = new DateTime(year, month, day, hour, minute, second, DateTimeKind.Local); } catch { dt = new DateTime(); } return dt; } public static uint DateTimeToDosTime(this DateTime? dateTime) { if (dateTime == null) { return 0; } var localDateTime = dateTime.Value.ToLocalTime(); return (uint)( (localDateTime.Second / 2) | (localDateTime.Minute << 5) | (localDateTime.Hour << 11) | (localDateTime.Day << 16) | (localDateTime.Month << 21) | ((localDateTime.Year - 1980) << 25)); } public static DateTime DosDateToDateTime(UInt32 iTime) { return DosDateToDateTime((UInt16)(iTime / 65536), (UInt16)(iTime % 65536)); } public static DateTime DosDateToDateTime(Int32 iTime) { return DosDateToDateTime((UInt32)iTime); } public static long TransferTo(this Stream source, Stream destination) { byte[] array = new byte[81920]; int count; long total = 0; while ((count = source.Read(array, 0, array.Length)) != 0) { total += count; destination.Write(array, 0, count); } return total; } public static bool ReadFully(this Stream stream, byte[] buffer) { int total = 0; int read; while ((read = stream.Read(buffer, total, buffer.Length - total)) > 0) { total += read; if (total >= buffer.Length) { return true; } } return (total >= buffer.Length); } public static string TrimNulls(this string source) { return source.Replace('\0', ' ').Trim(); } public static bool BinaryEquals(this byte[] source, byte[] target) { if (source.Length != target.Length) { return false; } for (int i = 0; i < source.Length; ++i) { if (source[i] != target[i]) { return false; } } return true; } public static void CopyTo(this byte[] array, byte[] destination, int index) { Array.Copy(array, 0, destination, index, array.Length); } } }
// 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.Linq; namespace Microsoft.AspNetCore.Cors.Infrastructure { /// <summary> /// Exposes methods to build a policy. /// </summary> public class CorsPolicyBuilder { private readonly CorsPolicy _policy = new CorsPolicy(); /// <summary> /// Creates a new instance of the <see cref="CorsPolicyBuilder"/>. /// </summary> /// <param name="origins">list of origins which can be added.</param> /// <remarks> <see cref="WithOrigins(string[])"/> for details on normalizing the origin value.</remarks> public CorsPolicyBuilder(params string[] origins) { WithOrigins(origins); } /// <summary> /// Creates a new instance of the <see cref="CorsPolicyBuilder"/>. /// </summary> /// <param name="policy">The policy which will be used to intialize the builder.</param> public CorsPolicyBuilder(CorsPolicy policy) { Combine(policy); } /// <summary> /// Adds the specified <paramref name="origins"/> to the policy. /// </summary> /// <param name="origins">The origins that are allowed.</param> /// <returns>The current policy builder.</returns> /// <remarks> /// This method normalizes the origin value prior to adding it to <see cref="CorsPolicy.Origins"/> to match /// the normalization performed by the browser on the value sent in the <c>ORIGIN</c> header. /// <list type="bullet"> /// <item> /// If the specified origin has an internationalized domain name (IDN), the punycoded value is used. If the origin /// specifies a default port (e.g. 443 for HTTPS or 80 for HTTP), this will be dropped as part of normalization. /// Finally, the scheme and punycoded host name are culture invariant lower cased before being added to the <see cref="CorsPolicy.Origins"/> /// collection. /// </item> /// <item> /// For all other origins, normalization involves performing a culture invariant lower casing of the host name. /// </item> /// </list> /// </remarks> public CorsPolicyBuilder WithOrigins(params string[] origins) { if (origins is null) { throw new ArgumentNullException(nameof(origins)); } foreach (var origin in origins) { var normalizedOrigin = GetNormalizedOrigin(origin); _policy.Origins.Add(normalizedOrigin); } return this; } internal static string GetNormalizedOrigin(string origin) { if (origin is null) { throw new ArgumentNullException(nameof(origin)); } if (Uri.TryCreate(origin, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) && !string.Equals(uri.IdnHost, uri.Host, StringComparison.Ordinal)) { var builder = new UriBuilder(uri.Scheme.ToLowerInvariant(), uri.IdnHost.ToLowerInvariant()); if (!uri.IsDefaultPort) { // Uri does not have a way to differentiate between a port value inferred by default (e.g. Port = 80 for http://www.example.com) and // a default port value that is specified (e.g. Port = 80 for http://www.example.com:80). Although the HTTP or FETCH spec does not say // anything about including the default port as part of the Origin header, at the time of writing, browsers drop "default" port when navigating // and when sending the Origin header. All this goes to say, it appears OK to drop an explicitly specified port, // if it is the default port when working with an IDN host. builder.Port = uri.Port; } return builder.Uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped); } return origin.ToLowerInvariant(); } /// <summary> /// Adds the specified <paramref name="headers"/> to the policy. /// </summary> /// <param name="headers">The headers which need to be allowed in the request.</param> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder WithHeaders(params string[] headers) { foreach (var req in headers) { _policy.Headers.Add(req); } return this; } /// <summary> /// Adds the specified <paramref name="exposedHeaders"/> to the policy. /// </summary> /// <param name="exposedHeaders">The headers which need to be exposed to the client.</param> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder WithExposedHeaders(params string[] exposedHeaders) { foreach (var req in exposedHeaders) { _policy.ExposedHeaders.Add(req); } return this; } /// <summary> /// Adds the specified <paramref name="methods"/> to the policy. /// </summary> /// <param name="methods">The methods which need to be added to the policy.</param> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder WithMethods(params string[] methods) { foreach (var req in methods) { _policy.Methods.Add(req); } return this; } /// <summary> /// Sets the policy to allow credentials. /// </summary> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder AllowCredentials() { _policy.SupportsCredentials = true; return this; } /// <summary> /// Sets the policy to not allow credentials. /// </summary> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder DisallowCredentials() { _policy.SupportsCredentials = false; return this; } /// <summary> /// Ensures that the policy allows any origin. /// </summary> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder AllowAnyOrigin() { _policy.Origins.Clear(); _policy.Origins.Add(CorsConstants.AnyOrigin); return this; } /// <summary> /// Ensures that the policy allows any method. /// </summary> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder AllowAnyMethod() { _policy.Methods.Clear(); _policy.Methods.Add("*"); return this; } /// <summary> /// Ensures that the policy allows any header. /// </summary> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder AllowAnyHeader() { _policy.Headers.Clear(); _policy.Headers.Add("*"); return this; } /// <summary> /// Sets the preflightMaxAge for the underlying policy. /// </summary> /// <param name="preflightMaxAge">A positive <see cref="TimeSpan"/> indicating the time a preflight /// request can be cached.</param> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder SetPreflightMaxAge(TimeSpan preflightMaxAge) { _policy.PreflightMaxAge = preflightMaxAge; return this; } /// <summary> /// Sets the specified <paramref name="isOriginAllowed"/> for the underlying policy. /// </summary> /// <param name="isOriginAllowed">The function used by the policy to evaluate if an origin is allowed.</param> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder SetIsOriginAllowed(Func<string, bool> isOriginAllowed) { _policy.IsOriginAllowed = isOriginAllowed; return this; } /// <summary> /// Sets the <see cref="CorsPolicy.IsOriginAllowed"/> property of the policy to be a function /// that allows origins to match a configured wildcarded domain when evaluating if the /// origin is allowed. /// </summary> /// <returns>The current policy builder.</returns> public CorsPolicyBuilder SetIsOriginAllowedToAllowWildcardSubdomains() { _policy.IsOriginAllowed = _policy.IsOriginAnAllowedSubdomain; return this; } /// <summary> /// Builds a new <see cref="CorsPolicy"/> using the entries added. /// </summary> /// <returns>The constructed <see cref="CorsPolicy"/>.</returns> public CorsPolicy Build() { if (_policy.AllowAnyOrigin && _policy.SupportsCredentials) { throw new InvalidOperationException(Resources.InsecureConfiguration); } return _policy; } /// <summary> /// Combines the given <paramref name="policy"/> to the existing properties in the builder. /// </summary> /// <param name="policy">The policy which needs to be combined.</param> /// <returns>The current policy builder.</returns> private CorsPolicyBuilder Combine(CorsPolicy policy) { if (policy == null) { throw new ArgumentNullException(nameof(policy)); } WithOrigins(policy.Origins.ToArray()); WithHeaders(policy.Headers.ToArray()); WithExposedHeaders(policy.ExposedHeaders.ToArray()); WithMethods(policy.Methods.ToArray()); SetIsOriginAllowed(policy.IsOriginAllowed); if (policy.PreflightMaxAge.HasValue) { SetPreflightMaxAge(policy.PreflightMaxAge.Value); } if (policy.SupportsCredentials) { AllowCredentials(); } else { DisallowCredentials(); } return this; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Xml; using System.Xml.Serialization; using AgenaTrader.API; using AgenaTrader.Custom; using AgenaTrader.Plugins; using AgenaTrader.Helper; /// <summary> /// Version: 1.1.0 /// ------------------------------------------------------------------------- /// Simon Pucher 2017 /// ------------------------------------------------------------------------- /// ****** Important ****** /// To compile this script without any error you also need access to the utility indicator to use these global source code elements. /// You will find this indicator on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs /// ------------------------------------------------------------------------- /// Namespace holds all indicators and is required. Do not change it. /// </summary> namespace AgenaTrader.UserCode { [Description("Draw the candle of the higher timeframe on the chart.")] public class HigherTimeFrameCandle_Indicator : UserIndicator { //private static readonly TimeFrame TF_Day = new TimeFrame(DatafeedHistoryPeriodicity.Day, 1); //private static readonly TimeFrame TF_Week = new TimeFrame(DatafeedHistoryPeriodicity.Week, 1); //private static readonly TimeFrame TF_Month = new TimeFrame(DatafeedHistoryPeriodicity.Month, 1); private DatafeedHistoryPeriodicity _datafeedhistoryperidocity = DatafeedHistoryPeriodicity.Day; private int _periodicityvalue = 1; private int _maxcandles = 0; private Color _color_long_signal_background = Const.DefaultArrowLongColor; private Color _color_short_signal_background = Const.DefaultArrowShortColor; private int _opacity_signal = 25; protected override void OnBarsRequirements() { //Add(TF_Day); //Add(TF_Week); //Add(TF_Month); Add(new TimeFrame(this.DF_DatafeedHistoryPeriodicity, this.DF_periodicityvalues)); } protected override void OnInit() { //Add(new OutputDescriptor(Color.FromKnownColor(KnownColor.Orange), "MyPlot1")); IsOverlay = true; CalculateOnClosedBar = false; } protected override void OnCalculate() { //Always show the day candle int _timeseriescount = 1; if (ProcessingBarSeriesIndex == 1) { ////Change time frame to higher candles //if (this.TimeFrame.Periodicity == DatafeedHistoryPeriodicity.Day) //{ // _timeseriescount = 2; //} //else if (this.TimeFrame.Periodicity == DatafeedHistoryPeriodicity.Week) //{ // _timeseriescount = 3; //} ////Drawing //Color _col = Color.Gray; //if (Opens[_timeseriescount][1] > Closes[_timeseriescount][1]) //{ // _col = this.ColorShortSignalBackground; //} //else if (Opens[_timeseriescount][1] < Closes[_timeseriescount][1]) //{ // _col = this.ColorLongSignalBackground; //} //DateTime mystart = Times[_timeseriescount][1]; //DateTime myend = Times[_timeseriescount][0].AddSeconds(-1); //AddChartRectangle("HTFCandle-" + Times[_timeseriescount][1], true, mystart, Lows[_timeseriescount][1], myend, Highs[_timeseriescount][1], _col, _col, this.OpacitySignal); //Drawing if (MaxCandles == 0 || Closes[1].Count - ProcessingBarIndexes[1] <= this.MaxCandles) { Color _col = Color.Gray; if (Opens[_timeseriescount][1] > Closes[_timeseriescount][1]) { _col = this.ColorShortSignalBackground; } else if (Opens[_timeseriescount][1] < Closes[_timeseriescount][1]) { _col = this.ColorLongSignalBackground; } DateTime mystart = Times[_timeseriescount][1]; DateTime myend = Times[_timeseriescount][0].AddSeconds(-1); AddChartRectangle("HTFCandle-" + Times[_timeseriescount][1], true, mystart, Lows[_timeseriescount][1], myend, Highs[_timeseriescount][1], _col, _col, this.OpacitySignal); } } } public override string ToString() { return "Higher TimeFrame Candle (I)"; } public override string DisplayName { get { return "Higher TimeFrame Candle (I)"; } } #region Properties [Browsable(false)] [XmlIgnore()] public DataSeries MyPlot1 { get { return Outputs[0]; } } [Description("Select the timeframe of the periodicity.")] [InputParameter] [DisplayName("HTF TimeFrame")] public DatafeedHistoryPeriodicity DF_DatafeedHistoryPeriodicity { get { return _datafeedhistoryperidocity; } set { _datafeedhistoryperidocity = value; } } [Description("Select the value of the periodicity.")] [InputParameter] [DisplayName("HTF Value")] public int DF_periodicityvalues { get { return _periodicityvalue; } set { _periodicityvalue = value; } } /// <summary> /// </summary> [Description("Select opacity for the background in percent.")] [Category("Background")] [DisplayName("Opacity Background %")] public int OpacitySignal { get { return _opacity_signal; } set { if (value < 0) value = 0; if (value > 100) value = 100; _opacity_signal = value; } } /// <summary> /// </summary> [Description("Select the number of max. candles (0 = show all candles in the higher timeframe, 3 = show the last 3 higher timeframe candles)")] [InputParameter] [DisplayName("Max Candles")] public int MaxCandles { get { return _maxcandles; } set { _maxcandles = value; } } /// <summary> /// </summary> [Description("Select Color for the background in long setup.")] [Category("Background")] [DisplayName("Color Background Long")] public Color ColorLongSignalBackground { get { return _color_long_signal_background; } set { _color_long_signal_background = value; } } // Serialize Color object [Browsable(false)] public string ColorLongSignalBackgroundSerialize { get { return SerializableColor.ToString(_color_long_signal_background); } set { _color_long_signal_background = SerializableColor.FromString(value); } } /// <summary> /// </summary> [Description("Select Color for the background in short setup.")] [Category("Background")] [DisplayName("Color Background Short")] public Color ColorShortSignalBackground { get { return _color_short_signal_background; } set { _color_short_signal_background = value; } } // Serialize Color object [Browsable(false)] public string ColorShortSignalBackgroundSerialize { get { return SerializableColor.ToString(_color_short_signal_background); } set { _color_short_signal_background = SerializableColor.FromString(value); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.OS; using Android.Support.V4.Media.Session; using Com.Google.Android.Exoplayer2; using Com.Google.Android.Exoplayer2.Extractor; using Com.Google.Android.Exoplayer2.Source; using Com.Google.Android.Exoplayer2.Trackselection; using Com.Google.Android.Exoplayer2.Upstream; using Com.Google.Android.Exoplayer2.Util; using Plugin.MediaManager.Abstractions; using Plugin.MediaManager.Abstractions.EventArguments; using Plugin.MediaManager.Abstractions.Implementations; using Object = Java.Lang.Object; namespace Plugin.MediaManager.ExoPlayer { using Android.Webkit; using Java.IO; using Java.Lang; using Java.Util.Concurrent; using Plugin.MediaManager.Abstractions.Enums; using Console = System.Console; using Double = System.Double; [Service] [IntentFilter(new[] { ActionPlay, ActionPause, ActionStop, ActionTogglePlayback, ActionNext, ActionPrevious })] public class ExoPlayerAudioService : MediaServiceBase, IExoPlayerEventListener, TrackSelector.IEventListener, ExtractorMediaSource.IEventListener { private SimpleExoPlayer _mediaPlayer; private IScheduledExecutorService _executorService = Executors.NewSingleThreadScheduledExecutor(); private IScheduledFuture _scheduledFuture; public override TimeSpan Position { get { double parsedPosition; var position = _mediaPlayer?.CurrentPosition; if (position > 0 && Double.TryParse(position.ToString(), out parsedPosition)) return TimeSpan.FromMilliseconds(parsedPosition); return TimeSpan.Zero; } } public override TimeSpan Duration { get { double parsedDuration; var duration = _mediaPlayer?.Duration; if (duration > 0 && Double.TryParse(duration.ToString(), out parsedDuration)) return TimeSpan.FromMilliseconds(parsedDuration); return TimeSpan.Zero; } } public override TimeSpan Buffered { get { double parsedBuffering; var buffered = _mediaPlayer?.BufferedPosition; if (buffered > 0 && Double.TryParse(buffered.ToString(), out parsedBuffering)) return TimeSpan.FromMilliseconds(parsedBuffering); return TimeSpan.Zero; } } public override void InitializePlayer() { var mainHandler = new Handler(); var trackSelector = new DefaultTrackSelector(mainHandler); trackSelector.AddListener(this); var loadControl = new DefaultLoadControl(); if (_mediaPlayer == null) { _mediaPlayer = ExoPlayerFactory.NewSimpleInstance(ApplicationContext, trackSelector, loadControl); _mediaPlayer.AddListener(this); } StatusChanged += (sender, args) => OnStatusChangedHandler(args); } public override void InitializePlayerWithUrl(string audioUrl) { throw new NotImplementedException(); } public override void SetMediaPlayerOptions() { } public override async Task Play(IMediaFile mediaFile = null) { await base.Play(mediaFile); _mediaPlayer.PlayWhenReady = true; ManuallyPaused = false; } public override Task Seek(TimeSpan position) { return Task.Run(() => { _mediaPlayer?.SeekTo(Convert.ToInt64(position.TotalMilliseconds)); }); } public override async Task Pause() { _mediaPlayer.PlayWhenReady = false; ManuallyPaused = true; await base.Pause(); } public override async Task Stop() { _mediaPlayer.Stop(); await base.Stop(); } public override void SetVolume(float leftVolume, float rightVolume) { _mediaPlayer.Volume = leftVolume; } public override async Task<bool> SetMediaPlayerDataSource() { var source = GetSource(CurrentFile.Url); _mediaPlayer.Prepare(source); return await Task.FromResult(true); } protected override void Resume() { } #region ************ ExoPlayer Events ***************** public void OnLoadingChanged(bool isLoading) { Console.WriteLine("Loading changed"); } public void OnPlayerError(ExoPlaybackException ex) { OnMediaFileFailed(new MediaFileFailedEventArgs(ex, CurrentFile)); } public void OnPlayerStateChanged(bool playWhenReady, int state) { if (state == Com.Google.Android.Exoplayer2.ExoPlayer.StateEnded) { OnMediaFinished(new MediaFinishedEventArgs(CurrentFile)); } else { var status = GetStatusByIntValue(state); var compatState = GetCompatValueByStatus(status); //OnStatusChanged(new StatusChangedEventArgs(status)); SessionManager.UpdatePlaybackState(compatState, Position.Seconds); } } public void OnPositionDiscontinuity() { Console.WriteLine("OnPositionDiscontinuity"); } public void OnTimelineChanged(Timeline timeline, Object manifest) { Console.WriteLine("OnTimelineChanged"); } public void OnTrackSelectionsChanged(TrackSelections p0) { Console.WriteLine("TrackSelectionChanged"); } /* TODO: Implement IOutput Interface => https://github.com/martijn00/ExoPlayerXamarin/issues/38 */ //public void OnMetadata(Object obj) //{ // Console.WriteLine("OnMetadata"); //} #endregion private MediaPlayerStatus GetStatusByIntValue(int state) { switch (state) { case Com.Google.Android.Exoplayer2.ExoPlayer.StateBuffering: return MediaPlayerStatus.Buffering; case Com.Google.Android.Exoplayer2.ExoPlayer.StateReady: return !ManuallyPaused && !TransientPaused ? MediaPlayerStatus.Playing : MediaPlayerStatus.Paused; case Com.Google.Android.Exoplayer2.ExoPlayer.StateIdle: return MediaPlayerStatus.Loading; default: return MediaPlayerStatus.Failed; } } private int GetCompatValueByStatus(MediaPlayerStatus state) { switch (state) { case MediaPlayerStatus.Buffering: return PlaybackStateCompat.StateBuffering; case MediaPlayerStatus.Failed: return PlaybackStateCompat.StateError; case MediaPlayerStatus.Loading: return PlaybackStateCompat.StateSkippingToQueueItem; case MediaPlayerStatus.Paused: return PlaybackStateCompat.StatePaused; case MediaPlayerStatus.Playing: return PlaybackStateCompat.StatePlaying; case MediaPlayerStatus.Stopped: return PlaybackStateCompat.StateStopped; default: return PlaybackStateCompat.StateNone; } } [Obsolete("deprecated")] public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) { HandleIntent(intent); return base.OnStartCommand(intent, flags, startId); } private void OnStatusChangedHandler(StatusChangedEventArgs args) { if (args.Status == MediaPlayerStatus.Buffering) { CancelBufferingTask(); StartBufferingSchedule(); } if (args.Status == MediaPlayerStatus.Stopped || args.Status == MediaPlayerStatus.Failed) CancelBufferingTask(); } private void CancelBufferingTask() { _scheduledFuture?.Cancel(false); OnBufferingChanged(new BufferingChangedEventArgs(0, TimeSpan.Zero)); } private void StartBufferingSchedule() { var handler = new Handler(); var runnable = new Runnable(() => { handler.Post(OnBuffering); }); if (!_executorService.IsShutdown) _scheduledFuture = _executorService.ScheduleAtFixedRate(runnable, 100, 1000, TimeUnit.Milliseconds); } private void OnBuffering() { if(_mediaPlayer == null || _mediaPlayer.BufferedPosition > TimeSpan.MaxValue.TotalMilliseconds - 100) return; OnBufferingChanged( new BufferingChangedEventArgs( _mediaPlayer.BufferedPercentage, TimeSpan.FromMilliseconds(Convert.ToInt64(_mediaPlayer.BufferedPosition)))); } private IMediaSource GetSource(string url) { string escapedUrl = Uri.EscapeDataString(url); var uri = Android.Net.Uri.Parse(escapedUrl); var factory = URLUtil.IsHttpUrl(escapedUrl) || URLUtil.IsHttpsUrl(escapedUrl) ? GetHttpFactory() : new FileDataSourceFactory(); var extractorFactory = new DefaultExtractorsFactory(); return new ExtractorMediaSource(uri , factory , extractorFactory, null, this); } private IDataSourceFactory GetHttpFactory() { var bandwithMeter = new DefaultBandwidthMeter(); var httpFactory = new DefaultHttpDataSourceFactory(ExoPlayerUtil.GetUserAgent(this, ApplicationInfo.Name), bandwithMeter); return new HttpSourceFactory(httpFactory, RequestHeaders); } public override Task Play(IEnumerable<IMediaFile> mediaFiles) { throw new NotImplementedException(); } public void OnLoadError(IOException ex) { OnMediaFileFailed(new MediaFileFailedEventArgs(ex, CurrentFile)); } } public class HttpSourceFactory : Object, IDataSourceFactory { private DefaultHttpDataSourceFactory _httpFactory; private Dictionary<string, string> _headers; public HttpSourceFactory(DefaultHttpDataSourceFactory httpFactory, Dictionary<string, string> headers) { _httpFactory = httpFactory; _headers = headers; } public HttpSourceFactory() { Console.WriteLine("HSF called"); } public IDataSource CreateDataSource() { var source = _httpFactory.CreateDataSource() as DefaultHttpDataSource; if (_headers == null || !_headers.Any()) return source; foreach (var header in _headers) { source?.SetRequestProperty(header.Key, header.Value); } return source; } public IDataSource createDataSource() { return CreateDataSource(); } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Linq; using System.Text; using Encog.App.Analyst.Script; using Encog.App.Analyst.Script.Prop; using Encog.Util.CSV; namespace Encog.App.Analyst.Analyze { /// <summary> /// This class represents a field that the Encog Analyst is in the process of /// analyzing. This class is used to track statistical information on the field /// that will help the Encog analyst determine what type of field this is, and /// how to normalize it. /// </summary> public class AnalyzedField : DataField { /// <summary> /// A mapping between the class names that the class items. /// </summary> private readonly IDictionary<String, AnalystClassItem> _classMap; /// <summary> /// The analyst script that the results are saved to. /// </summary> private readonly AnalystScript _script; /// <summary> /// The total for standard deviation calculation. /// </summary> private double _devTotal; /// <summary> /// The number of instances of this field. /// </summary> private int _instances; /// <summary> /// Tge sum of all values of this field. /// </summary> private double _total; /// <summary> /// The numeric format to use. /// </summary> private CSVFormat _fmt; /// <summary> /// Construct an analyzed field. /// </summary> /// <param name="theScript">The script being analyzed.</param> /// <param name="name">The name of the field.</param> public AnalyzedField(AnalystScript theScript, String name) : base(name) { _classMap = new Dictionary<String, AnalystClassItem>(); _instances = 0; _script = theScript; _fmt = _script.DetermineFormat(); } /// <summary> /// Get the class members. /// </summary> public IList<AnalystClassItem> AnalyzedClassMembers { get { List<string> sorted = _classMap.Keys.ToList(); sorted.Sort(); return sorted.Select(str => _classMap[str]).ToList(); } } /// <summary> /// Perform a pass one analysis of this field. /// </summary> /// <param name="str">The current value.</param> public void Analyze1(String v) { bool accountedFor = false; string str = v.Trim(); if (str.Trim().Length == 0 || str.Equals("?")) { Complete = false; return; } _instances++; if (Real) { try { double d = _fmt.Parse(str); Max = Math.Max(d, Max); Min = Math.Min(d, Min); _total += d; accountedFor = true; } catch (FormatException) { Real = false; if (!Integer) { Max = 0; Min = 0; StandardDeviation = 0; } } } if (Integer) { try { int i = Int32.Parse(str); Max = Math.Max(i, Max); Min = Math.Min(i, Min); if (!accountedFor) { _total += i; } } catch (FormatException) { Integer = false; if (!Real) { Max = 0; Min = 0; StandardDeviation = 0; } } } if (Class) { AnalystClassItem item; // is this a new class? if (!_classMap.ContainsKey(str)) { item = new AnalystClassItem(str, str, 1); _classMap[str] = item; // do we have too many different classes? int max = _script.Properties.GetPropertyInt( ScriptProperties.SetupConfigMaxClassCount); if (_classMap.Count > max) { Class = false; } } else { item = _classMap[str]; item.IncreaseCount(); } } } /// <summary> /// Perform a pass two analysis of this field. /// </summary> /// <param name="str">The current value.</param> public void Analyze2(String str) { if (str.Trim().Length == 0) { return; } if (Real || Integer) { if (!str.Equals("") && !str.Equals("?")) { double d = _fmt.Parse(str) - Mean; _devTotal += d*d; } } } /// <summary> /// Complete pass 1. /// </summary> public void CompletePass1() { _devTotal = 0; if (_instances == 0) { Mean = 0; } else { Mean = _total/_instances; } } /// <summary> /// Complete pass 2. /// </summary> public void CompletePass2() { StandardDeviation = Math.Sqrt(_devTotal/_instances); } /// <summary> /// Finalize the field, and create a DataField. /// </summary> /// <returns>The new DataField.</returns> public DataField FinalizeField() { var result = new DataField(Name) { Name = Name, Min = Min, Max = Max, Mean = Mean, StandardDeviation = StandardDeviation, Integer = Integer, Real = Real, Class = Class, Complete = Complete }; // if max and min are the same, we are dealing with a zero-sized range, // which will cause other issues. This is caused by ever number in the // column having exactly (or nearly exactly) the same value. Provide a // small range around that value so that every value in this column normalizes // to the midpoint of the desired normalization range, typically 0 or 0.5. if (Math.Abs(Max - Min) < EncogFramework.DefaultDoubleEqual) { result.Min = Min - 0.0001; result.Max = Min + 0.0001; } result.ClassMembers.Clear(); if (result.Class) { IList<AnalystClassItem> list = AnalyzedClassMembers; foreach (AnalystClassItem item in list) { result.ClassMembers.Add(item); } } return result; } /// <inheritdoc /> public override sealed String ToString() { var result = new StringBuilder("["); result.Append(GetType().Name); result.Append(" total="); result.Append(_total); result.Append(", instances="); result.Append(_instances); result.Append("]"); return result.ToString(); } } }
// // ImportDialog.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Gtk; using Hyena; using Mono.Unix; using Banshee.Configuration.Schema; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Gui; using Banshee.Gui.Dialogs; namespace Banshee.Library.Gui { public class ImportDialog : BansheeDialog { private ComboBox source_combo_box; private ListStore source_model; private Button import_button; private CheckButton do_not_show_check_button; public ImportDialog () : this (false) { } public ImportDialog (bool doNotShowAgainVisible) : base (String.Empty) { Resizable = false; DefaultResponse = ResponseType.Ok; AddStockButton (Stock.Cancel, ResponseType.Cancel); import_button = AddButton (String.Empty, ResponseType.Ok, true); uint row = 0; var table = new Table (doNotShowAgainVisible ? (uint)4 : (uint)3, 2, false) { RowSpacing = 12, ColumnSpacing = 16, Homogeneous = false }; table.Attach (new Label () { Markup = Catalog.GetString ("<big><b>Import Media to Library</b></big>"), Xalign = 0.0f }, 1, 2, row, ++row); if (ServiceManager.SourceManager.DefaultSource.Count == 0) { table.Attach (new Label () { Text = Catalog.GetString ("Your media library is empty. You may import new music and videos into your library now, or choose to do so later."), Xalign = 0.0f, Wrap = true }, 1, 2, row, ++row); } PopulateSourceList (); var vbox = new VBox () { Spacing = 2 }; vbox.PackStart (new Label () { Text = Catalog.GetString ("Import _from:"), Xalign = 0.0f, UseUnderline = true, MnemonicWidget = source_combo_box }, false, false, 0); vbox.PackStart (source_combo_box, false, false, 0); table.Attach (vbox, 1, 2, row, ++row); if (doNotShowAgainVisible) { table.Attach (do_not_show_check_button = new CheckButton ( Catalog.GetString ("Do not show this dialog again")), 1, 2, row, ++row); } table.Attach (new Image () { IconName = "drive-harddisk", IconSize = (int)IconSize.Dialog, Yalign = 0.0f }, 0, 1, 0, row, AttachOptions.Shrink, AttachOptions.Expand | AttachOptions.Fill, 0, 0); VBox.PackStart (table, true, true, 0); VBox.ShowAll (); if (doNotShowAgainVisible) { DoNotShowAgainVisible = doNotShowAgainVisible; } ServiceManager.SourceManager.SourceAdded += OnSourceAdded; ServiceManager.SourceManager.SourceRemoved += OnSourceRemoved; ServiceManager.SourceManager.SourceUpdated += OnSourceUpdated; } protected override void OnStyleSet (Style previous_style) { base.OnStyleSet (previous_style); UpdateIcons (); } private void UpdateImportLabel () { string label = ActiveSource == null ? null : ActiveSource.ImportLabel; import_button.Label = label ?? Catalog.GetString ("_Import"); import_button.WidthRequest = Math.Max (import_button.WidthRequest, 140); } private void PopulateSourceList () { source_model = new ListStore (typeof (Gdk.Pixbuf), typeof (string), typeof (IImportSource)); source_combo_box = new ComboBox (); source_combo_box.Changed += delegate { UpdateImportLabel (); }; source_combo_box.Model = source_model; source_combo_box.RowSeparatorFunc = (model, iter) => model.GetValue (iter, 2) == null; CellRendererPixbuf pixbuf_cr = new CellRendererPixbuf (); CellRendererText text_cr = new CellRendererText (); source_combo_box.PackStart (pixbuf_cr, false); source_combo_box.PackStart (text_cr, true); source_combo_box.SetAttributes (pixbuf_cr, "pixbuf", 0); source_combo_box.SetAttributes (text_cr, "text", 1); TreeIter active_iter = TreeIter.Zero; List<IImportSource> sources = new List<IImportSource> (); // Add the standalone import sources foreach (IImportSource source in ServiceManager.Get<ImportSourceManager> ()) { sources.Add (source); } // Find active sources that implement IImportSource foreach (Source source in ServiceManager.SourceManager.Sources) { if (source is IImportSource) { sources.Add ((IImportSource)source); } } // Sort the sources by their SortOrder properties sources.Sort (import_source_comparer); // And actually add them to the dialog int? last_sort_order = null; foreach (IImportSource source in sources) { if (last_sort_order != null && last_sort_order / 10 != source.SortOrder / 10) { source_model.AppendValues (null, null, null); } AddSource (source); last_sort_order = source.SortOrder; } if (!active_iter.Equals(TreeIter.Zero) || (active_iter.Equals (TreeIter.Zero) && source_model.GetIterFirst (out active_iter))) { source_combo_box.SetActiveIter (active_iter); } } private void UpdateIcons () { for (int i = 0, n = source_model.IterNChildren (); i < n; i++) { TreeIter iter; if (source_model.IterNthChild (out iter, i)) { object o = source_model.GetValue (iter, 0); IImportSource source = (IImportSource)source_model.GetValue (iter, 2); if (o != null) { ((Gdk.Pixbuf)o).Dispose (); } if (source != null) { var icon = GetIcon (source); if (icon != null) { source_model.SetValue (iter, 0, icon); } } } } } private Gdk.Pixbuf GetIcon (IImportSource source) { return IconThemeUtils.LoadIcon (22, source.IconNames); } private TreeIter AddSource (IImportSource source) { if (source == null) { return TreeIter.Zero; } return source_model.AppendValues (GetIcon (source), source.Name, source); } private void OnSourceAdded (SourceAddedArgs args) { if(args.Source is IImportSource) { ThreadAssist.ProxyToMain (delegate { AddSource ((IImportSource)args.Source); }); } } private void OnSourceRemoved (SourceEventArgs args) { if (args.Source is IImportSource) { ThreadAssist.ProxyToMain (delegate { TreeIter iter; if (FindSourceIter (out iter, (IImportSource)args.Source)) { source_model.Remove (ref iter); } }); } } private void OnSourceUpdated (SourceEventArgs args) { if (args.Source is IImportSource) { ThreadAssist.ProxyToMain (delegate { TreeIter iter; if(FindSourceIter (out iter, (IImportSource)args.Source)) { source_model.SetValue (iter, 1, args.Source.Name); } }); } } private bool FindSourceIter (out TreeIter iter, IImportSource source) { iter = TreeIter.Zero; for (int i = 0, n = source_model.IterNChildren (); i < n; i++) { TreeIter _iter; if (source_model.IterNthChild (out _iter, i)) { if (source == source_model.GetValue (_iter, 2)) { iter = _iter; return true; } } } return false; } private bool DoNotShowAgainVisible { get { return do_not_show_check_button.Visible; } set { do_not_show_check_button.Visible = value; } } /*private bool DoNotShowAgain { get { return do_not_show_check_button.Active; } }*/ public IImportSource ActiveSource { get { TreeIter iter; if (source_combo_box.GetActiveIter (out iter)) { return (IImportSource)source_model.GetValue (iter, 2); } return null; } } private static IComparer<IImportSource> import_source_comparer = new ImportSourceComparer (); private class ImportSourceComparer : IComparer<IImportSource> { public int Compare (IImportSource a, IImportSource b) { int ret = a.SortOrder.CompareTo (b.SortOrder); return ret != 0 ? ret : a.Name.CompareTo (b.Name); } } } }
// 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.Linq; using System.Net.Http.Headers; using Xunit; namespace System.Net.Http.Tests { public class RangeHeaderValueTest { [Fact] public void Ctor_InvalidRange_Throw() { Assert.Throws<ArgumentOutOfRangeException>(() => { new RangeHeaderValue(5, 2); }); } [Fact] public void Unit_GetAndSetValidAndInvalidValues_MatchExpectation() { RangeHeaderValue range = new RangeHeaderValue(); range.Unit = "myunit"; Assert.Equal("myunit", range.Unit); AssertExtensions.Throws<ArgumentException>("value", () => { range.Unit = null; }); AssertExtensions.Throws<ArgumentException>("value", () => { range.Unit = ""; }); Assert.Throws<FormatException>(() => { range.Unit = " x"; }); Assert.Throws<FormatException>(() => { range.Unit = "x "; }); Assert.Throws<FormatException>(() => { range.Unit = "x y"; }); } [Fact] public void ToString_UseDifferentRanges_AllSerializedCorrectly() { RangeHeaderValue range = new RangeHeaderValue(); range.Unit = "myunit"; range.Ranges.Add(new RangeItemHeaderValue(1, 3)); Assert.Equal("myunit=1-3", range.ToString()); range.Ranges.Add(new RangeItemHeaderValue(5, null)); range.Ranges.Add(new RangeItemHeaderValue(null, 17)); Assert.Equal("myunit=1-3, 5-, -17", range.ToString()); } [Fact] public void GetHashCode_UseSameAndDifferentRanges_SameOrDifferentHashCodes() { RangeHeaderValue range1 = new RangeHeaderValue(1, 2); RangeHeaderValue range2 = new RangeHeaderValue(1, 2); range2.Unit = "BYTES"; RangeHeaderValue range3 = new RangeHeaderValue(1, null); RangeHeaderValue range4 = new RangeHeaderValue(null, 2); RangeHeaderValue range5 = new RangeHeaderValue(); range5.Ranges.Add(new RangeItemHeaderValue(1, 2)); range5.Ranges.Add(new RangeItemHeaderValue(3, 4)); RangeHeaderValue range6 = new RangeHeaderValue(); range6.Ranges.Add(new RangeItemHeaderValue(3, 4)); // reverse order of range5 range6.Ranges.Add(new RangeItemHeaderValue(1, 2)); Assert.Equal(range1.GetHashCode(), range2.GetHashCode()); Assert.NotEqual(range1.GetHashCode(), range3.GetHashCode()); Assert.NotEqual(range1.GetHashCode(), range4.GetHashCode()); Assert.NotEqual(range1.GetHashCode(), range5.GetHashCode()); Assert.Equal(range5.GetHashCode(), range6.GetHashCode()); } [Fact] public void Equals_UseSameAndDifferentRanges_EqualOrNotEqualNoExceptions() { RangeHeaderValue range1 = new RangeHeaderValue(1, 2); RangeHeaderValue range2 = new RangeHeaderValue(1, 2); range2.Unit = "BYTES"; RangeHeaderValue range3 = new RangeHeaderValue(1, null); RangeHeaderValue range4 = new RangeHeaderValue(null, 2); RangeHeaderValue range5 = new RangeHeaderValue(); range5.Ranges.Add(new RangeItemHeaderValue(1, 2)); range5.Ranges.Add(new RangeItemHeaderValue(3, 4)); RangeHeaderValue range6 = new RangeHeaderValue(); range6.Ranges.Add(new RangeItemHeaderValue(3, 4)); // reverse order of range5 range6.Ranges.Add(new RangeItemHeaderValue(1, 2)); RangeHeaderValue range7 = new RangeHeaderValue(1, 2); range7.Unit = "other"; Assert.False(range1.Equals(null), "bytes=1-2 vs. <null>"); Assert.True(range1.Equals(range2), "bytes=1-2 vs. BYTES=1-2"); Assert.False(range1.Equals(range3), "bytes=1-2 vs. bytes=1-"); Assert.False(range1.Equals(range4), "bytes=1-2 vs. bytes=-2"); Assert.False(range1.Equals(range5), "bytes=1-2 vs. bytes=1-2,3-4"); Assert.True(range5.Equals(range6), "bytes=1-2,3-4 vs. bytes=3-4,1-2"); Assert.False(range1.Equals(range7), "bytes=1-2 vs. other=1-2"); } [Fact] public void Clone_Call_CloneFieldsMatchSourceFields() { RangeHeaderValue source = new RangeHeaderValue(1, 2); RangeHeaderValue clone = (RangeHeaderValue)((ICloneable)source).Clone(); Assert.Equal(1, source.Ranges.Count); Assert.Equal(source.Unit, clone.Unit); Assert.Equal(source.Ranges.Count, clone.Ranges.Count); Assert.Equal(source.Ranges.ElementAt(0), clone.Ranges.ElementAt(0)); source.Unit = "custom"; source.Ranges.Add(new RangeItemHeaderValue(3, null)); source.Ranges.Add(new RangeItemHeaderValue(null, 4)); clone = (RangeHeaderValue)((ICloneable)source).Clone(); Assert.Equal(3, source.Ranges.Count); Assert.Equal(source.Unit, clone.Unit); Assert.Equal(source.Ranges.Count, clone.Ranges.Count); Assert.Equal(source.Ranges.ElementAt(0), clone.Ranges.ElementAt(0)); Assert.Equal(source.Ranges.ElementAt(1), clone.Ranges.ElementAt(1)); Assert.Equal(source.Ranges.ElementAt(2), clone.Ranges.ElementAt(2)); } [Fact] public void GetRangeLength_DifferentValidScenarios_AllReturnNonZero() { RangeHeaderValue result = null; CallGetRangeLength(" custom = 1 - 2", 1, 14, out result); Assert.Equal("custom", result.Unit); Assert.Equal(1, result.Ranges.Count); Assert.Equal(new RangeItemHeaderValue(1, 2), result.Ranges.First()); CallGetRangeLength("bytes =1-2,,3-, , ,-4,,", 0, 23, out result); Assert.Equal("bytes", result.Unit); Assert.Equal(3, result.Ranges.Count); Assert.Equal(new RangeItemHeaderValue(1, 2), result.Ranges.ElementAt(0)); Assert.Equal(new RangeItemHeaderValue(3, null), result.Ranges.ElementAt(1)); Assert.Equal(new RangeItemHeaderValue(null, 4), result.Ranges.ElementAt(2)); } [Fact] public void GetRangeLength_DifferentInvalidScenarios_AllReturnZero() { CheckInvalidGetRangeLength(" bytes=1-2", 0); // no leading whitespace allowed CheckInvalidGetRangeLength("bytes=1", 0); CheckInvalidGetRangeLength("bytes=", 0); CheckInvalidGetRangeLength("bytes", 0); CheckInvalidGetRangeLength("bytes 1-2", 0); CheckInvalidGetRangeLength("bytes=1-2.5", 0); CheckInvalidGetRangeLength("bytes= ,,, , ,,", 0); CheckInvalidGetRangeLength("", 0); CheckInvalidGetRangeLength(null, 0); } [Fact] public void Parse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidParse(" bytes=1-2 ", new RangeHeaderValue(1, 2)); RangeHeaderValue expected = new RangeHeaderValue(); expected.Unit = "custom"; expected.Ranges.Add(new RangeItemHeaderValue(null, 5)); expected.Ranges.Add(new RangeItemHeaderValue(1, 4)); CheckValidParse("custom = - 5 , 1 - 4 ,,", expected); } [Fact] public void Parse_SetOfInvalidValueStrings_Throws() { CheckInvalidParse("bytes=1-2x"); // only delimiter ',' allowed after last range CheckInvalidParse("x bytes=1-2"); CheckInvalidParse("bytes=1-2.4"); CheckInvalidParse(null); CheckInvalidParse(string.Empty); } [Fact] public void TryParse_SetOfValidValueStrings_ParsedCorrectly() { CheckValidTryParse(" bytes=1-2 ", new RangeHeaderValue(1, 2)); RangeHeaderValue expected = new RangeHeaderValue(); expected.Unit = "custom"; expected.Ranges.Add(new RangeItemHeaderValue(null, 5)); expected.Ranges.Add(new RangeItemHeaderValue(1, 4)); CheckValidTryParse("custom = - 5 , 1 - 4 ,,", expected); } [Fact] public void TryParse_SetOfInvalidValueStrings_ReturnsFalse() { CheckInvalidTryParse("bytes=1-2x"); // only delimiter ',' allowed after last range CheckInvalidTryParse("x bytes=1-2"); CheckInvalidTryParse("bytes=1-2.4"); CheckInvalidTryParse(null); CheckInvalidTryParse(string.Empty); } #region Helper methods private void CheckValidParse(string input, RangeHeaderValue expectedResult) { RangeHeaderValue result = RangeHeaderValue.Parse(input); Assert.Equal(expectedResult, result); } private void CheckInvalidParse(string input) { Assert.Throws<FormatException>(() => { RangeHeaderValue.Parse(input); }); } private void CheckValidTryParse(string input, RangeHeaderValue expectedResult) { RangeHeaderValue result = null; Assert.True(RangeHeaderValue.TryParse(input, out result)); Assert.Equal(expectedResult, result); } private void CheckInvalidTryParse(string input) { RangeHeaderValue result = null; Assert.False(RangeHeaderValue.TryParse(input, out result)); Assert.Null(result); } private static void CallGetRangeLength(string input, int startIndex, int expectedLength, out RangeHeaderValue result) { object temp = null; Assert.Equal(expectedLength, RangeHeaderValue.GetRangeLength(input, startIndex, out temp)); result = temp as RangeHeaderValue; } private static void CheckInvalidGetRangeLength(string input, int startIndex) { object result = null; Assert.Equal(0, RangeHeaderValue.GetRangeLength(input, startIndex, out result)); Assert.Null(result); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using OmniSharp.Cake.Utilities; using OmniSharp.Models; using OmniSharp.Models.Navigate; using OmniSharp.Models.MembersTree; using OmniSharp.Models.Rename; using OmniSharp.Models.V2; using OmniSharp.Models.V2.CodeActions; using OmniSharp.Models.V2.CodeStructure; using OmniSharp.Utilities; namespace OmniSharp.Cake.Extensions { internal static class ResponseExtensions { public static QuickFixResponse OnlyThisFile(this QuickFixResponse response, string fileName) { if (response?.QuickFixes == null) { return response; } var quickFixes = response.QuickFixes.Where(x => PathsAreEqual(x.FileName, fileName)); response.QuickFixes = quickFixes; return response; bool PathsAreEqual(string x, string y) { if (x == null && y == null) { return true; } if (x == null || y == null) { return false; } var comparer = PlatformHelper.IsWindows ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; return Path.GetFullPath(x).Equals(Path.GetFullPath(y), comparer); } } public static Task<QuickFixResponse> TranslateAsync(this QuickFixResponse response, OmniSharpWorkspace workspace) { return response.TranslateAsync(workspace, new Request()); } public static async Task<QuickFixResponse> TranslateAsync(this QuickFixResponse response, OmniSharpWorkspace workspace, Request request, bool removeGenerated = false) { var quickFixes = new List<QuickFix>(); foreach (var quickFix in response.QuickFixes) { await quickFix.TranslateAsync(workspace, request); if (quickFix.Line < 0) { continue; } if (removeGenerated && quickFix.FileName.Equals(Constants.Paths.Generated)) { continue; } quickFixes.Add(quickFix); } response.QuickFixes = quickFixes; return response; } public static async Task<NavigateResponse> TranslateAsync(this NavigateResponse response, OmniSharpWorkspace workspace, Request request) { var (line, _) = await LineIndexHelper.TranslateFromGenerated(request.FileName, response.Line, workspace, true); response.Line = line; return response; } public static async Task<FileMemberTree> TranslateAsync(this FileMemberTree response, OmniSharpWorkspace workspace, Request request) { var zeroIndex = await LineIndexHelper.TranslateToGenerated(request.FileName, 0, workspace); var topLevelTypeDefinitions = new List<FileMemberElement>(); foreach (var topLevelTypeDefinition in response.TopLevelTypeDefinitions) { if (topLevelTypeDefinition.Location.Line < zeroIndex) { continue; } await topLevelTypeDefinition.TranslateAsync(workspace, request); if (topLevelTypeDefinition.Location.Line >= 0) { topLevelTypeDefinitions.Add(topLevelTypeDefinition); } } response.TopLevelTypeDefinitions = topLevelTypeDefinitions; return response; } public static async Task<RenameResponse> TranslateAsync(this RenameResponse response, OmniSharpWorkspace workspace, RenameRequest request) { var changes = new Dictionary<string, List<LinePositionSpanTextChange>>(); foreach (var change in response.Changes) { await PopulateModificationsAsync(change, workspace, changes); } response.Changes = changes.Select(x => new ModifiedFileResponse(x.Key) { Changes = x.Value }); return response; } public static async Task<RunCodeActionResponse> TranslateAsync(this RunCodeActionResponse response, OmniSharpWorkspace workspace) { if (response?.Changes == null) { return response; } var fileOperations = new List<FileOperationResponse>(); var changes = new Dictionary<string, List<LinePositionSpanTextChange>>(); foreach (var fileOperation in response.Changes) { if (fileOperation.ModificationType == FileModificationType.Modified && fileOperation is ModifiedFileResponse modifiedFile) { await PopulateModificationsAsync(modifiedFile, workspace, changes); } fileOperations.Add(fileOperation); } foreach (var change in changes) { if (fileOperations.FirstOrDefault(x => x.FileName == change.Key && x.ModificationType == FileModificationType.Modified) is ModifiedFileResponse modifiedFile) { modifiedFile.Changes = change.Value; } } response.Changes = fileOperations; return response; } public static async Task<CodeStructureResponse> TranslateAsync(this CodeStructureResponse response, OmniSharpWorkspace workspace, CodeStructureRequest request) { var zeroIndex = await LineIndexHelper.TranslateToGenerated(request.FileName, 0, workspace); var elements = new List<CodeElement>(); foreach (var element in response.Elements) { if (element.Ranges.Values.Any(x => x.Start.Line < zeroIndex)) { continue; } var translatedElement = await element.TranslateAsync(workspace, request); if (translatedElement.Ranges.Values.Any(x => x.Start.Line < 0)) { continue; } elements.Add(translatedElement); } response.Elements = elements; return response; } public static async Task<BlockStructureResponse> TranslateAsync(this BlockStructureResponse response, OmniSharpWorkspace workspace, SimpleFileRequest request) { if (response?.Spans == null) { return response; } var spans = new List<CodeFoldingBlock>(); foreach (var span in response.Spans) { var range = await span.Range.TranslateAsync(workspace, request); if (range.Start.Line < 0) { continue; } spans.Add(new CodeFoldingBlock(range, span.Kind)); } response.Spans = spans; return response; } private static async Task<CodeElement> TranslateAsync(this CodeElement element, OmniSharpWorkspace workspace, SimpleFileRequest request) { var builder = new CodeElement.Builder { Kind = element.Kind, DisplayName = element.DisplayName, Name = element.Name }; foreach (var property in element.Properties ?? Enumerable.Empty<KeyValuePair<string, object>>()) { builder.AddProperty(property.Key, property.Value); } foreach (var range in element.Ranges ?? Enumerable.Empty<KeyValuePair<string, Range>>()) { builder.AddRange(range.Key, await range.Value.TranslateAsync(workspace, request)); } foreach (var childElement in element.Children ?? Enumerable.Empty<CodeElement>()) { var translatedElement = await childElement.TranslateAsync(workspace, request); // This is plain stupid, but someone might put a #load directive inside a method or class if (translatedElement.Ranges.Values.Any(x => x.Start.Line < 0)) { continue; } builder.AddChild(childElement); } return builder.ToCodeElement(); } private static async Task<Range> TranslateAsync(this Range range, OmniSharpWorkspace workspace, SimpleFileRequest request) { var (line, _) = await LineIndexHelper.TranslateFromGenerated(request.FileName, range.Start.Line, workspace, true); if (range.Start.Line == range.End.Line) { range.Start.Line = line; range.End.Line = line; return range; } range.Start.Line = line; (line, _) = await LineIndexHelper.TranslateFromGenerated(request.FileName, range.End.Line, workspace, true); range.End.Line = line; return range; } private static async Task<FileMemberElement> TranslateAsync(this FileMemberElement element, OmniSharpWorkspace workspace, Request request) { element.Location = await element.Location.TranslateAsync(workspace, request); var childNodes = new List<FileMemberElement>(); foreach (var childNode in element.ChildNodes) { await childNode.TranslateAsync(workspace, request); if (childNode.Location.Line >= 0) { childNodes.Add(childNode); } } element.ChildNodes = childNodes; return element; } private static async Task<QuickFix> TranslateAsync(this QuickFix quickFix, OmniSharpWorkspace workspace, Request request) { var sameFile = string.IsNullOrEmpty(quickFix.FileName); var fileName = !sameFile ? quickFix.FileName : request.FileName; if (string.IsNullOrEmpty(fileName)) { return quickFix; } var (line, newFileName) = await LineIndexHelper.TranslateFromGenerated(fileName, quickFix.Line, workspace, sameFile); quickFix.Line = line; quickFix.FileName = newFileName; (line, _) = await LineIndexHelper.TranslateFromGenerated(fileName, quickFix.EndLine, workspace, sameFile); quickFix.EndLine = line; return quickFix; } private static async Task PopulateModificationsAsync( ModifiedFileResponse modification, OmniSharpWorkspace workspace, IDictionary<string, List<LinePositionSpanTextChange>> modifications) { foreach (var change in modification.Changes) { var (filename, _) = await change.TranslateAsync(workspace, modification.FileName); if (change.StartLine < 0) { continue; } if (modifications.TryGetValue(filename, out var changes)) { changes.Add(change); } else { modifications.Add(filename, new List<LinePositionSpanTextChange> { change }); } } } private static async Task<(string, LinePositionSpanTextChange)> TranslateAsync(this LinePositionSpanTextChange change, OmniSharpWorkspace workspace, string fileName) { var (line, newFileName) = await LineIndexHelper.TranslateFromGenerated(fileName, change.StartLine, workspace, false); change.StartLine = line; (line, _) = await LineIndexHelper.TranslateFromGenerated(fileName, change.EndLine, workspace, false); change.EndLine = line; return (newFileName, change); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// SampleResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Preview.Understand.Assistant.Task { public class SampleResource : Resource { private static Request BuildFetchRequest(FetchSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Fetch(FetchSampleOptions 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 Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> FetchAsync(FetchSampleOptions 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="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Fetch(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchSampleOptions(pathAssistantSid, pathTaskSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> FetchAsync(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchSampleOptions(pathAssistantSid, pathTaskSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static ResourceSet<SampleResource> Read(ReadSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<SampleResource>.FromJson("samples", response.Content); return new ResourceSet<SampleResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<ResourceSet<SampleResource>> ReadAsync(ReadSampleOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<SampleResource>.FromJson("samples", response.Content); return new ResourceSet<SampleResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="language"> An ISO language-country string of the sample. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static ResourceSet<SampleResource> Read(string pathAssistantSid, string pathTaskSid, string language = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSampleOptions(pathAssistantSid, pathTaskSid){Language = language, PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="language"> An ISO language-country string of the sample. </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<ResourceSet<SampleResource>> ReadAsync(string pathAssistantSid, string pathTaskSid, string language = null, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadSampleOptions(pathAssistantSid, pathTaskSid){Language = language, 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<SampleResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<SampleResource>.FromJson("samples", 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<SampleResource> NextPage(Page<SampleResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<SampleResource>.FromJson("samples", 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<SampleResource> PreviousPage(Page<SampleResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<SampleResource>.FromJson("samples", response.Content); } private static Request BuildCreateRequest(CreateSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Create(CreateSampleOptions 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 Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> CreateAsync(CreateSampleOptions 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="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="language"> An ISO language-country string of the sample. </param> /// <param name="taggedText"> The text example of how end-users may express this task. The sample may contain Field tag /// blocks. </param> /// <param name="sourceChannel"> The communication channel the sample was captured. It can be: voice, sms, chat, alexa, /// google-assistant, or slack. If not included the value will be null </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Create(string pathAssistantSid, string pathTaskSid, string language, string taggedText, string sourceChannel = null, ITwilioRestClient client = null) { var options = new CreateSampleOptions(pathAssistantSid, pathTaskSid, language, taggedText){SourceChannel = sourceChannel}; return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="language"> An ISO language-country string of the sample. </param> /// <param name="taggedText"> The text example of how end-users may express this task. The sample may contain Field tag /// blocks. </param> /// <param name="sourceChannel"> The communication channel the sample was captured. It can be: voice, sms, chat, alexa, /// google-assistant, or slack. If not included the value will be null </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> CreateAsync(string pathAssistantSid, string pathTaskSid, string language, string taggedText, string sourceChannel = null, ITwilioRestClient client = null) { var options = new CreateSampleOptions(pathAssistantSid, pathTaskSid, language, taggedText){SourceChannel = sourceChannel}; return await CreateAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// update /// </summary> /// <param name="options"> Update Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Update(UpdateSampleOptions 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 Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> UpdateAsync(UpdateSampleOptions 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="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="language"> An ISO language-country string of the sample. </param> /// <param name="taggedText"> The text example of how end-users may express this task. The sample may contain Field tag /// blocks. </param> /// <param name="sourceChannel"> The communication channel the sample was captured. It can be: voice, sms, chat, alexa, /// google-assistant, or slack. If not included the value will be null </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static SampleResource Update(string pathAssistantSid, string pathTaskSid, string pathSid, string language = null, string taggedText = null, string sourceChannel = null, ITwilioRestClient client = null) { var options = new UpdateSampleOptions(pathAssistantSid, pathTaskSid, pathSid){Language = language, TaggedText = taggedText, SourceChannel = sourceChannel}; return Update(options, client); } #if !NET35 /// <summary> /// update /// </summary> /// <param name="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="language"> An ISO language-country string of the sample. </param> /// <param name="taggedText"> The text example of how end-users may express this task. The sample may contain Field tag /// blocks. </param> /// <param name="sourceChannel"> The communication channel the sample was captured. It can be: voice, sms, chat, alexa, /// google-assistant, or slack. If not included the value will be null </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<SampleResource> UpdateAsync(string pathAssistantSid, string pathTaskSid, string pathSid, string language = null, string taggedText = null, string sourceChannel = null, ITwilioRestClient client = null) { var options = new UpdateSampleOptions(pathAssistantSid, pathTaskSid, pathSid){Language = language, TaggedText = taggedText, SourceChannel = sourceChannel}; return await UpdateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteSampleOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Preview, "/understand/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Samples/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static bool Delete(DeleteSampleOptions 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 Sample parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteSampleOptions 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="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Sample </returns> public static bool Delete(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteSampleOptions(pathAssistantSid, pathTaskSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathAssistantSid"> The unique ID of the Assistant. </param> /// <param name="pathTaskSid"> The unique ID of the Task associated with this Sample. </param> /// <param name="pathSid"> A 34 character string that uniquely identifies this resource. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Sample </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteSampleOptions(pathAssistantSid, pathTaskSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a SampleResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> SampleResource object represented by the provided JSON </returns> public static SampleResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<SampleResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique ID of the Account that created this Sample. /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The date that this resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The date that this resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The unique ID of the Task associated with this Sample. /// </summary> [JsonProperty("task_sid")] public string TaskSid { get; private set; } /// <summary> /// An ISO language-country string of the sample. /// </summary> [JsonProperty("language")] public string Language { get; private set; } /// <summary> /// The unique ID of the Assistant. /// </summary> [JsonProperty("assistant_sid")] public string AssistantSid { get; private set; } /// <summary> /// A 34 character string that uniquely identifies this resource. /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The text example of how end-users may express this task. The sample may contain Field tag blocks. /// </summary> [JsonProperty("tagged_text")] public string TaggedText { get; private set; } /// <summary> /// The url /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// The communication channel the sample was captured. It can be: voice, sms, chat, alexa, google-assistant, or slack. If not included the value will be null /// </summary> [JsonProperty("source_channel")] public string SourceChannel { get; private set; } private SampleResource() { } } }
/* * Swaggy Jenkins * * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// BranchImpllinks /// </summary> [DataContract(Name = "BranchImpllinks")] public partial class BranchImpllinks : IEquatable<BranchImpllinks>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="BranchImpllinks" /> class. /// </summary> /// <param name="self">self.</param> /// <param name="actions">actions.</param> /// <param name="runs">runs.</param> /// <param name="queue">queue.</param> /// <param name="_class">_class.</param> public BranchImpllinks(Link self = default(Link), Link actions = default(Link), Link runs = default(Link), Link queue = default(Link), string _class = default(string)) { this.Self = self; this.Actions = actions; this.Runs = runs; this.Queue = queue; this.Class = _class; } /// <summary> /// Gets or Sets Self /// </summary> [DataMember(Name = "self", EmitDefaultValue = false)] public Link Self { get; set; } /// <summary> /// Gets or Sets Actions /// </summary> [DataMember(Name = "actions", EmitDefaultValue = false)] public Link Actions { get; set; } /// <summary> /// Gets or Sets Runs /// </summary> [DataMember(Name = "runs", EmitDefaultValue = false)] public Link Runs { get; set; } /// <summary> /// Gets or Sets Queue /// </summary> [DataMember(Name = "queue", EmitDefaultValue = false)] public Link Queue { get; set; } /// <summary> /// Gets or Sets Class /// </summary> [DataMember(Name = "_class", EmitDefaultValue = false)] public string Class { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class BranchImpllinks {\n"); sb.Append(" Self: ").Append(Self).Append("\n"); sb.Append(" Actions: ").Append(Actions).Append("\n"); sb.Append(" Runs: ").Append(Runs).Append("\n"); sb.Append(" Queue: ").Append(Queue).Append("\n"); sb.Append(" Class: ").Append(Class).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 Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.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 BranchImpllinks); } /// <summary> /// Returns true if BranchImpllinks instances are equal /// </summary> /// <param name="input">Instance of BranchImpllinks to be compared</param> /// <returns>Boolean</returns> public bool Equals(BranchImpllinks input) { if (input == null) { return false; } return ( this.Self == input.Self || (this.Self != null && this.Self.Equals(input.Self)) ) && ( this.Actions == input.Actions || (this.Actions != null && this.Actions.Equals(input.Actions)) ) && ( this.Runs == input.Runs || (this.Runs != null && this.Runs.Equals(input.Runs)) ) && ( this.Queue == input.Queue || (this.Queue != null && this.Queue.Equals(input.Queue)) ) && ( this.Class == input.Class || (this.Class != null && this.Class.Equals(input.Class)) ); } /// <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.Self != null) { hashCode = (hashCode * 59) + this.Self.GetHashCode(); } if (this.Actions != null) { hashCode = (hashCode * 59) + this.Actions.GetHashCode(); } if (this.Runs != null) { hashCode = (hashCode * 59) + this.Runs.GetHashCode(); } if (this.Queue != null) { hashCode = (hashCode * 59) + this.Queue.GetHashCode(); } if (this.Class != null) { hashCode = (hashCode * 59) + this.Class.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
//--------------------------------------------------------------------- // File: Logger.cs // // Summary: // //--------------------------------------------------------------------- // Copyright (c) 2004-2017, Kevin B. Smith. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. //--------------------------------------------------------------------- using System; using System.Text; using System.IO; using System.Xml; namespace BizUnit.Core.Utilites { /// <summary> /// The BizUnit Logger is used to log data from BizUnit and test steps. /// </summary> public class Logger : ILogger { StringBuilder _sb = null; bool _concurrentExecutionMode = false; const string Crlf = "\r\n"; const string InfoLogLevel = "Info"; const string ErrorLogLevel = "Error"; const string WarningLogLevel = "Warning"; #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.ConcurrentExecutionMode' public bool ConcurrentExecutionMode #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.ConcurrentExecutionMode' { get { return _concurrentExecutionMode; } set { _concurrentExecutionMode = value; if (_concurrentExecutionMode) { _sb = new StringBuilder(); } } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStageStart(TestStage, DateTime)' public void TestStageStart(TestStage stage, DateTime time) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStageStart(TestStage, DateTime)' { switch(stage) { case TestStage.Setup: WriteLine(" "); WriteLine("Setup Stage: started @ {0}", FormatDate(time)); break; case TestStage.Execution: WriteLine(" "); WriteLine("Execute Stage: started @ {0}", FormatDate(time)); break; case TestStage.Cleanup: WriteLine(" "); WriteLine("Cleanup Stage: started @ {0}", FormatDate(time)); break; } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStageEnd(TestStage, DateTime, Exception)' public void TestStageEnd(TestStage stage, DateTime time, Exception stageException) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStageEnd(TestStage, DateTime, Exception)' { if (null != stageException) { LogException(stageException); } WriteLine(" "); if (null == stageException) { WriteLine("{0} Stage: ended @ {1}", stage, FormatDate(time)); } else { WriteLine("{0} Stage: ended @ {1} with ERROR's", stage, FormatDate(time)); } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.LogException(Exception)' public void LogException(Exception e) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.LogException(Exception)' { if (null == e) { return; } WriteLine(new string('*', 79)); WriteLine("{0}: {1}", ErrorLogLevel, "Exception caught!"); WriteLine( e.ToString() ); WriteLine(new string('*', 79)); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.LogData(string, string)' public void LogData(string description, string data) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.LogData(string, string)' { WriteLine(new string('~', 79)); WriteLine( "Data: {0}", description ); WriteLine(new string('~', 79)); WriteLine( data ); WriteLine(new string('~', 79)); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.LogXmlData(string, string)' public void LogXmlData(string description, string data) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.LogXmlData(string, string)' { WriteLine(new string('~', 79)); WriteLine("Data: {0}", description); WriteLine(new string('~', 79)); WriteLine(FormatPrettyPrint(data)); WriteLine(new string('~', 79)); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.Log(LogLevel, string)' public void Log(LogLevel logLevel, string text) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.Log(LogLevel, string)' { switch(logLevel) { case (LogLevel.INFO): WriteLine("{0}: {1}", InfoLogLevel, text); break; case (LogLevel.WARNING): WriteLine("{0}: {1}", WarningLogLevel, text); break; case (LogLevel.ERROR): WriteLine("{0}: {1}", ErrorLogLevel, text); break; default: throw new ApplicationException("Invalid log level was set!"); }; } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.Log(LogLevel, string, params object[])' public void Log(LogLevel logLevel, string text, params object[] args) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.Log(LogLevel, string, params object[])' { string formattedText = string.Format(text, args); Log(logLevel, formattedText); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.LogBufferedText(ILogger)' public void LogBufferedText(ILogger logger) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.LogBufferedText(ILogger)' { if (!logger.ConcurrentExecutionMode) { throw new ApplicationException("This instance is not a concurrent test step!"); } WriteLine(logger.BufferedText); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.BufferedText' public string BufferedText #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.BufferedText' { get { if (null != _sb) return _sb.ToString(); return null; } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStepStart(string, DateTime, bool, bool)' public void TestStepStart(string testStepName, DateTime time, bool runConcurrently, bool failOnError) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStepStart(string, DateTime, bool, bool)' { WriteLine(""); if (runConcurrently) { WriteLine( string.Format("Step: {0} started c o n c u r r e n t l y @ {1}, failOnError = {2}", testStepName, FormatDate(time), failOnError)); } else { WriteLine( string.Format("Step: {0} started @ {1}, failOnError = {2}", testStepName, FormatDate(time), failOnError)); } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStepEnd(string, DateTime, Exception)' public void TestStepEnd(string testStepName, DateTime time, Exception ex) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStepEnd(string, DateTime, Exception)' { if (null == ex) { WriteLine(string.Format("Step: {0} ended @ {1}", testStepName, FormatDate(time))); } else { WriteLine(string.Format("Step: {0} ended @ {1} with ERRORS, exception: {2}", testStepName, FormatDate(time), ex.GetType().ToString())); } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.ValidateTestSteps(TestStage, string, Exception)' public void ValidateTestSteps(TestStage stage, string testStepName, Exception ex) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.ValidateTestSteps(TestStage, string, Exception)' { if (null == ex) { WriteLine(string.Format("Test step validation for stage: {0}, step: {1} was successful.", stage, testStepName)); } else { WriteLine(string.Format("Test step validation for stage: {0}, step: {1} failed: {2}", stage, testStepName, ex)); } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestGroupStart(string, TestGroupPhase, DateTime, string)' public void TestGroupStart(string testGroupName, TestGroupPhase testGroupPhase, DateTime time, string userName) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestGroupStart(string, TestGroupPhase, DateTime, string)' { if (testGroupPhase == TestGroupPhase.TestGroupSetup) { WriteLine(" "); WriteLine(new string('-', 79)); WriteLine(" T E S T G R O U P S E T U P"); WriteLine(" "); WriteLine(string.Format("Test Group Setup: {0} started @ {1} by {2}", testGroupName, FormatDate(time), userName)); WriteLine(new string('-', 79)); } else { WriteLine(" "); WriteLine(new string('-', 79)); WriteLine(" T E S T G R O U P T E A R D O W N"); WriteLine(" "); WriteLine(string.Format("Test Group Tear Down: {0} completed @ {1}", testGroupName, FormatDate(time))); WriteLine(new string('-', 79)); } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestGroupEnd(TestGroupPhase, DateTime, Exception)' public void TestGroupEnd(TestGroupPhase testGroupPhase, DateTime time, Exception executionException) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestGroupEnd(TestGroupPhase, DateTime, Exception)' { if (testGroupPhase == TestGroupPhase.TestGroupSetup) { if (null != executionException) { WriteLine(string.Format("Test Group Setup completed @ {0}", FormatDate(time))); WriteLine(" ****** T E S T G R O U P S E T U P F A I L E D ******"); } else { WriteLine(string.Format("Test Group Setup completed @ {0}", FormatDate(time))); WriteLine(" T E S T G R O U P S E T U P P A S S"); } } else { if (null != executionException) { WriteLine(string.Format("Test Group Tear Down completed @ {0}", FormatDate(time))); WriteLine(" ****** T E S T G R O U P T E A R D O W N F A I L E D ******"); } else { WriteLine(string.Format("Test Group Tear Down completed @ {0}", FormatDate(time))); WriteLine(" T E S T G R O U P T E A R D O W N P A S S"); } } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStart(string, DateTime, string)' public void TestStart(string testName, DateTime time, string userName) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestStart(string, DateTime, string)' { WriteLine(" "); WriteLine(new string('-', 79)); WriteLine(" S T A R T"); WriteLine(" "); WriteLine(string.Format("Test: {0} started @ {1} by {2}", testName, FormatDate(time), userName)); WriteLine(new string('-', 79)); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestEnd(string, DateTime, Exception)' public void TestEnd(string testName, DateTime time, Exception ex) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.TestEnd(string, DateTime, Exception)' { LogException(ex); WriteLine(new string('-', 79)); WriteLine(string.Format("Test: {0} ended @ {1}", testName, FormatDate(time))); WriteLine(""); if (null != ex) { WriteLine(" ****** F A I L ******"); } else { WriteLine(" P A S S"); } WriteLine(new string('-', 79)); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.ValidatorStart(string, DateTime)' public void ValidatorStart(string validatorName, DateTime time) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.ValidatorStart(string, DateTime)' { WriteLine(""); WriteLine(string.Format("Validation: {0} started @ {1}", validatorName, FormatDate(time))); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.ValidatorEnd(string, DateTime, Exception)' public void ValidatorEnd(string validatorName, DateTime time, Exception ex) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.ValidatorEnd(string, DateTime, Exception)' { if(null == ex) { WriteLine(string.Format("Validation: {0} ended @ {1}", validatorName, FormatDate(time))); } else { WriteLine(string.Format("Validation: {0} ended @ {1} with ERRORS, exception: {2}", validatorName, FormatDate(time), ex.GetType().ToString())); } WriteLine(""); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.ContextLoaderStart(string, DateTime)' public void ContextLoaderStart(string contextLoaderName, DateTime time) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.ContextLoaderStart(string, DateTime)' { WriteLine(""); WriteLine(string.Format("ContextLoad: {0} started @ {1}", contextLoaderName, FormatDate(time))); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.ContextLoaderEnd(string, DateTime, Exception)' public void ContextLoaderEnd(string contextLoaderName, DateTime time, Exception ex) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.ContextLoaderEnd(string, DateTime, Exception)' { if (null == ex) { WriteLine(string.Format("ContextLoad: {0} ended @ {1}", contextLoaderName, FormatDate(time))); } else { WriteLine(string.Format("ContextLoad: {0} ended @ {1} with ERRORS, exception: {2}", contextLoaderName, FormatDate(time), ex.GetType().ToString())); } WriteLine(""); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.Clone()' public object Clone() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.Clone()' { return new Logger(); } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.Flush()' public void Flush() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.Flush()' { string buff = BufferedText; if(null != buff) { WriteLine(buff); } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'Logger.Close()' public void Close() #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'Logger.Close()' { } private static string FormatDate(DateTime time) { return time.ToString("HH:mm:ss.fff dd/MM/yyyy"); } private void WriteLine(string s) { if (_concurrentExecutionMode) { _sb.Append(s); _sb.Append(Crlf); } else { Console.WriteLine(s); } } private void WriteLine(string s, params object[] args) { if (_concurrentExecutionMode) { _sb.Append(String.Format(s, args)); _sb.Append(Crlf); } else { Console.WriteLine(s, args); } } private static string FormatPrettyPrint(string data) { var doc = new XmlDocument(); doc.LoadXml(data); return FormatPrettyPrint(doc); } private static string FormatPrettyPrint(XmlDocument doc) { var ms = new MemoryStream(); var tw = new XmlTextWriter(ms, Encoding.Unicode) {Formatting = Formatting.Indented}; doc.WriteContentTo(tw); tw.Flush(); ms.Flush(); ms.Seek(0, SeekOrigin.Begin); var sr = new StreamReader(ms); return sr.ReadToEnd(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Logging; package com.quantconnect.lean.Lean.Engine.DataFeeds { /** * Provides a means of distributing output from enumerators from a dedicated separate thread */ public class BaseDataExchange { private int _sleepInterval = 1; private volatile boolean _isStopping = false; private Func<Exception, bool> _isFatalError; private final String _name; private final object _enumeratorsWriteLock = new object(); private final ConcurrentMap<Symbol, DataHandler> _dataHandlers; private ConcurrentMap<Symbol, EnumeratorHandler> _enumerators; /** * Gets or sets how long this thread will sleep when no data is available */ public int SleepInterval { get { return _sleepInterval; } set { if( value > -1) _sleepInterval = value; } } /** * Gets a name for this exchange */ public String Name { get { return _name; } } /** * Initializes a new instance of the <see cref="BaseDataExchange"/> */ * @param name A name for this exchange * @param enumerators The enumerators to fanout public BaseDataExchange( String name) { _name = name; _isFatalError = x -> false; _dataHandlers = new ConcurrentMap<Symbol, DataHandler>(); _enumerators = new ConcurrentMap<Symbol, EnumeratorHandler>(); } /** * Adds the enumerator to this exchange. If it has already been added * then it will remain registered in the exchange only once */ * @param handler The handler to use when this symbol's data is encountered public void AddEnumerator(EnumeratorHandler handler) { _enumerators[handler.Symbol] = handler; } /** * Adds the enumerator to this exchange. If it has already been added * then it will remain registered in the exchange only once */ * @param symbol A unique symbol used to identify this enumerator * @param enumerator The enumerator to be added * @param shouldMoveNext Function used to determine if move next should be called on this * enumerator, defaults to always returning true * @param enumeratorFinished Delegate called when the enumerator move next returns false public void AddEnumerator(Symbol symbol, IEnumerator<BaseData> enumerator, Func<bool> shouldMoveNext = null, Action<EnumeratorHandler> enumeratorFinished = null ) { enumeratorHandler = new EnumeratorHandler(symbol, enumerator, shouldMoveNext); if( enumeratorFinished != null ) { enumeratorHandler.EnumeratorFinished += (sender, args) -> enumeratorFinished(args); } AddEnumerator(enumeratorHandler); } /** * Sets the specified function as the error handler. This function * returns true if it is a fatal error and queue consumption should * cease. */ * @param isFatalError The error handling function to use when an * error is encountered during queue consumption. Returns true if queue * consumption should be stopped, returns false if queue consumption should * continue public void SetErrorHandler(Func<Exception, bool> isFatalError) { // default to false; _isFatalError = isFatalError ?? (x -> false); } /** * Sets the specified hander function to handle data for the handler's symbol */ * @param handler The handler to use when this symbol's data is encountered @returns An identifier that can be used to remove this handler public void SetDataHandler(DataHandler handler) { _dataHandlers[handler.Symbol] = handler; } /** * Sets the specified hander function to handle data for the handler's symbol */ * @param symbol The symbol whose data is to be handled * @param handler The handler to use when this symbol's data is encountered @returns An identifier that can be used to remove this handler public void SetDataHandler(Symbol symbol, Action<BaseData> handler) { dataHandler = new DataHandler(symbol); dataHandler.DataEmitted += (sender, args) -> handler(args); SetDataHandler(dataHandler); } /** * Removes the handler with the specified identifier */ * @param symbol The symbol to remove handlers for public boolean RemoveDataHandler(Symbol symbol) { DataHandler handler; return _dataHandlers.TryRemove(symbol, out handler); } /** * Removes and returns enumerator handler with the specified symbol. * The removed handler is returned, null if not found */ public EnumeratorHandler RemoveEnumerator(Symbol symbol) { EnumeratorHandler handler; if( _enumerators.TryRemove(symbol, out handler)) { handler.OnEnumeratorFinished(); handler.Enumerator.Dispose(); } return handler; } /** * Begins consumption of the wrapped <see cref="IDataQueueHandler"/> on * a separate thread */ * @param token A cancellation token used to signal to stop public void Start(CancellationToken? token = null ) { Log.Trace( "BaseDataExchange(%1$s) Starting...", Name); _isStopping = false; ConsumeEnumerators(token ?? CancellationToken.None); } /** * Ends consumption of the wrapped <see cref="IDataQueueHandler"/> */ public void Stop() { Log.Trace( "BaseDataExchange(%1$s) Stopping...", Name); _isStopping = true; } /** Entry point for queue consumption </summary> * @param token A cancellation token used to signal to stop * This function only returns after <see cref="Stop"/> is called or the token is cancelled private void ConsumeEnumerators(CancellationToken token) { while (true) { if( _isStopping || token.IsCancellationRequested) { _isStopping = true; request = token.IsCancellationRequested ? "Cancellation requested" : "Stop requested"; Log.Trace( "BaseDataExchange(%1$s).ConsumeQueue(): %2$s. Exiting...", Name, request); return; } try { // call move next each enumerator and invoke the appropriate handlers handled = false; foreach (kvp in _enumerators) { enumeratorHandler = kvp.Value; enumerator = enumeratorHandler.Enumerator; // check to see if we should advance this enumerator if( !enumeratorHandler.ShouldMoveNext()) continue; if( !enumerator.MoveNext()) { enumeratorHandler.OnEnumeratorFinished(); enumeratorHandler.Enumerator.Dispose(); _enumerators.TryRemove(enumeratorHandler.Symbol, out enumeratorHandler); continue; } if( enumerator.Current == null ) continue; // if the enumerator is configured to handle it, then do it, don't pass to data handlers if( enumeratorHandler.HandlesData) { handled = true; enumeratorHandler.HandleData(enumerator.Current); continue; } // invoke the correct handler DataHandler dataHandler; if( _dataHandlers.TryGetValue(enumerator.Current.Symbol, out dataHandler)) { handled = true; dataHandler.OnDataEmitted(enumerator.Current); } } // if we didn't handle anything on this past iteration, take a nap if( !handled && _sleepInterval != 0) { Thread.Sleep(_sleepInterval); } } catch (Exception err) { Log.Error(err); if( _isFatalError(err)) { Log.Trace( "BaseDataExchange(%1$s).ConsumeQueue(): Fatal error encountered. Exiting...", Name); return; } } } } /** * Handler used to handle data emitted from enumerators */ public class DataHandler { /** * Event fired when MoveNext returns true and Current is non-null */ public event EventHandler<BaseData> DataEmitted; /** * The symbol this handler handles */ public final Symbol Symbol; /** * Initializes a new instance of the <see cref="DataHandler"/> class */ * @param symbol The symbol whose data is to be handled public DataHandler(Symbol symbol) { Symbol = symbol; } /** * Event invocator for the <see cref="DataEmitted"/> event */ * @param data The data being emitted public void OnDataEmitted(BaseData data) { handler = DataEmitted; if( handler != null ) handler(this, data); } } /** * Handler used to manage a single enumerator's move next/end of stream behavior */ public class EnumeratorHandler { private final Func<bool> _shouldMoveNext; private final Action<BaseData> _handleData; /** * Event fired when MoveNext returns false */ public event EventHandler<EnumeratorHandler> EnumeratorFinished; /** * A unique symbol used to identify this enumerator */ public final Symbol Symbol; /** * The enumerator this handler handles */ public final IEnumerator<BaseData> Enumerator; /** * Determines whether or not this handler is to be used for handling the * data emitted. This is useful when enumerators are not for a single symbol, * such is the case with universe subscriptions */ public final boolean HandlesData; /** * Initializes a new instance of the <see cref="EnumeratorHandler"/> class */ * @param symbol The symbol to identify this enumerator * @param enumerator The enumeator this handler handles * @param shouldMoveNext Predicate function used to determine if we should call move next * on the symbol's enumerator * @param handleData Handler for data if HandlesData=true public EnumeratorHandler(Symbol symbol, IEnumerator<BaseData> enumerator, Func<bool> shouldMoveNext = null, Action<BaseData> handleData = null ) { Symbol = symbol; Enumerator = enumerator; HandlesData = handleData != null; _handleData = handleData ?? (data -> { }); _shouldMoveNext = shouldMoveNext ?? (() -> true); } /** * Initializes a new instance of the <see cref="EnumeratorHandler"/> class */ * @param symbol The symbol to identify this enumerator * @param enumerator The enumeator this handler handles * @param handlesData True if this handler will handle the data, false otherwise protected EnumeratorHandler(Symbol symbol, IEnumerator<BaseData> enumerator, boolean handlesData) { Symbol = symbol; HandlesData = handlesData; Enumerator = enumerator; _handleData = data -> { }; _shouldMoveNext = () -> true; } /** * Event invocator for the <see cref="EnumeratorFinished"/> event */ public void OnEnumeratorFinished() { handler = EnumeratorFinished; if( handler != null ) handler(this, this); } /** * Returns true if this enumerator should move next */ public boolean ShouldMoveNext() { return _shouldMoveNext(); } /** * Handles the specified data. */ * @param data The data to be handled public void HandleData(BaseData data) { _handleData(data); } } } }
// 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.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; using Xunit.Sdk; namespace System.Diagnostics { /// <summary>Base class used for all tests that need to spawn a remote process.</summary> public abstract partial class RemoteExecutorTestBase : FileCleanupTestBase { /// <summary>A timeout (milliseconds) after which a wait on a remote operation should be considered a failure.</summary> public const int FailWaitTimeoutMilliseconds = 60 * 1000; /// <summary>The exit code returned when the test process exits successfully.</summary> public const int SuccessExitCode = 42; /// <summary>The name of the test console app.</summary> protected static readonly string TestConsoleApp = "RemoteExecutorConsoleApp.exe"; /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<int> method, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<Task<int>> method, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), Array.Empty<string>(), options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, int> method, string arg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, int> method, string arg1, string arg2, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, int> method, string arg1, string arg2, string arg3, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="arg4">The fourth argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="arg1">The first argument to pass to the method.</param> /// <param name="arg2">The second argument to pass to the method.</param> /// <param name="arg3">The third argument to pass to the method.</param> /// <param name="arg4">The fourth argument to pass to the method.</param> /// <param name="arg5">The fifth argument to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvoke( Func<string, string, string, string, string, int> method, string arg1, string arg2, string arg3, string arg4, string arg5, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { arg1, arg2, arg3, arg4, arg5 }, options); } /// <summary>Invokes the method from this assembly in another process using the specified arguments without performing any modifications to the arguments.</summary> /// <param name="method">The method to invoke.</param> /// <param name="args">The arguments to pass to the method.</param> /// <param name="options">Options to use for the invocation.</param> public static RemoteInvokeHandle RemoteInvokeRaw(Delegate method, string unparsedArg, RemoteInvokeOptions options = null) { return RemoteInvoke(GetMethodInfo(method), new[] { unparsedArg }, options, pasteArguments: false); } private static MethodInfo GetMethodInfo(Delegate d) { // RemoteInvoke doesn't support marshaling state on classes associated with // the delegate supplied (often a display class of a lambda). If such fields // are used, odd errors result, e.g. NullReferenceExceptions during the remote // execution. Try to ward off the common cases by proactively failing early // if it looks like such fields are needed. if (d.Target != null) { // The only fields on the type should be compiler-defined (any fields of the compiler's own // making generally include '<' and '>', as those are invalid in C# source). Note that this logic // may need to be revised in the future as the compiler changes, as this relies on the specifics of // actually how the compiler handles lifted fields for lambdas. Type targetType = d.Target.GetType(); Assert.All( targetType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly), fi => Assert.True(fi.Name.IndexOf('<') != -1, $"Field marshaling is not supported by {nameof(RemoteInvoke)}: {fi.Name}")); } return d.GetMethodInfo(); } /// <summary>A cleanup handle to the Process created for the remote invocation.</summary> public sealed class RemoteInvokeHandle : IDisposable { public RemoteInvokeHandle(Process process, RemoteInvokeOptions options) { Process = process; Options = options; } public Process Process { get; private set; } public RemoteInvokeOptions Options { get; private set; } public void Dispose() { if (Process != null) { // A bit unorthodox to do throwing operations in a Dispose, but by doing it here we avoid // needing to do this in every derived test and keep each test much simpler. try { Assert.True(Process.WaitForExit(Options.TimeOut), $"Timed out after {Options.TimeOut}ms waiting for remote process {Process.Id}"); if (File.Exists(Options.ExceptionFile)) { throw new RemoteExecutionException(File.ReadAllText(Options.ExceptionFile)); } if (Options.CheckExitCode) { int expected = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Options.ExpectedExitCode : unchecked((sbyte)Options.ExpectedExitCode); int actual = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Process.ExitCode : unchecked((sbyte)Process.ExitCode); Assert.True(expected == actual, $"Exit code was {Process.ExitCode} but it should have been {Options.ExpectedExitCode}"); } } finally { if (File.Exists(Options.ExceptionFile)) { File.Delete(Options.ExceptionFile); } // Cleanup try { Process.Kill(); } catch { } // ignore all cleanup errors Process.Dispose(); Process = null; } } } private sealed class RemoteExecutionException : XunitException { internal RemoteExecutionException(string stackTrace) : base("Remote process failed with an unhandled exception.", stackTrace) { } } } } /// <summary>Options used with RemoteInvoke.</summary> public sealed class RemoteInvokeOptions { public bool Start { get; set; } = true; public ProcessStartInfo StartInfo { get; set; } = new ProcessStartInfo(); public bool EnableProfiling { get; set; } = true; public bool CheckExitCode { get; set; } = true; public int TimeOut {get; set; } = RemoteExecutorTestBase.FailWaitTimeoutMilliseconds; public int ExpectedExitCode { get; set; } = RemoteExecutorTestBase.SuccessExitCode; public string ExceptionFile { get; } = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); } }
// 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 Newtonsoft.Json; using SensusService.Exceptions; using SensusUI.UiProperties; using System; using System.Collections.Generic; using System.Threading; using System.Linq; using SensusService.DataStores.Remote; using SensusService.DataStores.Local; using System.Threading.Tasks; namespace SensusService.DataStores { /// <summary> /// An abstract repository for probed data. /// </summary> public abstract class DataStore { /// <summary> /// We don't mind commit callbacks lag, since it don't affect any performance metrics and /// the latencies aren't inspected when testing data store health or participation. It also /// doesn't make sense to force rapid commits since data will not have accumulated. /// </summary> private const bool COMMIT_CALLBACK_LAG = true; private int _commitDelayMS; private int _commitTimeoutMinutes; private bool _running; private Protocol _protocol; private DateTime? _mostRecentSuccessfulCommitTime; private List<Datum> _nonProbeDataToCommit; private string _commitCallbackId; [EntryIntegerUiProperty("Commit Delay (MS):", true, 2)] public int CommitDelayMS { get { return _commitDelayMS; } set { if (value <= 1000) value = 1000; if (value != _commitDelayMS) { _commitDelayMS = value; if (_commitCallbackId != null) _commitCallbackId = SensusServiceHelper.Get().RescheduleRepeatingCallback(_commitCallbackId, _commitDelayMS, _commitDelayMS, COMMIT_CALLBACK_LAG); } } } [EntryIntegerUiProperty("Commit Timeout (Mins.):", true, 3)] public int CommitTimeoutMinutes { get { return _commitTimeoutMinutes; } set { if (value <= 0) value = 1; _commitTimeoutMinutes = value; } } public Protocol Protocol { get { return _protocol; } set { _protocol = value; } } [JsonIgnore] public bool Running { get { return _running; } } [JsonIgnore] public abstract string DisplayName { get; } [JsonIgnore] public abstract bool Clearable { get; } protected DataStore() { _commitDelayMS = 10000; _commitTimeoutMinutes = 5; _running = false; _mostRecentSuccessfulCommitTime = null; _nonProbeDataToCommit = new List<Datum>(); _commitCallbackId = null; } public void AddNonProbeDatum(Datum datum) { lock (_nonProbeDataToCommit) _nonProbeDataToCommit.Add(datum); } /// <summary> /// Starts the commit thread. This should always be called last within child-class overrides. /// </summary> public virtual void Start() { if (!_running) { _running = true; SensusServiceHelper.Get().Logger.Log("Starting.", LoggingLevel.Normal, GetType()); _mostRecentSuccessfulCommitTime = DateTime.Now; string userNotificationMessage = null; // we can't wake up the app on ios. this is problematic since data need to be stored locally and remotely // in something of a reliable schedule; otherwise, we risk data loss (e.g., from device restarts, app kills, etc.). // so, do the best possible thing and bug the user with a notification indicating that data need to be stored. // only do this for the remote data store to that we don't get duplicate notifications. #if __IOS__ if (this is RemoteDataStore) userNotificationMessage = "Sensus needs to submit your data for the \"" + _protocol.Name + "\" study. Please open this notification."; #endif ScheduledCallback callback = new ScheduledCallback(CommitAsync, GetType().FullName + " Commit", TimeSpan.FromMinutes(_commitTimeoutMinutes), userNotificationMessage); _commitCallbackId = SensusServiceHelper.Get().ScheduleRepeatingCallback(callback, _commitDelayMS, _commitDelayMS, COMMIT_CALLBACK_LAG); } } private Task CommitAsync(string callbackId, CancellationToken cancellationToken, Action letDeviceSleepCallback) { return CommitAsync(cancellationToken); } public Task CommitAsync(CancellationToken cancellationToken) { return Task.Run(async () => { if (_running) { int? numDataCommitted = null; try { SensusServiceHelper.Get().Logger.Log("Committing data.", LoggingLevel.Normal, GetType()); DateTime commitStartTime = DateTime.Now; List<Datum> dataToCommit = null; try { dataToCommit = GetDataToCommit(cancellationToken); if (dataToCommit == null) throw new DataStoreException("Null collection returned by GetDataToCommit"); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to get data to commit: " + ex.Message, LoggingLevel.Normal, GetType(), true); } if (dataToCommit != null && !cancellationToken.IsCancellationRequested) { // add in non-probe data (e.g., that from protocol reports or participation reward verifications) lock (_nonProbeDataToCommit) foreach (Datum datum in _nonProbeDataToCommit) dataToCommit.Add(datum); List<Datum> committedData = null; try { committedData = await CommitDataAsync(dataToCommit, cancellationToken); if (committedData == null) throw new DataStoreException("Null collection returned by CommitData"); _mostRecentSuccessfulCommitTime = DateTime.Now; numDataCommitted = committedData.Count; } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to commit data: " + ex.Message, LoggingLevel.Normal, GetType(), true); } // don't check cancellation token here, since we've committed data and need to process the results (i.e., remove from probe caches or delete from local data store). if we don't always do this we'll end up committing duplicate data on next commit. if (committedData != null && committedData.Count > 0) { try { // remove any non-probe data that were committed from the in-memory store. lock (_nonProbeDataToCommit) foreach (Datum datum in committedData) _nonProbeDataToCommit.Remove(datum); ProcessCommittedData(committedData); } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Failed to process committed data: " + ex.Message, LoggingLevel.Normal, GetType(), true); } } } SensusServiceHelper.Get().Logger.Log("Finished commit in " + (DateTime.Now - commitStartTime).TotalSeconds + " seconds.", LoggingLevel.Normal, GetType()); // on ios the user must activate the app in order to save data. give the user some feedback to let them know that the data were stored remotely. #if __IOS__ if (numDataCommitted != null && this is RemoteDataStore) { int numDataCommittedValue = numDataCommitted.GetValueOrDefault(); SensusServiceHelper.Get().FlashNotificationAsync("Submitted " + numDataCommittedValue + " data item" + (numDataCommittedValue == 1 ? "" : "s") + " to the \"" + _protocol.Name + "\" study." + (numDataCommittedValue > 0 ? " Thank you!" : "")); } #endif } catch (Exception ex) { SensusServiceHelper.Get().Logger.Log("Commit failed: " + ex.Message, LoggingLevel.Normal, GetType(), true); } } }); } protected abstract List<Datum> GetDataToCommit(CancellationToken cancellationToken); protected abstract Task<List<Datum>> CommitDataAsync(List<Datum> data, CancellationToken cancellationToken); protected abstract void ProcessCommittedData(List<Datum> committedData); public virtual void Clear() { } public bool HasNonProbeDatumToCommit(string datumId) { return _nonProbeDataToCommit.Any(datum => datum.Id == datumId); } /// <summary> /// Stops the commit thread. This should always be called first within parent-class overrides. /// </summary> public virtual void Stop() { if (_running) { _running = false; SensusServiceHelper.Get().Logger.Log("Stopping.", LoggingLevel.Normal, GetType()); SensusServiceHelper.Get().UnscheduleCallback(_commitCallbackId); _commitCallbackId = null; } } public void Restart() { Stop(); Start(); } public virtual bool TestHealth(ref string error, ref string warning, ref string misc) { bool restart = false; if (!_running) { error += "Datastore \"" + GetType().FullName + "\" is not running." + Environment.NewLine; restart = true; } double msElapsedSinceLastCommit = (DateTime.Now - _mostRecentSuccessfulCommitTime.GetValueOrDefault()).TotalMilliseconds; if (msElapsedSinceLastCommit > (_commitDelayMS + 5000)) // system timer callbacks aren't always fired exactly as scheduled, resulting in health tests that identify warning conditions for delayed data storage. allow a small fudge factor to ignore most of these warnings warnings. warning += "Datastore \"" + GetType().FullName + "\" has not committed data in " + msElapsedSinceLastCommit + "ms (commit delay = " + _commitDelayMS + "ms)." + Environment.NewLine; return restart; } public virtual void ClearForSharing() { if (_running) throw new Exception("Cannot clear data store for sharing while it is running."); _mostRecentSuccessfulCommitTime = null; _nonProbeDataToCommit.Clear(); _commitCallbackId = null; } public DataStore Copy() { JsonSerializerSettings settings = new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, TypeNameHandling = TypeNameHandling.All, ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor }; return JsonConvert.DeserializeObject<DataStore>(JsonConvert.SerializeObject(this, settings), settings); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace API.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/*- * See the file LICENSE for redistribution information. * * Copyright (c) 2009 Oracle. All rights reserved. * */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Xml; using NUnit.Framework; using BerkeleyDB; namespace CsharpAPITest { [TestFixture] public class SecondaryHashDatabaseTest { private string testFixtureHome; private string testFixtureName; private string testName; private string testHome; [TestFixtureSetUp] public void RunBeforeTests() { testFixtureName = "SecondaryHashDatabaseTest"; testFixtureHome = "./TestOut/" + testFixtureName; Configuration.ClearDir(testFixtureHome); } [Test] public void TestHashFunction() { testName = "TestHashFunction"; testHome = testFixtureHome + "/" + testName; string dbFileName = testHome + "/" + testName + ".db"; string dbSecFileName = testHome + "/" + testName + "_sec.db"; Configuration.ClearDir(testHome); // Open a primary hash database. HashDatabaseConfig dbConfig = new HashDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; HashDatabase hashDB = HashDatabase.Open( dbFileName, dbConfig); /* * Define hash function and open a secondary * hash database. */ SecondaryHashDatabaseConfig secDBConfig = new SecondaryHashDatabaseConfig(hashDB, null); secDBConfig.HashFunction = new HashFunctionDelegate(HashFunction); secDBConfig.Creation = CreatePolicy.IF_NEEDED; SecondaryHashDatabase secDB = SecondaryHashDatabase.Open(dbSecFileName, secDBConfig); /* * Confirm the hash function defined in the configuration. * Call the hash function and the one from secondary * database. If they return the same value, then the hash * function is configured successfully. */ uint data = secDB.HashFunction(BitConverter.GetBytes(1)); Assert.AreEqual(0, data); // Close all. secDB.Close(); hashDB.Close(); } public uint HashFunction(byte[] data) { data[0] = 0; return BitConverter.ToUInt32(data, 0); } [Test] public void TestCompare() { testName = "TestCompare"; testHome = testFixtureHome + "/" + testName; string dbFileName = testHome + "/" + testName + ".db"; string dbSecFileName = testHome + "/" + testName + "_sec.db"; Configuration.ClearDir(testHome); // Open a primary hash database. HashDatabaseConfig dbConfig = new HashDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; HashDatabase db = HashDatabase.Open( dbFileName, dbConfig); // Open a secondary hash database. SecondaryHashDatabaseConfig secConfig = new SecondaryHashDatabaseConfig(null, null); secConfig.Creation = CreatePolicy.IF_NEEDED; secConfig.Primary = db; secConfig.Compare = new EntryComparisonDelegate(SecondaryEntryComparison); SecondaryHashDatabase secDB = SecondaryHashDatabase.Open(dbSecFileName, secConfig); /* * Get the compare function set in the configuration * and run it in a comparison to see if it is alright. */ DatabaseEntry dbt1, dbt2; dbt1 = new DatabaseEntry( BitConverter.GetBytes((int)257)); dbt2 = new DatabaseEntry( BitConverter.GetBytes((int)255)); Assert.Less(0, secDB.Compare(dbt1, dbt2)); secDB.Close(); db.Close(); } [Test] public void TestDuplicates() { testName = "TestDuplicates"; testHome = testFixtureHome + "/" + testName; string dbFileName = testHome + "/" + testName + ".db"; string dbSecFileName = testHome + "/" + testName + "_sec.db"; Configuration.ClearDir(testHome); // Open a primary hash database. HashDatabaseConfig dbConfig = new HashDatabaseConfig(); dbConfig.Creation = CreatePolicy.ALWAYS; HashDatabase db = HashDatabase.Open( dbFileName, dbConfig); // Open a secondary hash database. SecondaryHashDatabaseConfig secConfig = new SecondaryHashDatabaseConfig(null, null); secConfig.Primary = db; secConfig.Duplicates = DuplicatesPolicy.SORTED; secConfig.Creation = CreatePolicy.IF_NEEDED; SecondaryHashDatabase secDB = SecondaryHashDatabase.Open( dbSecFileName, secConfig); // Confirm the duplicate in opened secondary database. Assert.AreEqual(DuplicatesPolicy.SORTED, secDB.Duplicates); secDB.Close(); db.Close(); } /* * Tests to all Open() share the same configuration in * AllTestData.xml. */ [Test] public void TestOpen() { testName = "TestOpen"; testHome = testFixtureHome + "/" + testName; string dbFileName = testHome + "/" + testName + ".db"; string dbSecFileName = testHome + "/" + testName + "_sec.db"; Configuration.ClearDir(testHome); OpenSecHashDB(testFixtureName, "TestOpen", dbFileName, dbSecFileName, false); } [Test] public void TestOpenWithDBName() { testName = "TestOpenWithDBName"; testHome = testFixtureHome + "/" + testName; string dbFileName = testHome + "/" + testName + ".db"; string dbSecFileName = testHome + "/" + testName + "_sec.db"; Configuration.ClearDir(testHome); OpenSecHashDB(testFixtureName, "TestOpen", dbFileName, dbSecFileName, true); } public void OpenSecHashDB(string className, string funName, string dbFileName, string dbSecFileName, bool ifDBName) { XmlElement xmlElem = Configuration.TestSetUp( className, funName); // Open a primary recno database. HashDatabaseConfig primaryDBConfig = new HashDatabaseConfig(); primaryDBConfig.Creation = CreatePolicy.IF_NEEDED; HashDatabase primaryDB; /* * If secondary database name is given, the primary * database is also opened with database name. */ if (ifDBName == false) primaryDB = HashDatabase.Open(dbFileName, primaryDBConfig); else primaryDB = HashDatabase.Open(dbFileName, "primary", primaryDBConfig); try { // Open a new secondary database. SecondaryHashDatabaseConfig secHashDBConfig = new SecondaryHashDatabaseConfig( primaryDB, null); SecondaryHashDatabaseConfigTest.Config( xmlElem, ref secHashDBConfig, false); secHashDBConfig.Creation = CreatePolicy.IF_NEEDED; SecondaryHashDatabase secHashDB; if (ifDBName == false) secHashDB = SecondaryHashDatabase.Open( dbSecFileName, secHashDBConfig); else secHashDB = SecondaryHashDatabase.Open( dbSecFileName, "secondary", secHashDBConfig); // Close the secondary database. secHashDB.Close(); // Open the existing secondary database. SecondaryDatabaseConfig secDBConfig = new SecondaryDatabaseConfig( primaryDB, null); SecondaryDatabase secDB; if (ifDBName == false) secDB = SecondaryHashDatabase.Open( dbSecFileName, secDBConfig); else secDB = SecondaryHashDatabase.Open( dbSecFileName, "secondary", secDBConfig); // Close secondary database. secDB.Close(); } catch (DatabaseException) { throw new TestException(); } finally { // Close primary database. primaryDB.Close(); } } [Test] public void TestOpenWithinTxn() { testName = "TestOpenWithinTxn"; testHome = testFixtureHome + "/" + testName; string dbFileName = testName + ".db"; string dbSecFileName = testName + "_sec.db"; Configuration.ClearDir(testHome); OpenSecHashDBWithinTxn(testFixtureName, "TestOpen", testHome, dbFileName, dbSecFileName, false); } [Test] public void TestOpenDBNameWithinTxn() { testName = "TestOpenDBNameWithinTxn"; testHome = testFixtureHome + "/" + testName; string dbFileName = testName + ".db"; string dbSecFileName = testName + "_sec.db"; Configuration.ClearDir(testHome); OpenSecHashDBWithinTxn(testFixtureName, "TestOpen", testHome, dbFileName, dbSecFileName, true); } public void OpenSecHashDBWithinTxn(string className, string funName, string home, string dbFileName, string dbSecFileName, bool ifDbName) { XmlElement xmlElem = Configuration.TestSetUp( className, funName); // Open an environment. DatabaseEnvironmentConfig envConfig = new DatabaseEnvironmentConfig(); envConfig.Create = true; envConfig.UseTxns = true; envConfig.UseMPool = true; envConfig.UseLogging = true; DatabaseEnvironment env = DatabaseEnvironment.Open( home, envConfig); // Open a primary hash database. Transaction openDBTxn = env.BeginTransaction(); HashDatabaseConfig dbConfig = new HashDatabaseConfig(); dbConfig.Creation = CreatePolicy.IF_NEEDED; dbConfig.Env = env; HashDatabase db = HashDatabase.Open( dbFileName, dbConfig, openDBTxn); openDBTxn.Commit(); // Open a secondary hash database. Transaction openSecTxn = env.BeginTransaction(); SecondaryHashDatabaseConfig secDBConfig = new SecondaryHashDatabaseConfig(db, new SecondaryKeyGenDelegate(SecondaryKeyGen)); SecondaryHashDatabaseConfigTest.Config(xmlElem, ref secDBConfig, false); secDBConfig.HashFunction = null; secDBConfig.Env = env; SecondaryHashDatabase secDB; if (ifDbName == false) secDB = SecondaryHashDatabase.Open( dbSecFileName, secDBConfig, openSecTxn); else secDB = SecondaryHashDatabase.Open( dbSecFileName, "secondary", secDBConfig, openSecTxn); openSecTxn.Commit(); // Confirm its flags configured in secDBConfig. Confirm(xmlElem, secDB, true); secDB.Close(); // Open the existing secondary database. Transaction secTxn = env.BeginTransaction(); SecondaryDatabaseConfig secConfig = new SecondaryDatabaseConfig(db, new SecondaryKeyGenDelegate(SecondaryKeyGen)); secConfig.Env = env; SecondaryDatabase secExDB; if (ifDbName == false) secExDB = SecondaryHashDatabase.Open( dbSecFileName, secConfig, secTxn); else secExDB = SecondaryHashDatabase.Open( dbSecFileName, "secondary", secConfig, secTxn); secExDB.Close(); secTxn.Commit(); db.Close(); env.Close(); } public DatabaseEntry SecondaryKeyGen( DatabaseEntry key, DatabaseEntry data) { DatabaseEntry dbtGen; dbtGen = new DatabaseEntry(data.Data); return dbtGen; } public int SecondaryEntryComparison( DatabaseEntry dbt1, DatabaseEntry dbt2) { int a, b; a = BitConverter.ToInt32(dbt1.Data, 0); b = BitConverter.ToInt32(dbt2.Data, 0); return a - b; } public static void Confirm(XmlElement xmlElem, SecondaryHashDatabase secDB, bool compulsory) { Configuration.ConfirmUint(xmlElem, "FillFactor", secDB.FillFactor, compulsory); Configuration.ConfirmUint(xmlElem, "NumElements", secDB.TableSize * secDB.FillFactor, compulsory); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsRequiredOptional { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class ImplicitModelExtensions { /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pathParameter'> /// </param> public static Error GetRequiredPath(this IImplicitModel operations, string pathParameter) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredPathAsync(pathParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='pathParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredPathAsync( this IImplicitModel operations, string pathParameter, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetRequiredPathWithHttpMessagesAsync(pathParameter, null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> public static void PutOptionalQuery(this IImplicitModel operations, string queryParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalQueryAsync(queryParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalQueryAsync( this IImplicitModel operations, string queryParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalQueryWithHttpMessagesAsync(queryParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly optional header parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> public static void PutOptionalHeader(this IImplicitModel operations, string queryParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalHeaderAsync(queryParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional header parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queryParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalHeaderAsync( this IImplicitModel operations, string queryParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalHeaderWithHttpMessagesAsync(queryParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly optional body parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> public static void PutOptionalBody(this IImplicitModel operations, string bodyParameter = default(string)) { Task.Factory.StartNew(s => ((IImplicitModel)s).PutOptionalBodyAsync(bodyParameter), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional body parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='bodyParameter'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task PutOptionalBodyAsync( this IImplicitModel operations, string bodyParameter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutOptionalBodyWithHttpMessagesAsync(bodyParameter, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetRequiredGlobalPath(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredGlobalPathAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required path parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredGlobalPathAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetRequiredGlobalPathWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test implicitly required query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetRequiredGlobalQuery(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetRequiredGlobalQueryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly required query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetRequiredGlobalQueryAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetRequiredGlobalQueryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Error GetOptionalGlobalQuery(this IImplicitModel operations) { return Task.Factory.StartNew(s => ((IImplicitModel)s).GetOptionalGlobalQueryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Test implicitly optional query parameter /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Error> GetOptionalGlobalQueryAsync( this IImplicitModel operations, CancellationToken cancellationToken = default(CancellationToken)) { var _result = await operations.GetOptionalGlobalQueryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return _result.Body; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Binary { using System; using System.Collections; /// <summary> /// binary object builder. Provides ability to build binary objects dynamically /// without having class definitions. /// <para /> /// Note that type ID is required in order to build binary object. Usually it is /// enough to provide a simple type name and Ignite will generate the type ID /// automatically. /// </summary> public interface IBinaryObjectBuilder { /// <summary> /// Get object field value. If value is another binary object, then /// builder for this object will be returned. If value is a container /// for other objects (array, ICollection, IDictionary), then container /// will be returned with primitive types in deserialized form and /// binary objects as builders. Any change in builder or collection /// returned through this method will be reflected in the resulting /// binary object after build. /// </summary> /// <param name="fieldName">Field name.</param> /// <returns>Field value.</returns> T GetField<T>(string fieldName); /// <summary> /// Set object field value. Value can be of any type including other /// <see cref="IBinaryObject"/> and other builders. /// </summary> /// <param name="fieldName">Field name.</param> /// <param name="val">Field value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetField<T>(string fieldName, T val); /// <summary> /// Remove object field. /// </summary> /// <param name="fieldName">Field name.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder RemoveField(string fieldName); /// <summary> /// Set explicit hash code. If builder creating object from scratch, /// then hash code initially set to 0. If builder is created from /// existing binary object, then hash code of that object is used /// as initial value. /// </summary> /// <param name="hashCode">Hash code.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetHashCode(int hashCode); /// <summary> /// Build the object. /// </summary> /// <returns>Resulting binary object.</returns> IBinaryObject Build(); /// <summary> /// Sets the array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetArrayField<T>(string fieldName, T[] val); /// <summary> /// Sets the boolean field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetBooleanField(string fieldName, bool val); /// <summary> /// Sets the boolean array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetBooleanArrayField(string fieldName, bool[] val); /// <summary> /// Sets the byte field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetByteField(string fieldName, byte val); /// <summary> /// Sets the byte array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetByteArrayField(string fieldName, byte[] val); /// <summary> /// Sets the char field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetCharField(string fieldName, char val); /// <summary> /// Sets the char array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetCharArrayField(string fieldName, char[] val); /// <summary> /// Sets the collection field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetCollectionField(string fieldName, ICollection val); /// <summary> /// Sets the decimal field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetDecimalField(string fieldName, decimal? val); /// <summary> /// Sets the decimal array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetDecimalArrayField(string fieldName, decimal?[] val); /// <summary> /// Sets the dictionary field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetDictionaryField(string fieldName, IDictionary val); /// <summary> /// Sets the double field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetDoubleField(string fieldName, double val); /// <summary> /// Sets the double array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetDoubleArrayField(string fieldName, double[] val); /// <summary> /// Sets the enum field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetEnumField<T>(string fieldName, T val); /// <summary> /// Sets the enum array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetEnumArrayField<T>(string fieldName, T[] val); /// <summary> /// Sets the float field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetFloatField(string fieldName, float val); /// <summary> /// Sets the float array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetFloatArrayField(string fieldName, float[] val); /// <summary> /// Sets the guid field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetGuidField(string fieldName, Guid? val); /// <summary> /// Sets the guid array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetGuidArrayField(string fieldName, Guid?[] val); /// <summary> /// Sets the int field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetIntField(string fieldName, int val); /// <summary> /// Sets the int array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetIntArrayField(string fieldName, int[] val); /// <summary> /// Sets the long field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetLongField(string fieldName, long val); /// <summary> /// Sets the long array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetLongArrayField(string fieldName, long[] val); /// <summary> /// Sets the short field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetShortField(string fieldName, short val); /// <summary> /// Sets the short array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetShortArrayField(string fieldName, short[] val); /// <summary> /// Sets the string field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetStringField(string fieldName, string val); /// <summary> /// Sets the string array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetStringArrayField(string fieldName, string[] val); /// <summary> /// Sets the timestamp field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetTimestampField(string fieldName, DateTime? val); /// <summary> /// Sets the timestamp array field. /// </summary> /// <param name="fieldName">Name of the field.</param> /// <param name="val">The value.</param> /// <returns>Current builder instance.</returns> IBinaryObjectBuilder SetTimestampArrayField(string fieldName, DateTime?[] val); } }
/* * File Name: Recognizer.cs * Author : Chi-En Wu * Date : 2012/01/04 */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Xml; using Utils.DataStructure; namespace Utils.NamedEntity { /// <summary> /// An Recognizer that is used to find all named entities that occurs in content text. /// </summary> /// <typeparam name="T">The type of the information that describes for each named entity.</typeparam> public class NamedEntityRecognizer<T> { #region [Constructor(s)] /// <summary> /// Initializes a new instance of the <see cref="NamedEntityRecognizer&lt;T&gt;"/> class. /// </summary> public NamedEntityRecognizer() { this.dictionary = new NamedEntityDictionary<T>(); } /// <summary> /// Initializes a new instance of the <see cref="NamedEntityRecognizer&lt;T&gt;"/> class contains elements given by the specified IDictionary&lt;string, T&gt;. /// </summary> /// <param name="dictionary">The IDictionary&lt;string, T&gt; that used to initialize the new <see cref="NamedEntityRecognizer&lt;T&gt;"/>.</param> public NamedEntityRecognizer(IDictionary<string, T> dictionary) { this.dictionary = new NamedEntityDictionary<T>(dictionary); } #endregion #region[Field(s)] private NamedEntityDictionary<T> dictionary; #endregion #region[Property(ies)] /// <summary> /// An dictionary records information of named entities. /// </summary> public NamedEntityDictionary<T> Dictionary { get { return this.dictionary; } } #endregion #region [Public Method(s)] /// <summary> /// Recognizes named entities occurring in content text that recorded in the dictionary. /// </summary> /// <param name="content">The content string to recognize the named entities.</param> /// <returns>A set of <see cref="NamedEntityInfo&lt;T&gt;"/> represents named entities that is recognized from the content text.</returns> public ICollection<NamedEntityInfo<T>> Recognize(string content) { return this.dictionary.Recognize(content); } #endregion } /// <summary> /// An dictionary records information of named entities. /// </summary> /// <typeparam name="T">The type of the information that describes for each named entity.</typeparam> public class NamedEntityDictionary<T> : AbstractDictionary<string, T> { #region [Constructor(s)] /// <summary> /// Initializes a new instance of the <see cref="NamedEntityDictionary&lt;T&gt;"/> class. /// </summary> public NamedEntityDictionary() { this.prefixTree = new PrefixTree<string, T>(); this.dictionary = new Dictionary<string, T>(); } /// <summary> /// Initializes a new instance of the <see cref="NamedEntityDictionary&lt;T&gt;"/> class contains elements given by the specified IDictionary&lt;string, T&gt;. /// </summary> /// <param name="dictionary">The IDictionary&lt;string, T&gt; that used to initialize the new <see cref="NamedEntityDictionary&lt;T&gt;"/>.</param> public NamedEntityDictionary(IDictionary<string, T> dictionary) : this() { foreach (KeyValuePair<string, T> pair in dictionary) { this.Add(pair.Key, pair.Value); } } #endregion #region [Field(s)] private PrefixTree<string, T> prefixTree; private Dictionary<string, T> dictionary; #endregion #region [Property(ies)] /// <summary> /// Gets the number of key/value pairs contained in the dictionary. /// </summary> public override int Count { get { return this.dictionary.Count; } } /// <summary> /// Gets a collection containing the keys in the dictionary. /// </summary> public override ICollection<string> Keys { get { return this.dictionary.Keys; } } /// <summary> /// Gets a collection containing the values in the dictionary. /// </summary> public override ICollection<T> Values { get { return dictionary.Values; } } /// <summary> /// Gets or sets the value associated with the specified key. /// </summary> /// <param name="key">The key of the value to get or set.</param> public override T this[string key] { get { return this.dictionary[key.ToLower()]; } set { key = key.ToLower(); this.prefixTree.TrySetValue(NamedEntityDictionary<T>.Tokenize(key), value); this.dictionary[key] = value; } } #endregion #region [Public Method(s)] /// <summary> /// Recognizes named entities occurring in content text that recorded in the dictionary. /// </summary> /// <param name="content">The content string to recognize the named entities.</param> /// <returns>A set of <see cref="NamedEntityInfo&lt;T&gt;"/> represents named entities that is recognized from the content text.</returns> public IList<NamedEntityInfo<T>> Recognize(string content) { content = content.ToLower(); IList<string> tokens = NamedEntityDictionary<T>.Tokenize(content); IList<NamedEntityInfo<T>> result = new List<NamedEntityInfo<T>>(); int contentIndex = 0; while (tokens.Count > 0) { PrefixMatch<string, T> match = this.prefixTree.LongestPrefixMatch(tokens); if (match.Length == 0) { contentIndex += tokens[0].Length; tokens.RemoveAt(0); continue; } int termLength = 0; for (int index = 0; index < match.Length; index++) { termLength += tokens[0].Length; tokens.RemoveAt(0); } NamedEntityInfo<T> entity = new NamedEntityInfo<T>(match.Value, contentIndex, termLength); result.Add(entity); contentIndex += termLength; } return result; } /// <summary> /// Updates the dictionary by the specified IDictionary&lt;string, T&gt;. If <paramref name="dictionary"/> contains keys including in the dictionary, the old value will be overwritten with the new one. /// </summary> /// <param name="dictionary">The IDictionary&lt;string, T&gt; that used to update the dictionary.</param> public void Update(IDictionary<string, T> dictionary) { foreach (KeyValuePair<string, T> pair in dictionary) { this[pair.Key] = pair.Value; } } /// <summary> /// Adds the specified key and value to the dictionary. /// </summary> /// <param name="key">The key of the element to add.</param> /// <param name="value">The value of the element to add. The value can be null for reference types.</param> public override void Add(string key, T value) { key = key.ToLower(); this.prefixTree.SetValue(NamedEntityDictionary<T>.Tokenize(key), value); this.dictionary.Add(key, value); } /// <summary> /// Removes all keys and values from the dictionary. /// </summary> public override void Clear() { this.dictionary.Clear(); this.prefixTree.Clear(); } /// <summary> /// Determines whether the dictionary contains the specified key. /// </summary> /// <param name="key">The key to locate in the dictionary.</param> /// <returns>True if the dictionary contains an element with the specified key; otherwise, false.</returns> public override bool ContainsKey(string key) { return this.dictionary.ContainsKey(key.ToLower()); } /// <summary> /// Removes the value with the specified key from the dictionary. /// </summary> /// <param name="key">The key of the element to remove.</param> /// <returns>True if the element is successfully found and removed; otherwise, false. This method returns false if key is not found in the dictionary.</returns> public override bool Remove(string key) { key = key.ToLower(); bool dictResult = this.dictionary.Remove(key); bool treeResult = this.prefixTree.Remove(NamedEntityDictionary<T>.Tokenize(key)); Debug.Assert(dictResult == treeResult); return treeResult; } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key of the value to get.</param> /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of the value parameter. This parameter is passed uninitialized.</param> /// <returns>True if the dictionary contains an element with the specified key; otherwise, false.</returns> public override bool TryGetValue(string key, out T value) { return this.dictionary.TryGetValue(key.ToLower(), out value); } /// <summary> /// Returns an enumerator that iterates through the dictionary. /// </summary> /// <returns>An <see cref="IEnumerator&lt;T&gt;"/> that can be used to iterate through the collection.</returns> public override IEnumerator<KeyValuePair<string, T>> GetEnumerator() { return this.dictionary.GetEnumerator(); } #endregion #region [Private Static Method(s)] private static IList<string> Tokenize(string content) { char[] symbols = @"_+-*/=|#.,:;!?'""()[] ".ToCharArray(); List<string> result = new List<string>(); int start = 0, end = 0; while ((end = content.IndexOfAny(symbols, start)) > 0) { if (start != end) { result.Add(content.Substring(start, end - start)); } result.Add(content[end].ToString()); start = end + 1; } if (start != content.Length) { result.Add(content.Substring(start)); } return result; } #endregion } /// <summary> /// Represents the result of named entity recognition. /// </summary> /// <typeparam name="T">The type of the information that describes for each named entity.</typeparam> public struct NamedEntityInfo<T> { #region [Constructor(s)] internal NamedEntityInfo(T info, int index, int length) { this.info = info; this.index = index; this.length = length; } #endregion #region [Field(s)] private T info; private int index; private int length; #endregion #region [Property(ies)] /// <summary> /// The information that describes for each named entity. /// </summary> public T Info { get { return this.info; } } /// <summary> /// The index of content text that the named entity occurs. /// </summary> public int Index { get { return this.index; } } /// <summary> /// The length of the named entity that occurs in the content text. /// </summary> public int Length { get { return this.length; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using NRules.Fluent.Dsl; using NRules.RuleModel; using NRules.RuleModel.Builders; namespace NRules.Fluent.Expressions { internal class QueryExpression : IQuery, IQueryBuilder { private readonly ParameterExpression _symbol; private readonly SymbolStack _symbolStack; private readonly GroupBuilder _groupBuilder; private Func<string, Type, BuildResult> _buildAction; public QueryExpression(ParameterExpression symbol, SymbolStack symbolStack, GroupBuilder groupBuilder) { _symbol = symbol; _symbolStack = symbolStack; _groupBuilder = groupBuilder; Builder = this; } public IQueryBuilder Builder { get; } public void FactQuery<TSource>(Expression<Func<TSource, bool>>[] conditions) { _buildAction = (name, _) => { var patternBuilder = new PatternBuilder(typeof(TSource), name); patternBuilder.DslConditions(_symbolStack.Scope.Declarations, conditions); _symbolStack.Scope.Add(patternBuilder.Declaration); return new BuildResult(patternBuilder); }; } public void From<TSource>(Expression<Func<TSource>> source) { _buildAction = (name, _) => { var patternBuilder = new PatternBuilder(typeof(TSource), name); var bindingBuilder = patternBuilder.Binding(); bindingBuilder.DslBindingExpression(_symbolStack.Scope.Declarations, source); _symbolStack.Scope.Add(patternBuilder.Declaration); return new BuildResult(patternBuilder); }; } public void Where<TSource>(Expression<Func<TSource, bool>>[] predicates) { var previousBuildAction = _buildAction; _buildAction = (name, type) => { var result = previousBuildAction(name, type); result.Pattern.DslConditions(_symbolStack.Scope.Declarations, predicates); return result; }; } public void Select<TSource, TResult>(Expression<Func<TSource, TResult>> selector) { var previousBuildAction = _buildAction; _buildAction = (name, _) => { var patternBuilder = new PatternBuilder(typeof(TResult), name); BuildResult result; using (_symbolStack.Frame()) { var aggregateBuilder = patternBuilder.Aggregate(); var previousResult = previousBuildAction(null, null); var sourceBuilder = previousResult.Pattern; var selectorExpression = sourceBuilder.DslPatternExpression(_symbolStack.Scope.Declarations, selector); aggregateBuilder.Project(selectorExpression); aggregateBuilder.Pattern(sourceBuilder); result = new BuildResult(patternBuilder, aggregateBuilder, sourceBuilder); } _symbolStack.Scope.Add(patternBuilder.Declaration); return result; }; } public void SelectMany<TSource, TResult>(Expression<Func<TSource, IEnumerable<TResult>>> selector) { var previousBuildAction = _buildAction; _buildAction = (name, _) => { var patternBuilder = new PatternBuilder(typeof(TResult), name); BuildResult result; using (_symbolStack.Frame()) { var aggregateBuilder = patternBuilder.Aggregate(); var previousResult = previousBuildAction(null, null); var sourceBuilder = previousResult.Pattern; var selectorExpression = sourceBuilder.DslPatternExpression(_symbolStack.Scope.Declarations, selector); aggregateBuilder.Flatten(selectorExpression); aggregateBuilder.Pattern(sourceBuilder); result = new BuildResult(patternBuilder, aggregateBuilder, sourceBuilder); } _symbolStack.Scope.Add(patternBuilder.Declaration); return result; }; } public void GroupBy<TSource, TKey, TElement>(Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector) { var previousBuildAction = _buildAction; _buildAction = (name, _) => { var patternBuilder = new PatternBuilder(typeof(IGrouping<TKey, TElement>), name); BuildResult result; using (_symbolStack.Frame()) { var aggregateBuilder = patternBuilder.Aggregate(); var previousResult = previousBuildAction(null, null); var sourceBuilder = previousResult.Pattern; var keySelectorExpression = sourceBuilder.DslPatternExpression(_symbolStack.Scope.Declarations, keySelector); var elementSelectorExpression = sourceBuilder.DslPatternExpression(_symbolStack.Scope.Declarations, elementSelector); aggregateBuilder.GroupBy(keySelectorExpression, elementSelectorExpression); aggregateBuilder.Pattern(sourceBuilder); result = new BuildResult(patternBuilder, aggregateBuilder, sourceBuilder); } _symbolStack.Scope.Add(patternBuilder.Declaration); return result; }; } public void Collect<TSource>() { var previousBuildAction = _buildAction; _buildAction = (name, type) => { var patternBuilder = new PatternBuilder(type ?? typeof(IEnumerable<TSource>), name); BuildResult result; using (_symbolStack.Frame()) { var aggregateBuilder = patternBuilder.Aggregate(); var previousResult = previousBuildAction(null, null); var sourceBuilder = previousResult.Pattern; aggregateBuilder.Collect(); aggregateBuilder.Pattern(sourceBuilder); result = new BuildResult(patternBuilder, aggregateBuilder, sourceBuilder); } _symbolStack.Scope.Add(patternBuilder.Declaration); return result; }; } public void ToLookup<TSource, TKey, TElement>(Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector) { var previousBuildAction = _buildAction; _buildAction = (name, _) => { var result = previousBuildAction(name, typeof(IKeyedLookup<TKey, TElement>)); var keySelectorExpression = result.Source.DslPatternExpression(_symbolStack.Scope.Declarations, keySelector); var elementSelectorExpression = result.Source.DslPatternExpression(_symbolStack.Scope.Declarations, elementSelector); result.Aggregate.ToLookup(keySelectorExpression, elementSelectorExpression); return result; }; } public void OrderBy<TSource, TKey>(Expression<Func<TSource, TKey>> keySelector, SortDirection sortDirection) { var previousBuildAction = _buildAction; _buildAction = (name, type) => { var result = previousBuildAction(name, type); var keySelectorExpression = result.Source.DslPatternExpression(_symbolStack.Scope.Declarations, keySelector); result.Aggregate.OrderBy(keySelectorExpression, sortDirection); return result; }; } public void Aggregate<TSource, TResult>(string aggregateName, IEnumerable<KeyValuePair<string, LambdaExpression>> expressions) { Aggregate<TSource, TResult>(aggregateName, expressions, null); } public void Aggregate<TSource, TResult>(string aggregateName, IEnumerable<KeyValuePair<string, LambdaExpression>> expressions, Type customFactoryType) { var previousBuildAction = _buildAction; _buildAction = (name, _) => { var patternBuilder = new PatternBuilder(typeof(TResult), name); BuildResult result; using (_symbolStack.Frame()) { var aggregateBuilder = patternBuilder.Aggregate(); var previousResult = previousBuildAction(null, null); var sourceBuilder = previousResult.Pattern; var rewrittenExpressionCollection = new List<KeyValuePair<string, LambdaExpression>>(); foreach (var item in expressions) { var expression = sourceBuilder.DslPatternExpression(_symbolStack.Scope.Declarations, item.Value); rewrittenExpressionCollection.Add(new KeyValuePair<string, LambdaExpression>(item.Key, expression)); } aggregateBuilder.Aggregator(aggregateName, rewrittenExpressionCollection, customFactoryType); aggregateBuilder.Pattern(sourceBuilder); result = new BuildResult(patternBuilder, aggregateBuilder, sourceBuilder); } _symbolStack.Scope.Add(patternBuilder.Declaration); return result; }; } public PatternBuilder Build() { var patternBuilder = _buildAction(_symbol.Name, null); _groupBuilder.Pattern(patternBuilder.Pattern); return patternBuilder.Pattern; } private class BuildResult { public BuildResult(PatternBuilder pattern, AggregateBuilder aggregate, PatternBuilder source) : this(pattern) { Aggregate = aggregate; Source = source; } public BuildResult(PatternBuilder pattern) { Pattern = pattern; } public PatternBuilder Pattern { get; } public AggregateBuilder Aggregate { get; } public PatternBuilder Source { get; } } } }
using Game.Network; using Game.Players; using Game.Utils; using LiteNetLib; using LiteNetLib.Utils; using System.Collections.Generic; namespace Presentation.Network { public class GameServer : SingletonMono<GameServer> { public static readonly int DEFAULT_PORT = 28960; public int port = DEFAULT_PORT; public int maxConnections = 8; private NetServer baseServer; private int serverID; private PlayerBuffer players; private Dictionary<NetPeer, int> clients; private ServerState currentState; #region Properties public int ID { get { return serverID; } } public PlayerBuffer Players { get { return players; } } #endregion #region MonoBehaviour void Awake() { DontDestroyOnLoad(this); serverID = 0; print("Server starting on port " + port + " ..."); baseServer = new NetServer(port, maxConnections, NetConfig.ServerDefault); players = new PlayerBuffer(maxConnections); clients = new Dictionary<NetPeer, int>(); StartServer(); currentState = new LobbyState(this); } void OnEnable() { baseServer.Bind(NetPacketType.PeerConnect, OnClientConnected); baseServer.Bind(NetPacketType.PeerDisconnect, OnClientDisconnected); baseServer.Bind(NetPacketType.NetError, OnNetworkError); baseServer.BindDefault(OnUnknownDataReceived); } void OnDisable() { baseServer.Unbind(NetPacketType.PeerConnect, OnClientConnected); baseServer.Unbind(NetPacketType.PeerDisconnect, OnClientDisconnected); baseServer.Unbind(NetPacketType.NetError, OnNetworkError); baseServer.UnbindDefault(OnUnknownDataReceived); } void Update() { if (baseServer.IsReady()) { baseServer.Listen(); baseServer.SendMessages(); } } void OnDestroy() { Stop(); players.Reset(); clients.Clear(); } #endregion #region Singleton /// <summary> /// Gets the netServer instance. /// </summary> public static NetServer NetworkServer { get { return Instance.baseServer; } } /// <summary> /// Starts the network server. /// </summary> public static void StartServer() { Init(); instance.baseServer.Start(); } /// <summary> /// Stops the network server. /// </summary> public static void Stop() { instance.baseServer.Stop(); } /// <summary> /// Starts the game, if the players are ready (host only) /// </summary> public static void StartGame() { instance.StartGameInternal(); } /// <summary> /// Adds the packet to the output queue. /// </summary> /// <param name="packet">message to be sent</param> /// <param name="client">client receiver</param> public static void Send(PacketBase packet, NetPeer client) { instance.baseServer.AddOutputMessage(new NetMessage(packet, client)); } /// <summary> /// Adds the packet to the output queue, for every client except the given one. /// </summary> /// <param name="packet">data to be sent</param> /// <param name="client">client excluded (usually the original sender)</param> public static void SendExcluding(PacketBase packet, NetPeer client) { instance.baseServer.AddMessageExcluding(packet, client); } /// <summary> /// Register an external handler for the given packet type. /// </summary> /// <param name="type">packet type</param> /// <param name="handler">function to add</param> public static void Register(NetPacketType type, MessageDelegate handler) { instance.baseServer.Bind(type, handler); } /// <summary> /// Unregister an external handler for the given packet type. /// </summary> /// <param name="type">packet type</param> /// <param name="handler">function to remove</param> public static void Unregister(NetPacketType type, MessageDelegate handler) { instance.baseServer.Unbind(type, handler); } #endregion #region Handlers /// <summary> /// A client connected, no actions are taken. /// </summary> /// <param name="client">client that connected</param> /// <param name="args">extra arguments (null in this case)</param> private void OnClientConnected(NetPeer client, NetEventArgs args) { UnityEngine.Debug.Log("[SERVER] Connected client, waiting for authentication request..."); } /// <summary> /// Handler for disconnections. /// </summary> /// <param name="client">client that disconnnected from this server</param> /// <param name="args">extra arguments</param> private void OnClientDisconnected(NetPeer client, NetEventArgs args) { UnityEngine.Debug.Log("[SERVER] Client disconnected"); int id; if (clients.TryGetValue(client, out id)) { Player p = players.Get(id); players.Remove(p); clients.Remove(client); PacketBase message = new PacketPlayerLeave(serverID, p); baseServer.AddOutputMessage(new NetMessage(message)); } } /// <summary> /// Handler for network errors. /// </summary> /// <param name="client">client tha probably caused it</param> /// <param name="args">data containing the error code</param> private void OnNetworkError(NetPeer client, NetEventArgs args) { UnityEngine.Debug.Log("[SERVER] Error on the network: " + (int)(args.Data)); } /// <summary> /// Handler for unhandled packet types. /// </summary> /// <param name="client">client who sent the packet</param> /// <param name="args">unknown packet</param> private void OnUnknownDataReceived(NetPeer client, NetEventArgs args) { UnityEngine.Debug.LogWarning("[SERVER] Received unhandled data from " + client.EndPoint); UnityEngine.Debug.LogWarning("[SERVER] Data: " + args.Data); } #endregion #region Helper Functions /// <summary> /// Disconnects the given client, sending the extra message as additional info. /// </summary> /// <param name="client">the client to refuse</param> /// <param name="additionalInfo">text describing the reason</param> public void Disconnect(NetPeer client, string additionalInfo) { clients.Remove(client); byte[] data = System.Text.Encoding.ASCII.GetBytes(additionalInfo); baseServer.Disconnect(client, data); } /// <summary> /// Registers the current player to the players buffer and assigns the relative client instance to the dictionary. /// </summary> /// <param name="client">peer instance belonging to the player</param> /// <param name="player">player instance containing every info</param> public void AddPlayer(NetPeer client, Player player) { clients.Add(client, player.ID); players.Add(player); } /// <summary> /// Instance function to start the game if all players are ready. /// </summary> private void StartGameInternal() { if (!players.ReadyToStart()) { UnityEngine.Debug.Log("[SERVER] All clients must be ready in order to start!"); return; } instance.baseServer.AddOutputMessage(new NetMessage(new PacketGameStart(instance.serverID))); currentState = currentState.Next(); } #endregion } }
// 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. #if CONTRACTS_EXPERIMENTAL using System; using Microsoft.Research.AbstractDomains; using Microsoft.Research.DataStructures; using System.Collections.Generic; using Microsoft.Research.CodeAnalysis; using Microsoft.Research.AbstractDomains.Expressions; using System.Diagnostics; namespace Microsoft.Research.CodeAnalysis { public static partial class AnalysisWrapper { /// <summary> /// Entry point to run the partition analysis /// </summary> public static TypeBindings<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable>.PartitionAnalysis RunPartitionAnalysis<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable> ( string methodName, IMethodDriver<APC, Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable, ILogOptions> driver, List<Analyzers.Containers.ContainerOptions> options, IFactQuery<BoxedExpression, Variable> factQuery) where Variable : IEquatable<Variable> where ExternalExpression : IEquatable<ExternalExpression> where Type : IEquatable<Type> { //var analysis = // new TypeBindings<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable>.PartitionAnalysis(methodName, driver, options); return TypeBindings<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable>.HelperForPartitionAnalysis(methodName, driver, options, factQuery); } /// <summary> /// This class is just for binding types for the internal classes /// </summary> public static partial class TypeBindings<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable> where Variable : IEquatable<Variable> where ExternalExpression : IEquatable<ExternalExpression> where Type : IEquatable<Type> { /// <summary> /// It runs the analysis. /// It is there because so we can use the typebinding, and make the code less verbose. /// </summary> internal static PartitionAnalysis HelperForPartitionAnalysis(string methodName, IMethodDriver<APC, Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable, ILogOptions> driver, List<Analyzers.Containers.ContainerOptions> optionsList, IFactQuery<BoxedExpression, Variable> factQuery) { PartitionAnalysis analysis; analysis = new PartitionAnalysis(methodName, driver, optionsList, factQuery); // *** The next lines must be strictly sequential *** var closure = driver.CreateForward<SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression>>(analysis); // At this point, CreateForward has called the Visitor, so the context has been created, so that now we can call initValue SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression>.Trace = optionsList[0].TracePartitionAnalysis; var initValue = analysis.InitialValue; closure(initValue); // Do the analysis return analysis; } #region Facility to forward operations on the abstract domain (implementation of IAbstractDomainOperations) public class AbstractOperationsImplementationPartition : IAbstractDomainOperations<APC, Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression>> { public bool LookupState(IMethodResult<Variable> mr, APC pc, out SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate) { astate = null; PartitionAnalysis an = mr as PartitionAnalysis; if (an == null) return false; return an.PreStateLookup(pc, out astate); } public SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Join(IMethodResult<Variable> mr, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate1, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate2) { PartitionAnalysis an = mr as PartitionAnalysis; if (an == null) return null; bool bWeaker; return an.Join(new Pair<APC, APC>(), astate1, astate2, out bWeaker, false); } public List<BoxedExpression> ExtractAssertions( IMethodResult<Variable> mr, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate, IExpressionContext<APC, Local, Parameter, Method, Field, Type, ExternalExpression, Variable> context, IDecodeMetaData<Local, Parameter, Method, Field, Property, Type, Attribute, Assembly> metaDataDecoder) { PartitionAnalysis an = mr as PartitionAnalysis; if (an == null) return null; BoxedExpressionReader<APC, Local, Parameter, Method, Field, Property, Type, Variable, ExternalExpression, Attribute, Assembly> br = new BoxedExpressionReader<APC, Local, Parameter, Method, Field, Property, Type, Variable, ExternalExpression, Attribute, Assembly>(context, metaDataDecoder); return an.ToListOfBoxedExpressions(astate, br); } public bool AssignInParallel(IMethodResult<Variable> mr, ref SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> astate, Dictionary<BoxedVariable<Variable>, FList<BoxedVariable<Variable>>> mapping, Converter<BoxedVariable<Variable>, BoxedExpression> convert) { PartitionAnalysis an = mr as PartitionAnalysis; if (an == null) return false; astate.AssignInParallel(mapping, convert); return true; } } #endregion /// <summary> /// The analysis for the partitions of the containers : a generic value analysis /// </summary> public class PartitionAnalysis : GenericValueAnalysis<SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression>, Analyzers.Containers.ContainerOptions> { //protected readonly List<Analyzers.Containers.ContainerOptions> optionsList; readonly PartitionsObligations obligations; //internal IMethodDriver<APC, Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable, ILogOptions> mdriver; protected readonly IFactQuery<BoxedExpression, Variable> factQuery; #region Constructors internal PartitionAnalysis( string methodName, IMethodDriver<APC, Local, Parameter, Method, Field, Property, Type, Attribute, Assembly, ExternalExpression, Variable, ILogOptions> mdriver, List<Analyzers.Containers.ContainerOptions> optionsList, IFactQuery<BoxedExpression, Variable> factQuery) : base(methodName, mdriver, optionsList[0]) { //this.mdriver = mdriver; //this.optionsList = optionsList; this.factQuery = factQuery; this.obligations = new PartitionsObligations(mdriver, optionsList[0]); } #endregion #region Extract information public bool TryPartitionAt(APC pc, out SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> result) { if (this.fixpointInfo.PreState(pc, out result)) { return true; } result = default(SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression>); return false; } #endregion #region Implementation of the abstract interface protected internal override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> InitialValue { get { // TODO: implement an option for choosing partition representation // IPartitionAbstraction<BoxedVariable<Variable>, BoxedExpression> partition = new ... // return new SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression>(this.Encoder, this.Decoder, partition); // Return an empty environment of partitions based on Octagons. return new SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression>(this.Encoder, this.Decoder); } } protected override ProofObligations<Local, Parameter, Method, Field, Property, Type, Variable, ExternalExpression, Attribute, Assembly, BoxedExpression, ProofObligationBase<BoxedExpression, Variable>> Obligations { get { // TODO return this.obligations; } } public override IFactQuery<BoxedExpression, Variable> FactQuery { get { // Result of a partition analysis will not be translated into a factQuery return new ComposedFactQuery<Variable>(this.MethodDriver.IsUnreachable); } } protected override void SuggestAnalysisSpecificPostconditions(List<BoxedExpression> postconditions) { return; } protected override bool TrySuggestPostconditionForOutParameters(List<BoxedExpression> postconditions, Variable p, FList<PathElement> path) { return false; } #endregion protected override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> HelperForJoin(SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> newState, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> prevState, Pair<APC, APC> edge) { /// - that an array can be null, and in his case not appearing into the environment var keep = new Set<BoxedVariable<Variable>>(); foreach (var bv in prevState.Variables) { Variable v; if (bv.TryUnpackVariable(out v)) { var atJoinPoint = this.factQuery.IsNull(edge.Two, v); var atJoinedPoint = this.factQuery.IsNull(edge.One, v); if (atJoinPoint == ProofOutcome.Top) { //if (atJoinedPoint == ProofOutcome.True) //{ // // do nothing //} //else if (atJoinedPoint == ProofOutcome.False) { // for some paths exp is null : we want to keep it in the environment keep.Add(bv); } // TODO: could be also TOP if in every branch a (non-identity) rebinding appeared } } } var result = newState.Join(prevState, keep); //return base.HelperForJoin(newState, prevState, edge); return result; } #region OfInterest1 /// <summary> /// Retrieve the lower bounds and the upper bounds of an <typeparam name="exp">expression</typeparam> at some <typeparam name="pc">control point</typeparam> and return /// the conjonction of the corresponding constraint on the <typeparam name="exp">expression</typeparam>. /// </summary> private BoxedExpression gatherKnowledge(APC pc, BoxedExpression exp) { var lowerBounds = this.factQuery.LowerBoundsAsExpressions(pc, exp, false); var strictLowerBounds = this.factQuery.LowerBoundsAsExpressions(pc, exp, true); var upperBounds = this.factQuery.UpperBoundsAsExpressions(pc, exp, false); var strictUpperBounds = this.factQuery.UpperBoundsAsExpressions(pc, exp, true); var result = this.Encoder.ConstantFor(true); foreach(var lowerBound in lowerBounds) { if (!(exp.IsConstant && lowerBound.IsConstant)) { var comparison = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.GreaterEqualThan, exp, lowerBound); result = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, comparison, result); } } foreach (var strictLowerBound in strictLowerBounds) { if (!(exp.IsConstant && strictLowerBound.IsConstant)) { var comparison = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.GreaterThan, exp, strictLowerBound); result = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, comparison, result); } } foreach (var upperBound in upperBounds) { if (!(exp.IsConstant && upperBound.IsConstant)) { var comparison = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.LessEqualThan, exp, upperBound); result = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, comparison, result); } } foreach (var strictUpperBound in strictUpperBounds) { if (!(exp.IsConstant && strictUpperBound.IsConstant)) { var comparison = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.LessThan, exp, strictUpperBound); result = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, comparison, result); } } return result; } /// <summary> /// Infer the tightest lower bound and upper bound of an <typeparam name="exp">expression</typeparam> at some <typeparam name="pc">control point</typeparam> /// TODO : ... if possible based on some <typeparam name="vars">specific variables</typeparam>. /// </summary> /// <remarks> /// Inference based on syntaxic comparisons for performance reasons. /// </remarks> private Pair<BoxedExpression,BoxedExpression> guessRange(APC pc, BoxedExpression exp) { if (exp.IsConstant) { return new Pair<BoxedExpression, BoxedExpression>(exp, exp); } var expVar = this.Decoder.UnderlyingVariable(exp); // lower bound var lowerBounds = this.factQuery.LowerBoundsAsExpressions(pc, exp, false); var lowerCandidates = new Dictionary<BoxedExpression, IEnumerable<BoxedExpression>>(); foreach (var lowerBound in lowerBounds) { var lowerBoundVar = this.Decoder.UnderlyingVariable(lowerBound); // we need a non-trivial lower bound if (lowerBound.Equals(exp) || (this.Decoder.VariablesIn(lowerBound).Contains(expVar)) || (this.Decoder.VariablesIn(exp).Contains(lowerBoundVar))) { continue; } // initialization if (lowerCandidates.Count == 0) { lowerCandidates.Add(lowerBound, this.factQuery.LowerBoundsAsExpressions(pc, lowerBound, false)); continue; } // Is there already a tighter candidate ? var uninteresting = false; var equalToCandidate = false; foreach (var lowerCandidate in lowerCandidates) { // if they (lowerBound and lowerCandidate) are equals, keep both, we will choose later. // TODO: Or choose now ? if (lowerBound.Equals(lowerCandidate.Key)) { equalToCandidate = true; break; } foreach (var uninterestingBound in lowerCandidate.Value) { if (lowerBound.Equals(uninterestingBound)) { uninteresting = true; break; } } if (uninteresting) { break; } } if (uninteresting) { continue; } var lowerLowerBounds = this.factQuery.LowerBoundsAsExpressions(pc, lowerBound, false); if (!equalToCandidate) { // Is it tighter than an existing candidate ? foreach (var lowerLowerBound in lowerLowerBounds) { if (lowerCandidates.ContainsKey(lowerLowerBound)) { lowerCandidates.Remove(lowerLowerBound); } } } lowerCandidates.Add(lowerBound, lowerLowerBounds); } // upper bound var upperBounds = this.factQuery.UpperBoundsAsExpressions(pc, exp, false); var upperCandidates = new Dictionary<BoxedExpression, IEnumerable<BoxedExpression>>(); foreach (var upperBound in upperBounds) { var upperBoundVar = this.Decoder.UnderlyingVariable(upperBound); // we need a non-trivial upper bound if (upperBound.Equals(exp) || (this.Decoder.VariablesIn(upperBound).Contains(expVar)) || (this.Decoder.VariablesIn(exp).Contains(upperBoundVar))) { continue; } // initialization if (upperCandidates.Count == 0) { upperCandidates.Add(upperBound, this.factQuery.UpperBoundsAsExpressions(pc, upperBound, false)); continue; } // Is there already a tighter candidate ? bool uninteresting = false; bool equalToCandidate = false; foreach (var upperCandidate in upperCandidates) { // if they (lowerBound and lowerCandidate) are equals, keep both, we will choose later. // TODO: Or choose now ? if (upperBound.Equals(upperCandidate.Key)) { equalToCandidate = true; break; } foreach (var uninterestingBound in upperCandidate.Value) { if (upperBound.Equals(uninterestingBound)) { uninteresting = true; break; } } if (uninteresting) { break; } } if (uninteresting) { continue; } var upperUpperBounds = this.factQuery.UpperBoundsAsExpressions(pc, upperBound, false); if (!equalToCandidate) { // Is it tighter than an existing candidate ? foreach (var upperUpperBound in upperUpperBounds) { if (upperCandidates.ContainsKey(upperUpperBound)) { upperCandidates.Remove(upperUpperBound); } } } upperCandidates.Add(upperBound, upperUpperBounds); } BoxedExpression choosedLowerBound; BoxedExpression choosedUpperBound; // mscorlid method 473, SR516: no lower bound because exp (the index) come from an array ... // if (lowerCandidates.Count == 0 || upperCandidates.Count == 0) { throw ... } // Choose one between possible bounds // TODO: prefer the ones based on variables already present in the partition // TODO: if not unique, prefer constants var enumLowerBounds = lowerCandidates.Keys.GetEnumerator(); var b = enumLowerBounds.MoveNext(); if (b) { choosedLowerBound = enumLowerBounds.Current; } else { choosedLowerBound = null; } var enumUpperBounds = upperCandidates.Keys.GetEnumerator(); b = enumUpperBounds.MoveNext(); if (b) { choosedUpperBound = enumUpperBounds.Current; } else { choosedUpperBound = null; } var result = new Pair<BoxedExpression, BoxedExpression>(choosedLowerBound, choosedUpperBound); return result; } #endregion #region OfInterest2 /// <summary> /// Hypothesis: Bound Analysis assumed that <code>0 &le; len </code> and /// </summary> /// <param name="dest"></param> private SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> HandleAllocations(APC pc, Variable dest, Variable len, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { var lenAsExp = BoxedExpression.For(this.Context.Refine(pc, len), this.Decoder.Outdecoder); lenAsExp = this.Decoder.Stripped(lenAsExp); var destAsExp = BoxedExpression.For(this.Context.Refine(pc, dest), this.Decoder.Outdecoder); ALog.BeginTransferFunction(StringClosure.For("[P]Allocation"), ExpressionPrinter.ToStringClosure(lenAsExp, this.Decoder), PrettyPrintPC(pc), StringClosure.For(data)); var refinedDomain = data.Allocation(new BoxedVariable<Variable>(dest), lenAsExp); ALog.EndTransferFunction(StringClosure.For(data)); return refinedDomain; } /// <summary> /// Hypothesis: Bound Analysis assumed. /// </summary> /// <param name="dest"></param> private SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> HandleArrayAssignment( string name, APC pc, Variable array, Variable index, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { var arrayAsExp = BoxedExpression.For(this.Context.Refine(pc, array), this.Decoder.Outdecoder); var indexAsExp = BoxedExpression.For(this.Context.Refine(pc, index), this.Decoder.Outdecoder); ALog.BeginTransferFunction(StringClosure.For("[P]ArrayAssignement"), ExpressionPrinter.ToStringClosure(arrayAsExp, this.Decoder), PrettyPrintPC(pc), StringClosure.For(data)); var baseVariables = this.Decoder.VariablesIn(indexAsExp); Log("VARIABLESIN={0}", baseVariables); // TODO: decide wich variables you want in the partition : probably here a variable inside. You must gatherKnowledge for each variable inside, and reconstruct the bounds of interest. // eg. index: sv1; index is (sv2+1); indexKnowledge is (0,sv3); so (sv2+1) go from 1 to sv3+1 (but could be unnecessary if sv2 is already into the partition ...; var notWanted = new Set<BoxedVariable<Variable>>(); if (baseVariables.Count > 1 || !baseVariables.Contains(ToBoxedVariable(index))) { notWanted.Add(ToBoxedVariable(index)); } var knowledge = this.Encoder.ConstantFor(true); var equalityKnowledge = this.Encoder.ConstantFor(true); foreach (var e in baseVariables) { knowledge = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, knowledge, gatherKnowledge(this.Context.Post(pc), ToBoxedExpression(this.Context.Post(pc), e))); } if (!notWanted.IsEmpty) { // NOTE : even if notWanted will not be part of the split partition used, it can already be present in the current partition. // This is why we provide the information, to be used in simplify. PolynomialOfInt<BoxedVariable<Variable>, BoxedExpression> indexAsPoly; if (PolynomialOfInt<BoxedVariable<Variable>, BoxedExpression>.TryToPolynomialForm(indexAsExp, this.Decoder, out indexAsPoly)) { equalityKnowledge = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Equal, indexAsExp, PolynomialOfInt<BoxedVariable<Variable>, BoxedExpression>.ToPureExpressionForm(indexAsPoly, this.Encoder)); knowledge = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, knowledge, equalityKnowledge); } } //var indexKnowledge = gatherKnowledge(pc, indexAsExp); foreach (var e in baseVariables) { var indexRange = guessRange(pc, ToBoxedExpression(pc, e)); // carefull : One or Two can be null. Log("LB({1})={0}", indexRange.One, e); Log("UB({1})={0}", indexRange.Two, e); } var indexRange2 = guessRange(pc, indexAsExp); // carefull : One or Two can be null. Log("LB({1})={0}", indexRange2.One, indexAsExp); Log("UB({1})={0}", indexRange2.Two, indexAsExp); var refinedDomain = data.ArrayAssignment(ToBoxedVariable(array), indexAsExp, knowledge, notWanted); //,notWanted ALog.EndTransferFunction(StringClosure.For(data)); return refinedDomain; } private SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> HandleIndexAssignment(string name, APC pc, BoxedVariable<Variable> array, BoxedVariable<Variable> index, BoxedExpression assignedAsExp, BoxedExpression assignmentKnowledge, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { ALog.BeginTransferFunction(StringClosure.For("[P]IndexAssignement"), StringClosure.For(""), PrettyPrintPC(pc), StringClosure.For(data)); //var baseVariables = this.Decoder.VariablesIn(indexAsExp); var baseVariables = this.Decoder.VariablesIn(assignedAsExp); Log("VARIABLESIN={0}", baseVariables); var indexAsExp = ToBoxedExpression(pc, index); var indexKnowledge = gatherKnowledge(this.Context.Post(pc), indexAsExp); //TODO: post is not useful here var knowledge = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, indexKnowledge, assignmentKnowledge); // TODO : useless if indexAsExp is based on variables already in the partition (which space is delimited) //var indexRange = guessRange(pc, indexAsExp); //Log("LB={0}", indexRange.One); //Log("UB={0}", indexRange.Two); IPartitionAbstraction<BoxedVariable<Variable>, BoxedExpression> arrayPartition; var refinedDomain = data; if (data.TryGetValue(array, out arrayPartition)) { var singles = arrayPartition.Singles(); Log("SINGLES={0}",singles); var b = baseVariables.Remove(index); foreach (var single in singles) { if (!this.Decoder.IsConstant(single)) { var variablesInSingle = this.Decoder.VariablesIn(single); if (baseVariables.IsSubset(variablesInSingle)) { // The general case is very complicated. Here we assume that single has the form of an octagon contraint (+/- y + c) if (baseVariables.Count == 1) { var indexSubstitute = this.Encoder.Substitute(single, ToBoxedExpression(pc, baseVariables.PickAnElement()), indexAsExp); var notWanted = new Set<BoxedVariable<Variable>>(baseVariables); if (!indexSubstitute.IsVariable) // HACK due to handling of expression { notWanted.Add(this.Decoder.UnderlyingVariable(indexSubstitute)); } refinedDomain = refinedDomain.ArrayAssignment(array, indexSubstitute, knowledge, notWanted); } else // Otherwise we try to partition wrt indexAsExp { refinedDomain = refinedDomain.ArrayAssignment(array, indexAsExp, knowledge, baseVariables); } } } } } else { throw new AbstractInterpretationException(); } ALog.EndTransferFunction(StringClosure.For(data)); return refinedDomain; } #endregion #region MSILVisitor Members // TODO : useless public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldnull(APC pc, Variable dest, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { if (isOneDimensionalArray(pc, dest)) { return GenericArrayHandling(pc, dest, data); } return data; } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldind(APC pc, Type type, bool @volatile, Variable dest, Variable ptr, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { if (isOneDimensionalArray(pc, dest)) { return GenericArrayHandling(pc, dest, data); } return data; } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldarg(APC pc, Parameter argument, bool isOld, Variable dest, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { // TODO: what is isOld for ? if (isOneDimensionalArray(pc, dest)) { return GenericArrayHandling(pc, dest, data); } return data; } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldsfld(APC pc, Field field, bool @volatile, Variable dest, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { if (isOneDimensionalArray(pc, dest)) { return GenericArrayHandling(pc, dest, data); } return data; } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Ldfld(APC pc, Field field, bool @volatile, Variable dest, Variable obj, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { if (isOneDimensionalArray(pc, dest)) { return GenericArrayHandling(pc, dest, data); } return data; } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Castclass(APC pc, Type type, Variable dest, Variable obj, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { if (isOneDimensionalArray(pc, dest)) { return GenericArrayHandling(pc, dest, data); } return data; } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Call<TypeList, ArgList>(APC pc, Method method, bool tail, bool virt, TypeList extraVarargs, Variable dest, ArgList args, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { if (isOneDimensionalArray(pc, dest)) { var fullNameForMethod = this.DecoderForMetaData.FullName(method); Variable arrayLengthVar; if (fullNameForMethod.StartsWith("System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray")) { if (this.Context.TryGetArrayLength(this.Context.Post(pc), args[0], out arrayLengthVar)) { var arrayLengthExp = BoxedExpression.For(this.Context.Refine(pc, arrayLengthVar), this.Decoder.Outdecoder); arrayLengthExp = this.Decoder.Stripped(arrayLengthExp); int n; if (arrayLengthExp.IsConstantInt(out n)) { var refinedDomain = data; // var arrayAsExp = BoxedExpression.For(this.Context.Refine(pc, args[0]), this.Decoder.Outdecoder); var array = ToBoxedVariable(args[0]); var knowledge = this.Encoder.ConstantFor(true); for (int i = 0; i < n; i++) { //refinedDomain = HandleArrayAssignment("InitializeArray", pc, args[0], i, refinedDomain); refinedDomain = refinedDomain.ArrayAssignment(array, this.Encoder.ConstantFor(i), knowledge, new Set<BoxedVariable<Variable>>()); } return refinedDomain; } else { // TODO: probably nothing } } Debug.Assert(false, "ArrayLength of an array must be known"); } //if (isArray(pc, dest)) //{ return GenericArrayHandling(pc, dest, data); //} } return data; } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Isinst(APC pc, Type type, Variable dest, Variable obj, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { if (isOneDimensionalArray(pc, dest)) { return GenericArrayHandling(pc, dest, data); } return data; } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Unary(APC pc, UnaryOperator op, bool overflow, bool unsigned, Variable dest, Variable source, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { // TODO: case Neg and Not Log("Unary:{0}",op); return data; } private BoxedExpression RecursiveStripped(BoxedExpression exp) { while (exp.IsUnary) { exp = this.Decoder.Stripped(exp); } if (exp.IsBinary) { var left = RecursiveStripped(exp.BinaryLeft); var right = RecursiveStripped(exp.BinaryRight); BoxedExpression expStripped; if (TryRepackAssignment(exp.BinaryOp, left, right, out expStripped)) { return expStripped; } //else //{ //} } return exp; } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Binary(APC pc, BinaryOperator op, Variable dest, Variable s1, Variable s2, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { Log("Binary:{0}", op); if (OperatorExtensions.IsComparisonBinaryOperator(op)) { // TODO: if s1 or s2 includes an array term, partitioning must be done. return data; } else if (OperatorExtensions.IsBooleanBinaryOperator(op)) { // TODO: see above return data; } else { var destAsExp = ToBoxedExpression(pc, dest); var leftAsExp = ToBoxedExpressionWithConstantRefinement(pc, s1); var rightAsExp = ToBoxedExpressionWithConstantRefinement(pc, s2); ALog.BeginTransferFunction(StringClosure.For("Assign"), StringClosure.For("{0} := {1}({2}, {3})", ExpressionPrinter.ToStringClosure(destAsExp, this.Decoder), StringClosure.For(op), ExpressionPrinter.ToStringClosure(leftAsExp, this.Decoder), ExpressionPrinter.ToStringClosure(rightAsExp, this.Decoder)), PrettyPrintPC(pc), StringClosure.For(data)); // Hypothesis : if it is a reminder or division operation, we assume that the dividend is not zero var refinedDomain = data; BoxedExpression rightOfAssignment; Log("REPACK:{1} {0} {2}", op, s1, s2); if (TryRepackAssignment(op, leftAsExp, rightAsExp, out rightOfAssignment)) { var arraysToRefine = data.arraysWithPartitionDefinedOnASubsetExpressionOf(rightOfAssignment); if (!arraysToRefine.IsEmpty) { var assignmentKnowledge = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Equal, destAsExp, rightOfAssignment); var assignmentStrippedKnowledge = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.Equal, destAsExp, RecursiveStripped(rightOfAssignment)); assignmentKnowledge = this.Encoder.CompoundExpressionFor(ExpressionType.Bool, ExpressionOperator.And, assignmentKnowledge, assignmentStrippedKnowledge); //Log("KNOWLEDGEonREPACK:{0}", rightOfAssignment); foreach (var array in arraysToRefine) { refinedDomain = HandleIndexAssignment("", pc, array, ToBoxedVariable(dest), rightOfAssignment, assignmentKnowledge, refinedDomain); } } } //else //{ // throw new AbstractInterpretationException(); //TODO : leave the else. //} ALog.EndTransferFunction(StringClosure.For(refinedDomain)); return refinedDomain; } } #region Arrays /// <summary> /// /// </summary> private SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> GenericArrayHandling(APC pc, Variable array, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { Variable arrayLengthVar; if (this.Context.TryGetArrayLength(this.Context.Post(pc), array, out arrayLengthVar)) { // if a symbolic value is assigned twice, thanks to symbolic values semantics, its equivalent to nop. // So we keep the partition such as it is. if (!data.ContainsKey(ToBoxedVariable(array))) { return HandleAllocations(pc, array, arrayLengthVar, data); } return data; } Debug.Assert(false, "ArrayLength of an array must be known"); return data; } /// <summary> /// We allocate a new partition to the array /// </summary> public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Newarray<ArgList>(APC pc, Type type, Variable dest, ArgList lengths, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { if (lengths.Count == 1) { return HandleAllocations(pc, dest, lengths[0], data); } else { return data; // TODO multidimensional array } } public override SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> Stelem(APC pc, Type type, Variable array, Variable index, Variable value, SimplePartitionAbstractDomain<BoxedVariable<Variable>, BoxedExpression> data) { if (isOneDimensionalArray(pc, array)) { bool wasTop = data.IsTop; Log("STELEM={0}[{1}]", array, index); var result = HandleArrayAssignment("Stelem", pc, array, index, data); Debug.Assert(wasTop || !result.IsTop); return result; } return data; } #endregion #region Containers #endregion #region Iterators #endregion #endregion private void Log(string format, params object[] args) { if(this.Options.LogOptions.TracePartitionAnalysis) { Console.WriteLine(format, args); } } } } } } #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. using System.Threading.Tasks; using Xunit; namespace System.Threading.Channels.Tests { public class BoundedChannelTests : ChannelTestBase { protected override Channel<T> CreateChannel<T>() => Channel.CreateBounded<T>(new BoundedChannelOptions(1) { AllowSynchronousContinuations = AllowSynchronousContinuations }); protected override Channel<T> CreateFullChannel<T>() { var c = Channel.CreateBounded<T>(new BoundedChannelOptions(1) { AllowSynchronousContinuations = AllowSynchronousContinuations }); c.Writer.WriteAsync(default).AsTask().Wait(); return c; } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void TryWrite_TryRead_Many_Wait(int bufferedCapacity) { var c = Channel.CreateBounded<int>(bufferedCapacity); for (int i = 0; i < bufferedCapacity; i++) { Assert.True(c.Writer.TryWrite(i)); } Assert.False(c.Writer.TryWrite(bufferedCapacity)); int result; for (int i = 0; i < bufferedCapacity; i++) { Assert.True(c.Reader.TryRead(out result)); Assert.Equal(i, result); } Assert.False(c.Reader.TryRead(out result)); Assert.Equal(0, result); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void TryWrite_TryRead_Many_DropOldest(int bufferedCapacity) { var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropOldest }); for (int i = 0; i < bufferedCapacity * 2; i++) { Assert.True(c.Writer.TryWrite(i)); } int result; for (int i = bufferedCapacity; i < bufferedCapacity * 2; i++) { Assert.True(c.Reader.TryRead(out result)); Assert.Equal(i, result); } Assert.False(c.Reader.TryRead(out result)); Assert.Equal(0, result); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void WriteAsync_TryRead_Many_DropOldest(int bufferedCapacity) { var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropOldest }); for (int i = 0; i < bufferedCapacity * 2; i++) { AssertSynchronousSuccess(c.Writer.WriteAsync(i)); } int result; for (int i = bufferedCapacity; i < bufferedCapacity * 2; i++) { Assert.True(c.Reader.TryRead(out result)); Assert.Equal(i, result); } Assert.False(c.Reader.TryRead(out result)); Assert.Equal(0, result); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void TryWrite_TryRead_Many_DropNewest(int bufferedCapacity) { var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropNewest }); for (int i = 0; i < bufferedCapacity * 2; i++) { Assert.True(c.Writer.TryWrite(i)); } int result; for (int i = 0; i < bufferedCapacity - 1; i++) { Assert.True(c.Reader.TryRead(out result)); Assert.Equal(i, result); } Assert.True(c.Reader.TryRead(out result)); Assert.Equal(bufferedCapacity * 2 - 1, result); Assert.False(c.Reader.TryRead(out result)); Assert.Equal(0, result); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void WriteAsync_TryRead_Many_DropNewest(int bufferedCapacity) { var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropNewest }); for (int i = 0; i < bufferedCapacity * 2; i++) { AssertSynchronousSuccess(c.Writer.WriteAsync(i)); } int result; for (int i = 0; i < bufferedCapacity - 1; i++) { Assert.True(c.Reader.TryRead(out result)); Assert.Equal(i, result); } Assert.True(c.Reader.TryRead(out result)); Assert.Equal(bufferedCapacity * 2 - 1, result); Assert.False(c.Reader.TryRead(out result)); Assert.Equal(0, result); } [Fact] public async Task TryWrite_DropNewest_WrappedAroundInternalQueue() { var c = Channel.CreateBounded<int>(new BoundedChannelOptions(3) { FullMode = BoundedChannelFullMode.DropNewest }); // Move head of dequeue beyond the beginning Assert.True(c.Writer.TryWrite(1)); Assert.True(c.Reader.TryRead(out int item)); Assert.Equal(1, item); // Add items to fill the capacity and put the tail at 0 Assert.True(c.Writer.TryWrite(2)); Assert.True(c.Writer.TryWrite(3)); Assert.True(c.Writer.TryWrite(4)); // Add an item to overwrite the newest Assert.True(c.Writer.TryWrite(5)); // Verify current contents Assert.Equal(2, await c.Reader.ReadAsync()); Assert.Equal(3, await c.Reader.ReadAsync()); Assert.Equal(5, await c.Reader.ReadAsync()); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void TryWrite_TryRead_Many_Ignore(int bufferedCapacity) { var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropWrite }); for (int i = 0; i < bufferedCapacity * 2; i++) { Assert.True(c.Writer.TryWrite(i)); } int result; for (int i = 0; i < bufferedCapacity; i++) { Assert.True(c.Reader.TryRead(out result)); Assert.Equal(i, result); } Assert.False(c.Reader.TryRead(out result)); Assert.Equal(0, result); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void WriteAsync_TryRead_Many_Ignore(int bufferedCapacity) { var c = Channel.CreateBounded<int>(new BoundedChannelOptions(bufferedCapacity) { FullMode = BoundedChannelFullMode.DropWrite }); for (int i = 0; i < bufferedCapacity * 2; i++) { AssertSynchronousSuccess(c.Writer.WriteAsync(i)); } int result; for (int i = 0; i < bufferedCapacity; i++) { Assert.True(c.Reader.TryRead(out result)); Assert.Equal(i, result); } Assert.False(c.Reader.TryRead(out result)); Assert.Equal(0, result); } [Fact] public async Task CancelPendingWrite_Reading_DataTransferredFromCorrectWriter() { var c = Channel.CreateBounded<int>(1); Assert.True(c.Writer.WriteAsync(42).IsCompletedSuccessfully); var cts = new CancellationTokenSource(); Task write1 = c.Writer.WriteAsync(43, cts.Token).AsTask(); Assert.Equal(TaskStatus.WaitingForActivation, write1.Status); cts.Cancel(); Task write2 = c.Writer.WriteAsync(44).AsTask(); Assert.Equal(42, await c.Reader.ReadAsync()); Assert.Equal(44, await c.Reader.ReadAsync()); await AssertCanceled(write1, cts.Token); await write2; } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void TryWrite_TryRead_OneAtATime(int bufferedCapacity) { var c = Channel.CreateBounded<int>(bufferedCapacity); const int NumItems = 100000; for (int i = 0; i < NumItems; i++) { Assert.True(c.Writer.TryWrite(i)); Assert.True(c.Reader.TryRead(out int result)); Assert.Equal(i, result); } } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void SingleProducerConsumer_ConcurrentReadWrite_WithBufferedCapacity_Success(int bufferedCapacity) { var c = Channel.CreateBounded<int>(bufferedCapacity); const int NumItems = 10000; Task.WaitAll( Task.Run(async () => { for (int i = 0; i < NumItems; i++) { await c.Writer.WriteAsync(i); } }), Task.Run(async () => { for (int i = 0; i < NumItems; i++) { Assert.Equal(i, await c.Reader.ReadAsync()); } })); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(10000)] public void ManyProducerConsumer_ConcurrentReadWrite_WithBufferedCapacity_Success(int bufferedCapacity) { var c = Channel.CreateBounded<int>(bufferedCapacity); const int NumWriters = 10; const int NumReaders = 10; const int NumItems = 10000; long readTotal = 0; int remainingWriters = NumWriters; int remainingItems = NumItems; Task[] tasks = new Task[NumWriters + NumReaders]; for (int i = 0; i < NumReaders; i++) { tasks[i] = Task.Run(async () => { try { while (true) { Interlocked.Add(ref readTotal, await c.Reader.ReadAsync()); } } catch (ChannelClosedException) { } }); } for (int i = 0; i < NumWriters; i++) { tasks[NumReaders + i] = Task.Run(async () => { while (true) { int value = Interlocked.Decrement(ref remainingItems); if (value < 0) { break; } await c.Writer.WriteAsync(value + 1); } if (Interlocked.Decrement(ref remainingWriters) == 0) { c.Writer.Complete(); } }); } Task.WaitAll(tasks); Assert.Equal((NumItems * (NumItems + 1L)) / 2, readTotal); } [Fact] public async Task WaitToWriteAsync_AfterFullThenRead_ReturnsTrue() { var c = Channel.CreateBounded<int>(1); Assert.True(c.Writer.TryWrite(1)); Task<bool> write1 = c.Writer.WaitToWriteAsync().AsTask(); Assert.False(write1.IsCompleted); Task<bool> write2 = c.Writer.WaitToWriteAsync().AsTask(); Assert.False(write2.IsCompleted); Assert.Equal(1, await c.Reader.ReadAsync()); Assert.True(await write1); Assert.True(await write2); } [Theory] [InlineData(false)] [InlineData(true)] public void AllowSynchronousContinuations_WaitToReadAsync_ContinuationsInvokedAccordingToSetting(bool allowSynchronousContinuations) { var c = Channel.CreateBounded<int>(new BoundedChannelOptions(1) { AllowSynchronousContinuations = allowSynchronousContinuations }); int expectedId = Environment.CurrentManagedThreadId; Task r = c.Reader.WaitToReadAsync().AsTask().ContinueWith(_ => { Assert.Equal(allowSynchronousContinuations, expectedId == Environment.CurrentManagedThreadId); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); Assert.True(c.Writer.WriteAsync(42).IsCompletedSuccessfully); ((IAsyncResult)r).AsyncWaitHandle.WaitOne(); // avoid inlining the continuation r.GetAwaiter().GetResult(); } [Theory] [InlineData(false)] [InlineData(true)] public void AllowSynchronousContinuations_CompletionTask_ContinuationsInvokedAccordingToSetting(bool allowSynchronousContinuations) { var c = Channel.CreateBounded<int>(new BoundedChannelOptions(1) { AllowSynchronousContinuations = allowSynchronousContinuations }); int expectedId = Environment.CurrentManagedThreadId; Task r = c.Reader.Completion.ContinueWith(_ => { Assert.Equal(allowSynchronousContinuations, expectedId == Environment.CurrentManagedThreadId); }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); Assert.True(c.Writer.TryComplete()); ((IAsyncResult)r).AsyncWaitHandle.WaitOne(); // avoid inlining the continuation r.GetAwaiter().GetResult(); } [Fact] public async Task TryWrite_NoBlockedReaders_WaitingReader_WaiterNotified() { Channel<int> c = CreateChannel(); Task<bool> r = c.Reader.WaitToReadAsync().AsTask(); Assert.True(c.Writer.TryWrite(42)); Assert.True(await r); } } }
// 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. internal partial class Interop { internal partial class User32 { public const int COLOR_WINDOW = 5; public const int CTRL_LOGOFF_EVENT = 5; public const int CTRL_SHUTDOWN_EVENT = 6; public const int ENDSESSION_CLOSEAPP = 0x00000001; public const int ENDSESSION_CRITICAL = 0x40000000; public const int ENDSESSION_LOGOFF = unchecked((int)0x80000000); public const int GCL_WNDPROC = (-24); public const int GWL_WNDPROC = (-4); public const int MWMO_INPUTAVAILABLE = 0x0004; public const int PBT_APMQUERYSUSPEND = 0x0000; public const int PBT_APMQUERYSTANDBY = 0x0001; public const int PBT_APMQUERYSUSPENDFAILED = 0x0002; public const int PBT_APMQUERYSTANDBYFAILED = 0x0003; public const int PBT_APMSUSPEND = 0x0004; public const int PBT_APMSTANDBY = 0x0005; public const int PBT_APMRESUMECRITICAL = 0x0006; public const int PBT_APMRESUMESUSPEND = 0x0007; public const int PBT_APMRESUMESTANDBY = 0x0008; public const int PBT_APMBATTERYLOW = 0x0009; public const int PBT_APMPOWERSTATUSCHANGE = 0x000A; public const int PBT_APMOEMEVENT = 0x000B; public const int PM_REMOVE = 0x0001; public const int QS_KEY = 0x0001, QS_MOUSEMOVE = 0x0002, QS_MOUSEBUTTON = 0x0004, QS_POSTMESSAGE = 0x0008, QS_TIMER = 0x0010, QS_PAINT = 0x0020, QS_SENDMESSAGE = 0x0040, QS_HOTKEY = 0x0080, QS_ALLPOSTMESSAGE = 0x0100, QS_MOUSE = QS_MOUSEMOVE | QS_MOUSEBUTTON, QS_INPUT = QS_MOUSE | QS_KEY, QS_ALLEVENTS = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY, QS_ALLINPUT = QS_INPUT | QS_POSTMESSAGE | QS_TIMER | QS_PAINT | QS_HOTKEY | QS_SENDMESSAGE; public const int SPI_GETBEEP = 1; public const int SPI_SETBEEP = 2; public const int SPI_GETMOUSE = 3; public const int SPI_SETMOUSE = 4; public const int SPI_GETBORDER = 5; public const int SPI_SETBORDER = 6; public const int SPI_GETKEYBOARDSPEED = 10; public const int SPI_SETKEYBOARDSPEED = 11; public const int SPI_LANGDRIVER = 12; public const int SPI_ICONHORIZONTALSPACING = 13; public const int SPI_GETSCREENSAVETIMEOUT = 14; public const int SPI_SETSCREENSAVETIMEOUT = 15; public const int SPI_GETSCREENSAVEACTIVE = 16; public const int SPI_SETSCREENSAVEACTIVE = 17; public const int SPI_GETGRIDGRANULARITY = 18; public const int SPI_SETGRIDGRANULARITY = 19; public const int SPI_SETDESKWALLPAPER = 20; public const int SPI_SETDESKPATTERN = 21; public const int SPI_GETKEYBOARDDELAY = 22; public const int SPI_SETKEYBOARDDELAY = 23; public const int SPI_ICONVERTICALSPACING = 24; public const int SPI_GETICONTITLEWRAP = 25; public const int SPI_SETICONTITLEWRAP = 26; public const int SPI_GETMENUDROPALIGNMENT = 27; public const int SPI_SETMENUDROPALIGNMENT = 28; public const int SPI_SETDOUBLECLKWIDTH = 29; public const int SPI_SETDOUBLECLKHEIGHT = 30; public const int SPI_GETICONTITLELOGFONT = 31; public const int SPI_SETDOUBLECLICKTIME = 32; public const int SPI_SETMOUSEBUTTONSWAP = 33; public const int SPI_SETICONTITLELOGFONT = 34; public const int SPI_GETFASTTASKSWITCH = 35; public const int SPI_SETFASTTASKSWITCH = 36; public const int SPI_SETDRAGFULLWINDOWS = 37; public const int SPI_GETDRAGFULLWINDOWS = 38; public const int SPI_GETNONCLIENTMETRICS = 41; public const int SPI_SETNONCLIENTMETRICS = 42; public const int SPI_GETMINIMIZEDMETRICS = 43; public const int SPI_SETMINIMIZEDMETRICS = 44; public const int SPI_GETICONMETRICS = 45; public const int SPI_SETICONMETRICS = 46; public const int SPI_SETWORKAREA = 47; public const int SPI_GETWORKAREA = 48; public const int SPI_SETPENWINDOWS = 49; public const int SPI_GETHIGHCONTRAST = 66; public const int SPI_SETHIGHCONTRAST = 67; public const int SPI_GETKEYBOARDPREF = 68; public const int SPI_SETKEYBOARDPREF = 69; public const int SPI_GETSCREENREADER = 70; public const int SPI_SETSCREENREADER = 71; public const int SPI_GETANIMATION = 72; public const int SPI_SETANIMATION = 73; public const int SPI_GETFONTSMOOTHING = 74; public const int SPI_SETFONTSMOOTHING = 75; public const int SPI_SETDRAGWIDTH = 76; public const int SPI_SETDRAGHEIGHT = 77; public const int SPI_SETHANDHELD = 78; public const int SPI_GETLOWPOWERTIMEOUT = 79; public const int SPI_GETPOWEROFFTIMEOUT = 80; public const int SPI_SETLOWPOWERTIMEOUT = 81; public const int SPI_SETPOWEROFFTIMEOUT = 82; public const int SPI_GETLOWPOWERACTIVE = 83; public const int SPI_GETPOWEROFFACTIVE = 84; public const int SPI_SETLOWPOWERACTIVE = 85; public const int SPI_SETPOWEROFFACTIVE = 86; public const int SPI_SETCURSORS = 87; public const int SPI_SETICONS = 88; public const int SPI_GETDEFAULTINPUTLANG = 89; public const int SPI_SETDEFAULTINPUTLANG = 90; public const int SPI_SETLANGTOGGLE = 91; public const int SPI_GETWINDOWSEXTENSION = 92; public const int SPI_SETMOUSETRAILS = 93; public const int SPI_GETMOUSETRAILS = 94; public const int SPI_SETSCREENSAVERRUNNING = 97; public const int SPI_SCREENSAVERRUNNING = SPI_SETSCREENSAVERRUNNING; public const int SPI_GETFILTERKEYS = 50; public const int SPI_SETFILTERKEYS = 51; public const int SPI_GETTOGGLEKEYS = 52; public const int SPI_SETTOGGLEKEYS = 53; public const int SPI_GETMOUSEKEYS = 54; public const int SPI_SETMOUSEKEYS = 55; public const int SPI_GETSHOWSOUNDS = 56; public const int SPI_SETSHOWSOUNDS = 57; public const int SPI_GETSTICKYKEYS = 58; public const int SPI_SETSTICKYKEYS = 59; public const int SPI_GETACCESSTIMEOUT = 60; public const int SPI_SETACCESSTIMEOUT = 61; public const int SPI_GETSERIALKEYS = 62; public const int SPI_SETSERIALKEYS = 63; public const int SPI_GETSOUNDSENTRY = 64; public const int SPI_SETSOUNDSENTRY = 65; public const int SPI_GETSNAPTODEFBUTTON = 95; public const int SPI_SETSNAPTODEFBUTTON = 96; public const int SPI_GETMOUSEHOVERWIDTH = 98; public const int SPI_SETMOUSEHOVERWIDTH = 99; public const int SPI_GETMOUSEHOVERHEIGHT = 100; public const int SPI_SETMOUSEHOVERHEIGHT = 101; public const int SPI_GETMOUSEHOVERTIME = 102; public const int SPI_SETMOUSEHOVERTIME = 103; public const int SPI_GETWHEELSCROLLLINES = 104; public const int SPI_SETWHEELSCROLLLINES = 105; public const int SPI_GETMENUSHOWDELAY = 106; public const int SPI_SETMENUSHOWDELAY = 107; public const int SPI_GETSHOWIMEUI = 110; public const int SPI_SETSHOWIMEUI = 111; public const int SPI_GETMOUSESPEED = 112; public const int SPI_SETMOUSESPEED = 113; public const int SPI_GETSCREENSAVERRUNNING = 114; public const int SPI_GETDESKWALLPAPER = 115; public const int SPI_GETACTIVEWINDOWTRACKING = 0x1000; public const int SPI_SETACTIVEWINDOWTRACKING = 0x1001; public const int SPI_GETMENUANIMATION = 0x1002; public const int SPI_SETMENUANIMATION = 0x1003; public const int SPI_GETCOMBOBOXANIMATION = 0x1004; public const int SPI_SETCOMBOBOXANIMATION = 0x1005; public const int SPI_GETLISTBOXSMOOTHSCROLLING = 0x1006; public const int SPI_SETLISTBOXSMOOTHSCROLLING = 0x1007; public const int SPI_GETGRADIENTCAPTIONS = 0x1008; public const int SPI_SETGRADIENTCAPTIONS = 0x1009; public const int SPI_GETKEYBOARDCUES = 0x100A; public const int SPI_SETKEYBOARDCUES = 0x100B; public const int SPI_GETMENUUNDERLINES = SPI_GETKEYBOARDCUES; public const int SPI_SETMENUUNDERLINES = SPI_SETKEYBOARDCUES; public const int SPI_GETACTIVEWNDTRKZORDER = 0x100C; public const int SPI_SETACTIVEWNDTRKZORDER = 0x100D; public const int SPI_GETHOTTRACKING = 0x100E; public const int SPI_SETHOTTRACKING = 0x100F; public const int SPI_GETMENUFADE = 0x1012; public const int SPI_SETMENUFADE = 0x1013; public const int SPI_GETSELECTIONFADE = 0x1014; public const int SPI_SETSELECTIONFADE = 0x1015; public const int SPI_GETTOOLTIPANIMATION = 0x1016; public const int SPI_SETTOOLTIPANIMATION = 0x1017; public const int SPI_GETTOOLTIPFADE = 0x1018; public const int SPI_SETTOOLTIPFADE = 0x1019; public const int SPI_GETCURSORSHADOW = 0x101A; public const int SPI_SETCURSORSHADOW = 0x101B; public const int SPI_GETUIEFFECTS = 0x103E; public const int SPI_SETUIEFFECTS = 0x103F; public const int SPI_GETFOREGROUNDLOCKTIMEOUT = 0x2000; public const int SPI_SETFOREGROUNDLOCKTIMEOUT = 0x2001; public const int SPI_GETACTIVEWNDTRKTIMEOUT = 0x2002; public const int SPI_SETACTIVEWNDTRKTIMEOUT = 0x2003; public const int SPI_GETFOREGROUNDFLASHCOUNT = 0x2004; public const int SPI_SETFOREGROUNDFLASHCOUNT = 0x2005; public const int SPI_GETCARETWIDTH = 0x2006; public const int SPI_SETCARETWIDTH = 0x2007; public const int WAIT_TIMEOUT = 0x00000102; public const int WM_CLOSE = 0x0010; public const int WM_QUERYENDSESSION = 0x0011; public const int WM_QUIT = 0x0012; public const int WM_SYSCOLORCHANGE = 0x0015; public const int WM_ENDSESSION = 0x0016; public const int WM_SETTINGCHANGE = 0x001A; public const int WM_FONTCHANGE = 0x001D; public const int WM_TIMECHANGE = 0x001E; public const int WM_COMPACTING = 0x0041; public const int WM_DISPLAYCHANGE = 0x007E; public const int WM_TIMER = 0x0113; public const int WM_POWERBROADCAST = 0x0218; public const int WM_WTSSESSION_CHANGE = 0x02B1; public const int WM_PALETTECHANGED = 0x0311; public const int WM_THEMECHANGED = 0x031A; public const int WM_USER = 0x0400; public const int WM_CREATETIMER = WM_USER + 1; public const int WM_KILLTIMER = WM_USER + 2; public const int WM_REFLECT = WM_USER + 0x1C00; public const int WS_POPUP = unchecked((int)0x80000000); public const int WSF_VISIBLE = 0x0001; public const int UOI_FLAGS = 1; } }
/* Copyright 2015 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ namespace Org.Brotli.Dec { /// <summary> /// <see cref="System.IO.Stream"/> /// decorator that decompresses brotli data. /// <p> Not thread-safe. /// </summary> public class BrotliInputStream : System.IO.Stream { public const int DefaultInternalBufferSize = 16384; /// <summary>Internal buffer used for efficient byte-by-byte reading.</summary> private byte[] buffer; /// <summary>Number of decoded but still unused bytes in internal buffer.</summary> private int remainingBufferBytes; /// <summary>Next unused byte offset.</summary> private int bufferOffset; /// <summary>Decoder state.</summary> private readonly Org.Brotli.Dec.State state = new Org.Brotli.Dec.State(); /// <summary> /// Creates a /// <see cref="System.IO.Stream"/> /// wrapper that decompresses brotli data. /// <p> For byte-by-byte reading ( /// <see cref="ReadByte()"/> /// ) internal buffer with /// <see cref="DefaultInternalBufferSize"/> /// size is allocated and used. /// <p> Will block the thread until first kilobyte of data of source is available. /// </summary> /// <param name="source">underlying data source</param> /// <exception cref="System.IO.IOException">in case of corrupted data or source stream problems</exception> public BrotliInputStream(System.IO.Stream source) : this(source, DefaultInternalBufferSize, null) { } /// <summary> /// Creates a /// <see cref="System.IO.Stream"/> /// wrapper that decompresses brotli data. /// <p> For byte-by-byte reading ( /// <see cref="ReadByte()"/> /// ) internal buffer of specified size is /// allocated and used. /// <p> Will block the thread until first kilobyte of data of source is available. /// </summary> /// <param name="source">compressed data source</param> /// <param name="byteReadBufferSize"> /// size of internal buffer used in case of /// byte-by-byte reading /// </param> /// <exception cref="System.IO.IOException">in case of corrupted data or source stream problems</exception> public BrotliInputStream(System.IO.Stream source, int byteReadBufferSize) : this(source, byteReadBufferSize, null) { } /// <summary> /// Creates a /// <see cref="System.IO.Stream"/> /// wrapper that decompresses brotli data. /// <p> For byte-by-byte reading ( /// <see cref="ReadByte()"/> /// ) internal buffer of specified size is /// allocated and used. /// <p> Will block the thread until first kilobyte of data of source is available. /// </summary> /// <param name="source">compressed data source</param> /// <param name="byteReadBufferSize"> /// size of internal buffer used in case of /// byte-by-byte reading /// </param> /// <param name="customDictionary"> /// custom dictionary data; /// <see langword="null"/> /// if not used /// </param> /// <exception cref="System.IO.IOException">in case of corrupted data or source stream problems</exception> public BrotliInputStream(System.IO.Stream source, int byteReadBufferSize, byte[] customDictionary) { if (byteReadBufferSize <= 0) { throw new System.ArgumentException("Bad buffer size:" + byteReadBufferSize); } else if (source == null) { throw new System.ArgumentException("source is null"); } this.buffer = new byte[byteReadBufferSize]; this.remainingBufferBytes = 0; this.bufferOffset = 0; try { Org.Brotli.Dec.State.SetInput(state, source); } catch (Org.Brotli.Dec.BrotliRuntimeException ex) { throw new System.IO.IOException("Brotli decoder initialization failed", ex); } if (customDictionary != null) { Org.Brotli.Dec.Decode.SetCustomDictionary(state, customDictionary); } } /// <summary><inheritDoc/></summary> /// <exception cref="System.IO.IOException"/> public override void Close() { Org.Brotli.Dec.State.Close(state); } /// <summary><inheritDoc/></summary> /// <exception cref="System.IO.IOException"/> public override int ReadByte() { if (bufferOffset >= remainingBufferBytes) { remainingBufferBytes = Read(buffer, 0, buffer.Length); bufferOffset = 0; if (remainingBufferBytes == -1) { return -1; } } return buffer[bufferOffset++] & unchecked((int)(0xFF)); } /// <summary><inheritDoc/></summary> /// <exception cref="System.IO.IOException"/> public override int Read(byte[] destBuffer, int destOffset, int destLen) { if (destOffset < 0) { throw new System.ArgumentException("Bad offset: " + destOffset); } else if (destLen < 0) { throw new System.ArgumentException("Bad length: " + destLen); } else if (destOffset + destLen > destBuffer.Length) { throw new System.ArgumentException("Buffer overflow: " + (destOffset + destLen) + " > " + destBuffer.Length); } else if (destLen == 0) { return 0; } int copyLen = System.Math.Max(remainingBufferBytes - bufferOffset, 0); if (copyLen != 0) { copyLen = System.Math.Min(copyLen, destLen); System.Array.Copy(buffer, bufferOffset, destBuffer, destOffset, copyLen); bufferOffset += copyLen; destOffset += copyLen; destLen -= copyLen; if (destLen == 0) { return copyLen; } } try { state.output = destBuffer; state.outputOffset = destOffset; state.outputLength = destLen; state.outputUsed = 0; Org.Brotli.Dec.Decode.Decompress(state); if (state.outputUsed == 0) { return 0; } return state.outputUsed + copyLen; } catch (Org.Brotli.Dec.BrotliRuntimeException ex) { throw new System.IO.IOException("Brotli stream decoding failed", ex); } } // <{[INJECTED CODE]}> public override bool CanRead { get {return true;} } public override bool CanSeek { get {return false;} } public override long Length { get {throw new System.NotSupportedException();} } public override long Position { get {throw new System.NotSupportedException();} set {throw new System.NotSupportedException();} } public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new System.NotSupportedException(); } public override void SetLength(long value){ throw new System.NotSupportedException(); } public override bool CanWrite{get{return false;}} public override System.IAsyncResult BeginWrite(byte[] buffer, int offset, int count, System.AsyncCallback callback, object state) { throw new System.NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new System.NotSupportedException(); } public override void Flush() {} } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; using System.Diagnostics.CodeAnalysis; namespace Microsoft.PowerShell.Commands { /// <summary> /// The implementation of the "get-alias" cmdlet /// </summary> /// [Cmdlet(VerbsCommon.Get, "Alias", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113306")] [OutputType(typeof(AliasInfo))] public class GetAliasCommand : PSCmdlet { #region Parameters /// <summary> /// The Name parameter for the command /// </summary> /// [Parameter(ParameterSetName = "Default", Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] public string[] Name { get { return _names; } set { _names = value ?? new string[] { "*" }; } } private string[] _names = new string[] { "*" }; /// <summary> /// The Exclude parameter for the command /// </summary> /// [Parameter] public string[] Exclude { get { return _excludes; } set { _excludes = value ?? new string[0]; } } private string[] _excludes = new string[0]; /// <summary> /// The scope parameter for the command determines /// which scope the aliases are retrieved from. /// </summary> /// [Parameter] public string Scope { get; set; } /// <summary> /// Parameter definition to retrieve aliases based on their definitions. /// </summary> [Parameter(ParameterSetName = "Definition")] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public String[] Definition { get; set; } #endregion Parameters #region Command code /// <summary> /// The main processing loop of the command. /// </summary> /// protected override void ProcessRecord() { if (ParameterSetName.Equals("Definition")) { foreach (string defn in Definition) { WriteMatches(defn, "Definition"); } } else { foreach (string aliasName in _names) { WriteMatches(aliasName, "Default"); } }//parameterset else } // ProcessRecord #endregion Command code private void WriteMatches(string value, string parametersetname) { // First get the alias table (from the proper scope if necessary) IDictionary<string, AliasInfo> aliasTable = null; //get the command origin CommandOrigin origin = MyInvocation.CommandOrigin; string displayString = "name"; if (!String.IsNullOrEmpty(Scope)) { // This can throw PSArgumentException and PSArgumentOutOfRangeException // but just let them go as this is terminal for the pipeline and the // exceptions are already properly adorned with an ErrorRecord. aliasTable = SessionState.Internal.GetAliasTableAtScope(Scope); } else { aliasTable = SessionState.Internal.GetAliasTable(); } bool matchfound = false; bool ContainsWildcard = WildcardPattern.ContainsWildcardCharacters(value); WildcardPattern wcPattern = WildcardPattern.Get(value, WildcardOptions.IgnoreCase); // excluding patter for Default paramset. Collection<WildcardPattern> excludePatterns = SessionStateUtilities.CreateWildcardsFromStrings( _excludes, WildcardOptions.IgnoreCase); List<AliasInfo> results = new List<AliasInfo>(); foreach (KeyValuePair<string, AliasInfo> tableEntry in aliasTable) { if (parametersetname.Equals("Definition", StringComparison.OrdinalIgnoreCase)) { displayString = "definition"; if (!wcPattern.IsMatch(tableEntry.Value.Definition)) { continue; } if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Value.Definition, excludePatterns, false)) { continue; } } else { if (!wcPattern.IsMatch(tableEntry.Key)) { continue; } //excludes pattern if (SessionStateUtilities.MatchesAnyWildcardPattern(tableEntry.Key, excludePatterns, false)) { continue; } } if (ContainsWildcard) { // Only write the command if it is visible to the requestor if (SessionState.IsVisible(origin, tableEntry.Value)) { matchfound = true; results.Add(tableEntry.Value); } } else { // For specifically named elements, generate an error for elements that aren't visible... try { SessionState.ThrowIfNotVisible(origin, tableEntry.Value); results.Add(tableEntry.Value); matchfound = true; } catch (SessionStateException sessionStateException) { WriteError( new ErrorRecord( sessionStateException.ErrorRecord, sessionStateException)); // Even though it resulted in an error, a result was found // so we don't want to generate the nothing found error // at the end... matchfound = true; continue; } } } results.Sort( delegate (AliasInfo left, AliasInfo right) { return StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name); }); foreach (AliasInfo alias in results) { this.WriteObject(alias); } if (!matchfound && !ContainsWildcard && (excludePatterns == null || excludePatterns.Count == 0)) { // Need to write an error if the user tries to get an alias // tat doesn't exist and they are not globbing. ItemNotFoundException itemNotFound = new ItemNotFoundException(StringUtil.Format(AliasCommandStrings.NoAliasFound, displayString, value)); ErrorRecord er = new ErrorRecord(itemNotFound, "ItemNotFoundException", ErrorCategory.ObjectNotFound, value); WriteError(er); } } } // class GetAliasCommand }//Microsoft.PowerShell.Commands