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.
// #define StressTest // set to raise the amount of time spent in concurrency tests that stress the collections
using System;
using System.Collections.Generic;
using System.Collections.Tests;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
public abstract class ProducerConsumerCollectionTests : IEnumerable_Generic_Tests<int>
{
protected override IEnumerable<ModifyEnumerable> ModifyEnumerables => new List<ModifyEnumerable>();
protected override int CreateT(int seed) => new Random(seed).Next();
protected override EnumerableOrder Order => EnumerableOrder.Unspecified;
protected override IEnumerable<int> GenericIEnumerableFactory(int count) => CreateProducerConsumerCollection(count);
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection() => CreateProducerConsumerCollection<int>();
protected IProducerConsumerCollection<int> CreateProducerConsumerCollection(int count) => CreateProducerConsumerCollection(Enumerable.Range(0, count));
protected abstract IProducerConsumerCollection<T> CreateProducerConsumerCollection<T>();
protected abstract IProducerConsumerCollection<int> CreateProducerConsumerCollection(IEnumerable<int> collection);
protected abstract bool IsEmpty(IProducerConsumerCollection<int> pcc);
protected abstract bool TryPeek<T>(IProducerConsumerCollection<T> pcc, out T result);
protected virtual IProducerConsumerCollection<int> CreateOracle() => CreateOracle(Enumerable.Empty<int>());
protected abstract IProducerConsumerCollection<int> CreateOracle(IEnumerable<int> collection);
protected static TaskFactory ThreadFactory { get; } = new TaskFactory(
CancellationToken.None, TaskCreationOptions.LongRunning, TaskContinuationOptions.LongRunning, TaskScheduler.Default);
private const double ConcurrencyTestSeconds =
#if StressTest
8.0;
#else
1.0;
#endif
[Fact]
public void Ctor_InvalidArgs_Throws()
{
AssertExtensions.Throws<ArgumentNullException>("collection", () => CreateProducerConsumerCollection(null));
}
[Fact]
public void Ctor_NoArg_ItemsAndCountMatch()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Equal(0, c.Count);
Assert.True(IsEmpty(c));
Assert.Equal(Enumerable.Empty<int>(), c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void Ctor_Collection_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, count));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(1, count));
Assert.Equal(oracle.Count == 0, IsEmpty(c));
Assert.Equal(oracle.Count, c.Count);
Assert.Equal<int>(oracle, c);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(3)]
[InlineData(1000)]
public void Ctor_InitializeFromCollection_ContainsExpectedItems(int numItems)
{
var expected = new HashSet<int>(Enumerable.Range(0, numItems));
IProducerConsumerCollection<int> pcc = CreateProducerConsumerCollection(expected);
Assert.Equal(expected.Count, pcc.Count);
int item;
var actual = new HashSet<int>();
for (int i = 0; i < expected.Count; i++)
{
Assert.Equal(expected.Count - i, pcc.Count);
Assert.True(pcc.TryTake(out item));
actual.Add(item);
}
Assert.False(pcc.TryTake(out item));
Assert.Equal(0, item);
AssertSetsEqual(expected, actual);
}
[Fact]
public void Add_TakeFromAnotherThread_ExpectedItemsTaken()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
const int NumItems = 100000;
Task producer = Task.Run(() => Parallel.For(1, NumItems + 1, i => Assert.True(c.TryAdd(i))));
var hs = new HashSet<int>();
while (hs.Count < NumItems)
{
int item;
if (c.TryTake(out item)) hs.Add(item);
}
producer.GetAwaiter().GetResult();
Assert.True(IsEmpty(c));
Assert.Equal(0, c.Count);
AssertSetsEqual(new HashSet<int>(Enumerable.Range(1, NumItems)), hs);
}
[Fact]
public void AddSome_ThenInterleaveAddsAndTakes_MatchesOracle()
{
IProducerConsumerCollection<int> c = CreateOracle();
IProducerConsumerCollection<int> oracle = CreateProducerConsumerCollection();
Action take = () =>
{
int item1;
Assert.True(c.TryTake(out item1));
int item2;
Assert.True(oracle.TryTake(out item2));
Assert.Equal(item1, item2);
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
};
for (int i = 0; i < 100; i++)
{
Assert.True(oracle.TryAdd(i));
Assert.True(c.TryAdd(i));
Assert.Equal(c.Count, oracle.Count);
Assert.Equal<int>(c, oracle);
// Start taking some after we've added some
if (i > 50)
{
take();
}
}
// Take the rest
while (c.Count > 0)
{
take();
}
}
[Fact]
public void AddTake_RandomChangesMatchOracle()
{
const int Iters = 1000;
var r = new Random(42);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Iters; i++)
{
if (r.NextDouble() < .5)
{
Assert.Equal(oracle.TryAdd(i), c.TryAdd(i));
}
else
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
Assert.Equal(oracle.Count, c.Count);
}
[Theory]
[InlineData(100, 1, 100, true)]
[InlineData(100, 4, 10, false)]
[InlineData(1000, 11, 100, true)]
[InlineData(100000, 2, 50000, true)]
public void Initialize_ThenTakeOrPeekInParallel_ItemsObtainedAsExpected(int numStartingItems, int threadsCount, int itemsPerThread, bool take)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, numStartingItems));
int successes = 0;
using (var b = new Barrier(threadsCount))
{
WaitAllOrAnyFailed(Enumerable.Range(0, threadsCount).Select(threadNum => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
for (int j = 0; j < itemsPerThread; j++)
{
int data;
if (take ? c.TryTake(out data) : TryPeek(c, out data))
{
Interlocked.Increment(ref successes);
Assert.NotEqual(0, data); // shouldn't be default(T)
}
}
})).ToArray());
}
Assert.Equal(
take ? numStartingItems : threadsCount * itemsPerThread,
successes);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(1000)]
public void ToArray_AddAllItemsThenEnumerate_ItemsAndCountMatch(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < count; i++)
{
Assert.Equal(oracle.TryAdd(i + count), c.TryAdd(i + count));
}
Assert.Equal(oracle.ToArray(), c.ToArray());
if (count > 0)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Theory]
[InlineData(1, 10)]
[InlineData(2, 10)]
[InlineData(10, 10)]
[InlineData(100, 10)]
public void ToArray_AddAndTakeItemsIntermixedWithEnumeration_ItemsAndCountMatch(int initialCount, int iters)
{
IEnumerable<int> initialItems = Enumerable.Range(1, initialCount);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
for (int i = 0; i < iters; i++)
{
Assert.Equal<int>(oracle, c);
Assert.Equal(oracle.TryAdd(initialCount + i), c.TryAdd(initialCount + i));
Assert.Equal<int>(oracle, c);
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal<int>(oracle, c);
}
}
[Fact]
public void AddFromMultipleThreads_ItemsRemainAfterThreadsGoAway()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
for (int i = 0; i < 1000; i += 100)
{
// Create a thread that adds items to the collection
ThreadFactory.StartNew(() =>
{
for (int j = i; j < i + 100; j++)
{
Assert.True(c.TryAdd(j));
}
}).GetAwaiter().GetResult();
// Allow threads to be collected
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
AssertSetsEqual(new HashSet<int>(Enumerable.Range(0, 1000)), new HashSet<int>(c));
}
[Fact]
public void AddManyItems_ThenTakeOnSameThread_ItemsOutputInExpectedOrder()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 100000));
IProducerConsumerCollection<int> oracle = CreateOracle(Enumerable.Range(0, 100000));
for (int i = 99999; i >= 0; --i)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
}
}
[Fact]
public void TryPeek_SucceedsOnEmptyCollectionThatWasOnceNonEmpty()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
int item;
for (int i = 0; i < 2; i++)
{
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
}
Assert.True(c.TryAdd(42));
for (int i = 0; i < 2; i++)
{
Assert.True(TryPeek(c, out item));
Assert.Equal(42, item);
}
Assert.True(c.TryTake(out item));
Assert.Equal(42, item);
Assert.False(TryPeek(c, out item));
Assert.Equal(0, item);
Assert.False(c.TryTake(out item));
Assert.Equal(0, item);
}
[Fact]
public void AddTakeWithAtLeastOneElementInCollection_IsEmpty_AlwaysFalse()
{
int items = 1000;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(0)); // make sure it's never empty
var cts = new CancellationTokenSource();
// Consumer repeatedly calls IsEmpty until it's told to stop
Task consumer = Task.Run(() =>
{
while (!cts.IsCancellationRequested) Assert.False(IsEmpty(c));
});
// Producer adds/takes a bunch of items, then tells the consumer to stop
Task producer = Task.Run(() =>
{
int ignored;
for (int i = 1; i <= items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(c.TryTake(out ignored));
}
cts.Cancel();
});
Task.WaitAll(producer, consumer);
}
[Fact]
public void CopyTo_Empty_NothingCopied()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
c.CopyTo(new int[0], 0);
c.CopyTo(new int[10], 10);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size];
c.CopyTo(actual, 0);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size];
oracle.CopyTo(expected, 0);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_SzArray_NonZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(initialItems);
int[] actual = new int[size + 2];
c.CopyTo(actual, 1);
IProducerConsumerCollection<int> oracle = CreateOracle(initialItems);
int[] expected = new int[size + 2];
oracle.CopyTo(expected, 1);
Assert.Equal(expected, actual);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(100)]
public void CopyTo_ArrayZeroLowerBound_ZeroIndex_ExpectedElementsCopied(int size)
{
IEnumerable<int> initialItems = Enumerable.Range(1, size);
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
c.CopyTo(actual, 0);
ICollection oracle = CreateOracle(initialItems);
Array expected = Array.CreateInstance(typeof(int), new int[] { size }, new int[] { 0 });
oracle.CopyTo(expected, 0);
Assert.Equal(expected.Cast<int>(), actual.Cast<int>());
}
[Fact]
public void CopyTo_ArrayNonZeroLowerBound_ExpectedElementsCopied()
{
if (!PlatformDetection.IsNonZeroLowerBoundArraySupported)
return;
int[] initialItems = Enumerable.Range(1, 10).ToArray();
const int LowerBound = 1;
ICollection c = CreateProducerConsumerCollection(initialItems);
Array actual = Array.CreateInstance(typeof(int), new int[] { initialItems.Length }, new int[] { LowerBound });
c.CopyTo(actual, LowerBound);
ICollection oracle = CreateOracle(initialItems);
int[] expected = new int[initialItems.Length];
oracle.CopyTo(expected, 0);
for (int i = 0; i < expected.Length; i++)
{
Assert.Equal(expected[i], actual.GetValue(i + LowerBound));
}
}
[Fact]
public void CopyTo_InvalidArgs_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
int[] dest = new int[10];
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length - 2));
Assert.Throws<ArgumentException>(() => c.CopyTo(new int[7, 7], 0));
}
[Fact]
public void ICollectionCopyTo_InvalidArgs_Throws()
{
ICollection c = CreateProducerConsumerCollection(Enumerable.Range(0, 10));
Array dest = new int[10];
AssertExtensions.Throws<ArgumentNullException>("array", () => c.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => c.CopyTo(dest, -1));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length));
Assert.Throws<ArgumentException>(() => c.CopyTo(dest, dest.Length - 2));
}
[Theory]
[InlineData(100, 1, 10)]
[InlineData(4, 100000, 10)]
public void BlockingCollection_WrappingCollection_ExpectedElementsTransferred(int numThreadsPerConsumerProducer, int numItemsPerThread, int producerSpin)
{
var bc = new BlockingCollection<int>(CreateProducerConsumerCollection());
long dummy = 0;
Task[] producers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 1; i <= numItemsPerThread; i++)
{
for (int j = 0; j < producerSpin; j++) dummy *= j; // spin a little
bc.Add(i);
}
})).ToArray();
Task[] consumers = Enumerable.Range(0, numThreadsPerConsumerProducer).Select(_ => ThreadFactory.StartNew(() =>
{
for (int i = 0; i < numItemsPerThread; i++)
{
const int TimeoutMs = 100000;
int item;
Assert.True(bc.TryTake(out item, TimeoutMs), $"Couldn't get {i}th item after {TimeoutMs}ms");
Assert.NotEqual(0, item);
}
})).ToArray();
WaitAllOrAnyFailed(producers);
WaitAllOrAnyFailed(consumers);
}
[Fact]
public void GetEnumerator_NonGeneric()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IEnumerable e = c;
Assert.False(e.GetEnumerator().MoveNext());
Assert.True(c.TryAdd(42));
Assert.True(c.TryAdd(84));
var hs = new HashSet<int>(e.Cast<int>());
Assert.Equal(2, hs.Count);
Assert.Contains(42, hs);
Assert.Contains(84, hs);
}
[Fact]
public void GetEnumerator_EnumerationsAreSnapshots()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c);
using (IEnumerator<int> e1 = c.GetEnumerator())
{
Assert.True(c.TryAdd(1));
using (IEnumerator<int> e2 = c.GetEnumerator())
{
Assert.True(c.TryAdd(2));
using (IEnumerator<int> e3 = c.GetEnumerator())
{
int item;
Assert.True(c.TryTake(out item));
using (IEnumerator<int> e4 = c.GetEnumerator())
{
Assert.False(e1.MoveNext());
Assert.True(e2.MoveNext());
Assert.False(e2.MoveNext());
Assert.True(e3.MoveNext());
Assert.True(e3.MoveNext());
Assert.False(e3.MoveNext());
Assert.True(e4.MoveNext());
Assert.False(e4.MoveNext());
}
}
}
}
}
[Theory]
[InlineData(0, true)]
[InlineData(1, true)]
[InlineData(1, false)]
[InlineData(10, true)]
[InlineData(100, true)]
[InlineData(100, false)]
public async Task GetEnumerator_Generic_ExpectedElementsYielded(int numItems, bool consumeFromSameThread)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
using (var e = c.GetEnumerator())
{
Assert.False(e.MoveNext());
}
// Add, and validate enumeration after each item added
for (int i = 1; i <= numItems; i++)
{
Assert.True(c.TryAdd(i));
Assert.Equal(i, c.Count);
Assert.Equal(i, c.Distinct().Count());
}
// Take, and validate enumerate after each item removed.
Action consume = () =>
{
for (int i = 1; i <= numItems; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.Equal(numItems - i, c.Count);
Assert.Equal(numItems - i, c.Distinct().Count());
}
};
if (consumeFromSameThread)
{
consume();
}
else
{
await ThreadFactory.StartNew(consume);
}
}
[Fact]
public void TryAdd_TryTake_ToArray()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.True(c.TryAdd(42));
Assert.Equal(new[] { 42 }, c.ToArray());
Assert.True(c.TryAdd(84));
Assert.Equal(new[] { 42, 84 }, c.ToArray().OrderBy(i => i));
int item;
Assert.True(c.TryTake(out item));
int remainingItem = item == 42 ? 84 : 42;
Assert.Equal(new[] { remainingItem }, c.ToArray());
Assert.True(c.TryTake(out item));
Assert.Equal(remainingItem, item);
Assert.Empty(c.ToArray());
}
[Fact]
public void ICollection_IsSynchronized_SyncRoot()
{
ICollection c = CreateProducerConsumerCollection();
Assert.False(c.IsSynchronized);
Assert.Throws<NotSupportedException>(() => c.SyncRoot);
}
[Fact]
public void ToArray_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c.ToArray());
Assert.Equal(NumItems, hs.Count);
});
}
[Fact]
public void ToArray_AddTakeSameThread_ExpectedResultsAfterAddsAndTakes()
{
const int Items = 20;
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
IProducerConsumerCollection<int> oracle = CreateOracle();
for (int i = 0; i < Items; i++)
{
Assert.True(c.TryAdd(i));
Assert.True(oracle.TryAdd(i));
Assert.Equal(oracle.ToArray(), c.ToArray());
}
for (int i = Items - 1; i >= 0; i--)
{
int expected, actual;
Assert.Equal(oracle.TryTake(out expected), c.TryTake(out actual));
Assert.Equal(expected, actual);
Assert.Equal(oracle.ToArray(), c.ToArray());
}
}
[Fact]
public void GetEnumerator_ParallelInvocations_Succeed()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Assert.Empty(c.ToArray());
const int NumItems = 10000;
Parallel.For(0, NumItems, i => Assert.True(c.TryAdd(i)));
Assert.Equal(NumItems, c.Count);
Parallel.For(0, 10, i =>
{
var hs = new HashSet<int>(c);
Assert.Equal(NumItems, hs.Count);
});
}
[Theory]
[InlineData(1, ConcurrencyTestSeconds / 2)]
[InlineData(4, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_EnsureTrackedCountsMatchResultingCollection(int threadsPerProc, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
DateTime end = default(DateTime);
using (var b = new Barrier(Environment.ProcessorCount * threadsPerProc, _ => end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds)))
{
Task<int>[] tasks = Enumerable.Range(0, b.ParticipantCount).Select(_ => ThreadFactory.StartNew(() =>
{
b.SignalAndWait();
int count = 0;
var rand = new Random();
while (DateTime.UtcNow < end)
{
if (rand.NextDouble() < .5)
{
Assert.True(c.TryAdd(rand.Next()));
count++;
}
else
{
int item;
if (c.TryTake(out item)) count--;
}
}
return count;
})).ToArray();
Task.WaitAll(tasks);
Assert.Equal(tasks.Sum(t => t.Result), c.Count);
}
}
[Fact]
[OuterLoop]
public void ManyConcurrentAddsTakes_CollectionRemainsConsistent()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int operations = 30000;
Action addAndRemove = () =>
{
for (int i = 1; i < operations; i++)
{
int addCount = new Random(12354).Next(1, 100);
int item;
for (int j = 0; j < addCount; j++)
Assert.True(c.TryAdd(i));
for (int j = 0; j < addCount; j++)
Assert.True(c.TryTake(out item));
}
};
const int numberOfThreads = 3;
var tasks = new Task[numberOfThreads];
for (int i = 0; i < numberOfThreads; i++)
tasks[i] = ThreadFactory.StartNew(addAndRemove);
// Wait for them all to finish
WaitAllOrAnyFailed(tasks);
Assert.Empty(c);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsTaking(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
total++;
}
int item;
if (TryPeek(c, out item))
{
Assert.InRange(item, 1, MaxCount);
}
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item, 1, MaxCount);
}
}
}
return total;
});
Task<long> takesFromOtherThread = ThreadFactory.StartNew(() =>
{
long total = 0;
int item;
while (DateTime.UtcNow < end)
{
if (c.TryTake(out item))
{
total++;
Assert.InRange(item, 1, MaxCount);
}
}
return total;
});
WaitAllOrAnyFailed(addsTakes, takesFromOtherThread);
long remaining = addsTakes.Result - takesFromOtherThread.Result;
Assert.InRange(remaining, 0, long.MaxValue);
Assert.Equal(remaining, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
public void ManyConcurrentAddsTakesPeeks_ForceContentionWithOtherThreadsPeeking(double seconds)
{
IProducerConsumerCollection<LargeStruct> c = CreateProducerConsumerCollection<LargeStruct>();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task<long> addsTakes = ThreadFactory.StartNew(() =>
{
long total = 0;
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(new LargeStruct(i)));
total++;
}
LargeStruct item;
Assert.True(TryPeek(c, out item));
Assert.InRange(item.Value, 1, MaxCount);
for (int i = 1; i <= MaxCount; i++)
{
if (c.TryTake(out item))
{
total--;
Assert.InRange(item.Value, 1, MaxCount);
}
}
}
return total;
});
Task peeksFromOtherThread = ThreadFactory.StartNew(() =>
{
LargeStruct item;
while (DateTime.UtcNow < end)
{
if (TryPeek(c, out item))
{
Assert.InRange(item.Value, 1, MaxCount);
}
}
});
WaitAllOrAnyFailed(addsTakes, peeksFromOtherThread);
Assert.Equal(0, addsTakes.Result);
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(ConcurrencyTestSeconds)]
[ActiveIssue("https://github.com/dotnet/corefx/issues/20474", TargetFrameworkMonikers.UapAot)]
public void ManyConcurrentAddsTakes_ForceContentionWithToArray(double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.ToArray();
Assert.InRange(arr.Length, 0, MaxCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(0, c.Count);
}
[Theory]
[InlineData(0, ConcurrencyTestSeconds / 2)]
[InlineData(1, ConcurrencyTestSeconds / 2)]
public void ManyConcurrentAddsTakes_ForceContentionWithGetEnumerator(int initialCount, double seconds)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(Enumerable.Range(1, initialCount));
const int MaxCount = 4;
DateTime end = DateTime.UtcNow + TimeSpan.FromSeconds(seconds);
Task addsTakes = ThreadFactory.StartNew(() =>
{
while (DateTime.UtcNow < end)
{
for (int i = 1; i <= MaxCount; i++)
{
Assert.True(c.TryAdd(i));
}
for (int i = 1; i <= MaxCount; i++)
{
int item;
Assert.True(c.TryTake(out item));
Assert.InRange(item, 1, MaxCount);
}
}
});
while (DateTime.UtcNow < end)
{
int[] arr = c.Select(i => i).ToArray();
Assert.InRange(arr.Length, initialCount, MaxCount + initialCount);
Assert.DoesNotContain(0, arr); // make sure we didn't get default(T)
}
addsTakes.GetAwaiter().GetResult();
Assert.Equal(initialCount, c.Count);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerAttributes_Success(int count)
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection(count);
DebuggerAttributes.ValidateDebuggerDisplayReferences(c);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(c);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")]
public void DebuggerTypeProxy_Ctor_NullArgument_Throws()
{
IProducerConsumerCollection<int> c = CreateProducerConsumerCollection();
Type proxyType = DebuggerAttributes.GetProxyType(c);
var tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, new object[] { null }));
Assert.IsType<ArgumentNullException>(tie.InnerException);
}
protected static void AssertSetsEqual<T>(HashSet<T> expected, HashSet<T> actual)
{
Assert.Equal(expected.Count, actual.Count);
Assert.Subset(expected, actual);
Assert.Subset(actual, expected);
}
protected static void WaitAllOrAnyFailed(params Task[] tasks)
{
if (tasks.Length == 0)
{
return;
}
int remaining = tasks.Length;
var mres = new ManualResetEventSlim();
foreach (Task task in tasks)
{
task.ContinueWith(t =>
{
if (Interlocked.Decrement(ref remaining) == 0 || t.IsFaulted)
{
mres.Set();
}
}, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
mres.Wait();
// Either all tasks are completed or at least one failed
foreach (Task t in tasks)
{
if (t.IsFaulted)
{
t.GetAwaiter().GetResult(); // propagate for the first one that failed
}
}
}
private struct LargeStruct // used to help validate that values aren't torn while being read
{
private readonly long _a, _b, _c, _d, _e, _f, _g, _h;
public LargeStruct(long value) { _a = _b = _c = _d = _e = _f = _g = _h = value; }
public long Value
{
get
{
if (_a != _b || _a != _c || _a != _d || _a != _e || _a != _f || _a != _g || _a != _h)
{
throw new Exception($"Inconsistent {nameof(LargeStruct)}: {_a} {_b} {_c} {_d} {_e} {_f} {_g} {_h}");
}
return _a;
}
}
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace Mapbox.Editor.NodeEditor
{
public static class GUIScaleUtility
{
// General
private static bool compabilityMode;
private static bool initiated;
// cache the reflected methods
private static FieldInfo currentGUILayoutCache;
private static FieldInfo currentTopLevelGroup;
// Delegates to the reflected methods
private static Func<Rect> GetTopRectDelegate;
private static Func<Rect> topmostRectDelegate;
// Delegate accessors
public static Rect getTopRect { get { return (Rect)GetTopRectDelegate.Invoke(); } }
public static Rect getTopRectScreenSpace { get { return (Rect)topmostRectDelegate.Invoke(); } }
// Rect stack for manipulating groups
public static List<Rect> currentRectStack { get; private set; }
private static List<List<Rect>> rectStackGroups;
// Matrices stack
private static List<Matrix4x4> GUIMatrices;
private static List<bool> adjustedGUILayout;
#region Init
public static void CheckInit()
{
if (!initiated)
Init();
}
public static void Init()
{
// Fetch rect acessors using Reflection
Assembly UnityEngine = Assembly.GetAssembly(typeof(UnityEngine.GUI));
Type GUIClipType = UnityEngine.GetType("UnityEngine.GUIClip", true);
PropertyInfo topmostRect = GUIClipType.GetProperty("topmostRect", BindingFlags.Static | BindingFlags.Public);
MethodInfo GetTopRect = GUIClipType.GetMethod("GetTopRect", BindingFlags.Static | BindingFlags.NonPublic);
MethodInfo ClipRect = GUIClipType.GetMethod("Clip", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder, new Type[] { typeof(Rect) }, new ParameterModifier[] { });
if (GUIClipType == null || topmostRect == null || GetTopRect == null || ClipRect == null)
{
Debug.LogWarning("GUIScaleUtility cannot run on this system! Compability mode enabled. For you that means you're not able to use the Node Editor inside more than one group:( Please PM me (Seneral @UnityForums) so I can figure out what causes this! Thanks!");
Debug.LogWarning((GUIClipType == null ? "GUIClipType is Null, " : "") + (topmostRect == null ? "topmostRect is Null, " : "") + (GetTopRect == null ? "GetTopRect is Null, " : "") + (ClipRect == null ? "ClipRect is Null, " : ""));
compabilityMode = true;
initiated = true;
return;
}
// Create simple acessor delegates
GetTopRectDelegate = (Func<Rect>)Delegate.CreateDelegate(typeof(Func<Rect>), GetTopRect);
topmostRectDelegate = (Func<Rect>)Delegate.CreateDelegate(typeof(Func<Rect>), topmostRect.GetGetMethod());
if (GetTopRectDelegate == null || topmostRectDelegate == null)
{
Debug.LogWarning("GUIScaleUtility cannot run on this system! Compability mode enabled. For you that means you're not able to use the Node Editor inside more than one group:( Please PM me (Seneral @UnityForums) so I can figure out what causes this! Thanks!");
Debug.LogWarning((GUIClipType == null ? "GUIClipType is Null, " : "") + (topmostRect == null ? "topmostRect is Null, " : "") + (GetTopRect == null ? "GetTopRect is Null, " : "") + (ClipRect == null ? "ClipRect is Null, " : ""));
compabilityMode = true;
initiated = true;
return;
}
// As we can call Begin/Ends inside another, we need to save their states hierarchial in Lists (not Stack, as we need to iterate over them!):
currentRectStack = new List<Rect>();
rectStackGroups = new List<List<Rect>>();
GUIMatrices = new List<Matrix4x4>();
adjustedGUILayout = new List<bool>();
// Sometimes, strange errors pop up (related to Mac?), which we try to catch and enable a compability Mode no supporting zooming in groups
/*try
{
topmostRectDelegate.Invoke ();
}
catch (Exception e)
{
Debug.LogWarning ("GUIScaleUtility cannot run on this system! Compability mode enabled. For you that means you're not able to use the Node Editor inside more than one group:( Please PM me (Seneral @UnityForums) so I can figure out what causes this! Thanks!");
Debug.Log (e.Message);
compabilityMode = true;
}*/
initiated = true;
}
#endregion
#region Scale Area
public static Vector2 getCurrentScale { get { return new Vector2(1 / GUI.matrix.GetColumn(0).magnitude, 1 / GUI.matrix.GetColumn(1).magnitude); } }
/// <summary>
/// Begins a scaled local area.
/// Returns vector to offset GUI controls with to account for zooming to the pivot.
/// Using adjustGUILayout does that automatically for GUILayout rects. Theoretically can be nested!
/// </summary>
public static Vector2 BeginScale(ref Rect rect, Vector2 zoomPivot, float zoom, bool adjustGUILayout)
{
Rect screenRect;
if (compabilityMode)
{ // In compability mode, we will assume only one top group and do everything manually, not using reflected calls (-> practically blind)
GUI.EndGroup();
screenRect = rect;
#if UNITY_EDITOR
if (!Application.isPlaying)
screenRect.y += 23;
#endif
}
else
{ // If it's supported, we take the completely generic way using reflected calls
GUIScaleUtility.BeginNoClip();
screenRect = GUIScaleUtility.GUIToScaledSpace(rect);
}
rect = Scale(screenRect, screenRect.position + zoomPivot, new Vector2(zoom, zoom));
// Now continue drawing using the new clipping group
GUI.BeginGroup(rect);
rect.position = Vector2.zero; // Adjust because we entered the new group
// Because I currently found no way to actually scale to a custom pivot rather than (0, 0),
// we'll make use of a cheat and just offset it accordingly to let it appear as if it would scroll to the center
// Note, due to that, controls not adjusted are still scaled to (0, 0)
Vector2 zoomPosAdjust = rect.center - screenRect.size / 2 + zoomPivot;
// For GUILayout, we can make this adjustment here if desired
adjustedGUILayout.Add(adjustGUILayout);
if (adjustGUILayout)
{
GUILayout.BeginHorizontal();
GUILayout.Space(rect.center.x - screenRect.size.x + zoomPivot.x);
GUILayout.BeginVertical();
GUILayout.Space(rect.center.y - screenRect.size.y + zoomPivot.y);
}
// Take a matrix backup to restore back later on
GUIMatrices.Add(GUI.matrix);
// Scale GUI.matrix. After that we have the correct clipping group again.
GUIUtility.ScaleAroundPivot(new Vector2(1 / zoom, 1 / zoom), zoomPosAdjust);
return zoomPosAdjust;
}
/// <summary>
/// Ends a scale region previously opened with BeginScale
/// </summary>
public static void EndScale()
{
// Set last matrix and clipping group
if (GUIMatrices.Count == 0 || adjustedGUILayout.Count == 0)
throw new UnityException("GUIScaleUtility: You are ending more scale regions than you are beginning!");
GUI.matrix = GUIMatrices[GUIMatrices.Count - 1];
GUIMatrices.RemoveAt(GUIMatrices.Count - 1);
// End GUILayout zoomPosAdjustment
if (adjustedGUILayout[adjustedGUILayout.Count - 1])
{
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
adjustedGUILayout.RemoveAt(adjustedGUILayout.Count - 1);
// End the scaled group
GUI.EndGroup();
if (compabilityMode)
{ // In compability mode, we don't know the previous group rect, but as we cannot use top groups there either way, we restore the screen group
if (!Application.isPlaying) // We're in an editor window
GUI.BeginClip(new Rect(0, 23, Screen.width, Screen.height - 23));
else
GUI.BeginClip(new Rect(0, 0, Screen.width, Screen.height));
}
else
{ // Else, restore the clips (groups)
GUIScaleUtility.RestoreClips();
}
}
#endregion
#region Clips Hierarchy
/// <summary>
/// Begins a field without groups. They should be restored using RestoreClips. Can be nested!
/// </summary>
public static void BeginNoClip()
{
// Record and close all clips one by one, from bottom to top, until we hit the 'origin'
List<Rect> rectStackGroup = new List<Rect>();
Rect topMostClip = getTopRect;
while (topMostClip != new Rect(-10000, -10000, 40000, 40000))
{
rectStackGroup.Add(topMostClip);
GUI.EndClip();
topMostClip = getTopRect;
}
// Store the clips appropriately
rectStackGroup.Reverse();
rectStackGroups.Add(rectStackGroup);
currentRectStack.AddRange(rectStackGroup);
}
/// <summary>
/// Begins a field without the last count groups. They should be restored using RestoreClips. Can be nested!
/// </summary>
public static void MoveClipsUp(int count)
{
// Record and close all clips one by one, from bottom to top, until reached the count or hit the 'origin'
List<Rect> rectStackGroup = new List<Rect>();
Rect topMostClip = getTopRect;
while (topMostClip != new Rect(-10000, -10000, 40000, 40000) && count > 0)
{
rectStackGroup.Add(topMostClip);
GUI.EndClip();
topMostClip = getTopRect;
count--;
}
// Store the clips appropriately
rectStackGroup.Reverse();
rectStackGroups.Add(rectStackGroup);
currentRectStack.AddRange(rectStackGroup);
}
/// <summary>
/// Restores the clips removed in BeginNoClip or MoveClipsUp
/// </summary>
public static void RestoreClips()
{
if (rectStackGroups.Count == 0)
{
Debug.LogError("GUIClipHierarchy: BeginNoClip/MoveClipsUp - RestoreClips count not balanced!");
return;
}
// Read and restore clips one by one, from top to bottom
List<Rect> rectStackGroup = rectStackGroups[rectStackGroups.Count - 1];
for (int clipCnt = 0; clipCnt < rectStackGroup.Count; clipCnt++)
{
GUI.BeginClip(rectStackGroup[clipCnt]);
currentRectStack.RemoveAt(currentRectStack.Count - 1);
}
rectStackGroups.RemoveAt(rectStackGroups.Count - 1);
}
#endregion
#region Layout & Matrix Ignores
/// <summary>
/// Ignores the current GUILayout cache and begins a new one. Cannot be nested!
/// </summary>
public static void BeginNewLayout()
{
if (compabilityMode)
return;
// Will mimic a new layout by creating a new group at (0, 0). Will be restored though after ending the new Layout
Rect topMostClip = getTopRect;
if (topMostClip != new Rect(-10000, -10000, 40000, 40000))
GUILayout.BeginArea(new Rect(0, 0, topMostClip.width, topMostClip.height));
else
GUILayout.BeginArea(new Rect(0, 0, Screen.width, Screen.height));
}
/// <summary>
/// Ends the last GUILayout cache
/// </summary>
public static void EndNewLayout()
{
if (!compabilityMode)
GUILayout.EndArea();
}
/// <summary>
/// Begins an area without GUIMatrix transformations. Can be nested!
/// </summary>
public static void BeginIgnoreMatrix()
{
// Store and clean current matrix
GUIMatrices.Add(GUI.matrix);
GUI.matrix = Matrix4x4.identity;
}
/// <summary>
/// Restores last matrix ignored with BeginIgnoreMatrix
/// </summary>
public static void EndIgnoreMatrix()
{
if (GUIMatrices.Count == 0)
throw new UnityException("GUIScaleutility: You are ending more ignoreMatrices than you are beginning!");
// Read and assign previous matrix
GUI.matrix = GUIMatrices[GUIMatrices.Count - 1];
GUIMatrices.RemoveAt(GUIMatrices.Count - 1);
}
#endregion
#region Space Transformations
/// <summary>
/// Scales the position around the pivot with scale
/// </summary>
public static Vector2 Scale(Vector2 pos, Vector2 pivot, Vector2 scale)
{
return Vector2.Scale(pos - pivot, scale) + pivot;
}
/// <summary>
/// Scales the rect around the pivot with scale
/// </summary>
public static Rect Scale(Rect rect, Vector2 pivot, Vector2 scale)
{
rect.position = Vector2.Scale(rect.position - pivot, scale) + pivot;
rect.size = Vector2.Scale(rect.size, scale);
return rect;
}
/// <summary>
/// Transforms the position from the space aquired with BeginNoClip or MoveClipsUp to it's previous space
/// </summary>
public static Vector2 ScaledToGUISpace(Vector2 scaledPosition)
{
if (rectStackGroups == null || rectStackGroups.Count == 0)
return scaledPosition;
// Iterate through the clips and substract positions
List<Rect> rectStackGroup = rectStackGroups[rectStackGroups.Count - 1];
for (int clipCnt = 0; clipCnt < rectStackGroup.Count; clipCnt++)
scaledPosition -= rectStackGroup[clipCnt].position;
return scaledPosition;
}
/// <summary>
/// Transforms the rect from the space aquired with BeginNoClip or MoveClipsUp to it's previous space.
/// DOES NOT scale the rect, only offsets it!
/// </summary>
public static Rect ScaledToGUISpace(Rect scaledRect)
{
if (rectStackGroups == null || rectStackGroups.Count == 0)
return scaledRect;
scaledRect.position = ScaledToGUISpace(scaledRect.position);
return scaledRect;
}
/// <summary>
/// Transforms the position to the new space aquired with BeginNoClip or MoveClipsUp
/// It's way faster to call GUIToScreenSpace before modifying the space though!
/// </summary>
public static Vector2 GUIToScaledSpace(Vector2 guiPosition)
{
if (rectStackGroups == null || rectStackGroups.Count == 0)
return guiPosition;
// Iterate through the clips and add positions ontop
List<Rect> rectStackGroup = rectStackGroups[rectStackGroups.Count - 1];
for (int clipCnt = 0; clipCnt < rectStackGroup.Count; clipCnt++)
guiPosition += rectStackGroup[clipCnt].position;
return guiPosition;
}
/// <summary>
/// Transforms the rect to the new space aquired with BeginNoClip or MoveClipsUp.
/// DOES NOT scale the rect, only offsets it!
/// It's way faster to call GUIToScreenSpace before modifying the space though!
/// </summary>
public static Rect GUIToScaledSpace(Rect guiRect)
{
if (rectStackGroups == null || rectStackGroups.Count == 0)
return guiRect;
guiRect.position = GUIToScaledSpace(guiRect.position);
return guiRect;
}
/// <summary>
/// Transforms the position to screen space.
/// You can use GUIToScaledSpace when you want to transform an old rect to the new space aquired with BeginNoClip or MoveClipsUp (slower, try to call this function before any of these two)!
/// ATTENTION: This does not work well when any of the top groups is negative, means extends to the top or left of the screen. You may consider to use GUIToScaledSpace then, if possible!
/// </summary>
public static Vector2 GUIToScreenSpace(Vector2 guiPosition)
{
#if UNITY_EDITOR
if (!Application.isPlaying)
return guiPosition + getTopRectScreenSpace.position - new Vector2(0, 22);
#endif
return guiPosition + getTopRectScreenSpace.position;
}
/// <summary>
/// Transforms the rect to screen space.
/// You can use GUIToScaledSpace when you want to transform an old rect to the new space aquired with BeginNoClip or MoveClipsUp (slower, try to call this function before any of these two)!
/// ATTENTION: This does not work well when any of the top groups is negative, means extends to the top or left of the screen. You may consider to use GUIToScaledSpace then, if possible!
/// </summary>
public static Rect GUIToScreenSpace(Rect guiRect)
{
guiRect.position += getTopRectScreenSpace.position;
#if UNITY_EDITOR
if (!Application.isPlaying)
guiRect.y -= 22;
#endif
return guiRect;
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.IO;
using Server;
using Server.Accounting;
namespace Knives.Chat3
{
public class GumpInfo
{
private static Hashtable s_Infos = new Hashtable();
private static ArrayList s_Backgrounds = new ArrayList();
private static ArrayList s_TextColors = new ArrayList();
private static bool s_ForceMenu = false;
private static Hashtable s_ForceInfos = new Hashtable();
public static ArrayList Backgrounds { get { return s_Backgrounds; } }
public static ArrayList TextColors { get { return s_TextColors; } }
public static bool ForceMenu { get { return s_ForceMenu; } set { s_ForceMenu = value; } }
public static Hashtable ForceInfos { get { return s_ForceInfos; } }
public static void Initialize()
{
s_Backgrounds.Add( 0xA3C );
s_Backgrounds.Add( 0x53 );
s_Backgrounds.Add( 0x2486 );
s_Backgrounds.Add( 0xDAC );
s_Backgrounds.Add( 0xE10 );
s_Backgrounds.Add( 0x13EC );
s_Backgrounds.Add( 0x1400 );
s_Backgrounds.Add( 0x2422 );
s_Backgrounds.Add( 0x242C );
s_Backgrounds.Add( 0x13BE );
s_Backgrounds.Add( 0x2436 );
s_Backgrounds.Add( 0x2454 );
s_Backgrounds.Add( 0x251C );
s_Backgrounds.Add( 0x254E );
s_Backgrounds.Add( 0x24A4 );
s_Backgrounds.Add( 0x24AE );
General.LoadBacksFile();
s_TextColors.Add("FFFFFF");
s_TextColors.Add("111111");
s_TextColors.Add("FF0000");
s_TextColors.Add("FF9999");
s_TextColors.Add("00FF00");
s_TextColors.Add("0000FF");
s_TextColors.Add("999999");
s_TextColors.Add("333333");
s_TextColors.Add("FFFF00");
s_TextColors.Add("990099");
s_TextColors.Add("CC00FF");
General.LoadColorsFile();
}
public static void Save()
{
try
{
if (!Directory.Exists(General.SavePath))
Directory.CreateDirectory(General.SavePath);
GenericWriter writer = new BinaryFileWriter(Path.Combine(General.SavePath, "Gumps.bin"), true);
writer.Write(0); // version
writer.Write(s_ForceMenu);
writer.Write(s_ForceInfos.Count);
foreach (GumpInfo ginfo in s_ForceInfos.Values)
ginfo.Save(writer);
ArrayList list = new ArrayList();
GumpInfo info;
foreach (object o in new ArrayList(s_Infos.Values))
{
if (!(o is Hashtable))
continue;
foreach (object ob in new ArrayList(((Hashtable)o).Values))
{
if (!(ob is GumpInfo))
continue;
info = (GumpInfo)ob;
if (info.Mobile != null
&& info.Mobile.Player
&& !info.Mobile.Deleted
&& info.Mobile.Account != null
&& ((Account)info.Mobile.Account).LastLogin > DateTime.Now - TimeSpan.FromDays(30))
list.Add(ob);
}
}
writer.Write(list.Count);
foreach (GumpInfo ginfo in list)
ginfo.Save(writer);
writer.Close();
}
catch (Exception e)
{
Errors.Report(General.Local(199));
Console.WriteLine(e.Message);
Console.WriteLine(e.Source);
Console.WriteLine(e.StackTrace);
}
}
public static void Load()
{
try
{
if (!File.Exists(Path.Combine(General.SavePath, "Gumps.bin")))
return;
using (FileStream bin = new FileStream(Path.Combine(General.SavePath, "Gumps.bin"), FileMode.Open, FileAccess.Read, FileShare.Read))
{
GenericReader reader = new BinaryFileReader(new BinaryReader(bin));
int version = reader.ReadInt();
if (version >= 0)
{
s_ForceMenu = reader.ReadBool();
int count = reader.ReadInt();
GumpInfo info;
for (int i = 0; i < count; ++i)
{
info = new GumpInfo();
info.Load(reader);
if (info.Type == null)
continue;
s_ForceInfos[info.Type] = info;
}
count = reader.ReadInt();
for (int i = 0; i < count; ++i)
{
info = new GumpInfo();
info.Load(reader);
if (info.Mobile == null || info.Type == null)
continue;
if (s_Infos[info.Mobile] == null)
s_Infos[info.Mobile] = new Hashtable();
((Hashtable)s_Infos[info.Mobile])[info.Type] = info;
}
}
reader.End();
}
}
catch (Exception e)
{
Errors.Report(General.Local(198));
Console.WriteLine(e.Message);
Console.WriteLine(e.Source);
Console.WriteLine(e.StackTrace);
}
}
public static GumpInfo GetInfo( Mobile m, Type type )
{
if (s_ForceMenu)
{
if (s_ForceInfos[type] == null)
s_ForceInfos[type] = new GumpInfo(null, type);
return (GumpInfo)s_ForceInfos[type];
}
if (s_Infos[m] == null)
s_Infos[m] = new Hashtable();
Hashtable table = (Hashtable)s_Infos[m];
if (table[type] == null)
table[type] = new GumpInfo( m, type );
return (GumpInfo)table[type];
}
public static bool HasMods( Mobile m, Type type )
{
if (s_ForceMenu)
return s_ForceInfos[type] != null;
if (s_Infos[m] == null)
s_Infos[m] = new Hashtable();
if ( ((Hashtable)s_Infos[m])[type] == null )
return false;
return true;
}
private Mobile c_Mobile;
private Type c_Type;
private bool c_Transparent, c_DefaultTrans;
private string c_TextColorRGB;
private int c_Background;
public Mobile Mobile{ get{ return c_Mobile; } }
public Type Type{ get{ return c_Type; } }
public bool Transparent { get { return c_Transparent; } set { c_Transparent = value; c_DefaultTrans = false; } }
public bool DefaultTrans{ get{ return c_DefaultTrans; } set{ c_DefaultTrans = value; } }
public string TextColorRGB{ get{ return c_TextColorRGB; } set{ c_TextColorRGB = value; } }
public string TextColor{ get{ return String.Format( "<BASEFONT COLOR=#{0}>", c_TextColorRGB ); } }
public int Background{ get{ return c_Background; } }
public GumpInfo()
{
}
public GumpInfo( Mobile m, Type type )
{
c_Mobile = m;
c_Type = type;
c_TextColorRGB = "";
c_Background = -1;
c_DefaultTrans = true;
}
public void BackgroundUp()
{
if (c_Background == -1)
{
c_Background = (int)s_Backgrounds[0];
return;
}
for (int i = 0; i < s_Backgrounds.Count; ++i)
if (c_Background == (int)s_Backgrounds[i])
{
if (i == s_Backgrounds.Count - 1)
{
c_Background = (int)s_Backgrounds[0];
return;
}
c_Background = (int)s_Backgrounds[i + 1];
return;
}
}
public void BackgroundDown()
{
if (c_Background == -1)
{
c_Background = (int)s_Backgrounds[s_Backgrounds.Count - 1];
return;
}
for (int i = 0; i < s_Backgrounds.Count; ++i)
if (c_Background == (int)s_Backgrounds[i])
{
if (i == 0)
{
c_Background = (int)s_Backgrounds[s_Backgrounds.Count - 1];
return;
}
c_Background = (int)s_Backgrounds[i - 1];
return;
}
}
public void TextColorUp()
{
if (c_TextColorRGB == "")
{
c_TextColorRGB = s_TextColors[0].ToString();
return;
}
for (int i = 0; i < s_TextColors.Count; ++i)
if (c_TextColorRGB == s_TextColors[i].ToString())
{
if (i == s_TextColors.Count - 1)
{
c_TextColorRGB = s_TextColors[0].ToString();
return;
}
c_TextColorRGB = s_TextColors[i + 1].ToString();
return;
}
}
public void TextColorDown()
{
if (c_TextColorRGB == "")
{
c_TextColorRGB = s_TextColors[s_TextColors.Count - 1].ToString();
return;
}
for (int i = 0; i < s_TextColors.Count; ++i)
if (c_TextColorRGB == s_TextColors[i].ToString())
{
if (i == 0)
{
c_TextColorRGB = s_TextColors[s_TextColors.Count - 1].ToString();
return;
}
c_TextColorRGB = s_TextColors[i - 1].ToString();
return;
}
}
public void Default()
{
if (s_ForceMenu)
{
s_ForceInfos.Remove(c_Type);
return;
}
if (c_Mobile == null || s_Infos[c_Mobile] == null)
return;
((Hashtable)s_Infos[c_Mobile]).Remove(c_Type);
}
private void Save(GenericWriter writer)
{
writer.Write( 0 ); // version
// Version 0
writer.Write( c_Mobile );
writer.Write( c_Type.ToString() );
writer.Write( c_Transparent );
writer.Write( c_DefaultTrans );
writer.Write( c_TextColorRGB );
writer.Write( c_Background );
}
private void Load( GenericReader reader )
{
int version = reader.ReadInt();
if ( version >= 0 )
{
c_Mobile = reader.ReadMobile();
c_Type = ScriptCompiler.FindTypeByFullName( reader.ReadString() );
c_Transparent = reader.ReadBool();
c_DefaultTrans = reader.ReadBool();
c_TextColorRGB = reader.ReadString();
c_Background = reader.ReadInt();
}
}
}
}
| |
// 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.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic.Utils;
using System.Threading;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a block that contains a sequence of expressions where variables can be defined.
/// </summary>
[DebuggerTypeProxy(typeof(Expression.BlockExpressionProxy))]
public class BlockExpression : Expression
{
/// <summary>
/// Gets the expressions in this block.
/// </summary>
public ReadOnlyCollection<Expression> Expressions
{
get { return GetOrMakeExpressions(); }
}
/// <summary>
/// Gets the variables defined in this block.
/// </summary>
public ReadOnlyCollection<ParameterExpression> Variables
{
get
{
return GetOrMakeVariables();
}
}
/// <summary>
/// Gets the last expression in this block.
/// </summary>
public Expression Result
{
get
{
Debug.Assert(ExpressionCount > 0);
return GetExpression(ExpressionCount - 1);
}
}
internal BlockExpression()
{
}
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitBlock(this);
}
/// <summary>
/// Returns the node type of this Expression. Extension nodes should return
/// ExpressionType.Extension when overriding this method.
/// </summary>
/// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
public sealed override ExpressionType NodeType
{
get { return ExpressionType.Block; }
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression" /> represents.
/// </summary>
/// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns>
public override Type Type
{
get { return GetExpression(ExpressionCount - 1).Type; }
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="variables">The <see cref="Variables" /> property of the result.</param>
/// <param name="expressions">The <see cref="Expressions" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public BlockExpression Update(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions)
{
if (variables == Variables && expressions == Expressions)
{
return this;
}
return Expression.Block(Type, variables, expressions);
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual Expression GetExpression(int index)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual int ExpressionCount
{
get
{
throw ContractUtils.Unreachable;
}
}
[ExcludeFromCodeCoverage] // Unreachable
internal virtual ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
throw ContractUtils.Unreachable;
}
internal virtual ReadOnlyCollection<ParameterExpression> GetOrMakeVariables()
{
return EmptyReadOnlyCollection<ParameterExpression>.Instance;
}
/// <summary>
/// Makes a copy of this node replacing the parameters/args with the provided values. The
/// shape of the parameters/args needs to match the shape of the current block - in other
/// words there should be the same # of parameters and args.
///
/// parameters can be null in which case the existing parameters are used.
///
/// This helper is provided to allow re-writing of nodes to not depend on the specific optimized
/// subclass of BlockExpression which is being used.
/// </summary>
[ExcludeFromCodeCoverage] // Unreachable
internal virtual BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
throw ContractUtils.Unreachable;
}
/// <summary>
/// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T.
///
/// This is similar to the ReturnReadOnly which only takes a single argument. This version
/// supports nodes which hold onto 5 Expressions and puts all of the arguments into the
/// ReadOnlyCollection.
///
/// Ultimately this means if we create the readonly collection we will be slightly more wasteful as we'll
/// have a readonly collection + some fields in the type. The DLR internally avoids accessing anything
/// which would force the readonly collection to be created.
///
/// This is used by BlockExpression5 and MethodCallExpression5.
/// </summary>
internal static ReadOnlyCollection<Expression> ReturnReadOnlyExpressions(BlockExpression provider, ref object collection)
{
Expression tObj = collection as Expression;
if (tObj != null)
{
// otherwise make sure only one readonly collection ever gets exposed
Interlocked.CompareExchange(
ref collection,
new ReadOnlyCollection<Expression>(new BlockExpressionList(provider, tObj)),
tObj
);
}
// and return what is not guaranteed to be a readonly collection
return (ReadOnlyCollection<Expression>)collection;
}
}
#region Specialized Subclasses
internal sealed class Block2 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1; // storage for the 2nd argument.
internal Block2(Expression arg0, Expression arg1)
{
_arg0 = arg0;
_arg1 = arg1;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
default: throw Error.ArgumentOutOfRange(nameof(index));
}
}
internal override int ExpressionCount
{
get
{
return 2;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args != null);
Debug.Assert(args.Length == 2);
Debug.Assert(variables == null || variables.Count == 0);
return new Block2(args[0], args[1]);
}
}
internal sealed class Block3 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2; // storage for the 2nd and 3rd arguments.
internal Block3(Expression arg0, Expression arg1, Expression arg2)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
default: throw Error.ArgumentOutOfRange(nameof(index));
}
}
internal override int ExpressionCount
{
get
{
return 3;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args != null);
Debug.Assert(args.Length == 3);
Debug.Assert(variables == null || variables.Count == 0);
return new Block3(args[0], args[1], args[2]);
}
}
internal sealed class Block4 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2, _arg3; // storarg for the 2nd, 3rd, and 4th arguments.
internal Block4(Expression arg0, Expression arg1, Expression arg2, Expression arg3)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
default: throw Error.ArgumentOutOfRange(nameof(index));
}
}
internal override int ExpressionCount
{
get
{
return 4;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args != null);
Debug.Assert(args.Length == 4);
Debug.Assert(variables == null || variables.Count == 0);
return new Block4(args[0], args[1], args[2], args[3]);
}
}
internal sealed class Block5 : BlockExpression
{
private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider
private readonly Expression _arg1, _arg2, _arg3, _arg4; // storage for the 2nd - 5th args.
internal Block5(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
{
_arg0 = arg0;
_arg1 = arg1;
_arg2 = arg2;
_arg3 = arg3;
_arg4 = arg4;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_arg0);
case 1: return _arg1;
case 2: return _arg2;
case 3: return _arg3;
case 4: return _arg4;
default: throw Error.ArgumentOutOfRange(nameof(index));
}
}
internal override int ExpressionCount
{
get
{
return 5;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _arg0);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(args != null);
Debug.Assert(args.Length == 5);
Debug.Assert(variables == null || variables.Count == 0);
return new Block5(args[0], args[1], args[2], args[3], args[4]);
}
}
internal class BlockN : BlockExpression
{
private IList<Expression> _expressions; // either the original IList<Expression> or a ReadOnlyCollection if the user has accessed it.
internal BlockN(IList<Expression> expressions)
{
Debug.Assert(expressions.Count != 0);
_expressions = expressions;
}
internal override Expression GetExpression(int index)
{
Debug.Assert(index >= 0 && index < _expressions.Count);
return _expressions[index];
}
internal override int ExpressionCount
{
get
{
return _expressions.Count;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnly(ref _expressions);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
Debug.Assert(variables == null || variables.Count == 0);
Debug.Assert(args != null);
return new BlockN(args);
}
}
internal class ScopeExpression : BlockExpression
{
private IList<ParameterExpression> _variables; // list of variables or ReadOnlyCollection if the user has accessed the readonly collection
internal ScopeExpression(IList<ParameterExpression> variables)
{
_variables = variables;
}
internal override ReadOnlyCollection<ParameterExpression> GetOrMakeVariables()
{
return ReturnReadOnly(ref _variables);
}
protected IList<ParameterExpression> VariablesList
{
get
{
return _variables;
}
}
// Used for rewrite of the nodes to either reuse existing set of variables if not rewritten.
internal IList<ParameterExpression> ReuseOrValidateVariables(ReadOnlyCollection<ParameterExpression> variables)
{
if (variables != null && variables != VariablesList)
{
// Need to validate the new variables (uniqueness, not byref)
ValidateVariables(variables, nameof(variables));
return variables;
}
else
{
return VariablesList;
}
}
}
internal sealed class Scope1 : ScopeExpression
{
private object _body;
internal Scope1(IList<ParameterExpression> variables, Expression body)
: this(variables, (object)body)
{
}
private Scope1(IList<ParameterExpression> variables, object body)
: base(variables)
{
_body = body;
}
internal override Expression GetExpression(int index)
{
switch (index)
{
case 0: return ReturnObject<Expression>(_body);
default: throw Error.ArgumentOutOfRange(nameof(index));
}
}
internal override int ExpressionCount
{
get
{
return 1;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnlyExpressions(this, ref _body);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
if (args == null)
{
Debug.Assert(variables.Count == Variables.Count);
ValidateVariables(variables, nameof(variables));
return new Scope1(variables, _body);
}
Debug.Assert(args.Length == 1);
Debug.Assert(variables == null || variables.Count == Variables.Count);
return new Scope1(ReuseOrValidateVariables(variables), args[0]);
}
}
internal class ScopeN : ScopeExpression
{
private IList<Expression> _body;
internal ScopeN(IList<ParameterExpression> variables, IList<Expression> body)
: base(variables)
{
_body = body;
}
protected IList<Expression> Body
{
get { return _body; }
}
internal override Expression GetExpression(int index)
{
return _body[index];
}
internal override int ExpressionCount
{
get
{
return _body.Count;
}
}
internal override ReadOnlyCollection<Expression> GetOrMakeExpressions()
{
return ReturnReadOnly(ref _body);
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
if (args == null)
{
Debug.Assert(variables.Count == Variables.Count);
ValidateVariables(variables, nameof(variables));
return new ScopeN(variables, _body);
}
Debug.Assert(args.Length == ExpressionCount);
Debug.Assert(variables == null || variables.Count == Variables.Count);
return new ScopeN(ReuseOrValidateVariables(variables), args);
}
}
internal class ScopeWithType : ScopeN
{
private readonly Type _type;
internal ScopeWithType(IList<ParameterExpression> variables, IList<Expression> expressions, Type type)
: base(variables, expressions)
{
_type = type;
}
public sealed override Type Type
{
get { return _type; }
}
internal override BlockExpression Rewrite(ReadOnlyCollection<ParameterExpression> variables, Expression[] args)
{
if (args == null)
{
Debug.Assert(variables.Count == Variables.Count);
ValidateVariables(variables, nameof(variables));
return new ScopeWithType(variables, Body, _type);
}
Debug.Assert(args.Length == ExpressionCount);
Debug.Assert(variables == null || variables.Count == Variables.Count);
return new ScopeWithType(ReuseOrValidateVariables(variables), args, _type);
}
}
#endregion
#region Block List Classes
/// <summary>
/// Provides a wrapper around an IArgumentProvider which exposes the argument providers
/// members out as an IList of Expression. This is used to avoid allocating an array
/// which needs to be stored inside of a ReadOnlyCollection. Instead this type has
/// the same amount of overhead as an array without duplicating the storage of the
/// elements. This ensures that internally we can avoid creating and copying arrays
/// while users of the Expression trees also don't pay a size penalty for this internal
/// optimization. See IArgumentProvider for more general information on the Expression
/// tree optimizations being used here.
/// </summary>
internal class BlockExpressionList : IList<Expression>
{
private readonly BlockExpression _block;
private readonly Expression _arg0;
internal BlockExpressionList(BlockExpression provider, Expression arg0)
{
_block = provider;
_arg0 = arg0;
}
#region IList<Expression> Members
public int IndexOf(Expression item)
{
if (_arg0 == item)
{
return 0;
}
for (int i = 1; i < _block.ExpressionCount; i++)
{
if (_block.GetExpression(i) == item)
{
return i;
}
}
return -1;
}
[ExcludeFromCodeCoverage] // Unreachable
public void Insert(int index, Expression item)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
public void RemoveAt(int index)
{
throw ContractUtils.Unreachable;
}
public Expression this[int index]
{
get
{
if (index == 0)
{
return _arg0;
}
return _block.GetExpression(index);
}
[ExcludeFromCodeCoverage] // Unreachable
set
{
throw ContractUtils.Unreachable;
}
}
#endregion
#region ICollection<Expression> Members
[ExcludeFromCodeCoverage] // Unreachable
public void Add(Expression item)
{
throw ContractUtils.Unreachable;
}
[ExcludeFromCodeCoverage] // Unreachable
public void Clear()
{
throw ContractUtils.Unreachable;
}
public bool Contains(Expression item)
{
return IndexOf(item) != -1;
}
public void CopyTo(Expression[] array, int arrayIndex)
{
array[arrayIndex++] = _arg0;
for (int i = 1; i < _block.ExpressionCount; i++)
{
array[arrayIndex++] = _block.GetExpression(i);
}
}
public int Count
{
get { return _block.ExpressionCount; }
}
[ExcludeFromCodeCoverage] // Unreachable
public bool IsReadOnly
{
get
{
throw ContractUtils.Unreachable;
}
}
[ExcludeFromCodeCoverage] // Unreachable
public bool Remove(Expression item)
{
throw ContractUtils.Unreachable;
}
#endregion
#region IEnumerable<Expression> Members
public IEnumerator<Expression> GetEnumerator()
{
yield return _arg0;
for (int i = 1; i < _block.ExpressionCount; i++)
{
yield return _block.GetExpression(i);
}
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
#endregion
public partial class Expression
{
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains two expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1)
{
RequiresCanRead(arg0, nameof(arg0));
RequiresCanRead(arg1, nameof(arg1));
return new Block2(arg0, arg1);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains three expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <param name="arg2">The third expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2)
{
RequiresCanRead(arg0, nameof(arg0));
RequiresCanRead(arg1, nameof(arg1));
RequiresCanRead(arg2, nameof(arg2));
return new Block3(arg0, arg1, arg2);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains four expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <param name="arg2">The third expression in the block.</param>
/// <param name="arg3">The fourth expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3)
{
RequiresCanRead(arg0, nameof(arg0));
RequiresCanRead(arg1, nameof(arg1));
RequiresCanRead(arg2, nameof(arg2));
RequiresCanRead(arg3, nameof(arg3));
return new Block4(arg0, arg1, arg2, arg3);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains five expressions and has no variables.
/// </summary>
/// <param name="arg0">The first expression in the block.</param>
/// <param name="arg1">The second expression in the block.</param>
/// <param name="arg2">The third expression in the block.</param>
/// <param name="arg3">The fourth expression in the block.</param>
/// <param name="arg4">The fifth expression in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4)
{
RequiresCanRead(arg0, nameof(arg0));
RequiresCanRead(arg1, nameof(arg1));
RequiresCanRead(arg2, nameof(arg2));
RequiresCanRead(arg3, nameof(arg3));
RequiresCanRead(arg4, nameof(arg4));
return new Block5(arg0, arg1, arg2, arg3, arg4);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables.
/// </summary>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(params Expression[] expressions)
{
ContractUtils.RequiresNotNull(expressions, nameof(expressions));
return GetOptimizedBlockExpression(expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions and has no variables.
/// </summary>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(IEnumerable<Expression> expressions)
{
return Block(EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, params Expression[] expressions)
{
ContractUtils.RequiresNotNull(expressions, nameof(expressions));
return Block(type, (IEnumerable<Expression>)expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given expressions, has no variables and has specific result type.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, IEnumerable<Expression> expressions)
{
return Block(type, EmptyReadOnlyCollection<ParameterExpression>.Instance, expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(IEnumerable<ParameterExpression> variables, params Expression[] expressions)
{
return Block(variables, (IEnumerable<Expression>)expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, params Expression[] expressions)
{
return Block(type, variables, (IEnumerable<Expression>)expressions);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions)
{
ContractUtils.RequiresNotNull(expressions, nameof(expressions));
var variableList = variables.ToReadOnly();
if (variableList.Count == 0)
{
return GetOptimizedBlockExpression(expressions as IReadOnlyList<Expression> ?? expressions.ToReadOnly());
}
var expressionList = expressions.ToReadOnly();
return BlockCore(null, variableList, expressionList);
}
/// <summary>
/// Creates a <see cref="BlockExpression"/> that contains the given variables and expressions.
/// </summary>
/// <param name="type">The result type of the block.</param>
/// <param name="variables">The variables in the block.</param>
/// <param name="expressions">The expressions in the block.</param>
/// <returns>The created <see cref="BlockExpression"/>.</returns>
public static BlockExpression Block(Type type, IEnumerable<ParameterExpression> variables, IEnumerable<Expression> expressions)
{
ContractUtils.RequiresNotNull(type, nameof(type));
ContractUtils.RequiresNotNull(expressions, nameof(expressions));
var expressionList = expressions.ToReadOnly();
var variableList = variables.ToReadOnly();
if (variableList.Count == 0 && expressionList.Count != 0)
{
var expressionCount = expressionList.Count;
if (expressionCount != 0)
{
var lastExpression = expressionList[expressionCount - 1];
if (lastExpression == null)
{
throw Error.ArgumentNull(nameof(expressions));
}
if (lastExpression.Type == type)
{
return GetOptimizedBlockExpression(expressionList);
}
}
}
return BlockCore(type, variableList, expressionList);
}
private static BlockExpression BlockCore(Type type, ReadOnlyCollection<ParameterExpression> variables, ReadOnlyCollection<Expression> expressions)
{
RequiresCanRead(expressions, nameof(expressions));
ValidateVariables(variables, nameof(variables));
if (type != null)
{
if (expressions.Count == 0)
{
if (type != typeof(void))
{
throw Error.ArgumentTypesMustMatch();
}
return new ScopeWithType(variables, expressions, type);
}
Expression last = expressions.Last();
if (type != typeof(void))
{
if (!TypeUtils.AreReferenceAssignable(type, last.Type))
{
throw Error.ArgumentTypesMustMatch();
}
}
if (!TypeUtils.AreEquivalent(type, last.Type))
{
return new ScopeWithType(variables, expressions, type);
}
}
switch (expressions.Count)
{
case 0:
return new ScopeWithType(variables, expressions, typeof(void));
case 1:
return new Scope1(variables, expressions[0]);
default:
return new ScopeN(variables, expressions);
}
}
// Checks that all variables are non-null, not byref, and unique.
internal static void ValidateVariables(ReadOnlyCollection<ParameterExpression> varList, string collectionName)
{
if (varList.Count == 0)
{
return;
}
int count = varList.Count;
var set = new Set<ParameterExpression>(count);
for (int i = 0; i < count; i++)
{
ParameterExpression v = varList[i];
if (v == null)
{
throw new ArgumentNullException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}[{1}]", collectionName, set.Count));
}
if (v.IsByRef)
{
throw Error.VariableMustNotBeByRef(v, v.Type);
}
if (set.Contains(v))
{
throw Error.DuplicateVariable(v);
}
set.Add(v);
}
}
private static BlockExpression GetOptimizedBlockExpression(IReadOnlyList<Expression> expressions)
{
RequiresCanRead(expressions, nameof(expressions));
switch (expressions.Count)
{
case 0: return BlockCore(typeof(void), EmptyReadOnlyCollection<ParameterExpression>.Instance, EmptyReadOnlyCollection<Expression>.Instance);
case 2: return new Block2(expressions[0], expressions[1]);
case 3: return new Block3(expressions[0], expressions[1], expressions[2]);
case 4: return new Block4(expressions[0], expressions[1], expressions[2], expressions[3]);
case 5: return new Block5(expressions[0], expressions[1], expressions[2], expressions[3], expressions[4]);
default:
return new BlockN(expressions as ReadOnlyCollection<Expression> ?? (IList<Expression>)expressions.ToArray());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing.Drawing2D;
using System.IO;
using System.Reflection;
using System.Diagnostics;
using System.Globalization;
namespace System.Drawing.Html
{
public static class CssValue
{
/// <summary>
/// Evals a number and returns it. If number is a percentage, it will be multiplied by <see cref="hundredPercent"/>
/// </summary>
/// <param name="number">Number to be parsed</param>
/// <param name="factor">Number that represents the 100% if parsed number is a percentage</param>
/// <returns>Parsed number. Zero if error while parsing.</returns>
public static float ParseNumber(string number, float hundredPercent)
{
if (string.IsNullOrEmpty(number))
{
return 0f;
}
string toParse = number;
bool isPercent = number.EndsWith("%");
float result = 0f;
if (isPercent) toParse = number.Substring(0, number.Length - 1);
if (!float.TryParse(toParse, NumberStyles.Number, NumberFormatInfo.InvariantInfo, out result))
{
return 0f;
}
if (isPercent)
{
result = (result / 100f) * hundredPercent;
}
return result;
}
/// <summary>
/// Parses a length. Lengths are followed by an unit identifier (e.g. 10px, 3.1em)
/// </summary>
/// <param name="length">Specified length</param>
/// <param name="hundredPercent">Equivalent to 100 percent when length is percentage</param>
/// <param name="box"></param>
/// <returns></returns>
public static float ParseLength(string length, float hundredPercent, CssBox box)
{
return ParseLength(length, hundredPercent, box, box.GetEmHeight(), false);
}
/// <summary>
/// Parses a length. Lengths are followed by an unit identifier (e.g. 10px, 3.1em)
/// </summary>
/// <param name="length">Specified length</param>
/// <param name="hundredPercent">Equivalent to 100 percent when length is percentage</param>
/// <param name="box"></param>
/// <param name="useParentsEm"></param>
/// <param name="returnPoints">Allows the return float to be in points. If false, result will be pixels</param>
/// <returns></returns>
public static float ParseLength(string length, float hundredPercent, CssBox box, float emFactor, bool returnPoints)
{
//Return zero if no length specified, zero specified
if (string.IsNullOrEmpty(length) || length == "0") return 0f;
//If percentage, use ParseNumber
if (length.EndsWith("%")) return ParseNumber(length, hundredPercent);
//If no units, return zero
if (length.Length < 3) return 0f;
//Get units of the length
string unit = length.Substring(length.Length - 2, 2);
//Factor will depend on the unit
float factor = 1f;
//Number of the length
string number = length.Substring(0, length.Length - 2);
//TODO: Units behave different in paper and in screen!
switch (unit)
{
case CssConstants.Em:
factor = emFactor;
break;
case CssConstants.Px:
factor = 1f;
break;
case CssConstants.Mm:
factor = 3f; //3 pixels per millimeter
break;
case CssConstants.Cm:
factor = 37f; //37 pixels per centimeter
break;
case CssConstants.In:
factor = 96f; //96 pixels per inch
break;
case CssConstants.Pt:
factor = 96f / 72f; // 1 point = 1/72 of inch
if (returnPoints)
{
return ParseNumber(number, hundredPercent);
}
break;
case CssConstants.Pc:
factor = 96f / 72f * 12f; // 1 pica = 12 points
break;
default:
factor = 0f;
break;
}
return factor * ParseNumber(number, hundredPercent);
}
/// <summary>
/// Parses a color value in CSS style; e.g. #ff0000, red, rgb(255,0,0), rgb(100%, 0, 0)
/// </summary>
/// <param name="colorValue">Specified color value; e.g. #ff0000, red, rgb(255,0,0), rgb(100%, 0, 0)</param>
/// <returns>System.Drawing.Color value</returns>
public static Color GetActualColor(string colorValue)
{
int a = 0xff;
int r = 0;
int g = 0;
int b = 0;
Color onError = Color.Empty;
if (string.IsNullOrEmpty(colorValue)) return onError;
colorValue = colorValue.ToLower().Trim();
if (colorValue.StartsWith("#"))
{
#region hexadecimal forms
string hex = colorValue.Substring(1);
if (hex.Length == 8)
{
a = int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
r = int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
g = int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
b = int.Parse(hex.Substring(6, 2), System.Globalization.NumberStyles.HexNumber);
}
else if (hex.Length == 6)
{
r = int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber);
g = int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber);
b = int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber);
}
else if (hex.Length == 3)
{
r = int.Parse(new String(hex.Substring(0, 1)[0], 2), System.Globalization.NumberStyles.HexNumber);
g = int.Parse(new String(hex.Substring(1, 1)[0], 2), System.Globalization.NumberStyles.HexNumber);
b = int.Parse(new String(hex.Substring(2, 1)[0], 2), System.Globalization.NumberStyles.HexNumber);
}
else
{
return onError;
}
#endregion
}
else if (colorValue.StartsWith("rgb(") && colorValue.EndsWith(")"))
{
#region RGB forms
string rgb = colorValue.Substring(4, colorValue.Length - 5);
string[] chunks = rgb.Split(',');
if (chunks.Length == 3)
{
unchecked
{
r = Convert.ToInt32(ParseNumber(chunks[0].Trim(), 255f));
g = Convert.ToInt32(ParseNumber(chunks[1].Trim(), 255f));
b = Convert.ToInt32(ParseNumber(chunks[2].Trim(), 255f));
}
}
else
{
return onError;
}
#endregion
}
else
{
#region Color Constants
string hex = string.Empty;
switch (colorValue)
{
case CssConstants.Maroon:
hex = "#800000"; break;
case CssConstants.Red:
hex = "#ff0000"; break;
case CssConstants.Orange:
hex = "#ffA500"; break;
case CssConstants.Olive:
hex = "#808000"; break;
case CssConstants.Purple:
hex = "#800080"; break;
case CssConstants.Fuchsia:
hex = "#ff00ff"; break;
case CssConstants.White:
hex = "#ffffff"; break;
case CssConstants.Lime:
hex = "#00ff00"; break;
case CssConstants.Green:
hex = "#008000"; break;
case CssConstants.Navy:
hex = "#000080"; break;
case CssConstants.Blue:
hex = "#0000ff"; break;
case CssConstants.Aqua:
hex = "#00ffff"; break;
case CssConstants.Teal:
hex = "#008080"; break;
case CssConstants.Black:
hex = "#000000"; break;
case CssConstants.Silver:
hex = "#c0c0c0"; break;
case CssConstants.Gray:
hex = "#808080"; break;
case CssConstants.Yellow:
hex = "#FFFF00"; break;
}
if (string.IsNullOrEmpty(hex))
{
return onError;
}
else
{
Color c = GetActualColor(hex);
r = c.R;
g = c.G;
b = c.B;
}
#endregion
}
return Color.FromArgb(a, r, g, b);
}
/// <summary>
/// Parses a border value in CSS style; e.g. 1px, 1, thin, thick, medium
/// </summary>
/// <param name="borderValue"></param>
/// <returns></returns>
public static float GetActualBorderWidth(string borderValue, CssBox b)
{
if (string.IsNullOrEmpty(borderValue))
{
return GetActualBorderWidth(CssConstants.Medium, b);
}
switch (borderValue)
{
case CssConstants.Thin:
return 1f;
case CssConstants.Medium:
return 2f;
case CssConstants.Thick:
return 4f;
default:
return Math.Abs(ParseLength(borderValue, 1, b));
}
}
/// <summary>
/// Split the value by spaces; e.g. Useful in values like 'padding:5 4 3 inherit'
/// </summary>
/// <param name="value">Value to be splitted</param>
/// <returns>Splitted and trimmed values</returns>
public static string[] SplitValues(string value)
{
return SplitValues(value, ' ');
}
/// <summary>
/// Split the value by the specified separator; e.g. Useful in values like 'padding:5 4 3 inherit'
/// </summary>
/// <param name="value">Value to be splitted</param>
/// <returns>Splitted and trimmed values</returns>
public static string[] SplitValues(string value, char separator)
{
//TODO: CRITICAL! Don't split values on parenthesis (like rgb(0, 0, 0)) or quotes ("strings")
if (string.IsNullOrEmpty(value)) return new string[] { };
string[] values = value.Split(separator);
List<string> result = new List<string>();
for (int i = 0; i < values.Length; i++)
{
string val = values[i].Trim();
if (!string.IsNullOrEmpty(val))
{
result.Add(val);
}
}
return result.ToArray();
}
/// <summary>
/// Detects the type name in a path.
/// E.g. Gets System.Drawing.Graphics from a path like System.Drawing.Graphics.Clear
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static Type GetTypeInfo(string path, ref string moreInfo)
{
int lastDot = path.LastIndexOf('.');
if (lastDot < 0) return null;
string type = path.Substring(0, lastDot);
moreInfo = path.Substring(lastDot + 1);
moreInfo = moreInfo.Replace("(", string.Empty).Replace(")", string.Empty);
foreach (Assembly a in HtmlRenderer.References)
{
Type t = a.GetType(type, false, true);
if (t != null) return t;
}
return null;
}
/// <summary>
/// Returns the object specific to the path
/// </summary>
/// <param name="path"></param>
/// <returns>One of the following possible objects: FileInfo, MethodInfo, PropertyInfo</returns>
private static object DetectSource(string path)
{
if (path.StartsWith("method:", StringComparison.CurrentCultureIgnoreCase))
{
string methodName = string.Empty;
Type t = GetTypeInfo(path.Substring(7), ref methodName); if (t == null) return null;
MethodInfo method = t.GetMethod(methodName);
if (!method.IsStatic || method.GetParameters().Length > 0)
{
return null;
}
return method;
}
else if (path.StartsWith("property:", StringComparison.CurrentCultureIgnoreCase))
{
string propName = string.Empty;
Type t = GetTypeInfo(path.Substring(9), ref propName); if (t == null) return null;
PropertyInfo prop = t.GetProperty(propName);
return prop;
}
else if (Uri.IsWellFormedUriString(path, UriKind.RelativeOrAbsolute))
{
return new Uri(path);
}
else
{
return new FileInfo(path);
}
}
/// <summary>
/// Gets the image of the specified path
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static Image GetImage(string path)
{
object source = DetectSource(path);
FileInfo finfo = source as FileInfo;
PropertyInfo prop = source as PropertyInfo;
MethodInfo method = source as MethodInfo;
try
{
if (finfo != null)
{
if (!finfo.Exists) return null;
return Image.FromFile(finfo.FullName);
}
else if (prop != null)
{
if (!prop.PropertyType.IsSubclassOf(typeof(Image)) && !prop.PropertyType.Equals(typeof(Image))) return null;
return prop.GetValue(null, null) as Image;
}
else if (method != null)
{
if (!method.ReturnType.IsSubclassOf(typeof(Image))) return null;
return method.Invoke(null, null) as Image;
}
else
{
return null;
}
}
catch
{
return new Bitmap(50, 50); //TODO: Return error image
}
}
/// <summary>
/// Gets the content of the stylesheet specified in the path
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string GetStyleSheet(string path)
{
object source = DetectSource(path);
FileInfo finfo = source as FileInfo;
PropertyInfo prop = source as PropertyInfo;
MethodInfo method = source as MethodInfo;
try
{
if (finfo != null)
{
if (!finfo.Exists) return null;
StreamReader sr = new StreamReader(finfo.FullName);
string result = sr.ReadToEnd();
sr.Dispose();
return result;
}
else if (prop != null)
{
if (!prop.PropertyType.Equals(typeof(string))) return null;
return prop.GetValue(null, null) as string;
}
else if (method != null)
{
if (!method.ReturnType.Equals(typeof(string))) return null;
return method.Invoke(null, null) as string;
}
else
{
return string.Empty;
}
}
catch
{
return string.Empty;
}
}
/// <summary>
/// Executes the desired action when the user clicks a link
/// </summary>
/// <param name="href"></param>
public static void GoLink(string href)
{
object source = DetectSource(href);
FileInfo finfo = source as FileInfo;
PropertyInfo prop = source as PropertyInfo;
MethodInfo method = source as MethodInfo;
Uri uri = source as Uri;
try
{
if (finfo != null || uri != null)
{
ProcessStartInfo nfo = new ProcessStartInfo(href);
nfo.UseShellExecute = true;
Process.Start(nfo);
}
else if (method != null)
{
method.Invoke(null, null);
}
else
{
//Nothing to do.
}
}
catch
{
throw;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Net;
using System.Security.Principal;
using System.DirectoryServices;
namespace System.DirectoryServices.AccountManagement
{
internal partial class SAMStoreCtx : StoreCtx
{
//
// Native <--> Principal
//
// For modified object, pushes any changes (including IdentityClaim changes)
// into the underlying store-specific object (e.g., DirectoryEntry) and returns the underlying object.
// For unpersisted object, creates a underlying object if one doesn't already exist (in
// Principal.UnderlyingObject), then pushes any changes into the underlying object.
internal override object PushChangesToNative(Principal p)
{
try
{
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Type principalType = p.GetType();
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Entering PushChangesToNative, type={0}", p.GetType());
if (de == null)
{
// Must be a newly-inserted Principal for which PushChangesToNative has not yet
// been called.
// Determine the objectClass of the SAM entry we'll be creating
string objectClass;
if (principalType == typeof(UserPrincipal) || principalType.IsSubclassOf(typeof(UserPrincipal)))
objectClass = "user";
else if (principalType == typeof(GroupPrincipal) || principalType.IsSubclassOf(typeof(GroupPrincipal)))
objectClass = "group";
else
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForSave, principalType.ToString()));
}
// Determine the SAM account name for the entry we'll be creating. Use the name from the NT4 IdentityClaim.
string samAccountName = GetSamAccountName(p);
if (samAccountName == null)
{
// They didn't set a NT4 IdentityClaim.
throw new InvalidOperationException(SR.NameMustBeSetToPersistPrincipal);
}
lock (_ctxBaseLock)
{
de = _ctxBase.Children.Add(samAccountName, objectClass);
}
GlobalDebug.WriteLineIf(
GlobalDebug.Info, "SAMStoreCtx", "PushChangesToNative: created fresh DE, oc={0}, name={1}, path={2}",
objectClass, samAccountName, de.Path);
p.UnderlyingObject = de;
// set the default user account control bits for authenticable principals
if (principalType.IsSubclassOf(typeof(AuthenticablePrincipal)))
{
InitializeUserAccountControl((AuthenticablePrincipal)p);
}
}
// Determine the mapping table to use, based on the principal type
Hashtable propertyMappingTableByProperty;
if (principalType == typeof(UserPrincipal))
{
propertyMappingTableByProperty = s_userPropertyMappingTableByProperty;
}
else if (principalType == typeof(GroupPrincipal))
{
propertyMappingTableByProperty = s_groupPropertyMappingTableByProperty;
}
else
{
Debug.Assert(principalType == typeof(ComputerPrincipal));
propertyMappingTableByProperty = s_computerPropertyMappingTableByProperty;
}
// propertyMappingTableByProperty has entries for all writable properties,
// including writable properties which we don't support in SAM for some or
// all principal types.
// If we don't support the property, the PropertyMappingTableEntry will map
// it to a converter which will throw an appropriate exception.
foreach (DictionaryEntry dictEntry in propertyMappingTableByProperty)
{
ArrayList propertyEntries = (ArrayList)dictEntry.Value;
foreach (PropertyMappingTableEntry propertyEntry in propertyEntries)
{
if (null != propertyEntry.papiToWinNTConverter)
{
if (p.GetChangeStatusForProperty(propertyEntry.propertyName))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "PushChangesToNative: pushing {0}", propertyEntry.propertyName);
// The property was set. Write it to the DirectoryEntry.
Debug.Assert(propertyEntry.propertyName == (string)dictEntry.Key);
propertyEntry.papiToWinNTConverter(
p,
propertyEntry.propertyName,
de,
propertyEntry.suggestedWinNTPropertyName,
this.IsLSAM
);
}
}
}
}
// Unlike AD, where password sets on newly-created principals must be handled after persisting the principal,
// in SAM they get set before persisting the principal, and ADSI's WinNT provider saves off the operation
// until the SetInfo() is performed.
if (p.GetChangeStatusForProperty(PropertyNames.PwdInfoPassword))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "PushChangesToNative: setting password");
// Only AuthenticablePrincipals can have PasswordInfo
Debug.Assert(p is AuthenticablePrincipal);
string password = (string)p.GetValueForProperty(PropertyNames.PwdInfoPassword);
Debug.Assert(password != null); // if null, PasswordInfo should not have indicated it was changed
SDSUtils.SetPassword(de, password);
}
return de;
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
private string GetSamAccountName(Principal p)
{
// They didn't set any IdentityClaims, so they certainly didn't set a NT4 IdentityClaim
if (!p.GetChangeStatusForProperty(PropertyNames.PrincipalSamAccountName))
return null;
string Name = p.SamAccountName;
if (Name == null)
return null;
// Split the SAM account name out of the UrnValue
// We accept both "host\user" and "user"
int index = Name.IndexOf('\\');
if (index == Name.Length - 1)
return null;
return (index != -1) ? Name.Substring(index + 1) : // +1 to skip the '/'
Name;
}
// Given a underlying store object (e.g., DirectoryEntry), further narrowed down a discriminant
// (if applicable for the StoreCtx type), returns a fresh instance of a Principal
// object based on it. The WinFX Principal API follows ADSI-style semantics, where you get multiple
// in-memory objects all referring to the same store pricipal, rather than WinFS semantics, where
// multiple searches all return references to the same in-memory object.
// Used to implement the reverse wormhole. Also, used internally by FindResultEnumerator
// to construct Principals from the store objects returned by a store query.
//
// The Principal object produced by this method does not have all the properties
// loaded. The Principal object will call the Load method on demand to load its properties
// from its Principal.UnderlyingObject.
//
//
// This method works for native objects from the store corresponding to _this_ StoreCtx.
// Each StoreCtx will also have its own internal algorithms used for dealing with cross-store objects, e.g.,
// for use when iterating over group membership. These routines are exposed as
// ResolveCrossStoreRefToPrincipal, and will be called by the StoreCtx's associated ResultSet
// classes when iterating over a representation of a "foreign" principal.
internal override Principal GetAsPrincipal(object storeObject, object discriminant)
{
// SAM doesn't use discriminant, should always be null.
Debug.Assert(discriminant == null);
Debug.Assert(storeObject != null);
Debug.Assert(storeObject is DirectoryEntry);
DirectoryEntry de = (DirectoryEntry)storeObject;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "GetAsPrincipal: using path={0}", de.Path);
// Construct a appropriate Principal object.
Principal p = SDSUtils.DirectoryEntryToPrincipal(de, this.OwningContext, null);
Debug.Assert(p != null);
// Assign a SAMStoreKey to the newly-constructed Principal.
// If it doesn't have an objectSid, it's not a principal and we shouldn't be here.
Debug.Assert((de.Properties["objectSid"] != null) && (de.Properties["objectSid"].Count == 1));
SAMStoreKey key = new SAMStoreKey(this.MachineFlatName, (byte[])de.Properties["objectSid"].Value);
p.Key = key;
return p;
}
internal override void Load(Principal p, string principalPropertyName)
{
Debug.Assert(p != null);
Debug.Assert(p.UnderlyingObject != null);
Debug.Assert(p.UnderlyingObject is DirectoryEntry);
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Type principalType = p.GetType();
Hashtable propertyMappingTableByProperty;
if (principalType == typeof(UserPrincipal))
{
propertyMappingTableByProperty = s_userPropertyMappingTableByProperty;
}
else if (principalType == typeof(GroupPrincipal))
{
propertyMappingTableByProperty = s_groupPropertyMappingTableByProperty;
}
else
{
Debug.Assert(principalType == typeof(ComputerPrincipal));
propertyMappingTableByProperty = s_computerPropertyMappingTableByProperty;
}
ArrayList entries = (ArrayList)propertyMappingTableByProperty[principalPropertyName];
// We don't support this property and cannot load it. To maintain backward compatibility with the old code just return.
if (entries == null)
return;
try
{
foreach (PropertyMappingTableEntry entry in entries)
{
if (null != entry.winNTToPapiConverter)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Load_PropertyName: loading {0}", entry.propertyName);
entry.winNTToPapiConverter(de, entry.suggestedWinNTPropertyName, p, entry.propertyName);
}
}
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
// Loads the store values from p.UnderlyingObject into p, performing schema mapping as needed.
internal override void Load(Principal p)
{
try
{
Debug.Assert(p != null);
Debug.Assert(p.UnderlyingObject != null);
Debug.Assert(p.UnderlyingObject is DirectoryEntry);
DirectoryEntry de = (DirectoryEntry)p.UnderlyingObject;
Debug.Assert(de != null);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Entering Load, type={0}, path={1}", p.GetType(), de.Path);
// The list of all the SAM attributes in the DirectoryEntry
ICollection samAttributes = de.Properties.PropertyNames;
// Determine the mapping table to use, based on the principal type
Type principalType = p.GetType();
Hashtable propertyMappingTableByWinNT;
if (principalType == typeof(UserPrincipal))
{
propertyMappingTableByWinNT = s_userPropertyMappingTableByWinNT;
}
else if (principalType == typeof(GroupPrincipal))
{
propertyMappingTableByWinNT = s_groupPropertyMappingTableByWinNT;
}
else
{
Debug.Assert(principalType == typeof(ComputerPrincipal));
propertyMappingTableByWinNT = s_computerPropertyMappingTableByWinNT;
}
// Map each SAM attribute into the Principal in turn
foreach (string samAttribute in samAttributes)
{
ArrayList entries = (ArrayList)propertyMappingTableByWinNT[samAttribute.ToLower(CultureInfo.InvariantCulture)];
// If it's not in the table, it's not an SAM attribute we care about
if (entries == null)
continue;
// Load it into the Principal. Some LDAP attributes (such as userAccountControl)
// map to more than one Principal property.
foreach (PropertyMappingTableEntry entry in entries)
{
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "Load: loading {0}", entry.propertyName);
entry.winNTToPapiConverter(de, entry.suggestedWinNTPropertyName, p, entry.propertyName);
}
}
}
catch (System.Runtime.InteropServices.COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
// Performs store-specific resolution of an IdentityReference to a Principal
// corresponding to the IdentityReference. Returns null if no matching object found.
// principalType can be used to scope the search to principals of a specified type, e.g., users or groups.
// Specify typeof(Principal) to search all principal types.
internal override Principal FindPrincipalByIdentRef(
Type principalType, string urnScheme, string urnValue, DateTime referenceDate)
{
// Perform the appropriate action based on the type of the UrnScheme
if (urnScheme == UrnScheme.SidScheme)
{
// Get the SID from the UrnValue
SecurityIdentifier sidObj = new SecurityIdentifier(urnValue);
byte[] sid = new byte[sidObj.BinaryLength];
sidObj.GetBinaryForm(sid, 0);
if (sid == null)
throw new ArgumentException(SR.StoreCtxSecurityIdentityClaimBadFormat);
// If they're searching by SID for a SID corresponding to a fake group, construct
// and return the fake group
IntPtr pSid = IntPtr.Zero;
try
{
pSid = Utils.ConvertByteArrayToIntPtr(sid);
if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"SAMStoreCtx",
"FindPrincipalByIdentRef: fake principal {0}",
sidObj.ToString());
return ConstructFakePrincipalFromSID(sid);
}
}
finally
{
if (pSid != IntPtr.Zero)
Marshal.FreeHGlobal(pSid);
}
// Not a fake group. Search for the real group.
object o = FindNativeBySIDIdentRef(principalType, sid);
return (o != null) ? GetAsPrincipal(o, null) : null;
}
else if (urnScheme == UrnScheme.SamAccountScheme || urnScheme == UrnScheme.NameScheme)
{
object o = FindNativeByNT4IdentRef(principalType, urnValue);
return (o != null) ? GetAsPrincipal(o, null) : null;
}
else if (urnScheme == null)
{
object sidPrincipal = null;
object nt4Principal = null;
//
// Try UrnValue as a SID IdentityClaim
//
// Get the SID from the UrnValue
byte[] sid = null;
try
{
SecurityIdentifier sidObj = new SecurityIdentifier(urnValue);
sid = new byte[sidObj.BinaryLength];
sidObj.GetBinaryForm(sid, 0);
}
catch (ArgumentException)
{
// must not have been a valid sid claim ignore it.
}
// If null, must have been a non-SID UrnValue. Ignore it, and
// continue on to try NT4 Account IdentityClaim.
if (sid != null)
{
// Are they perhaps searching for a fake group?
// If they passed in a valid SID for a fake group, construct and return the fake
// group.
if (principalType == typeof(Principal) || principalType == typeof(GroupPrincipal) || principalType.IsSubclassOf(typeof(GroupPrincipal)))
{
// They passed in a hex string, is it a valid SID, and if so, does it correspond to a fake
// principal?
IntPtr pSid = IntPtr.Zero;
try
{
pSid = Utils.ConvertByteArrayToIntPtr(sid);
if (UnsafeNativeMethods.IsValidSid(pSid) && (Utils.ClassifySID(pSid) == SidType.FakeObject))
{
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"SAMStoreCtx",
"FindPrincipalByIdentRef: fake principal {0} (scheme==null)",
Utils.ByteArrayToString(sid));
return ConstructFakePrincipalFromSID(sid);
}
}
finally
{
if (pSid != IntPtr.Zero)
Marshal.FreeHGlobal(pSid);
}
}
sidPrincipal = FindNativeBySIDIdentRef(principalType, sid);
}
//
// Try UrnValue as a NT4 IdentityClaim
//
try
{
nt4Principal = FindNativeByNT4IdentRef(principalType, urnValue);
}
catch (ArgumentException)
{
// Must have been a non-NT4 Account UrnValue. Ignore it.
}
GlobalDebug.WriteLineIf(GlobalDebug.Info,
"SAMStoreCtx",
"FindPrincipalByIdentRef: scheme==null, found nt4={0}, found sid={1}",
(nt4Principal != null),
(sidPrincipal != null));
// If they both succeeded in finding a match, we have too many matches.
// Throw an exception.
if ((sidPrincipal != null) && (nt4Principal != null))
throw new MultipleMatchesException(SR.MultipleMatchingPrincipals);
// Return whichever one matched. If neither matched, this will return null.
return (sidPrincipal != null) ? GetAsPrincipal(sidPrincipal, null) :
((nt4Principal != null) ? GetAsPrincipal(nt4Principal, null) :
null);
}
else
{
// Unsupported type of IdentityClaim
throw new ArgumentException(SR.StoreCtxUnsupportedIdentityClaimForQuery);
}
}
private object FindNativeBySIDIdentRef(Type principalType, byte[] sid)
{
// We can't lookup directly by SID, so we transform the SID --> SAM account name,
// and do a lookup by that.
string samUrnValue;
string name;
string domainName;
int accountUsage;
// Map the SID to a machine and account name
// If this fails, there's no match
int err = Utils.LookupSid(this.MachineUserSuppliedName, _credentials, sid, out name, out domainName, out accountUsage);
if (err != 0)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error,
"SAMStoreCtx",
"FindNativeBySIDIdentRef:LookupSid on {0} failed, err={1}",
this.MachineUserSuppliedName,
err);
return null;
}
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeBySIDIdentRef: mapped to {0}\\{1}", domainName, name);
// Fixup the domainName for BUILTIN principals
if (Utils.ClassifySID(sid) == SidType.RealObjectFakeDomain)
{
// BUILTIN principal ---> Issuer is actually our machine, not "BUILTIN" domain.
domainName = this.MachineFlatName;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeBySIDIdentRef: using {0} for domainName", domainName);
}
// Valid SID, but not for our context (machine). No match.
if (String.Compare(domainName, this.MachineFlatName, StringComparison.OrdinalIgnoreCase) != 0)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "FindNativeBySIDIdentRef: {0} != {1}, no match", domainName, this.MachineFlatName);
return null;
}
// Build the NT4 UrnValue
samUrnValue = domainName + "\\" + name;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeBySIDIdentRef: searching for {0}", samUrnValue);
return FindNativeByNT4IdentRef(principalType, samUrnValue);
}
private object FindNativeByNT4IdentRef(Type principalType, string urnValue)
{
// Extract the SAM account name from the UrnValue.
// We'll accept both "host\user" and "user".
int index = urnValue.IndexOf('\\');
if (index == urnValue.Length - 1)
throw new ArgumentException(SR.StoreCtxNT4IdentityClaimWrongForm);
string samAccountName = (index != -1) ? urnValue.Substring(index + 1) : // +1 to skip the '/'
urnValue;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeByNT4IdentRef: searching for {0}", samAccountName);
// If they specified a specific type of principal, use that as a hint to speed up
// the lookup.
string principalHint = "";
if (principalType == typeof(UserPrincipal) || principalType.IsSubclassOf(typeof(UserPrincipal)))
{
principalHint = ",user";
principalType = typeof(UserPrincipal);
}
else if (principalType == typeof(GroupPrincipal) || principalType.IsSubclassOf(typeof(GroupPrincipal)))
{
principalHint = ",group";
principalType = typeof(GroupPrincipal);
}
else if (principalType == typeof(ComputerPrincipal) || principalType.IsSubclassOf(typeof(ComputerPrincipal)))
{
principalHint = ",computer";
principalType = typeof(ComputerPrincipal);
}
// Retrieve the object from SAM
string adsPath = "WinNT://" + this.MachineUserSuppliedName + "/" + samAccountName + principalHint;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "FindNativeByNT4IdentRef: adsPath={0}", adsPath);
DirectoryEntry de = SDSUtils.BuildDirectoryEntry(_credentials, _authTypes);
try
{
de.Path = adsPath;
// If it has no SID, it's not a security principal, and we're not interested in it.
// This also has the side effect of forcing the object to load, thereby testing
// whether or not it exists.
if (de.Properties["objectSid"] == null || de.Properties["objectSid"].Count == 0)
return false;
}
catch (System.Runtime.InteropServices.COMException e)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error,
"SAMStoreCtx",
"FindNativeByNT4IdentRef: caught COMException, message={0}, code={1}",
e.Message,
e.ErrorCode);
// Failed to find it
if ((e.ErrorCode == unchecked((int)0x800708AB)) || // unknown user
(e.ErrorCode == unchecked((int)0x800708AC)) || // unknown group
(e.ErrorCode == unchecked((int)0x80070035)) || // bad net path
(e.ErrorCode == unchecked((int)0x800708AD)))
{
return null;
}
// Unknown error, don't suppress it
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
// Make sure it's of the correct type
bool fMatch = false;
if ((principalType == typeof(UserPrincipal)) && SAMUtils.IsOfObjectClass(de, "User"))
fMatch = true;
else if ((principalType == typeof(GroupPrincipal)) && SAMUtils.IsOfObjectClass(de, "Group"))
fMatch = true;
else if ((principalType == typeof(ComputerPrincipal)) && SAMUtils.IsOfObjectClass(de, "Computer"))
fMatch = true;
else if ((principalType == typeof(AuthenticablePrincipal)) &&
(SAMUtils.IsOfObjectClass(de, "User") || SAMUtils.IsOfObjectClass(de, "Computer")))
fMatch = true;
else
{
Debug.Assert(principalType == typeof(Principal));
if (SAMUtils.IsOfObjectClass(de, "User") || SAMUtils.IsOfObjectClass(de, "Group") || SAMUtils.IsOfObjectClass(de, "Computer"))
fMatch = true;
}
if (fMatch)
return de;
return null;
}
// Returns a type indicating the type of object that would be returned as the wormhole for the specified
// Principal. For some StoreCtxs, this method may always return a constant (e.g., typeof(DirectoryEntry)
// for ADStoreCtx). For others, it may vary depending on the Principal passed in.
internal override Type NativeType(Principal p)
{
Debug.Assert(p != null);
return typeof(DirectoryEntry);
}
//
// Property mapping tables
//
// We only list properties we map in this table. At run-time, if we detect they set a
// property that's not listed here, or is listed here but not for the correct principal type,
// when writing to SAM, we throw an exception.
private static object[,] s_propertyMappingTableRaw =
{
// PropertyName Principal Type SAM property Converter(WinNT->PAPI) Converter(PAPI->WinNT)
{PropertyNames.PrincipalDisplayName, typeof(UserPrincipal), "FullName", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.PrincipalDescription, typeof(UserPrincipal), "Description", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.PrincipalDescription, typeof(GroupPrincipal), "Description", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.PrincipalSamAccountName, typeof(Principal), "Name", new FromWinNTConverterDelegate(SamAccountNameFromWinNTConverter), null},
{PropertyNames.PrincipalSid, typeof(Principal), "objectSid", new FromWinNTConverterDelegate(SidFromWinNTConverter), null },
{PropertyNames.PrincipalDistinguishedName, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalGuid, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalUserPrincipalName, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
// Name and SamAccountNAme properties are currently routed to the same underlying Name property.
{PropertyNames.PrincipalName, typeof(Principal), "Name", new FromWinNTConverterDelegate(SamAccountNameFromWinNTConverter), null},
//
{PropertyNames.AuthenticablePrincipalEnabled , typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.AuthenticablePrincipalCertificates, typeof(UserPrincipal), "*******", new FromWinNTConverterDelegate(CertFromWinNTConverter), new ToWinNTConverterDelegate(CertToWinNT)},
//
{PropertyNames.GroupIsSecurityGroup, typeof(GroupPrincipal), "*******", new FromWinNTConverterDelegate(GroupTypeFromWinNTConverter), new ToWinNTConverterDelegate(GroupTypeToWinNTConverter)},
{PropertyNames.GroupGroupScope, typeof(GroupPrincipal), "groupType", new FromWinNTConverterDelegate(GroupTypeFromWinNTConverter), new ToWinNTConverterDelegate(GroupTypeToWinNTConverter)},
//
{PropertyNames.UserEmailAddress, typeof(UserPrincipal), "*******" , new FromWinNTConverterDelegate(EmailFromWinNTConverter), new ToWinNTConverterDelegate(EmailToWinNTConverter)},
//
{PropertyNames.AcctInfoLastLogon, typeof(UserPrincipal), "LastLogin", new FromWinNTConverterDelegate(DateFromWinNTConverter), null},
{PropertyNames.AcctInfoPermittedWorkstations, typeof(UserPrincipal), "LoginWorkstations", new FromWinNTConverterDelegate(MultiStringFromWinNTConverter), new ToWinNTConverterDelegate(MultiStringToWinNTConverter)},
{PropertyNames.AcctInfoPermittedLogonTimes, typeof(UserPrincipal), "LoginHours", new FromWinNTConverterDelegate(BinaryFromWinNTConverter), new ToWinNTConverterDelegate(LogonHoursToWinNTConverter)},
{PropertyNames.AcctInfoExpirationDate, typeof(UserPrincipal), "AccountExpirationDate", new FromWinNTConverterDelegate(DateFromWinNTConverter), new ToWinNTConverterDelegate(AcctExpirDateToNTConverter)},
{PropertyNames.AcctInfoSmartcardRequired, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.AcctInfoDelegationPermitted, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.AcctInfoBadLogonCount, typeof(UserPrincipal), "BadPasswordAttempts", new FromWinNTConverterDelegate(IntFromWinNTConverter), null},
{PropertyNames.AcctInfoHomeDirectory, typeof(UserPrincipal), "HomeDirectory", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.AcctInfoHomeDrive, typeof(UserPrincipal), "HomeDirDrive", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
{PropertyNames.AcctInfoScriptPath, typeof(UserPrincipal), "LoginScript", new FromWinNTConverterDelegate(StringFromWinNTConverter), new ToWinNTConverterDelegate(StringToWinNTConverter)},
//
{PropertyNames.PwdInfoLastPasswordSet, typeof(UserPrincipal), "PasswordAge", new FromWinNTConverterDelegate(ElapsedTimeFromWinNTConverter), null},
{PropertyNames.PwdInfoLastBadPasswordAttempt, typeof(UserPrincipal), "*******", new FromWinNTConverterDelegate(LastBadPwdAttemptFromWinNTConverter), null},
{PropertyNames.PwdInfoPasswordNotRequired, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.PwdInfoPasswordNeverExpires, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.PwdInfoCannotChangePassword, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
{PropertyNames.PwdInfoAllowReversiblePasswordEncryption, typeof(UserPrincipal), "UserFlags", new FromWinNTConverterDelegate(UserFlagsFromWinNTConverter), new ToWinNTConverterDelegate(UserFlagsToWinNTConverter)},
//
// Writable properties we don't support writing in SAM
//
{PropertyNames.UserGivenName, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.UserMiddleName, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.UserSurname, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.UserVoiceTelephoneNumber, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.UserEmployeeID, typeof(UserPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalDisplayName, typeof(GroupPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalDisplayName, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PrincipalDescription, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AuthenticablePrincipalEnabled, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AuthenticablePrincipalCertificates, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.ComputerServicePrincipalNames, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoPermittedWorkstations, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoPermittedLogonTimes, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoExpirationDate, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoSmartcardRequired, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoDelegationPermitted, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoHomeDirectory, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoHomeDrive, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.AcctInfoScriptPath, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PwdInfoPasswordNotRequired, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PwdInfoPasswordNeverExpires, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PwdInfoCannotChangePassword, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)},
{PropertyNames.PwdInfoAllowReversiblePasswordEncryption, typeof(ComputerPrincipal), null, null, new ToWinNTConverterDelegate(ExceptionToWinNTConverter)}
};
private static Hashtable s_userPropertyMappingTableByProperty = null;
private static Hashtable s_userPropertyMappingTableByWinNT = null;
private static Hashtable s_groupPropertyMappingTableByProperty = null;
private static Hashtable s_groupPropertyMappingTableByWinNT = null;
private static Hashtable s_computerPropertyMappingTableByProperty = null;
private static Hashtable s_computerPropertyMappingTableByWinNT = null;
private static Dictionary<string, ObjectMask> s_validPropertyMap = null;
private static Dictionary<Type, ObjectMask> s_maskMap = null;
[Flags]
private enum ObjectMask
{
None = 0,
User = 0x1,
Computer = 0x2,
Group = 0x4,
Principal = User | Computer | Group
}
private class PropertyMappingTableEntry
{
internal string propertyName; // PAPI name
internal string suggestedWinNTPropertyName; // WinNT attribute name
internal FromWinNTConverterDelegate winNTToPapiConverter;
internal ToWinNTConverterDelegate papiToWinNTConverter;
}
//
// Conversion routines
//
// Loads the specified attribute of the DirectoryEntry into the specified property of the Principal
private delegate void FromWinNTConverterDelegate(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName);
// Loads the specified property of the Principal into the specified attribute of the DirectoryEntry.
// For multivalued attributes, must test to make sure the value hasn't already been loaded into the DirectoryEntry
// (to maintain idempotency when PushChangesToNative is called multiple times).
private delegate void ToWinNTConverterDelegate(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM);
//
// WinNT --> PAPI
//
private static void StringFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
PropertyValueCollection values = de.Properties[suggestedWinNTProperty];
// The WinNT provider represents some string attributes that haven't been set as an empty string.
// Map them to null (not set), to maintain consistency with the LDAP context.
if ((values.Count > 0) && (((string)values[0]).Length == 0))
return;
SDSUtils.SingleScalarFromDirectoryEntry<string>(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName);
}
private static void SidFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
byte[] sid = (byte[])de.Properties["objectSid"][0];
string stringizedSid = Utils.ByteArrayToString(sid);
string sddlSid = Utils.ConvertSidToSDDL(sid);
SecurityIdentifier SidObj = new SecurityIdentifier(sddlSid);
p.LoadValueIntoProperty(propertyName, (object)SidObj);
}
private static void SamAccountNameFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
Debug.Assert(de.Properties["Name"].Count == 1);
string samAccountName = (string)de.Properties["Name"][0];
// string urnValue = p.Context.ConnectedServer + @"\" + samAccountName;
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "SamAccountNameFromWinNTConverter: loading SAM{0}", samAccountName);
p.LoadValueIntoProperty(propertyName, (object)samAccountName);
}
private static void MultiStringFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
// ValueCollection<string> is Load'ed from a List<string>
SDSUtils.MultiScalarFromDirectoryEntry<string>(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName);
}
private static void IntFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
SDSUtils.SingleScalarFromDirectoryEntry<int>(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName);
}
private static void BinaryFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
SDSUtils.SingleScalarFromDirectoryEntry<byte[]>(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName);
}
private static void CertFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
}
private static void GroupTypeFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
// Groups are always enabled in SAM. There is no such thing as a distribution group.
p.LoadValueIntoProperty(PropertyNames.GroupIsSecurityGroup, (object)true);
if (propertyName == PropertyNames.GroupIsSecurityGroup)
{
// Do nothing for this property.
}
else
{
Debug.Assert(propertyName == PropertyNames.GroupGroupScope);
// All local machine SAM groups are local
#if DEBUG
PropertyValueCollection values = de.Properties[suggestedWinNTProperty];
if (values.Count != 0)
Debug.Assert(((int)values[0]) == 4);
#endif
p.LoadValueIntoProperty(propertyName, GroupScope.Local);
}
}
private static void EmailFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
}
private static void LastBadPwdAttemptFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
}
private static void ElapsedTimeFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
// These properties are expressed as "seconds passed since the event of interest". So to convert
// to a DateTime, we substract them from DateTime.UtcNow.
PropertyValueCollection values = de.Properties[suggestedWinNTProperty];
if (values.Count != 0)
{
// We're intended to handle single-valued scalar properties
Debug.Assert(values.Count == 1);
Debug.Assert(values[0] is Int32);
int secondsLapsed = (int)values[0];
Nullable<DateTime> dt = DateTime.UtcNow - new TimeSpan(0, 0, secondsLapsed);
p.LoadValueIntoProperty(propertyName, dt);
}
}
private static void DateFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
PropertyValueCollection values = de.Properties[suggestedWinNTProperty];
if (values.Count != 0)
{
Debug.Assert(values.Count == 1);
// Unlike with the ADSI LDAP provider, these come back as a DateTime (expressed in UTC), instead
// of a IADsLargeInteger.
Nullable<DateTime> dt = (Nullable<DateTime>)values[0];
p.LoadValueIntoProperty(propertyName, dt);
}
}
private static void UserFlagsFromWinNTConverter(DirectoryEntry de, string suggestedWinNTProperty, Principal p, string propertyName)
{
Debug.Assert(String.Compare(suggestedWinNTProperty, "UserFlags", StringComparison.OrdinalIgnoreCase) == 0);
SDSUtils.AccountControlFromDirectoryEntry(new dSPropertyCollection(de.Properties), suggestedWinNTProperty, p, propertyName, true);
}
//
// PAPI --> WinNT
//
private static void ExceptionToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
SR.PrincipalUnsupportPropertyForType,
p.GetType().ToString(),
PropertyNamesExternal.GetExternalForm(propertyName)));
}
private static void StringToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
string value = (string)p.GetValueForProperty(propertyName);
if (p.unpersisted && value == null)
return;
if (value != null && value.Length > 0)
de.Properties[suggestedWinNTProperty].Value = value;
else
de.Properties[suggestedWinNTProperty].Value = "";
}
private static void MultiStringToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
SDSUtils.MultiStringToDirectoryEntryConverter(p, propertyName, de, suggestedWinNTProperty);
}
private static void LogonHoursToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
Debug.Assert(propertyName == PropertyNames.AcctInfoPermittedLogonTimes);
byte[] value = (byte[])p.GetValueForProperty(propertyName);
if (p.unpersisted && value == null)
return;
if (value != null && value.Length != 0)
{
de.Properties[suggestedWinNTProperty].Value = value;
}
else
{
byte[] allHours = new byte[]{0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff};
de.Properties[suggestedWinNTProperty].Value = allHours;
}
}
private static void CertToWinNT(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
if (!isLSAM)
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
SR.PrincipalUnsupportPropertyForPlatform,
PropertyNamesExternal.GetExternalForm(propertyName)));
}
private static void GroupTypeToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
if (propertyName == PropertyNames.GroupIsSecurityGroup)
{
if (!isLSAM)
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
SR.PrincipalUnsupportPropertyForPlatform,
PropertyNamesExternal.GetExternalForm(propertyName)));
}
else
{
Debug.Assert(propertyName == PropertyNames.GroupGroupScope);
// local machine SAM only supports local groups
GroupScope value = (GroupScope)p.GetValueForProperty(propertyName);
if (value != GroupScope.Local)
throw new InvalidOperationException(SR.SAMStoreCtxLocalGroupsOnly);
}
}
private static void EmailToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
if (!isLSAM)
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
SR.PrincipalUnsupportPropertyForPlatform,
PropertyNamesExternal.GetExternalForm(propertyName)));
}
private static void AcctExpirDateToNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
Nullable<DateTime> value = (Nullable<DateTime>)p.GetValueForProperty(propertyName);
if (p.unpersisted && value == null)
return;
// ADSI's WinNT provider uses 1/1/1970 to represent "never expires" when setting the property
if (value.HasValue)
de.Properties[suggestedWinNTProperty].Value = (DateTime)value;
else
de.Properties[suggestedWinNTProperty].Value = new DateTime(1970, 1, 1);
}
private static void UserFlagsToWinNTConverter(Principal p, string propertyName, DirectoryEntry de, string suggestedWinNTProperty, bool isLSAM)
{
Debug.Assert(String.Compare(suggestedWinNTProperty, "UserFlags", StringComparison.OrdinalIgnoreCase) == 0);
SDSUtils.AccountControlToDirectoryEntry(p, propertyName, de, suggestedWinNTProperty, true, p.unpersisted);
}
private static void UpdateGroupMembership(Principal group, DirectoryEntry de, NetCred credentials, AuthenticationTypes authTypes)
{
Debug.Assert(group.fakePrincipal == false);
PrincipalCollection members = (PrincipalCollection)group.GetValueForProperty(PropertyNames.GroupMembers);
UnsafeNativeMethods.IADsGroup iADsGroup = (UnsafeNativeMethods.IADsGroup)de.NativeObject;
try
{
//
// Process clear
//
if (members.Cleared)
{
// Unfortunately, there's no quick way to clear a group's membership in SAM.
// So we remove each member in turn, by enumerating over the group membership
// and calling remove on each.
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UpdateGroupMembership: clearing {0}", de.Path);
// Prepare the COM Interopt enumeration
UnsafeNativeMethods.IADsMembers iADsMembers = iADsGroup.Members();
IEnumVARIANT enumerator = (IEnumVARIANT)iADsMembers._NewEnum;
object[] nativeMembers = new object[1];
int hr;
do
{
hr = enumerator.Next(1, nativeMembers, IntPtr.Zero);
if (hr == 0) // S_OK
{
// Found a member, remove it.
UnsafeNativeMethods.IADs iADs = (UnsafeNativeMethods.IADs)nativeMembers[0];
iADsGroup.Remove(iADs.ADsPath);
}
}
while (hr == 0);
// Either hr == S_FALSE (1), which means we completed the enumerator,
// or we encountered an error
if (hr != 1)
{
// Error occurred.
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "UpdateGroupMembership: error while clearing, hr={0}", hr);
throw new PrincipalOperationException(
String.Format(
CultureInfo.CurrentCulture,
SR.SAMStoreCtxFailedToClearGroup,
hr.ToString(CultureInfo.InvariantCulture)));
}
}
//
// Process inserted members
//
List<Principal> insertedMembers = members.Inserted;
// First, validate the members to be added
foreach (Principal member in insertedMembers)
{
Type memberType = member.GetType();
if ((memberType != typeof(UserPrincipal)) && (!memberType.IsSubclassOf(typeof(UserPrincipal))) &&
(memberType != typeof(ComputerPrincipal)) && (!memberType.IsSubclassOf(typeof(ComputerPrincipal))) &&
(memberType != typeof(GroupPrincipal)) && (!memberType.IsSubclassOf(typeof(GroupPrincipal))))
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture, SR.StoreCtxUnsupportedPrincipalTypeForGroupInsert, memberType.ToString()));
}
// Can't inserted unpersisted principal
if (member.unpersisted)
throw new InvalidOperationException(SR.StoreCtxGroupHasUnpersistedInsertedPrincipal);
Debug.Assert(member.Context != null);
// There's no restriction on the type of principal to be inserted (AD/reg-SAM/MSAM), but it needs
// to have a SID IdentityClaim. We'll check that as we go.
}
// Now add each member to the group
foreach (Principal member in insertedMembers)
{
// We'll add the member via its SID. This works for both MSAM members and AD members.
// Build a SID ADsPath
string memberSidPath = GetSidADsPathFromPrincipal(member);
if (memberSidPath == null)
throw new InvalidOperationException(SR.SAMStoreCtxCouldntGetSIDForGroupMember);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UpdateGroupMembership: inserting {0}", memberSidPath);
// Add the member to the group
iADsGroup.Add(memberSidPath);
}
//
// Process removed members
//
List<Principal> removedMembers = members.Removed;
foreach (Principal member in removedMembers)
{
// Since we don't allow any of these to be inserted, none of them should ever
// show up in the removal list
Debug.Assert(member.unpersisted == false);
// If the collection was cleared, there should be no original members to remove
Debug.Assert(members.Cleared == false);
// Like insertion, we'll remove by SID.
// Build a SID ADsPath
string memberSidPath = GetSidADsPathFromPrincipal(member);
if (memberSidPath == null)
throw new InvalidOperationException(SR.SAMStoreCtxCouldntGetSIDForGroupMember);
GlobalDebug.WriteLineIf(GlobalDebug.Info, "SAMStoreCtx", "UpdateGroupMembership: removing {0}", memberSidPath);
// Remove the member from the group
iADsGroup.Remove(memberSidPath);
}
}
catch (System.Runtime.InteropServices.COMException e)
{
GlobalDebug.WriteLineIf(GlobalDebug.Error,
"SAMStoreCtx",
"UpdateGroupMembership: caught COMException, message={0}, code={1}",
e.Message,
e.ErrorCode);
// ADSI threw an exception trying to update the group membership
throw ExceptionHelper.GetExceptionFromCOMException(e);
}
}
private static string GetSidADsPathFromPrincipal(Principal p)
{
Debug.Assert(p.unpersisted == false);
// Get the member's SID from its Security IdentityClaim
SecurityIdentifier Sid = p.Sid;
if (Sid == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn, "SAMStoreCtx", "GetSidADsPathFromPrincipal: no SID");
return null;
}
string sddlSid = Sid.ToString();
if (sddlSid == null)
{
GlobalDebug.WriteLineIf(GlobalDebug.Warn,
"SAMStoreCtx",
"GetSidADsPathFromPrincipal: Couldn't convert to SDDL ({0})",
Sid.ToString());
return null;
}
// Build a SID ADsPath
return @"WinNT://" + sddlSid;
}
}
}
// #endif // PAPI_REGSAM
| |
// Copyright (c) Microsoft Corporation. All rights reserved
//
// This program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Diagnostics.Eventing;
using System.Collections.ObjectModel;
using Microsoft.Diagnostics.Tracing;
#if TARGET_FRAMEWORK_4_5_OR_HIGHER
using System.Runtime.InteropServices.WindowsRuntime;
#endif
class Program
{
static class EventSourceReflectionProxy
{
public static string ManifestGenerator { get; set; }
#if USE_EVENTSOURCE_REFLECTION
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static Type GetBuiltinEventSourceType()
{
// defining this function allows us to avoid loading the builtin EventSource assembly while
// JIT-ing GetEventSourceBaseIfOverridden when the ManifestGenerator is *not* "builtin"
return typeof(Microsoft.Diagnostics.Tracing.EventSource);
}
private static Type GetEventSourceBaseIfOverridden()
{
Type result = null;
if (string.IsNullOrEmpty(ManifestGenerator))
ManifestGenerator = "builtin";
if (string.Compare(ManifestGenerator, "base", true) == 0)
return null;
else if (string.Compare(ManifestGenerator, "builtin", true) == 0)
return GetBuiltinEventSourceType();
if (!File.Exists(ManifestGenerator))
throw new ApplicationException(string.Format("Failed to find file specified by ManifestGenerator ({0}).", ManifestGenerator));
try
{
var asm = Assembly.LoadFrom(ManifestGenerator);
result = asm.GetTypes().FirstOrDefault(t => t.Name == "EventSource");
}
catch { /* ignore errors */ }
if (result == null)
throw new ApplicationException(string.Format("Failed to find EventSource type in assembly specified by ManifestGenerator ({0}).", ManifestGenerator));
return result;
}
private static Type GetBaseEventSourceType(Type reflectionOnlyDerivedEventSourceType)
{
// If overriding base EventSource return the overriding type
Type loadFromEvtSrc = GetEventSourceBaseIfOverridden();
if (loadFromEvtSrc != null)
return loadFromEvtSrc;
// At this point we have the assemblies defining (a) the custom event source and (b) the base class EventSource
// loaded as reflection-only assemblies. In order to run methods on EventSource we're now loading the base type for
// execution.
Type reflectionOnlyEvtSrc = reflectionOnlyDerivedEventSourceType.BaseType;
// find the "root" non-abstract EventSource. This leads to us ignoring GetName/GenerateManifest methods overridden
// in derived abstract EventSources. We do this in order to avoid attempting to load for execution a user assembly
// that might not be "compatible" with us (e.g. platform specific assembly, or app store assembly)
while (reflectionOnlyEvtSrc.IsAbstract)
reflectionOnlyEvtSrc = reflectionOnlyEvtSrc.BaseType;
Assembly assm = reflectionOnlyEvtSrc.Assembly;
if (assm.ReflectionOnly)
assm = Assembly.LoadFrom(assm.Location);
loadFromEvtSrc = assm.GetType(reflectionOnlyEvtSrc.FullName);
if (loadFromEvtSrc == null)
throw new ApplicationException(string.Format("Failed to load base EventSource type while processing {0}.", reflectionOnlyDerivedEventSourceType.FullName));
return loadFromEvtSrc;
}
#endif
internal static string GetName(Type eventSourceType)
{
#if USE_EVENTSOURCE_REFLECTION
var loadFromEvtSrcType = GetBaseEventSourceType(eventSourceType);
MethodInfo mi = loadFromEvtSrcType.GetMethod("GetName", BindingFlags.Static | BindingFlags.Public,
null, new Type[]{typeof(Type)}, null);
if (mi == null)
throw new ApplicationException(string.Format("Base EventSource type does not implement expected GetName() method (processing {0}).", eventSourceType.FullName));
string name = (string)mi.Invoke(null, new object[] { eventSourceType });
return name;
#else
return EventSource.GetName(eventSourceType);
#endif
}
internal static string GenerateManifest(Type eventSourceType, string manifestDllPath, bool bForce = true)
{
#if USE_EVENTSOURCE_REFLECTION
var loadFromEvtSrcType = GetBaseEventSourceType(eventSourceType);
Type tyGmf = loadFromEvtSrcType.Assembly.GetType(loadFromEvtSrcType.Namespace + ".EventManifestOptions");
string man = null;
MethodInfo mi = null;
if (tyGmf != null)
{
mi = loadFromEvtSrcType.GetMethod("GenerateManifest", BindingFlags.Static | BindingFlags.Public,
null, new Type[] { typeof(Type), typeof(string), tyGmf }, null);
}
if (mi != null)
{
int flags = (bForce ? 0x0b : 0x0f); // Strict + Culture + AllowEventSourceOverride + maybe (OnlyIfRegistrationNeeded)
man = (string)mi.Invoke(null, new object[] { eventSourceType, manifestDllPath, flags });
}
else
{
mi = loadFromEvtSrcType.GetMethod("GenerateManifest", BindingFlags.Static | BindingFlags.Public,
null, new Type[] { typeof(Type), typeof(string) }, null);
if (mi == null)
throw new ApplicationException(string.Format("Base EventSource type does not implement expected GenerateManifest or GenerateManifestEx method", eventSourceType.FullName));
man = (string)mi.Invoke(null, new object[] { eventSourceType, manifestDllPath });
}
return man;
#else
return EventSource.GenerateManifest(eventSourceType, manifestDllPath);
#endif
}
}
static int Main()
{
#if USE_EVENTSOURCE_REFLECTION
// If this app does not take a dependency on a specific EventSource implementation we'll need to use the EventSource
// type that represents the base type of the custom event source that needs to be registered. To accomplish this we
// need to set up a separate domain that has the app base set to the location of the assembly to be registered, and
// the config file set to the config file that might be associated with this assembly, in the case the assembly is
// an EXE. Having the worker domain set up in this way allows for the regular assembly lookup rules to kick in and
// perform the expected lookup the the EventSource-base assembly based on the passed in assembly.
// In the worker domain we load in the "reflection-only" context the assembly passed in as an argument and allow its
// dependency to be loaded as well. Once the base assembly is loaded in the reflection-only context we retrieve its
// location and call LoadFrom() on the assembly in order to get access to the EventSource static methods we need to
// call.
var workerDomainFriendlyName = "eventRegister_workerDomain";
if (AppDomain.CurrentDomain.FriendlyName != workerDomainFriendlyName)
{
// See code:#CommandLineDefinitions for Command line defintions
CommandLine commandLine = new CommandLine();
var ads = new AppDomainSetup();
// ads.PrivateBinPath = Path.GetDirectoryName(Path.GetFullPath(commandLine.DllPath));
ads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;
// ads.ApplicationBase = Path.GetDirectoryName(Path.GetFullPath(commandLine.DllPath));
// var configName = Path.GetFullPath(commandLine.DllPath) + ".config";
// if (Path.GetExtension(commandLine.DllPath) == ".exe" && File.Exists(configName))
// ads.ConfigurationFile = configName;
var workerDom = AppDomain.CreateDomain(workerDomainFriendlyName, null, ads, new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted));
// make sure the worker domain is aware of the additional paths to probe when resolving the EventSource base type
if (commandLine.ReferencePath != null)
workerDom.SetData("ReferencePath", Environment.ExpandEnvironmentVariables(commandLine.ReferencePath));
return workerDom.ExecuteAssembly(typeof(Program).Assembly.Location);
}
else
#endif
return CommandLineUtilities.RunConsoleMainWithExceptionProcessing(delegate
{
// See code:#CommandLineDefinitions for Command line defintions
CommandLine commandLine = new CommandLine();
List<Tuple<string, string>> regDlls;
EventSourceReflectionProxy.ManifestGenerator = commandLine.ManifestGenerator;
switch (commandLine.Command)
{
// Create the XML description in the data directory "will be called
case CommandLine.CommandType.DumpManifest:
var manifests = CreateManifestsFromManagedDll(commandLine.DllPath, commandLine.ManifestPrefix);
if (manifests.Count == 0)
Console.WriteLine("Info: No event source classes " + (commandLine.ForceAll ? "" : "needing registration ") + "found in " + commandLine.DllPath);
break;
case CommandLine.CommandType.CompileManifest:
CompileManifest(commandLine.ManPath, System.IO.Path.ChangeExtension(commandLine.ManPath, ".dll"));
break;
case CommandLine.CommandType.DumpRegDlls:
regDlls = CreateRegDllsFromManagedDll(commandLine.DllPath, commandLine.ForceAll, commandLine.ManifestPrefix);
if (regDlls.Count == 0)
Console.WriteLine("Info: No event source classes " + (commandLine.ForceAll ? "" : "needing registration ") + "found in " + commandLine.DllPath);
break;
case CommandLine.CommandType.Install:
regDlls = RegisterManagedDll(commandLine.DllPath, false, commandLine.ManifestPrefix);
if (regDlls.Count == 0)
Console.WriteLine("Info: No event source classes " + (commandLine.ForceAll ? "" : "needing registration ") + "found in " + commandLine.DllPath);
break;
case CommandLine.CommandType.Uninstall:
regDlls = RegisterManagedDll(commandLine.DllPath, true, commandLine.ManifestPrefix);
if (regDlls.Count == 0)
Console.WriteLine("Info: No event source classes " + (commandLine.ForceAll ? "" : "needing registration ") + "found in " + commandLine.DllPath);
break;
}
return 0;
});
}
// These correspond to command line commands
/// <summary>
/// Create a manifest file for each EventSource in 'managedDll'. The manifest will
/// have the name manifestPrefix + ProviderName + .etwManifest.dll. It is assumed
/// that the manifest DLL name is manifestPrefix + ProviderName + .etwManifest.man
///
/// manifestPrefix and be null, in which case the basename of managedDllPath is used.
/// </summary>
private static List<string> CreateManifestsFromManagedDll(string managedDllPath, string manifestPrefix=null)
{
if (manifestPrefix == null)
manifestPrefix = Path.ChangeExtension(managedDllPath, null);
bool bErrors = false;
List<string> ret = new List<string>();
foreach (var eventSource in GetEventSources(managedDllPath))
{
try
{
string providerName = EventSourceReflectionProxy.GetName(eventSource);
string manifestXmlPath = manifestPrefix + "." + providerName + ".etwManifest.man";
string manifestDllPath = manifestPrefix + "." + providerName + ".etwManifest.dll";
CreateManifest(eventSource, manifestDllPath, manifestXmlPath);
if (!File.Exists(manifestXmlPath))
continue;
Console.WriteLine("Created manifest {0}", manifestXmlPath);
ret.Add(manifestXmlPath);
}
catch (MultiErrorException e)
{
bErrors = true;
Console.WriteLine("Error: " + eventSource.FullName + ": " + e.Message);
foreach (var error in e.Errors)
Console.Error.WriteLine("Error: " + eventSource.FullName + ": " + error);
}
catch (ApplicationException e)
{
bErrors = true;
Console.Error.WriteLine("Error: " + eventSource.FullName + ": " + e.Message);
}
}
if (bErrors)
throw new ApplicationException("Failures encountered creating manifests for EventSources in " + managedDllPath);
return ret;
}
/// <summary>
///
/// </summary>
private static List<Tuple<string, string>> CreateRegDllsFromManagedDll(string managedDllPath, bool bForceAll, string manifestPrefix = null)
{
if (manifestPrefix == null)
manifestPrefix = Path.ChangeExtension(managedDllPath, null);
bool bErrors = false;
List<Tuple<string, string>> ret = new List<Tuple<string, string>>();
foreach (var eventSource in GetEventSources(managedDllPath))
{
try
{
string providerName = EventSourceReflectionProxy.GetName(eventSource);
string manifestXmlPath = manifestPrefix + "." + providerName + ".etwManifest.man";
string manifestDllPath = manifestPrefix + "." + providerName + ".etwManifest.dll";
CreateManifest(eventSource, manifestDllPath, manifestXmlPath, bForceAll);
if (!File.Exists(manifestXmlPath))
continue;
CompileManifest(manifestXmlPath, manifestDllPath);
ret.Add(Tuple.Create(manifestXmlPath, manifestDllPath));
}
catch (MultiErrorException e)
{
bErrors = true;
Console.WriteLine("Error: " + eventSource.FullName + ": " + e.Message);
foreach (var error in e.Errors)
Console.Error.WriteLine("Error: " + eventSource.FullName + ": " + error);
}
catch (ApplicationException e)
{
bErrors = true;
Console.Error.WriteLine("Error: " + eventSource.FullName + ": " + e.Message);
}
}
if (bErrors)
throw new ApplicationException("Failures encountered creating registration DLLs for EventSources in " + managedDllPath);
return ret;
}
/// <summary>
/// Create a manifest file for each EventSource in 'managedDll'. and registers (or unregisters)
/// those manifests with the system.
/// </summary>
private static List<Tuple<string, string>> RegisterManagedDll(string managedDllPath, bool unregister, string manifestPrefix = null)
{
if (manifestPrefix == null)
manifestPrefix = Path.ChangeExtension(managedDllPath, null);
bool bErrors = false;
List<Tuple<string, string>> ret = new List<Tuple<string, string>>();
foreach (var eventSource in GetEventSources(managedDllPath))
{
try
{
string providerName = EventSourceReflectionProxy.GetName(eventSource);
string manifestXmlPath = manifestPrefix + "." + providerName + ".etwManifest.man";
string manifestDllPath = manifestPrefix + "." + providerName + ".etwManifest.dll";
CreateManifest(eventSource, manifestDllPath, manifestXmlPath);
if (!File.Exists(manifestXmlPath))
continue;
CompileManifest(manifestXmlPath, manifestDllPath);
RegisterManifestDll(manifestXmlPath, manifestDllPath, unregister);
ret.Add(Tuple.Create(manifestXmlPath, manifestDllPath));
}
catch (MultiErrorException e)
{
bErrors = true;
Console.Error.WriteLine("Error: " + eventSource.FullName + ": " + e.Message);
foreach (var error in e.Errors)
Console.Error.WriteLine("Error: " + eventSource.FullName + ": " + error);
}
catch (ApplicationException e)
{
bErrors = true;
Console.Error.WriteLine("Error: " + eventSource.FullName + ": " + e.Message);
}
}
if (bErrors)
throw new ApplicationException("Failures encountered during " + (unregister ? "unregistration" : "registration") + " of EventSources in " + managedDllPath);
return ret;
}
/// <summary>
/// Returns true when the "candidate" type derives from a type named "EventSource" through any number
/// of abstract classes
/// </summary>
private static bool IsEventSourceType(Type candidate)
{
// return false for "object" and interfaces
if (candidate.BaseType == null)
return false;
// now go up the inheritance chain until hitting a concrete type ("object" at worse)
do
{
candidate = candidate.BaseType;
}
while (candidate != null && candidate.IsAbstract);
return candidate != null && candidate.Name == "EventSource";
}
// These are helper functions.
/// <summary>
/// Returns a list of types from 'dllPath' that inherit from EventSource
/// </summary>
private static List<Type> GetEventSources(string dllPath)
{
List<Type> ret = new List<Type>();
Assembly assembly;
try
{
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += CurrentDomain_ReflectionOnlyAssemblyResolve;
if (System.Environment.OSVersion.Version >= new Version(6, 2, 0, 0))
{
// on Win8+ support winmd assembly resolution
SubscribeToWinRTReflectionOnlyNamespaceResolve();
}
assembly = Assembly.ReflectionOnlyLoadFrom(dllPath);
foreach (Type type in assembly.GetTypes())
{
if (IsEventSourceType(type))
{
ret.Add(type);
}
}
}
catch (ReflectionTypeLoadException rtle)
{
string msg = rtle.Message;
foreach (var le in rtle.LoaderExceptions)
msg += "\r\nLoaderException:\r\n" + le.ToString();
throw new ApplicationException(msg);
}
catch (Exception e)
{
// Convert to an application exception TODO is this a good idea?
throw new ApplicationException(e.Message);
}
return ret;
}
#region WinRT Reflection-Only Load Handling
#if TARGET_FRAMEWORK_4_5_OR_HIGHER
static void WindowsRuntimeMetadata_ReflectionOnlyNamespaceResolve(object sender, NamespaceResolveEventArgs e)
{
foreach (string s in WindowsRuntimeMetadata.ResolveNamespace(e.NamespaceName, null))
{
e.ResolvedAssemblies.Add(Assembly.ReflectionOnlyLoadFrom(s));
}
}
static void SubscribeToWinRTReflectionOnlyNamespaceResolve()
{
WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve += WindowsRuntimeMetadata_ReflectionOnlyNamespaceResolve;
}
#else
static void WindowsRuntimeMetadata_ReflectionOnlyNamespaceResolve(object sender, object /*NamespaceResolveEventArgs*/ e)
{
// foreach (string s in WindowsRuntimeMetadata.ResolveNamespace(e.NamespaceName, null))
// {
// e.ResolvedAssemblies.Add(Assembly.ReflectionOnlyLoadFrom(s));
// }
Assembly mscorlibAsm = typeof(object).Assembly;
Type twrm = mscorlibAsm.GetType("System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata");
Type tnrea = mscorlibAsm.GetType("System.Runtime.InteropServices.WindowsRuntime.NamespaceResolveEventArgs");
var namespaceName = (string)tnrea.GetProperty("NamespaceName").GetValue(e, null);
var winmdFileNames = (IEnumerable<string>)twrm.InvokeMember("ResolveNamespace",
BindingFlags.InvokeMethod, null, null, new object[] { namespaceName, null });
foreach(var s in winmdFileNames)
{
var assms = (Collection<Assembly>)tnrea.GetProperty("ResolvedAssemblies").GetValue(e, null);
assms.Add(Assembly.ReflectionOnlyLoadFrom(s));
}
}
static void SubscribeToWinRTReflectionOnlyNamespaceResolve()
{
// WindowsRuntimeMetadata.ReflectionOnlyNamespaceResolve += WindowsRuntimeMetadata_ReflectionOnlyNamespaceResolve;
Assembly mscorlibAsm = typeof(object).Assembly;
Type twrm = mscorlibAsm.GetType("System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMetadata");
if (twrm != null)
{
// Get the EventInfo representing the ReflectionOnlyNamespaceResolve event,
// and the type of delegate that handles the event.
EventInfo evRonsr = twrm.GetEvent("ReflectionOnlyNamespaceResolve");
Type tDelegate = evRonsr.EventHandlerType;
// If you already have a method with the correct signature, you can simply get a MethodInfo for it.
MethodInfo miHandler =
typeof(Program).GetMethod("WindowsRuntimeMetadata_ReflectionOnlyNamespaceResolve",
BindingFlags.NonPublic | BindingFlags.Static);
// Create an instance of the delegate. Using the overloads
// of CreateDelegate that take MethodInfo is recommended.
Delegate d = Delegate.CreateDelegate(tDelegate, null, miHandler, true);
// Get the "add" accessor of the event and invoke it late-bound
MethodInfo addHandler = evRonsr.GetAddMethod();
addHandler.Invoke(evRonsr, new object[] { d });
}
}
#endif
#endregion WinRT Reflection-Only Load Handling
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
// ensure we handle retargeting and unification
string name = AppDomain.CurrentDomain.ApplyPolicy(args.Name);
Assembly assm = null;
try
{ assm = Assembly.ReflectionOnlyLoad(name); }
catch
{ }
if (assm != null)
return assm;
string paths = (string)AppDomain.CurrentDomain.GetData("ReferencePath");
if (string.IsNullOrEmpty(paths))
return null;
foreach (var path in paths.Split(';'))
{
try
{ assm = Assembly.ReflectionOnlyLoadFrom(path); }
catch
{ }
if (assm != null && assm.FullName == name)
return assm;
}
return null;
}
/// <summary>
/// Given an eventSourceType, and the name of the DLL that the manifest where the manifest
/// is intended to be placed, create the manifest XML and put it in the file manifestXmlPath
/// </summary>
private static void CreateManifest(Type eventSourceType, string manifestDllPath, string manifestXmlPath, bool bForce = true)
{
try
{
string providerXML = (string)EventSourceReflectionProxy.GenerateManifest(eventSourceType, Path.GetFullPath(manifestDllPath), bForce);
if (!string.IsNullOrEmpty(providerXML))
{
using (TextWriter writer = File.CreateText(manifestXmlPath))
{
writer.Write(providerXML);
}
}
}
catch (TargetInvocationException e)
{
string msg = e.InnerException != null ? e.InnerException.Message : e.Message;
throw new MultiErrorException("Generation of ETW manifest failed", msg);
}
}
/// <summary>
/// Takes an manifest XML in manifestXmlPath and compiles it into a DLL that can
/// be registered using wevtutil placing it in string manifestDllPath
/// </summary>
private static void CompileManifest(string manifestXmlPath, string manifestDllPath)
{
DirectoryUtilities.Clean(WorkingDir);
// Get the tools and put them on my path.
string toolsDir = Path.Combine(WorkingDir, "tools");
Directory.CreateDirectory(toolsDir);
ResourceUtilities.UnpackResourceAsFile(@".\mc.exe", Path.Combine(toolsDir, "mc.exe"));
ResourceUtilities.UnpackResourceAsFile(@".\rc.exe", Path.Combine(toolsDir, "rc.exe"));
ResourceUtilities.UnpackResourceAsFile(@".\rcdll.dll", Path.Combine(toolsDir, "rcdll.dll"));
// put runtimeDir directory on the path so that we have the CSC on the path.
string runtimeDir = RuntimeEnvironment.GetRuntimeDirectory();
Environment.SetEnvironmentVariable("PATH", toolsDir + ";" + runtimeDir + ";" + Environment.GetEnvironmentVariable("PATH"));
// Unpack the winmeta.xml file
string dataDir = Path.Combine(WorkingDir, "data");
Directory.CreateDirectory(dataDir);
ResourceUtilities.UnpackResourceAsFile(@".\winmeta.xml", Path.Combine(dataDir, "winmeta.xml"));
// Compile Xml manifest into a binary reasource, this produces a
// * MANIFEST.rc A text description of the resource which refers to
// * MANIFESTTEMP.Bin The binary form of the manifest
// * MANIFEST_MSG00001.Bin The localized strings from the manifest
Console.WriteLine("Compiling Manifest {0} to ETW binary form.", manifestXmlPath);
try
{
string inputXml = Path.Combine(dataDir, Path.GetFileName(manifestXmlPath));
File.Copy(manifestXmlPath, inputXml);
Command.Run(string.Format("{0} -W \"{1}\" -b \"{2}\"",
Path.Combine(toolsDir, "mc.exe"),
Path.Combine(dataDir, "winmeta.xml"),
inputXml),
new CommandOptions().AddCurrentDirectory(dataDir));
string rcFilePath = Path.ChangeExtension(inputXml, ".rc");
Debug.Assert(File.Exists(rcFilePath));
// Compile the .rc file into a .res file (which is the binary form of everything in the
// .rc file
Command.Run(string.Format("rc \"{0}\"", rcFilePath));
string resFilePath = Path.ChangeExtension(inputXml, ".res");
Debug.Assert(File.Exists(resFilePath));
// Make a dummy c# file
string csFilePath = Path.Combine(dataDir, Path.GetFileNameWithoutExtension(inputXml) + ".cs");
File.WriteAllText(csFilePath, "");
// At this point we have .RES file, we now create a etw manifest dll to hold it a
Console.WriteLine("Creating Manifest DLL to hold binary Manifest at {0}.", manifestDllPath);
FileUtilities.ForceDelete(manifestDllPath);
Command.Run(string.Format("csc /nologo /target:library \"/out:{0}\" \"/win32res:{1}\" \"{2}\"",
manifestDllPath, resFilePath, csFilePath));
Debug.Assert(File.Exists(manifestDllPath));
}
catch (Exception e)
{
throw new ApplicationException(
"ERROR: compilation of the ETW manifest failed.\r\n" +
"File: " + manifestXmlPath + "\r\n" +
"Details:\r\n" +
e.Message);
}
finally
{
DirectoryUtilities.Clean(WorkingDir);
}
}
/// <summary>
/// Registers (or unregisters if unregister=true) manifestDllPath with the OS
/// </summary>
private static void RegisterManifestDll(string manifestXmlPath, string manifestDllPath = null, bool unregister = false)
{
Console.WriteLine("Using wevtutil to {0} manifest {1}", unregister ? "uninstall" : "install", manifestXmlPath);
string resdll = "";
if (!unregister && !string.IsNullOrEmpty(manifestDllPath))
resdll = string.Format(" /rf:\"{0}\" /mf:\"{0}\"", Path.GetFullPath(manifestDllPath));
Command.Run(string.Format("wevtutil {1} \"{0}\"{2}", manifestXmlPath, unregister ? "uninstall-manifest" : "install-manifest", resdll));
}
private static string WorkingDir
{
get
{
if (s_WorkingDir == null)
{
string tempDir = Environment.GetEnvironmentVariable("TEMP");
if (tempDir == null)
tempDir = ".";
s_WorkingDir = Path.Combine(tempDir, "eventRegister" + System.Diagnostics.Process.GetCurrentProcess().Id);
}
return s_WorkingDir;
}
}
private static string s_WorkingDir;
}
class MultiErrorException : ApplicationException
{
public MultiErrorException(string msg, string multilineMsg, string sep = null)
: base(msg)
{
if (sep == null)
sep = Environment.NewLine;
Errors = multilineMsg.Split(new string[] { sep }, int.MaxValue, StringSplitOptions.RemoveEmptyEntries);
}
public string[] Errors { get; private set; }
}
/// <summary>
/// The code:CommandLine class holds the parsed form of all the Command line arguments. It is
/// intialized by handing it the 'args' array for main, and it has a public field for each named argument
/// (eg -debug). See code:#CommandLineDefinitions for the code that defines the arguments (and the help
/// strings associated with them).
///
/// See code:CommandLineParser for more on parser itself.
/// </summary>
class CommandLine
{
public CommandLine()
{
bool usersGuide = false;
CommandLineParser.ParseForConsoleApplication(delegate(CommandLineParser parser)
{
string dllPathHelp = "The path to the DLL containing the Event provider (the class that subclasses EventSource).";
// parser.NoDashOnParameterSets = true;
// #CommandLineDefinitions
parser.DefineOptionalQualifier("ReferencePath", ref ReferencePath, "If specified, use this list of semi-colon separated assemblies to resolve the assembly containing the EventSource base class. Use only if regular resolution does not work adequately.");
parser.DefineOptionalQualifier("ManifestGenerator", ref ManifestGenerator,
"Specifies what code runs to validate and generate the manifest for the user-defined event source classes. " +
"Use \"builtin\" (the default choice) to choose the tool's builtin EventSource. " +
"Use \"base\" to choose the code from the base class of the user-defined event source. " +
"Or use a path name to choose the first \"EventSource\" type from the assembly specified by the path.");
parser.DefineParameterSet("UsersGuide", ref usersGuide, true, "Display the users guide.");
parser.DefineParameterSet("DumpManifest", ref Command, CommandType.DumpManifest, "Just generates the XML manifest for the managed code.");
parser.DefineParameter("AssemblyPath", ref DllPath, dllPathHelp);
parser.DefineOptionalParameter("ManifestXmlPrefix", ref ManifestPrefix, "The file name prefix used to generate output file names for the provider manifests.");
parser.DefineParameterSet("CompileManifest", ref Command, CommandType.CompileManifest, "Just generates the registration DLL from the XML manifest.");
parser.DefineParameter("ManifestXmlPath", ref ManPath, "The path to the XML manifest containing the Event provider");
DllPath = ManPath; // fake it so "Main" can create the secondary app domain
parser.DefineParameterSet("DumpRegDlls", ref Command, CommandType.DumpRegDlls, "Just generates the XML manifest and registration DLL for the managed code.");
parser.DefineOptionalQualifier("ForceAll", ref ForceAll, "If specified, generate manifests and registration DLLs for all EventSource-derived classes, otherwise it generates them only for the classes that need explicit registration.");
parser.DefineParameter("AssemblyPath", ref DllPath, dllPathHelp);
parser.DefineOptionalParameter("ManifestXmlPrefix", ref ManifestPrefix, "The file name prefix used to generate output file names for the provider manifests.");
parser.DefineParameterSet("Uninstall", ref Command, CommandType.Uninstall, "Uninstall all providers defined in the assembly.");
parser.DefineParameter("AssemblyPath", ref DllPath, dllPathHelp);
parser.DefineDefaultParameterSet("Installs managed Event Tracing for Windows (ETW) event providers defined in the assembly.");
parser.DefineParameter("AssemblyPath", ref DllPath, dllPathHelp);
parser.DefineOptionalParameter("ManifestXmlPrefix", ref ManifestPrefix, "The file name prefix used to generate output file names for the provider manifests.");
});
if (usersGuide)
UsersGuide.DisplayConsoleAppUsersGuide("UsersGuide.htm");
}
public enum CommandType
{
Install,
Uninstall,
DumpManifest,
CompileManifest,
DumpRegDlls,
}
public CommandType Command = CommandType.Install;
public string DllPath;
public string ManPath;
public string ManifestPrefix;
public string ReferencePath;
public string ManifestGenerator = "builtin"; // "base", "path_to_assm_containing_EventSource_type"
public bool ForceAll;
};
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: bgs/low/pb/client/connection_service.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Bgs.Protocol.Connection.V1 {
/// <summary>Holder for reflection information generated from bgs/low/pb/client/connection_service.proto</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static partial class ConnectionServiceReflection {
#region Descriptor
/// <summary>File descriptor for bgs/low/pb/client/connection_service.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ConnectionServiceReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CipiZ3MvbG93L3BiL2NsaWVudC9jb25uZWN0aW9uX3NlcnZpY2UucHJvdG8S",
"GmJncy5wcm90b2NvbC5jb25uZWN0aW9uLnYxGixiZ3MvbG93L3BiL2NsaWVu",
"dC9jb250ZW50X2hhbmRsZV90eXBlcy5wcm90bxohYmdzL2xvdy9wYi9jbGll",
"bnQvcnBjX3R5cGVzLnByb3RvIpUBCg5Db25uZWN0UmVxdWVzdBIqCgljbGll",
"bnRfaWQYASABKAsyFy5iZ3MucHJvdG9jb2wuUHJvY2Vzc0lkEj0KDGJpbmRf",
"cmVxdWVzdBgCIAEoCzInLmJncy5wcm90b2NvbC5jb25uZWN0aW9uLnYxLkJp",
"bmRSZXF1ZXN0EhgKEHVzZV9iaW5kbGVzc19ycGMYAyABKAgiVwogQ29ubmVj",
"dGlvbk1ldGVyaW5nQ29udGVudEhhbmRsZXMSMwoOY29udGVudF9oYW5kbGUY",
"ASADKAsyGy5iZ3MucHJvdG9jb2wuQ29udGVudEhhbmRsZSKtAwoPQ29ubmVj",
"dFJlc3BvbnNlEioKCXNlcnZlcl9pZBgBIAEoCzIXLmJncy5wcm90b2NvbC5Q",
"cm9jZXNzSWQSKgoJY2xpZW50X2lkGAIgASgLMhcuYmdzLnByb3RvY29sLlBy",
"b2Nlc3NJZBITCgtiaW5kX3Jlc3VsdBgDIAEoDRI/Cg1iaW5kX3Jlc3BvbnNl",
"GAQgASgLMiguYmdzLnByb3RvY29sLmNvbm5lY3Rpb24udjEuQmluZFJlc3Bv",
"bnNlEloKFGNvbnRlbnRfaGFuZGxlX2FycmF5GAUgASgLMjwuYmdzLnByb3Rv",
"Y29sLmNvbm5lY3Rpb24udjEuQ29ubmVjdGlvbk1ldGVyaW5nQ29udGVudEhh",
"bmRsZXMSEwoLc2VydmVyX3RpbWUYBiABKAQSGAoQdXNlX2JpbmRsZXNzX3Jw",
"YxgHIAEoCBJhChtiaW5hcnlfY29udGVudF9oYW5kbGVfYXJyYXkYCCABKAsy",
"PC5iZ3MucHJvdG9jb2wuY29ubmVjdGlvbi52MS5Db25uZWN0aW9uTWV0ZXJp",
"bmdDb250ZW50SGFuZGxlcyIoCgxCb3VuZFNlcnZpY2USDAoEaGFzaBgBIAEo",
"BxIKCgJpZBgCIAEoDSKYAgoLQmluZFJlcXVlc3QSLgogZGVwcmVjYXRlZF9p",
"bXBvcnRlZF9zZXJ2aWNlX2hhc2gYASADKAdCBBABGAESUQobZGVwcmVjYXRl",
"ZF9leHBvcnRlZF9zZXJ2aWNlGAIgAygLMiguYmdzLnByb3RvY29sLmNvbm5l",
"Y3Rpb24udjEuQm91bmRTZXJ2aWNlQgIYARJCChBleHBvcnRlZF9zZXJ2aWNl",
"GAMgAygLMiguYmdzLnByb3RvY29sLmNvbm5lY3Rpb24udjEuQm91bmRTZXJ2",
"aWNlEkIKEGltcG9ydGVkX3NlcnZpY2UYBCADKAsyKC5iZ3MucHJvdG9jb2wu",
"Y29ubmVjdGlvbi52MS5Cb3VuZFNlcnZpY2UiMQoMQmluZFJlc3BvbnNlEiEK",
"E2ltcG9ydGVkX3NlcnZpY2VfaWQYASADKA1CBBABGAEiQgoLRWNob1JlcXVl",
"c3QSDAoEdGltZRgBIAEoBhIUCgxuZXR3b3JrX29ubHkYAiABKAgSDwoHcGF5",
"bG9hZBgDIAEoDCItCgxFY2hvUmVzcG9uc2USDAoEdGltZRgBIAEoBhIPCgdw",
"YXlsb2FkGAIgASgMIicKEURpc2Nvbm5lY3RSZXF1ZXN0EhIKCmVycm9yX2Nv",
"ZGUYASABKA0iPAoWRGlzY29ubmVjdE5vdGlmaWNhdGlvbhISCgplcnJvcl9j",
"b2RlGAEgASgNEg4KBnJlYXNvbhgCIAEoCSIQCg5FbmNyeXB0UmVxdWVzdDKD",
"BQoRQ29ubmVjdGlvblNlcnZpY2USYgoHQ29ubmVjdBIqLmJncy5wcm90b2Nv",
"bC5jb25uZWN0aW9uLnYxLkNvbm5lY3RSZXF1ZXN0GisuYmdzLnByb3RvY29s",
"LmNvbm5lY3Rpb24udjEuQ29ubmVjdFJlc3BvbnNlEl4KBEJpbmQSJy5iZ3Mu",
"cHJvdG9jb2wuY29ubmVjdGlvbi52MS5CaW5kUmVxdWVzdBooLmJncy5wcm90",
"b2NvbC5jb25uZWN0aW9uLnYxLkJpbmRSZXNwb25zZSIDiAIBElkKBEVjaG8S",
"Jy5iZ3MucHJvdG9jb2wuY29ubmVjdGlvbi52MS5FY2hvUmVxdWVzdBooLmJn",
"cy5wcm90b2NvbC5jb25uZWN0aW9uLnYxLkVjaG9SZXNwb25zZRJgCg9Gb3Jj",
"ZURpc2Nvbm5lY3QSMi5iZ3MucHJvdG9jb2wuY29ubmVjdGlvbi52MS5EaXNj",
"b25uZWN0Tm90aWZpY2F0aW9uGhkuYmdzLnByb3RvY29sLk5PX1JFU1BPTlNF",
"EjwKCUtlZXBBbGl2ZRIULmJncy5wcm90b2NvbC5Ob0RhdGEaGS5iZ3MucHJv",
"dG9jb2wuTk9fUkVTUE9OU0USUAoHRW5jcnlwdBIqLmJncy5wcm90b2NvbC5j",
"b25uZWN0aW9uLnYxLkVuY3J5cHRSZXF1ZXN0GhQuYmdzLnByb3RvY29sLk5v",
"RGF0YSIDiAIBEl0KEVJlcXVlc3REaXNjb25uZWN0Ei0uYmdzLnByb3RvY29s",
"LmNvbm5lY3Rpb24udjEuRGlzY29ubmVjdFJlcXVlc3QaGS5iZ3MucHJvdG9j",
"b2wuTk9fUkVTUE9OU0VCPQobYm5ldC5wcm90b2NvbC5jb25uZWN0aW9uLnYx",
"QhZDb25uZWN0aW9uU2VydmljZVByb3RvSAKAAQCIAQFiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Bgs.Protocol.ContentHandleTypesReflection.Descriptor, global::Bgs.Protocol.RpcTypesReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.ConnectRequest), global::Bgs.Protocol.Connection.V1.ConnectRequest.Parser, new[]{ "ClientId", "BindRequest", "UseBindlessRpc" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles), global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles.Parser, new[]{ "ContentHandle" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.ConnectResponse), global::Bgs.Protocol.Connection.V1.ConnectResponse.Parser, new[]{ "ServerId", "ClientId", "BindResult", "BindResponse", "ContentHandleArray", "ServerTime", "UseBindlessRpc", "BinaryContentHandleArray" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.BoundService), global::Bgs.Protocol.Connection.V1.BoundService.Parser, new[]{ "Hash", "Id" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.BindRequest), global::Bgs.Protocol.Connection.V1.BindRequest.Parser, new[]{ "DeprecatedImportedServiceHash", "DeprecatedExportedService", "ExportedService", "ImportedService" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.BindResponse), global::Bgs.Protocol.Connection.V1.BindResponse.Parser, new[]{ "ImportedServiceId" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.EchoRequest), global::Bgs.Protocol.Connection.V1.EchoRequest.Parser, new[]{ "Time", "NetworkOnly", "Payload" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.EchoResponse), global::Bgs.Protocol.Connection.V1.EchoResponse.Parser, new[]{ "Time", "Payload" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.DisconnectRequest), global::Bgs.Protocol.Connection.V1.DisconnectRequest.Parser, new[]{ "ErrorCode" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.DisconnectNotification), global::Bgs.Protocol.Connection.V1.DisconnectNotification.Parser, new[]{ "ErrorCode", "Reason" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Bgs.Protocol.Connection.V1.EncryptRequest), global::Bgs.Protocol.Connection.V1.EncryptRequest.Parser, null, null, null, null)
}));
}
#endregion
}
#region Messages
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ConnectRequest : pb::IMessage<ConnectRequest> {
private static readonly pb::MessageParser<ConnectRequest> _parser = new pb::MessageParser<ConnectRequest>(() => new ConnectRequest());
public static pb::MessageParser<ConnectRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[0]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ConnectRequest() {
OnConstruction();
}
partial void OnConstruction();
public ConnectRequest(ConnectRequest other) : this() {
ClientId = other.clientId_ != null ? other.ClientId.Clone() : null;
BindRequest = other.bindRequest_ != null ? other.BindRequest.Clone() : null;
useBindlessRpc_ = other.useBindlessRpc_;
}
public ConnectRequest Clone() {
return new ConnectRequest(this);
}
/// <summary>Field number for the "client_id" field.</summary>
public const int ClientIdFieldNumber = 1;
private global::Bgs.Protocol.ProcessId clientId_;
public global::Bgs.Protocol.ProcessId ClientId {
get { return clientId_; }
set {
clientId_ = value;
}
}
/// <summary>Field number for the "bind_request" field.</summary>
public const int BindRequestFieldNumber = 2;
private global::Bgs.Protocol.Connection.V1.BindRequest bindRequest_;
public global::Bgs.Protocol.Connection.V1.BindRequest BindRequest {
get { return bindRequest_; }
set {
bindRequest_ = value;
}
}
/// <summary>Field number for the "use_bindless_rpc" field.</summary>
public const int UseBindlessRpcFieldNumber = 3;
private bool useBindlessRpc_;
public bool UseBindlessRpc {
get { return useBindlessRpc_; }
set {
useBindlessRpc_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as ConnectRequest);
}
public bool Equals(ConnectRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(ClientId, other.ClientId)) return false;
if (!object.Equals(BindRequest, other.BindRequest)) return false;
if (UseBindlessRpc != other.UseBindlessRpc) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (clientId_ != null) hash ^= ClientId.GetHashCode();
if (bindRequest_ != null) hash ^= BindRequest.GetHashCode();
if (UseBindlessRpc != false) hash ^= UseBindlessRpc.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (clientId_ != null) {
output.WriteRawTag(10);
output.WriteMessage(ClientId);
}
if (bindRequest_ != null) {
output.WriteRawTag(18);
output.WriteMessage(BindRequest);
}
if (UseBindlessRpc != false) {
output.WriteRawTag(24);
output.WriteBool(UseBindlessRpc);
}
}
public int CalculateSize() {
int size = 0;
if (clientId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ClientId);
}
if (bindRequest_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BindRequest);
}
if (UseBindlessRpc != false) {
size += 1 + 1;
}
return size;
}
public void MergeFrom(ConnectRequest other) {
if (other == null) {
return;
}
if (other.clientId_ != null) {
if (clientId_ == null) {
clientId_ = new global::Bgs.Protocol.ProcessId();
}
ClientId.MergeFrom(other.ClientId);
}
if (other.bindRequest_ != null) {
if (bindRequest_ == null) {
bindRequest_ = new global::Bgs.Protocol.Connection.V1.BindRequest();
}
BindRequest.MergeFrom(other.BindRequest);
}
if (other.UseBindlessRpc != false) {
UseBindlessRpc = other.UseBindlessRpc;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (clientId_ == null) {
clientId_ = new global::Bgs.Protocol.ProcessId();
}
input.ReadMessage(clientId_);
break;
}
case 18: {
if (bindRequest_ == null) {
bindRequest_ = new global::Bgs.Protocol.Connection.V1.BindRequest();
}
input.ReadMessage(bindRequest_);
break;
}
case 24: {
UseBindlessRpc = input.ReadBool();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ConnectionMeteringContentHandles : pb::IMessage<ConnectionMeteringContentHandles> {
private static readonly pb::MessageParser<ConnectionMeteringContentHandles> _parser = new pb::MessageParser<ConnectionMeteringContentHandles>(() => new ConnectionMeteringContentHandles());
public static pb::MessageParser<ConnectionMeteringContentHandles> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[1]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ConnectionMeteringContentHandles() {
OnConstruction();
}
partial void OnConstruction();
public ConnectionMeteringContentHandles(ConnectionMeteringContentHandles other) : this() {
contentHandle_ = other.contentHandle_.Clone();
}
public ConnectionMeteringContentHandles Clone() {
return new ConnectionMeteringContentHandles(this);
}
/// <summary>Field number for the "content_handle" field.</summary>
public const int ContentHandleFieldNumber = 1;
private static readonly pb::FieldCodec<global::Bgs.Protocol.ContentHandle> _repeated_contentHandle_codec
= pb::FieldCodec.ForMessage(10, global::Bgs.Protocol.ContentHandle.Parser);
private readonly pbc::RepeatedField<global::Bgs.Protocol.ContentHandle> contentHandle_ = new pbc::RepeatedField<global::Bgs.Protocol.ContentHandle>();
public pbc::RepeatedField<global::Bgs.Protocol.ContentHandle> ContentHandle {
get { return contentHandle_; }
}
public override bool Equals(object other) {
return Equals(other as ConnectionMeteringContentHandles);
}
public bool Equals(ConnectionMeteringContentHandles other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!contentHandle_.Equals(other.contentHandle_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= contentHandle_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
contentHandle_.WriteTo(output, _repeated_contentHandle_codec);
}
public int CalculateSize() {
int size = 0;
size += contentHandle_.CalculateSize(_repeated_contentHandle_codec);
return size;
}
public void MergeFrom(ConnectionMeteringContentHandles other) {
if (other == null) {
return;
}
contentHandle_.Add(other.contentHandle_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
contentHandle_.AddEntriesFrom(input, _repeated_contentHandle_codec);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class ConnectResponse : pb::IMessage<ConnectResponse> {
private static readonly pb::MessageParser<ConnectResponse> _parser = new pb::MessageParser<ConnectResponse>(() => new ConnectResponse());
public static pb::MessageParser<ConnectResponse> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[2]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public ConnectResponse() {
OnConstruction();
}
partial void OnConstruction();
public ConnectResponse(ConnectResponse other) : this() {
ServerId = other.serverId_ != null ? other.ServerId.Clone() : null;
ClientId = other.clientId_ != null ? other.ClientId.Clone() : null;
bindResult_ = other.bindResult_;
BindResponse = other.bindResponse_ != null ? other.BindResponse.Clone() : null;
ContentHandleArray = other.contentHandleArray_ != null ? other.ContentHandleArray.Clone() : null;
serverTime_ = other.serverTime_;
useBindlessRpc_ = other.useBindlessRpc_;
BinaryContentHandleArray = other.binaryContentHandleArray_ != null ? other.BinaryContentHandleArray.Clone() : null;
}
public ConnectResponse Clone() {
return new ConnectResponse(this);
}
/// <summary>Field number for the "server_id" field.</summary>
public const int ServerIdFieldNumber = 1;
private global::Bgs.Protocol.ProcessId serverId_;
public global::Bgs.Protocol.ProcessId ServerId {
get { return serverId_; }
set {
serverId_ = value;
}
}
/// <summary>Field number for the "client_id" field.</summary>
public const int ClientIdFieldNumber = 2;
private global::Bgs.Protocol.ProcessId clientId_;
public global::Bgs.Protocol.ProcessId ClientId {
get { return clientId_; }
set {
clientId_ = value;
}
}
/// <summary>Field number for the "bind_result" field.</summary>
public const int BindResultFieldNumber = 3;
private uint bindResult_;
public uint BindResult {
get { return bindResult_; }
set {
bindResult_ = value;
}
}
/// <summary>Field number for the "bind_response" field.</summary>
public const int BindResponseFieldNumber = 4;
private global::Bgs.Protocol.Connection.V1.BindResponse bindResponse_;
public global::Bgs.Protocol.Connection.V1.BindResponse BindResponse {
get { return bindResponse_; }
set {
bindResponse_ = value;
}
}
/// <summary>Field number for the "content_handle_array" field.</summary>
public const int ContentHandleArrayFieldNumber = 5;
private global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles contentHandleArray_;
public global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles ContentHandleArray {
get { return contentHandleArray_; }
set {
contentHandleArray_ = value;
}
}
/// <summary>Field number for the "server_time" field.</summary>
public const int ServerTimeFieldNumber = 6;
private ulong serverTime_;
public ulong ServerTime {
get { return serverTime_; }
set {
serverTime_ = value;
}
}
/// <summary>Field number for the "use_bindless_rpc" field.</summary>
public const int UseBindlessRpcFieldNumber = 7;
private bool useBindlessRpc_;
public bool UseBindlessRpc {
get { return useBindlessRpc_; }
set {
useBindlessRpc_ = value;
}
}
/// <summary>Field number for the "binary_content_handle_array" field.</summary>
public const int BinaryContentHandleArrayFieldNumber = 8;
private global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles binaryContentHandleArray_;
public global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles BinaryContentHandleArray {
get { return binaryContentHandleArray_; }
set {
binaryContentHandleArray_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as ConnectResponse);
}
public bool Equals(ConnectResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (!object.Equals(ServerId, other.ServerId)) return false;
if (!object.Equals(ClientId, other.ClientId)) return false;
if (BindResult != other.BindResult) return false;
if (!object.Equals(BindResponse, other.BindResponse)) return false;
if (!object.Equals(ContentHandleArray, other.ContentHandleArray)) return false;
if (ServerTime != other.ServerTime) return false;
if (UseBindlessRpc != other.UseBindlessRpc) return false;
if (!object.Equals(BinaryContentHandleArray, other.BinaryContentHandleArray)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= ServerId.GetHashCode();
if (clientId_ != null) hash ^= ClientId.GetHashCode();
if (BindResult != 0) hash ^= BindResult.GetHashCode();
if (bindResponse_ != null) hash ^= BindResponse.GetHashCode();
if (contentHandleArray_ != null) hash ^= ContentHandleArray.GetHashCode();
if (ServerTime != 0UL) hash ^= ServerTime.GetHashCode();
if (UseBindlessRpc != false) hash ^= UseBindlessRpc.GetHashCode();
if (binaryContentHandleArray_ != null) hash ^= BinaryContentHandleArray.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
{
output.WriteRawTag(10);
output.WriteMessage(ServerId);
}
if (clientId_ != null) {
output.WriteRawTag(18);
output.WriteMessage(ClientId);
}
if (BindResult != 0) {
output.WriteRawTag(24);
output.WriteUInt32(BindResult);
}
if (bindResponse_ != null) {
output.WriteRawTag(34);
output.WriteMessage(BindResponse);
}
if (contentHandleArray_ != null) {
output.WriteRawTag(42);
output.WriteMessage(ContentHandleArray);
}
if (ServerTime != 0UL) {
output.WriteRawTag(48);
output.WriteUInt64(ServerTime);
}
if (UseBindlessRpc != false) {
output.WriteRawTag(56);
output.WriteBool(UseBindlessRpc);
}
if (binaryContentHandleArray_ != null) {
output.WriteRawTag(66);
output.WriteMessage(BinaryContentHandleArray);
}
}
public int CalculateSize() {
int size = 0;
{
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ServerId);
}
if (clientId_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ClientId);
}
if (BindResult != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(BindResult);
}
if (bindResponse_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BindResponse);
}
if (contentHandleArray_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ContentHandleArray);
}
if (ServerTime != 0UL) {
size += 1 + pb::CodedOutputStream.ComputeUInt64Size(ServerTime);
}
if (UseBindlessRpc != false) {
size += 1 + 1;
}
if (binaryContentHandleArray_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(BinaryContentHandleArray);
}
return size;
}
public void MergeFrom(ConnectResponse other) {
if (other == null) {
return;
}
if (other.serverId_ != null) {
if (serverId_ == null) {
serverId_ = new global::Bgs.Protocol.ProcessId();
}
ServerId.MergeFrom(other.ServerId);
}
if (other.clientId_ != null) {
if (clientId_ == null) {
clientId_ = new global::Bgs.Protocol.ProcessId();
}
ClientId.MergeFrom(other.ClientId);
}
if (other.BindResult != 0) {
BindResult = other.BindResult;
}
if (other.bindResponse_ != null) {
if (bindResponse_ == null) {
bindResponse_ = new global::Bgs.Protocol.Connection.V1.BindResponse();
}
BindResponse.MergeFrom(other.BindResponse);
}
if (other.contentHandleArray_ != null) {
if (contentHandleArray_ == null) {
contentHandleArray_ = new global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles();
}
ContentHandleArray.MergeFrom(other.ContentHandleArray);
}
if (other.ServerTime != 0UL) {
ServerTime = other.ServerTime;
}
if (other.UseBindlessRpc != false) {
UseBindlessRpc = other.UseBindlessRpc;
}
if (other.binaryContentHandleArray_ != null) {
if (binaryContentHandleArray_ == null) {
binaryContentHandleArray_ = new global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles();
}
BinaryContentHandleArray.MergeFrom(other.BinaryContentHandleArray);
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
if (serverId_ == null) {
serverId_ = new global::Bgs.Protocol.ProcessId();
}
input.ReadMessage(serverId_);
break;
}
case 18: {
if (clientId_ == null) {
clientId_ = new global::Bgs.Protocol.ProcessId();
}
input.ReadMessage(clientId_);
break;
}
case 24: {
BindResult = input.ReadUInt32();
break;
}
case 34: {
if (bindResponse_ == null) {
bindResponse_ = new global::Bgs.Protocol.Connection.V1.BindResponse();
}
input.ReadMessage(bindResponse_);
break;
}
case 42: {
if (contentHandleArray_ == null) {
contentHandleArray_ = new global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles();
}
input.ReadMessage(contentHandleArray_);
break;
}
case 48: {
ServerTime = input.ReadUInt64();
break;
}
case 56: {
UseBindlessRpc = input.ReadBool();
break;
}
case 66: {
if (binaryContentHandleArray_ == null) {
binaryContentHandleArray_ = new global::Bgs.Protocol.Connection.V1.ConnectionMeteringContentHandles();
}
input.ReadMessage(binaryContentHandleArray_);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class BoundService : pb::IMessage<BoundService> {
private static readonly pb::MessageParser<BoundService> _parser = new pb::MessageParser<BoundService>(() => new BoundService());
public static pb::MessageParser<BoundService> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[3]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public BoundService() {
OnConstruction();
}
partial void OnConstruction();
public BoundService(BoundService other) : this() {
hash_ = other.hash_;
id_ = other.id_;
}
public BoundService Clone() {
return new BoundService(this);
}
/// <summary>Field number for the "hash" field.</summary>
public const int HashFieldNumber = 1;
private uint hash_;
public uint Hash {
get { return hash_; }
set {
hash_ = value;
}
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 2;
private uint id_;
public uint Id {
get { return id_; }
set {
id_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as BoundService);
}
public bool Equals(BoundService other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Hash != other.Hash) return false;
if (Id != other.Id) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= Hash.GetHashCode();
hash ^= Id.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
{
output.WriteRawTag(13);
output.WriteFixed32(Hash);
}
{
output.WriteRawTag(16);
output.WriteUInt32(Id);
}
}
public int CalculateSize() {
int size = 0;
{
size += 1 + 4;
}
{
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(Id);
}
return size;
}
public void MergeFrom(BoundService other) {
if (other == null) {
return;
}
if (other.Hash != 0) {
Hash = other.Hash;
}
if (other.Id != 0) {
Id = other.Id;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 13: {
Hash = input.ReadFixed32();
break;
}
case 16: {
Id = input.ReadUInt32();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class BindRequest : pb::IMessage<BindRequest> {
private static readonly pb::MessageParser<BindRequest> _parser = new pb::MessageParser<BindRequest>(() => new BindRequest());
public static pb::MessageParser<BindRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[4]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public BindRequest() {
OnConstruction();
}
partial void OnConstruction();
public BindRequest(BindRequest other) : this() {
deprecatedImportedServiceHash_ = other.deprecatedImportedServiceHash_.Clone();
deprecatedExportedService_ = other.deprecatedExportedService_.Clone();
exportedService_ = other.exportedService_.Clone();
importedService_ = other.importedService_.Clone();
}
public BindRequest Clone() {
return new BindRequest(this);
}
/// <summary>Field number for the "deprecated_imported_service_hash" field.</summary>
public const int DeprecatedImportedServiceHashFieldNumber = 1;
private static readonly pb::FieldCodec<uint> _repeated_deprecatedImportedServiceHash_codec
= pb::FieldCodec.ForFixed32(10);
private readonly pbc::RepeatedField<uint> deprecatedImportedServiceHash_ = new pbc::RepeatedField<uint>();
[global::System.ObsoleteAttribute()]
public pbc::RepeatedField<uint> DeprecatedImportedServiceHash {
get { return deprecatedImportedServiceHash_; }
}
/// <summary>Field number for the "deprecated_exported_service" field.</summary>
public const int DeprecatedExportedServiceFieldNumber = 2;
private static readonly pb::FieldCodec<global::Bgs.Protocol.Connection.V1.BoundService> _repeated_deprecatedExportedService_codec
= pb::FieldCodec.ForMessage(18, global::Bgs.Protocol.Connection.V1.BoundService.Parser);
private readonly pbc::RepeatedField<global::Bgs.Protocol.Connection.V1.BoundService> deprecatedExportedService_ = new pbc::RepeatedField<global::Bgs.Protocol.Connection.V1.BoundService>();
[global::System.ObsoleteAttribute()]
public pbc::RepeatedField<global::Bgs.Protocol.Connection.V1.BoundService> DeprecatedExportedService {
get { return deprecatedExportedService_; }
}
/// <summary>Field number for the "exported_service" field.</summary>
public const int ExportedServiceFieldNumber = 3;
private static readonly pb::FieldCodec<global::Bgs.Protocol.Connection.V1.BoundService> _repeated_exportedService_codec
= pb::FieldCodec.ForMessage(26, global::Bgs.Protocol.Connection.V1.BoundService.Parser);
private readonly pbc::RepeatedField<global::Bgs.Protocol.Connection.V1.BoundService> exportedService_ = new pbc::RepeatedField<global::Bgs.Protocol.Connection.V1.BoundService>();
public pbc::RepeatedField<global::Bgs.Protocol.Connection.V1.BoundService> ExportedService {
get { return exportedService_; }
}
/// <summary>Field number for the "imported_service" field.</summary>
public const int ImportedServiceFieldNumber = 4;
private static readonly pb::FieldCodec<global::Bgs.Protocol.Connection.V1.BoundService> _repeated_importedService_codec
= pb::FieldCodec.ForMessage(34, global::Bgs.Protocol.Connection.V1.BoundService.Parser);
private readonly pbc::RepeatedField<global::Bgs.Protocol.Connection.V1.BoundService> importedService_ = new pbc::RepeatedField<global::Bgs.Protocol.Connection.V1.BoundService>();
public pbc::RepeatedField<global::Bgs.Protocol.Connection.V1.BoundService> ImportedService {
get { return importedService_; }
}
public override bool Equals(object other) {
return Equals(other as BindRequest);
}
public bool Equals(BindRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!deprecatedImportedServiceHash_.Equals(other.deprecatedImportedServiceHash_)) return false;
if(!deprecatedExportedService_.Equals(other.deprecatedExportedService_)) return false;
if(!exportedService_.Equals(other.exportedService_)) return false;
if(!importedService_.Equals(other.importedService_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= deprecatedImportedServiceHash_.GetHashCode();
hash ^= deprecatedExportedService_.GetHashCode();
hash ^= exportedService_.GetHashCode();
hash ^= importedService_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
deprecatedImportedServiceHash_.WriteTo(output, _repeated_deprecatedImportedServiceHash_codec);
deprecatedExportedService_.WriteTo(output, _repeated_deprecatedExportedService_codec);
exportedService_.WriteTo(output, _repeated_exportedService_codec);
importedService_.WriteTo(output, _repeated_importedService_codec);
}
public int CalculateSize() {
int size = 0;
size += deprecatedImportedServiceHash_.CalculateSize(_repeated_deprecatedImportedServiceHash_codec);
size += deprecatedExportedService_.CalculateSize(_repeated_deprecatedExportedService_codec);
size += exportedService_.CalculateSize(_repeated_exportedService_codec);
size += importedService_.CalculateSize(_repeated_importedService_codec);
return size;
}
public void MergeFrom(BindRequest other) {
if (other == null) {
return;
}
deprecatedImportedServiceHash_.Add(other.deprecatedImportedServiceHash_);
deprecatedExportedService_.Add(other.deprecatedExportedService_);
exportedService_.Add(other.exportedService_);
importedService_.Add(other.importedService_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10:
case 13: {
deprecatedImportedServiceHash_.AddEntriesFrom(input, _repeated_deprecatedImportedServiceHash_codec);
break;
}
case 18: {
deprecatedExportedService_.AddEntriesFrom(input, _repeated_deprecatedExportedService_codec);
break;
}
case 26: {
exportedService_.AddEntriesFrom(input, _repeated_exportedService_codec);
break;
}
case 34: {
importedService_.AddEntriesFrom(input, _repeated_importedService_codec);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class BindResponse : pb::IMessage<BindResponse> {
private static readonly pb::MessageParser<BindResponse> _parser = new pb::MessageParser<BindResponse>(() => new BindResponse());
public static pb::MessageParser<BindResponse> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[5]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public BindResponse() {
OnConstruction();
}
partial void OnConstruction();
public BindResponse(BindResponse other) : this() {
importedServiceId_ = other.importedServiceId_.Clone();
}
public BindResponse Clone() {
return new BindResponse(this);
}
/// <summary>Field number for the "imported_service_id" field.</summary>
public const int ImportedServiceIdFieldNumber = 1;
private static readonly pb::FieldCodec<uint> _repeated_importedServiceId_codec
= pb::FieldCodec.ForUInt32(10);
private readonly pbc::RepeatedField<uint> importedServiceId_ = new pbc::RepeatedField<uint>();
[global::System.ObsoleteAttribute()]
public pbc::RepeatedField<uint> ImportedServiceId {
get { return importedServiceId_; }
}
public override bool Equals(object other) {
return Equals(other as BindResponse);
}
public bool Equals(BindResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if(!importedServiceId_.Equals(other.importedServiceId_)) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= importedServiceId_.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
importedServiceId_.WriteTo(output, _repeated_importedServiceId_codec);
}
public int CalculateSize() {
int size = 0;
size += importedServiceId_.CalculateSize(_repeated_importedServiceId_codec);
return size;
}
public void MergeFrom(BindResponse other) {
if (other == null) {
return;
}
importedServiceId_.Add(other.importedServiceId_);
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10:
case 8: {
importedServiceId_.AddEntriesFrom(input, _repeated_importedServiceId_codec);
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class EchoRequest : pb::IMessage<EchoRequest> {
private static readonly pb::MessageParser<EchoRequest> _parser = new pb::MessageParser<EchoRequest>(() => new EchoRequest());
public static pb::MessageParser<EchoRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[6]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public EchoRequest() {
OnConstruction();
}
partial void OnConstruction();
public EchoRequest(EchoRequest other) : this() {
time_ = other.time_;
networkOnly_ = other.networkOnly_;
payload_ = other.payload_;
}
public EchoRequest Clone() {
return new EchoRequest(this);
}
/// <summary>Field number for the "time" field.</summary>
public const int TimeFieldNumber = 1;
private ulong time_;
public ulong Time {
get { return time_; }
set {
time_ = value;
}
}
/// <summary>Field number for the "network_only" field.</summary>
public const int NetworkOnlyFieldNumber = 2;
private bool networkOnly_;
public bool NetworkOnly {
get { return networkOnly_; }
set {
networkOnly_ = value;
}
}
/// <summary>Field number for the "payload" field.</summary>
public const int PayloadFieldNumber = 3;
private pb::ByteString payload_ = pb::ByteString.Empty;
public pb::ByteString Payload {
get { return payload_; }
set {
payload_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as EchoRequest);
}
public bool Equals(EchoRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Time != other.Time) return false;
if (NetworkOnly != other.NetworkOnly) return false;
if (Payload != other.Payload) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Time != 0UL) hash ^= Time.GetHashCode();
if (NetworkOnly != false) hash ^= NetworkOnly.GetHashCode();
if (Payload.Length != 0) hash ^= Payload.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Time != 0UL) {
output.WriteRawTag(9);
output.WriteFixed64(Time);
}
if (NetworkOnly != false) {
output.WriteRawTag(16);
output.WriteBool(NetworkOnly);
}
if (Payload.Length != 0) {
output.WriteRawTag(26);
output.WriteBytes(Payload);
}
}
public int CalculateSize() {
int size = 0;
if (Time != 0UL) {
size += 1 + 8;
}
if (NetworkOnly != false) {
size += 1 + 1;
}
if (Payload.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Payload);
}
return size;
}
public void MergeFrom(EchoRequest other) {
if (other == null) {
return;
}
if (other.Time != 0UL) {
Time = other.Time;
}
if (other.NetworkOnly != false) {
NetworkOnly = other.NetworkOnly;
}
if (other.Payload.Length != 0) {
Payload = other.Payload;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
Time = input.ReadFixed64();
break;
}
case 16: {
NetworkOnly = input.ReadBool();
break;
}
case 26: {
Payload = input.ReadBytes();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class EchoResponse : pb::IMessage<EchoResponse> {
private static readonly pb::MessageParser<EchoResponse> _parser = new pb::MessageParser<EchoResponse>(() => new EchoResponse());
public static pb::MessageParser<EchoResponse> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[7]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public EchoResponse() {
OnConstruction();
}
partial void OnConstruction();
public EchoResponse(EchoResponse other) : this() {
time_ = other.time_;
payload_ = other.payload_;
}
public EchoResponse Clone() {
return new EchoResponse(this);
}
/// <summary>Field number for the "time" field.</summary>
public const int TimeFieldNumber = 1;
private ulong time_;
public ulong Time {
get { return time_; }
set {
time_ = value;
}
}
/// <summary>Field number for the "payload" field.</summary>
public const int PayloadFieldNumber = 2;
private pb::ByteString payload_ = pb::ByteString.Empty;
public pb::ByteString Payload {
get { return payload_; }
set {
payload_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as EchoResponse);
}
public bool Equals(EchoResponse other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Time != other.Time) return false;
if (Payload != other.Payload) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
if (Time != 0UL) hash ^= Time.GetHashCode();
if (Payload.Length != 0) hash ^= Payload.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
if (Time != 0UL) {
output.WriteRawTag(9);
output.WriteFixed64(Time);
}
if (Payload.Length != 0) {
output.WriteRawTag(18);
output.WriteBytes(Payload);
}
}
public int CalculateSize() {
int size = 0;
if (Time != 0UL) {
size += 1 + 8;
}
if (Payload.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Payload);
}
return size;
}
public void MergeFrom(EchoResponse other) {
if (other == null) {
return;
}
if (other.Time != 0UL) {
Time = other.Time;
}
if (other.Payload.Length != 0) {
Payload = other.Payload;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 9: {
Time = input.ReadFixed64();
break;
}
case 18: {
Payload = input.ReadBytes();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DisconnectRequest : pb::IMessage<DisconnectRequest> {
private static readonly pb::MessageParser<DisconnectRequest> _parser = new pb::MessageParser<DisconnectRequest>(() => new DisconnectRequest());
public static pb::MessageParser<DisconnectRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[8]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public DisconnectRequest() {
OnConstruction();
}
partial void OnConstruction();
public DisconnectRequest(DisconnectRequest other) : this() {
errorCode_ = other.errorCode_;
}
public DisconnectRequest Clone() {
return new DisconnectRequest(this);
}
/// <summary>Field number for the "error_code" field.</summary>
public const int ErrorCodeFieldNumber = 1;
private uint errorCode_;
public uint ErrorCode {
get { return errorCode_; }
set {
errorCode_ = value;
}
}
public override bool Equals(object other) {
return Equals(other as DisconnectRequest);
}
public bool Equals(DisconnectRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ErrorCode != other.ErrorCode) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= ErrorCode.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
{
output.WriteRawTag(8);
output.WriteUInt32(ErrorCode);
}
}
public int CalculateSize() {
int size = 0;
{
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(ErrorCode);
}
return size;
}
public void MergeFrom(DisconnectRequest other) {
if (other == null) {
return;
}
if (other.ErrorCode != 0) {
ErrorCode = other.ErrorCode;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
ErrorCode = input.ReadUInt32();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class DisconnectNotification : pb::IMessage<DisconnectNotification> {
private static readonly pb::MessageParser<DisconnectNotification> _parser = new pb::MessageParser<DisconnectNotification>(() => new DisconnectNotification());
public static pb::MessageParser<DisconnectNotification> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[9]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public DisconnectNotification() {
OnConstruction();
}
partial void OnConstruction();
public DisconnectNotification(DisconnectNotification other) : this() {
errorCode_ = other.errorCode_;
reason_ = other.reason_;
}
public DisconnectNotification Clone() {
return new DisconnectNotification(this);
}
/// <summary>Field number for the "error_code" field.</summary>
public const int ErrorCodeFieldNumber = 1;
private uint errorCode_;
public uint ErrorCode {
get { return errorCode_; }
set {
errorCode_ = value;
}
}
/// <summary>Field number for the "reason" field.</summary>
public const int ReasonFieldNumber = 2;
private string reason_ = "";
public string Reason {
get { return reason_; }
set {
reason_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
public override bool Equals(object other) {
return Equals(other as DisconnectNotification);
}
public bool Equals(DisconnectNotification other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ErrorCode != other.ErrorCode) return false;
if (Reason != other.Reason) return false;
return true;
}
public override int GetHashCode() {
int hash = 1;
hash ^= ErrorCode.GetHashCode();
if (Reason.Length != 0) hash ^= Reason.GetHashCode();
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
{
output.WriteRawTag(8);
output.WriteUInt32(ErrorCode);
}
if (Reason.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Reason);
}
}
public int CalculateSize() {
int size = 0;
{
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(ErrorCode);
}
if (Reason.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Reason);
}
return size;
}
public void MergeFrom(DisconnectNotification other) {
if (other == null) {
return;
}
if (other.ErrorCode != 0) {
ErrorCode = other.ErrorCode;
}
if (other.Reason.Length != 0) {
Reason = other.Reason;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
ErrorCode = input.ReadUInt32();
break;
}
case 18: {
Reason = input.ReadString();
break;
}
}
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
public sealed partial class EncryptRequest : pb::IMessage<EncryptRequest> {
private static readonly pb::MessageParser<EncryptRequest> _parser = new pb::MessageParser<EncryptRequest>(() => new EncryptRequest());
public static pb::MessageParser<EncryptRequest> Parser { get { return _parser; } }
public static pbr::MessageDescriptor Descriptor {
get { return global::Bgs.Protocol.Connection.V1.ConnectionServiceReflection.Descriptor.MessageTypes[10]; }
}
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
public EncryptRequest() {
OnConstruction();
}
partial void OnConstruction();
public EncryptRequest(EncryptRequest other) : this() {
}
public EncryptRequest Clone() {
return new EncryptRequest(this);
}
public override bool Equals(object other) {
return Equals(other as EncryptRequest);
}
public bool Equals(EncryptRequest other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return true;
}
public override int GetHashCode() {
int hash = 1;
return hash;
}
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
public void WriteTo(pb::CodedOutputStream output) {
}
public int CalculateSize() {
int size = 0;
return size;
}
public void MergeFrom(EncryptRequest other) {
if (other == null) {
return;
}
}
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
/*
* 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 QuantConnect.Data;
using QuantConnect.Interfaces;
using QuantConnect.Lean.Engine.DataFeeds.Transport;
using QuantConnect.Util;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// Provides an implementations of <see cref="ISubscriptionDataSourceReader"/> that uses the
/// <see cref="BaseData.Reader(QuantConnect.Data.SubscriptionDataConfig,string,System.DateTime,bool)"/>
/// method to read lines of text from a <see cref="SubscriptionDataSource"/>
/// </summary>
public class TextSubscriptionDataSourceReader : ISubscriptionDataSourceReader
{
private readonly bool _isLiveMode;
private readonly BaseData _factory;
private readonly DateTime _date;
private readonly SubscriptionDataConfig _config;
private readonly IDataCacheProvider _dataCacheProvider;
/// <summary>
/// Event fired when the specified source is considered invalid, this may
/// be from a missing file or failure to download a remote source
/// </summary>
public event EventHandler<InvalidSourceEventArgs> InvalidSource;
/// <summary>
/// Event fired when an exception is thrown during a call to
/// <see cref="BaseData.Reader(QuantConnect.Data.SubscriptionDataConfig,string,System.DateTime,bool)"/>
/// </summary>
public event EventHandler<ReaderErrorEventArgs> ReaderError;
/// <summary>
/// Event fired when there's an error creating an <see cref="IStreamReader"/> or the
/// instantiated <see cref="IStreamReader"/> has no data.
/// </summary>
public event EventHandler<CreateStreamReaderErrorEventArgs> CreateStreamReaderError;
/// <summary>
/// Initializes a new instance of the <see cref="TextSubscriptionDataSourceReader"/> class
/// </summary>
/// <param name="dataCacheProvider">This provider caches files if needed</param>
/// <param name="config">The subscription's configuration</param>
/// <param name="date">The date this factory was produced to read data for</param>
/// <param name="isLiveMode">True if we're in live mode, false for backtesting</param>
public TextSubscriptionDataSourceReader(IDataCacheProvider dataCacheProvider, SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
_dataCacheProvider = dataCacheProvider;
_date = date;
_config = config;
_isLiveMode = isLiveMode;
_factory = (BaseData) ObjectActivator.GetActivator(config.Type).Invoke(new object[] { config.Type });
}
/// <summary>
/// Reads the specified <paramref name="source"/>
/// </summary>
/// <param name="source">The source to be read</param>
/// <returns>An <see cref="IEnumerable{BaseData}"/> that contains the data in the source</returns>
public IEnumerable<BaseData> Read(SubscriptionDataSource source)
{
using (var reader = CreateStreamReader(source))
{
// if the reader doesn't have data then we're done with this subscription
if (reader == null || reader.EndOfStream)
{
OnCreateStreamReaderError(_date, source);
yield break;
}
// while the reader has data
while (!reader.EndOfStream)
{
// read a line and pass it to the base data factory
var line = reader.ReadLine();
BaseData instance = null;
try
{
instance = _factory.Reader(_config, line, _date, _isLiveMode);
}
catch (Exception err)
{
OnReaderError(line, err);
}
if (instance != null)
{
yield return instance;
}
}
}
}
/// <summary>
/// Creates a new <see cref="IStreamReader"/> for the specified <paramref name="subscriptionDataSource"/>
/// </summary>
/// <param name="subscriptionDataSource">The source to produce an <see cref="IStreamReader"/> for</param>
/// <returns>A new instance of <see cref="IStreamReader"/> to read the source, or null if there was an error</returns>
private IStreamReader CreateStreamReader(SubscriptionDataSource subscriptionDataSource)
{
IStreamReader reader;
switch (subscriptionDataSource.TransportMedium)
{
case SubscriptionTransportMedium.LocalFile:
reader = HandleLocalFileSource(subscriptionDataSource);
break;
case SubscriptionTransportMedium.RemoteFile:
reader = HandleRemoteSourceFile(subscriptionDataSource);
break;
case SubscriptionTransportMedium.Rest:
reader = new RestSubscriptionStreamReader(subscriptionDataSource.Source);
break;
default:
throw new InvalidEnumArgumentException("Unexpected SubscriptionTransportMedium specified: " + subscriptionDataSource.TransportMedium);
}
return reader;
}
/// <summary>
/// Event invocator for the <see cref="InvalidSource"/> event
/// </summary>
/// <param name="source">The <see cref="SubscriptionDataSource"/> that was invalid</param>
/// <param name="exception">The exception if one was raised, otherwise null</param>
private void OnInvalidSource(SubscriptionDataSource source, Exception exception)
{
var handler = InvalidSource;
if (handler != null) handler(this, new InvalidSourceEventArgs(source, exception));
}
/// <summary>
/// Event invocator for the <see cref="ReaderError"/> event
/// </summary>
/// <param name="line">The line that caused the exception</param>
/// <param name="exception">The exception that was caught</param>
private void OnReaderError(string line, Exception exception)
{
var handler = ReaderError;
if (handler != null) handler(this, new ReaderErrorEventArgs(line, exception));
}
/// <summary>
/// Event invocator for the <see cref="CreateStreamReaderError"/> event
/// </summary>
/// <param name="date">The date of the source</param>
/// <param name="source">The source that caused the error</param>
private void OnCreateStreamReaderError(DateTime date, SubscriptionDataSource source)
{
var handler = CreateStreamReaderError;
if (handler != null) handler(this, new CreateStreamReaderErrorEventArgs(date, source));
}
/// <summary>
/// Opens up an IStreamReader for a local file source
/// </summary>
private IStreamReader HandleLocalFileSource(SubscriptionDataSource source)
{
// handles zip or text files
return new LocalFileSubscriptionStreamReader(_dataCacheProvider, source.Source);
}
/// <summary>
/// Opens up an IStreamReader for a remote file source
/// </summary>
private IStreamReader HandleRemoteSourceFile(SubscriptionDataSource source)
{
SubscriptionDataSourceReader.CheckRemoteFileCache();
try
{
// this will fire up a web client in order to download the 'source' file to the cache
return new RemoteFileSubscriptionStreamReader(_dataCacheProvider, source.Source, Globals.Cache);
}
catch (Exception err)
{
OnInvalidSource(source, err);
return null;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
namespace System
{
public abstract partial class Attribute
{
#region Private Statics
#region PropertyInfo
private static Attribute[] InternalGetCustomAttributes(PropertyInfo element, Type type, bool inherit)
{
Debug.Assert(element != null);
Debug.Assert(type != null);
Debug.Assert(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (!inherit)
return attributes;
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
// if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
PropertyInfo? baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
attributes = GetCustomAttributes(baseProp, type, false);
AddAttributesToList(attributeList, attributes, types);
baseProp = GetParentDefinition(baseProp, indexParamTypes);
}
Attribute[] array = CreateAttributeArrayHelper(type, attributeList.Count);
attributeList.CopyTo(array, 0);
return array;
}
private static bool InternalIsDefined(PropertyInfo element, Type attributeType, bool inherit)
{
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
// if this is an index we need to get the parameter types to help disambiguate
Type[] indexParamTypes = GetIndexParameterTypes(element);
PropertyInfo? baseProp = GetParentDefinition(element, indexParamTypes);
while (baseProp != null)
{
if (baseProp.IsDefined(attributeType, false))
return true;
baseProp = GetParentDefinition(baseProp, indexParamTypes);
}
}
return false;
}
private static PropertyInfo? GetParentDefinition(PropertyInfo property, Type[] propertyParameters)
{
Debug.Assert(property != null);
// for the current property get the base class of the getter and the setter, they might be different
// note that this only works for RuntimeMethodInfo
MethodInfo? propAccessor = property.GetGetMethod(true) ?? property.GetSetMethod(true);
RuntimeMethodInfo? rtPropAccessor = propAccessor as RuntimeMethodInfo;
if (rtPropAccessor != null)
{
rtPropAccessor = rtPropAccessor.GetParentDefinition();
if (rtPropAccessor != null)
{
// There is a public overload of Type.GetProperty that takes both a BingingFlags enum and a return type.
// However, we cannot use that because it doesn't accept null for "types".
return rtPropAccessor.DeclaringType!.GetProperty(
property.Name,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly,
null, // will use default binder
property.PropertyType,
propertyParameters, // used for index properties
null);
}
}
return null;
}
#endregion
#region EventInfo
private static Attribute[] InternalGetCustomAttributes(EventInfo element, Type type, bool inherit)
{
Debug.Assert(element != null);
Debug.Assert(type != null);
Debug.Assert(type.IsSubclassOf(typeof(Attribute)) || type == typeof(Attribute));
// walk up the hierarchy chain
Attribute[] attributes = (Attribute[])element.GetCustomAttributes(type, inherit);
if (inherit)
{
// create the hashtable that keeps track of inherited types
Dictionary<Type, AttributeUsageAttribute> types = new Dictionary<Type, AttributeUsageAttribute>(11);
// create an array list to collect all the requested attibutes
List<Attribute> attributeList = new List<Attribute>();
CopyToArrayList(attributeList, attributes, types);
EventInfo? baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
attributes = GetCustomAttributes(baseEvent, type, false);
AddAttributesToList(attributeList, attributes, types);
baseEvent = GetParentDefinition(baseEvent);
}
Attribute[] array = CreateAttributeArrayHelper(type, attributeList.Count);
attributeList.CopyTo(array, 0);
return array;
}
else
return attributes;
}
private static EventInfo? GetParentDefinition(EventInfo ev)
{
Debug.Assert(ev != null);
// note that this only works for RuntimeMethodInfo
MethodInfo? add = ev.GetAddMethod(true);
RuntimeMethodInfo? rtAdd = add as RuntimeMethodInfo;
if (rtAdd != null)
{
rtAdd = rtAdd.GetParentDefinition();
if (rtAdd != null)
return rtAdd.DeclaringType!.GetEvent(ev.Name!);
}
return null;
}
private static bool InternalIsDefined(EventInfo element, Type attributeType, bool inherit)
{
Debug.Assert(element != null);
// walk up the hierarchy chain
if (element.IsDefined(attributeType, inherit))
return true;
if (inherit)
{
AttributeUsageAttribute usage = InternalGetAttributeUsage(attributeType);
if (!usage.Inherited)
return false;
EventInfo? baseEvent = GetParentDefinition(element);
while (baseEvent != null)
{
if (baseEvent.IsDefined(attributeType, false))
return true;
baseEvent = GetParentDefinition(baseEvent);
}
}
return false;
}
#endregion
#region ParameterInfo
private static ParameterInfo? GetParentDefinition(ParameterInfo param)
{
Debug.Assert(param != null);
// note that this only works for RuntimeMethodInfo
RuntimeMethodInfo? rtMethod = param.Member as RuntimeMethodInfo;
if (rtMethod != null)
{
rtMethod = rtMethod.GetParentDefinition();
if (rtMethod != null)
{
// Find the ParameterInfo on this method
int position = param.Position;
if (position == -1)
{
return rtMethod.ReturnParameter;
}
else
{
ParameterInfo[] parameters = rtMethod.GetParameters();
return parameters[position]; // Point to the correct ParameterInfo of the method
}
}
}
return null;
}
private static Attribute[] InternalParamGetCustomAttributes(ParameterInfo param, Type? type, bool inherit)
{
Debug.Assert(param != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain that
// have this ParameterInfo defined. .We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the MethodInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk so the default ParameterInfo attributes are returned.
// For MethodInfo's on a class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the
// class inherits from and return the respective ParameterInfo attributes
List<Type> disAllowMultiple = new List<Type>();
object?[] objAttr;
type ??= typeof(Attribute);
objAttr = param.GetCustomAttributes(type, false);
for (int i = 0; i < objAttr.Length; i++)
{
Type objType = objAttr[i]!.GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if (!attribUsage.AllowMultiple)
disAllowMultiple.Add(objType);
}
// Get all the attributes that have Attribute as the base class
Attribute[] ret;
if (objAttr.Length == 0)
ret = CreateAttributeArrayHelper(type, 0);
else
ret = (Attribute[])objAttr;
if (param.Member.DeclaringType is null) // This is an interface so we are done.
return ret;
if (!inherit)
return ret;
ParameterInfo? baseParam = GetParentDefinition(param);
while (baseParam != null)
{
objAttr = baseParam.GetCustomAttributes(type, false);
int count = 0;
for (int i = 0; i < objAttr.Length; i++)
{
Type objType = objAttr[i]!.GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((attribUsage.Inherited) && (!disAllowMultiple.Contains(objType)))
{
if (!attribUsage.AllowMultiple)
disAllowMultiple.Add(objType);
count++;
}
else
objAttr[i] = null;
}
// Get all the attributes that have Attribute as the base class
Attribute[] attributes = CreateAttributeArrayHelper(type, count);
count = 0;
for (int i = 0; i < objAttr.Length; i++)
{
if (objAttr[i] != null)
{
attributes[count] = (Attribute)objAttr[i]!; // TODO-NULLABLE: Indexer nullability tracked (https://github.com/dotnet/roslyn/issues/34644)
count++;
}
}
Attribute[] temp = ret;
ret = CreateAttributeArrayHelper(type, temp.Length + count);
Array.Copy(temp, 0, ret, 0, temp.Length);
int offset = temp.Length;
for (int i = 0; i < attributes.Length; i++)
ret[offset + i] = attributes[i];
baseParam = GetParentDefinition(baseParam);
}
return ret;
}
private static bool InternalParamIsDefined(ParameterInfo param, Type type, bool inherit)
{
Debug.Assert(param != null);
Debug.Assert(type != null);
// For ParameterInfo's we need to make sure that we chain through all the MethodInfo's in the inheritance chain.
// We pick up all the CustomAttributes for the starting ParameterInfo. We need to pick up only attributes
// that are marked inherited from the remainder of the ParameterInfo's in the inheritance chain.
// For MethodInfo's on an interface we do not do an inheritance walk. For ParameterInfo's on a
// Class we walk up the inheritance chain but do not look at the MethodInfo's on the interfaces that the class inherits from.
if (param.IsDefined(type, false))
return true;
if (param.Member.DeclaringType is null || !inherit) // This is an interface so we are done.
return false;
ParameterInfo? baseParam = GetParentDefinition(param);
while (baseParam != null)
{
object[] objAttr = baseParam.GetCustomAttributes(type, false);
for (int i = 0; i < objAttr.Length; i++)
{
Type objType = objAttr[i].GetType();
AttributeUsageAttribute attribUsage = InternalGetAttributeUsage(objType);
if ((objAttr[i] is Attribute) && (attribUsage.Inherited))
return true;
}
baseParam = GetParentDefinition(baseParam);
}
return false;
}
#endregion
#region Utility
private static void CopyToArrayList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
attributeList.Add(attributes[i]);
Type attrType = attributes[i].GetType();
if (!types.ContainsKey(attrType))
types[attrType] = InternalGetAttributeUsage(attrType);
}
}
private static Type[] GetIndexParameterTypes(PropertyInfo element)
{
ParameterInfo[] indexParams = element.GetIndexParameters();
if (indexParams.Length > 0)
{
Type[] indexParamTypes = new Type[indexParams.Length];
for (int i = 0; i < indexParams.Length; i++)
{
indexParamTypes[i] = indexParams[i].ParameterType;
}
return indexParamTypes;
}
return Array.Empty<Type>();
}
private static void AddAttributesToList(List<Attribute> attributeList, Attribute[] attributes, Dictionary<Type, AttributeUsageAttribute> types)
{
for (int i = 0; i < attributes.Length; i++)
{
Type attrType = attributes[i].GetType();
AttributeUsageAttribute? usage;
types.TryGetValue(attrType, out usage);
if (usage == null)
{
// the type has never been seen before if it's inheritable add it to the list
usage = InternalGetAttributeUsage(attrType);
types[attrType] = usage;
if (usage.Inherited)
attributeList.Add(attributes[i]);
}
else if (usage.Inherited && usage.AllowMultiple)
{
// we saw this type already add it only if it is inheritable and it does allow multiple
attributeList.Add(attributes[i]);
}
}
}
private static AttributeUsageAttribute InternalGetAttributeUsage(Type type)
{
// Check if the custom attributes is Inheritable
object[] obj = type.GetCustomAttributes(typeof(AttributeUsageAttribute), false);
if (obj.Length == 1)
return (AttributeUsageAttribute)obj[0];
if (obj.Length == 0)
return AttributeUsageAttribute.Default;
throw new FormatException(
SR.Format(SR.Format_AttributeUsage, type));
}
private static Attribute[] CreateAttributeArrayHelper(Type elementType, int elementCount)
{
return (Attribute[])Array.CreateInstance(elementType, elementCount);
}
#endregion
#endregion
#region Public Statics
#region MemberInfo
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type)
{
return GetCustomAttributes(element, type, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, Type type, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (type == null)
throw new ArgumentNullException(nameof(type));
if (!type.IsSubclassOf(typeof(Attribute)) && type != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return element.MemberType switch
{
MemberTypes.Property => InternalGetCustomAttributes((PropertyInfo)element, type, inherit),
MemberTypes.Event => InternalGetCustomAttributes((EventInfo)element, type, inherit),
_ => (element.GetCustomAttributes(type, inherit) as Attribute[])!,
};
}
public static Attribute[] GetCustomAttributes(MemberInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
return element.MemberType switch
{
MemberTypes.Property => InternalGetCustomAttributes((PropertyInfo)element, typeof(Attribute), inherit),
MemberTypes.Event => InternalGetCustomAttributes((EventInfo)element, typeof(Attribute), inherit),
_ => (element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[])!,
};
}
public static bool IsDefined(MemberInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit)
{
// Returns true if a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return element.MemberType switch
{
MemberTypes.Property => InternalIsDefined((PropertyInfo)element, attributeType, inherit),
MemberTypes.Event => InternalIsDefined((EventInfo)element, attributeType, inherit),
_ => element.IsDefined(attributeType, inherit),
};
}
public static Attribute? GetCustomAttribute(MemberInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute? GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit)
{
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
#region ParameterInfo
public static Attribute[] GetCustomAttributes(ParameterInfo element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType)
{
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
if (element.Member == null)
throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, attributeType, inherit);
return (element.GetCustomAttributes(attributeType, inherit) as Attribute[])!;
}
public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (element.Member == null)
throw new ArgumentException(SR.Argument_InvalidParameterInfo, nameof(element));
MemberInfo member = element.Member;
if (member.MemberType == MemberTypes.Method && inherit)
return InternalParamGetCustomAttributes(element, null, inherit);
return (element.GetCustomAttributes(typeof(Attribute), inherit) as Attribute[])!;
}
public static bool IsDefined(ParameterInfo element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with inheritance walk
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
MemberInfo member = element.Member;
switch (member.MemberType)
{
case MemberTypes.Method: // We need to climb up the member hierarchy
return InternalParamIsDefined(element, attributeType, inherit);
case MemberTypes.Constructor:
return element.IsDefined(attributeType, false);
case MemberTypes.Property:
return element.IsDefined(attributeType, false);
default:
Debug.Fail("Invalid type for ParameterInfo member in Attribute class");
throw new ArgumentException(SR.Argument_InvalidParamInfo);
}
}
public static Attribute? GetCustomAttribute(ParameterInfo element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute? GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the ParameterInfo or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
#region Module
public static Attribute[] GetCustomAttributes(Module element, Type attributeType)
{
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Module element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Module element, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static Attribute[] GetCustomAttributes(Module element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static bool IsDefined(Module element, Type attributeType)
{
return IsDefined(element, attributeType, false);
}
public static bool IsDefined(Module element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return element.IsDefined(attributeType, false);
}
public static Attribute? GetCustomAttribute(Module element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute? GetCustomAttribute(Module element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Module or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
#region Assembly
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType)
{
return GetCustomAttributes(element, attributeType, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, Type attributeType, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return (Attribute[])element.GetCustomAttributes(attributeType, inherit);
}
public static Attribute[] GetCustomAttributes(Assembly element)
{
return GetCustomAttributes(element, true);
}
public static Attribute[] GetCustomAttributes(Assembly element, bool inherit)
{
if (element == null)
throw new ArgumentNullException(nameof(element));
return (Attribute[])element.GetCustomAttributes(typeof(Attribute), inherit);
}
public static bool IsDefined(Assembly element, Type attributeType)
{
return IsDefined(element, attributeType, true);
}
public static bool IsDefined(Assembly element, Type attributeType, bool inherit)
{
// Returns true is a custom attribute subclass of attributeType class/interface with no inheritance walk
if (element == null)
throw new ArgumentNullException(nameof(element));
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
if (!attributeType.IsSubclassOf(typeof(Attribute)) && attributeType != typeof(Attribute))
throw new ArgumentException(SR.Argument_MustHaveAttributeBaseClass);
return element.IsDefined(attributeType, false);
}
public static Attribute? GetCustomAttribute(Assembly element, Type attributeType)
{
return GetCustomAttribute(element, attributeType, true);
}
public static Attribute? GetCustomAttribute(Assembly element, Type attributeType, bool inherit)
{
// Returns an Attribute of base class/inteface attributeType on the Assembly or null if none exists.
// throws an AmbiguousMatchException if there are more than one defined.
Attribute[] attrib = GetCustomAttributes(element, attributeType, inherit);
if (attrib == null || attrib.Length == 0)
return null;
if (attrib.Length == 1)
return attrib[0];
throw new AmbiguousMatchException(SR.RFLCT_AmbigCust);
}
#endregion
#endregion
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.core.selection
{
/// <summary>
/// <para>Generic selection manager to bring rich desktop like selection behavior
/// to widgets and low-level interactive controls.</para>
/// <para>The selection handling supports both Shift and Ctrl/Meta modifies like
/// known from native applications.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.core.selection.Abstract", OmitOptionalParameters = true, Export = false)]
public abstract partial class Abstract : qx.core.Object
{
#region Events
/// <summary>
/// <para>Fires after the selection was modified. Contains the selection under the data property.</para>
/// </summary>
public event Action<qx.eventx.type.Data> OnChangeSelection;
#endregion Events
#region Properties
/// <summary>
/// <para>Enable drag selection (multi selection of items through
/// dragging the mouse in pressed states).</para>
/// <para>Only possible for the modes multi and additive</para>
/// </summary>
[JsProperty(Name = "drag", NativeField = true)]
public bool Drag { get; set; }
/// <summary>
/// <para>Selects the selection mode to use.</para>
/// <list type="bullet">
/// <item>single: One or no element is selected</item>
/// <item>multi: Multi items could be selected. Also allows empty selections.</item>
/// <item>additive: Easy Web-2.0 selection mode. Allows multiple selections without modifier keys.</item>
/// <item>one: If possible always exactly one item is selected</item>
/// </list>
/// </summary>
/// <remarks>
/// Possible values: "single","multi","additive","one"
/// </remarks>
[JsProperty(Name = "mode", NativeField = true)]
public object Mode { get; set; }
/// <summary>
/// <para>Enable quick selection mode, where no click is needed to change the selection.</para>
/// <para>Only possible for the modes single and one.</para>
/// </summary>
[JsProperty(Name = "quick", NativeField = true)]
public bool Quick { get; set; }
#endregion Properties
#region Methods
public Abstract() { throw new NotImplementedException(); }
/// <summary>
/// <para>Adds the given item to the existing selection.</para>
/// <para>Use <see cref="SelectItem"/> instead if you want to replace
/// the current selection.</para>
/// </summary>
/// <param name="item">Any valid item</param>
[JsMethod(Name = "addItem")]
public void AddItem(object item) { throw new NotImplementedException(); }
/// <summary>
/// <para>Clears the whole selection at once. Also
/// resets the lead and anchor items and their
/// styles.</para>
/// </summary>
[JsMethod(Name = "clearSelection")]
public void ClearSelection() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property drag.</para>
/// </summary>
[JsMethod(Name = "getDrag")]
public bool GetDrag() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the current lead item. Generally the item which was last modified
/// by the user (clicked on etc.)</para>
/// </summary>
/// <returns>The lead item or null</returns>
[JsMethod(Name = "getLeadItem")]
public object GetLeadItem() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property mode.</para>
/// </summary>
[JsMethod(Name = "getMode")]
public object GetMode() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property quick.</para>
/// </summary>
[JsMethod(Name = "getQuick")]
public bool GetQuick() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns all selectable items of the container.</para>
/// </summary>
/// <param name="all">true for all selectables, false for the selectables the user can interactively select</param>
/// <returns>A list of items</returns>
[JsMethod(Name = "getSelectables")]
public JsArray GetSelectables(bool all) { throw new NotImplementedException(); }
/// <summary>
/// <para>Get the selected item. This method does only work in single
/// selection mode.</para>
/// </summary>
/// <returns>The selected item.</returns>
[JsMethod(Name = "getSelectedItem")]
public object GetSelectedItem() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns an array of currently selected items.</para>
/// <para>Note: The result is only a set of selected items, so the order can
/// differ from the sequence in which the items were added.</para>
/// </summary>
/// <returns>List of items.</returns>
[JsMethod(Name = "getSelection")]
public object GetSelection() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the selection context. One of click,
/// quick, drag or key or
/// null.</para>
/// </summary>
/// <returns>One of click, quick, drag or key or null</returns>
[JsMethod(Name = "getSelectionContext")]
public string GetSelectionContext() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the selection sorted by the index in the
/// container of the selection (the assigned widget)</para>
/// </summary>
/// <returns>Sorted list of items</returns>
[JsMethod(Name = "getSortedSelection")]
public object GetSortedSelection() { throw new NotImplementedException(); }
/// <summary>
/// <para>This method should be connected to the addItem event
/// of the managed object.</para>
/// </summary>
/// <param name="e">The event object</param>
[JsMethod(Name = "handleAddItem")]
public void HandleAddItem(qx.eventx.type.Data e) { throw new NotImplementedException(); }
/// <summary>
/// <para>This method should be connected to the keypress event
/// of the managed object.</para>
/// </summary>
/// <param name="eventx">A valid key sequence event</param>
[JsMethod(Name = "handleKeyPress")]
public void HandleKeyPress(qx.eventx.type.KeySequence eventx) { throw new NotImplementedException(); }
/// <summary>
/// <para>This method should be connected to the losecapture event
/// of the managed object.</para>
/// </summary>
/// <param name="eventx">A valid mouse event</param>
[JsMethod(Name = "handleLoseCapture")]
public void HandleLoseCapture(qx.eventx.type.Mouse eventx) { throw new NotImplementedException(); }
/// <summary>
/// <para>This method should be connected to the mousedown event
/// of the managed object.</para>
/// </summary>
/// <param name="eventx">A valid mouse event</param>
[JsMethod(Name = "handleMouseDown")]
public void HandleMouseDown(qx.eventx.type.Mouse eventx) { throw new NotImplementedException(); }
/// <summary>
/// <para>This method should be connected to the mousemove event
/// of the managed object.</para>
/// </summary>
/// <param name="eventx">A valid mouse event</param>
[JsMethod(Name = "handleMouseMove")]
public void HandleMouseMove(qx.eventx.type.Mouse eventx) { throw new NotImplementedException(); }
/// <summary>
/// <para>This method should be connected to the mouseover event
/// of the managed object.</para>
/// </summary>
/// <param name="eventx">A valid mouse event</param>
[JsMethod(Name = "handleMouseOver")]
public void HandleMouseOver(qx.eventx.type.Mouse eventx) { throw new NotImplementedException(); }
/// <summary>
/// <para>This method should be connected to the mouseup event
/// of the managed object.</para>
/// </summary>
/// <param name="eventx">A valid mouse event</param>
[JsMethod(Name = "handleMouseUp")]
public void HandleMouseUp(qx.eventx.type.Mouse eventx) { throw new NotImplementedException(); }
/// <summary>
/// <para>This method should be connected to the removeItem event
/// of the managed object.</para>
/// </summary>
/// <param name="e">The event object</param>
[JsMethod(Name = "handleRemoveItem")]
public void HandleRemoveItem(qx.eventx.type.Data e) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property drag
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property drag.</param>
[JsMethod(Name = "initDrag")]
public void InitDrag(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property mode
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property mode.</param>
[JsMethod(Name = "initMode")]
public void InitMode(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property quick
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property quick.</param>
[JsMethod(Name = "initQuick")]
public void InitQuick(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Invert the selection. Select the non selected and deselect the selected.</para>
/// </summary>
[JsMethod(Name = "invertSelection")]
public void InvertSelection() { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property drag equals true.</para>
/// </summary>
[JsMethod(Name = "isDrag")]
public void IsDrag() { throw new NotImplementedException(); }
/// <summary>
/// <para>Detects whether the given item is currently selected.</para>
/// </summary>
/// <param name="item">Any valid selectable item</param>
/// <returns>Whether the item is selected</returns>
[JsMethod(Name = "isItemSelected")]
public bool IsItemSelected(object item) { throw new NotImplementedException(); }
/// <summary>
/// <para>Check whether the (computed) value of the boolean property quick equals true.</para>
/// </summary>
[JsMethod(Name = "isQuick")]
public void IsQuick() { throw new NotImplementedException(); }
/// <summary>
/// <para>Whether the selection is empty</para>
/// </summary>
/// <returns>Whether the selection is empty</returns>
[JsMethod(Name = "isSelectionEmpty")]
public bool IsSelectionEmpty() { throw new NotImplementedException(); }
/// <summary>
/// <para>Removes the given item from the selection.</para>
/// <para>Use <see cref="ClearSelection"/> when you want to clear
/// the whole selection at once.</para>
/// </summary>
/// <param name="item">Any valid item</param>
[JsMethod(Name = "removeItem")]
public void RemoveItem(object item) { throw new NotImplementedException(); }
/// <summary>
/// <para>Replaces current selection with given array of items.</para>
/// <para>Please note that in single selection scenarios it is more
/// efficient to directly use <see cref="SelectItem"/>.</para>
/// </summary>
/// <param name="items">Items to select</param>
[JsMethod(Name = "replaceSelection")]
public void ReplaceSelection(JsArray items) { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property drag.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetDrag")]
public void ResetDrag() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property mode.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetMode")]
public void ResetMode() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property quick.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetQuick")]
public void ResetQuick() { throw new NotImplementedException(); }
/// <summary>
/// <para>Selects all items of the managed object.</para>
/// </summary>
[JsMethod(Name = "selectAll")]
public void SelectAll() { throw new NotImplementedException(); }
/// <summary>
/// <para>Selects the given item. Replaces current selection
/// completely with the new item.</para>
/// <para>Use <see cref="AddItem"/> instead if you want to add new
/// items to an existing selection.</para>
/// </summary>
/// <param name="item">Any valid item</param>
[JsMethod(Name = "selectItem")]
public void SelectItem(object item) { throw new NotImplementedException(); }
/// <summary>
/// <para>Selects an item range between two given items.</para>
/// </summary>
/// <param name="begin">Item to start with</param>
/// <param name="end">Item to end at</param>
[JsMethod(Name = "selectItemRange")]
public void SelectItemRange(object begin, object end) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property drag.</para>
/// </summary>
/// <param name="value">New value for property drag.</param>
[JsMethod(Name = "setDrag")]
public void SetDrag(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property mode.</para>
/// </summary>
/// <param name="value">New value for property mode.</param>
[JsMethod(Name = "setMode")]
public void SetMode(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property quick.</para>
/// </summary>
/// <param name="value">New value for property quick.</param>
[JsMethod(Name = "setQuick")]
public void SetQuick(bool value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property drag.</para>
/// </summary>
[JsMethod(Name = "toggleDrag")]
public void ToggleDrag() { throw new NotImplementedException(); }
/// <summary>
/// <para>Toggles the (computed) value of the boolean property quick.</para>
/// </summary>
[JsMethod(Name = "toggleQuick")]
public void ToggleQuick() { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
/*
* Naiad ver. 0.5
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Research.Peloponnese.Shared;
using Microsoft.Research.Peloponnese.Hdfs;
using Microsoft.Research.Peloponnese.WebHdfs;
using Microsoft.Research.Peloponnese.Azure;
using Microsoft.Research.Peloponnese.ClusterUtils;
using Microsoft.Research.Naiad.Util;
namespace Microsoft.Research.Naiad.Cluster.Submission
{
public class Program
{
private enum ExecutionType
{
Local,
Yarn,
Azure
};
private static Flag ShowHelp = Flags.Define("-h,--help", typeof(bool));
private static Flag ForceLocal = Flags.Define("--local", typeof(bool));
private static Flag ForceAzure = Flags.Define("--azure", typeof(bool));
private static Flag ForceYarn = Flags.Define("--yarn", typeof(bool));
private static Flag NumHosts = Flags.Define("-n,--numhosts", 2);
private static Flag PeloponneseHome = Flags.Define("-p,--peloponnesehome", typeof(string));
private static Flag RMHostAndPort = Flags.Define("-r,--rmhost", typeof(string));
private static Flag NameNodeAndPort = Flags.Define("-nn,--namenode", typeof(string));
private static Flag YarnJobQueue = Flags.Define("-yq,--yarnqueue", typeof(string));
private static Flag YarnAMMemory = Flags.Define("-amm,--ammemorymb", typeof(int));
private static Flag YarnWorkerMemory = Flags.Define("-wm,--workermemorymb", typeof(int));
private static Flag WebHdfsPort = Flags.Define("-w,--webhdfsport", typeof(int));
private static Flag LauncherHostAndPort = Flags.Define("-l,--launcher", typeof(string));
private static Flag LogsDumpFile = Flags.Define("-f,--fetch", typeof(string));
private static Flag AzureSubscriptionId = Flags.Define("--subscriptionid", typeof(string));
private static Flag AzureClusterName = Flags.Define("-c,--clustername", typeof(string));
private static Flag AzureCertificateThumbprint = Flags.Define("--certthumbprint", typeof(string));
private static Flag AzureStorageAccountName = Flags.Define("--storageaccount", typeof(string));
private static Flag AzureStorageAccountKey = Flags.Define("--storagekey", typeof(string));
private static Flag AzureStorageContainerName = Flags.Define("--container", typeof(string));
private static Flag LocalJobDirectory = Flags.Define("-ld,--localdir", typeof(string));
private const string Usage = @"Usage: RunNaiad [Shared options] [[Azure options]|[Yarn options]|[Local options]] NaiadExecutable.exe [Naiad options]
Runs the given Naiad executable on an Azure HDInsight or YARN cluster, or a set of local processes. If no Azure or Yarn
options are specified, local execution is assumed.
(N.B. For convenience, each option can be set in the App.config for this program,
using the long form option name.)
Shared options:
-n,--numhosts Number of Naiad processes (default = 2)
-p,--peloponnesehome Location of Peloponnese binaries (defaults to directory of the running binary)
Yarn options:
-r,--rmhost YARN cluster RM node hostname and optional port. Hostname is required, port defaults to 8088
-nn,--namenode YARN cluster namenode and optional port, defaults to rm hostname
-yq,--yarnqueue YARN cluster job queue, defaults to cluster's default queue
-amm,--ammemorymb YARN container memory requested for AM (coordinator). Default is cluster's maximum container size
-wm,--workermemorymb YARN container memory requested for workers (Naiad processes). Default is cluster's maximum container size
-w,--webhdfsport Optional YARN namenode webhdfs port, defaults to 50070. If provided, RunNaiad will use
WebHdfs to upload resources. Otherwise, Java and YARN must be installed on the client computer.
-l,--launcher yarnlauncher hostname and optional port. If provided, RunNaiad will launch the job via the launcher
process. Otherwise, Java and YARN must be installed on the client computer.
-f,--fetch filename. fetch the job logs after the job finishes. yarn.cmd must be in the path for this to work.
Azure options:
--c,clustername HDInsight cluster name (required)
--subscriptionid Azure subscription ID (default = taken from Powershell settings)
--certthumbprint Azure certificate thumbprint (required if and only if subscription ID is provided)
--storageaccount Azure storage account name for staging resources (default = cluster default storage account)
--storagekey Azure storage account key for staging resources (default = cluster default storage account key)
--container Azure storage blob container name for staging resources (default = ""staging"")
Local options:
-ld,--localdir Local job working directory (default = '%PWD%\LocalJobs')";
private static void GetHostAndPort(string input, string defaultHost, int defaultPort, out string host, out int port)
{
if (input == null)
{
host = defaultHost;
port = defaultPort;
}
else
{
string[] parts = input.Split(':');
host = parts[0].Trim();
if (parts.Length == 2)
{
if (Int32.TryParse(parts[1], out port))
{
}
else
{
throw new ApplicationException("Bad port specifier: " + input);
}
}
else if (parts.Length > 2)
{
throw new ApplicationException("Bad host:port specifier: " + input);
}
else
{
port = defaultPort;
}
}
}
private static void FetchLogs(string dumpFile, string applicationId)
{
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
startInfo.Arguments = "/c yarn.cmd logs -applicationId " + applicationId + " -appOwner " + Environment.UserName;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
Console.WriteLine("Fetch logs to '" + dumpFile + "' with command 'cmd.exe " + startInfo.Arguments + "'");
try
{
using (Stream dumpStream = new FileStream(dumpFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
{
Process process = new Process();
process.StartInfo = startInfo;
bool started = process.Start();
if (!started)
{
Console.Error.WriteLine("Failed to start fetch command");
return;
}
using (StreamReader reader = process.StandardOutput)
{
Task finishCopy = reader.BaseStream.CopyToAsync(dumpStream);
process.WaitForExit();
finishCopy.Wait();
}
}
}
catch (Exception e)
{
Console.Error.WriteLine("Fetching logs got exception: " + e.ToString());
}
}
private static int RunNativeYarn(string[] args)
{
if (!RMHostAndPort.IsSet)
{
Console.Error.WriteLine("Error: Yarn cluster rm node hostname not set.");
Console.Error.WriteLine(Usage);
return 1;
}
string rmHost;
int wsPort;
GetHostAndPort(RMHostAndPort.StringValue, null, 8088, out rmHost, out wsPort);
string nameNode;
int hdfsPort;
GetHostAndPort(NameNodeAndPort.IsSet ? NameNodeAndPort.StringValue : null, rmHost, -1, out nameNode, out hdfsPort);
string queueName = null;
if (YarnJobQueue.IsSet)
{
queueName = YarnJobQueue.StringValue;
}
int amMemoryMB = -1;
if (YarnAMMemory.IsSet)
{
amMemoryMB = YarnAMMemory.IntValue;
}
int workerMemoryMB = -1;
if (YarnWorkerMemory.IsSet)
{
workerMemoryMB = YarnWorkerMemory.IntValue;
}
string launcherNode;
int launcherPort;
GetHostAndPort(
LauncherHostAndPort.IsSet ? LauncherHostAndPort.StringValue : null, null, -1,
out launcherNode, out launcherPort);
DfsClient dfsClient;
if (WebHdfsPort.IsSet)
{
dfsClient = new WebHdfsClient(Environment.UserName, WebHdfsPort.IntValue);
}
else
{
dfsClient = new HdfsClient();
}
if (args[0].ToLower().StartsWith("hdfs://"))
{
if (!dfsClient.IsFileExists(new Uri(args[0])))
{
Console.Error.WriteLine("Error: Naiad program {0} does not exist.", args[0]);
Console.Error.WriteLine(Usage);
return 1;
}
}
else
{
if (!File.Exists(args[0]))
{
Console.Error.WriteLine("Error: Naiad program {0} does not exist.", args[0]);
Console.Error.WriteLine(Usage);
return 1;
}
}
UriBuilder builder = new UriBuilder();
builder.Scheme = "hdfs";
builder.Host = nameNode;
builder.Port = hdfsPort;
Uri jobRoot = dfsClient.Combine(builder.Uri, "user", Environment.UserName);
Uri stagingRoot = dfsClient.Combine(builder.Uri, "tmp", "staging");
NativeYarnSubmission submission;
if (launcherNode == null)
{
submission = new NativeYarnSubmission(rmHost, wsPort, dfsClient, queueName, stagingRoot, jobRoot, PeloponneseHome, amMemoryMB, NumHosts, workerMemoryMB, args);
}
else
{
submission = new NativeYarnSubmission(rmHost, wsPort, dfsClient, queueName, stagingRoot, jobRoot, launcherNode, launcherPort, amMemoryMB, NumHosts, workerMemoryMB, args);
}
submission.Submit();
Console.WriteLine("Waiting for application to complete");
int ret = submission.Join();
if (LogsDumpFile.IsSet)
{
FetchLogs(LogsDumpFile.StringValue, submission.ClusterJob.Id);
}
submission.Dispose();
return ret;
}
private static int RunHDInsight(string[] args)
{
if (!File.Exists(args[0]))
{
Console.Error.WriteLine("Error: Naiad program {0} does not exist.", args[0]);
Console.Error.WriteLine(Usage);
return 1;
}
AzureSubscriptions subscriptionManagement = new AzureSubscriptions();
if (AzureSubscriptionId.IsSet && AzureCertificateThumbprint.IsSet)
{
subscriptionManagement.AddSubscription(AzureSubscriptionId.StringValue, AzureCertificateThumbprint.StringValue);
}
string clusterName = null;
if (AzureClusterName.IsSet)
{
clusterName = AzureClusterName.StringValue;
if (AzureStorageAccountName.IsSet && AzureStorageAccountKey.IsSet)
{
subscriptionManagement.SetClusterAccountAsync(clusterName, AzureStorageAccountName.StringValue, AzureStorageAccountKey.StringValue).Wait();
}
}
else
{
IEnumerable<AzureCluster> clusters = subscriptionManagement.GetClusters();
if (clusters.Count() == 1)
{
clusterName = clusters.Single().Name;
}
else
{
Console.Error.WriteLine("Error: Cluster name must be specified unless there is a single configured cluster in default and supplied subscriptions");
Console.Error.WriteLine(Usage);
return 1;
}
}
AzureCluster cluster;
try
{
cluster = subscriptionManagement.GetClusterAsync(clusterName).Result;
}
catch (Exception)
{
Console.Error.WriteLine("Error: Failed to find cluster " + clusterName + " in default or supplied subscriptions");
Console.Error.WriteLine(Usage);
return 1;
}
if (cluster == null)
{
Console.Error.WriteLine("Error: Failed to find cluster {0} in default or supplied subscriptions", clusterName);
Console.Error.WriteLine(Usage);
return 1;
}
string containerName = "staging";
if (AzureStorageContainerName.IsSet)
{
containerName = AzureStorageContainerName.StringValue;
}
// The args are augmented with an additional setting containing the Azure connection string.
args = args.Concat(new string[] { "--addsetting", "Microsoft.Research.Naiad.Cluster.Azure.DefaultConnectionString", string.Format("\"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}\"", cluster.StorageAccount.Split('.').First(), cluster.StorageKey) }).ToArray();
Console.Error.WriteLine("Submitting job with args: {0}", string.Join(" ", args));
AzureDfsClient azureDfs = new AzureDfsClient(cluster.StorageAccount, cluster.StorageKey, containerName);
Uri baseUri = Utils.ToAzureUri(cluster.StorageAccount, containerName, "", null, cluster.StorageKey);
AzureYarnClient azureYarn = new AzureYarnClient(subscriptionManagement, azureDfs, baseUri, ConfigHelpers.GetPPMHome(null), clusterName);
AzureYarnSubmission submission = new AzureYarnSubmission(azureYarn, baseUri, NumHosts, args);
submission.Submit();
return submission.Join();
}
private static int RunLocal(string[] args)
{
if (!File.Exists(args[0]))
{
Console.Error.WriteLine("Error: Naiad program {0} does not exist.", args[0]);
Console.Error.WriteLine(Usage);
return 1;
}
if (!LocalJobDirectory.IsSet)
{
LocalJobDirectory.Parse("LocalJobs");
}
LocalSubmission submission = new LocalSubmission(NumHosts, args, LocalJobDirectory);
submission.Submit();
return submission.Join();
}
public static int Run(string[] args)
{
if (Environment.GetEnvironmentVariable("PELOPONNESE_HOME") != null)
{
PeloponneseHome.Parse(Environment.GetEnvironmentVariable("PELOPONNESE_HOME"));
}
else
{
string exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
PeloponneseHome.Parse(Path.GetDirectoryName(exeName));
}
Flags.Parse(ConfigurationManager.AppSettings);
args = Flags.Parse(args);
if (ShowHelp.BooleanValue)
{
Console.Error.WriteLine(Usage);
return 0;
}
if (args.Length < 1)
{
Console.Error.WriteLine("Error: No Naiad program specified.");
Console.Error.WriteLine(Usage);
return 1;
}
bool isLocal = ForceLocal.IsSet;
bool isNativeYarn = ForceYarn.IsSet;
bool isAzureHDInsight = ForceAzure.IsSet;
// first find out if we forced an execution type with an explicit argument
if (isLocal)
{
if (isNativeYarn)
{
Console.Error.WriteLine("Can't force both Yarn and Local execution.");
Console.Error.WriteLine(Usage);
return 1;
}
if (isAzureHDInsight)
{
Console.Error.WriteLine("Can't force both Azure and Local execution.");
Console.Error.WriteLine(Usage);
return 1;
}
}
else if (isNativeYarn)
{
if (isAzureHDInsight)
{
Console.Error.WriteLine("Can't force both Azure and Yarn execution.");
Console.Error.WriteLine(Usage);
return 1;
}
}
else if (!isAzureHDInsight)
{
// there's no explicit argument to force execution type, so guess based on which arguments are set
isLocal =
(LocalJobDirectory.IsSet);
isNativeYarn =
(RMHostAndPort.IsSet || NameNodeAndPort.IsSet || YarnJobQueue.IsSet || YarnAMMemory.IsSet || YarnWorkerMemory.IsSet ||
WebHdfsPort.IsSet || LauncherHostAndPort.IsSet || LogsDumpFile.IsSet);
isAzureHDInsight =
(AzureSubscriptionId.IsSet || AzureClusterName.IsSet || AzureCertificateThumbprint.IsSet ||
AzureStorageAccountName.IsSet || AzureStorageAccountKey.IsSet || AzureStorageContainerName.IsSet);
}
if (isNativeYarn)
{
if (isAzureHDInsight)
{
Console.Error.WriteLine("Can't specify Yarn and Azure options.");
Console.Error.WriteLine(Usage);
return 1;
}
if (isLocal)
{
Console.Error.WriteLine("Can't specify Yarn and local options.");
Console.Error.WriteLine(Usage);
return 1;
}
return RunNativeYarn(args);
}
else if (isAzureHDInsight)
{
if (isLocal)
{
Console.Error.WriteLine("Can't specify Azure and local options.");
Console.Error.WriteLine(Usage);
return 1;
}
return RunHDInsight(args);
}
else
{
return RunLocal(args);
}
}
public static void Main(string[] args)
{
try
{
int exitCode = Run(args);
Console.WriteLine("Application return exit code " + exitCode);
}
catch (Exception e)
{
Console.WriteLine("Exception " + e.Message + "\n" + e.ToString());
}
}
}
}
| |
// <copyright file="DriverService.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Security.Permissions;
using OpenQA.Selenium.Internal;
using OpenQA.Selenium.Remote;
namespace OpenQA.Selenium
{
/// <summary>
/// Exposes the service provided by a native WebDriver server executable.
/// </summary>
public abstract class DriverService : ICommandServer
{
private string driverServicePath;
private string driverServiceExecutableName;
private string driverServiceHostName = "localhost";
private int driverServicePort;
private bool silent;
private bool hideCommandPromptWindow;
private bool isDisposed;
private Process driverServiceProcess;
/// <summary>
/// Initializes a new instance of the <see cref="DriverService"/> class.
/// </summary>
/// <param name="servicePath">The full path to the directory containing the executable providing the service to drive the browser.</param>
/// <param name="port">The port on which the driver executable should listen.</param>
/// <param name="driverServiceExecutableName">The file name of the driver service executable.</param>
/// <param name="driverServiceDownloadUrl">A URL at which the driver service executable may be downloaded.</param>
/// <exception cref="ArgumentException">
/// If the path specified is <see langword="null"/> or an empty string.
/// </exception>
/// <exception cref="DriverServiceNotFoundException">
/// If the specified driver service executable does not exist in the specified directory.
/// </exception>
protected DriverService(string servicePath, int port, string driverServiceExecutableName, Uri driverServiceDownloadUrl)
{
if (string.IsNullOrEmpty(servicePath))
{
throw new ArgumentException("Path to locate driver executable cannot be null or empty.", "servicePath");
}
string executablePath = Path.Combine(servicePath, driverServiceExecutableName);
if (!File.Exists(executablePath))
{
throw new DriverServiceNotFoundException(string.Format(CultureInfo.InvariantCulture, "The file {0} does not exist. The driver can be downloaded at {1}", executablePath, driverServiceDownloadUrl));
}
this.driverServicePath = servicePath;
this.driverServiceExecutableName = driverServiceExecutableName;
this.driverServicePort = port;
}
/// <summary>
/// Occurs when the driver process is starting.
/// </summary>
public event EventHandler<DriverProcessStartingEventArgs> DriverProcessStarting;
/// <summary>
/// Occurs when the driver process has completely started.
/// </summary>
public event EventHandler<DriverProcessStartedEventArgs> DriverProcessStarted;
/// <summary>
/// Gets the Uri of the service.
/// </summary>
public Uri ServiceUrl
{
get { return new Uri(string.Format(CultureInfo.InvariantCulture, "http://{0}:{1}", this.driverServiceHostName, this.driverServicePort)); }
}
/// <summary>
/// Gets or sets the host name of the service. Defaults to "localhost."
/// </summary>
/// <remarks>
/// Most driver service executables do not allow connections from remote
/// (non-local) machines. This property can be used as a workaround so
/// that an IP address (like "127.0.0.1" or "::1") can be used instead.
/// </remarks>
public string HostName
{
get { return this.driverServiceHostName; }
set { this.driverServiceHostName = value; }
}
/// <summary>
/// Gets or sets the port of the service.
/// </summary>
public int Port
{
get { return this.driverServicePort; }
set { this.driverServicePort = value; }
}
/// <summary>
/// Gets or sets a value indicating whether the initial diagnostic information is suppressed
/// when starting the driver server executable. Defaults to <see langword="false"/>, meaning
/// diagnostic information should be shown by the driver server executable.
/// </summary>
public bool SuppressInitialDiagnosticInformation
{
get { return this.silent; }
set { this.silent = value; }
}
/// <summary>
/// Gets a value indicating whether the service is running.
/// </summary>
public bool IsRunning
{
get { return this.driverServiceProcess != null && !this.driverServiceProcess.HasExited; }
}
/// <summary>
/// Gets or sets a value indicating whether the command prompt window of the service should be hidden.
/// </summary>
public bool HideCommandPromptWindow
{
get { return this.hideCommandPromptWindow; }
set { this.hideCommandPromptWindow = value; }
}
/// <summary>
/// Gets the process ID of the running driver service executable. Returns 0 if the process is not running.
/// </summary>
public int ProcessId
{
get
{
if (this.IsRunning)
{
// There's a slight chance that the Process object is running,
// but does not have an ID set. This should be rare, but we
// definitely don't want to throw an exception.
try
{
return this.driverServiceProcess.Id;
}
catch (InvalidOperationException)
{
}
}
return 0;
}
}
/// <summary>
/// Gets the executable file name of the driver service.
/// </summary>
protected string DriverServiceExecutableName
{
get { return this.driverServiceExecutableName; }
}
/// <summary>
/// Gets the command-line arguments for the driver service.
/// </summary>
protected virtual string CommandLineArguments
{
get { return string.Format(CultureInfo.InvariantCulture, "--port={0}", this.driverServicePort); }
}
/// <summary>
/// Gets a value indicating the time to wait for an initial connection before timing out.
/// </summary>
protected virtual TimeSpan InitializationTimeout
{
get { return TimeSpan.FromSeconds(20); }
}
/// <summary>
/// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate.
/// </summary>
protected virtual TimeSpan TerminationTimeout
{
get { return TimeSpan.FromSeconds(10); }
}
/// <summary>
/// Gets a value indicating whether the service has a shutdown API that can be called to terminate
/// it gracefully before forcing a termination.
/// </summary>
protected virtual bool HasShutdown
{
get { return true; }
}
/// <summary>
/// Gets a value indicating whether the service is responding to HTTP requests.
/// </summary>
protected virtual bool IsInitialized
{
get
{
bool isInitialized = false;
try
{
Uri serviceHealthUri = new Uri(this.ServiceUrl, new Uri(DriverCommand.Status, UriKind.Relative));
HttpWebRequest request = HttpWebRequest.Create(serviceHealthUri) as HttpWebRequest;
request.KeepAlive = false;
request.Timeout = 5000;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
// Checking the response from the 'status' end point. Note that we are simply checking
// that the HTTP status returned is a 200 status, and that the resposne has the correct
// Content-Type header. A more sophisticated check would parse the JSON response and
// validate its values. At the moment we do not do this more sophisticated check.
isInitialized = response.StatusCode == HttpStatusCode.OK && response.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase);
response.Close();
}
catch (WebException ex)
{
Console.WriteLine(ex.Message);
}
return isInitialized;
}
}
/// <summary>
/// Releases all resources associated with this <see cref="DriverService"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Starts the DriverService if it is not already running.
/// </summary>
public void Start()
{
if (this.driverServiceProcess != null)
{
return;
}
this.driverServiceProcess = new Process();
this.driverServiceProcess.StartInfo.FileName = Path.Combine(this.driverServicePath, this.driverServiceExecutableName);
this.driverServiceProcess.StartInfo.Arguments = this.CommandLineArguments;
this.driverServiceProcess.StartInfo.UseShellExecute = false;
this.driverServiceProcess.StartInfo.CreateNoWindow = this.hideCommandPromptWindow;
DriverProcessStartingEventArgs eventArgs = new DriverProcessStartingEventArgs(this.driverServiceProcess.StartInfo);
this.OnDriverProcessStarting(eventArgs);
this.driverServiceProcess.Start();
bool serviceAvailable = this.WaitForServiceInitialization();
DriverProcessStartedEventArgs processStartedEventArgs = new DriverProcessStartedEventArgs(this.driverServiceProcess);
this.OnDriverProcessStarted(processStartedEventArgs);
if (!serviceAvailable)
{
string msg = "Cannot start the driver service on " + this.ServiceUrl;
throw new WebDriverException(msg);
}
}
/// <summary>
/// Finds the specified driver service executable.
/// </summary>
/// <param name="executableName">The file name of the executable to find.</param>
/// <param name="downloadUrl">A URL at which the driver service executable may be downloaded.</param>
/// <returns>The directory containing the driver service executable.</returns>
/// <exception cref="DriverServiceNotFoundException">
/// If the specified driver service executable does not exist in the current directory or in a directory on the system path.
/// </exception>
protected static string FindDriverServiceExecutable(string executableName, Uri downloadUrl)
{
string serviceDirectory = FileUtilities.FindFile(executableName);
if (string.IsNullOrEmpty(serviceDirectory))
{
throw new DriverServiceNotFoundException(string.Format(CultureInfo.InvariantCulture, "The {0} file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at {1}.", executableName, downloadUrl));
}
return serviceDirectory;
}
/// <summary>
/// Releases all resources associated with this <see cref="DriverService"/>.
/// </summary>
/// <param name="disposing"><see langword="true"/> if the Dispose method was explicitly called; otherwise, <see langword="false"/>.</param>
protected virtual void Dispose(bool disposing)
{
if (!this.isDisposed)
{
if (disposing)
{
this.Stop();
}
this.isDisposed = true;
}
}
/// <summary>
/// Raises the <see cref="DriverProcessStarting"/> event.
/// </summary>
/// <param name="eventArgs">A <see cref="DriverProcessStartingEventArgs"/> that contains the event data.</param>
protected void OnDriverProcessStarting(DriverProcessStartingEventArgs eventArgs)
{
if (eventArgs == null)
{
throw new ArgumentNullException("eventArgs", "eventArgs must not be null");
}
if (this.DriverProcessStarting != null)
{
this.DriverProcessStarting(this, eventArgs);
}
}
/// <summary>
/// Raises the <see cref="DriverProcessStarted"/> event.
/// </summary>
/// <param name="eventArgs">A <see cref="DriverProcessStartedEventArgs"/> that contains the event data.</param>
protected void OnDriverProcessStarted(DriverProcessStartedEventArgs eventArgs)
{
if (eventArgs == null)
{
throw new ArgumentNullException("eventArgs", "eventArgs must not be null");
}
if (this.DriverProcessStarted != null)
{
this.DriverProcessStarted(this, eventArgs);
}
}
/// <summary>
/// Stops the DriverService.
/// </summary>
private void Stop()
{
if (this.IsRunning)
{
if (this.HasShutdown)
{
Uri shutdownUrl = new Uri(this.ServiceUrl, "/shutdown");
DateTime timeout = DateTime.Now.Add(this.TerminationTimeout);
while (this.IsRunning && DateTime.Now < timeout)
{
try
{
// Issue the shutdown HTTP request, then wait a short while for
// the process to have exited. If the process hasn't yet exited,
// we'll retry. We wait for exit here, since catching the exception
// for a failed HTTP request due to a closed socket is particularly
// expensive.
HttpWebRequest request = HttpWebRequest.Create(shutdownUrl) as HttpWebRequest;
request.KeepAlive = false;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
response.Close();
this.driverServiceProcess.WaitForExit(3000);
}
catch (WebException)
{
}
}
}
// If at this point, the process still hasn't exited, wait for one
// last-ditch time, then, if it still hasn't exited, kill it. Note
// that falling into this branch of code should be exceedingly rare.
if (this.IsRunning)
{
this.driverServiceProcess.WaitForExit(Convert.ToInt32(this.TerminationTimeout.TotalMilliseconds));
if (!this.driverServiceProcess.HasExited)
{
this.driverServiceProcess.Kill();
}
}
this.driverServiceProcess.Dispose();
this.driverServiceProcess = null;
}
}
/// <summary>
/// Waits until a the service is initialized, or the timeout set
/// by the <see cref="InitializationTimeout"/> property is reached.
/// </summary>
/// <returns><see langword="true"/> if the service is properly started and receiving HTTP requests;
/// otherwise; <see langword="false"/>.</returns>
private bool WaitForServiceInitialization()
{
bool isInitialized = false;
DateTime timeout = DateTime.Now.Add(this.InitializationTimeout);
while (!isInitialized && DateTime.Now < timeout)
{
// If the driver service process has exited, we can exit early.
if (!this.IsRunning)
{
break;
}
isInitialized = this.IsInitialized;
}
return isInitialized;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests
{
public class TaskFactory_FromAsyncTests
{
// Exercise the FromAsync() methods in Task and Task<TResult>.
[Fact]
public static void RunAPMFactoryTests()
{
FakeAsyncClass fac = new FakeAsyncClass();
Task t = null;
Task<string> f = null;
string check;
object stateObject = new object();
// Exercise void overload that takes IAsyncResult instead of StartMethod
t = Task.Factory.FromAsync(fac.StartWrite("", 0, 0, null, null), delegate (IAsyncResult iar) { });
t.Wait();
check = fac.ToString();
Assert.Equal(0, check.Length);
//CreationOption overload
t = Task.Factory.FromAsync(fac.StartWrite("", 0, 0, null, null), delegate (IAsyncResult iar) { }, TaskCreationOptions.None);
t.Wait();
check = fac.ToString();
Assert.Equal(0, check.Length);
// Exercise 0-arg void option
t = Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, stateObject);
t.Wait();
Assert.Equal(0, check.Length);
Assert.Same(stateObject, ((IAsyncResult)t).AsyncState);
// Exercise 1-arg void option
Task.Factory.FromAsync(
fac.StartWrite,
fac.EndWrite,
"1234", stateObject).Wait();
check = fac.ToString();
Assert.Equal("1234", check);
Assert.Same(stateObject, ((IAsyncResult)t).AsyncState);
// Exercise 2-arg void option
Task.Factory.FromAsync(
fac.StartWrite,
fac.EndWrite,
"aaaabcdef",
4, stateObject).Wait();
check = fac.ToString();
Assert.Equal("1234aaaa", check);
Assert.Same(stateObject, ((IAsyncResult)t).AsyncState);
// Exercise 3-arg void option
Task.Factory.FromAsync(
fac.StartWrite,
fac.EndWrite,
"abcdzzzz",
4,
4,
stateObject).Wait();
check = fac.ToString();
Assert.Equal("1234aaaazzzz", check);
Assert.Same(stateObject, ((IAsyncResult)t).AsyncState);
// Read side, exercises getting return values from EndMethod
char[] carray = new char[100];
// Exercise 3-arg value option
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
4, // maxchars
carray,
0,
stateObject);
string s = f.Result;
Assert.Equal("1234", s);
Assert.Equal('1', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 2-arg value option
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
4,
carray,
stateObject);
s = f.Result;
Assert.Equal("aaaa", s);
Assert.Equal('a', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 1-arg value option
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
1,
stateObject);
s = f.Result;
Assert.Equal("z", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 0-arg value option
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
stateObject);
s = f.Result;
Assert.Equal("zzz", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
//
// Do all of the read tests again, except with Task.Factory.FromAsync<string>(), instead of Task<string>.Factory.FromAsync().
//
fac.EndWrite(fac.StartWrite("12345678aaaaAAAAzzzz", null, null));
// Exercise 3-arg value option
f = Task.Factory.FromAsync<int, char[], int, string>(
//f = Task.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
4, // maxchars
carray,
0,
stateObject);
s = f.Result;
Assert.Equal("1234", s);
Assert.Equal('1', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// one more with the creationOptions overload
f = Task.Factory.FromAsync<int, char[], int, string>(
//f = Task.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
4, // maxchars
carray,
0,
stateObject,
TaskCreationOptions.None);
s = f.Result;
Assert.Equal("5678", s);
Assert.Equal('5', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 2-arg value option
f = Task.Factory.FromAsync<int, char[], string>(
fac.StartRead,
fac.EndRead,
4,
carray,
stateObject);
s = f.Result;
Assert.Equal("aaaa", s);
Assert.Equal('a', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
//one more with the creation option overload
f = Task.Factory.FromAsync<int, char[], string>(
fac.StartRead,
fac.EndRead,
4,
carray,
stateObject,
TaskCreationOptions.None);
s = f.Result;
Assert.Equal("AAAA", s);
Assert.Equal('A', carray[0]);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 1-arg value option
f = Task.Factory.FromAsync<int, string>(
fac.StartRead,
fac.EndRead,
1,
stateObject);
s = f.Result;
Assert.Equal("z", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// one more with creation option overload
f = Task.Factory.FromAsync<int, string>(
fac.StartRead,
fac.EndRead,
1,
stateObject,
TaskCreationOptions.None);
s = f.Result;
Assert.Equal("z", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Exercise 0-arg value option
f = Task.Factory.FromAsync<string>(
fac.StartRead,
fac.EndRead,
stateObject);
s = f.Result;
Assert.Equal("zz", s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
//one more with Creation options overload
f = Task.Factory.FromAsync<string>(
fac.StartRead,
fac.EndRead,
stateObject,
TaskCreationOptions.None);
s = f.Result;
Assert.Equal(string.Empty, s);
Assert.Same(stateObject, ((IAsyncResult)f).AsyncState);
// Inject a few more characters into the buffer
fac.EndWrite(fac.StartWrite("0123456789", null, null));
// Exercise value overload that accepts an IAsyncResult instead of a beginMethod.
f = Task<string>.Factory.FromAsync(
fac.StartRead(4, null, null),
fac.EndRead);
s = f.Result;
Assert.Equal("0123", s);
f = Task.Factory.FromAsync<string>(
fac.StartRead(4, null, null),
fac.EndRead);
s = f.Result;
Assert.Equal("4567", s);
// Test Exception handling from beginMethod
Assert.ThrowsAsync<NullReferenceException>(() =>
t = Task.Factory.FromAsync(
fac.StartWrite,
fac.EndWrite,
(string)null, // will cause null.Length to be dereferenced
null));
// Test Exception handling from asynchronous logic
f = Task<string>.Factory.FromAsync(
fac.StartRead,
fac.EndRead,
10,
carray,
200, // offset past end of array
null);
Assert.Throws<AggregateException>(() =>
check = f.Result);
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, null, TaskCreationOptions.LongRunning));
Assert.ThrowsAsync<ArgumentOutOfRangeException>(() =>
Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, null, TaskCreationOptions.PreferFairness));
// Empty the buffer, then inject a few more characters into the buffer
fac.ResetStateTo("0123456789");
Task asyncTask = null;
//
// Now check that the endMethod throwing an OCE correctly results in a canceled task.
//
// Test IAsyncResult overload that returns Task
asyncTask = Task.Factory.FromAsync(
fac.StartWrite("abc", null, null),
delegate (IAsyncResult iar) { throw new OperationCanceledException("FromAsync"); });
AggregateException ae = Assert.Throws<AggregateException>(() =>
{
asyncTask.Wait();
});
Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType());
Assert.Equal(TaskStatus.Canceled, asyncTask.Status);
// Test beginMethod overload that returns Task
asyncTask = Task.Factory.FromAsync(
fac.StartWrite,
delegate (IAsyncResult iar) { throw new OperationCanceledException("FromAsync"); },
"abc",
null);
ae = Assert.Throws<AggregateException>(() =>
{
asyncTask.Wait();
});
Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType());
Assert.Equal(TaskStatus.Canceled, asyncTask.Status);
// Test IAsyncResult overload that returns Task<string>
Task<string> asyncFuture = null;
asyncFuture = Task<string>.Factory.FromAsync(
fac.StartRead(3, null, null),
delegate (IAsyncResult iar) { throw new OperationCanceledException("FromAsync"); });
ae = Assert.Throws<AggregateException>(() =>
{
asyncTask.Wait();
});
Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType());
Assert.Equal(TaskStatus.Canceled, asyncTask.Status);
// Test beginMethod overload that returns Task<string>
asyncFuture = null;
asyncFuture = Task<string>.Factory.FromAsync(
fac.StartRead,
delegate (IAsyncResult iar) { throw new OperationCanceledException("FromAsync"); },
3, null);
ae = Assert.Throws<AggregateException>(() =>
{
asyncFuture.Wait();
});
Assert.Equal(typeof(TaskCanceledException), ae.InnerException.GetType());
Assert.Equal(TaskStatus.Canceled, asyncFuture.Status);
//
// Make sure that tasks aren't left hanging if StartXYZ() throws an exception
//
Task foo = Task.Factory.StartNew(delegate
{
// Every one of these should throw an exception from StartWrite/StartRead. Test to
// see that foo is allowed to complete (i.e., no dangling attached tasks from FromAsync()
// calls.
Task foo1 = Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, (string)null, null, TaskCreationOptions.AttachedToParent);
Task foo2 = Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, (string)null, 4, null, TaskCreationOptions.AttachedToParent);
Task foo3 = Task.Factory.FromAsync(fac.StartWrite, fac.EndWrite, (string)null, 4, 4, null, TaskCreationOptions.AttachedToParent);
Task<string> foo4 = Task<string>.Factory.FromAsync(fac.StartRead, fac.EndRead, -1, null, TaskCreationOptions.AttachedToParent);
Task<string> foo5 = Task<string>.Factory.FromAsync(fac.StartRead, fac.EndRead, -1, (char[])null, null, TaskCreationOptions.AttachedToParent);
Task<string> foo6 = Task<string>.Factory.FromAsync(fac.StartRead, fac.EndRead, -1, (char[])null, 200, null, TaskCreationOptions.AttachedToParent);
});
Debug.WriteLine("RunAPMFactoryTests: Waiting on task w/ faulted FromAsync() calls. If we hang, there is a problem");
Assert.Throws<AggregateException>(() =>
{
foo.Wait();
});
}
// This class is used in testing APM Factory tests.
private class FakeAsyncClass
{
private List<char> _list = new List<char>();
public override string ToString()
{
StringBuilder sb = new StringBuilder();
lock (_list)
{
for (int i = 0; i < _list.Count; i++)
sb.Append(_list[i]);
}
return sb.ToString();
}
// Silly use of Write, but I wanted to test no-argument StartXXX handling.
public IAsyncResult StartWrite(AsyncCallback cb, object o)
{
return StartWrite("", 0, 0, cb, o);
}
public IAsyncResult StartWrite(string s, AsyncCallback cb, object o)
{
return StartWrite(s, 0, s.Length, cb, o);
}
public IAsyncResult StartWrite(string s, int length, AsyncCallback cb, object o)
{
return StartWrite(s, 0, length, cb, o);
}
public IAsyncResult StartWrite(string s, int offset, int length, AsyncCallback cb, object o)
{
myAsyncResult mar = new myAsyncResult(cb, o);
// Allow for exception throwing to test our handling of that.
if (s == null)
throw new ArgumentNullException("s");
Task t = Task.Factory.StartNew(delegate
{
//Task.Delay(100).Wait();
try
{
lock (_list)
{
for (int i = 0; i < length; i++)
_list.Add(s[i + offset]);
}
mar.Signal();
}
catch (Exception e) { mar.Signal(e); }
});
return mar;
}
public void EndWrite(IAsyncResult iar)
{
myAsyncResult mar = iar as myAsyncResult;
mar.Wait();
if (mar.IsFaulted)
throw (mar.Exception);
}
public IAsyncResult StartRead(AsyncCallback cb, object o)
{
return StartRead(128 /*=maxbytes*/, null, 0, cb, o);
}
public IAsyncResult StartRead(int maxBytes, AsyncCallback cb, object o)
{
return StartRead(maxBytes, null, 0, cb, o);
}
public IAsyncResult StartRead(int maxBytes, char[] buf, AsyncCallback cb, object o)
{
return StartRead(maxBytes, buf, 0, cb, o);
}
public IAsyncResult StartRead(int maxBytes, char[] buf, int offset, AsyncCallback cb, object o)
{
myAsyncResult mar = new myAsyncResult(cb, o);
// Allow for exception throwing to test our handling of that.
if (maxBytes == -1)
throw new ArgumentException("maxBytes");
Task t = Task.Factory.StartNew(delegate
{
//Thread.Sleep(100);
StringBuilder sb = new StringBuilder();
int bytesRead = 0;
try
{
lock (_list)
{
while ((_list.Count > 0) && (bytesRead < maxBytes))
{
sb.Append(_list[0]);
if (buf != null) { buf[offset] = _list[0]; offset++; }
_list.RemoveAt(0);
bytesRead++;
}
}
mar.SignalState(sb.ToString());
}
catch (Exception e) { mar.Signal(e); }
});
return mar;
}
public string EndRead(IAsyncResult iar)
{
myAsyncResult mar = iar as myAsyncResult;
if (mar.IsFaulted)
throw (mar.Exception);
return (string)mar.AsyncState;
}
public void ResetStateTo(string s)
{
_list.Clear();
for (int i = 0; i < s.Length; i++)
_list.Add(s[i]);
}
}
// This is an internal class used for a concrete IAsyncResult in the APM Factory tests.
private class myAsyncResult : IAsyncResult
{
private volatile int _isCompleted;
private ManualResetEvent _asyncWaitHandle;
private AsyncCallback _callback;
private object _asyncState;
private Exception _exception;
public myAsyncResult(AsyncCallback cb, object o)
{
_isCompleted = 0;
_asyncWaitHandle = new ManualResetEvent(false);
_callback = cb;
_asyncState = o;
_exception = null;
}
public bool IsCompleted
{
get { return (_isCompleted == 1); }
}
public bool CompletedSynchronously
{
get { return false; }
}
public WaitHandle AsyncWaitHandle
{
get { return _asyncWaitHandle; }
}
public object AsyncState
{
get { return _asyncState; }
}
public void Signal()
{
_isCompleted = 1;
_asyncWaitHandle.Set();
if (_callback != null)
_callback(this);
}
public void Signal(Exception e)
{
_exception = e;
Signal();
}
public void SignalState(object o)
{
_asyncState = o;
Signal();
}
public void Wait()
{
_asyncWaitHandle.WaitOne();
if (_exception != null)
throw (_exception);
}
public bool IsFaulted
{
get { return ((_isCompleted == 1) && (_exception != null)); }
}
public Exception Exception
{
get { return _exception; }
}
}
}
}
| |
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
/*
Wrapper for Objective-C iOS SDK
*/
public class GAIHandler {
#if UNITY_IPHONE && !UNITY_EDITOR
[DllImport("__Internal")]
private static extern void setOptOut(bool optOut);
public void _setOptOut(bool optOut){
setOptOut(optOut);
}
[DllImport("__Internal")]
private static extern void setDispatchInterval(int time);
public void _setDispatchInterval(int time){
setDispatchInterval(time);
}
[DllImport("__Internal")]
private static extern void anonymizeIP();
public void _anonymizeIP(){
anonymizeIP();
}
[DllImport("__Internal")]
private static extern void enableIDFACollection();
public void _enableIDFACollection(){
enableIDFACollection();
}
[DllImport("__Internal")]
private static extern void setTrackUncaughtExceptions(bool trackUncaughtExceptions);
public void _setTrackUncaughtExceptions(bool trackUncaughtExceptions){
setTrackUncaughtExceptions(trackUncaughtExceptions);
}
[DllImport("__Internal")]
private static extern void setDryRun(bool dryRun);
public void _setDryRun(bool dryRun){
setDryRun(dryRun);
}
[DllImport("__Internal")]
private static extern void setSampleFrequency(int sampleFrequency);
public void _setSampleFrequency(int sampleFrequency){
setSampleFrequency(sampleFrequency);
}
[DllImport("__Internal")]
private static extern void setLogLevel(int logLevel);
public void _setLogLevel(int logLevel){
setLogLevel(logLevel);
}
[DllImport("__Internal")]
private static extern void startSession();
public void _startSession(){
startSession();
}
[DllImport("__Internal")]
private static extern void stopSession();
public void _stopSession(){
stopSession();
}
[DllImport("__Internal")]
private static extern IntPtr trackerWithName(string name, string trackingId);
public IntPtr _getTrackerWithName(string name, string trackingId){
return trackerWithName(name, trackingId);
}
[DllImport("__Internal")]
private static extern IntPtr trackerWithTrackingId(string trackingId);
public IntPtr _getTrackerWithTrackingId(string trackingId){
return trackerWithTrackingId(trackingId);
}
[DllImport("__Internal")]
private static extern void set(string parameterName, string value);
public void _set(string parameterName, object value){
set(parameterName, value.ToString());
}
[DllImport("__Internal")]
private static extern void setBool(string parameterName, bool value);
public void _setBool(string parameterName, bool value){
setBool(parameterName, value);
}
[DllImport("__Internal")]
private static extern string get(string parameterName);
public string _get(string parameterName){
return get(parameterName);
}
[DllImport("__Internal")]
private static extern void dispatch();
public void _dispatchHits(){
dispatch();
}
[DllImport("__Internal")]
private static extern void sendAppView(string screenName);
public void _sendAppView(AppViewHitBuilder builder){
_buildCustomMetricsDictionary(builder);
_buildCustomDimensionsDictionary(builder);
_buildCampaignParametersDictionary(builder);
sendAppView(builder.GetScreenName());
}
[DllImport("__Internal")]
private static extern void sendEvent(string category, string action, string label, long value);
public void _sendEvent(EventHitBuilder builder){
_buildCustomMetricsDictionary(builder);
_buildCustomDimensionsDictionary(builder);
_buildCampaignParametersDictionary(builder);
sendEvent(builder.GetEventCategory(), builder.GetEventAction(), builder.GetEventLabel(), builder.GetEventValue());
}
[DllImport("__Internal")]
private static extern void sendTransaction(string transactionID, string affiliation, double revenue, double tax, double shipping, string currencyCode);
public void _sendTransaction(TransactionHitBuilder builder){
_buildCustomMetricsDictionary(builder);
_buildCustomDimensionsDictionary(builder);
_buildCampaignParametersDictionary(builder);
sendTransaction(builder.GetTransactionID(), builder.GetAffiliation(), builder.GetRevenue(), builder.GetTax(), builder.GetShipping(), builder.GetCurrencyCode());
}
[DllImport("__Internal")]
private static extern void sendItemWithTransaction(string transactionID, string name, string sku, string category, double price, long quantity, string currencyCode);
public void _sendItemWithTransaction(ItemHitBuilder builder){
_buildCustomMetricsDictionary(builder);
_buildCustomDimensionsDictionary(builder);
_buildCampaignParametersDictionary(builder);
sendItemWithTransaction(builder.GetTransactionID(), builder.GetName(), builder.GetSKU(), builder.GetCategory(), builder.GetPrice(), builder.GetQuantity(),builder.GetCurrencyCode());
}
[DllImport("__Internal")]
private static extern void sendException(string exceptionDescription, bool isFatal);
public void _sendException(ExceptionHitBuilder builder){
_buildCustomMetricsDictionary(builder);
_buildCustomDimensionsDictionary(builder);
_buildCampaignParametersDictionary(builder);
sendException(builder.GetExceptionDescription(), builder.IsFatal());
}
[DllImport("__Internal")]
private static extern void sendSocial(string socialNetwork, string socialAction, string targetUrl);
public void _sendSocial(SocialHitBuilder builder){
_buildCustomMetricsDictionary(builder);
_buildCustomDimensionsDictionary(builder);
_buildCampaignParametersDictionary(builder);
sendSocial(builder.GetSocialNetwork(), builder.GetSocialAction(), builder.GetSocialTarget());
}
[DllImport("__Internal")]
private static extern void sendTiming(string timingCategory,long timingInterval, string timingName, string timingLabel);
public void _sendTiming(TimingHitBuilder builder){
_buildCustomMetricsDictionary(builder);
_buildCustomDimensionsDictionary(builder);
_buildCampaignParametersDictionary(builder);
sendTiming(builder.GetTimingCategory(), builder.GetTimingInterval(), builder.GetTimingName(), builder.GetTimingLabel());
}
[DllImport("__Internal")]
private static extern void addCustomDimensionToDictionary(int key, string value);
public void _buildCustomDimensionsDictionary<T>(HitBuilder<T> builder){
foreach(KeyValuePair<int, string> entry in builder.GetCustomDimensions())
{
addCustomDimensionToDictionary(entry.Key, entry.Value);
}
}
[DllImport("__Internal")]
private static extern void addCustomMetricToDictionary(int key, string value);
public void _buildCustomMetricsDictionary<T>(HitBuilder<T> builder){
foreach(KeyValuePair<int, float> entry in builder.GetCustomMetrics())
{
addCustomMetricToDictionary(entry.Key, entry.Value.ToString());
}
}
[DllImport("__Internal")]
private static extern void buildCampaignParametersDictionary(string source, string medium, string name, string content, string keyword);
public void _buildCampaignParametersDictionary<T>(HitBuilder<T> builder){
if(!String.IsNullOrEmpty(builder.GetCampaignSource())){
buildCampaignParametersDictionary(builder.GetCampaignSource(),
builder.GetCampaignMedium() != null ? builder.GetCampaignMedium() : "",
builder.GetCampaignName() != null? builder.GetCampaignName() : "",
builder.GetCampaignContent() != null? builder.GetCampaignContent() : "",
builder.GetCampaignKeyword() != null? builder.GetCampaignKeyword() : "");
} else if(!String.IsNullOrEmpty(builder.GetCampaignMedium()) ||
!String.IsNullOrEmpty(builder.GetCampaignName()) ||
!String.IsNullOrEmpty(builder.GetCampaignMedium()) ||
!String.IsNullOrEmpty(builder.GetCampaignContent()) ||
!String.IsNullOrEmpty(builder.GetCampaignKeyword())) {
Debug.Log("A required parameter (campaign source) is null or empty. No campaign parameters will be added to hit.");
}
}
#endif
}
| |
using System;
using System.Collections;
using System.Data;
using System.Text;
using PCSComMaterials.Inventory.DS;
using PCSComProduct.Items.DS;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
using PCSComMaterials.Plan.DS;
namespace PCSComMaterials.Plan.BO
{
public interface IMRPCycleOptionBO
{
int Add(DataSet pdstDetailData, object pobjMasterData);
void UpdateMasterAndDetail(DataSet pdstDetailData, object pobjMasterData);
DataSet GetDetailByMasterID(int pintCycleOptionMasterID);
void DeleteCycleOptionMasterAndDetail(int pintCCNID, int pintCycleOptionMasterID, DataSet pdstData);
DataTable GetCycleOptionMaster(int pintMasterID);
}
/// <summary>
/// Summary description for MRPCycleOptionBO.
/// </summary>
public class MRPCycleOptionBO : IMRPCycleOptionBO
{
public MRPCycleOptionBO()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// Add
/// </summary>
/// <param name="pdstDetailData"></param>
/// <param name="pobjMasterData"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Thursday, August 11 2005</date>
public int Add(DataSet pdstDetailData, object pobjMasterData)
{
try
{
//Add and Return ID
MTR_MRPCycleOptionMasterDS dsMTR_MRPCycleOptionMaster = new MTR_MRPCycleOptionMasterDS();
int pintMasterID = dsMTR_MRPCycleOptionMaster.AddAndReturnID(pobjMasterData);
foreach (DataRow drow in pdstDetailData.Tables[0].Rows)
{
drow[MTR_MRPCycleOptionDetailTable.MRPCYCLEOPTIONMASTERID_FLD] = pintMasterID;
}
//Update DataSet
MTR_MRPCycleOptionDetailDS dsMTR_MRPCycleOptionDetail = new MTR_MRPCycleOptionDetailDS();
dsMTR_MRPCycleOptionDetail.UpdateDataSet(pdstDetailData);
return pintMasterID;
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// UpdateMasterAndDetail
/// </summary>
/// <param name="pdstDetailData"></param>
/// <param name="pobjMasterData"></param>
/// <author>Trada</author>
/// <date>Friday, August 12 2005</date>
public void UpdateMasterAndDetail(DataSet pdstDetailData, object pobjMasterData)
{
try
{
//Update Master
MTR_MRPCycleOptionMasterVO objObject = (MTR_MRPCycleOptionMasterVO) pobjMasterData;
MTR_MRPCycleOptionMasterDS dsMTR_MRPCycleOptionMaster = new MTR_MRPCycleOptionMasterDS();
dsMTR_MRPCycleOptionMaster.Update(pobjMasterData);
//Update Detail
foreach (DataRow drow in pdstDetailData.Tables[0].Rows)
{
if (drow.RowState == DataRowState.Added)
{
drow[MTR_MRPCycleOptionDetailTable.MRPCYCLEOPTIONMASTERID_FLD] = objObject.MRPCycleOptionMasterID;
}
}
MTR_MRPCycleOptionDetailDS dsMTR_MRPCycleOptionDetail = new MTR_MRPCycleOptionDetailDS();
dsMTR_MRPCycleOptionDetail.UpdateDataSet(pdstDetailData);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// GetDetailByMasterID
/// </summary>
/// <param name="pintCycleOptionMasterID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Thursday, August 11 2005</date>
public DataSet GetDetailByMasterID(int pintCycleOptionMasterID)
{
try
{
MTR_MRPCycleOptionDetailDS dsMTR_MRPCycleOptionDetail = new MTR_MRPCycleOptionDetailDS();
DataSet dstMTR_MRPCycleOptionDetail = new DataSet();
dstMTR_MRPCycleOptionDetail = dsMTR_MRPCycleOptionDetail.List(pintCycleOptionMasterID);
return dstMTR_MRPCycleOptionDetail;
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// DeleteCycleOptionMasterAndDetail
/// </summary>
/// <param name="pintCycleOptionMasterID"></param>
/// <param name="pdstData"></param>
/// <author>Trada</author>
/// <date>Thursday, August 11 2005</date>
public void DeleteCycleOptionMasterAndDetail(int pintCCNID,int pintCycleOptionMasterID, DataSet pdstData)
{
foreach (DataRow drow in pdstData.Tables[0].Rows)
{
if (drow.RowState != DataRowState.Deleted)
{
drow.Delete();
}
}
//Delete Detail
MTR_MRPCycleOptionDetailDS dsMTR_MRPCycleOptionDetail = new MTR_MRPCycleOptionDetailDS();
dsMTR_MRPCycleOptionDetail.UpdateDataSet(pdstData);
//Delete MTR_CPO
MTR_CPODS dsMTR_CPO = new MTR_CPODS();
dsMTR_CPO.Delete(pintCCNID, pintCycleOptionMasterID);
//Delete Master
MTR_MRPCycleOptionMasterDS dsMTR_MRPCycleOptionMaster = new MTR_MRPCycleOptionMasterDS();
dsMTR_MRPCycleOptionMaster.Delete(pintCycleOptionMasterID);
}
public void DeleteMRPResult(int pintCCNID, int pintCycleOptionID)
{
//Delete MTR_CPO
MTR_CPODS dsMTR_CPO = new MTR_CPODS();
dsMTR_CPO.Delete(pintCCNID, pintCycleOptionID);
}
/// <summary>
/// GetCycleOptionMaster
/// </summary>
/// <param name="pintMasterID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Friday, August 12 2005</date>
public DataTable GetCycleOptionMaster(int pintMasterID)
{
try
{
MTR_MRPCycleOptionMasterDS dsMTR_MRPCycleOptionMaster = new MTR_MRPCycleOptionMasterDS();
return dsMTR_MRPCycleOptionMaster.GetMRPCycleOptionMaster(pintMasterID);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Insert a new record into database
/// </summary>
public void Add(object pObjectDetail)
{
throw new NotImplementedException();
}
/// <summary>
/// Delete record by condition
/// </summary>
public void Delete(object pObjectVO)
{
throw new NotImplementedException();
}
/// <summary>
/// Get the object information by ID of VO class
/// </summary>
public object GetObjectVO(int pintID, string VOclass)
{
throw new NotImplementedException();
}
/// <summary>
/// Return the DataSet (list of record) by inputing the FieldList and Condition
/// </summary>
public void UpdateDataSet(DataSet dstData)
{
throw new NotImplementedException();
}
/// <summary>
/// Update into Database
/// </summary>
public void Update(object pObjectDetail)
{
throw new NotImplementedException();
}
public DataTable ListOutsideItem()
{
ITM_ProductDS dsProduct = new ITM_ProductDS();
return dsProduct.ListOutsideItem();
}
public DataTable GetBeginMRP(DateTime pdtmAsOfDate)
{
IV_MasLocCacheDS dsMasLoc = new IV_MasLocCacheDS();
return dsMasLoc.GetBeginQuantityOfNiguri(pdtmAsOfDate);
}
public DataTable GetAvailableQuantityForPlan(DateTime dtmDate)
{
IV_BalanceBinDS dsBin = new IV_BalanceBinDS();
return dsBin.GetAvailableQuantityForPlan(dtmDate);
}
public DataTable getAllReleasePOForItems(StringBuilder pstrItemsID, DateTime pdtmFromDate, DateTime pdtmToDate, int pintMasLocID)
{
MRPRegenerationProcessDS dsProcess = new MRPRegenerationProcessDS();
return dsProcess.getAllReleasePOForItems(pstrItemsID, pdtmFromDate, pdtmToDate, pintMasLocID);
}
public DataTable getAllReleaseSOForItems(StringBuilder pstrItemsID, DateTime pdtmFromDate, DateTime pdtmToDate, int pintMasLocID)
{
MRPRegenerationProcessDS dsProcess = new MRPRegenerationProcessDS();
return dsProcess.getAllReleaseSOForItems(pstrItemsID, pdtmFromDate, pdtmToDate, pintMasLocID);
}
public DataTable getAllCPOForItems(StringBuilder pstrItemsID, DateTime pdtmFromDate, DateTime pdtmToDate, int pintMasLocID)
{
MRPRegenerationProcessDS dsProcess = new MRPRegenerationProcessDS();
return dsProcess.getAllCPOForItems(pstrItemsID, pdtmFromDate, pdtmToDate, pintMasLocID);
}
public void UpdateBeginMRP(DataTable pdtbData)
{
MRPRegenerationProcessDS dsMRP = new MRPRegenerationProcessDS();
dsMRP.UpdateBeginMRP(pdtbData);
}
}
}
| |
#if !LOCALTEST
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace System.IO {
public class StreamReader : TextReader {
const int DefaultBufferSize = 1024;
const int DefaultFileBufferSize = 4096;
const int MinimumBufferSize = 128;
//
// The input buffer
//
byte[] input_buffer;
//
// The decoded buffer from the above input buffer
//
char[] decoded_buffer;
//
// Decoded bytes in decoded_buffer.
//
int decoded_count;
//
// Current position in the decoded_buffer
//
int pos;
//
// The buffer size that we are using
//
int buffer_size;
int do_checks;
Encoding encoding;
Decoder decoder;
Stream base_stream;
bool mayBlock;
StringBuilder line_builder;
private class NullStreamReader : StreamReader {
public override int Peek() {
return -1;
}
public override int Read() {
return -1;
}
public override int Read([In, Out] char[] buffer, int index, int count) {
return 0;
}
public override string ReadLine() {
return null;
}
public override string ReadToEnd() {
return String.Empty;
}
public override Stream BaseStream {
get { return Stream.Null; }
}
public override Encoding CurrentEncoding {
get { return Encoding.Unicode; }
}
}
public new static readonly StreamReader Null = (StreamReader)(new NullStreamReader());
internal StreamReader() { }
public StreamReader(Stream stream)
: this(stream, Encoding.UTF8Unmarked, true, DefaultBufferSize) { }
public StreamReader(Stream stream, bool detect_encoding_from_bytemarks)
: this(stream, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultBufferSize) { }
public StreamReader(Stream stream, Encoding encoding)
: this(stream, encoding, true, DefaultBufferSize) { }
public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks)
: this(stream, encoding, detect_encoding_from_bytemarks, DefaultBufferSize) { }
public StreamReader(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size) {
Initialize(stream, encoding, detect_encoding_from_bytemarks, buffer_size);
}
public StreamReader(string path)
: this(path, Encoding.UTF8Unmarked, true, DefaultFileBufferSize) { }
public StreamReader(string path, bool detect_encoding_from_bytemarks)
: this(path, Encoding.UTF8Unmarked, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
public StreamReader(string path, Encoding encoding)
: this(path, encoding, true, DefaultFileBufferSize) { }
public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks)
: this(path, encoding, detect_encoding_from_bytemarks, DefaultFileBufferSize) { }
public StreamReader(string path, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size) {
if (null == path) {
throw new ArgumentNullException("path");
}
if (String.Empty == path) {
throw new ArgumentException("Empty path not allowed");
}
if (path.IndexOfAny(Path.InvalidPathChars) != -1) {
throw new ArgumentException("path contains invalid characters");
}
if (null == encoding) {
throw new ArgumentNullException("encoding");
}
if (buffer_size <= 0) {
throw new ArgumentOutOfRangeException("buffer_size", "The minimum size of the buffer must be positive");
}
Stream stream = File.OpenRead(path);
Initialize(stream, encoding, detect_encoding_from_bytemarks, buffer_size);
}
internal void Initialize(Stream stream, Encoding encoding, bool detect_encoding_from_bytemarks, int buffer_size) {
if (null == stream) {
throw new ArgumentNullException("stream");
}
if (null == encoding) {
throw new ArgumentNullException("encoding");
}
if (!stream.CanRead) {
throw new ArgumentException("Cannot read stream");
}
if (buffer_size <= 0) {
throw new ArgumentOutOfRangeException("buffer_size", "The minimum size of the buffer must be positive");
}
if (buffer_size < MinimumBufferSize) {
buffer_size = MinimumBufferSize;
}
base_stream = stream;
input_buffer = new byte[buffer_size];
this.buffer_size = buffer_size;
this.encoding = encoding;
decoder = encoding.GetDecoder();
byte[] preamble = encoding.GetPreamble();
do_checks = detect_encoding_from_bytemarks ? 1 : 0;
do_checks += (preamble.Length == 0) ? 0 : 2;
decoded_buffer = new char[encoding.GetMaxCharCount(buffer_size)];
decoded_count = 0;
pos = 0;
}
public virtual Stream BaseStream {
get {
return base_stream;
}
}
public virtual Encoding CurrentEncoding {
get {
if (encoding == null) {
throw new Exception();
}
return encoding;
}
}
public bool EndOfStream {
get { return Peek() < 0; }
}
public override void Close() {
Dispose(true);
}
protected override void Dispose(bool disposing) {
if (disposing && base_stream != null) {
base_stream.Close();
}
input_buffer = null;
decoded_buffer = null;
encoding = null;
decoder = null;
base_stream = null;
base.Dispose(disposing);
}
//
// Provides auto-detection of the encoding, as well as skipping over
// byte marks at the beginning of a stream.
//
int DoChecks(int count) {
if ((do_checks & 2) == 2) {
byte[] preamble = encoding.GetPreamble();
int c = preamble.Length;
if (count >= c) {
int i;
for (i = 0; i < c; i++) {
if (input_buffer[i] != preamble[i]) {
break;
}
}
if (i == c) {
return i;
}
}
}
if ((do_checks & 1) == 1) {
if (count < 2) {
return 0;
}
/*if (input_buffer[0] == 0xfe && input_buffer[1] == 0xff) {
this.encoding = Encoding.BigEndianUnicode;
return 2;
}*/
if (count < 3) {
return 0;
}
if (input_buffer[0] == 0xef && input_buffer[1] == 0xbb && input_buffer[2] == 0xbf) {
this.encoding = Encoding.UTF8Unmarked;
return 3;
}
if (count < 4) {
if (input_buffer[0] == 0xff && input_buffer[1] == 0xfe && input_buffer[2] != 0) {
this.encoding = Encoding.Unicode;
return 2;
}
return 0;
}
/*if (input_buffer[0] == 0 && input_buffer[1] == 0
&& input_buffer[2] == 0xfe && input_buffer[3] == 0xff) {
this.encoding = Encoding.BigEndianUTF32;
return 4;
}
if (input_buffer[0] == 0xff && input_buffer[1] == 0xfe) {
if (input_buffer[2] == 0 && input_buffer[3] == 0) {
this.encoding = Encoding.UTF32;
return 4;
}
this.encoding = Encoding.Unicode;
return 2;
}*/
}
return 0;
}
public void DiscardBufferedData() {
pos = decoded_count = 0;
mayBlock = false;
// Discard internal state of the decoder too.
decoder = encoding.GetDecoder();
}
// the buffer is empty, fill it again
private int ReadBuffer() {
pos = 0;
int cbEncoded = 0;
// keep looping until the decoder gives us some chars
decoded_count = 0;
int parse_start = 0;
do {
cbEncoded = base_stream.Read(input_buffer, 0, buffer_size);
if (cbEncoded <= 0) {
return 0;
}
mayBlock = (cbEncoded < buffer_size);
if (do_checks > 0) {
Encoding old = encoding;
parse_start = DoChecks(cbEncoded);
if (old != encoding) {
decoder = encoding.GetDecoder();
}
do_checks = 0;
cbEncoded -= parse_start;
}
decoded_count += decoder.GetChars(input_buffer, parse_start, cbEncoded, decoded_buffer, 0);
parse_start = 0;
} while (decoded_count == 0);
return decoded_count;
}
public override int Peek() {
if (base_stream == null) {
throw new ObjectDisposedException("StreamReader", "Cannot read from a closed StreamReader");
}
if (pos >= decoded_count && (mayBlock || ReadBuffer() == 0)) {
return -1;
}
return decoded_buffer[pos];
}
public override int Read() {
if (base_stream == null) {
throw new ObjectDisposedException("StreamReader", "Cannot read from a closed StreamReader");
}
if (pos >= decoded_count && ReadBuffer() == 0) {
return -1;
}
return decoded_buffer[pos++];
}
public override int Read([In, Out] char[] dest_buffer, int index, int count) {
if (base_stream == null) {
throw new ObjectDisposedException("StreamReader", "Cannot read from a closed StreamReader");
}
if (dest_buffer == null) {
throw new ArgumentNullException("dest_buffer");
}
if (index < 0) {
throw new ArgumentOutOfRangeException("index", "< 0");
}
if (count < 0) {
throw new ArgumentOutOfRangeException("count", "< 0");
}
// re-ordered to avoid possible integer overflow
if (index > dest_buffer.Length - count) {
throw new ArgumentException("index + count > dest_buffer.Length");
}
int chars_read = 0;
while (count > 0) {
if (pos >= decoded_count && ReadBuffer() == 0) {
return chars_read > 0 ? chars_read : 0;
}
int cch = Math.Min(decoded_count - pos, count);
Array.Copy(decoded_buffer, pos, dest_buffer, index, cch);
pos += cch;
index += cch;
count -= cch;
chars_read += cch;
if (mayBlock) {
break;
}
}
return chars_read;
}
bool foundCR;
int FindNextEOL() {
char c = '\0';
for (; pos < decoded_count; pos++) {
c = decoded_buffer[pos];
if (c == '\n') {
pos++;
int res = (foundCR) ? (pos - 2) : (pos - 1);
if (res < 0) {
res = 0; // if a new buffer starts with a \n and there was a \r at
}
// the end of the previous one, we get here.
foundCR = false;
return res;
} else if (foundCR) {
foundCR = false;
return pos - 1;
}
foundCR = (c == '\r');
}
return -1;
}
public override string ReadLine() {
if (base_stream == null) {
throw new ObjectDisposedException("StreamReader", "Cannot read from a closed StreamReader");
}
if (pos >= decoded_count && ReadBuffer() == 0) {
return null;
}
int begin = pos;
int end = FindNextEOL();
if (end < decoded_count && end >= begin) {
return new string(decoded_buffer, begin, end - begin);
}
if (line_builder == null) {
line_builder = new StringBuilder();
} else {
line_builder.Length = 0;
}
while (true) {
if (foundCR) { // don't include the trailing CR if present
decoded_count--;
}
line_builder.Append(decoded_buffer, begin, decoded_count - begin);
if (ReadBuffer() == 0) {
if (line_builder.Capacity > 32768) {
StringBuilder sb = line_builder;
line_builder = null;
return sb.ToString(0, sb.Length);
}
return line_builder.ToString(0, line_builder.Length);
}
begin = pos;
end = FindNextEOL();
if (end < decoded_count && end >= begin) {
line_builder.Append(decoded_buffer, begin, end - begin);
if (line_builder.Capacity > 32768) {
StringBuilder sb = line_builder;
line_builder = null;
return sb.ToString(0, sb.Length);
}
return line_builder.ToString(0, line_builder.Length);
}
}
}
public override string ReadToEnd() {
if (base_stream == null) {
throw new ObjectDisposedException("StreamReader", "Cannot read from a closed StreamReader");
}
StringBuilder text = new StringBuilder();
int size = decoded_buffer.Length;
char[] buffer = new char[size];
int len;
while ((len = Read(buffer, 0, size)) > 0) {
text.Append(buffer, 0, len);
}
return text.ToString();
}
}
}
#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;
using System.Globalization;
public class DateTimeParseExact1
{
private const int c_MIN_STRING_LEN = 1;
private const int c_MAX_STRING_LEN = 2048;
private const int c_NUM_LOOPS = 100;
private static CultureInfo CurrentCulture = TestLibrary.Utilities.CurrentCulture;
private static CultureInfo EnglishCulture = new CultureInfo("en-US");
private static string[] c_MONTHS = EnglishCulture.DateTimeFormat.MonthGenitiveNames;
private static string[] c_MONTHS_SH = EnglishCulture.DateTimeFormat.AbbreviatedMonthGenitiveNames;
private static string[] c_DAYS_SH = EnglishCulture.DateTimeFormat.AbbreviatedDayNames;
public static int Main()
{
DateTimeParseExact1 test = new DateTimeParseExact1();
TestLibrary.TestFramework.BeginTestCase("DateTimeParseExact1");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest15() && retVal;
TestLibrary.Utilities.CurrentCulture = EnglishCulture;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
retVal = PosTest14() && retVal;
TestLibrary.Utilities.CurrentCulture = CurrentCulture;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
MyFormater formater = new MyFormater();
string dateBefore = "";
DateTime dateAfter;
TestLibrary.TestFramework.BeginScenario("PosTest1: DateTime.ParseExact(G, DateTime.Now)");
try
{
dateBefore = DateTime.Now.ToString();
dateAfter = DateTime.ParseExact( dateBefore, "G", formater );
if (!dateBefore.Equals(dateAfter.ToString()))
{
TestLibrary.TestFramework.LogError("001", "DateTime.ParseExact(" + dateBefore + ") did not equal " + dateAfter.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 29
int year; // 1900 - 2000
int month; // 1 - 12
TestLibrary.TestFramework.BeginScenario("PosTest2: DateTime.ParseExact(d, M/d/yyyy (ShortDatePattern ex: 1/3/2002))");
// Skipping test because format 'd' on some platforms represents the year using two digits,
// this cause extrange results. Some dates are shifted 1 hour backward. See DDB 173277 - MAC bug
// Culture could be customized and dateseparator may be different than / or MM is used in the format
if (String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.ShortDatePattern, "M/d/yyyy", StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogInformation("Skipping test case, ShortDatePattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.ShortDatePattern);
return retVal;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 28) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1;
dateBefore = month + "/" + day + "/" + year;
dateAfter = DateTime.ParseExact( dateBefore, "d", formater);
if (month != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year)
{
TestLibrary.TestFramework.LogError("003", "DateTime.ParseExact(" + dateBefore + ") did not equal " + dateAfter.ToString() + ". Got M="+dateAfter.Month+", d="+dateAfter.Day+", y="+dateAfter.Year);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int dayOfWeek; // 0 - 6
int day; // 1 - 28
int year; // 1900 - 2000
int month; // 0 - 11
TestLibrary.TestFramework.BeginScenario("PosTest3: DateTime.ParseExact(D, dddd, MMMM dd, yyyy (LongDatePattern ex: Thursday, January 03, 2002))");
// Culture could be customized
if (String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongDatePattern, "dddd, MMMM dd, yyyy", StringComparison.Ordinal) != 0 &&
String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongDatePattern, "dddd, MMMM d, yyyy", StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogInformation("Skipping test case, LongDatePattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongDatePattern);
return retVal;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
// cheat and get day of the week
dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year);
dayOfWeek = (int)dateAfter.DayOfWeek;
// parse the date
dateBefore = (DayOfWeek)dayOfWeek + ", " + c_MONTHS[month] + " " +
(String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongDatePattern, "dddd, MMMM dd, yyyy", StringComparison.Ordinal) == 0 && 10 > day ? "0" : "") + day + ", " + year;
dateAfter = DateTime.ParseExact( dateBefore, "D", formater );
if ((month+1) != dateAfter.Month || day != dateAfter.Day || year != dateAfter.Year || (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek)
{
TestLibrary.TestFramework.LogError("005", "DateTime.ParseExact(" + dateBefore + ") did not equal (" + dateAfter.DayOfWeek + ", " + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ", " + dateAfter.Year + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int dayOfWeek; // 0 - 6
int day; // 1 - 28
int year; // 1900 - 2000
int month; // 0 - 11
int hour; // 0 - 11
int minute; // 0 - 59
int second; // 0 - 59
int timeOfDay; // 0 -1
string[] twelveHour = new string[2] {"AM", "PM"};
DateTime dateBeforeForValidity;
TestLibrary.TestFramework.BeginScenario("PosTest5: DateTime.ParseExact(F, dddd, MMMM dd, yyyy h:mm:ss tt (FullDateTimePattern ex: Thursday, January 03, 2002 12:00:00 AM))");
// Culture could be customized
if (!((String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongDatePattern, "dddd, MMMM dd, yyyy", StringComparison.Ordinal) == 0 ||
String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongDatePattern, "dddd, MMMM d, yyyy", StringComparison.Ordinal) == 0) &&
(String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern, "hh:mm:ss tt", StringComparison.Ordinal) == 0 ||
String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern, "h:mm:ss tt", StringComparison.Ordinal) == 0)))
{
TestLibrary.TestFramework.LogInformation("Skipping test case, " +
" LongDatePattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongDatePattern +
" LongTimePattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern);
return retVal;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
hour = (TestLibrary.Generator.GetInt32(-55) % 12);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2);
dateBeforeForValidity = new DateTime(year, month + 1, day, hour, minute, second);
// cheat and get day of the week
dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year);
dayOfWeek = (int)dateAfter.DayOfWeek;
// parse the date
dateBefore = (DayOfWeek)dayOfWeek + ", " +
c_MONTHS[month] + " " +
(String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongDatePattern, "dddd, MMMM dd, yyyy", StringComparison.Ordinal) == 0 && 10 > day ? "0" : "") + day + ", " +
year + " " +
(String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern, "hh:mm:ss tt", StringComparison.Ordinal) == 0 && 10 > hour ? "0" : "") + hour + ":" +
(10 > minute ? "0" : "") + minute + ":" +
(10 > second ? "0" : "") + second + " " + twelveHour[timeOfDay];
if (!TestLibrary.Utilities.IsWindows)
{
dateAfter = DateTime.Parse(dateBefore);
TimeSpan span = dateAfter - dateAfter.ToUniversalTime();
String strSpan = (span.Duration()==span ? "+" : "-") +
(10 > span.Duration().Hours ? "0" : "") + span.Duration().Hours +
":" + (10 > span.Minutes ? "0" : "") + span.Minutes;
dateBefore += " " + strSpan;
}
dateAfter = DateTime.ParseExact( dateBefore, "F", formater );
//Dev10 Bug 686124: For mac, the ambiguous and invalid points in time on the Mac
if (false == TimeZoneInfo.Local.IsInvalidTime(dateBeforeForValidity))
{
if ((month + 1) != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek
|| (hour + timeOfDay * 12) != dateAfter.Hour
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("009", "DateTime.ParseExact(" + dateBefore + ") did not equal (" + dateAfter.DayOfWeek + ", " + c_MONTHS[dateAfter.Month - 1] + " " + dateAfter.Day + ", " + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")");
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 28
int month; // 1 - 12
int year; // 1900 - 2000
int hour; // 0 - 11
int minute; // 0 - 59
int second; // 0 - 59
int timeOfDay; // 0 -1
string[] twelveHour = new string[2] {"AM", "PM"};
DateTime dateBeforeForValidity;
TestLibrary.TestFramework.BeginScenario("PosTest7: DateTime.ParseExact(G, ex: 1/3/2002 12:00:00 AM)");
// Culture could be customized
if (!(String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.ShortDatePattern, "M/d/yyyy", StringComparison.Ordinal) == 0 &&
(String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern, "hh:mm:ss tt", StringComparison.Ordinal) == 0 ||
String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern, "h:mm:ss tt", StringComparison.Ordinal) == 0)))
{
TestLibrary.TestFramework.LogInformation("Skipping test case, " +
" ShortDatePattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.ShortDatePattern +
" LongTimePattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern);
return retVal;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1930;
month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1;
hour = (TestLibrary.Generator.GetInt32(-55) % 12);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2);
dateBeforeForValidity = new DateTime(year, month, day, hour, minute, second);
// parse the date
dateBefore = month + "/" + + day + "/" + year + " " +
(String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern, "hh:mm:ss tt", StringComparison.Ordinal) == 0 && 10 > hour ? "0" : "") + hour + ":" +
(10 > minute ? "0" : "") + minute + ":" + (10 > second ? "0" : "") + second + " " + twelveHour[timeOfDay];
if (!TestLibrary.Utilities.IsWindows)
{
dateAfter = DateTime.Parse(dateBefore);
TimeSpan span = dateAfter - dateAfter.ToUniversalTime();
String strSpan = (span.Duration()==span ? "+" : "-") +
(10 > span.Duration().Hours ? "0" : "") + span.Duration().Hours +
":" + (10 > span.Minutes ? "0" : "") + span.Minutes;
dateBefore += " " + strSpan;
}
dateAfter = DateTime.ParseExact(dateBefore, "G", formater);
//Dev10 Bug 686124: For mac, the ambiguous and invalid points in time on the Mac
if (false == TimeZoneInfo.Local.IsInvalidTime(dateBeforeForValidity))
{
if (month != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| (hour + timeOfDay * 12) != dateAfter.Hour
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("013", "DateTime.ParseExact(" + dateBefore + ") did not equal (" + dateAfter.Month + "/" + dateAfter.Day + "/" + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")");
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("014", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 28
int month; // 0 - 11
TestLibrary.TestFramework.BeginScenario("PosTest8: DateTime.ParseExact(m, MMMM dd (MonthDayPattern ex: January 03))");
// Culture could be customized
if (String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.MonthDayPattern, "MMMM dd", StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogInformation("Skipping test case, MonthDayPattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.MonthDayPattern);
return retVal;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
// parse the date
dateBefore = c_MONTHS[month] + " " + (10>day?"0":"") + day;
dateAfter = DateTime.ParseExact( dateBefore, "m", formater );
if ((month+1) != dateAfter.Month
|| day != dateAfter.Day)
{
TestLibrary.TestFramework.LogError("015", "DateTime.ParseExact(" + dateBefore + ") did not equal (" + c_MONTHS[dateAfter.Month-1] + " " + dateAfter.Day + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("016", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int dayOfWeek; // 0 - 6
int day; // 1 - 28
int year; // 1900 - 2000
int month; // 0 - 11
int hour; // 12 - 23
int minute; // 0 - 59
int second; // 0 - 59
DateTime dateBeforeForValidity;
TestLibrary.TestFramework.BeginScenario("PosTest9: DateTime.ParseExact(R, ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (RFC1123Pattern ex: Thu, 03 Jan 2002 00:00:00 GMT))");
// if there is any change in RFC1123Pattern, this test case would fail. The formatting should be updated!!!
if (String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.RFC1123Pattern, "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogError("PosTest9", "Skipping test case, RFC1123Pattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.RFC1123Pattern);
return false;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
hour = (TestLibrary.Generator.GetInt32(-55) % 12) + 12; // Parse will convert perform GMT -> PST conversion
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
dayOfWeek = (TestLibrary.Generator.GetInt32(-55) % 7);
dateBeforeForValidity = new DateTime(year, month + 1, day, hour, minute, second);
// cheat and get day of the week
dateAfter = DateTime.Parse( (month+1) + "/" + day + "/" + year);
dayOfWeek = (int)dateAfter.DayOfWeek;
// parse the date
dateBefore = c_DAYS_SH[dayOfWeek] + ", " + (10>day?"0":"") + day + " " + c_MONTHS_SH[month] + " " + year + " " + (10>hour?"0":"") + hour + ":" + (10>minute?"0":"") + minute + ":" + (10>second?"0":"") + second + " GMT";
dateAfter = DateTime.ParseExact( dateBefore, "R", formater );
//Dev10 Bug 686124: For mac, the ambiguous and invalid points in time on the Mac
if (false == TimeZoneInfo.Local.IsInvalidTime(dateBeforeForValidity))
{
if ((month + 1) != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| (DayOfWeek)dayOfWeek != dateAfter.DayOfWeek
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("017", "DateTime.ParseExact(" + dateBefore + ") did not equal (" + c_DAYS_SH[(int)dateAfter.DayOfWeek] + ", " + dateAfter.Day + " " + c_MONTHS_SH[dateAfter.Month - 1] + " " + dateAfter.Year + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + " GMT)");
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("018", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 28
int month; // 1 - 12
int year; // 1900 - 2000
int hour; // 0 - 23
int minute; // 0 - 59
int second; // 0 - 59
DateTime dateBeforeForValidity;
TestLibrary.TestFramework.BeginScenario("PosTest10: DateTime.ParseExact(s, yyyy'-'MM'-'dd'T'HH':'mm':'ss (SortableDateTimePattern ex: 2002-01-03T00:00:00))");
// if there is any change in SortableDateTimePattern, this test case would fail, The formatting should be updated!!!
if (String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.SortableDateTimePattern, "yyyy'-'MM'-'dd'T'HH':'mm':'ss", StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogError("PosTest10", "Skipping test case, SortableDateTimePattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.SortableDateTimePattern);
return false;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1;
hour = (TestLibrary.Generator.GetInt32(-55) % 24);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
dateBeforeForValidity = new DateTime(year, month, day, hour, minute, second);
// parse the date
dateBefore = year + "-" + (10>month?"0":"") + month + "-" + (10>day?"0":"") + day + "T" + ((10 > hour) ? "0" : "") + hour + ":" + ((10 > minute) ? "0" : "") + minute + ":" + ((10 > second) ? "0" : "") + second;
dateAfter = DateTime.ParseExact( dateBefore, "s", formater );
//Dev10 Bug 686124: For mac, the ambiguous and invalid points in time on the Mac
if (false == TimeZoneInfo.Local.IsInvalidTime(dateBeforeForValidity))
{
if (month != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| hour != dateAfter.Hour
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("019", "DateTime.ParseExact(" + dateBefore + ") did not equal (" + dateAfter.Year + "-" + dateAfter.Month + "-" + dateAfter.Day + "T" + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")");
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("020", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest12()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int hour; // 0 - 11
int minute; // 0 - 59
int second; // 0 - 59
int timeOfDay; // 0 -1
string[] twelveHour = new string[2] {"AM", "PM"};
TestLibrary.TestFramework.BeginScenario("PosTest12: DateTime.ParseExact(T, h:mm:ss tt (LongTimePattern ex: 12:00:00 AM))");
// Culture could be customized
if (String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern, "hh:mm:ss tt", StringComparison.Ordinal) != 0 &&
String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern, "h:mm:ss tt", StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogInformation("Skipping test case, " + " LongTimePattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern);
return retVal;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
hour = (TestLibrary.Generator.GetInt32(-55) % 12);
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
timeOfDay = (TestLibrary.Generator.GetInt32(-55) % 2);
// parse the date
int newHour = hour==0?12:hour;
dateBefore = (String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.LongTimePattern, "hh:mm:ss tt", StringComparison.Ordinal) == 0 && 10 > newHour ? "0" : "") + newHour +
":" + (10 > minute ? "0" : "") + minute + ":" + (10 > second ? "0" : "") + second + " " + twelveHour[timeOfDay];
if (!TestLibrary.Utilities.IsWindows)
{
dateAfter = DateTime.Parse(dateBefore);
TimeSpan span = dateAfter - dateAfter.ToUniversalTime();
String strSpan = (span.Duration()==span ? "+" : "-") +
(10 > span.Duration().Hours ? "0" : "") + span.Duration().Hours +
":" + (10 > span.Minutes ? "0" : "") + span.Minutes;
dateBefore += " " + strSpan;
}
dateAfter = DateTime.ParseExact(dateBefore, "T", formater);
if ((hour + timeOfDay*12) != dateAfter.Hour
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("023", "DateTime.ParseExact(" + dateBefore + ") did not equal (" + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + ")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("024", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("024", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest13()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int day; // 1 - 28
int month; // 1 - 12
int year; // 1900 - 2000
int hour; // 12 - 23
int minute; // 0 - 59
int second; // 0 - 59
DateTime dateBeforeForValidity;
TestLibrary.TestFramework.BeginScenario("PosTest13: DateTime.ParseExact(u, yyyy'-'MM'-'dd HH':'mm':'ss'Z' (UniversalSortableDateTimePattern ex: 2002-01-03 00:00:00Z))");
// if there is any change in SortableDateTimePattern, this test case would fail, The formatting should be updated!!!
if (String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.UniversalSortableDateTimePattern, "yyyy'-'MM'-'dd HH':'mm':'ss'Z'", StringComparison.Ordinal) != 0)
{
TestLibrary.TestFramework.LogError("PosTest13", "Skipping test case, UniversalSortableDateTimePattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.UniversalSortableDateTimePattern);
return false;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
day = (TestLibrary.Generator.GetInt32(-55) % 27) + 1;
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12) + 1;
hour = (TestLibrary.Generator.GetInt32(-55) % 12) + 12; // conversion
minute = (TestLibrary.Generator.GetInt32(-55) % 60);
second = (TestLibrary.Generator.GetInt32(-55) % 60);
dateBeforeForValidity = new DateTime(year, month, day, hour, minute, second);
// parse the date
dateBefore = year + "-" + (10>month?"0":"") + month + "-" + (10>day?"0":"") + day + " " + ((10 > hour) ? "0" : "") + hour + ":" + ((10 > minute) ? "0" : "") + minute + ":" + ((10 > second) ? "0" : "") + second +"Z";
dateAfter = DateTime.ParseExact( dateBefore, "u", formater );
//Dev10 Bug 686124: For mac, the ambiguous and invalid points in time on the Mac
if (false == TimeZoneInfo.Local.IsInvalidTime(dateBeforeForValidity))
{
if (month != dateAfter.Month
|| day != dateAfter.Day
|| year != dateAfter.Year
|| minute != dateAfter.Minute
|| second != dateAfter.Second)
{
TestLibrary.TestFramework.LogError("025", "DateTime.ParseExact(" + dateBefore + ") did not equal (" + dateAfter.Year + "-" + dateAfter.Month + "-" + dateAfter.Day + " " + dateAfter.Hour + ":" + dateAfter.Minute + ":" + dateAfter.Second + "Z)");
retVal = false;
}
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("026", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("026", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest14()
{
bool retVal = true;
MyFormater formater = new MyFormater();
DateTime dateAfter;
string dateBefore = "";
int year; // 1900 - 2000
int month; // 0 - 11
TestLibrary.TestFramework.BeginScenario("PosTest14: DateTime.ParseExact(y, MMMM, yyyy (YearMonthPattern ex: January, 2002))");
// Culture could be customized
if (String.Compare(TestLibrary.Utilities.CurrentCulture.DateTimeFormat.YearMonthPattern, "MMMM, yyyy", StringComparison.Ordinal) != 0 )
{
TestLibrary.TestFramework.LogInformation("Skipping test case, YearMonthPattern: " + TestLibrary.Utilities.CurrentCulture.DateTimeFormat.YearMonthPattern);
return retVal;
}
try
{
for(int i=0; i<c_NUM_LOOPS; i++)
{
year = (TestLibrary.Generator.GetInt32(-55) % 100) + 1900;
month = (TestLibrary.Generator.GetInt32(-55) % 12);
dateBefore = c_MONTHS[month] + ", " + year;
dateAfter = DateTime.ParseExact(dateBefore, "y", formater);
if ((month+1) != dateAfter.Month
|| year != dateAfter.Year)
{
TestLibrary.TestFramework.LogError("027", "DateTime.ParseExact(" + dateBefore + ") did not equal (" + c_MONTHS[dateAfter.Month-1] + ", " + dateAfter.Year + ")-("+dateAfter.ToString()+")-DST("+dateAfter.IsDaylightSavingTime()+")");
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("028", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("028", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosTest15()
{
bool retVal = true;
MyFormater formater = new MyFormater();
string dateBefore = "";
DateTime dateAfter;
TestLibrary.TestFramework.BeginScenario("PosTest15: DateTime.ParseExact(G, DateTime.Now, null)");
try
{
dateBefore = DateTime.Now.ToString();
dateAfter = DateTime.ParseExact( dateBefore, "G", null );
if (!dateBefore.Equals(dateAfter.ToString()))
{
TestLibrary.TestFramework.LogError("101", "DateTime.ParseExact(" + dateBefore + ") did not equal " + dateAfter.ToString());
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("102", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest1()
{
bool retVal = true;
MyFormater formater = new MyFormater();
TestLibrary.TestFramework.BeginScenario("NegTest1: DateTime.ParseExact(null)");
try
{
DateTime.ParseExact(null, "d", formater);
TestLibrary.TestFramework.LogError("029", "DateTime.ParseExact(null) should have thrown");
retVal = false;
}
catch (ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("030", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
MyFormater formater = new MyFormater();
TestLibrary.TestFramework.BeginScenario("NegTest2: DateTime.ParseExact(String.Empty)");
try
{
DateTime.ParseExact(String.Empty, "d", formater);
TestLibrary.TestFramework.LogError("031", "DateTime.ParseExact(String.Empty) should have thrown");
retVal = false;
}
catch (FormatException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("032", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
MyFormater formater = new MyFormater();
string strDateTime = "";
DateTime dateAfter;
string[] formats = new string[17] {"d", "D", "f", "F", "g", "G", "m", "M", "r", "R", "s", "t", "T", "u", "U", "y", "Y"};
string format;
int formatIndex;
TestLibrary.TestFramework.BeginScenario("NegTest3: DateTime.ParseExact(<garbage>)");
try
{
for (int i=0; i<c_NUM_LOOPS; i++)
{
try
{
formatIndex = TestLibrary.Generator.GetInt32(-55) % 34;
if (0 <= formatIndex && formatIndex < 17)
{
format = formats[formatIndex];
}
else
{
format = TestLibrary.Generator.GetChar(-55) + "";
}
strDateTime = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN);
dateAfter = DateTime.ParseExact(strDateTime, format, formater);
TestLibrary.TestFramework.LogError("033", "DateTime.ParseExact(" + strDateTime + ", "+ format + ") should have thrown (" + dateAfter + ")");
retVal = false;
}
catch (FormatException)
{
// expected
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("034", "Failing date: " + strDateTime);
TestLibrary.TestFramework.LogError("034", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
MyFormater formater = new MyFormater();
string dateBefore = "";
DateTime dateAfter;
TestLibrary.TestFramework.BeginScenario("NegTest4: DateTime.ParseExact(\"\", DateTime.Now, formater)");
try
{
dateBefore = DateTime.Now.ToString();
dateAfter = DateTime.ParseExact( dateBefore, "", formater );
TestLibrary.TestFramework.LogError("103", "DateTime.ParseExact(" + dateBefore + ") should have thrown " + dateAfter.ToString());
retVal = false;
}
catch (System.FormatException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("104", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
MyFormater formater = new MyFormater();
string dateBefore = "";
DateTime dateAfter;
TestLibrary.TestFramework.BeginScenario("NegTest5: DateTime.ParseExact(null, DateTime.Now, formater)");
try
{
dateBefore = DateTime.Now.ToString();
dateAfter = DateTime.ParseExact( dateBefore, null, formater );
TestLibrary.TestFramework.LogError("105", "DateTime.ParseExact(" + dateBefore + ") should have thrown " + dateAfter.ToString());
retVal = false;
}
catch (System.ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("106", "Failing date: " + dateBefore);
TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
public class MyFormater : IFormatProvider
{
public object GetFormat(Type formatType)
{
if (typeof(IFormatProvider) == formatType)
{
return this;
}
else
{
return null;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using Blueprint41;
using Blueprint41.Core;
using Blueprint41.Query;
using Blueprint41.DatastoreTemplates;
using q = Domain.Data.Query;
namespace Domain.Data.Manipulation
{
public interface ICreditCardOriginalData : ISchemaBaseOriginalData
{
string CardType { get; }
string CardNumber { get; }
string ExpMonth { get; }
string ExpYear { get; }
IEnumerable<Person> Persons { get; }
}
public partial class CreditCard : OGM<CreditCard, CreditCard.CreditCardData, System.String>, ISchemaBase, INeo4jBase, ICreditCardOriginalData
{
#region Initialize
static CreditCard()
{
Register.Types();
}
protected override void RegisterGeneratedStoredQueries()
{
#region LoadByKeys
RegisterQuery(nameof(LoadByKeys), (query, alias) => query.
Where(alias.Uid.In(Parameter.New<System.String>(Param0))));
#endregion
AdditionalGeneratedStoredQueries();
}
partial void AdditionalGeneratedStoredQueries();
public static Dictionary<System.String, CreditCard> LoadByKeys(IEnumerable<System.String> uids)
{
return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item);
}
protected static void RegisterQuery(string name, Func<IMatchQuery, q.CreditCardAlias, IWhereQuery> query)
{
q.CreditCardAlias alias;
IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.CreditCard.Alias(out alias));
IWhereQuery partial = query.Invoke(matchQuery, alias);
ICompiled compiled = partial.Return(alias).Compile();
RegisterQuery(name, compiled);
}
public override string ToString()
{
return $"CreditCard => CardType : {this.CardType}, CardNumber : {this.CardNumber}, ExpMonth : {this.ExpMonth}, ExpYear : {this.ExpYear}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}";
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected override void LazySet()
{
base.LazySet();
if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged)
{
if ((object)InnerData == (object)OriginalData)
OriginalData = new CreditCardData(InnerData);
}
}
#endregion
#region Validations
protected override void ValidateSave()
{
bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged);
#pragma warning disable CS0472
if (InnerData.CardType == null)
throw new PersistenceException(string.Format("Cannot save CreditCard with key '{0}' because the CardType cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.CardNumber == null)
throw new PersistenceException(string.Format("Cannot save CreditCard with key '{0}' because the CardNumber cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ExpMonth == null)
throw new PersistenceException(string.Format("Cannot save CreditCard with key '{0}' because the ExpMonth cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ExpYear == null)
throw new PersistenceException(string.Format("Cannot save CreditCard with key '{0}' because the ExpYear cannot be null.", this.Uid?.ToString() ?? "<null>"));
if (InnerData.ModifiedDate == null)
throw new PersistenceException(string.Format("Cannot save CreditCard with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>"));
#pragma warning restore CS0472
}
protected override void ValidateDelete()
{
}
#endregion
#region Inner Data
public class CreditCardData : Data<System.String>
{
public CreditCardData()
{
}
public CreditCardData(CreditCardData data)
{
CardType = data.CardType;
CardNumber = data.CardNumber;
ExpMonth = data.ExpMonth;
ExpYear = data.ExpYear;
Persons = data.Persons;
ModifiedDate = data.ModifiedDate;
Uid = data.Uid;
}
#region Initialize Collections
protected override void InitializeCollections()
{
NodeType = "CreditCard";
Persons = new EntityCollection<Person>(Wrapper, Members.Persons, item => { if (Members.Persons.Events.HasRegisteredChangeHandlers) { object loadHack = item.CreditCard; } });
}
public string NodeType { get; private set; }
sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); }
sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); }
#endregion
#region Map Data
sealed public override IDictionary<string, object> MapTo()
{
IDictionary<string, object> dictionary = new Dictionary<string, object>();
dictionary.Add("CardType", CardType);
dictionary.Add("CardNumber", CardNumber);
dictionary.Add("ExpMonth", ExpMonth);
dictionary.Add("ExpYear", ExpYear);
dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate));
dictionary.Add("Uid", Uid);
return dictionary;
}
sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties)
{
object value;
if (properties.TryGetValue("CardType", out value))
CardType = (string)value;
if (properties.TryGetValue("CardNumber", out value))
CardNumber = (string)value;
if (properties.TryGetValue("ExpMonth", out value))
ExpMonth = (string)value;
if (properties.TryGetValue("ExpYear", out value))
ExpYear = (string)value;
if (properties.TryGetValue("ModifiedDate", out value))
ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value);
if (properties.TryGetValue("Uid", out value))
Uid = (string)value;
}
#endregion
#region Members for interface ICreditCard
public string CardType { get; set; }
public string CardNumber { get; set; }
public string ExpMonth { get; set; }
public string ExpYear { get; set; }
public EntityCollection<Person> Persons { get; private set; }
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get; set; }
#endregion
#region Members for interface INeo4jBase
public string Uid { get; set; }
#endregion
}
#endregion
#region Outer Data
#region Members for interface ICreditCard
public string CardType { get { LazyGet(); return InnerData.CardType; } set { if (LazySet(Members.CardType, InnerData.CardType, value)) InnerData.CardType = value; } }
public string CardNumber { get { LazyGet(); return InnerData.CardNumber; } set { if (LazySet(Members.CardNumber, InnerData.CardNumber, value)) InnerData.CardNumber = value; } }
public string ExpMonth { get { LazyGet(); return InnerData.ExpMonth; } set { if (LazySet(Members.ExpMonth, InnerData.ExpMonth, value)) InnerData.ExpMonth = value; } }
public string ExpYear { get { LazyGet(); return InnerData.ExpYear; } set { if (LazySet(Members.ExpYear, InnerData.ExpYear, value)) InnerData.ExpYear = value; } }
public EntityCollection<Person> Persons { get { return InnerData.Persons; } }
private void ClearPersons(DateTime? moment)
{
((ILookupHelper<Person>)InnerData.Persons).ClearLookup(moment);
}
#endregion
#region Members for interface ISchemaBase
public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } }
#endregion
#region Members for interface INeo4jBase
public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } }
#endregion
#region Virtual Node Type
public string NodeType { get { return InnerData.NodeType; } }
#endregion
#endregion
#region Reflection
private static CreditCardMembers members = null;
public static CreditCardMembers Members
{
get
{
if (members == null)
{
lock (typeof(CreditCard))
{
if (members == null)
members = new CreditCardMembers();
}
}
return members;
}
}
public class CreditCardMembers
{
internal CreditCardMembers() { }
#region Members for interface ICreditCard
public Property CardType { get; } = Datastore.AdventureWorks.Model.Entities["CreditCard"].Properties["CardType"];
public Property CardNumber { get; } = Datastore.AdventureWorks.Model.Entities["CreditCard"].Properties["CardNumber"];
public Property ExpMonth { get; } = Datastore.AdventureWorks.Model.Entities["CreditCard"].Properties["ExpMonth"];
public Property ExpYear { get; } = Datastore.AdventureWorks.Model.Entities["CreditCard"].Properties["ExpYear"];
public Property Persons { get; } = Datastore.AdventureWorks.Model.Entities["CreditCard"].Properties["Persons"];
#endregion
#region Members for interface ISchemaBase
public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"];
#endregion
#region Members for interface INeo4jBase
public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"];
#endregion
}
private static CreditCardFullTextMembers fullTextMembers = null;
public static CreditCardFullTextMembers FullTextMembers
{
get
{
if (fullTextMembers == null)
{
lock (typeof(CreditCard))
{
if (fullTextMembers == null)
fullTextMembers = new CreditCardFullTextMembers();
}
}
return fullTextMembers;
}
}
public class CreditCardFullTextMembers
{
internal CreditCardFullTextMembers() { }
}
sealed public override Entity GetEntity()
{
if (entity == null)
{
lock (typeof(CreditCard))
{
if (entity == null)
entity = Datastore.AdventureWorks.Model.Entities["CreditCard"];
}
}
return entity;
}
private static CreditCardEvents events = null;
public static CreditCardEvents Events
{
get
{
if (events == null)
{
lock (typeof(CreditCard))
{
if (events == null)
events = new CreditCardEvents();
}
}
return events;
}
}
public class CreditCardEvents
{
#region OnNew
private bool onNewIsRegistered = false;
private EventHandler<CreditCard, EntityEventArgs> onNew;
public event EventHandler<CreditCard, EntityEventArgs> OnNew
{
add
{
lock (this)
{
if (!onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
Entity.Events.OnNew += onNewProxy;
onNewIsRegistered = true;
}
onNew += value;
}
}
remove
{
lock (this)
{
onNew -= value;
if (onNew == null && onNewIsRegistered)
{
Entity.Events.OnNew -= onNewProxy;
onNewIsRegistered = false;
}
}
}
}
private void onNewProxy(object sender, EntityEventArgs args)
{
EventHandler<CreditCard, EntityEventArgs> handler = onNew;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
#region OnDelete
private bool onDeleteIsRegistered = false;
private EventHandler<CreditCard, EntityEventArgs> onDelete;
public event EventHandler<CreditCard, EntityEventArgs> OnDelete
{
add
{
lock (this)
{
if (!onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
Entity.Events.OnDelete += onDeleteProxy;
onDeleteIsRegistered = true;
}
onDelete += value;
}
}
remove
{
lock (this)
{
onDelete -= value;
if (onDelete == null && onDeleteIsRegistered)
{
Entity.Events.OnDelete -= onDeleteProxy;
onDeleteIsRegistered = false;
}
}
}
}
private void onDeleteProxy(object sender, EntityEventArgs args)
{
EventHandler<CreditCard, EntityEventArgs> handler = onDelete;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
#region OnSave
private bool onSaveIsRegistered = false;
private EventHandler<CreditCard, EntityEventArgs> onSave;
public event EventHandler<CreditCard, EntityEventArgs> OnSave
{
add
{
lock (this)
{
if (!onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
Entity.Events.OnSave += onSaveProxy;
onSaveIsRegistered = true;
}
onSave += value;
}
}
remove
{
lock (this)
{
onSave -= value;
if (onSave == null && onSaveIsRegistered)
{
Entity.Events.OnSave -= onSaveProxy;
onSaveIsRegistered = false;
}
}
}
}
private void onSaveProxy(object sender, EntityEventArgs args)
{
EventHandler<CreditCard, EntityEventArgs> handler = onSave;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
#region OnPropertyChange
public static class OnPropertyChange
{
#region OnCardType
private static bool onCardTypeIsRegistered = false;
private static EventHandler<CreditCard, PropertyEventArgs> onCardType;
public static event EventHandler<CreditCard, PropertyEventArgs> OnCardType
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onCardTypeIsRegistered)
{
Members.CardType.Events.OnChange -= onCardTypeProxy;
Members.CardType.Events.OnChange += onCardTypeProxy;
onCardTypeIsRegistered = true;
}
onCardType += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onCardType -= value;
if (onCardType == null && onCardTypeIsRegistered)
{
Members.CardType.Events.OnChange -= onCardTypeProxy;
onCardTypeIsRegistered = false;
}
}
}
}
private static void onCardTypeProxy(object sender, PropertyEventArgs args)
{
EventHandler<CreditCard, PropertyEventArgs> handler = onCardType;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
#region OnCardNumber
private static bool onCardNumberIsRegistered = false;
private static EventHandler<CreditCard, PropertyEventArgs> onCardNumber;
public static event EventHandler<CreditCard, PropertyEventArgs> OnCardNumber
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onCardNumberIsRegistered)
{
Members.CardNumber.Events.OnChange -= onCardNumberProxy;
Members.CardNumber.Events.OnChange += onCardNumberProxy;
onCardNumberIsRegistered = true;
}
onCardNumber += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onCardNumber -= value;
if (onCardNumber == null && onCardNumberIsRegistered)
{
Members.CardNumber.Events.OnChange -= onCardNumberProxy;
onCardNumberIsRegistered = false;
}
}
}
}
private static void onCardNumberProxy(object sender, PropertyEventArgs args)
{
EventHandler<CreditCard, PropertyEventArgs> handler = onCardNumber;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
#region OnExpMonth
private static bool onExpMonthIsRegistered = false;
private static EventHandler<CreditCard, PropertyEventArgs> onExpMonth;
public static event EventHandler<CreditCard, PropertyEventArgs> OnExpMonth
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onExpMonthIsRegistered)
{
Members.ExpMonth.Events.OnChange -= onExpMonthProxy;
Members.ExpMonth.Events.OnChange += onExpMonthProxy;
onExpMonthIsRegistered = true;
}
onExpMonth += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onExpMonth -= value;
if (onExpMonth == null && onExpMonthIsRegistered)
{
Members.ExpMonth.Events.OnChange -= onExpMonthProxy;
onExpMonthIsRegistered = false;
}
}
}
}
private static void onExpMonthProxy(object sender, PropertyEventArgs args)
{
EventHandler<CreditCard, PropertyEventArgs> handler = onExpMonth;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
#region OnExpYear
private static bool onExpYearIsRegistered = false;
private static EventHandler<CreditCard, PropertyEventArgs> onExpYear;
public static event EventHandler<CreditCard, PropertyEventArgs> OnExpYear
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onExpYearIsRegistered)
{
Members.ExpYear.Events.OnChange -= onExpYearProxy;
Members.ExpYear.Events.OnChange += onExpYearProxy;
onExpYearIsRegistered = true;
}
onExpYear += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onExpYear -= value;
if (onExpYear == null && onExpYearIsRegistered)
{
Members.ExpYear.Events.OnChange -= onExpYearProxy;
onExpYearIsRegistered = false;
}
}
}
}
private static void onExpYearProxy(object sender, PropertyEventArgs args)
{
EventHandler<CreditCard, PropertyEventArgs> handler = onExpYear;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
#region OnPersons
private static bool onPersonsIsRegistered = false;
private static EventHandler<CreditCard, PropertyEventArgs> onPersons;
public static event EventHandler<CreditCard, PropertyEventArgs> OnPersons
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onPersonsIsRegistered)
{
Members.Persons.Events.OnChange -= onPersonsProxy;
Members.Persons.Events.OnChange += onPersonsProxy;
onPersonsIsRegistered = true;
}
onPersons += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onPersons -= value;
if (onPersons == null && onPersonsIsRegistered)
{
Members.Persons.Events.OnChange -= onPersonsProxy;
onPersonsIsRegistered = false;
}
}
}
}
private static void onPersonsProxy(object sender, PropertyEventArgs args)
{
EventHandler<CreditCard, PropertyEventArgs> handler = onPersons;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
#region OnModifiedDate
private static bool onModifiedDateIsRegistered = false;
private static EventHandler<CreditCard, PropertyEventArgs> onModifiedDate;
public static event EventHandler<CreditCard, PropertyEventArgs> OnModifiedDate
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
Members.ModifiedDate.Events.OnChange += onModifiedDateProxy;
onModifiedDateIsRegistered = true;
}
onModifiedDate += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onModifiedDate -= value;
if (onModifiedDate == null && onModifiedDateIsRegistered)
{
Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy;
onModifiedDateIsRegistered = false;
}
}
}
}
private static void onModifiedDateProxy(object sender, PropertyEventArgs args)
{
EventHandler<CreditCard, PropertyEventArgs> handler = onModifiedDate;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
#region OnUid
private static bool onUidIsRegistered = false;
private static EventHandler<CreditCard, PropertyEventArgs> onUid;
public static event EventHandler<CreditCard, PropertyEventArgs> OnUid
{
add
{
lock (typeof(OnPropertyChange))
{
if (!onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
Members.Uid.Events.OnChange += onUidProxy;
onUidIsRegistered = true;
}
onUid += value;
}
}
remove
{
lock (typeof(OnPropertyChange))
{
onUid -= value;
if (onUid == null && onUidIsRegistered)
{
Members.Uid.Events.OnChange -= onUidProxy;
onUidIsRegistered = false;
}
}
}
}
private static void onUidProxy(object sender, PropertyEventArgs args)
{
EventHandler<CreditCard, PropertyEventArgs> handler = onUid;
if ((object)handler != null)
handler.Invoke((CreditCard)sender, args);
}
#endregion
}
#endregion
}
#endregion
#region ICreditCardOriginalData
public ICreditCardOriginalData OriginalVersion { get { return this; } }
#region Members for interface ICreditCard
string ICreditCardOriginalData.CardType { get { return OriginalData.CardType; } }
string ICreditCardOriginalData.CardNumber { get { return OriginalData.CardNumber; } }
string ICreditCardOriginalData.ExpMonth { get { return OriginalData.ExpMonth; } }
string ICreditCardOriginalData.ExpYear { get { return OriginalData.ExpYear; } }
IEnumerable<Person> ICreditCardOriginalData.Persons { get { return OriginalData.Persons.OriginalData; } }
#endregion
#region Members for interface ISchemaBase
ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } }
System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } }
#endregion
#region Members for interface INeo4jBase
INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } }
string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } }
#endregion
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
/// <summary>
/// Equals(System.Object)
/// </summary>
public class GuidEquals2
{
#region Private Fields
private const int c_GUID_BYTE_ARRAY_SIZE = 16;
#endregion
#region Public Methods
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
return retVal;
}
#region Positive Test Cases
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Call Equals with self instance");
try
{
Guid guid = Guid.Empty;
if (!guid.Equals((object)guid))
{
TestLibrary.TestFramework.LogError("001.1", "Calling Equals with self instance returns false");
retVal = false;
}
// double check
if (!guid.Equals((object)guid))
{
TestLibrary.TestFramework.LogError("001.2", "Calling Equals with self instance returns false");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid = new Guid(bytes);
if (!guid.Equals((object)guid))
{
TestLibrary.TestFramework.LogError("001.3", "Calling Equals with self instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
// double check
if (!guid.Equals((object)guid))
{
TestLibrary.TestFramework.LogError("001.4", "Calling Equals with self instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Call Equals with equal instance");
try
{
Guid guid1 = Guid.Empty;
Guid guid2 = new Guid("00000000-0000-0000-0000-000000000000");
if (!guid1.Equals((object)guid2))
{
TestLibrary.TestFramework.LogError("002.1", "Calling Equals with equal instance returns false");
retVal = false;
}
// double check
if (!guid1.Equals((object)guid2))
{
TestLibrary.TestFramework.LogError("002.2", "Calling Equals with equal instance returns false");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid1 = new Guid(bytes);
guid2 = new Guid(bytes);
if (!guid1.Equals((object)guid2))
{
TestLibrary.TestFramework.LogError("002.3", "Calling Equals with equal instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2);
retVal = false;
}
// double check
if (!guid1.Equals((object)guid2))
{
TestLibrary.TestFramework.LogError("002.4", "Calling Equals with equal instance returns false");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Call Equals with not equal instance");
try
{
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000000001"), false, "003.1") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000000100"), false, "003.2") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000000010000"), false, "003.3") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000001000000"), false, "003.4") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-000100000000"), false, "003.5") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0000-010000000000"), false, "003.6") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0001-000000000000"), false, "003.7") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0000-0100-000000000000"), false, "003.8") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0001-0000-000000000000"), false, "003.9") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0000-0100-0000-000000000000"), false, "003.10") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0001-0000-0000-000000000000"), false, "003.11") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000000-0100-0000-0000-000000000000"), false, "003.12") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000001-0000-0000-0000-000000000000"), false, "003.13") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00000100-0000-0000-0000-000000000000"), false, "003.14") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("00010000-0000-0000-0000-000000000000"), false, "003.15") && retVal;
retVal = VerificationHelper(Guid.Empty, new Guid("01000000-0000-0000-0000-000000000000"), false, "003.16") && retVal;
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Call Equals with null reference");
try
{
Guid guid = Guid.Empty;
if (guid.Equals(null))
{
TestLibrary.TestFramework.LogError("004.1", "Calling Equals with null reference returns true");
retVal = false;
}
// double check
if (guid.Equals(null))
{
TestLibrary.TestFramework.LogError("004.2", "Calling Equals with null reference returns true");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid = new Guid(bytes);
if (guid.Equals(null))
{
TestLibrary.TestFramework.LogError("004.3", "Calling Equals with null reference returns true");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
// double check
if (guid.Equals(null))
{
TestLibrary.TestFramework.LogError("004.4", "Calling Equals with null reference returns true");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest5: Call Equals with not a Guid instance");
try
{
Guid guid = Guid.Empty;
Object obj = new Object();
if (guid.Equals(obj))
{
TestLibrary.TestFramework.LogError("005.1", "Calling Equals with not a Guid instance returns true");
retVal = false;
}
// double check
if (guid.Equals(obj))
{
TestLibrary.TestFramework.LogError("005.2", "Calling Equals with not a Guid instance returns true");
retVal = false;
}
byte[] bytes = new byte[c_GUID_BYTE_ARRAY_SIZE];
TestLibrary.Generator.GetBytes(-55, bytes);
guid = new Guid(bytes);
if (guid.Equals(obj))
{
TestLibrary.TestFramework.LogError("005.3", "Calling Equals with not a Guid instance returns true");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
// double check
if (guid.Equals(obj))
{
TestLibrary.TestFramework.LogError("005.4", "Calling Equals with not a Guid instance returns true");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid = " + guid);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005.0", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
#endregion
#endregion
public static int Main()
{
GuidEquals2 test = new GuidEquals2();
TestLibrary.TestFramework.BeginTestCase("GuidEquals2");
if (test.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
#region Private Methods
private bool VerificationHelper(Guid guid1, object guid2, bool expected, string errorNo)
{
bool retVal = true;
bool actual = guid1.Equals(guid2);
if (actual != expected)
{
TestLibrary.TestFramework.LogError(errorNo, "Calling Equals returns wrong result");
TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] guid1 = " + guid1 + ", guid2 = " + guid2 + ", actual = " + actual + ", expected = " + expected);
retVal = false;
}
return retVal;
}
#endregion
}
| |
using System;
using Polly.CircuitBreaker;
using Polly.Utilities;
namespace Polly
{
/// <summary>
/// Fluent API for defining a Circuit Breaker <see cref="AsyncPolicy{TResult}"/>.
/// </summary>
public static class AsyncAdvancedCircuitBreakerTResultSyntax
{
/// <summary>
/// <para> Builds a <see cref="AsyncPolicy{TResult}"/> that will function like a Circuit Breaker.</para>
/// <para>The circuit will break if, within any timeslice of duration <paramref name="samplingDuration"/>, the proportion of actions resulting in a handled exception or result exceeds <paramref name="failureThreshold"/>, provided also that the number of actions through the circuit in the timeslice is at least <paramref name="minimumThroughput" />. </para>
/// <para>The circuit will stay broken for the <paramref name="durationOfBreak" />. Any attempt to execute this policy
/// while the circuit is broken, will immediately throw a <see cref="BrokenCircuitException" /> containing the exception or result
/// that broke the circuit.
/// </para>
/// <para>If the first action after the break duration period results in a handled exception or result, the circuit will break
/// again for another <paramref name="durationOfBreak" />; if no exception or handled result is encountered, the circuit will reset.
/// </para>
/// </summary>
/// <param name="policyBuilder">The policy builder.</param>
/// <param name="failureThreshold">The failure threshold at which the circuit will break (a number between 0 and 1; eg 0.5 represents breaking if 50% or more of actions result in a handled failure.</param>
/// <param name="samplingDuration">The duration of the timeslice over which failure ratios are assessed.</param>
/// <param name="minimumThroughput">The minimum throughput: this many actions or more must pass through the circuit in the timeslice, for statistics to be considered significant and the circuit-breaker to come into action.</param>
/// <param name="durationOfBreak">The duration the circuit will stay open before resetting.</param>
/// <returns>The policy instance.</returns>
/// <remarks>(see "Release It!" by Michael T. Nygard fi)</remarks>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be greater than zero</exception>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be less than or equal to one</exception>
/// <exception cref="ArgumentOutOfRangeException">samplingDuration;Value must be equal to or greater than the minimum resolution of the CircuitBreaker timer</exception>
/// <exception cref="ArgumentOutOfRangeException">minimumThroughput;Value must be greater than one</exception>
/// <exception cref="ArgumentOutOfRangeException">durationOfBreak;Value must be greater than zero</exception>
public static AsyncCircuitBreakerPolicy<TResult> AdvancedCircuitBreakerAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak)
{
Action<DelegateResult<TResult>, TimeSpan> doNothingOnBreak = (_, __) => { };
Action doNothingOnReset = () => { };
return policyBuilder.AdvancedCircuitBreakerAsync(
failureThreshold, samplingDuration, minimumThroughput,
durationOfBreak,
doNothingOnBreak,
doNothingOnReset
);
}
/// <summary>
/// <para> Builds a <see cref="AsyncPolicy{TResult}"/> that will function like a Circuit Breaker.</para>
/// <para>The circuit will break if, within any timeslice of duration <paramref name="samplingDuration"/>, the proportion of actions resulting in a handled exception exceeds <paramref name="failureThreshold"/>, provided also that the number of actions through the circuit in the timeslice is at least <paramref name="minimumThroughput" />. </para>
/// <para>The circuit will stay broken for the <paramref name="durationOfBreak" />. Any attempt to execute this policy
/// while the circuit is broken, will immediately throw a <see cref="BrokenCircuitException" /> containing the exception or result
/// that broke the circuit.
/// </para>
/// <para>If the first action after the break duration period results in a handled exception or result, the circuit will break
/// again for another <paramref name="durationOfBreak" />; if no exception or handled result is encountered, the circuit will reset.
/// </para>
/// </summary>
/// <param name="policyBuilder">The policy builder.</param>
/// <param name="failureThreshold">The failure threshold at which the circuit will break (a number between 0 and 1; eg 0.5 represents breaking if 50% or more of actions result in a handled failure.</param>
/// <param name="samplingDuration">The duration of the timeslice over which failure ratios are assessed.</param>
/// <param name="minimumThroughput">The minimum throughput: this many actions or more must pass through the circuit in the timeslice, for statistics to be considered significant and the circuit-breaker to come into action.</param>
/// <param name="durationOfBreak">The duration the circuit will stay open before resetting.</param>
/// <param name="onBreak">The action to call when the circuit transitions to an <see cref="CircuitState.Open"/> state.</param>
/// <param name="onReset">The action to call when the circuit resets to a <see cref="CircuitState.Closed"/> state.</param>
/// <returns>The policy instance.</returns>
/// <remarks>(see "Release It!" by Michael T. Nygard fi)</remarks>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be greater than zero</exception>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be less than or equal to one</exception>
/// <exception cref="ArgumentOutOfRangeException">samplingDuration;Value must be equal to or greater than the minimum resolution of the CircuitBreaker timer</exception>
/// <exception cref="ArgumentOutOfRangeException">minimumThroughput;Value must be greater than one</exception>
/// <exception cref="ArgumentOutOfRangeException">durationOfBreak;Value must be greater than zero</exception>
/// <exception cref="ArgumentNullException">onBreak</exception>
/// <exception cref="ArgumentNullException">onReset</exception>
public static AsyncCircuitBreakerPolicy<TResult> AdvancedCircuitBreakerAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak, Action<DelegateResult<TResult>, TimeSpan> onBreak, Action onReset)
=> policyBuilder.AdvancedCircuitBreakerAsync(
failureThreshold, samplingDuration, minimumThroughput,
durationOfBreak,
(outcome, timespan, context) => onBreak(outcome, timespan),
context => onReset()
);
/// <summary>
/// <para> Builds a <see cref="AsyncPolicy{TResult}"/> that will function like a Circuit Breaker.</para>
/// <para>The circuit will break if, within any timeslice of duration <paramref name="samplingDuration"/>, the proportion of actions resulting in a handled exception exceeds <paramref name="failureThreshold"/>, provided also that the number of actions through the circuit in the timeslice is at least <paramref name="minimumThroughput" />. </para>
/// <para>The circuit will stay broken for the <paramref name="durationOfBreak" />. Any attempt to execute this policy
/// while the circuit is broken, will immediately throw a <see cref="BrokenCircuitException" /> containing the exception or result
/// that broke the circuit.
/// </para>
/// <para>If the first action after the break duration period results in a handled exception or result, the circuit will break
/// again for another <paramref name="durationOfBreak" />; if no exception or handled result is encountered, the circuit will reset.
/// </para>
/// </summary>
/// <param name="policyBuilder">The policy builder.</param>
/// <param name="failureThreshold">The failure threshold at which the circuit will break (a number between 0 and 1; eg 0.5 represents breaking if 50% or more of actions result in a handled failure.</param>
/// <param name="samplingDuration">The duration of the timeslice over which failure ratios are assessed.</param>
/// <param name="minimumThroughput">The minimum throughput: this many actions or more must pass through the circuit in the timeslice, for statistics to be considered significant and the circuit-breaker to come into action.</param>
/// <param name="durationOfBreak">The duration the circuit will stay open before resetting.</param>
/// <param name="onBreak">The action to call when the circuit transitions to an <see cref="CircuitState.Open"/> state.</param>
/// <param name="onReset">The action to call when the circuit resets to a <see cref="CircuitState.Closed"/> state.</param>
/// <returns>The policy instance.</returns>
/// <remarks>(see "Release It!" by Michael T. Nygard fi)</remarks>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be greater than zero</exception>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be less than or equal to one</exception>
/// <exception cref="ArgumentOutOfRangeException">samplingDuration;Value must be equal to or greater than the minimum resolution of the CircuitBreaker timer</exception>
/// <exception cref="ArgumentOutOfRangeException">minimumThroughput;Value must be greater than one</exception>
/// <exception cref="ArgumentOutOfRangeException">durationOfBreak;Value must be greater than zero</exception>
/// <exception cref="ArgumentNullException">onBreak</exception>
/// <exception cref="ArgumentNullException">onReset</exception>
public static AsyncCircuitBreakerPolicy<TResult> AdvancedCircuitBreakerAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak, Action<DelegateResult<TResult>, TimeSpan, Context> onBreak, Action<Context> onReset)
{
Action doNothingOnHalfOpen = () => { };
return policyBuilder.AdvancedCircuitBreakerAsync(
failureThreshold, samplingDuration, minimumThroughput,
durationOfBreak,
onBreak,
onReset,
doNothingOnHalfOpen
);
}
/// <summary>
/// <para> Builds a <see cref="AsyncPolicy{TResult}"/> that will function like a Circuit Breaker.</para>
/// <para>The circuit will break if, within any timeslice of duration <paramref name="samplingDuration"/>, the proportion of actions resulting in a handled exception exceeds <paramref name="failureThreshold"/>, provided also that the number of actions through the circuit in the timeslice is at least <paramref name="minimumThroughput" />. </para>
/// <para>The circuit will stay broken for the <paramref name="durationOfBreak" />. Any attempt to execute this policy
/// while the circuit is broken, will immediately throw a <see cref="BrokenCircuitException" /> containing the exception or result
/// that broke the circuit.
/// </para>
/// <para>If the first action after the break duration period results in a handled exception or result, the circuit will break
/// again for another <paramref name="durationOfBreak" />; if no exception or handled result is encountered, the circuit will reset.
/// </para>
/// </summary>
/// <param name="policyBuilder">The policy builder.</param>
/// <param name="failureThreshold">The failure threshold at which the circuit will break (a number between 0 and 1; eg 0.5 represents breaking if 50% or more of actions result in a handled failure.</param>
/// <param name="samplingDuration">The duration of the timeslice over which failure ratios are assessed.</param>
/// <param name="minimumThroughput">The minimum throughput: this many actions or more must pass through the circuit in the timeslice, for statistics to be considered significant and the circuit-breaker to come into action.</param>
/// <param name="durationOfBreak">The duration the circuit will stay open before resetting.</param>
/// <param name="onBreak">The action to call when the circuit transitions to an <see cref="CircuitState.Open"/> state.</param>
/// <param name="onReset">The action to call when the circuit resets to a <see cref="CircuitState.Closed"/> state.</param>
/// <param name="onHalfOpen">The action to call when the circuit transitions to <see cref="CircuitState.HalfOpen"/> state, ready to try action executions again. </param>
/// <returns>The policy instance.</returns>
/// <remarks>(see "Release It!" by Michael T. Nygard fi)</remarks>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be greater than zero</exception>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be less than or equal to one</exception>
/// <exception cref="ArgumentOutOfRangeException">samplingDuration;Value must be equal to or greater than the minimum resolution of the CircuitBreaker timer</exception>
/// <exception cref="ArgumentOutOfRangeException">minimumThroughput;Value must be greater than one</exception>
/// <exception cref="ArgumentOutOfRangeException">durationOfBreak;Value must be greater than zero</exception>
/// <exception cref="ArgumentNullException">onBreak</exception>
/// <exception cref="ArgumentNullException">onReset</exception>
public static AsyncCircuitBreakerPolicy<TResult> AdvancedCircuitBreakerAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak, Action<DelegateResult<TResult>, TimeSpan> onBreak, Action onReset, Action onHalfOpen)
=> policyBuilder.AdvancedCircuitBreakerAsync(
failureThreshold, samplingDuration, minimumThroughput,
durationOfBreak,
(outcome, timespan, context) => onBreak(outcome, timespan),
context => onReset(),
onHalfOpen
);
/// <summary>
/// <para> Builds a <see cref="AsyncPolicy{TResult}"/> that will function like a Circuit Breaker.</para>
/// <para>The circuit will break if, within any timeslice of duration <paramref name="samplingDuration"/>, the proportion of actions resulting in a handled exception exceeds <paramref name="failureThreshold"/>, provided also that the number of actions through the circuit in the timeslice is at least <paramref name="minimumThroughput" />. </para>
/// <para>The circuit will stay broken for the <paramref name="durationOfBreak" />. Any attempt to execute this policy
/// while the circuit is broken, will immediately throw a <see cref="BrokenCircuitException" /> containing the exception or result
/// that broke the circuit.
/// </para>
/// <para>If the first action after the break duration period results in a handled exception or result, the circuit will break
/// again for another <paramref name="durationOfBreak" />; if no exception or handled result is encountered, the circuit will reset.
/// </para>
/// </summary>
/// <param name="policyBuilder">The policy builder.</param>
/// <param name="failureThreshold">The failure threshold at which the circuit will break (a number between 0 and 1; eg 0.5 represents breaking if 50% or more of actions result in a handled failure.</param>
/// <param name="samplingDuration">The duration of the timeslice over which failure ratios are assessed.</param>
/// <param name="minimumThroughput">The minimum throughput: this many actions or more must pass through the circuit in the timeslice, for statistics to be considered significant and the circuit-breaker to come into action.</param>
/// <param name="durationOfBreak">The duration the circuit will stay open before resetting.</param>
/// <param name="onBreak">The action to call when the circuit transitions to an <see cref="CircuitState.Open"/> state.</param>
/// <param name="onReset">The action to call when the circuit resets to a <see cref="CircuitState.Closed"/> state.</param>
/// <param name="onHalfOpen">The action to call when the circuit transitions to <see cref="CircuitState.HalfOpen"/> state, ready to try action executions again. </param>
/// <returns>The policy instance.</returns>
/// <remarks>(see "Release It!" by Michael T. Nygard fi)</remarks>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be greater than zero</exception>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be less than or equal to one</exception>
/// <exception cref="ArgumentOutOfRangeException">samplingDuration;Value must be equal to or greater than the minimum resolution of the CircuitBreaker timer</exception>
/// <exception cref="ArgumentOutOfRangeException">minimumThroughput;Value must be greater than one</exception>
/// <exception cref="ArgumentOutOfRangeException">durationOfBreak;Value must be greater than zero</exception>
/// <exception cref="ArgumentNullException">onBreak</exception>
/// <exception cref="ArgumentNullException">onReset</exception>
/// <exception cref="ArgumentNullException">onHalfOpen</exception>
public static AsyncCircuitBreakerPolicy<TResult> AdvancedCircuitBreakerAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak, Action<DelegateResult<TResult>, TimeSpan, Context> onBreak, Action<Context> onReset, Action onHalfOpen)
=> policyBuilder.AdvancedCircuitBreakerAsync(
failureThreshold, samplingDuration, minimumThroughput,
durationOfBreak,
(outcome, state, timespan, context) => onBreak(outcome, timespan, context),
onReset,
onHalfOpen
);
/// <summary>
/// <para> Builds a <see cref="AsyncPolicy{TResult}"/> that will function like a Circuit Breaker.</para>
/// <para>The circuit will break if, within any timeslice of duration <paramref name="samplingDuration"/>, the proportion of actions resulting in a handled exception exceeds <paramref name="failureThreshold"/>, provided also that the number of actions through the circuit in the timeslice is at least <paramref name="minimumThroughput" />. </para>
/// <para>The circuit will stay broken for the <paramref name="durationOfBreak" />. Any attempt to execute this policy
/// while the circuit is broken, will immediately throw a <see cref="BrokenCircuitException" /> containing the exception or result
/// that broke the circuit.
/// </para>
/// <para>If the first action after the break duration period results in a handled exception or result, the circuit will break
/// again for another <paramref name="durationOfBreak" />; if no exception or handled result is encountered, the circuit will reset.
/// </para>
/// </summary>
/// <param name="policyBuilder">The policy builder.</param>
/// <param name="failureThreshold">The failure threshold at which the circuit will break (a number between 0 and 1; eg 0.5 represents breaking if 50% or more of actions result in a handled failure.</param>
/// <param name="samplingDuration">The duration of the timeslice over which failure ratios are assessed.</param>
/// <param name="minimumThroughput">The minimum throughput: this many actions or more must pass through the circuit in the timeslice, for statistics to be considered significant and the circuit-breaker to come into action.</param>
/// <param name="durationOfBreak">The duration the circuit will stay open before resetting.</param>
/// <param name="onBreak">The action to call when the circuit transitions to an <see cref="CircuitState.Open"/> state.</param>
/// <param name="onReset">The action to call when the circuit resets to a <see cref="CircuitState.Closed"/> state.</param>
/// <param name="onHalfOpen">The action to call when the circuit transitions to <see cref="CircuitState.HalfOpen"/> state, ready to try action executions again. </param>
/// <returns>The policy instance.</returns>
/// <remarks>(see "Release It!" by Michael T. Nygard fi)</remarks>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be greater than zero</exception>
/// <exception cref="ArgumentOutOfRangeException">failureThreshold;Value must be less than or equal to one</exception>
/// <exception cref="ArgumentOutOfRangeException">samplingDuration;Value must be equal to or greater than the minimum resolution of the CircuitBreaker timer</exception>
/// <exception cref="ArgumentOutOfRangeException">minimumThroughput;Value must be greater than one</exception>
/// <exception cref="ArgumentOutOfRangeException">durationOfBreak;Value must be greater than zero</exception>
/// <exception cref="ArgumentNullException">onBreak</exception>
/// <exception cref="ArgumentNullException">onReset</exception>
/// <exception cref="ArgumentNullException">onHalfOpen</exception>
public static AsyncCircuitBreakerPolicy<TResult> AdvancedCircuitBreakerAsync<TResult>(this PolicyBuilder<TResult> policyBuilder, double failureThreshold, TimeSpan samplingDuration, int minimumThroughput, TimeSpan durationOfBreak, Action<DelegateResult<TResult>, CircuitState, TimeSpan, Context> onBreak, Action<Context> onReset, Action onHalfOpen)
{
var resolutionOfCircuit = TimeSpan.FromTicks(AdvancedCircuitController<EmptyStruct>.ResolutionOfCircuitTimer);
if (failureThreshold <= 0) throw new ArgumentOutOfRangeException(nameof(failureThreshold), "Value must be greater than zero.");
if (failureThreshold > 1) throw new ArgumentOutOfRangeException(nameof(failureThreshold), "Value must be less than or equal to one.");
if (samplingDuration < resolutionOfCircuit) throw new ArgumentOutOfRangeException(nameof(samplingDuration), $"Value must be equal to or greater than {resolutionOfCircuit.TotalMilliseconds} milliseconds. This is the minimum resolution of the CircuitBreaker timer.");
if (minimumThroughput <= 1) throw new ArgumentOutOfRangeException(nameof(minimumThroughput), "Value must be greater than one.");
if (durationOfBreak < TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(durationOfBreak), "Value must be greater than zero.");
if (onBreak == null) throw new ArgumentNullException(nameof(onBreak));
if (onReset == null) throw new ArgumentNullException(nameof(onReset));
if (onHalfOpen == null) throw new ArgumentNullException(nameof(onHalfOpen));
var breakerController = new AdvancedCircuitController<TResult>(
failureThreshold,
samplingDuration,
minimumThroughput,
durationOfBreak,
onBreak,
onReset,
onHalfOpen);
return new AsyncCircuitBreakerPolicy<TResult>(
policyBuilder,
breakerController
);
}
}
}
| |
#if !IGNORE_VISTA
using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using VistaDB;
using VistaDB.DDA;
using VistaDB.Provider;
using VistaDB.Diagnostic;
namespace Vista
{
class MyMetaHelper
{
private static readonly IVistaDBDDA DDA = VistaDBEngine.Connections.OpenDDA();
private string dbName = @"C:\Program Files\VistaDB 3.0 CTP\Data\Northwind.vdb3";
private string password = "";
public MyMetaHelper()
{
}
public MyMetaHelper(string dbName, string password)
{
}
public string GetDatabaseName()
{
string name = "";
int index = dbName.LastIndexOfAny(new char[]{'\\'});
if (index >= 0)
{
name = dbName.Substring(index + 1);
}
return name;
}
public DataTable GetDatabases()
{
DataTable metaData = new DataTable();
metaData.Columns.Add("CATALOG_NAME", Type.GetType("System.String"));
metaData.Columns.Add("DESCRIPTION", Type.GetType("System.String"));
metaData.Columns.Add("SCHEMA_NAME", Type.GetType("System.String"));
metaData.Columns.Add("SCHEMA_OWNER", Type.GetType("System.String"));
metaData.Columns.Add("DEFAULT_CHARACTER_SET_CATALOG", Type.GetType("System.String"));
metaData.Columns.Add("DEFAULT_CHARACTER_SET_SCHEMA", Type.GetType("System.String"));
metaData.Columns.Add("DEFAULT_CHARACTER_SET_NAME", Type.GetType("System.String"));
DataRow row = metaData.NewRow();
metaData.Rows.Add(row);
IVistaDBDatabase db = DDA.OpenDatabase(dbName, VistaDBDatabaseOpenMode.NonexclusiveReadOnly, password);
row["CATALOG_NAME"] = GetDatabaseName();
row["DESCRIPTION"] = db.Description;
return metaData;
}
public DataTable GetTables()
{
DataTable metaData = new DataTable();
//metaData.Columns.Add("TABLE_CATALOG", Type.GetType("System.String"));
//metaData.Columns.Add("TABLE_SCHEMA", Type.GetType("System.String"));
metaData.Columns.Add("TABLE_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("TABLE_TYPE", Type.GetType("System.String"));
//metaData.Columns.Add("TABLE_GUID", Type.GetType("System.String"));
metaData.Columns.Add("DESCRIPTION", Type.GetType("System.String"));
//metaData.Columns.Add("TABLE_PROPID", Type.GetType("System.String"));
//metaData.Columns.Add("DATE_CREATED", Type.GetType("System.String"));
//metaData.Columns.Add("DATE_MODIFIED", Type.GetType("System.String"));
IVistaDBDatabase db = DDA.OpenDatabase(dbName, VistaDBDatabaseOpenMode.NonexclusiveReadOnly, "");
ArrayList tables = db.EnumTables();
foreach (string table in tables)
{
IVistaDBTableStructure tblStructure = db.TableStructure(table);
DataRow row = metaData.NewRow();
metaData.Rows.Add(row);
row["TABLE_NAME"] = tblStructure.Name;
row["DESCRIPTION"] = tblStructure.Description;
}
return metaData;
}
public DataTable GetColumns(string tableName)
{
DataTable metaData = new DataTable();
//metaData.Columns.Add("TABLE_CATALOG", Type.GetType("System.String"));
//metaData.Columns.Add("TABLE_SCHEMA", Type.GetType("System.String"));
//metaData.Columns.Add("TABLE_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_GUID", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_PROPID", Type.GetType("System.String"));
//metaData.Columns.Add("ORDINAL_POSITION", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_HASDEFAULT", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_DEFAULT", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_FLAGS", Type.GetType("System.String"));
//metaData.Columns.Add("IS_NULLABLE", Type.GetType("System.String"));
//metaData.Columns.Add("DATA_TYPE", Type.GetType("System.String"));
//metaData.Columns.Add("TYPE_GUID", Type.GetType("System.String"));
//metaData.Columns.Add("CHARACTER_MAXIMUM_LENGTH", Type.GetType("System.String"));
//metaData.Columns.Add("CHARACTER_OCTET_LENGTH", Type.GetType("System.String"));
//metaData.Columns.Add("NUMERIC_PRECISION", Type.GetType("System.String"));
//metaData.Columns.Add("NUMERIC_SCALE", Type.GetType("System.String"));
//metaData.Columns.Add("DATETIME_PRECISION", Type.GetType("System.String"));
//metaData.Columns.Add("CHARACTER_SET_CATALOG", Type.GetType("System.String"));
//metaData.Columns.Add("CHARACTER_SET_SCHEMA", Type.GetType("System.String"));
//metaData.Columns.Add("CHARACTER_SET_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("COLLATION_CATALOG", Type.GetType("System.String"));
//metaData.Columns.Add("COLLATION_SCHEMA", Type.GetType("System.String"));
//metaData.Columns.Add("COLLATION_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("DOMAIN_CATALOG", Type.GetType("System.String"));
//metaData.Columns.Add("DOMAIN_SCHEMA", Type.GetType("System.String"));
//metaData.Columns.Add("DOMAIN_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("DESCRIPTION", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_LCID", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_COMPFLAGS", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_SORTID", Type.GetType("System.String"));
//metaData.Columns.Add("COLUMN_TDSCOLLATION", Type.GetType("System.String"));
//metaData.Columns.Add("IS_COMPUTED", Type.GetType("System.String"));
//metaData.Columns.Add("IS_AUTO_KEY", Type.GetType("System.String"));
//metaData.Columns.Add("AUTO_KEY_SEED", Type.GetType("System.String"));
//metaData.Columns.Add("AUTO_KEY_INCREMENT", Type.GetType("System.String"));
metaData.Columns.Add("TABLE_NAME", Type.GetType("System.String"));
metaData.Columns.Add("COLUMN_NAME", Type.GetType("System.String"));
metaData.Columns.Add("ORDINAL_POSITION", Type.GetType("System.Int32"));
metaData.Columns.Add("IS_NULLABLE", Type.GetType("System.Boolean"));
metaData.Columns.Add("COLUMN_HASDEFAULT", Type.GetType("System.Boolean"));
metaData.Columns.Add("COLUMN_DEFAULT", Type.GetType("System.String"));
metaData.Columns.Add("IS_AUTO_KEY", Type.GetType("System.Boolean"));
metaData.Columns.Add("AUTO_KEY_SEED", Type.GetType("System.Int32"));
metaData.Columns.Add("AUTO_KEY_INCREMENT", Type.GetType("System.Int32"));
metaData.Columns.Add("DATA_TYPE_NAME", Type.GetType("System.String"));
metaData.Columns.Add("NUMERIC_PRECISION", Type.GetType("System.Int32"));
metaData.Columns.Add("NUMERIC_SCALE", Type.GetType("System.Int32"));
metaData.Columns.Add("CHARACTER_MAXIMUM_LENGTH", Type.GetType("System.Int32"));
metaData.Columns.Add("CHARACTER_OCTET_LENGTH", Type.GetType("System.Int32"));
metaData.Columns.Add("DESCRIPTION", Type.GetType("System.String"));
metaData.Columns.Add("IS_PRIMARY_KEY", Type.GetType("System.Boolean"));
IVistaDBDatabase db = DDA.OpenDatabase(dbName, VistaDBDatabaseOpenMode.NonexclusiveReadOnly, "");
ArrayList tables = db.EnumTables();
IVistaDBTableStructure tblStructure = db.TableStructure(tableName);
foreach (IVistaDBColumnAttributes c in tblStructure)
{
string colName = c.Name;
string def = "";
if(tblStructure.Defaults.Contains(colName))
{
def = tblStructure.Defaults[colName].Expression;
}
int width = c.MaxLength; //c.ColumnWidth;
int dec = 0; //c.ColumnDecimals;
int length = 0;
int octLength = width;
IVistaDBIdentityInformation identity = null;
if(tblStructure.Identities.Contains(colName))
{
identity = tblStructure.Identities[colName];
}
string[] pks = null;
if(tblStructure.Indexes.Contains("PrimaryKey"))
{
pks = tblStructure.Indexes["PrimaryKey"].KeyExpression.Split(',');
}
else
{
foreach(IVistaDBIndexInformation pk in tblStructure.Indexes)
{
if(pk.Primary)
{
pks = pk.KeyExpression.Split(',');
break;
}
}
}
System.Collections.Hashtable pkCols = null;
if(pks != null)
{
pkCols = new Hashtable();
foreach(string pkColName in pks)
{
pkCols[pkColName] = true;
}
}
switch(c.Type)
{
case VistaDBType.Char:
case VistaDBType.NChar:
case VistaDBType.NText:
case VistaDBType.NVarchar:
case VistaDBType.Text:
case VistaDBType.Varchar:
length = width;
width = 0;
dec = 0;
break;
case VistaDBType.Currency:
case VistaDBType.Double:
case VistaDBType.Decimal:
case VistaDBType.Single:
break;
default:
width = 0;
dec = 0;
break;
}
metaData.Rows.Add(new object[]
{
tblStructure.Name,
c.Name,
c.RowIndex,
c.AllowNull,
def == string.Empty ? false : true,
def,
identity == null ? false : true,
1,
identity == null ? 0 : Convert.ToInt32(identity.StepExpression),
c.Type.ToString(),
width,
dec,
length,
octLength,
c.Description,
pkCols == null ? false : pkCols.Contains(colName)
} );
}
return metaData;
}
public DataTable GetIndexes(string tableName)
{
DataTable metaData = new DataTable();
//metaData.Columns.Add("TABLE_CATALOG", Type.GetType("System.String"));
//metaData.Columns.Add("TABLE_SCHEMA", Type.GetType("System.String"));
//metaData.Columns.Add("TABLE_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("INDEX_CATALOG", Type.GetType("System.String"));
//metaData.Columns.Add("INDEX_SCHEMA", Type.GetType("System.String"));
//metaData.Columns.Add("INDEX_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("UNIQUE", Type.GetType("System.String"));
//metaData.Columns.Add("CLUSTERED", Type.GetType("System.String"));
//metaData.Columns.Add("TYPE", Type.GetType("System.String"));
//metaData.Columns.Add("FILL_FACTOR", Type.GetType("System.String"));
//metaData.Columns.Add("INITIAL_SIZE", Type.GetType("System.String"));
//metaData.Columns.Add("NULLS", Type.GetType("System.String"));
//metaData.Columns.Add("SORT_BOOKMARKS", Type.GetType("System.String"));
//metaData.Columns.Add("AUTO_UPDATE", Type.GetType("System.String"));
//metaData.Columns.Add("NULL_COLLATION", Type.GetType("System.String"));
//metaData.Columns.Add("COLLATION", Type.GetType("System.String"));
//metaData.Columns.Add("CARDINALITY", Type.GetType("System.String"));
//metaData.Columns.Add("PAGES", Type.GetType("System.String"));
//metaData.Columns.Add("FILTER_CONDITION", Type.GetType("System.String"));
//metaData.Columns.Add("INTEGRATED", Type.GetType("System.String"));
metaData.Columns.Add("TABLE_CATALOG", Type.GetType("System.String"));
metaData.Columns.Add("TABLE_NAME", Type.GetType("System.String"));
metaData.Columns.Add("INDEX_CATALOG", Type.GetType("System.String"));
metaData.Columns.Add("INDEX_NAME", Type.GetType("System.String"));
metaData.Columns.Add("UNIQUE", Type.GetType("System.Boolean"));
metaData.Columns.Add("COLLATION", Type.GetType("System.Int16"));
metaData.Columns.Add("COLUMN_NAME", Type.GetType("System.String"));
IVistaDBDatabase db = DDA.OpenDatabase(dbName, VistaDBDatabaseOpenMode.NonexclusiveReadOnly, "");
ArrayList tables = db.EnumTables();
IVistaDBTableStructure tblStructure = db.TableStructure(tableName);
foreach (IVistaDBIndexInformation indexInfo in tblStructure.Indexes)
{
string[] pks = indexInfo.KeyExpression.Split(',');
int index = 0;
foreach(string colName in pks)
{
metaData.Rows.Add(new object[]
{
GetDatabaseName(),
tblStructure.Name,
GetDatabaseName(),
indexInfo.Name,
indexInfo.Unique,
indexInfo.KeyStructure[index++].Descending ? 2 : 1,
colName});
}
}
return metaData;
}
public DataTable GetForeignKeys(string tableName)
{
DataTable metaData = new DataTable();
//metaData.Columns.Add("PK_TABLE_CATALOG", Type.GetType("System.String"));
//metaData.Columns.Add("PK_TABLE_SCHEMA", Type.GetType("System.String"));
//metaData.Columns.Add("PK_TABLE_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("FK_TABLE_CATALOG", Type.GetType("System.String"));
//metaData.Columns.Add("FK_TABLE_SCHEMA", Type.GetType("System.String"));
//metaData.Columns.Add("FK_TABLE_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("ORDINAL", Type.GetType("System.String"));
//metaData.Columns.Add("UPDATE_RULE", Type.GetType("System.String"));
//metaData.Columns.Add("DELETE_RULE", Type.GetType("System.String"));
//metaData.Columns.Add("PK_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("FK_NAME", Type.GetType("System.String"));
//metaData.Columns.Add("DEFERRABILITY", Type.GetType("System.String"));
metaData.Columns.Add("PK_TABLE_CATALOG", Type.GetType("System.String"));
metaData.Columns.Add("PK_TABLE_SCHEMA", Type.GetType("System.String"));
metaData.Columns.Add("FK_TABLE_CATALOG", Type.GetType("System.String"));
metaData.Columns.Add("FK_TABLE_SCHEMA", Type.GetType("System.String"));
metaData.Columns.Add("FK_TABLE_NAME", Type.GetType("System.String"));
metaData.Columns.Add("PK_TABLE_NAME", Type.GetType("System.String"));
metaData.Columns.Add("ORDINAL", Type.GetType("System.Int32"));
metaData.Columns.Add("FK_NAME", Type.GetType("System.String"));
metaData.Columns.Add("PK_NAME", Type.GetType("System.String"));
metaData.Columns.Add("PK_COLUMN_NAME", Type.GetType("System.String"));
metaData.Columns.Add("FK_COLUMN_NAME", Type.GetType("System.String"));
IVistaDBDatabase db = DDA.OpenDatabase(dbName, VistaDBDatabaseOpenMode.NonexclusiveReadOnly, "");
ArrayList tables = db.EnumTables();
IVistaDBTableStructure tblStructure = db.TableStructure(tableName);
foreach (IVistaDBRelationshipInformation relInfo in tblStructure.ForeignKeys)
{
//string[] fColumns = relInfo.ForeignKey.Split(new char[] {';'});
//string[] pColumns = relInfo.p.ForeignKey.pprimaryKey.Split(new char[] {';'});
//for(int i = 0; i < fColumns.GetLength(0); i++)
{
metaData.Rows.Add(new object[]
{
GetDatabaseName(),
DBNull.Value,
DBNull.Value,
DBNull.Value,
tblStructure.Name,
relInfo.PrimaryTable,
0,
relInfo.Name,
"PKEY",
"", //pColumns[i],
"" }); //fColumns[i]});
}
}
return metaData;
}
public void GetDBCompexInfo(string dbName)
{
try
{
using (IVistaDBDDA conn = VistaDBEngine.Connections.OpenDDA())
{
using (IVistaDBDatabase db = conn.OpenDatabase(dbName, VistaDBDatabaseOpenMode.ExclusiveReadOnly, null))
{
Console.WriteLine("METAINFORMATION FOR " + dbName + " DATABASE");
Console.WriteLine("-------------------------------------------");
Console.WriteLine("Table Description: " + db.Description);
Console.WriteLine("Row count: " + db.RowCount.ToString());
Console.WriteLine("PageSize: " + db.PageSize.ToString());
Console.WriteLine("Open mode: " + db.Mode.ToString());
Console.WriteLine("Culture: " + db.Culture.ToString());
Console.WriteLine("Case Sensitive: " + db.CaseSensitive.ToString());
ArrayList tables = db.EnumTables();
foreach (string table in tables)
{
IVistaDBTableStructure tblStructure = db.TableStructure(table);
Console.WriteLine("============================================");
Console.WriteLine("Table " + table);
Console.WriteLine("============================================");
//columns
Console.WriteLine("COLUMNS:");
foreach (IVistaDBColumnAttributes colInfo in tblStructure)
{
Console.WriteLine("\t" + colInfo.Name);
//use colInfo for getting columns metadata
}
//indexes
Console.WriteLine("INDEXES:");
foreach (IVistaDBIndexInformation indexInfo in tblStructure.Indexes)
{
Console.WriteLine("\t" + indexInfo.Name);
//use indexInfo for getting columns metadata
}
//constraints
Console.WriteLine("CONSTRAINTS:");
foreach (IVistaDBConstraintInformation constrInfo in tblStructure.Constraints)
{
Console.WriteLine("\t" + constrInfo.Name);
//use constrInfo for getting columns metadata
}
//foreignKeys
Console.WriteLine("FOREIGN KEYS:");
foreach (IVistaDBRelationshipInformation relInfo in tblStructure.ForeignKeys)
{
Console.WriteLine("\t" + relInfo.Name);
//use foreignKeys for getting columns metadata
}
}
}
}
}
catch (VistaDBException ex)
{
}
catch
{
}
}
}
}
#endif
| |
/*
* Vericred API
*
* Vericred's API allows you to search for Health Plans that a specific doctor
accepts.
## Getting Started
Visit our [Developer Portal](https://developers.vericred.com) to
create an account.
Once you have created an account, you can create one Application for
Production and another for our Sandbox (select the appropriate Plan when
you create the Application).
## SDKs
Our API follows standard REST conventions, so you can use any HTTP client
to integrate with us. You will likely find it easier to use one of our
[autogenerated SDKs](https://github.com/vericred/?query=vericred-),
which we make available for several common programming languages.
## Authentication
To authenticate, pass the API Key you created in the Developer Portal as
a `Vericred-Api-Key` header.
`curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Versioning
Vericred's API default to the latest version. However, if you need a specific
version, you can request it with an `Accept-Version` header.
The current version is `v3`. Previous versions are `v1` and `v2`.
`curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"`
## Pagination
Endpoints that accept `page` and `per_page` parameters are paginated. They expose
four additional fields that contain data about your position in the response,
namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988).
For example, to display 5 results per page and view the second page of a
`GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`.
## Sideloading
When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s
we sideload the associated data. In this example, we would provide an Array of
`State`s and a `state_id` for each provider. This is done primarily to reduce the
payload size since many of the `Provider`s will share a `State`
```
{
providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }],
states: [{ id: 1, code: 'NY' }]
}
```
If you need the second level of the object graph, you can just match the
corresponding id.
## Selecting specific data
All endpoints allow you to specify which fields you would like to return.
This allows you to limit the response to contain only the data you need.
For example, let's take a request that returns the following JSON by default
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890',
field_we_dont_care_about: 'value_we_dont_care_about'
},
states: [{
id: 1,
name: 'New York',
code: 'NY',
field_we_dont_care_about: 'value_we_dont_care_about'
}]
}
```
To limit our results to only return the fields we care about, we specify the
`select` query string parameter for the corresponding fields in the JSON
document.
In this case, we want to select `name` and `phone` from the `provider` key,
so we would add the parameters `select=provider.name,provider.phone`.
We also want the `name` and `code` from the `states` key, so we would
add the parameters `select=states.name,staes.code`. The id field of
each document is always returned whether or not it is requested.
Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code`
The response would be
```
{
provider: {
id: 1,
name: 'John',
phone: '1234567890'
},
states: [{
id: 1,
name: 'New York',
code: 'NY'
}]
}
```
## Benefits summary format
Benefit cost-share strings are formatted to capture:
* Network tiers
* Compound or conditional cost-share
* Limits on the cost-share
* Benefit-specific maximum out-of-pocket costs
**Example #1**
As an example, we would represent [this Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as:
* **Hospital stay facility fees**:
- Network Provider: `$400 copay/admit plus 20% coinsurance`
- Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance`
- Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible`
* **Rehabilitation services:**
- Network Provider: `20% coinsurance`
- Out-of-Network Provider: `50% coinsurance`
- Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.`
- Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period`
**Example #2**
In [this other Summary of Benefits & Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies.
* **Specialty drugs:**
- Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply`
- Out-of-Network Provider `Not covered`
- Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%`
**BNF**
Here's a description of the benefits summary string, represented as a context-free grammar:
```
<cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit>
<tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:"
<opt-num-prefix> ::= "first" <num> <unit> | ""
<unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)"
<value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable"
<compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible>
<copay> ::= "$" <num>
<coinsurace> ::= <num> "%"
<ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited"
<opt-per-unit> ::= "per day" | "per visit" | "per stay" | ""
<deductible> ::= "before deductible" | "after deductible" | ""
<tier-limit> ::= ", " <limit> | ""
<benefit-limit> ::= <limit> | ""
```
*
* OpenAPI spec version: 1.0.0
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*
* 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.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 IO.Vericred.Model
{
/// <summary>
/// Pricing
/// </summary>
[DataContract]
public partial class Pricing : IEquatable<Pricing>
{
/// <summary>
/// Initializes a new instance of the <see cref="Pricing" /> class.
/// </summary>
/// <param name="Age">Age of applicant.</param>
/// <param name="EffectiveDate">Effective date of plan.</param>
/// <param name="ExpirationDate">Plan expiration date.</param>
/// <param name="PlanId">Foreign key to plans.</param>
/// <param name="PremiumChildOnly">Child-only premium.</param>
/// <param name="PremiumFamily">Family premium.</param>
/// <param name="PremiumSingle">Single-person premium.</param>
/// <param name="PremiumSingleAndChildren">Single person including children premium.</param>
/// <param name="PremiumSingleAndSpouse">Person with spouse premium.</param>
/// <param name="PremiumSingleSmoker">Premium for single smoker.</param>
/// <param name="RatingAreaId">Foreign key to rating areas.</param>
/// <param name="PremiumSource">Where was this pricing data extracted from?.</param>
/// <param name="UpdatedAt">Time when pricing was last updated.</param>
public Pricing(int? Age = null, DateTime? EffectiveDate = null, DateTime? ExpirationDate = null, int? PlanId = null, decimal? PremiumChildOnly = null, decimal? PremiumFamily = null, decimal? PremiumSingle = null, decimal? PremiumSingleAndChildren = null, decimal? PremiumSingleAndSpouse = null, decimal? PremiumSingleSmoker = null, string RatingAreaId = null, string PremiumSource = null, string UpdatedAt = null)
{
this.Age = Age;
this.EffectiveDate = EffectiveDate;
this.ExpirationDate = ExpirationDate;
this.PlanId = PlanId;
this.PremiumChildOnly = PremiumChildOnly;
this.PremiumFamily = PremiumFamily;
this.PremiumSingle = PremiumSingle;
this.PremiumSingleAndChildren = PremiumSingleAndChildren;
this.PremiumSingleAndSpouse = PremiumSingleAndSpouse;
this.PremiumSingleSmoker = PremiumSingleSmoker;
this.RatingAreaId = RatingAreaId;
this.PremiumSource = PremiumSource;
this.UpdatedAt = UpdatedAt;
}
/// <summary>
/// Age of applicant
/// </summary>
/// <value>Age of applicant</value>
[DataMember(Name="age", EmitDefaultValue=false)]
public int? Age { get; set; }
/// <summary>
/// Effective date of plan
/// </summary>
/// <value>Effective date of plan</value>
[DataMember(Name="effective_date", EmitDefaultValue=false)]
public DateTime? EffectiveDate { get; set; }
/// <summary>
/// Plan expiration date
/// </summary>
/// <value>Plan expiration date</value>
[DataMember(Name="expiration_date", EmitDefaultValue=false)]
public DateTime? ExpirationDate { get; set; }
/// <summary>
/// Foreign key to plans
/// </summary>
/// <value>Foreign key to plans</value>
[DataMember(Name="plan_id", EmitDefaultValue=false)]
public int? PlanId { get; set; }
/// <summary>
/// Child-only premium
/// </summary>
/// <value>Child-only premium</value>
[DataMember(Name="premium_child_only", EmitDefaultValue=false)]
public decimal? PremiumChildOnly { get; set; }
/// <summary>
/// Family premium
/// </summary>
/// <value>Family premium</value>
[DataMember(Name="premium_family", EmitDefaultValue=false)]
public decimal? PremiumFamily { get; set; }
/// <summary>
/// Single-person premium
/// </summary>
/// <value>Single-person premium</value>
[DataMember(Name="premium_single", EmitDefaultValue=false)]
public decimal? PremiumSingle { get; set; }
/// <summary>
/// Single person including children premium
/// </summary>
/// <value>Single person including children premium</value>
[DataMember(Name="premium_single_and_children", EmitDefaultValue=false)]
public decimal? PremiumSingleAndChildren { get; set; }
/// <summary>
/// Person with spouse premium
/// </summary>
/// <value>Person with spouse premium</value>
[DataMember(Name="premium_single_and_spouse", EmitDefaultValue=false)]
public decimal? PremiumSingleAndSpouse { get; set; }
/// <summary>
/// Premium for single smoker
/// </summary>
/// <value>Premium for single smoker</value>
[DataMember(Name="premium_single_smoker", EmitDefaultValue=false)]
public decimal? PremiumSingleSmoker { get; set; }
/// <summary>
/// Foreign key to rating areas
/// </summary>
/// <value>Foreign key to rating areas</value>
[DataMember(Name="rating_area_id", EmitDefaultValue=false)]
public string RatingAreaId { get; set; }
/// <summary>
/// Where was this pricing data extracted from?
/// </summary>
/// <value>Where was this pricing data extracted from?</value>
[DataMember(Name="premium_source", EmitDefaultValue=false)]
public string PremiumSource { get; set; }
/// <summary>
/// Time when pricing was last updated
/// </summary>
/// <value>Time when pricing was last updated</value>
[DataMember(Name="updated_at", EmitDefaultValue=false)]
public string UpdatedAt { 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 Pricing {\n");
sb.Append(" Age: ").Append(Age).Append("\n");
sb.Append(" EffectiveDate: ").Append(EffectiveDate).Append("\n");
sb.Append(" ExpirationDate: ").Append(ExpirationDate).Append("\n");
sb.Append(" PlanId: ").Append(PlanId).Append("\n");
sb.Append(" PremiumChildOnly: ").Append(PremiumChildOnly).Append("\n");
sb.Append(" PremiumFamily: ").Append(PremiumFamily).Append("\n");
sb.Append(" PremiumSingle: ").Append(PremiumSingle).Append("\n");
sb.Append(" PremiumSingleAndChildren: ").Append(PremiumSingleAndChildren).Append("\n");
sb.Append(" PremiumSingleAndSpouse: ").Append(PremiumSingleAndSpouse).Append("\n");
sb.Append(" PremiumSingleSmoker: ").Append(PremiumSingleSmoker).Append("\n");
sb.Append(" RatingAreaId: ").Append(RatingAreaId).Append("\n");
sb.Append(" PremiumSource: ").Append(PremiumSource).Append("\n");
sb.Append(" UpdatedAt: ").Append(UpdatedAt).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 Pricing);
}
/// <summary>
/// Returns true if Pricing instances are equal
/// </summary>
/// <param name="other">Instance of Pricing to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Pricing other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Age == other.Age ||
this.Age != null &&
this.Age.Equals(other.Age)
) &&
(
this.EffectiveDate == other.EffectiveDate ||
this.EffectiveDate != null &&
this.EffectiveDate.Equals(other.EffectiveDate)
) &&
(
this.ExpirationDate == other.ExpirationDate ||
this.ExpirationDate != null &&
this.ExpirationDate.Equals(other.ExpirationDate)
) &&
(
this.PlanId == other.PlanId ||
this.PlanId != null &&
this.PlanId.Equals(other.PlanId)
) &&
(
this.PremiumChildOnly == other.PremiumChildOnly ||
this.PremiumChildOnly != null &&
this.PremiumChildOnly.Equals(other.PremiumChildOnly)
) &&
(
this.PremiumFamily == other.PremiumFamily ||
this.PremiumFamily != null &&
this.PremiumFamily.Equals(other.PremiumFamily)
) &&
(
this.PremiumSingle == other.PremiumSingle ||
this.PremiumSingle != null &&
this.PremiumSingle.Equals(other.PremiumSingle)
) &&
(
this.PremiumSingleAndChildren == other.PremiumSingleAndChildren ||
this.PremiumSingleAndChildren != null &&
this.PremiumSingleAndChildren.Equals(other.PremiumSingleAndChildren)
) &&
(
this.PremiumSingleAndSpouse == other.PremiumSingleAndSpouse ||
this.PremiumSingleAndSpouse != null &&
this.PremiumSingleAndSpouse.Equals(other.PremiumSingleAndSpouse)
) &&
(
this.PremiumSingleSmoker == other.PremiumSingleSmoker ||
this.PremiumSingleSmoker != null &&
this.PremiumSingleSmoker.Equals(other.PremiumSingleSmoker)
) &&
(
this.RatingAreaId == other.RatingAreaId ||
this.RatingAreaId != null &&
this.RatingAreaId.Equals(other.RatingAreaId)
) &&
(
this.PremiumSource == other.PremiumSource ||
this.PremiumSource != null &&
this.PremiumSource.Equals(other.PremiumSource)
) &&
(
this.UpdatedAt == other.UpdatedAt ||
this.UpdatedAt != null &&
this.UpdatedAt.Equals(other.UpdatedAt)
);
}
/// <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.Age != null)
hash = hash * 59 + this.Age.GetHashCode();
if (this.EffectiveDate != null)
hash = hash * 59 + this.EffectiveDate.GetHashCode();
if (this.ExpirationDate != null)
hash = hash * 59 + this.ExpirationDate.GetHashCode();
if (this.PlanId != null)
hash = hash * 59 + this.PlanId.GetHashCode();
if (this.PremiumChildOnly != null)
hash = hash * 59 + this.PremiumChildOnly.GetHashCode();
if (this.PremiumFamily != null)
hash = hash * 59 + this.PremiumFamily.GetHashCode();
if (this.PremiumSingle != null)
hash = hash * 59 + this.PremiumSingle.GetHashCode();
if (this.PremiumSingleAndChildren != null)
hash = hash * 59 + this.PremiumSingleAndChildren.GetHashCode();
if (this.PremiumSingleAndSpouse != null)
hash = hash * 59 + this.PremiumSingleAndSpouse.GetHashCode();
if (this.PremiumSingleSmoker != null)
hash = hash * 59 + this.PremiumSingleSmoker.GetHashCode();
if (this.RatingAreaId != null)
hash = hash * 59 + this.RatingAreaId.GetHashCode();
if (this.PremiumSource != null)
hash = hash * 59 + this.PremiumSource.GetHashCode();
if (this.UpdatedAt != null)
hash = hash * 59 + this.UpdatedAt.GetHashCode();
return hash;
}
}
}
}
| |
// Copyright (c) 2007 James Newton-King; 2014 Extesla, LLC.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using OpenGamingLibrary.Json.Linq;
using OpenGamingLibrary.Json.Utilities;
using OpenGamingLibrary.Json.Serialization;
using System.Linq;
namespace OpenGamingLibrary.Json.Schema
{
/// <summary>
/// Generates a <see cref="JsonSchema"/> from a specified <see cref="Type"/>.
/// </summary>
public class JsonSchemaGenerator
{
/// <summary>
/// Gets or sets how undefined schemas are handled by the serializer.
/// </summary>
public UndefinedSchemaIdHandling UndefinedSchemaIdHandling { get; set; }
private IContractResolver _contractResolver;
/// <summary>
/// Gets or sets the contract resolver.
/// </summary>
/// <value>The contract resolver.</value>
public IContractResolver ContractResolver
{
get
{
if (_contractResolver == null)
return DefaultContractResolver.Instance;
return _contractResolver;
}
set { _contractResolver = value; }
}
private class TypeSchema
{
public Type Type { get; private set; }
public JsonSchema Schema { get; private set; }
public TypeSchema(Type type, JsonSchema schema)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(schema, "schema");
Type = type;
Schema = schema;
}
}
private JsonSchemaResolver _resolver;
private readonly IList<TypeSchema> _stack = new List<TypeSchema>();
private JsonSchema _currentSchema;
private JsonSchema CurrentSchema
{
get { return _currentSchema; }
}
private void Push(TypeSchema typeSchema)
{
_currentSchema = typeSchema.Schema;
_stack.Add(typeSchema);
_resolver.LoadedSchemas.Add(typeSchema.Schema);
}
private TypeSchema Pop()
{
TypeSchema popped = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
TypeSchema newValue = _stack.LastOrDefault();
if (newValue != null)
{
_currentSchema = newValue.Schema;
}
else
{
_currentSchema = null;
}
return popped;
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type)
{
return Generate(type, new JsonSchemaResolver(), false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver)
{
return Generate(type, resolver, false);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, bool rootSchemaNullable)
{
return Generate(type, new JsonSchemaResolver(), rootSchemaNullable);
}
/// <summary>
/// Generate a <see cref="JsonSchema"/> from the specified type.
/// </summary>
/// <param name="type">The type to generate a <see cref="JsonSchema"/> from.</param>
/// <param name="resolver">The <see cref="JsonSchemaResolver"/> used to resolve schema references.</param>
/// <param name="rootSchemaNullable">Specify whether the generated root <see cref="JsonSchema"/> will be nullable.</param>
/// <returns>A <see cref="JsonSchema"/> generated from the specified type.</returns>
public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable)
{
ValidationUtils.ArgumentNotNull(type, "type");
ValidationUtils.ArgumentNotNull(resolver, "resolver");
_resolver = resolver;
return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false);
}
private string GetTitle(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Title))
return containerAttribute.Title;
return null;
}
private string GetDescription(Type type)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Description))
return containerAttribute.Description;
#if !(NETFX_CORE || PORTABLE40 || PORTABLE)
DescriptionAttribute descriptionAttribute = ReflectionUtils.GetAttribute<DescriptionAttribute>(type);
if (descriptionAttribute != null)
return descriptionAttribute.Description;
#endif
return null;
}
private string GetTypeId(Type type, bool explicitOnly)
{
JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute<JsonContainerAttribute>(type);
if (containerAttribute != null && !string.IsNullOrEmpty(containerAttribute.Id))
return containerAttribute.Id;
if (explicitOnly)
return null;
switch (UndefinedSchemaIdHandling)
{
case UndefinedSchemaIdHandling.UseTypeName:
return type.FullName;
case UndefinedSchemaIdHandling.UseAssemblyQualifiedName:
return type.AssemblyQualifiedName;
default:
return null;
}
}
private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required)
{
ValidationUtils.ArgumentNotNull(type, "type");
string resolvedId = GetTypeId(type, false);
string explicitId = GetTypeId(type, true);
if (!string.IsNullOrEmpty(resolvedId))
{
JsonSchema resolvedSchema = _resolver.GetSchema(resolvedId);
if (resolvedSchema != null)
{
// resolved schema is not null but referencing member allows nulls
// change resolved schema to allow nulls. hacky but what are ya gonna do?
if (valueRequired != Required.Always && !HasFlag(resolvedSchema.Type, JsonSchemaType.Null))
resolvedSchema.Type |= JsonSchemaType.Null;
if (required && resolvedSchema.Required != true)
resolvedSchema.Required = true;
return resolvedSchema;
}
}
// test for unresolved circular reference
if (_stack.Any(tc => tc.Type == type))
{
throw new JsonException("Unresolved circular reference for type '{0}'. Explicitly define an Id for the type using a JsonObject/JsonArray attribute or automatically generate a type Id using the UndefinedSchemaIdHandling property.".FormatWith(CultureInfo.InvariantCulture, type));
}
JsonContract contract = ContractResolver.ResolveContract(type);
JsonConverter converter;
if ((converter = contract.Converter) != null || (converter = contract.InternalConverter) != null)
{
JsonSchema converterSchema = converter.GetSchema();
if (converterSchema != null)
return converterSchema;
}
Push(new TypeSchema(type, new JsonSchema()));
if (explicitId != null)
CurrentSchema.Id = explicitId;
if (required)
CurrentSchema.Required = true;
CurrentSchema.Title = GetTitle(type);
CurrentSchema.Description = GetDescription(type);
if (converter != null)
{
// todo: Add GetSchema to JsonConverter and use here?
CurrentSchema.Type = JsonSchemaType.Any;
}
else
{
switch (contract.ContractType)
{
case JsonContractType.Object:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateObjectSchema(type, (JsonObjectContract)contract);
break;
case JsonContractType.Array:
CurrentSchema.Type = AddNullType(JsonSchemaType.Array, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
JsonArrayAttribute arrayAttribute = JsonTypeReflector.GetCachedAttribute<JsonArrayAttribute>(type);
bool allowNullItem = (arrayAttribute == null || arrayAttribute.AllowNullItems);
Type collectionItemType = ReflectionUtils.GetCollectionItemType(type);
if (collectionItemType != null)
{
CurrentSchema.Items = new List<JsonSchema>();
CurrentSchema.Items.Add(GenerateInternal(collectionItemType, (!allowNullItem) ? Required.Always : Required.Default, false));
}
break;
case JsonContractType.Primitive:
CurrentSchema.Type = GetJsonSchemaType(type, valueRequired);
if (CurrentSchema.Type == JsonSchemaType.Integer && type.IsEnum() && !type.IsDefined(typeof(FlagsAttribute), true))
{
CurrentSchema.Enum = new List<JToken>();
IList<EnumValue<long>> enumValues = EnumUtils.GetNamesAndValues<long>(type);
foreach (EnumValue<long> enumValue in enumValues)
{
JToken value = JToken.FromObject(enumValue.Value);
CurrentSchema.Enum.Add(value);
}
}
break;
case JsonContractType.String:
JsonSchemaType schemaType = (!ReflectionUtils.IsNullable(contract.UnderlyingType))
? JsonSchemaType.String
: AddNullType(JsonSchemaType.String, valueRequired);
CurrentSchema.Type = schemaType;
break;
case JsonContractType.Dictionary:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
Type keyType;
Type valueType;
ReflectionUtils.GetDictionaryKeyValueTypes(type, out keyType, out valueType);
if (keyType != null)
{
JsonContract keyContract = ContractResolver.ResolveContract(keyType);
// can be converted to a string
if (keyContract.ContractType == JsonContractType.Primitive)
{
CurrentSchema.AdditionalProperties = GenerateInternal(valueType, Required.Default, false);
}
}
break;
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
case JsonContractType.Serializable:
CurrentSchema.Type = AddNullType(JsonSchemaType.Object, valueRequired);
CurrentSchema.Id = GetTypeId(type, false);
GenerateISerializableContract(type, (JsonISerializableContract)contract);
break;
#endif
#if !(NET35 || NET20 || PORTABLE40)
case JsonContractType.Dynamic:
#endif
case JsonContractType.Linq:
CurrentSchema.Type = JsonSchemaType.Any;
break;
default:
throw new JsonException("Unexpected contract type: {0}".FormatWith(CultureInfo.InvariantCulture, contract));
}
}
return Pop().Schema;
}
private JsonSchemaType AddNullType(JsonSchemaType type, Required valueRequired)
{
if (valueRequired != Required.Always)
return type | JsonSchemaType.Null;
return type;
}
private bool HasFlag(DefaultValueHandling value, DefaultValueHandling flag)
{
return ((value & flag) == flag);
}
private void GenerateObjectSchema(Type type, JsonObjectContract contract)
{
CurrentSchema.Properties = new Dictionary<string, JsonSchema>();
foreach (JsonProperty property in contract.Properties)
{
if (!property.Ignored)
{
bool optional = property.NullValueHandling == NullValueHandling.Ignore ||
HasFlag(property.DefaultValueHandling.GetValueOrDefault(), DefaultValueHandling.Ignore) ||
property.ShouldSerialize != null ||
property.GetIsSpecified != null;
JsonSchema propertySchema = GenerateInternal(property.PropertyType, property.Required, !optional);
if (property.DefaultValue != null)
propertySchema.Default = JToken.FromObject(property.DefaultValue);
CurrentSchema.Properties.Add(property.PropertyName, propertySchema);
}
}
if (type.IsSealed())
CurrentSchema.AllowAdditionalProperties = false;
}
#if !(NETFX_CORE || PORTABLE || PORTABLE40)
private void GenerateISerializableContract(Type type, JsonISerializableContract contract)
{
CurrentSchema.AllowAdditionalProperties = true;
}
#endif
internal static bool HasFlag(JsonSchemaType? value, JsonSchemaType flag)
{
// default value is Any
if (value == null)
return true;
bool match = ((value & flag) == flag);
if (match)
return true;
// integer is a subset of float
if (flag == JsonSchemaType.Integer && (value & JsonSchemaType.Float) == JsonSchemaType.Float)
return true;
return false;
}
private JsonSchemaType GetJsonSchemaType(Type type, Required valueRequired)
{
JsonSchemaType schemaType = JsonSchemaType.None;
if (valueRequired != Required.Always && ReflectionUtils.IsNullable(type))
{
schemaType = JsonSchemaType.Null;
if (ReflectionUtils.IsNullableType(type))
type = Nullable.GetUnderlyingType(type);
}
PrimitiveTypeCode typeCode = ConvertUtils.GetTypeCode(type);
switch (typeCode)
{
case PrimitiveTypeCode.Empty:
case PrimitiveTypeCode.Object:
return schemaType | JsonSchemaType.String;
#if !(NETFX_CORE || PORTABLE)
case PrimitiveTypeCode.DBNull:
return schemaType | JsonSchemaType.Null;
#endif
case PrimitiveTypeCode.Boolean:
return schemaType | JsonSchemaType.Boolean;
case PrimitiveTypeCode.Char:
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
#if !(PORTABLE || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
#endif
return schemaType | JsonSchemaType.Integer;
case PrimitiveTypeCode.Single:
case PrimitiveTypeCode.Double:
case PrimitiveTypeCode.Decimal:
return schemaType | JsonSchemaType.Float;
// convert to string?
case PrimitiveTypeCode.DateTime:
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
#endif
return schemaType | JsonSchemaType.String;
case PrimitiveTypeCode.String:
case PrimitiveTypeCode.Uri:
case PrimitiveTypeCode.Guid:
case PrimitiveTypeCode.TimeSpan:
case PrimitiveTypeCode.Bytes:
return schemaType | JsonSchemaType.String;
default:
throw new JsonException("Unexpected type code '{0}' for type '{1}'.".FormatWith(CultureInfo.InvariantCulture, typeCode, type));
}
}
}
}
| |
// 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.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Internal;
using System.Reflection.Metadata.Ecma335;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Reflection.Metadata
{
/// <summary>
/// Reads metadata as defined byte the ECMA 335 CLI specification.
/// </summary>
public sealed partial class MetadataReader
{
private readonly MetadataReaderOptions _options;
internal readonly MetadataStringDecoder utf8Decoder;
internal readonly NamespaceCache namespaceCache;
private Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>> _lazyNestedTypesMap;
internal readonly MemoryBlock Block;
// A row id of "mscorlib" AssemblyRef in a WinMD file (each WinMD file must have such a reference).
internal readonly int WinMDMscorlibRef;
#region Constructors
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length)
: this(metadata, length, MetadataReaderOptions.Default, null)
{
}
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions)"/> to obtain
/// metadata from a PE image.
/// </remarks>
public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options)
: this(metadata, length, options, null)
{
}
/// <summary>
/// Creates a metadata reader from the metadata stored at the given memory location.
/// </summary>
/// <remarks>
/// The memory is owned by the caller and it must be kept memory alive and unmodified throughout the lifetime of the <see cref="MetadataReader"/>.
/// Use <see cref="PEReaderExtensions.GetMetadataReader(PortableExecutable.PEReader, MetadataReaderOptions, MetadataStringDecoder)"/> to obtain
/// metadata from a PE image.
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is not positive.</exception>
/// <exception cref="ArgumentNullException"><paramref name="metadata"/> is null.</exception>
/// <exception cref="ArgumentException">The encoding of <paramref name="utf8Decoder"/> is not <see cref="UTF8Encoding"/>.</exception>
/// <exception cref="PlatformNotSupportedException">The current platform is big-endian.</exception>
public unsafe MetadataReader(byte* metadata, int length, MetadataReaderOptions options, MetadataStringDecoder utf8Decoder)
{
// Do not throw here when length is 0. We'll throw BadImageFormatException later on, so that the caller doesn't need to
// worry about the image (stream) being empty and can handle all image errors by catching BadImageFormatException.
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (metadata == null)
{
throw new ArgumentNullException(nameof(metadata));
}
if (utf8Decoder == null)
{
utf8Decoder = MetadataStringDecoder.DefaultUTF8;
}
if (!(utf8Decoder.Encoding is UTF8Encoding))
{
throw new ArgumentException(SR.MetadataStringDecoderEncodingMustBeUtf8, nameof(utf8Decoder));
}
if (!BitConverter.IsLittleEndian)
{
Throw.LitteEndianArchitectureRequired();
}
this.Block = new MemoryBlock(metadata, length);
_options = options;
this.utf8Decoder = utf8Decoder;
var headerReader = new BlobReader(this.Block);
this.ReadMetadataHeader(ref headerReader, out _versionString);
_metadataKind = GetMetadataKind(_versionString);
var streamHeaders = this.ReadStreamHeaders(ref headerReader);
// storage header and stream headers:
MemoryBlock metadataTableStream;
MemoryBlock standalonePdbStream;
this.InitializeStreamReaders(ref this.Block, streamHeaders, out _metadataStreamKind, out metadataTableStream, out standalonePdbStream);
int[] externalTableRowCountsOpt;
if (standalonePdbStream.Length > 0)
{
ReadStandalonePortablePdbStream(standalonePdbStream, out _debugMetadataHeader, out externalTableRowCountsOpt);
}
else
{
externalTableRowCountsOpt = null;
}
var tableReader = new BlobReader(metadataTableStream);
HeapSizes heapSizes;
int[] metadataTableRowCounts;
this.ReadMetadataTableHeader(ref tableReader, out heapSizes, out metadataTableRowCounts, out _sortedTables);
this.InitializeTableReaders(tableReader.GetMemoryBlockAt(0, tableReader.RemainingBytes), heapSizes, metadataTableRowCounts, externalTableRowCountsOpt);
// This previously could occur in obfuscated assemblies but a check was added to prevent
// it getting to this point
Debug.Assert(this.AssemblyTable.NumberOfRows <= 1);
// Although the specification states that the module table will have exactly one row,
// the native metadata reader would successfully read files containing more than one row.
// Such files exist in the wild and may be produced by obfuscators.
if (standalonePdbStream.Length == 0 && this.ModuleTable.NumberOfRows < 1)
{
throw new BadImageFormatException(SR.Format(SR.ModuleTableInvalidNumberOfRows, this.ModuleTable.NumberOfRows));
}
// read
this.namespaceCache = new NamespaceCache(this);
if (_metadataKind != MetadataKind.Ecma335)
{
this.WinMDMscorlibRef = FindMscorlibAssemblyRefNoProjection();
}
}
#endregion
#region Metadata Headers
private readonly string _versionString;
private readonly MetadataKind _metadataKind;
private readonly MetadataStreamKind _metadataStreamKind;
private readonly DebugMetadataHeader _debugMetadataHeader;
internal StringStreamReader StringStream;
internal BlobStreamReader BlobStream;
internal GuidStreamReader GuidStream;
internal UserStringStreamReader UserStringStream;
/// <summary>
/// True if the metadata stream has minimal delta format. Used for EnC.
/// </summary>
/// <remarks>
/// The metadata stream has minimal delta format if "#JTD" stream is present.
/// Minimal delta format uses large size (4B) when encoding table/heap references.
/// The heaps in minimal delta only contain data of the delta,
/// there is no padding at the beginning of the heaps that would align them
/// with the original full metadata heaps.
/// </remarks>
internal bool IsMinimalDelta;
/// <summary>
/// Looks like this function reads beginning of the header described in
/// ECMA-335 24.2.1 Metadata root
/// </summary>
private void ReadMetadataHeader(ref BlobReader memReader, out string versionString)
{
if (memReader.RemainingBytes < COR20Constants.MinimumSizeofMetadataHeader)
{
throw new BadImageFormatException(SR.MetadataHeaderTooSmall);
}
uint signature = memReader.ReadUInt32();
if (signature != COR20Constants.COR20MetadataSignature)
{
throw new BadImageFormatException(SR.MetadataSignature);
}
// major version
memReader.ReadUInt16();
// minor version
memReader.ReadUInt16();
// reserved:
memReader.ReadUInt32();
int versionStringSize = memReader.ReadInt32();
if (memReader.RemainingBytes < versionStringSize)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForVersionString);
}
int numberOfBytesRead;
versionString = memReader.GetMemoryBlockAt(0, versionStringSize).PeekUtf8NullTerminated(0, null, utf8Decoder, out numberOfBytesRead, '\0');
memReader.SkipBytes(versionStringSize);
}
private MetadataKind GetMetadataKind(string versionString)
{
// Treat metadata as CLI raw metadata if the client doesn't want to see projections.
if ((_options & MetadataReaderOptions.ApplyWindowsRuntimeProjections) == 0)
{
return MetadataKind.Ecma335;
}
if (!versionString.Contains("WindowsRuntime"))
{
return MetadataKind.Ecma335;
}
else if (versionString.Contains("CLR"))
{
return MetadataKind.ManagedWindowsMetadata;
}
else
{
return MetadataKind.WindowsMetadata;
}
}
/// <summary>
/// Reads stream headers described in ECMA-335 24.2.2 Stream header
/// </summary>
private StreamHeader[] ReadStreamHeaders(ref BlobReader memReader)
{
// storage header:
memReader.ReadUInt16();
int streamCount = memReader.ReadInt16();
var streamHeaders = new StreamHeader[streamCount];
for (int i = 0; i < streamHeaders.Length; i++)
{
if (memReader.RemainingBytes < COR20Constants.MinimumSizeofStreamHeader)
{
throw new BadImageFormatException(SR.StreamHeaderTooSmall);
}
streamHeaders[i].Offset = memReader.ReadUInt32();
streamHeaders[i].Size = memReader.ReadInt32();
streamHeaders[i].Name = memReader.ReadUtf8NullTerminated();
bool aligned = memReader.TryAlign(4);
if (!aligned || memReader.RemainingBytes == 0)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForStreamHeaderName);
}
}
return streamHeaders;
}
private void InitializeStreamReaders(
ref MemoryBlock metadataRoot,
StreamHeader[] streamHeaders,
out MetadataStreamKind metadataStreamKind,
out MemoryBlock metadataTableStream,
out MemoryBlock standalonePdbStream)
{
metadataTableStream = default(MemoryBlock);
standalonePdbStream = default(MemoryBlock);
metadataStreamKind = MetadataStreamKind.Illegal;
foreach (StreamHeader streamHeader in streamHeaders)
{
switch (streamHeader.Name)
{
case COR20Constants.StringStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForStringStream);
}
this.StringStream = new StringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind);
break;
case COR20Constants.BlobStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream);
}
this.BlobStream = new BlobStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size), _metadataKind);
break;
case COR20Constants.GUIDStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForGUIDStream);
}
this.GuidStream = new GuidStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size));
break;
case COR20Constants.UserStringStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForBlobStream);
}
this.UserStringStream = new UserStringStreamReader(metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size));
break;
case COR20Constants.CompressedMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream);
}
metadataStreamKind = MetadataStreamKind.Compressed;
metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size);
break;
case COR20Constants.UncompressedMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream);
}
metadataStreamKind = MetadataStreamKind.Uncompressed;
metadataTableStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size);
break;
case COR20Constants.MinimalDeltaMetadataTableStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream);
}
// the content of the stream is ignored
this.IsMinimalDelta = true;
break;
case COR20Constants.StandalonePdbStreamName:
if (metadataRoot.Length < streamHeader.Offset + streamHeader.Size)
{
throw new BadImageFormatException(SR.NotEnoughSpaceForMetadataStream);
}
standalonePdbStream = metadataRoot.GetMemoryBlockAt((int)streamHeader.Offset, streamHeader.Size);
break;
default:
// Skip unknown streams. Some obfuscators insert invalid streams.
continue;
}
}
if (IsMinimalDelta && metadataStreamKind != MetadataStreamKind.Uncompressed)
{
throw new BadImageFormatException(SR.InvalidMetadataStreamFormat);
}
}
#endregion
#region Tables and Heaps
private readonly TableMask _sortedTables;
/// <summary>
/// A row count for each possible table. May be indexed by <see cref="TableIndex"/>.
/// </summary>
internal int[] TableRowCounts;
internal ModuleTableReader ModuleTable;
internal TypeRefTableReader TypeRefTable;
internal TypeDefTableReader TypeDefTable;
internal FieldPtrTableReader FieldPtrTable;
internal FieldTableReader FieldTable;
internal MethodPtrTableReader MethodPtrTable;
internal MethodTableReader MethodDefTable;
internal ParamPtrTableReader ParamPtrTable;
internal ParamTableReader ParamTable;
internal InterfaceImplTableReader InterfaceImplTable;
internal MemberRefTableReader MemberRefTable;
internal ConstantTableReader ConstantTable;
internal CustomAttributeTableReader CustomAttributeTable;
internal FieldMarshalTableReader FieldMarshalTable;
internal DeclSecurityTableReader DeclSecurityTable;
internal ClassLayoutTableReader ClassLayoutTable;
internal FieldLayoutTableReader FieldLayoutTable;
internal StandAloneSigTableReader StandAloneSigTable;
internal EventMapTableReader EventMapTable;
internal EventPtrTableReader EventPtrTable;
internal EventTableReader EventTable;
internal PropertyMapTableReader PropertyMapTable;
internal PropertyPtrTableReader PropertyPtrTable;
internal PropertyTableReader PropertyTable;
internal MethodSemanticsTableReader MethodSemanticsTable;
internal MethodImplTableReader MethodImplTable;
internal ModuleRefTableReader ModuleRefTable;
internal TypeSpecTableReader TypeSpecTable;
internal ImplMapTableReader ImplMapTable;
internal FieldRVATableReader FieldRvaTable;
internal EnCLogTableReader EncLogTable;
internal EnCMapTableReader EncMapTable;
internal AssemblyTableReader AssemblyTable;
internal AssemblyProcessorTableReader AssemblyProcessorTable; // unused
internal AssemblyOSTableReader AssemblyOSTable; // unused
internal AssemblyRefTableReader AssemblyRefTable;
internal AssemblyRefProcessorTableReader AssemblyRefProcessorTable; // unused
internal AssemblyRefOSTableReader AssemblyRefOSTable; // unused
internal FileTableReader FileTable;
internal ExportedTypeTableReader ExportedTypeTable;
internal ManifestResourceTableReader ManifestResourceTable;
internal NestedClassTableReader NestedClassTable;
internal GenericParamTableReader GenericParamTable;
internal MethodSpecTableReader MethodSpecTable;
internal GenericParamConstraintTableReader GenericParamConstraintTable;
// debug tables
internal DocumentTableReader DocumentTable;
internal MethodDebugInformationTableReader MethodDebugInformationTable;
internal LocalScopeTableReader LocalScopeTable;
internal LocalVariableTableReader LocalVariableTable;
internal LocalConstantTableReader LocalConstantTable;
internal ImportScopeTableReader ImportScopeTable;
internal StateMachineMethodTableReader StateMachineMethodTable;
internal CustomDebugInformationTableReader CustomDebugInformationTable;
private void ReadMetadataTableHeader(ref BlobReader reader, out HeapSizes heapSizes, out int[] metadataTableRowCounts, out TableMask sortedTables)
{
if (reader.RemainingBytes < MetadataStreamConstants.SizeOfMetadataTableHeader)
{
throw new BadImageFormatException(SR.MetadataTableHeaderTooSmall);
}
// reserved (shall be ignored):
reader.ReadUInt32();
// major version (shall be ignored):
reader.ReadByte();
// minor version (shall be ignored):
reader.ReadByte();
// heap sizes:
heapSizes = (HeapSizes)reader.ReadByte();
// reserved (shall be ignored):
reader.ReadByte();
ulong presentTables = reader.ReadUInt64();
sortedTables = (TableMask)reader.ReadUInt64();
// According to ECMA-335, MajorVersion and MinorVersion have fixed values and,
// based on recommendation in 24.1 Fixed fields: When writing these fields it
// is best that they be set to the value indicated, on reading they should be ignored.
// We will not be checking version values. We will continue checking that the set of
// present tables is within the set we understand.
ulong validTables = (ulong)TableMask.V3_0_TablesMask;
if ((presentTables & ~validTables) != 0)
{
throw new BadImageFormatException(SR.Format(SR.UnknownTables, presentTables));
}
if (_metadataStreamKind == MetadataStreamKind.Compressed)
{
// In general Ptr tables and EnC tables are not allowed in a compressed stream.
// However when asked for a snapshot of the current metadata after an EnC change has been applied
// the CLR includes the EnCLog table into the snapshot. We need to be able to read the image,
// so we'll allow the table here but pretend it's empty later.
if ((presentTables & (ulong)(TableMask.PtrTables | TableMask.EnCMap)) != 0)
{
throw new BadImageFormatException(SR.IllegalTablesInCompressedMetadataStream);
}
}
metadataTableRowCounts = ReadMetadataTableRowCounts(ref reader, presentTables);
if ((heapSizes & HeapSizes.ExtraData) == HeapSizes.ExtraData)
{
// Skip "extra data" used by some obfuscators. Although it is not mentioned in the CLI spec,
// it is honored by the native metadata reader.
reader.ReadUInt32();
}
}
private static int[] ReadMetadataTableRowCounts(ref BlobReader memReader, ulong presentTableMask)
{
ulong currentTableBit = 1;
var rowCounts = new int[TableIndexExtensions.Count];
for (int i = 0; i < rowCounts.Length; i++)
{
if ((presentTableMask & currentTableBit) != 0)
{
if (memReader.RemainingBytes < sizeof(uint))
{
throw new BadImageFormatException(SR.TableRowCountSpaceTooSmall);
}
uint rowCount = memReader.ReadUInt32();
if (rowCount > TokenTypeIds.RIDMask)
{
throw new BadImageFormatException(SR.Format(SR.InvalidRowCount, rowCount));
}
rowCounts[i] = (int)rowCount;
}
currentTableBit <<= 1;
}
return rowCounts;
}
// internal for testing
internal static void ReadStandalonePortablePdbStream(MemoryBlock block, out DebugMetadataHeader debugMetadataHeader, out int[] externalTableRowCounts)
{
var reader = new BlobReader(block);
const int PdbIdSize = 20;
byte[] pdbId = reader.ReadBytes(PdbIdSize);
// ECMA-335 15.4.1.2:
// The entry point to an application shall be static.
// This entry point method can be a global method or it can appear inside a type.
// The entry point method shall either accept no arguments or a vector of strings.
// The return type of the entry point method shall be void, int32, or unsigned int32.
// The entry point method cannot be defined in a generic class.
uint entryPointToken = reader.ReadUInt32();
int entryPointRowId = (int)(entryPointToken & TokenTypeIds.RIDMask);
if (entryPointToken != 0 && ((entryPointToken & TokenTypeIds.TypeMask) != TokenTypeIds.MethodDef || entryPointRowId == 0))
{
throw new BadImageFormatException(string.Format(SR.InvalidEntryPointToken, entryPointToken));
}
ulong externalTableMask = reader.ReadUInt64();
// EnC & Ptr tables can't be referenced from standalone PDB metadata:
const ulong validTables = (ulong)(TableMask.V2_0_TablesMask & ~TableMask.PtrTables & ~TableMask.EnCLog & ~TableMask.EnCMap);
if ((externalTableMask & ~validTables) != 0)
{
throw new BadImageFormatException(string.Format(SR.UnknownTables, (TableMask)externalTableMask));
}
externalTableRowCounts = ReadMetadataTableRowCounts(ref reader, externalTableMask);
debugMetadataHeader = new DebugMetadataHeader(
ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref pdbId),
MethodDefinitionHandle.FromRowId(entryPointRowId));
}
private const int SmallIndexSize = 2;
private const int LargeIndexSize = 4;
private int GetReferenceSize(int[] rowCounts, TableIndex index)
{
return (rowCounts[(int)index] < MetadataStreamConstants.LargeTableRowCount && !IsMinimalDelta) ? SmallIndexSize : LargeIndexSize;
}
private void InitializeTableReaders(MemoryBlock metadataTablesMemoryBlock, HeapSizes heapSizes, int[] rowCounts, int[] externalRowCountsOpt)
{
// Size of reference tags in each table.
this.TableRowCounts = rowCounts;
// TODO (https://github.com/dotnet/corefx/issues/2061):
// Shouldn't XxxPtr table be always the same size or smaller than the corresponding Xxx table?
// Compute ref sizes for tables that can have pointer tables
int fieldRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.FieldPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Field);
int methodRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.MethodPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.MethodDef);
int paramRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.ParamPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Param);
int eventRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.EventPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Event);
int propertyRefSizeSorted = GetReferenceSize(rowCounts, TableIndex.PropertyPtr) > SmallIndexSize ? LargeIndexSize : GetReferenceSize(rowCounts, TableIndex.Property);
// Compute the coded token ref sizes
int typeDefOrRefRefSize = ComputeCodedTokenSize(TypeDefOrRefTag.LargeRowSize, rowCounts, TypeDefOrRefTag.TablesReferenced);
int hasConstantRefSize = ComputeCodedTokenSize(HasConstantTag.LargeRowSize, rowCounts, HasConstantTag.TablesReferenced);
int hasCustomAttributeRefSize = ComputeCodedTokenSize(HasCustomAttributeTag.LargeRowSize, rowCounts, HasCustomAttributeTag.TablesReferenced);
int hasFieldMarshalRefSize = ComputeCodedTokenSize(HasFieldMarshalTag.LargeRowSize, rowCounts, HasFieldMarshalTag.TablesReferenced);
int hasDeclSecurityRefSize = ComputeCodedTokenSize(HasDeclSecurityTag.LargeRowSize, rowCounts, HasDeclSecurityTag.TablesReferenced);
int memberRefParentRefSize = ComputeCodedTokenSize(MemberRefParentTag.LargeRowSize, rowCounts, MemberRefParentTag.TablesReferenced);
int hasSemanticsRefSize = ComputeCodedTokenSize(HasSemanticsTag.LargeRowSize, rowCounts, HasSemanticsTag.TablesReferenced);
int methodDefOrRefRefSize = ComputeCodedTokenSize(MethodDefOrRefTag.LargeRowSize, rowCounts, MethodDefOrRefTag.TablesReferenced);
int memberForwardedRefSize = ComputeCodedTokenSize(MemberForwardedTag.LargeRowSize, rowCounts, MemberForwardedTag.TablesReferenced);
int implementationRefSize = ComputeCodedTokenSize(ImplementationTag.LargeRowSize, rowCounts, ImplementationTag.TablesReferenced);
int customAttributeTypeRefSize = ComputeCodedTokenSize(CustomAttributeTypeTag.LargeRowSize, rowCounts, CustomAttributeTypeTag.TablesReferenced);
int resolutionScopeRefSize = ComputeCodedTokenSize(ResolutionScopeTag.LargeRowSize, rowCounts, ResolutionScopeTag.TablesReferenced);
int typeOrMethodDefRefSize = ComputeCodedTokenSize(TypeOrMethodDefTag.LargeRowSize, rowCounts, TypeOrMethodDefTag.TablesReferenced);
// Compute HeapRef Sizes
int stringHeapRefSize = (heapSizes & HeapSizes.StringHeapLarge) == HeapSizes.StringHeapLarge ? LargeIndexSize : SmallIndexSize;
int guidHeapRefSize = (heapSizes & HeapSizes.GuidHeapLarge) == HeapSizes.GuidHeapLarge ? LargeIndexSize : SmallIndexSize;
int blobHeapRefSize = (heapSizes & HeapSizes.BlobHeapLarge) == HeapSizes.BlobHeapLarge ? LargeIndexSize : SmallIndexSize;
// Populate the Table blocks
int totalRequiredSize = 0;
this.ModuleTable = new ModuleTableReader(rowCounts[(int)TableIndex.Module], stringHeapRefSize, guidHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ModuleTable.Block.Length;
this.TypeRefTable = new TypeRefTableReader(rowCounts[(int)TableIndex.TypeRef], resolutionScopeRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeRefTable.Block.Length;
this.TypeDefTable = new TypeDefTableReader(rowCounts[(int)TableIndex.TypeDef], fieldRefSizeSorted, methodRefSizeSorted, typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeDefTable.Block.Length;
this.FieldPtrTable = new FieldPtrTableReader(rowCounts[(int)TableIndex.FieldPtr], GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldPtrTable.Block.Length;
this.FieldTable = new FieldTableReader(rowCounts[(int)TableIndex.Field], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldTable.Block.Length;
this.MethodPtrTable = new MethodPtrTableReader(rowCounts[(int)TableIndex.MethodPtr], GetReferenceSize(rowCounts, TableIndex.MethodDef), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodPtrTable.Block.Length;
this.MethodDefTable = new MethodTableReader(rowCounts[(int)TableIndex.MethodDef], paramRefSizeSorted, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodDefTable.Block.Length;
this.ParamPtrTable = new ParamPtrTableReader(rowCounts[(int)TableIndex.ParamPtr], GetReferenceSize(rowCounts, TableIndex.Param), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ParamPtrTable.Block.Length;
this.ParamTable = new ParamTableReader(rowCounts[(int)TableIndex.Param], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ParamTable.Block.Length;
this.InterfaceImplTable = new InterfaceImplTableReader(rowCounts[(int)TableIndex.InterfaceImpl], IsDeclaredSorted(TableMask.InterfaceImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.InterfaceImplTable.Block.Length;
this.MemberRefTable = new MemberRefTableReader(rowCounts[(int)TableIndex.MemberRef], memberRefParentRefSize, stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MemberRefTable.Block.Length;
this.ConstantTable = new ConstantTableReader(rowCounts[(int)TableIndex.Constant], IsDeclaredSorted(TableMask.Constant), hasConstantRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ConstantTable.Block.Length;
this.CustomAttributeTable = new CustomAttributeTableReader(rowCounts[(int)TableIndex.CustomAttribute],
IsDeclaredSorted(TableMask.CustomAttribute),
hasCustomAttributeRefSize,
customAttributeTypeRefSize,
blobHeapRefSize,
metadataTablesMemoryBlock,
totalRequiredSize);
totalRequiredSize += this.CustomAttributeTable.Block.Length;
this.FieldMarshalTable = new FieldMarshalTableReader(rowCounts[(int)TableIndex.FieldMarshal], IsDeclaredSorted(TableMask.FieldMarshal), hasFieldMarshalRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldMarshalTable.Block.Length;
this.DeclSecurityTable = new DeclSecurityTableReader(rowCounts[(int)TableIndex.DeclSecurity], IsDeclaredSorted(TableMask.DeclSecurity), hasDeclSecurityRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.DeclSecurityTable.Block.Length;
this.ClassLayoutTable = new ClassLayoutTableReader(rowCounts[(int)TableIndex.ClassLayout], IsDeclaredSorted(TableMask.ClassLayout), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ClassLayoutTable.Block.Length;
this.FieldLayoutTable = new FieldLayoutTableReader(rowCounts[(int)TableIndex.FieldLayout], IsDeclaredSorted(TableMask.FieldLayout), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldLayoutTable.Block.Length;
this.StandAloneSigTable = new StandAloneSigTableReader(rowCounts[(int)TableIndex.StandAloneSig], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.StandAloneSigTable.Block.Length;
this.EventMapTable = new EventMapTableReader(rowCounts[(int)TableIndex.EventMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), eventRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventMapTable.Block.Length;
this.EventPtrTable = new EventPtrTableReader(rowCounts[(int)TableIndex.EventPtr], GetReferenceSize(rowCounts, TableIndex.Event), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventPtrTable.Block.Length;
this.EventTable = new EventTableReader(rowCounts[(int)TableIndex.Event], typeDefOrRefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EventTable.Block.Length;
this.PropertyMapTable = new PropertyMapTableReader(rowCounts[(int)TableIndex.PropertyMap], GetReferenceSize(rowCounts, TableIndex.TypeDef), propertyRefSizeSorted, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyMapTable.Block.Length;
this.PropertyPtrTable = new PropertyPtrTableReader(rowCounts[(int)TableIndex.PropertyPtr], GetReferenceSize(rowCounts, TableIndex.Property), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyPtrTable.Block.Length;
this.PropertyTable = new PropertyTableReader(rowCounts[(int)TableIndex.Property], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.PropertyTable.Block.Length;
this.MethodSemanticsTable = new MethodSemanticsTableReader(rowCounts[(int)TableIndex.MethodSemantics], IsDeclaredSorted(TableMask.MethodSemantics), GetReferenceSize(rowCounts, TableIndex.MethodDef), hasSemanticsRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodSemanticsTable.Block.Length;
this.MethodImplTable = new MethodImplTableReader(rowCounts[(int)TableIndex.MethodImpl], IsDeclaredSorted(TableMask.MethodImpl), GetReferenceSize(rowCounts, TableIndex.TypeDef), methodDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodImplTable.Block.Length;
this.ModuleRefTable = new ModuleRefTableReader(rowCounts[(int)TableIndex.ModuleRef], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ModuleRefTable.Block.Length;
this.TypeSpecTable = new TypeSpecTableReader(rowCounts[(int)TableIndex.TypeSpec], blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.TypeSpecTable.Block.Length;
this.ImplMapTable = new ImplMapTableReader(rowCounts[(int)TableIndex.ImplMap], IsDeclaredSorted(TableMask.ImplMap), GetReferenceSize(rowCounts, TableIndex.ModuleRef), memberForwardedRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ImplMapTable.Block.Length;
this.FieldRvaTable = new FieldRVATableReader(rowCounts[(int)TableIndex.FieldRva], IsDeclaredSorted(TableMask.FieldRva), GetReferenceSize(rowCounts, TableIndex.Field), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FieldRvaTable.Block.Length;
this.EncLogTable = new EnCLogTableReader(rowCounts[(int)TableIndex.EncLog], metadataTablesMemoryBlock, totalRequiredSize, _metadataStreamKind);
totalRequiredSize += this.EncLogTable.Block.Length;
this.EncMapTable = new EnCMapTableReader(rowCounts[(int)TableIndex.EncMap], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.EncMapTable.Block.Length;
this.AssemblyTable = new AssemblyTableReader(rowCounts[(int)TableIndex.Assembly], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyTable.Block.Length;
this.AssemblyProcessorTable = new AssemblyProcessorTableReader(rowCounts[(int)TableIndex.AssemblyProcessor], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyProcessorTable.Block.Length;
this.AssemblyOSTable = new AssemblyOSTableReader(rowCounts[(int)TableIndex.AssemblyOS], metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyOSTable.Block.Length;
this.AssemblyRefTable = new AssemblyRefTableReader(rowCounts[(int)TableIndex.AssemblyRef], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize, _metadataKind);
totalRequiredSize += this.AssemblyRefTable.Block.Length;
this.AssemblyRefProcessorTable = new AssemblyRefProcessorTableReader(rowCounts[(int)TableIndex.AssemblyRefProcessor], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyRefProcessorTable.Block.Length;
this.AssemblyRefOSTable = new AssemblyRefOSTableReader(rowCounts[(int)TableIndex.AssemblyRefOS], GetReferenceSize(rowCounts, TableIndex.AssemblyRef), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.AssemblyRefOSTable.Block.Length;
this.FileTable = new FileTableReader(rowCounts[(int)TableIndex.File], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.FileTable.Block.Length;
this.ExportedTypeTable = new ExportedTypeTableReader(rowCounts[(int)TableIndex.ExportedType], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ExportedTypeTable.Block.Length;
this.ManifestResourceTable = new ManifestResourceTableReader(rowCounts[(int)TableIndex.ManifestResource], implementationRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ManifestResourceTable.Block.Length;
this.NestedClassTable = new NestedClassTableReader(rowCounts[(int)TableIndex.NestedClass], IsDeclaredSorted(TableMask.NestedClass), GetReferenceSize(rowCounts, TableIndex.TypeDef), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.NestedClassTable.Block.Length;
this.GenericParamTable = new GenericParamTableReader(rowCounts[(int)TableIndex.GenericParam], IsDeclaredSorted(TableMask.GenericParam), typeOrMethodDefRefSize, stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.GenericParamTable.Block.Length;
this.MethodSpecTable = new MethodSpecTableReader(rowCounts[(int)TableIndex.MethodSpec], methodDefOrRefRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodSpecTable.Block.Length;
this.GenericParamConstraintTable = new GenericParamConstraintTableReader(rowCounts[(int)TableIndex.GenericParamConstraint], IsDeclaredSorted(TableMask.GenericParamConstraint), GetReferenceSize(rowCounts, TableIndex.GenericParam), typeDefOrRefRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.GenericParamConstraintTable.Block.Length;
// debug tables:
// Type-system metadata tables may be stored in a separate (external) metadata file.
// We need to use the row counts of the external tables when referencing them.
// Debug tables are local to the current metadata image and type system metadata tables are external and precede all debug tables.
var combinedRowCounts = (externalRowCountsOpt != null) ? CombineRowCounts(rowCounts, externalRowCountsOpt, firstLocalTableIndex: TableIndex.Document) : rowCounts;
int methodRefSizeCombined = GetReferenceSize(combinedRowCounts, TableIndex.MethodDef);
int hasCustomDebugInformationRefSizeCombined = ComputeCodedTokenSize(HasCustomDebugInformationTag.LargeRowSize, combinedRowCounts, HasCustomDebugInformationTag.TablesReferenced);
this.DocumentTable = new DocumentTableReader(rowCounts[(int)TableIndex.Document], guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.DocumentTable.Block.Length;
this.MethodDebugInformationTable = new MethodDebugInformationTableReader(rowCounts[(int)TableIndex.MethodDebugInformation], GetReferenceSize(rowCounts, TableIndex.Document), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.MethodDebugInformationTable.Block.Length;
this.LocalScopeTable = new LocalScopeTableReader(rowCounts[(int)TableIndex.LocalScope], IsDeclaredSorted(TableMask.LocalScope), methodRefSizeCombined, GetReferenceSize(rowCounts, TableIndex.ImportScope), GetReferenceSize(rowCounts, TableIndex.LocalVariable), GetReferenceSize(rowCounts, TableIndex.LocalConstant), metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.LocalScopeTable.Block.Length;
this.LocalVariableTable = new LocalVariableTableReader(rowCounts[(int)TableIndex.LocalVariable], stringHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.LocalVariableTable.Block.Length;
this.LocalConstantTable = new LocalConstantTableReader(rowCounts[(int)TableIndex.LocalConstant], stringHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.LocalConstantTable.Block.Length;
this.ImportScopeTable = new ImportScopeTableReader(rowCounts[(int)TableIndex.ImportScope], GetReferenceSize(rowCounts, TableIndex.ImportScope), blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.ImportScopeTable.Block.Length;
this.StateMachineMethodTable = new StateMachineMethodTableReader(rowCounts[(int)TableIndex.StateMachineMethod], IsDeclaredSorted(TableMask.StateMachineMethod), methodRefSizeCombined, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.StateMachineMethodTable.Block.Length;
this.CustomDebugInformationTable = new CustomDebugInformationTableReader(rowCounts[(int)TableIndex.CustomDebugInformation], IsDeclaredSorted(TableMask.CustomDebugInformation), hasCustomDebugInformationRefSizeCombined, guidHeapRefSize, blobHeapRefSize, metadataTablesMemoryBlock, totalRequiredSize);
totalRequiredSize += this.CustomDebugInformationTable.Block.Length;
if (totalRequiredSize > metadataTablesMemoryBlock.Length)
{
throw new BadImageFormatException(SR.MetadataTablesTooSmall);
}
}
private static int[] CombineRowCounts(int[] local, int[] external, TableIndex firstLocalTableIndex)
{
Debug.Assert(local.Length == external.Length);
var rowCounts = new int[local.Length];
for (int i = 0; i < (int)firstLocalTableIndex; i++)
{
rowCounts[i] = external[i];
}
for (int i = (int)firstLocalTableIndex; i < rowCounts.Length; i++)
{
rowCounts[i] = local[i];
}
return rowCounts;
}
private int ComputeCodedTokenSize(int largeRowSize, int[] rowCounts, TableMask tablesReferenced)
{
if (IsMinimalDelta)
{
return LargeIndexSize;
}
bool isAllReferencedTablesSmall = true;
ulong tablesReferencedMask = (ulong)tablesReferenced;
for (int tableIndex = 0; tableIndex < TableIndexExtensions.Count; tableIndex++)
{
if ((tablesReferencedMask & 1) != 0)
{
isAllReferencedTablesSmall = isAllReferencedTablesSmall && (rowCounts[tableIndex] < largeRowSize);
}
tablesReferencedMask >>= 1;
}
return isAllReferencedTablesSmall ? SmallIndexSize : LargeIndexSize;
}
private bool IsDeclaredSorted(TableMask index)
{
return (_sortedTables & index) != 0;
}
#endregion
#region Helpers
// internal for testing
internal NamespaceCache NamespaceCache
{
get { return namespaceCache; }
}
internal bool UseFieldPtrTable
{
get { return this.FieldPtrTable.NumberOfRows > 0; }
}
internal bool UseMethodPtrTable
{
get { return this.MethodPtrTable.NumberOfRows > 0; }
}
internal bool UseParamPtrTable
{
get { return this.ParamPtrTable.NumberOfRows > 0; }
}
internal bool UseEventPtrTable
{
get { return this.EventPtrTable.NumberOfRows > 0; }
}
internal bool UsePropertyPtrTable
{
get { return this.PropertyPtrTable.NumberOfRows > 0; }
}
internal void GetFieldRange(TypeDefinitionHandle typeDef, out int firstFieldRowId, out int lastFieldRowId)
{
int typeDefRowId = typeDef.RowId;
firstFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId);
if (firstFieldRowId == 0)
{
firstFieldRowId = 1;
lastFieldRowId = 0;
}
else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
{
lastFieldRowId = (this.UseFieldPtrTable) ? this.FieldPtrTable.NumberOfRows : this.FieldTable.NumberOfRows;
}
else
{
lastFieldRowId = this.TypeDefTable.GetFieldStart(typeDefRowId + 1) - 1;
}
}
internal void GetMethodRange(TypeDefinitionHandle typeDef, out int firstMethodRowId, out int lastMethodRowId)
{
int typeDefRowId = typeDef.RowId;
firstMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId);
if (firstMethodRowId == 0)
{
firstMethodRowId = 1;
lastMethodRowId = 0;
}
else if (typeDefRowId == this.TypeDefTable.NumberOfRows)
{
lastMethodRowId = (this.UseMethodPtrTable) ? this.MethodPtrTable.NumberOfRows : this.MethodDefTable.NumberOfRows;
}
else
{
lastMethodRowId = this.TypeDefTable.GetMethodStart(typeDefRowId + 1) - 1;
}
}
internal void GetEventRange(TypeDefinitionHandle typeDef, out int firstEventRowId, out int lastEventRowId)
{
int eventMapRowId = this.EventMapTable.FindEventMapRowIdFor(typeDef);
if (eventMapRowId == 0)
{
firstEventRowId = 1;
lastEventRowId = 0;
return;
}
firstEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId);
if (eventMapRowId == this.EventMapTable.NumberOfRows)
{
lastEventRowId = this.UseEventPtrTable ? this.EventPtrTable.NumberOfRows : this.EventTable.NumberOfRows;
}
else
{
lastEventRowId = this.EventMapTable.GetEventListStartFor(eventMapRowId + 1) - 1;
}
}
internal void GetPropertyRange(TypeDefinitionHandle typeDef, out int firstPropertyRowId, out int lastPropertyRowId)
{
int propertyMapRowId = this.PropertyMapTable.FindPropertyMapRowIdFor(typeDef);
if (propertyMapRowId == 0)
{
firstPropertyRowId = 1;
lastPropertyRowId = 0;
return;
}
firstPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId);
if (propertyMapRowId == this.PropertyMapTable.NumberOfRows)
{
lastPropertyRowId = (this.UsePropertyPtrTable) ? this.PropertyPtrTable.NumberOfRows : this.PropertyTable.NumberOfRows;
}
else
{
lastPropertyRowId = this.PropertyMapTable.GetPropertyListStartFor(propertyMapRowId + 1) - 1;
}
}
internal void GetParameterRange(MethodDefinitionHandle methodDef, out int firstParamRowId, out int lastParamRowId)
{
int rid = methodDef.RowId;
firstParamRowId = this.MethodDefTable.GetParamStart(rid);
if (firstParamRowId == 0)
{
firstParamRowId = 1;
lastParamRowId = 0;
}
else if (rid == this.MethodDefTable.NumberOfRows)
{
lastParamRowId = (this.UseParamPtrTable ? this.ParamPtrTable.NumberOfRows : this.ParamTable.NumberOfRows);
}
else
{
lastParamRowId = this.MethodDefTable.GetParamStart(rid + 1) - 1;
}
}
internal void GetLocalVariableRange(LocalScopeHandle scope, out int firstVariableRowId, out int lastVariableRowId)
{
int scopeRowId = scope.RowId;
firstVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId);
if (firstVariableRowId == 0)
{
firstVariableRowId = 1;
lastVariableRowId = 0;
}
else if (scopeRowId == this.LocalScopeTable.NumberOfRows)
{
lastVariableRowId = this.LocalVariableTable.NumberOfRows;
}
else
{
lastVariableRowId = this.LocalScopeTable.GetVariableStart(scopeRowId + 1) - 1;
}
}
internal void GetLocalConstantRange(LocalScopeHandle scope, out int firstConstantRowId, out int lastConstantRowId)
{
int scopeRowId = scope.RowId;
firstConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId);
if (firstConstantRowId == 0)
{
firstConstantRowId = 1;
lastConstantRowId = 0;
}
else if (scopeRowId == this.LocalScopeTable.NumberOfRows)
{
lastConstantRowId = this.LocalConstantTable.NumberOfRows;
}
else
{
lastConstantRowId = this.LocalScopeTable.GetConstantStart(scopeRowId + 1) - 1;
}
}
#endregion
#region Public APIs
/// <summary>
/// Pointer to the underlying data.
/// </summary>
public unsafe byte* MetadataPointer => Block.Pointer;
/// <summary>
/// Length of the underlying data.
/// </summary>
public int MetadataLength => Block.Length;
/// <summary>
/// Options passed to the constructor.
/// </summary>
public MetadataReaderOptions Options => _options;
/// <summary>
/// Version string read from metadata header.
/// </summary>
public string MetadataVersion => _versionString;
/// <summary>
/// Information decoded from #Pdb stream, or null if the stream is not present.
/// </summary>
public DebugMetadataHeader DebugMetadataHeader => _debugMetadataHeader;
/// <summary>
/// The kind of the metadata (plain ECMA335, WinMD, etc.).
/// </summary>
public MetadataKind MetadataKind => _metadataKind;
/// <summary>
/// Comparer used to compare strings stored in metadata.
/// </summary>
public MetadataStringComparer StringComparer => new MetadataStringComparer(this);
/// <summary>
/// Returns true if the metadata represent an assembly.
/// </summary>
public bool IsAssembly => AssemblyTable.NumberOfRows == 1;
public AssemblyReferenceHandleCollection AssemblyReferences => new AssemblyReferenceHandleCollection(this);
public TypeDefinitionHandleCollection TypeDefinitions => new TypeDefinitionHandleCollection(TypeDefTable.NumberOfRows);
public TypeReferenceHandleCollection TypeReferences => new TypeReferenceHandleCollection(TypeRefTable.NumberOfRows);
public CustomAttributeHandleCollection CustomAttributes => new CustomAttributeHandleCollection(this);
public DeclarativeSecurityAttributeHandleCollection DeclarativeSecurityAttributes => new DeclarativeSecurityAttributeHandleCollection(this);
public MemberReferenceHandleCollection MemberReferences => new MemberReferenceHandleCollection(MemberRefTable.NumberOfRows);
public ManifestResourceHandleCollection ManifestResources => new ManifestResourceHandleCollection(ManifestResourceTable.NumberOfRows);
public AssemblyFileHandleCollection AssemblyFiles => new AssemblyFileHandleCollection(FileTable.NumberOfRows);
public ExportedTypeHandleCollection ExportedTypes => new ExportedTypeHandleCollection(ExportedTypeTable.NumberOfRows);
public MethodDefinitionHandleCollection MethodDefinitions => new MethodDefinitionHandleCollection(this);
public FieldDefinitionHandleCollection FieldDefinitions => new FieldDefinitionHandleCollection(this);
public EventDefinitionHandleCollection EventDefinitions => new EventDefinitionHandleCollection(this);
public PropertyDefinitionHandleCollection PropertyDefinitions => new PropertyDefinitionHandleCollection(this);
public DocumentHandleCollection Documents => new DocumentHandleCollection(this);
public MethodDebugInformationHandleCollection MethodDebugInformation => new MethodDebugInformationHandleCollection(this);
public LocalScopeHandleCollection LocalScopes => new LocalScopeHandleCollection(this, 0);
public LocalVariableHandleCollection LocalVariables => new LocalVariableHandleCollection(this, default(LocalScopeHandle));
public LocalConstantHandleCollection LocalConstants => new LocalConstantHandleCollection(this, default(LocalScopeHandle));
public ImportScopeCollection ImportScopes => new ImportScopeCollection(this);
public CustomDebugInformationHandleCollection CustomDebugInformation => new CustomDebugInformationHandleCollection(this);
public AssemblyDefinition GetAssemblyDefinition()
{
if (!IsAssembly)
{
throw new InvalidOperationException(SR.MetadataImageDoesNotRepresentAnAssembly);
}
return new AssemblyDefinition(this);
}
public string GetString(StringHandle handle)
{
return StringStream.GetString(handle, utf8Decoder);
}
public string GetString(NamespaceDefinitionHandle handle)
{
if (handle.HasFullName)
{
return StringStream.GetString(handle.GetFullName(), utf8Decoder);
}
return namespaceCache.GetFullName(handle);
}
public byte[] GetBlobBytes(BlobHandle handle)
{
return BlobStream.GetBytes(handle);
}
public ImmutableArray<byte> GetBlobContent(BlobHandle handle)
{
// TODO: We can skip a copy for virtual blobs.
byte[] bytes = GetBlobBytes(handle);
return ImmutableByteArrayInterop.DangerousCreateFromUnderlyingArray(ref bytes);
}
public BlobReader GetBlobReader(BlobHandle handle)
{
return BlobStream.GetBlobReader(handle);
}
public string GetUserString(UserStringHandle handle)
{
return UserStringStream.GetString(handle);
}
public Guid GetGuid(GuidHandle handle)
{
return GuidStream.GetGuid(handle);
}
public ModuleDefinition GetModuleDefinition()
{
if (_debugMetadataHeader != null)
{
throw new InvalidOperationException(SR.StandaloneDebugMetadataImageDoesNotContainModuleTable);
}
return new ModuleDefinition(this);
}
public AssemblyReference GetAssemblyReference(AssemblyReferenceHandle handle)
{
return new AssemblyReference(this, handle.Value);
}
public TypeDefinition GetTypeDefinition(TypeDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new TypeDefinition(this, GetTypeDefTreatmentAndRowId(handle));
}
public NamespaceDefinition GetNamespaceDefinitionRoot()
{
NamespaceData data = namespaceCache.GetRootNamespace();
return new NamespaceDefinition(data);
}
public NamespaceDefinition GetNamespaceDefinition(NamespaceDefinitionHandle handle)
{
NamespaceData data = namespaceCache.GetNamespaceData(handle);
return new NamespaceDefinition(data);
}
private uint GetTypeDefTreatmentAndRowId(TypeDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (_metadataKind == MetadataKind.Ecma335)
{
return (uint)handle.RowId;
}
return CalculateTypeDefTreatmentAndRowId(handle);
}
public TypeReference GetTypeReference(TypeReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new TypeReference(this, GetTypeRefTreatmentAndRowId(handle));
}
private uint GetTypeRefTreatmentAndRowId(TypeReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (_metadataKind == MetadataKind.Ecma335)
{
return (uint)handle.RowId;
}
return CalculateTypeRefTreatmentAndRowId(handle);
}
public ExportedType GetExportedType(ExportedTypeHandle handle)
{
return new ExportedType(this, handle.RowId);
}
public CustomAttributeHandleCollection GetCustomAttributes(EntityHandle handle)
{
Debug.Assert(!handle.IsNil);
return new CustomAttributeHandleCollection(this, handle);
}
public CustomAttribute GetCustomAttribute(CustomAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new CustomAttribute(this, GetCustomAttributeTreatmentAndRowId(handle));
}
private uint GetCustomAttributeTreatmentAndRowId(CustomAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (_metadataKind == MetadataKind.Ecma335)
{
return (uint)handle.RowId;
}
return TreatmentAndRowId((byte)CustomAttributeTreatment.WinMD, handle.RowId);
}
public DeclarativeSecurityAttribute GetDeclarativeSecurityAttribute(DeclarativeSecurityAttributeHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new DeclarativeSecurityAttribute(this, handle.RowId);
}
public Constant GetConstant(ConstantHandle handle)
{
return new Constant(this, handle.RowId);
}
public MethodDefinition GetMethodDefinition(MethodDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new MethodDefinition(this, GetMethodDefTreatmentAndRowId(handle));
}
private uint GetMethodDefTreatmentAndRowId(MethodDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (_metadataKind == MetadataKind.Ecma335)
{
return (uint)handle.RowId;
}
return CalculateMethodDefTreatmentAndRowId(handle);
}
public FieldDefinition GetFieldDefinition(FieldDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new FieldDefinition(this, GetFieldDefTreatmentAndRowId(handle));
}
private uint GetFieldDefTreatmentAndRowId(FieldDefinitionHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (_metadataKind == MetadataKind.Ecma335)
{
return (uint)handle.RowId;
}
return CalculateFieldDefTreatmentAndRowId(handle);
}
public PropertyDefinition GetPropertyDefinition(PropertyDefinitionHandle handle)
{
return new PropertyDefinition(this, handle);
}
public EventDefinition GetEventDefinition(EventDefinitionHandle handle)
{
return new EventDefinition(this, handle);
}
public MethodImplementation GetMethodImplementation(MethodImplementationHandle handle)
{
return new MethodImplementation(this, handle);
}
public MemberReference GetMemberReference(MemberReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
return new MemberReference(this, GetMemberRefTreatmentAndRowId(handle));
}
private uint GetMemberRefTreatmentAndRowId(MemberReferenceHandle handle)
{
// PERF: This code pattern is JIT friendly and results in very efficient code.
if (_metadataKind == MetadataKind.Ecma335)
{
return (uint)handle.RowId;
}
return CalculateMemberRefTreatmentAndRowId(handle);
}
public MethodSpecification GetMethodSpecification(MethodSpecificationHandle handle)
{
return new MethodSpecification(this, handle);
}
public Parameter GetParameter(ParameterHandle handle)
{
return new Parameter(this, handle);
}
public GenericParameter GetGenericParameter(GenericParameterHandle handle)
{
return new GenericParameter(this, handle);
}
public GenericParameterConstraint GetGenericParameterConstraint(GenericParameterConstraintHandle handle)
{
return new GenericParameterConstraint(this, handle);
}
public ManifestResource GetManifestResource(ManifestResourceHandle handle)
{
return new ManifestResource(this, handle);
}
public AssemblyFile GetAssemblyFile(AssemblyFileHandle handle)
{
return new AssemblyFile(this, handle);
}
public StandaloneSignature GetStandaloneSignature(StandaloneSignatureHandle handle)
{
return new StandaloneSignature(this, handle);
}
public TypeSpecification GetTypeSpecification(TypeSpecificationHandle handle)
{
return new TypeSpecification(this, handle);
}
public ModuleReference GetModuleReference(ModuleReferenceHandle handle)
{
return new ModuleReference(this, handle);
}
public InterfaceImplementation GetInterfaceImplementation(InterfaceImplementationHandle handle)
{
return new InterfaceImplementation(this, handle);
}
internal TypeDefinitionHandle GetDeclaringType(MethodDefinitionHandle methodDef)
{
int methodRowId;
if (UseMethodPtrTable)
{
methodRowId = MethodPtrTable.GetRowIdForMethodDefRow(methodDef.RowId);
}
else
{
methodRowId = methodDef.RowId;
}
return TypeDefTable.FindTypeContainingMethod(methodRowId, MethodDefTable.NumberOfRows);
}
internal TypeDefinitionHandle GetDeclaringType(FieldDefinitionHandle fieldDef)
{
int fieldRowId;
if (UseFieldPtrTable)
{
fieldRowId = FieldPtrTable.GetRowIdForFieldDefRow(fieldDef.RowId);
}
else
{
fieldRowId = fieldDef.RowId;
}
return TypeDefTable.FindTypeContainingField(fieldRowId, FieldTable.NumberOfRows);
}
private static readonly ObjectPool<StringBuilder> s_stringBuilderPool = new ObjectPool<StringBuilder>(() => new StringBuilder());
public string GetString(DocumentNameBlobHandle handle)
{
return BlobStream.GetDocumentName(handle);
}
public Document GetDocument(DocumentHandle handle)
{
return new Document(this, handle);
}
public MethodDebugInformation GetMethodDebugInformation(MethodDebugInformationHandle handle)
{
return new MethodDebugInformation(this, handle);
}
public MethodDebugInformation GetMethodDebugInformation(MethodDefinitionHandle handle)
{
return new MethodDebugInformation(this, MethodDebugInformationHandle.FromRowId(handle.RowId));
}
public LocalScope GetLocalScope(LocalScopeHandle handle)
{
return new LocalScope(this, handle);
}
public LocalVariable GetLocalVariable(LocalVariableHandle handle)
{
return new LocalVariable(this, handle);
}
public LocalConstant GetLocalConstant(LocalConstantHandle handle)
{
return new LocalConstant(this, handle);
}
public ImportScope GetImportScope(ImportScopeHandle handle)
{
return new ImportScope(this, handle);
}
public CustomDebugInformation GetCustomDebugInformation(CustomDebugInformationHandle handle)
{
return new CustomDebugInformation(this, handle);
}
public CustomDebugInformationHandleCollection GetCustomDebugInformation(EntityHandle handle)
{
Debug.Assert(!handle.IsNil);
return new CustomDebugInformationHandleCollection(this, handle);
}
public LocalScopeHandleCollection GetLocalScopes(MethodDefinitionHandle handle)
{
return new LocalScopeHandleCollection(this, handle.RowId);
}
public LocalScopeHandleCollection GetLocalScopes(MethodDebugInformationHandle handle)
{
return new LocalScopeHandleCollection(this, handle.RowId);
}
#endregion
#region Nested Types
private void InitializeNestedTypesMap()
{
var groupedNestedTypes = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>.Builder>();
int numberOfNestedTypes = NestedClassTable.NumberOfRows;
ImmutableArray<TypeDefinitionHandle>.Builder builder = null;
TypeDefinitionHandle previousEnclosingClass = default(TypeDefinitionHandle);
for (int i = 1; i <= numberOfNestedTypes; i++)
{
TypeDefinitionHandle enclosingClass = NestedClassTable.GetEnclosingClass(i);
Debug.Assert(!enclosingClass.IsNil);
if (enclosingClass != previousEnclosingClass)
{
if (!groupedNestedTypes.TryGetValue(enclosingClass, out builder))
{
builder = ImmutableArray.CreateBuilder<TypeDefinitionHandle>();
groupedNestedTypes.Add(enclosingClass, builder);
}
previousEnclosingClass = enclosingClass;
}
else
{
Debug.Assert(builder == groupedNestedTypes[enclosingClass]);
}
builder.Add(NestedClassTable.GetNestedClass(i));
}
var nestedTypesMap = new Dictionary<TypeDefinitionHandle, ImmutableArray<TypeDefinitionHandle>>();
foreach (var group in groupedNestedTypes)
{
nestedTypesMap.Add(group.Key, group.Value.ToImmutable());
}
_lazyNestedTypesMap = nestedTypesMap;
}
/// <summary>
/// Returns an array of types nested in the specified type.
/// </summary>
internal ImmutableArray<TypeDefinitionHandle> GetNestedTypes(TypeDefinitionHandle typeDef)
{
if (_lazyNestedTypesMap == null)
{
InitializeNestedTypesMap();
}
ImmutableArray<TypeDefinitionHandle> nestedTypes;
if (_lazyNestedTypesMap.TryGetValue(typeDef, out nestedTypes))
{
return nestedTypes;
}
return ImmutableArray<TypeDefinitionHandle>.Empty;
}
#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.
// File System.Reflection.Emit.AssemblyBuilder.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Reflection.Emit
{
sealed public partial class AssemblyBuilder : System.Reflection.Assembly, System.Runtime.InteropServices._AssemblyBuilder
{
#region Methods and constructors
public void AddResourceFile(string name, string fileName, System.Reflection.ResourceAttributes attribute)
{
}
public void AddResourceFile(string name, string fileName)
{
}
internal AssemblyBuilder()
{
}
public ModuleBuilder DefineDynamicModule(string name)
{
Contract.Ensures(Contract.Result<System.Reflection.Emit.ModuleBuilder>() != null);
return default(ModuleBuilder);
}
public ModuleBuilder DefineDynamicModule(string name, string fileName)
{
Contract.Ensures(Contract.Result<System.Reflection.Emit.ModuleBuilder>() != null);
return default(ModuleBuilder);
}
public ModuleBuilder DefineDynamicModule(string name, bool emitSymbolInfo)
{
Contract.Ensures(Contract.Result<System.Reflection.Emit.ModuleBuilder>() != null);
return default(ModuleBuilder);
}
public ModuleBuilder DefineDynamicModule(string name, string fileName, bool emitSymbolInfo)
{
Contract.Ensures(Contract.Result<System.Reflection.Emit.ModuleBuilder>() != null);
return default(ModuleBuilder);
}
public System.Resources.IResourceWriter DefineResource(string name, string description, string fileName, System.Reflection.ResourceAttributes attribute)
{
Contract.Ensures(Contract.Result<System.Resources.IResourceWriter>() != null);
return default(System.Resources.IResourceWriter);
}
public System.Resources.IResourceWriter DefineResource(string name, string description, string fileName)
{
Contract.Ensures(Contract.Result<System.Resources.IResourceWriter>() != null);
return default(System.Resources.IResourceWriter);
}
public void DefineUnmanagedResource(byte[] resource)
{
}
public void DefineUnmanagedResource(string resourceFileName)
{
}
public void DefineVersionInfoResource(string product, string productVersion, string company, string copyright, string trademark)
{
}
public void DefineVersionInfoResource()
{
}
public override bool Equals(Object obj)
{
return default(bool);
}
public override Object[] GetCustomAttributes(bool inherit)
{
return default(Object[]);
}
public override Object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return default(Object[]);
}
public override IList<System.Reflection.CustomAttributeData> GetCustomAttributesData()
{
return default(IList<System.Reflection.CustomAttributeData>);
}
public ModuleBuilder GetDynamicModule(string name)
{
return default(ModuleBuilder);
}
public override Type[] GetExportedTypes()
{
return default(Type[]);
}
public override FileStream GetFile(string name)
{
return default(FileStream);
}
public override FileStream[] GetFiles(bool getResourceModules)
{
return default(FileStream[]);
}
public override int GetHashCode()
{
return default(int);
}
public override System.Reflection.Module[] GetLoadedModules(bool getResourceModules)
{
return default(System.Reflection.Module[]);
}
public override System.Reflection.ManifestResourceInfo GetManifestResourceInfo(string resourceName)
{
return default(System.Reflection.ManifestResourceInfo);
}
public override string[] GetManifestResourceNames()
{
return default(string[]);
}
public override Stream GetManifestResourceStream(string name)
{
return default(Stream);
}
public override Stream GetManifestResourceStream(Type type, string name)
{
return default(Stream);
}
public override System.Reflection.Module GetModule(string name)
{
return default(System.Reflection.Module);
}
public override System.Reflection.Module[] GetModules(bool getResourceModules)
{
return default(System.Reflection.Module[]);
}
public override System.Reflection.AssemblyName GetName(bool copiedName)
{
return default(System.Reflection.AssemblyName);
}
public override System.Reflection.AssemblyName[] GetReferencedAssemblies()
{
return default(System.Reflection.AssemblyName[]);
}
public override System.Reflection.Assembly GetSatelliteAssembly(System.Globalization.CultureInfo culture, Version version)
{
return default(System.Reflection.Assembly);
}
public override System.Reflection.Assembly GetSatelliteAssembly(System.Globalization.CultureInfo culture)
{
return default(System.Reflection.Assembly);
}
public override Type GetType(string name, bool throwOnError, bool ignoreCase)
{
return default(Type);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return default(bool);
}
public void Save(string assemblyFileName)
{
}
public void Save(string assemblyFileName, System.Reflection.PortableExecutableKinds portableExecutableKind, System.Reflection.ImageFileMachine imageFileMachine)
{
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
}
public void SetCustomAttribute(System.Reflection.ConstructorInfo con, byte[] binaryAttribute)
{
}
public void SetEntryPoint(System.Reflection.MethodInfo entryMethod)
{
}
public void SetEntryPoint(System.Reflection.MethodInfo entryMethod, PEFileKinds fileKind)
{
}
void System.Runtime.InteropServices._AssemblyBuilder.GetIDsOfNames(ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId)
{
}
void System.Runtime.InteropServices._AssemblyBuilder.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo)
{
}
void System.Runtime.InteropServices._AssemblyBuilder.GetTypeInfoCount(out uint pcTInfo)
{
pcTInfo = default(uint);
}
void System.Runtime.InteropServices._AssemblyBuilder.Invoke(uint dispIdMember, ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr)
{
}
#endregion
#region Properties and indexers
public override string CodeBase
{
get
{
return default(string);
}
}
public override System.Reflection.MethodInfo EntryPoint
{
get
{
return default(System.Reflection.MethodInfo);
}
}
public override System.Security.Policy.Evidence Evidence
{
get
{
return default(System.Security.Policy.Evidence);
}
}
public override string FullName
{
get
{
return default(string);
}
}
public override bool GlobalAssemblyCache
{
get
{
return default(bool);
}
}
public override long HostContext
{
get
{
return default(long);
}
}
public override string ImageRuntimeVersion
{
get
{
return default(string);
}
}
public override bool IsDynamic
{
get
{
return default(bool);
}
}
public override string Location
{
get
{
return default(string);
}
}
public override System.Reflection.Module ManifestModule
{
get
{
return default(System.Reflection.Module);
}
}
public override System.Security.PermissionSet PermissionSet
{
get
{
return default(System.Security.PermissionSet);
}
}
public override bool ReflectionOnly
{
get
{
return default(bool);
}
}
public override System.Security.SecurityRuleSet SecurityRuleSet
{
get
{
return default(System.Security.SecurityRuleSet);
}
}
#endregion
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="OrthographicCamera.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using MS.Internal.Collections;
using MS.Internal.PresentationCore;
using MS.Utility;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Markup;
using System.Windows.Media.Media3D.Converters;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Composition;
using System.Security;
using System.Security.Permissions;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
using System.Windows.Media.Imaging;
// These types are aliased to match the unamanaged names used in interop
using BOOL = System.UInt32;
using WORD = System.UInt16;
using Float = System.Single;
namespace System.Windows.Media.Media3D
{
sealed partial class OrthographicCamera : ProjectionCamera
{
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Shadows inherited Clone() with a strongly typed
/// version for convenience.
/// </summary>
public new OrthographicCamera Clone()
{
return (OrthographicCamera)base.Clone();
}
/// <summary>
/// Shadows inherited CloneCurrentValue() with a strongly typed
/// version for convenience.
/// </summary>
public new OrthographicCamera CloneCurrentValue()
{
return (OrthographicCamera)base.CloneCurrentValue();
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
private static void WidthPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
OrthographicCamera target = ((OrthographicCamera) d);
target.PropertyChanged(WidthProperty);
}
#region Public Properties
/// <summary>
/// Width - double. Default value is (double)2.0.
/// </summary>
public double Width
{
get
{
return (double) GetValue(WidthProperty);
}
set
{
SetValueInternal(WidthProperty, value);
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Protected Methods
//
//------------------------------------------------------
#region Protected Methods
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new OrthographicCamera();
}
#endregion ProtectedMethods
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
#region Internal Methods
/// <SecurityNote>
/// Critical: This code calls into an unsafe code block
/// TreatAsSafe: This code does not return any critical data.It is ok to expose
/// Channels are safe to call into and do not go cross domain and cross process
/// </SecurityNote>
[SecurityCritical,SecurityTreatAsSafe]
internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck)
{
// If we're told we can skip the channel check, then we must be on channel
Debug.Assert(!skipOnChannelCheck || _duceResource.IsOnChannel(channel));
if (skipOnChannelCheck || _duceResource.IsOnChannel(channel))
{
base.UpdateResource(channel, skipOnChannelCheck);
// Read values of properties into local variables
Transform3D vTransform = Transform;
// Obtain handles for properties that implement DUCE.IResource
DUCE.ResourceHandle hTransform;
if (vTransform == null ||
Object.ReferenceEquals(vTransform, Transform3D.Identity)
)
{
hTransform = DUCE.ResourceHandle.Null;
}
else
{
hTransform = ((DUCE.IResource)vTransform).GetHandle(channel);
}
// Obtain handles for animated properties
DUCE.ResourceHandle hNearPlaneDistanceAnimations = GetAnimationResourceHandle(NearPlaneDistanceProperty, channel);
DUCE.ResourceHandle hFarPlaneDistanceAnimations = GetAnimationResourceHandle(FarPlaneDistanceProperty, channel);
DUCE.ResourceHandle hPositionAnimations = GetAnimationResourceHandle(PositionProperty, channel);
DUCE.ResourceHandle hLookDirectionAnimations = GetAnimationResourceHandle(LookDirectionProperty, channel);
DUCE.ResourceHandle hUpDirectionAnimations = GetAnimationResourceHandle(UpDirectionProperty, channel);
DUCE.ResourceHandle hWidthAnimations = GetAnimationResourceHandle(WidthProperty, channel);
// Pack & send command packet
DUCE.MILCMD_ORTHOGRAPHICCAMERA data;
unsafe
{
data.Type = MILCMD.MilCmdOrthographicCamera;
data.Handle = _duceResource.GetHandle(channel);
data.htransform = hTransform;
if (hNearPlaneDistanceAnimations.IsNull)
{
data.nearPlaneDistance = NearPlaneDistance;
}
data.hNearPlaneDistanceAnimations = hNearPlaneDistanceAnimations;
if (hFarPlaneDistanceAnimations.IsNull)
{
data.farPlaneDistance = FarPlaneDistance;
}
data.hFarPlaneDistanceAnimations = hFarPlaneDistanceAnimations;
if (hPositionAnimations.IsNull)
{
data.position = CompositionResourceManager.Point3DToMilPoint3F(Position);
}
data.hPositionAnimations = hPositionAnimations;
if (hLookDirectionAnimations.IsNull)
{
data.lookDirection = CompositionResourceManager.Vector3DToMilPoint3F(LookDirection);
}
data.hLookDirectionAnimations = hLookDirectionAnimations;
if (hUpDirectionAnimations.IsNull)
{
data.upDirection = CompositionResourceManager.Vector3DToMilPoint3F(UpDirection);
}
data.hUpDirectionAnimations = hUpDirectionAnimations;
if (hWidthAnimations.IsNull)
{
data.width = Width;
}
data.hWidthAnimations = hWidthAnimations;
// Send packed command structure
channel.SendCommand(
(byte*)&data,
sizeof(DUCE.MILCMD_ORTHOGRAPHICCAMERA));
}
}
}
internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel)
{
if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_ORTHOGRAPHICCAMERA))
{
Transform3D vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel);
AddRefOnChannelAnimations(channel);
UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ );
}
return _duceResource.GetHandle(channel);
}
internal override void ReleaseOnChannelCore(DUCE.Channel channel)
{
Debug.Assert(_duceResource.IsOnChannel(channel));
if (_duceResource.ReleaseOnChannel(channel))
{
Transform3D vTransform = Transform;
if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel);
ReleaseOnChannelAnimations(channel);
}
}
internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel)
{
// Note that we are in a lock here already.
return _duceResource.GetHandle(channel);
}
internal override int GetChannelCountCore()
{
// must already be in composition lock here
return _duceResource.GetChannelCount();
}
internal override DUCE.Channel GetChannelCore(int index)
{
// Note that we are in a lock here already.
return _duceResource.GetChannel(index);
}
#endregion Internal Methods
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
#endregion Internal Properties
//------------------------------------------------------
//
// Dependency Properties
//
//------------------------------------------------------
#region Dependency Properties
/// <summary>
/// The DependencyProperty for the OrthographicCamera.Width property.
/// </summary>
public static readonly DependencyProperty WidthProperty;
#endregion Dependency Properties
//------------------------------------------------------
//
// Internal Fields
//
//------------------------------------------------------
#region Internal Fields
internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource();
internal const double c_Width = (double)2.0;
#endregion Internal Fields
#region Constructors
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
static OrthographicCamera()
{
// We check our static default fields which are of type Freezable
// to make sure that they are not mutable, otherwise we will throw
// if these get touched by more than one thread in the lifetime
// of your app. (Windows OS Bug #947272)
//
// Initializations
Type typeofThis = typeof(OrthographicCamera);
WidthProperty =
RegisterProperty("Width",
typeof(double),
typeofThis,
(double)2.0,
new PropertyChangedCallback(WidthPropertyChanged),
null,
/* isIndependentlyAnimated = */ true,
/* coerceValueCallback */ null);
}
#endregion Constructors
}
}
| |
//
// ParameterList.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2012 Jeffrey Stedfast
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using MimeKit.Encodings;
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A list of parameters, as found in the Content-Type and Content-Disposition headers.
/// </summary>
public sealed class ParameterList : IList<Parameter>
{
static readonly StringComparer icase = StringComparer.InvariantCultureIgnoreCase;
readonly Dictionary<string, Parameter> table;
readonly List<Parameter> parameters;
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.ParameterList"/> class.
/// </summary>
public ParameterList ()
{
table = new Dictionary<string, Parameter> (icase);
parameters = new List<Parameter> ();
}
/// <summary>
/// Adds a parameter with the specified name and value.
/// </summary>
/// <param name="name">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="name"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="value"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="name"/> contains illegal characters.
/// </exception>
public void Add (string name, string value)
{
Add (new Parameter (name, value));
}
/// <summary>
/// Checks if the <see cref="MimeKit.ParameterList"/> contains a parameter with the specified name.
/// </summary>
/// <returns><value>true</value> if the requested parameter exists;
/// otherwise <value>false</value>.</returns>
/// <param name="name">The parameter name.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="name"/> is <c>null</c>.
/// </exception>
public bool Contains (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
return table.ContainsKey (name);
}
/// <summary>
/// Gets the index of the requested parameter, if it exists.
/// </summary>
/// <returns>The index of the requested parameter; otherwise <value>-1</value>.</returns>
/// <param name="name">The parameter name.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="name"/> is <c>null</c>.
/// </exception>
public int IndexOf (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
for (int i = 0; i < parameters.Count; i++) {
if (parameters[i].Name == name)
return i;
}
return -1;
}
/// <summary>
/// Inserts a parameter with the specified name and value at the given index.
/// </summary>
/// <param name="index">The index to insert the parameter.</param>
/// <param name="name">The parameter name.</param>
/// <param name="value">The parameter value.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="name"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="value"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="name"/> contains illegal characters.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is out of range.
/// </exception>
public void Insert (int index, string name, string value)
{
if (index < 0 || index > Count)
throw new ArgumentOutOfRangeException ("index");
Insert (index, new Parameter (name, value));
}
/// <summary>
/// Removes the first occurance of the specified parameter.
/// </summary>
/// <returns><value>true</value> if the frst occurance of the specified
/// parameter was removed; otherwise <value>false</value>.</returns>
/// <param name="name">The parameter name.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="name"/> is <c>null</c>.
/// </exception>
public bool Remove (string name)
{
if (name == null)
throw new ArgumentNullException ("name");
Parameter param;
if (!table.TryGetValue (name, out param))
return false;
return Remove (param);
}
/// <summary>
/// Gets or sets the value of the first occurance of a parameter
/// with the specified name.
/// </summary>
/// <param name="name">The parameter name.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="name"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="value"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// The <paramref name="name"/> contains illegal characters.
/// </exception>
public string this [string name] {
get {
if (name == null)
throw new ArgumentNullException ("name");
Parameter param;
if (table.TryGetValue (name, out param))
return param.Value;
return null;
}
set {
if (name == null)
throw new ArgumentNullException ("name");
if (value == null)
throw new ArgumentNullException ("value");
Parameter param;
if (table.TryGetValue (name, out param)) {
param.Value = value;
} else {
Add (name, value);
}
}
}
#region ICollection implementation
/// <summary>
/// Gets the number of parameters in the <see cref="MimeKit.ParameterList"/>.
/// </summary>
/// <value>The number of parameters.</value>
public int Count {
get { return parameters.Count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read only.
/// </summary>
/// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value>
public bool IsReadOnly {
get { return false; }
}
/// <summary>
/// Adds the specified parameter.
/// </summary>
/// <param name="param">The parameter to add.</param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="param"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentException">
/// A parameter with the same name as <paramref name="param"/>
/// already exists.
/// </exception>
public void Add (Parameter param)
{
if (param == null)
throw new ArgumentNullException ("param");
if (table.ContainsKey (param.Name))
throw new ArgumentException ("A parameter of that name already exists.");
param.Changed += OnParamChanged;
table.Add (param.Name, param);
parameters.Add (param);
OnChanged ();
}
/// <summary>
/// Removes all parameters from the <see cref="MimeKit.ParameterList"/>.
/// </summary>
public void Clear ()
{
foreach (var param in parameters)
param.Changed -= OnParamChanged;
parameters.Clear ();
table.Clear ();
OnChanged ();
}
/// <summary>
/// Checks if the <see cref="MimeKit.ParameterList"/> contains the specified parameter.
/// </summary>
/// <returns><value>true</value> if the specified parameter is contained;
/// otherwise <value>false</value>.</returns>
/// <param name="param">The parameter.</param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="param"/> is <c>null</c>.
/// </exception>
public bool Contains (Parameter param)
{
if (param == null)
throw new ArgumentNullException ("param");
return parameters.Contains (param);
}
/// <summary>
/// Copies all of the contained parameters to the specified array.
/// </summary>
/// <param name="array">The array to copy the parameters to.</param>
/// <param name="arrayIndex">The index into the array.</param>
public void CopyTo (Parameter[] array, int arrayIndex)
{
parameters.CopyTo (array, arrayIndex);
}
/// <summary>
/// Removes the specified parameter.
/// </summary>
/// <returns><value>true</value> if the specified parameter was removed;
/// otherwise <value>false</value>.</returns>
/// <param name="param">The parameter.</param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="param"/> is <c>null</c>.
/// </exception>
public bool Remove (Parameter param)
{
if (param == null)
throw new ArgumentNullException ("param");
if (!parameters.Remove (param))
return false;
param.Changed -= OnParamChanged;
table.Remove (param.Name);
OnChanged ();
return true;
}
#endregion
#region IList implementation
/// <summary>
/// Gets the index of the requested parameter, if it exists.
/// </summary>
/// <returns>The index of the requested parameter; otherwise <value>-1</value>.</returns>
/// <param name="param">The parameter.</param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="param"/> is <c>null</c>.
/// </exception>
public int IndexOf (Parameter param)
{
if (param == null)
throw new ArgumentNullException ("param");
return parameters.IndexOf (param);
}
/// <summary>
/// Inserts the specified parameter at the given index.
/// </summary>
/// <param name="index">The index to insert the parameter.</param>
/// <param name="param">The parameter.</param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="param"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="index"/> is out of range.
/// </exception>
/// <exception cref="System.ArgumentException">
/// A parameter with the same name as <paramref name="param"/>
/// already exists.
/// </exception>
public void Insert (int index, Parameter param)
{
if (index < 0 || index > Count)
throw new ArgumentOutOfRangeException ("index");
if (param == null)
throw new ArgumentNullException ("param");
if (table.ContainsKey (param.Name))
throw new ArgumentException ("A parameter of that name already exists.");
parameters.Insert (index, param);
table.Add (param.Name, param);
param.Changed += OnParamChanged;
OnChanged ();
}
/// <summary>
/// Removes the parameter at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="index"/> is out of range.
/// </exception>
public void RemoveAt (int index)
{
if (index < 0 || index > Count)
throw new ArgumentOutOfRangeException ("index");
var param = parameters[index];
param.Changed -= OnParamChanged;
parameters.RemoveAt (index);
table.Remove (param.Name);
OnChanged ();
}
/// <summary>
/// Gets or sets the <see cref="MimeKit.Parameter"/> at the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <exception cref="System.ArgumentNullException">
/// The <paramref name="value"/> is <c>null</c>.
/// </exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// The <paramref name="index"/> is out of range.
/// </exception>
/// <exception cref="System.ArgumentException">
/// A parameter with the same name as <paramref name="value"/>
/// already exists.
/// </exception>
public Parameter this [int index] {
get {
return parameters[index];
}
set {
if (index < 0 || index > Count)
throw new ArgumentOutOfRangeException ("index");
var param = parameters[index];
if (param == value)
return;
if (icase.Compare (param.Name, value.Name) == 0) {
// replace the old param with the new one
if (table[param.Name] == param)
table[param.Name] = value;
} else if (table.ContainsKey (value.Name)) {
throw new ArgumentException ("A parameter of that name already exists.");
} else {
table.Add (value.Name, value);
table.Remove (param.Name);
}
param.Changed -= OnParamChanged;
value.Changed += OnParamChanged;
parameters[index] = value;
OnChanged ();
}
}
#endregion
#region IEnumerable implementation
/// <summary>
/// Gets an enumerator for the list of parameters.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<Parameter> GetEnumerator ()
{
return parameters.GetEnumerator ();
}
#endregion
#region IEnumerable implementation
IEnumerator IEnumerable.GetEnumerator ()
{
return parameters.GetEnumerator ();
}
#endregion
internal void Encode (FormatOptions options, StringBuilder builder, ref int lineLength, Encoding charset)
{
foreach (var param in parameters)
param.Encode (options, builder, ref lineLength, charset);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current
/// <see cref="MimeKit.ParameterList"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current
/// <see cref="MimeKit.ParameterList"/>.</returns>
public override string ToString ()
{
var values = new StringBuilder ();
foreach (var param in parameters) {
values.Append ("; ");
values.Append (param.ToString ());
}
return values.ToString ();
}
internal event EventHandler Changed;
void OnParamChanged (object sender, EventArgs args)
{
OnChanged ();
}
void OnChanged ()
{
if (Changed != null)
Changed (this, EventArgs.Empty);
}
static bool SkipParamName (byte[] text, ref int index, int endIndex)
{
int startIndex = index;
while (index < endIndex && text[index].IsAttr ())
index++;
return index > startIndex;
}
class NameValuePair : IComparable<NameValuePair> {
public int ValueLength;
public int ValueStart;
public bool Encoded;
public string Name;
public int? Id;
#region IComparable implementation
public int CompareTo (NameValuePair other)
{
if (!Id.HasValue) {
if (other.Id.HasValue)
return -1;
return 0;
}
if (!other.Id.HasValue)
return 1;
return Id.Value - other.Id.Value;
}
#endregion
}
static bool TryParseNameValuePair (byte[] text, ref int index, int endIndex, bool throwOnError, out NameValuePair pair)
{
int valueIndex, startIndex;
bool encoded = false;
int? id = null;
string name;
pair = null;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
startIndex = index;
if (!SkipParamName (text, ref index, endIndex)) {
if (throwOnError)
throw new ParseException (string.Format ("Invalid parameter name token at offset {0}", startIndex), startIndex, index);
return false;
}
name = Encoding.ASCII.GetString (text, startIndex, index - startIndex);
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete parameter at offset {0}", startIndex), startIndex, index);
return false;
}
if (text[index] == (byte) '*') {
// the parameter is either encoded or it has a part id
index++;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete parameter at offset {0}", startIndex), startIndex, index);
return false;
}
int value;
if (ParseUtils.TryParseInt32 (text, ref index, endIndex, out value)) {
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete parameter at offset {0}", startIndex), startIndex, index);
return false;
}
if (text[index] == (byte) '*') {
encoded = true;
index++;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete parameter at offset {0}", startIndex), startIndex, index);
return false;
}
}
id = value;
} else {
encoded = true;
}
}
if (text[index] != (byte) '=') {
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete parameter at offset {0}", startIndex), startIndex, index);
return false;
}
}
index++;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex) {
if (index >= endIndex) {
if (throwOnError)
throw new ParseException (string.Format ("Incomplete parameter at offset {0}", startIndex), startIndex, index);
return false;
}
}
valueIndex = index;
if (text[index] == (byte) '"')
ParseUtils.SkipQuoted (text, ref index, endIndex, throwOnError);
else
ParseUtils.SkipToken (text, ref index, endIndex);
pair = new NameValuePair () {
ValueLength = index - valueIndex,
ValueStart = valueIndex,
Encoded = encoded,
Name = name,
Id = id
};
return true;
}
static bool TryGetCharset (byte[] text, ref int index, int endIndex, out string charset)
{
int startIndex = index;
int charsetEnd;
int i;
charset = null;
for (i = index; i < endIndex; i++) {
if (text[i] == (byte) '\'')
break;
}
if (i == startIndex || i == endIndex)
return false;
charsetEnd = i;
for (i++; i < endIndex; i++) {
if (text[i] == (byte) '\'')
break;
}
if (i == endIndex)
return false;
charset = Encoding.ASCII.GetString (text, startIndex, charsetEnd - startIndex);
index = i + 1;
return true;
}
static string DecodeRfc2184 (ref Decoder decoder, HexDecoder hex, byte[] text, int startIndex, int count, bool flush)
{
int endIndex = startIndex + count;
int index = startIndex;
string charset;
// Note: decoder is only null if this is the first segment
if (decoder == null) {
if (TryGetCharset (text, ref index, endIndex, out charset)) {
try {
var encoding = CharsetUtils.GetEncoding (charset, "?");
decoder = encoding.GetDecoder ();
} catch (NotSupportedException) {
var encoding = Encoding.GetEncoding (28591); // iso-8859-1
decoder = encoding.GetDecoder ();
}
} else {
// When no charset is specified, it should be safe to assume US-ASCII...
// but we all know what assume means, right??
var encoding = Encoding.GetEncoding (28591); // iso-8859-1
decoder = encoding.GetDecoder ();
}
}
int length = endIndex - index;
var decoded = new byte[hex.EstimateOutputLength (length)];
// hex decode...
length = hex.Decode (text, index, length, decoded);
int outLength = decoder.GetCharCount (decoded, 0, length, flush);
char[] output = new char[outLength];
outLength = decoder.GetChars (decoded, 0, length, output, 0, flush);
return new string (output, 0, outLength);
}
internal static bool TryParse (ParserOptions options, byte[] text, ref int index, int endIndex, bool throwOnError, out ParameterList paramList)
{
var rfc2184 = new Dictionary<string, List<NameValuePair>> (icase);
var @params = new List<NameValuePair> ();
List<NameValuePair> parts;
paramList = null;
do {
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (index >= endIndex)
break;
// handle empty parameter name/value pairs
if (text[index] == (byte) ';') {
index++;
continue;
}
NameValuePair pair;
if (!TryParseNameValuePair (text, ref index, endIndex, throwOnError, out pair))
return false;
if (!ParseUtils.SkipCommentsAndWhiteSpace (text, ref index, endIndex, throwOnError))
return false;
if (pair.Id.HasValue) {
if (rfc2184.TryGetValue (pair.Name, out parts)) {
parts.Add (pair);
} else {
parts = new List<NameValuePair> ();
rfc2184.Add (pair.Name, parts);
@params.Add (pair);
parts.Add (pair);
}
} else {
@params.Add (pair);
}
if (index >= endIndex)
break;
if (text[index] != (byte) ';') {
if (throwOnError)
throw new ParseException (string.Format ("Invalid parameter list token at offset {0}", index), index, index);
return false;
}
index++;
} while (true);
paramList = new ParameterList ();
var hex = new HexDecoder ();
foreach (var param in @params) {
int startIndex = param.ValueStart;
int length = param.ValueLength;
Decoder decoder = null;
string value;
if (param.Id.HasValue) {
parts = rfc2184[param.Name];
parts.Sort ();
value = string.Empty;
for (int i = 0; i < parts.Count; i++) {
startIndex = parts[i].ValueStart;
length = parts[i].ValueLength;
if (parts[i].Encoded) {
bool flush = i + 1 >= parts.Count || !parts[i+1].Encoded;
value += DecodeRfc2184 (ref decoder, hex, text, startIndex, length, flush);
} else if (length >= 2 && text[startIndex] == (byte) '"') {
// FIXME: use Rfc2047.Unquote()??
value += CharsetUtils.ConvertToUnicode (options, text, startIndex + 1, length - 2);
hex.Reset ();
} else if (length > 0) {
value += CharsetUtils.ConvertToUnicode (options, text, startIndex, length);
hex.Reset ();
}
}
hex.Reset ();
} else if (param.Encoded) {
value = DecodeRfc2184 (ref decoder, hex, text, startIndex, length, true);
hex.Reset ();
} else if (length >= 2 && text[startIndex] == (byte) '"') {
// FIXME: use Rfc2047.Unquote()??
value = Rfc2047.DecodeText (options, text, startIndex + 1, length - 2);
} else if (length > 0) {
value = Rfc2047.DecodeText (options, text, startIndex, length);
} else {
value = string.Empty;
}
paramList.Add (new Parameter (param.Name, value));
}
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Runtime.CompilerServices;
namespace System.Numerics
{
/// <summary>
/// Contains various methods useful for creating, manipulating, combining, and converting generic vectors with one another.
/// </summary>
public static class Vector
{
// JIT is not looking at the Vector class methods
// all methods here should be inlined and they must be implemented in terms of Vector<T> intrinsics
#region Select Methods
/// <summary>
/// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector.
/// </summary>
/// <param name="condition">The integral mask vector used to drive selection.</param>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The new vector with elements selected based on the mask.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Single> ConditionalSelect(Vector<int> condition, Vector<Single> left, Vector<Single> right)
{
return (Vector<Single>)Vector<Single>.ConditionalSelect((Vector<Single>)condition, left, right);
}
/// <summary>
/// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector.
/// </summary>
/// <param name="condition">The integral mask vector used to drive selection.</param>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The new vector with elements selected based on the mask.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<double> ConditionalSelect(Vector<long> condition, Vector<double> left, Vector<double> right)
{
return (Vector<double>)Vector<double>.ConditionalSelect((Vector<double>)condition, left, right);
}
/// <summary>
/// Creates a new vector with elements selected between the two given source vectors, and based on a mask vector.
/// </summary>
/// <param name="condition">The mask vector used to drive selection.</param>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The new vector with elements selected based on the mask.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> ConditionalSelect<T>(Vector<T> condition, Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.ConditionalSelect(condition, left, right);
}
#endregion Select Methods
#region Comparison methods
#region Equals methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left and right were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Equals<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.Equals(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether elements in the left and right floating point vectors were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> Equals(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.Equals(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left and right were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> Equals(Vector<int> left, Vector<int> right)
{
return Vector<int>.Equals(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether elements in the left and right floating point vectors were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> Equals(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.Equals(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left and right were equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> Equals(Vector<long> left, Vector<long> right)
{
return Vector<long>.Equals(left, right);
}
/// <summary>
/// Returns a boolean indicating whether each pair of elements in the given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The first vector to compare.</param>
/// <returns>True if all elements are equal; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool EqualsAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left == right;
}
/// <summary>
/// Returns a boolean indicating whether any single pair of elements in the given vectors are equal.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any element pairs are equal; False if no element pairs are equal.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool EqualsAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
return !Vector<T>.Equals(left, right).Equals(Vector<T>.Zero);
}
#endregion Equals methods
#region Lessthan Methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> LessThan<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.LessThan(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> LessThan(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.LessThan(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> LessThan(Vector<int> left, Vector<int> right)
{
return Vector<int>.LessThan(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> LessThan(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.LessThan(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> LessThan(Vector<long> left, Vector<long> right)
{
return Vector<long>.LessThan(left, right);
}
/// <summary>
/// Returns a boolean indicating whether all of the elements in left are less than their corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if all elements in left are less than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool LessThanAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.LessThan(left, right);
return cond.Equals(Vector<int>.AllOnes);
}
/// <summary>
/// Returns a boolean indicating whether any element in left is less than its corresponding element in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any elements in left are less than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool LessThanAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.LessThan(left, right);
return !cond.Equals(Vector<int>.Zero);
}
#endregion LessthanMethods
#region Lessthanorequal methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> LessThanOrEqual<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> LessThanOrEqual(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> LessThanOrEqual(Vector<int> left, Vector<int> right)
{
return Vector<int>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> LessThanOrEqual(Vector<long> left, Vector<long> right)
{
return Vector<long>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were less than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> LessThanOrEqual(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.LessThanOrEqual(left, right);
}
/// <summary>
/// Returns a boolean indicating whether all elements in left are less than or equal to their corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if all elements in left are less than or equal to their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool LessThanOrEqualAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.LessThanOrEqual(left, right);
return cond.Equals(Vector<int>.AllOnes);
}
/// <summary>
/// Returns a boolean indicating whether any element in left is less than or equal to its corresponding element in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any elements in left are less than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool LessThanOrEqualAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.LessThanOrEqual(left, right);
return !cond.Equals(Vector<int>.Zero);
}
#endregion Lessthanorequal methods
#region Greaterthan methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> GreaterThan<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.GreaterThan(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> GreaterThan(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.GreaterThan(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> GreaterThan(Vector<int> left, Vector<int> right)
{
return Vector<int>.GreaterThan(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> GreaterThan(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.GreaterThan(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> GreaterThan(Vector<long> left, Vector<long> right)
{
return Vector<long>.GreaterThan(left, right);
}
/// <summary>
/// Returns a boolean indicating whether all elements in left are greater than the corresponding elements in right.
/// elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if all elements in left are greater than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool GreaterThanAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.GreaterThan(left, right);
return cond.Equals(Vector<int>.AllOnes);
}
/// <summary>
/// Returns a boolean indicating whether any element in left is greater than its corresponding element in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any elements in left are greater than their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool GreaterThanAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.GreaterThan(left, right);
return !cond.Equals(Vector<int>.Zero);
}
#endregion Greaterthan methods
#region Greaterthanorequal methods
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> GreaterThanOrEqual<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were greater than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> GreaterThanOrEqual(Vector<Single> left, Vector<Single> right)
{
return (Vector<int>)Vector<Single>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<int> GreaterThanOrEqual(Vector<int> left, Vector<int> right)
{
return Vector<int>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns a new vector whose elements signal whether the elements in left were greater than or equal to their
/// corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> GreaterThanOrEqual(Vector<long> left, Vector<long> right)
{
return Vector<long>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns an integral vector whose elements signal whether the elements in left were greater than or equal to
/// their corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>The resultant integral vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<long> GreaterThanOrEqual(Vector<double> left, Vector<double> right)
{
return (Vector<long>)Vector<double>.GreaterThanOrEqual(left, right);
}
/// <summary>
/// Returns a boolean indicating whether all of the elements in left are greater than or equal to
/// their corresponding elements in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if all elements in left are greater than or equal to their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool GreaterThanOrEqualAll<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.GreaterThanOrEqual(left, right);
return cond.Equals(Vector<int>.AllOnes);
}
/// <summary>
/// Returns a boolean indicating whether any element in left is greater than or equal to its corresponding element in right.
/// </summary>
/// <param name="left">The first vector to compare.</param>
/// <param name="right">The second vector to compare.</param>
/// <returns>True if any elements in left are greater than or equal to their corresponding elements in right; False otherwise.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static bool GreaterThanOrEqualAny<T>(Vector<T> left, Vector<T> right) where T : struct
{
Vector<int> cond = (Vector<int>)Vector<T>.GreaterThanOrEqual(left, right);
return !cond.Equals(Vector<int>.Zero);
}
#endregion Greaterthanorequal methods
#endregion Comparison methods
#region Vector Math Methods
// Every operation must either be a JIT intrinsic or implemented over a JIT intrinsic
// as a thin wrapper
// Operations implemented over a JIT intrinsic should be inlined
// Methods that do not have a <T> type parameter are recognized as intrinsics
/// <summary>
/// Returns whether or not vector operations are subject to hardware acceleration through JIT intrinsic support.
/// </summary>
[JitIntrinsic]
public static bool IsHardwareAccelerated
{
get
{
return false;
}
}
// Vector<T>
// Basic Math
// All Math operations for Vector<T> are aggressively inlined here
/// <summary>
/// Returns a new vector whose elements are the absolute values of the given vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The absolute value vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Abs<T>(Vector<T> value) where T : struct
{
return Vector<T>.Abs(value);
}
/// <summary>
/// Returns a new vector whose elements are the minimum of each pair of elements in the two given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The minimum vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Min<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.Min(left, right);
}
/// <summary>
/// Returns a new vector whose elements are the maximum of each pair of elements in the two given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The maximum vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Max<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.Max(left, right);
}
// Specialized vector operations
/// <summary>
/// Returns the dot product of two vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The dot product.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static T Dot<T>(Vector<T> left, Vector<T> right) where T : struct
{
return Vector<T>.DotProduct(left, right);
}
/// <summary>
/// Returns a new vector whose elements are the square roots of the given vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The square root vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> SquareRoot<T>(Vector<T> value) where T : struct
{
return Vector<T>.SquareRoot(value);
}
#endregion Vector Math Methods
#region Named Arithmetic Operators
/// <summary>
/// Creates a new vector whose values are the sum of each pair of elements from the two given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Add<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left + right;
}
/// <summary>
/// Creates a new vector whose values are the difference between each pairs of elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The difference vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Subtract<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left - right;
}
/// <summary>
/// Creates a new vector whose values are the product of each pair of elements from the two given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The summed vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Multiply<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left * right;
}
/// <summary>
/// Returns a new vector whose values are the values of the given vector each multiplied by a scalar value.
/// </summary>
/// <param name="left">The source vector.</param>
/// <param name="right">The scalar factor.</param>
/// <returns>The scaled vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Multiply<T>(Vector<T> left, T right) where T : struct
{
return left * right;
}
/// <summary>
/// Returns a new vector whose values are the values of the given vector each multiplied by a scalar value.
/// </summary>
/// <param name="left">The scalar factor.</param>
/// <param name="right">The source vector.</param>
/// <returns>The scaled vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Multiply<T>(T left, Vector<T> right) where T : struct
{
return left * right;
}
/// <summary>
/// Returns a new vector whose values are the result of dividing the first vector's elements
/// by the corresponding elements in the second vector.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The divided vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Divide<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left / right;
}
/// <summary>
/// Returns a new vector whose elements are the given vector's elements negated.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The negated vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Negate<T>(Vector<T> value) where T : struct
{
return -value;
}
#endregion Named Arithmetic Operators
#region Named Bitwise Operators
/// <summary>
/// Returns a new vector by performing a bitwise-and operation on each of the elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> BitwiseAnd<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left & right;
}
/// <summary>
/// Returns a new vector by performing a bitwise-or operation on each of the elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> BitwiseOr<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left | right;
}
/// <summary>
/// Returns a new vector whose elements are obtained by taking the one's complement of the given vector's elements.
/// </summary>
/// <param name="value">The source vector.</param>
/// <returns>The one's complement vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> OnesComplement<T>(Vector<T> value) where T : struct
{
return ~value;
}
/// <summary>
/// Returns a new vector by performing a bitwise-exclusive-or operation on each of the elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> Xor<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left ^ right;
}
/// <summary>
/// Returns a new vector by performing a bitwise-and-not operation on each of the elements in the given vectors.
/// </summary>
/// <param name="left">The first source vector.</param>
/// <param name="right">The second source vector.</param>
/// <returns>The resultant vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<T> AndNot<T>(Vector<T> left, Vector<T> right) where T : struct
{
return left & ~right;
}
#endregion Named Bitwise Operators
#region Conversion Methods
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of unsigned bytes.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Byte> AsVectorByte<T>(Vector<T> value) where T : struct
{
return (Vector<Byte>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of signed bytes.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<SByte> AsVectorSByte<T>(Vector<T> value) where T : struct
{
return (Vector<SByte>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of 16-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<UInt16> AsVectorUInt16<T>(Vector<T> value) where T : struct
{
return (Vector<UInt16>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of signed 16-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Int16> AsVectorInt16<T>(Vector<T> value) where T : struct
{
return (Vector<Int16>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of unsigned 32-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<UInt32> AsVectorUInt32<T>(Vector<T> value) where T : struct
{
return (Vector<UInt32>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of signed 32-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Int32> AsVectorInt32<T>(Vector<T> value) where T : struct
{
return (Vector<Int32>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of unsigned 64-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<UInt64> AsVectorUInt64<T>(Vector<T> value) where T : struct
{
return (Vector<UInt64>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of signed 64-bit integers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Int64> AsVectorInt64<T>(Vector<T> value) where T : struct
{
return (Vector<Int64>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of 32-bit floating point numbers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Single> AsVectorSingle<T>(Vector<T> value) where T : struct
{
return (Vector<Single>)value;
}
/// <summary>
/// Reinterprets the bits of the given vector into those of a vector of 64-bit floating point numbers.
/// </summary>
/// <param name="value">The source vector</param>
/// <returns>The reinterpreted vector.</returns>
[MethodImplAttribute(MethodImplOptions.AggressiveInlining)]
public static Vector<Double> AsVectorDouble<T>(Vector<T> value) where T : struct
{
return (Vector<Double>)value;
}
#endregion Conversion Methods
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Layouts
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using NLog.Common;
using NLog.Conditions;
using NLog.Config;
using NLog.Internal;
using NLog.LayoutRenderers;
using NLog.LayoutRenderers.Wrappers;
/// <summary>
/// Parses layout strings.
/// </summary>
internal sealed class LayoutParser
{
internal static LayoutRenderer[] CompileLayout(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr, bool isNested, out string text)
{
var result = new List<LayoutRenderer>();
var literalBuf = new StringBuilder();
int ch;
int p0 = sr.Position;
while ((ch = sr.Peek()) != -1)
{
if (isNested)
{
//possible escape char `\`
if (ch == '\\')
{
sr.Read();
var nextChar = sr.Peek();
//escape chars
if (nextChar == '}' || nextChar == ':')
{
//read next char and append
sr.Read();
literalBuf.Append((char)nextChar);
}
else
{
//dont treat \ as escape char and just read it
literalBuf.Append('\\');
}
continue;
}
if (ch == '}' || ch == ':')
{
//end of innerlayout.
// `}` is when double nested inner layout.
// `:` when single nested layout
break;
}
}
sr.Read();
//detect `${` (new layout-renderer)
if (ch == '$' && sr.Peek() == '{')
{
//stach already found layout-renderer.
if (literalBuf.Length > 0)
{
result.Add(new LiteralLayoutRenderer(literalBuf.ToString()));
literalBuf.Length = 0;
}
LayoutRenderer newLayoutRenderer = ParseLayoutRenderer(configurationItemFactory, sr);
if (CanBeConvertedToLiteral(newLayoutRenderer))
{
newLayoutRenderer = ConvertToLiteral(newLayoutRenderer);
}
// layout renderer
result.Add(newLayoutRenderer);
}
else
{
literalBuf.Append((char)ch);
}
}
if (literalBuf.Length > 0)
{
result.Add(new LiteralLayoutRenderer(literalBuf.ToString()));
literalBuf.Length = 0;
}
int p1 = sr.Position;
MergeLiterals(result);
text = sr.Substring(p0, p1);
return result.ToArray();
}
private static string ParseLayoutRendererName(SimpleStringReader sr)
{
int ch;
var nameBuf = new StringBuilder();
while ((ch = sr.Peek()) != -1)
{
if (ch == ':' || ch == '}')
{
break;
}
nameBuf.Append((char)ch);
sr.Read();
}
return nameBuf.ToString();
}
private static string ParseParameterName(SimpleStringReader sr)
{
int ch;
int nestLevel = 0;
var nameBuf = new StringBuilder();
while ((ch = sr.Peek()) != -1)
{
if ((ch == '=' || ch == '}' || ch == ':') && nestLevel == 0)
{
break;
}
if (ch == '$')
{
sr.Read();
nameBuf.Append('$');
if (sr.Peek() == '{')
{
nameBuf.Append('{');
nestLevel++;
sr.Read();
}
continue;
}
if (ch == '}')
{
nestLevel--;
}
if (ch == '\\')
{
// skip the backslash
sr.Read();
// append next character
nameBuf.Append((char)sr.Read());
continue;
}
nameBuf.Append((char)ch);
sr.Read();
}
return nameBuf.ToString();
}
private static string ParseParameterValue(SimpleStringReader sr)
{
int ch;
var nameBuf = new StringBuilder();
while ((ch = sr.Peek()) != -1)
{
if (ch == ':' || ch == '}')
{
break;
}
// Code in this condition was replaced
// to support escape codes e.g. '\r' '\n' '\u003a',
// which can not be used directly as they are used as tokens by the parser
// All escape codes listed in the following link were included
// in addition to "\{", "\}", "\:" which are NLog specific:
// http://blogs.msdn.com/b/csharpfaq/archive/2004/03/12/what-character-escape-sequences-are-available.aspx
if (ch == '\\')
{
// skip the backslash
sr.Read();
var nextChar = (char)sr.Peek();
switch (nextChar)
{
case ':':
sr.Read();
nameBuf.Append(':');
break;
case '{':
sr.Read();
nameBuf.Append('{');
break;
case '}':
sr.Read();
nameBuf.Append('}');
break;
case '\'':
sr.Read();
nameBuf.Append('\'');
break;
case '"':
sr.Read();
nameBuf.Append('"');
break;
case '\\':
sr.Read();
nameBuf.Append('\\');
break;
case '0':
sr.Read();
nameBuf.Append('\0');
break;
case 'a':
sr.Read();
nameBuf.Append('\a');
break;
case 'b':
sr.Read();
nameBuf.Append('\b');
break;
case 'f':
sr.Read();
nameBuf.Append('\f');
break;
case 'n':
sr.Read();
nameBuf.Append('\n');
break;
case 'r':
sr.Read();
nameBuf.Append('\r');
break;
case 't':
sr.Read();
nameBuf.Append('\t');
break;
case 'u':
sr.Read();
var uChar = GetUnicode(sr, 4); // 4 digits
nameBuf.Append(uChar);
break;
case 'U':
sr.Read();
var UChar = GetUnicode(sr, 8); // 8 digits
nameBuf.Append(UChar);
break;
case 'x':
sr.Read();
var xChar = GetUnicode(sr, 4); // 1-4 digits
nameBuf.Append(xChar);
break;
case 'v':
sr.Read();
nameBuf.Append('\v');
break;
}
continue;
}
nameBuf.Append((char)ch);
sr.Read();
}
return nameBuf.ToString();
}
private static char GetUnicode(SimpleStringReader sr, int maxDigits)
{
int code = 0;
for (int cnt = 0; cnt < maxDigits; cnt++)
{
var digitCode = sr.Peek();
if (digitCode >= (int)'0' && digitCode <= (int)'9')
digitCode = digitCode - (int)'0';
else if (digitCode >= (int)'a' && digitCode <= (int)'f')
digitCode = digitCode - (int)'a' + 10;
else if (digitCode >= (int)'A' && digitCode <= (int)'F')
digitCode = digitCode - (int)'A' + 10;
else
break;
sr.Read();
code = code * 16 + digitCode;
}
return (char)code;
}
private static LayoutRenderer ParseLayoutRenderer(ConfigurationItemFactory configurationItemFactory, SimpleStringReader sr)
{
int ch = sr.Read();
Debug.Assert(ch == '{', "'{' expected in layout specification");
string name = ParseLayoutRendererName(sr);
LayoutRenderer lr = configurationItemFactory.LayoutRenderers.CreateInstance(name);
var wrappers = new Dictionary<Type, LayoutRenderer>();
var orderedWrappers = new List<LayoutRenderer>();
ch = sr.Read();
while (ch != -1 && ch != '}')
{
string parameterName = ParseParameterName(sr).Trim();
if (sr.Peek() == '=')
{
sr.Read(); // skip the '='
PropertyInfo pi;
LayoutRenderer parameterTarget = lr;
if (!PropertyHelper.TryGetPropertyInfo(lr, parameterName, out pi))
{
Type wrapperType;
if (configurationItemFactory.AmbientProperties.TryGetDefinition(parameterName, out wrapperType))
{
LayoutRenderer wrapperRenderer;
if (!wrappers.TryGetValue(wrapperType, out wrapperRenderer))
{
wrapperRenderer = configurationItemFactory.AmbientProperties.CreateInstance(parameterName);
wrappers[wrapperType] = wrapperRenderer;
orderedWrappers.Add(wrapperRenderer);
}
if (!PropertyHelper.TryGetPropertyInfo(wrapperRenderer, parameterName, out pi))
{
pi = null;
}
else
{
parameterTarget = wrapperRenderer;
}
}
}
if (pi == null)
{
ParseParameterValue(sr);
}
else
{
if (typeof(Layout).IsAssignableFrom(pi.PropertyType))
{
var nestedLayout = new SimpleLayout();
string txt;
LayoutRenderer[] renderers = CompileLayout(configurationItemFactory, sr, true, out txt);
nestedLayout.SetRenderers(renderers, txt);
pi.SetValue(parameterTarget, nestedLayout, null);
}
else if (typeof(ConditionExpression).IsAssignableFrom(pi.PropertyType))
{
var conditionExpression = ConditionParser.ParseExpression(sr, configurationItemFactory);
pi.SetValue(parameterTarget, conditionExpression, null);
}
else
{
string value = ParseParameterValue(sr);
PropertyHelper.SetPropertyFromString(parameterTarget, parameterName, value, configurationItemFactory);
}
}
}
else
{
// what we've just read is not a parameterName, but a value
// assign it to a default property (denoted by empty string)
PropertyInfo pi;
if (PropertyHelper.TryGetPropertyInfo(lr, string.Empty, out pi))
{
if (typeof(SimpleLayout) == pi.PropertyType)
{
pi.SetValue(lr, new SimpleLayout(parameterName), null);
}
else
{
string value = parameterName;
PropertyHelper.SetPropertyFromString(lr, pi.Name, value, configurationItemFactory);
}
}
else
{
InternalLogger.Warn("{0} has no default property", lr.GetType().FullName);
}
}
ch = sr.Read();
}
lr = ApplyWrappers(configurationItemFactory, lr, orderedWrappers);
return lr;
}
private static LayoutRenderer ApplyWrappers(ConfigurationItemFactory configurationItemFactory, LayoutRenderer lr, List<LayoutRenderer> orderedWrappers)
{
for (int i = orderedWrappers.Count - 1; i >= 0; --i)
{
var newRenderer = (WrapperLayoutRendererBase)orderedWrappers[i];
InternalLogger.Trace("Wrapping {0} with {1}", lr.GetType().Name, newRenderer.GetType().Name);
if (CanBeConvertedToLiteral(lr))
{
lr = ConvertToLiteral(lr);
}
newRenderer.Inner = new SimpleLayout(new[] { lr }, string.Empty, configurationItemFactory);
lr = newRenderer;
}
return lr;
}
private static bool CanBeConvertedToLiteral(LayoutRenderer lr)
{
foreach (IRenderable renderable in ObjectGraphScanner.FindReachableObjects<IRenderable>(lr))
{
if (renderable.GetType() == typeof(SimpleLayout))
{
continue;
}
if (!renderable.GetType().IsDefined(typeof(AppDomainFixedOutputAttribute), false))
{
return false;
}
}
return true;
}
private static void MergeLiterals(List<LayoutRenderer> list)
{
for (int i = 0; i + 1 < list.Count; )
{
var lr1 = list[i] as LiteralLayoutRenderer;
var lr2 = list[i + 1] as LiteralLayoutRenderer;
if (lr1 != null && lr2 != null)
{
lr1.Text += lr2.Text;
list.RemoveAt(i + 1);
}
else
{
i++;
}
}
}
private static LayoutRenderer ConvertToLiteral(LayoutRenderer renderer)
{
return new LiteralLayoutRenderer(renderer.Render(LogEventInfo.CreateNullEvent()));
}
}
}
| |
using System.Text;
using NUnit.Framework;
using Sodium;
using Sodium.Exceptions;
namespace Tests
{
/// <summary>Exception tests for the PublicKeyBox class</summary>
[TestFixture]
public class PublicKeyBoxExceptionTest
{
[Test]
public void GenerateKeyPairFromPrivateBadKeyTest()
{
//Don`t copy bobSk for other tests (bad key)!
//30 byte
var bobSk = new byte[] {
0x5d,0xab,0x08,0x7e,0x62,0x4a,0x8a,0x4b,
0x79,0xe1,0x7f,0x8b,0x83,0x80,0x0e,0xe6,
0x6f,0x3b,0xb1,0x29,0x26,0x18,0xb6,0xfd,
0x1c,0x2f,0x8b,0x27,0xff,0x88
};
Assert.Throws<SeedOutOfRangeException>(
() => PublicKeyBox.GenerateKeyPair(bobSk));
}
[Test]
public void PublicKeyBoxCreateWithBadPrivateKey()
{
var bobSk = new byte[] {
0x5d,0xab,0x08,0x7e,0x62,0x4a,0x8a,0x4b,
0x79,0xe1,0x7f,0x8b,0x83,0x80,0x0e,0xe6,
0x6f,0x3b,0xb1,0x29,0x26,0x18,0xb6,0xfd,
0x1c,0x2f,0x8b,0x27,0xff,0x88
};
var message = Encoding.UTF8.GetBytes("Adam Caudill");
var nonce = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX");
var alicePk = Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645");
Assert.Throws<KeyOutOfRangeException>(
() => PublicKeyBox.Create(message, nonce, bobSk, alicePk));
}
[Test]
public void PublicKeyBoxCreateWithBadPublicKey()
{
var bobPk = new byte[] {
0x5d,0xab,0x08,0x7e,0x62,0x4a,0x8a,0x4b,
0x79,0xe1,0x7f,0x8b,0x83,0x80,0x0e,0xe6,
0x6f,0x3b,0xb1,0x29,0x26,0x18,0xb6,0xfd,
0x1c,0x2f,0x8b,0x27,0xff,0x88
};
var message = Encoding.UTF8.GetBytes("Adam Caudill");
var nonce = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX");
var aliceSk = Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975");
Assert.Throws<KeyOutOfRangeException>(
() => PublicKeyBox.Create(message, nonce, aliceSk, bobPk));
}
[Test]
public void PublicKeyBoxCreateWithBadNonce()
{
var message = Encoding.UTF8.GetBytes("Adam Caudill");
var nonce = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVX");
var bobSk = Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975");
var alicePk = Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645");
Assert.Throws<NonceOutOfRangeException>(
() => PublicKeyBox.Create(message, nonce, bobSk, alicePk));
}
[Test]
public void PublicKeyBoxCreateDetachedWithBadPrivateKey()
{
var bobSk = new byte[] {
0x5d,0xab,0x08,0x7e,0x62,0x4a,0x8a,0x4b,
0x79,0xe1,0x7f,0x8b,0x83,0x80,0x0e,0xe6,
0x6f,0x3b,0xb1,0x29,0x26,0x18,0xb6,0xfd,
0x1c,0x2f,0x8b,0x27,0xff,0x88
};
var message = Encoding.UTF8.GetBytes("Adam Caudill");
var nonce = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX");
var alicePk = Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645");
Assert.Throws<KeyOutOfRangeException>(
() => PublicKeyBox.CreateDetached(message, nonce, bobSk, alicePk));
}
[Test]
public void PublicKeyBoxCreateDetachedWithBadPublicKey()
{
var bobPk = new byte[] {
0x5d,0xab,0x08,0x7e,0x62,0x4a,0x8a,0x4b,
0x79,0xe1,0x7f,0x8b,0x83,0x80,0x0e,0xe6,
0x6f,0x3b,0xb1,0x29,0x26,0x18,0xb6,0xfd,
0x1c,0x2f,0x8b,0x27,0xff,0x88
};
var message = Encoding.UTF8.GetBytes("Adam Caudill");
var nonce = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX");
var aliceSk = Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975");
Assert.Throws<KeyOutOfRangeException>(
() => PublicKeyBox.CreateDetached(message, nonce, aliceSk, bobPk));
}
[Test]
public void PublicKeyBoxCreateDetachedWithBadNonce()
{
Assert.Throws<NonceOutOfRangeException>(() =>
{
PublicKeyBox.CreateDetached(
Encoding.UTF8.GetBytes("Adam Caudill"),
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVX"),
Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
});
}
[Test]
public void PublicKeyBoxOpenBadPrivateKey()
{
var bobPk = new byte[] {
0x5d,0xab,0x08,0x7e,0x62,0x4a,0x8a,0x4b,
0x79,0xe1,0x7f,0x8b,0x83,0x80,0x0e,0xe6,
0x6f,0x3b,0xb1,0x29,0x26,0x18,0xb6,0xfd,
0x1c,0x2f,0x8b,0x27,0xff,0x88
};
Assert.Throws<KeyOutOfRangeException>(() =>
{
PublicKeyBox.Open(
Utilities.HexToBinary("aed04284c55860ad0f6379f235cc2cb8c32aba7a811b35cfac94f64d"),
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
bobPk,
Utilities.HexToBinary("753cb95919b15b76654b1969c554a4aaf8334402ef1468cb40a602b9c9fd2c13"));
});
}
[Test]
public void PublicKeyBoxOpenBadPublicKey()
{
var bobPk = new byte[] {
0x5d,0xab,0x08,0x7e,0x62,0x4a,0x8a,0x4b,
0x79,0xe1,0x7f,0x8b,0x83,0x80,0x0e,0xe6,
0x6f,0x3b,0xb1,0x29,0x26,0x18,0xb6,0xfd,
0x1c,0x2f,0x8b,0x27,0xff,0x88
};
Assert.Throws<KeyOutOfRangeException>(() =>
{
PublicKeyBox.Open(
Utilities.HexToBinary("aed04284c55860ad0f6379f235cc2cb8c32aba7a811b35cfac94f64d"),
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
Utilities.HexToBinary("d4c8438482d5d103a2315251a5eed7c46017864a02ddc4c8b03f0ede8cb3ef9b"), bobPk);
});
}
[Test]
public void PublicKeyBoxOpenBadNonce()
{
Assert.Throws<NonceOutOfRangeException>(() =>
{
PublicKeyBox.Open(
Utilities.HexToBinary("aed04284c55860ad0f6379f235cc2cb8c32aba7a811b35cfac94f64d"),
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVW"),
Utilities.HexToBinary("d4c8438482d5d103a2315251a5eed7c46017864a02ddc4c8b03f0ede8cb3ef9b"),
Utilities.HexToBinary("753cb95919b15b76654b1969c554a4aaf8334402ef1468cb40a602b9c9fd2c13"));
});
}
[Test]
public void PublicKeyBoxOpenDetachedBadPrivateKey()
{
var actual = PublicKeyBox.CreateDetached(
Encoding.UTF8.GetBytes("Adam Caudill"),
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
Assert.Throws<KeyOutOfRangeException>(() =>
{
PublicKeyBox.OpenDetached(actual.CipherText, actual.Mac,
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a159"),
Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
});
}
[Test]
public void PublicKeyBoxOpenDetachedBadPublicKey()
{
var actual = PublicKeyBox.CreateDetached(
Encoding.UTF8.GetBytes("Adam Caudill"),
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
Assert.Throws<KeyOutOfRangeException>(() =>
{
PublicKeyBox.OpenDetached(actual.CipherText, actual.Mac,
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec856"));
});
}
[Test]
public void PublicKeyBoxOpenDetachedBadNonce()
{
var actual = PublicKeyBox.CreateDetached(
Encoding.UTF8.GetBytes("Adam Caudill"),
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
Assert.Throws<NonceOutOfRangeException>(() =>
{
PublicKeyBox.OpenDetached(actual.CipherText, actual.Mac,
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVW"),
Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
});
}
[Test]
public void PublicKeyBoxOpenDetachedBadMac()
{
var actual = PublicKeyBox.CreateDetached(
Encoding.UTF8.GetBytes("Adam Caudill"),
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
Assert.Throws<MacOutOfRangeException>(() =>
{
PublicKeyBox.OpenDetached(actual.CipherText, null,
Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWX"),
Utilities.HexToBinary("2a5c92fac62514f793c0bfd374f629a138c5702793a32c61dadc593728a15975"),
Utilities.HexToBinary("83638e30326e2f55509286ac86afeb5bfd0732a3d11747bd50eb96bb9ec85645"));
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using SubSonic.DataProviders;
using SubSonic.Extensions;
using System.Linq.Expressions;
using SubSonic.Schema;
using SubSonic.Repository;
using System.Data.Common;
using SubSonic.SqlGeneration.Schema;
namespace Solution.DataAccess.DataModel
{
/// <summary>
/// A class which represents the WeekRest table in the HKHR Database.
/// </summary>
public partial class WeekRest: IActiveRecord
{
#region Built-in testing
static TestRepository<WeekRest> _testRepo;
static void SetTestRepo(){
_testRepo = _testRepo ?? new TestRepository<WeekRest>(new Solution.DataAccess.DataModel.HKHRDB());
}
public static void ResetTestRepo(){
_testRepo = null;
SetTestRepo();
}
public static void Setup(List<WeekRest> testlist){
SetTestRepo();
foreach (var item in testlist)
{
_testRepo._items.Add(item);
}
}
public static void Setup(WeekRest item) {
SetTestRepo();
_testRepo._items.Add(item);
}
public static void Setup(int testItems) {
SetTestRepo();
for(int i=0;i<testItems;i++){
WeekRest item=new WeekRest();
_testRepo._items.Add(item);
}
}
public bool TestMode = false;
#endregion
IRepository<WeekRest> _repo;
ITable tbl;
bool _isNew;
public bool IsNew(){
return _isNew;
}
public void SetIsLoaded(bool isLoaded){
_isLoaded=isLoaded;
if(isLoaded)
OnLoaded();
}
public void SetIsNew(bool isNew){
_isNew=isNew;
}
bool _isLoaded;
public bool IsLoaded(){
return _isLoaded;
}
List<IColumn> _dirtyColumns;
public bool IsDirty(){
return _dirtyColumns.Count>0;
}
public List<IColumn> GetDirtyColumns (){
return _dirtyColumns;
}
Solution.DataAccess.DataModel.HKHRDB _db;
public WeekRest(string connectionString, string providerName) {
_db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName);
Init();
}
void Init(){
TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase);
_dirtyColumns=new List<IColumn>();
if(TestMode){
WeekRest.SetTestRepo();
_repo=_testRepo;
}else{
_repo = new SubSonicRepository<WeekRest>(_db);
}
tbl=_repo.GetTable();
SetIsNew(true);
OnCreated();
}
public WeekRest(){
_db=new Solution.DataAccess.DataModel.HKHRDB();
Init();
}
public void ORMapping(IDataRecord dataRecord)
{
IReadRecord readRecord = SqlReadRecord.GetIReadRecord();
readRecord.DataRecord = dataRecord;
Id = readRecord.get_int("Id",null);
wr_code = readRecord.get_string("wr_code",null);
wr_name = readRecord.get_string("wr_name",null);
wr_date = readRecord.get_datetime("wr_date",null);
wr_end = readRecord.get_datetime("wr_end",null);
begin_time = readRecord.get_datetime("begin_time",null);
end_time = readRecord.get_datetime("end_time",null);
wr_rate = readRecord.get_decimal("wr_rate",null);
wr_kind = readRecord.get_int("wr_kind",null);
alway_use = readRecord.get_short("alway_use",null);
have_hrs = readRecord.get_short("have_hrs",null);
}
partial void OnCreated();
partial void OnLoaded();
partial void OnSaved();
partial void OnChanged();
public IList<IColumn> Columns{
get{
return tbl.Columns;
}
}
public WeekRest(Expression<Func<WeekRest, bool>> expression):this() {
SetIsLoaded(_repo.Load(this,expression));
}
internal static IRepository<WeekRest> GetRepo(string connectionString, string providerName){
Solution.DataAccess.DataModel.HKHRDB db;
if(String.IsNullOrEmpty(connectionString)){
db=new Solution.DataAccess.DataModel.HKHRDB();
}else{
db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName);
}
IRepository<WeekRest> _repo;
if(db.TestMode){
WeekRest.SetTestRepo();
_repo=_testRepo;
}else{
_repo = new SubSonicRepository<WeekRest>(db);
}
return _repo;
}
internal static IRepository<WeekRest> GetRepo(){
return GetRepo("","");
}
public static WeekRest SingleOrDefault(Expression<Func<WeekRest, bool>> expression) {
var repo = GetRepo();
var results=repo.Find(expression);
WeekRest single=null;
if(results.Count() > 0){
single=results.ToList()[0];
single.OnLoaded();
single.SetIsLoaded(true);
single.SetIsNew(false);
}
return single;
}
public static WeekRest SingleOrDefault(Expression<Func<WeekRest, bool>> expression,string connectionString, string providerName) {
var repo = GetRepo(connectionString,providerName);
var results=repo.Find(expression);
WeekRest single=null;
if(results.Count() > 0){
single=results.ToList()[0];
}
return single;
}
public static bool Exists(Expression<Func<WeekRest, bool>> expression,string connectionString, string providerName) {
return All(connectionString,providerName).Any(expression);
}
public static bool Exists(Expression<Func<WeekRest, bool>> expression) {
return All().Any(expression);
}
public static IList<WeekRest> Find(Expression<Func<WeekRest, bool>> expression) {
var repo = GetRepo();
return repo.Find(expression).ToList();
}
public static IList<WeekRest> Find(Expression<Func<WeekRest, bool>> expression,string connectionString, string providerName) {
var repo = GetRepo(connectionString,providerName);
return repo.Find(expression).ToList();
}
public static IQueryable<WeekRest> All(string connectionString, string providerName) {
return GetRepo(connectionString,providerName).GetAll();
}
public static IQueryable<WeekRest> All() {
return GetRepo().GetAll();
}
public static PagedList<WeekRest> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) {
return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize);
}
public static PagedList<WeekRest> GetPaged(string sortBy, int pageIndex, int pageSize) {
return GetRepo().GetPaged(sortBy, pageIndex, pageSize);
}
public static PagedList<WeekRest> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) {
return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize);
}
public static PagedList<WeekRest> GetPaged(int pageIndex, int pageSize) {
return GetRepo().GetPaged(pageIndex, pageSize);
}
public string KeyName()
{
return "Id";
}
public object KeyValue()
{
return this.Id;
}
public void SetKeyValue(object value) {
if (value != null && value!=DBNull.Value) {
var settable = value.ChangeTypeTo<int>();
this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null);
}
}
public override string ToString(){
var sb = new StringBuilder();
sb.Append("Id=" + Id + "; ");
sb.Append("wr_code=" + wr_code + "; ");
sb.Append("wr_name=" + wr_name + "; ");
sb.Append("wr_date=" + wr_date + "; ");
sb.Append("wr_end=" + wr_end + "; ");
sb.Append("begin_time=" + begin_time + "; ");
sb.Append("end_time=" + end_time + "; ");
sb.Append("wr_rate=" + wr_rate + "; ");
sb.Append("wr_kind=" + wr_kind + "; ");
sb.Append("alway_use=" + alway_use + "; ");
sb.Append("have_hrs=" + have_hrs + "; ");
return sb.ToString();
}
public override bool Equals(object obj){
if(obj.GetType()==typeof(WeekRest)){
WeekRest compare=(WeekRest)obj;
return compare.KeyValue()==this.KeyValue();
}else{
return base.Equals(obj);
}
}
public override int GetHashCode() {
return this.Id;
}
public string DescriptorValue()
{
return this.wr_code.ToString();
}
public string DescriptorColumn() {
return "wr_code";
}
public static string GetKeyColumn()
{
return "Id";
}
public static string GetDescriptorColumn()
{
return "wr_code";
}
#region ' Foreign Keys '
#endregion
int _Id;
/// <summary>
///
/// </summary>
[SubSonicPrimaryKey]
public int Id
{
get { return _Id; }
set
{
if(_Id!=value || _isLoaded){
_Id=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
string _wr_code;
/// <summary>
///
/// </summary>
public string wr_code
{
get { return _wr_code; }
set
{
if(_wr_code!=value || _isLoaded){
_wr_code=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="wr_code");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
string _wr_name;
/// <summary>
///
/// </summary>
public string wr_name
{
get { return _wr_name; }
set
{
if(_wr_name!=value || _isLoaded){
_wr_name=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="wr_name");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
DateTime _wr_date;
/// <summary>
///
/// </summary>
public DateTime wr_date
{
get { return _wr_date; }
set
{
if(_wr_date!=value || _isLoaded){
_wr_date=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="wr_date");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
DateTime? _wr_end;
/// <summary>
///
/// </summary>
public DateTime? wr_end
{
get { return _wr_end; }
set
{
if(_wr_end!=value || _isLoaded){
_wr_end=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="wr_end");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
DateTime? _begin_time;
/// <summary>
///
/// </summary>
public DateTime? begin_time
{
get { return _begin_time; }
set
{
if(_begin_time!=value || _isLoaded){
_begin_time=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="begin_time");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
DateTime? _end_time;
/// <summary>
///
/// </summary>
public DateTime? end_time
{
get { return _end_time; }
set
{
if(_end_time!=value || _isLoaded){
_end_time=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="end_time");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
decimal? _wr_rate;
/// <summary>
///
/// </summary>
public decimal? wr_rate
{
get { return _wr_rate; }
set
{
if(_wr_rate!=value || _isLoaded){
_wr_rate=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="wr_rate");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
int? _wr_kind;
/// <summary>
///
/// </summary>
public int? wr_kind
{
get { return _wr_kind; }
set
{
if(_wr_kind!=value || _isLoaded){
_wr_kind=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="wr_kind");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
short? _alway_use;
/// <summary>
///
/// </summary>
public short? alway_use
{
get { return _alway_use; }
set
{
if(_alway_use!=value || _isLoaded){
_alway_use=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="alway_use");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
short? _have_hrs;
/// <summary>
///
/// </summary>
public short? have_hrs
{
get { return _have_hrs; }
set
{
if(_have_hrs!=value || _isLoaded){
_have_hrs=value;
var col=tbl.Columns.SingleOrDefault(x=>x.Name=="have_hrs");
if(col!=null){
if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){
_dirtyColumns.Add(col);
}
}
OnChanged();
}
}
}
public DbCommand GetUpdateCommand() {
if(TestMode)
return _db.DataProvider.CreateCommand();
else
return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand();
}
public DbCommand GetInsertCommand() {
if(TestMode)
return _db.DataProvider.CreateCommand();
else
return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand();
}
public DbCommand GetDeleteCommand() {
if(TestMode)
return _db.DataProvider.CreateCommand();
else
return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand();
}
public void Update(){
Update(_db.DataProvider);
}
public void Update(IDataProvider provider){
if(this._dirtyColumns.Count>0){
_repo.Update(this,provider);
_dirtyColumns.Clear();
}
OnSaved();
}
public void Add(){
Add(_db.DataProvider);
}
public void Add(IDataProvider provider){
var key=KeyValue();
if(key==null){
var newKey=_repo.Add(this,provider);
this.SetKeyValue(newKey);
}else{
_repo.Add(this,provider);
}
SetIsNew(false);
OnSaved();
}
public void Save() {
Save(_db.DataProvider);
}
public void Save(IDataProvider provider) {
if (_isNew) {
Add(provider);
} else {
Update(provider);
}
}
public void Delete(IDataProvider provider) {
_repo.Delete(KeyValue());
}
public void Delete() {
Delete(_db.DataProvider);
}
public static void Delete(Expression<Func<WeekRest, bool>> expression) {
var repo = GetRepo();
repo.DeleteMany(expression);
}
public void Load(IDataReader rdr) {
Load(rdr, true);
}
public void Load(IDataReader rdr, bool closeReader) {
if (rdr.Read()) {
try {
rdr.Load(this);
SetIsNew(false);
SetIsLoaded(true);
} catch {
SetIsLoaded(false);
throw;
}
}else{
SetIsLoaded(false);
}
if (closeReader)
rdr.Dispose();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*=============================================================================
**
**
** Purpose: An array implementation of a generic stack.
**
**
=============================================================================*/
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace System.Collections.Generic
{
// A simple stack of objects. Internally it is implemented as an array,
// so Push can be O(n). Pop is O(1).
[DebuggerTypeProxy(typeof(StackDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public class Stack<T> : IEnumerable<T>,
System.Collections.ICollection,
IReadOnlyCollection<T>
{
private T[] _array; // Storage for stack elements
private int _size; // Number of items in the stack.
private int _version; // Used to keep enumerator in sync w/ collection.
private object _syncRoot;
private const int DefaultCapacity = 4;
public Stack()
{
_array = Array.Empty<T>();
}
// Create a stack with a specific initial capacity. The initial capacity
// must be a non-negative number.
public Stack(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum);
_array = new T[capacity];
}
// Fills a Stack with the contents of a particular collection. The items are
// pushed onto the stack in the same order they are read by the enumerator.
public Stack(IEnumerable<T> collection)
{
if (collection == null)
throw new ArgumentNullException(nameof(collection));
_array = EnumerableHelpers.ToArray(collection, out _size);
}
public int Count
{
get { return _size; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
// Removes all Objects from the Stack.
public void Clear()
{
Array.Clear(_array, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
_size = 0;
_version++;
}
public bool Contains(T item)
{
int count = _size;
EqualityComparer<T> c = EqualityComparer<T>.Default;
while (count-- > 0)
{
if (c.Equals(_array[count], item))
{
return true;
}
}
return false;
}
// Copies the stack into an array.
public void CopyTo(T[] array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
Debug.Assert(array != _array);
int srcIndex = 0;
int dstIndex = arrayIndex + _size;
for (int i = 0; i < _size; i++)
array[--dstIndex] = _array[srcIndex++];
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (arrayIndex < 0 || arrayIndex > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index);
}
if (array.Length - arrayIndex < _size)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
try
{
Array.Copy(_array, 0, array, arrayIndex, _size);
Array.Reverse(array, arrayIndex, _size);
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
// Returns an IEnumerator for this Stack.
public Enumerator GetEnumerator()
{
return new Enumerator(this);
}
/// <internalonly/>
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this);
}
public void TrimExcess()
{
int threshold = (int)(((double)_array.Length) * 0.9);
if (_size < threshold)
{
Array.Resize(ref _array, _size);
_version++;
}
}
// Returns the top object on the stack without removing it. If the stack
// is empty, Peek throws an InvalidOperationException.
public T Peek()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
return _array[_size - 1];
}
// Pops an item from the top of the stack. If the stack is empty, Pop
// throws an InvalidOperationException.
public T Pop()
{
if (_size == 0)
throw new InvalidOperationException(SR.InvalidOperation_EmptyStack);
_version++;
T item = _array[--_size];
_array[_size] = default(T); // Free memory quicker.
return item;
}
// Pushes an item to the top of the stack.
public void Push(T item)
{
if (_size == _array.Length)
{
Array.Resize(ref _array, (_array.Length == 0) ? DefaultCapacity : 2 * _array.Length);
}
_array[_size++] = item;
_version++;
}
// Copies the Stack to an array, in the same order Pop would return the items.
public T[] ToArray()
{
if (_size == 0)
return Array.Empty<T>();
T[] objArray = new T[_size];
int i = 0;
while (i < _size)
{
objArray[i] = _array[_size - i - 1];
i++;
}
return objArray;
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<T>,
System.Collections.IEnumerator
{
private readonly Stack<T> _stack;
private readonly int _version;
private int _index;
private T _currentElement;
internal Enumerator(Stack<T> stack)
{
_stack = stack;
_version = stack._version;
_index = -2;
_currentElement = default(T);
}
public void Dispose()
{
_index = -1;
}
public bool MoveNext()
{
bool retval;
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (_index == -2)
{ // First call to enumerator.
_index = _stack._size - 1;
retval = (_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
return retval;
}
if (_index == -1)
{ // End of enumeration.
return false;
}
retval = (--_index >= 0);
if (retval)
_currentElement = _stack._array[_index];
else
_currentElement = default(T);
return retval;
}
public T Current
{
get
{
if (_index < 0)
ThrowEnumerationNotStartedOrEnded();
return _currentElement;
}
}
private void ThrowEnumerationNotStartedOrEnded()
{
Debug.Assert(_index == -1 || _index == -2);
throw new InvalidOperationException(_index == -2 ? SR.InvalidOperation_EnumNotStarted : SR.InvalidOperation_EnumEnded);
}
object System.Collections.IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
if (_version != _stack._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
_index = -2;
_currentElement = default(T);
}
}
}
}
| |
// <copyright file="HostingMeterExtensionTests.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OpenTelemetry.Metrics;
using Xunit;
namespace OpenTelemetry.Extensions.Hosting.Tests
{
public class HostingMeterExtensionTests
{
[Fact]
public async Task AddOpenTelemetryMeterProviderInstrumentationCreationAndDisposal()
{
var testInstrumentation = new TestInstrumentation();
var callbackRun = false;
var builder = new HostBuilder().ConfigureServices(services =>
{
services.AddOpenTelemetryMetrics(builder =>
{
builder.AddInstrumentation(() =>
{
callbackRun = true;
return testInstrumentation;
});
});
});
var host = builder.Build();
Assert.False(callbackRun);
Assert.False(testInstrumentation.Disposed);
await host.StartAsync();
Assert.True(callbackRun);
Assert.False(testInstrumentation.Disposed);
await host.StopAsync();
Assert.True(callbackRun);
Assert.False(testInstrumentation.Disposed);
host.Dispose();
Assert.True(callbackRun);
Assert.True(testInstrumentation.Disposed);
}
[Fact]
public void AddOpenTelemetryMeterProvider_HostBuilt_OpenTelemetrySdk_RegisteredAsSingleton()
{
var builder = new HostBuilder().ConfigureServices(services =>
{
services.AddOpenTelemetryMetrics();
});
var host = builder.Build();
var meterProvider1 = host.Services.GetRequiredService<MeterProvider>();
var meterProvider2 = host.Services.GetRequiredService<MeterProvider>();
Assert.Same(meterProvider1, meterProvider2);
}
[Fact]
public void AddOpenTelemetryMeterProvider_ServiceProviderArgument_ServicesRegistered()
{
var testInstrumentation = new TestInstrumentation();
var services = new ServiceCollection();
services.AddSingleton(testInstrumentation);
services.AddOpenTelemetryMetrics(builder =>
{
builder.Configure(
(sp, b) => b.AddInstrumentation(() => sp.GetRequiredService<TestInstrumentation>()));
});
var serviceProvider = services.BuildServiceProvider();
var meterFactory = serviceProvider.GetRequiredService<MeterProvider>();
Assert.NotNull(meterFactory);
Assert.False(testInstrumentation.Disposed);
serviceProvider.Dispose();
Assert.True(testInstrumentation.Disposed);
}
[Fact]
public void AddOpenTelemetryMeterProvider_BadArgs_NullServiceCollection()
{
ServiceCollection services = null;
Assert.Throws<ArgumentNullException>(() => services.AddOpenTelemetryMetrics(null));
Assert.Throws<ArgumentNullException>(() =>
services.AddOpenTelemetryMetrics(builder =>
{
builder.Configure(
(sp, b) => b.AddInstrumentation(() => sp.GetRequiredService<TestInstrumentation>()));
}));
}
[Fact]
public void AddOpenTelemetryMeterProvider_GetServicesExtension()
{
var services = new ServiceCollection();
services.AddOpenTelemetryMetrics(builder => AddMyFeature(builder));
using var serviceProvider = services.BuildServiceProvider();
var meterProvider = (MeterProviderSdk)serviceProvider.GetRequiredService<MeterProvider>();
Assert.True(meterProvider.Reader is TestReader);
}
[Fact]
public void AddOpenTelemetryMeterProvider_NestedConfigureCallbacks()
{
int configureCalls = 0;
var services = new ServiceCollection();
services.AddOpenTelemetryMetrics(builder => builder
.Configure((sp1, builder1) =>
{
configureCalls++;
builder1.Configure((sp2, builder2) =>
{
configureCalls++;
});
}));
using var serviceProvider = services.BuildServiceProvider();
var meterFactory = serviceProvider.GetRequiredService<MeterProvider>();
Assert.Equal(2, configureCalls);
}
[Fact]
public void AddOpenTelemetryMeterProvider_ConfigureCallbacksUsingExtensions()
{
var services = new ServiceCollection();
services.AddSingleton<TestInstrumentation>();
services.AddSingleton<TestReader>();
services.AddOpenTelemetryMetrics(builder => builder
.Configure((sp1, builder1) =>
{
builder1
.AddInstrumentation<TestInstrumentation>()
.AddReader<TestReader>();
}));
using var serviceProvider = services.BuildServiceProvider();
var meterProvider = (MeterProviderSdk)serviceProvider.GetRequiredService<MeterProvider>();
Assert.True(meterProvider.Instrumentations.FirstOrDefault() is TestInstrumentation);
Assert.True(meterProvider.Reader is TestReader);
}
[Fact(Skip = "Known limitation. See issue 1215.")]
public void AddOpenTelemetryMeterProvider_Idempotent()
{
var testInstrumentation1 = new TestInstrumentation();
var testInstrumentation2 = new TestInstrumentation();
var services = new ServiceCollection();
services.AddSingleton(testInstrumentation1);
services.AddOpenTelemetryMetrics(builder =>
{
builder.AddInstrumentation(() => testInstrumentation1);
});
services.AddOpenTelemetryMetrics(builder =>
{
builder.AddInstrumentation(() => testInstrumentation2);
});
var serviceProvider = services.BuildServiceProvider();
var meterFactory = serviceProvider.GetRequiredService<MeterProvider>();
Assert.NotNull(meterFactory);
Assert.False(testInstrumentation1.Disposed);
Assert.False(testInstrumentation2.Disposed);
serviceProvider.Dispose();
Assert.True(testInstrumentation1.Disposed);
Assert.True(testInstrumentation2.Disposed);
}
private static MeterProviderBuilder AddMyFeature(MeterProviderBuilder meterProviderBuilder)
{
(meterProviderBuilder.GetServices() ?? throw new NotSupportedException("MyFeature requires a hosting MeterProviderBuilder instance."))
.AddSingleton<TestReader>();
return meterProviderBuilder.AddReader<TestReader>();
}
internal class TestInstrumentation : IDisposable
{
public bool Disposed { get; private set; }
public void Dispose()
{
this.Disposed = true;
}
}
internal class TestReader : MetricReader
{
}
}
}
| |
//
// X509Store.cs: Handles a X.509 certificates/CRLs store
//
// Author:
// Sebastien Pouliot <sebastien@ximian.com>
// Pablo Ruiz <pruiz@netway.org>
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// (C) 2010 Pablo Ruiz.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using Mono.Security.Cryptography;
using Mono.Security.X509.Extensions;
using SSCX = System.Security.Cryptography.X509Certificates;
namespace Mono.Security.X509 {
#if INSIDE_CORLIB
internal
#else
public
#endif
class X509Store {
private string _storePath;
private X509CertificateCollection _certificates;
private ArrayList _crls;
private bool _crl;
private bool _newFormat;
private string _name;
internal X509Store (string path, bool crl, bool newFormat)
{
_storePath = path;
_crl = crl;
_newFormat = newFormat;
}
// properties
public X509CertificateCollection Certificates {
get {
if (_certificates == null) {
_certificates = BuildCertificatesCollection (_storePath);
}
return _certificates;
}
}
public ArrayList Crls {
get {
// CRL aren't applicable to all stores
// but returning null is a little rude
if (!_crl) {
_crls = new ArrayList ();
}
if (_crls == null) {
_crls = BuildCrlsCollection (_storePath);
}
return _crls;
}
}
public string Name {
get {
if (_name == null) {
int n = _storePath.LastIndexOf (Path.DirectorySeparatorChar);
_name = _storePath.Substring (n+1);
}
return _name;
}
}
// methods
public void Clear ()
{
/*
* Both _certificates and _crls extend CollectionBase, whose Clear() method calls OnClear() and
* OnClearComplete(), which should be overridden in derivative classes. So we should not worry about
* other threads that might be holding references to _certificates or _crls. They should be smart enough
* to handle this gracefully. And if not, it's their own fault.
*/
ClearCertificates ();
ClearCrls ();
}
void ClearCertificates()
{
if (_certificates != null)
_certificates.Clear ();
_certificates = null;
}
void ClearCrls ()
{
if (_crls != null)
_crls.Clear ();
_crls = null;
}
public void Import (X509Certificate certificate)
{
CheckStore (_storePath, true);
if (_newFormat) {
ImportNewFormat (certificate);
return;
}
string filename = Path.Combine (_storePath, GetUniqueName (certificate));
if (!File.Exists (filename)) {
filename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate));
if (!File.Exists (filename)) {
using (FileStream fs = File.Create (filename)) {
byte[] data = certificate.RawData;
fs.Write (data, 0, data.Length);
fs.Close ();
}
ClearCertificates (); // We have modified the store on disk. So forget the old state.
}
} else {
string newfilename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate));
if (GetUniqueNameWithSerial (LoadCertificate (filename)) != GetUniqueNameWithSerial (certificate)) {
using (FileStream fs = File.Create (newfilename)) {
byte[] data = certificate.RawData;
fs.Write (data, 0, data.Length);
fs.Close ();
}
ClearCertificates (); // We have modified the store on disk. So forget the old state.
}
}
#if !MOBILE
// Try to save privateKey if available..
CspParameters cspParams = new CspParameters ();
cspParams.KeyContainerName = CryptoConvert.ToHex (certificate.Hash);
// Right now this seems to be the best way to know if we should use LM store.. ;)
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath) || _storePath.StartsWith(X509StoreManager.NewLocalMachinePath))
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
ImportPrivateKey (certificate, cspParams);
#endif
}
public void Import (X509Crl crl)
{
CheckStore (_storePath, true);
if (_newFormat)
throw new NotSupportedException ();
string filename = Path.Combine (_storePath, GetUniqueName (crl));
if (!File.Exists (filename)) {
using (FileStream fs = File.Create (filename)) {
byte[] data = crl.RawData;
fs.Write (data, 0, data.Length);
}
ClearCrls (); // We have modified the store on disk. So forget the old state.
}
}
public void Remove (X509Certificate certificate)
{
if (_newFormat) {
RemoveNewFormat (certificate);
return;
}
string filename = Path.Combine (_storePath, GetUniqueNameWithSerial (certificate));
if (File.Exists (filename)) {
File.Delete (filename);
ClearCertificates (); // We have modified the store on disk. So forget the old state.
} else {
filename = Path.Combine (_storePath, GetUniqueName (certificate));
if (File.Exists (filename)) {
File.Delete (filename);
ClearCertificates (); // We have modified the store on disk. So forget the old state.
}
}
}
public void Remove (X509Crl crl)
{
if (_newFormat)
throw new NotSupportedException ();
string filename = Path.Combine (_storePath, GetUniqueName (crl));
if (File.Exists (filename)) {
File.Delete (filename);
ClearCrls (); // We have modified the store on disk. So forget the old state.
}
}
// new format
void ImportNewFormat (X509Certificate certificate)
{
#if INSIDE_CORLIB
throw new NotSupportedException ();
#else
using (var sscxCert = new SSCX.X509Certificate (certificate.RawData)) {
var hash = SSCX.X509Helper2.GetSubjectNameHash (sscxCert);
var filename = Path.Combine (_storePath, string.Format ("{0:x8}.0", hash));
if (!File.Exists (filename)) {
using (FileStream fs = File.Create (filename))
SSCX.X509Helper2.ExportAsPEM (sscxCert, fs, true);
ClearCertificates ();
}
}
#endif
}
void RemoveNewFormat (X509Certificate certificate)
{
#if INSIDE_CORLIB
throw new NotSupportedException ();
#else
using (var sscxCert = new SSCX.X509Certificate (certificate.RawData)) {
var hash = SSCX.X509Helper2.GetSubjectNameHash (sscxCert);
var filename = Path.Combine (_storePath, string.Format ("{0:x8}.0", hash));
if (File.Exists (filename)) {
File.Delete (filename);
ClearCertificates ();
}
}
#endif
}
// private stuff
private string GetUniqueNameWithSerial (X509Certificate certificate)
{
return GetUniqueName (certificate, certificate.SerialNumber);
}
private string GetUniqueName (X509Certificate certificate, byte[] serial = null)
{
string method;
byte[] name = GetUniqueName (certificate.Extensions, serial);
if (name == null) {
method = "tbp"; // thumbprint
name = certificate.Hash;
} else {
method = "ski";
}
return GetUniqueName (method, name, ".cer");
}
private string GetUniqueName (X509Crl crl)
{
string method;
byte[] name = GetUniqueName (crl.Extensions);
if (name == null) {
method = "tbp"; // thumbprint
name = crl.Hash;
} else {
method = "ski";
}
return GetUniqueName (method, name, ".crl");
}
private byte[] GetUniqueName (X509ExtensionCollection extensions, byte[] serial = null)
{
// We prefer Subject Key Identifier as the unique name
// as it will provide faster lookups
X509Extension ext = extensions ["2.5.29.14"];
if (ext == null)
return null;
SubjectKeyIdentifierExtension ski = new SubjectKeyIdentifierExtension (ext);
if (serial == null) {
return ski.Identifier;
} else {
byte[] uniqueWithSerial = new byte[ski.Identifier.Length + serial.Length];
System.Buffer.BlockCopy (ski.Identifier, 0, uniqueWithSerial, 0, ski.Identifier.Length );
System.Buffer.BlockCopy (serial, 0, uniqueWithSerial, ski.Identifier.Length, serial.Length );
return uniqueWithSerial;
}
}
private string GetUniqueName (string method, byte[] name, string fileExtension)
{
StringBuilder sb = new StringBuilder (method);
sb.Append ("-");
foreach (byte b in name) {
sb.Append (b.ToString ("X2", CultureInfo.InvariantCulture));
}
sb.Append (fileExtension);
return sb.ToString ();
}
private byte[] Load (string filename)
{
byte[] data = null;
using (FileStream fs = File.OpenRead (filename)) {
data = new byte [fs.Length];
fs.Read (data, 0, data.Length);
fs.Close ();
}
return data;
}
private X509Certificate LoadCertificate (string filename)
{
byte[] data = Load (filename);
X509Certificate cert = new X509Certificate (data);
#if !MOBILE
// If privateKey it's available, load it too..
CspParameters cspParams = new CspParameters ();
cspParams.KeyContainerName = CryptoConvert.ToHex (cert.Hash);
if (_storePath.StartsWith (X509StoreManager.LocalMachinePath) || _storePath.StartsWith(X509StoreManager.NewLocalMachinePath))
cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
KeyPairPersistence kpp = new KeyPairPersistence (cspParams);
try {
if (!kpp.Load ())
return cert;
}
catch {
return cert;
}
if (cert.RSA != null)
cert.RSA = new RSACryptoServiceProvider (cspParams);
else if (cert.DSA != null)
cert.DSA = new DSACryptoServiceProvider (cspParams);
#endif
return cert;
}
private X509Crl LoadCrl (string filename)
{
byte[] data = Load (filename);
X509Crl crl = new X509Crl (data);
return crl;
}
private bool CheckStore (string path, bool throwException)
{
try {
if (Directory.Exists (path))
return true;
Directory.CreateDirectory (path);
return Directory.Exists (path);
}
catch {
if (throwException)
throw;
return false;
}
}
private X509CertificateCollection BuildCertificatesCollection (string storeName)
{
X509CertificateCollection coll = new X509CertificateCollection ();
string path = Path.Combine (_storePath, storeName);
if (!CheckStore (path, false))
return coll; // empty collection
string[] files = Directory.GetFiles (path, _newFormat ? "*.0" : "*.cer");
if ((files != null) && (files.Length > 0)) {
foreach (string file in files) {
try {
X509Certificate cert = LoadCertificate (file);
coll.Add (cert);
}
catch {
// in case someone is dumb enough
// (like me) to include a base64
// encoded certs (or other junk
// into the store).
}
}
}
return coll;
}
private ArrayList BuildCrlsCollection (string storeName)
{
ArrayList list = new ArrayList ();
string path = Path.Combine (_storePath, storeName);
if (!CheckStore (path, false))
return list; // empty list
string[] files = Directory.GetFiles (path, "*.crl");
if ((files != null) && (files.Length > 0)) {
foreach (string file in files) {
try {
X509Crl crl = LoadCrl (file);
list.Add (crl);
}
catch {
// junk catcher
}
}
}
return list;
}
#if !MOBILE
private void ImportPrivateKey (X509Certificate certificate, CspParameters cspParams)
{
RSACryptoServiceProvider rsaCsp = certificate.RSA as RSACryptoServiceProvider;
if (rsaCsp != null) {
if (rsaCsp.PublicOnly)
return;
RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
csp.ImportParameters(rsaCsp.ExportParameters(true));
csp.PersistKeyInCsp = true;
return;
}
RSAManaged rsaMng = certificate.RSA as RSAManaged;
if (rsaMng != null) {
if (rsaMng.PublicOnly)
return;
RSACryptoServiceProvider csp = new RSACryptoServiceProvider(cspParams);
csp.ImportParameters(rsaMng.ExportParameters(true));
csp.PersistKeyInCsp = true;
return;
}
DSACryptoServiceProvider dsaCsp = certificate.DSA as DSACryptoServiceProvider;
if (dsaCsp != null) {
if (dsaCsp.PublicOnly)
return;
DSACryptoServiceProvider csp = new DSACryptoServiceProvider(cspParams);
csp.ImportParameters(dsaCsp.ExportParameters(true));
csp.PersistKeyInCsp = true;
}
}
#endif
}
}
| |
namespace System.IO.BACnet;
public enum BacnetPropertyIds
{
PROP_ACKED_TRANSITIONS = 0,
PROP_ACK_REQUIRED = 1,
PROP_ACTION = 2,
PROP_ACTION_TEXT = 3,
PROP_ACTIVE_TEXT = 4,
PROP_ACTIVE_VT_SESSIONS = 5,
PROP_ALARM_VALUE = 6,
PROP_ALARM_VALUES = 7,
PROP_ALL = 8,
PROP_ALL_WRITES_SUCCESSFUL = 9,
PROP_APDU_SEGMENT_TIMEOUT = 10,
PROP_APDU_TIMEOUT = 11,
PROP_APPLICATION_SOFTWARE_VERSION = 12,
PROP_ARCHIVE = 13,
PROP_BIAS = 14,
PROP_CHANGE_OF_STATE_COUNT = 15,
PROP_CHANGE_OF_STATE_TIME = 16,
PROP_NOTIFICATION_CLASS = 17,
PROP_BLANK_1 = 18,
PROP_CONTROLLED_VARIABLE_REFERENCE = 19,
PROP_CONTROLLED_VARIABLE_UNITS = 20,
PROP_CONTROLLED_VARIABLE_VALUE = 21,
PROP_COV_INCREMENT = 22,
PROP_DATE_LIST = 23,
PROP_DAYLIGHT_SAVINGS_STATUS = 24,
PROP_DEADBAND = 25,
PROP_DERIVATIVE_CONSTANT = 26,
PROP_DERIVATIVE_CONSTANT_UNITS = 27,
PROP_DESCRIPTION = 28,
PROP_DESCRIPTION_OF_HALT = 29,
PROP_DEVICE_ADDRESS_BINDING = 30,
PROP_DEVICE_TYPE = 31,
PROP_EFFECTIVE_PERIOD = 32,
PROP_ELAPSED_ACTIVE_TIME = 33,
PROP_ERROR_LIMIT = 34,
PROP_EVENT_ENABLE = 35,
PROP_EVENT_STATE = 36,
PROP_EVENT_TYPE = 37,
PROP_EXCEPTION_SCHEDULE = 38,
PROP_FAULT_VALUES = 39,
PROP_FEEDBACK_VALUE = 40,
PROP_FILE_ACCESS_METHOD = 41,
PROP_FILE_SIZE = 42,
PROP_FILE_TYPE = 43,
PROP_FIRMWARE_REVISION = 44,
PROP_HIGH_LIMIT = 45,
PROP_INACTIVE_TEXT = 46,
PROP_IN_PROCESS = 47,
PROP_INSTANCE_OF = 48,
PROP_INTEGRAL_CONSTANT = 49,
PROP_INTEGRAL_CONSTANT_UNITS = 50,
PROP_ISSUE_CONFIRMED_NOTIFICATIONS = 51,
PROP_LIMIT_ENABLE = 52,
PROP_LIST_OF_GROUP_MEMBERS = 53,
PROP_LIST_OF_OBJECT_PROPERTY_REFERENCES = 54,
PROP_LIST_OF_SESSION_KEYS = 55,
PROP_LOCAL_DATE = 56,
PROP_LOCAL_TIME = 57,
PROP_LOCATION = 58,
PROP_LOW_LIMIT = 59,
PROP_MANIPULATED_VARIABLE_REFERENCE = 60,
PROP_MAXIMUM_OUTPUT = 61,
PROP_MAX_APDU_LENGTH_ACCEPTED = 62,
PROP_MAX_INFO_FRAMES = 63,
PROP_MAX_MASTER = 64,
PROP_MAX_PRES_VALUE = 65,
PROP_MINIMUM_OFF_TIME = 66,
PROP_MINIMUM_ON_TIME = 67,
PROP_MINIMUM_OUTPUT = 68,
PROP_MIN_PRES_VALUE = 69,
PROP_MODEL_NAME = 70,
PROP_MODIFICATION_DATE = 71,
PROP_NOTIFY_TYPE = 72,
PROP_NUMBER_OF_APDU_RETRIES = 73,
PROP_NUMBER_OF_STATES = 74,
PROP_OBJECT_IDENTIFIER = 75,
PROP_OBJECT_LIST = 76,
PROP_OBJECT_NAME = 77,
PROP_OBJECT_PROPERTY_REFERENCE = 78,
PROP_OBJECT_TYPE = 79,
PROP_OPTIONAL = 80,
PROP_OUT_OF_SERVICE = 81,
PROP_OUTPUT_UNITS = 82,
PROP_EVENT_PARAMETERS = 83,
PROP_POLARITY = 84,
PROP_PRESENT_VALUE = 85,
PROP_PRIORITY = 86,
PROP_PRIORITY_ARRAY = 87,
PROP_PRIORITY_FOR_WRITING = 88,
PROP_PROCESS_IDENTIFIER = 89,
PROP_PROGRAM_CHANGE = 90,
PROP_PROGRAM_LOCATION = 91,
PROP_PROGRAM_STATE = 92,
PROP_PROPORTIONAL_CONSTANT = 93,
PROP_PROPORTIONAL_CONSTANT_UNITS = 94,
PROP_PROTOCOL_CONFORMANCE_CLASS = 95, /* deleted in version 1 revision 2 */
PROP_PROTOCOL_OBJECT_TYPES_SUPPORTED = 96,
PROP_PROTOCOL_SERVICES_SUPPORTED = 97,
PROP_PROTOCOL_VERSION = 98,
PROP_READ_ONLY = 99,
PROP_REASON_FOR_HALT = 100,
PROP_RECIPIENT = 101,
PROP_RECIPIENT_LIST = 102,
PROP_RELIABILITY = 103,
PROP_RELINQUISH_DEFAULT = 104,
PROP_REQUIRED = 105,
PROP_RESOLUTION = 106,
PROP_SEGMENTATION_SUPPORTED = 107,
PROP_SETPOINT = 108,
PROP_SETPOINT_REFERENCE = 109,
PROP_STATE_TEXT = 110,
PROP_STATUS_FLAGS = 111,
PROP_SYSTEM_STATUS = 112,
PROP_TIME_DELAY = 113,
PROP_TIME_OF_ACTIVE_TIME_RESET = 114,
PROP_TIME_OF_STATE_COUNT_RESET = 115,
PROP_TIME_SYNCHRONIZATION_RECIPIENTS = 116,
PROP_UNITS = 117,
PROP_UPDATE_INTERVAL = 118,
PROP_UTC_OFFSET = 119,
PROP_VENDOR_IDENTIFIER = 120,
PROP_VENDOR_NAME = 121,
PROP_VT_CLASSES_SUPPORTED = 122,
PROP_WEEKLY_SCHEDULE = 123,
PROP_ATTEMPTED_SAMPLES = 124,
PROP_AVERAGE_VALUE = 125,
PROP_BUFFER_SIZE = 126,
PROP_CLIENT_COV_INCREMENT = 127,
PROP_COV_RESUBSCRIPTION_INTERVAL = 128,
PROP_CURRENT_NOTIFY_TIME = 129,
PROP_EVENT_TIME_STAMPS = 130,
PROP_LOG_BUFFER = 131,
PROP_LOG_DEVICE_OBJECT_PROPERTY = 132,
/* The enable property is renamed from log-enable in
Addendum b to ANSI/ASHRAE 135-2004(135b-2) */
PROP_ENABLE = 133,
PROP_LOG_INTERVAL = 134,
PROP_MAXIMUM_VALUE = 135,
PROP_MINIMUM_VALUE = 136,
PROP_NOTIFICATION_THRESHOLD = 137,
PROP_PREVIOUS_NOTIFY_TIME = 138,
PROP_PROTOCOL_REVISION = 139,
PROP_RECORDS_SINCE_NOTIFICATION = 140,
PROP_RECORD_COUNT = 141,
PROP_START_TIME = 142,
PROP_STOP_TIME = 143,
PROP_STOP_WHEN_FULL = 144,
PROP_TOTAL_RECORD_COUNT = 145,
PROP_VALID_SAMPLES = 146,
PROP_WINDOW_INTERVAL = 147,
PROP_WINDOW_SAMPLES = 148,
PROP_MAXIMUM_VALUE_TIMESTAMP = 149,
PROP_MINIMUM_VALUE_TIMESTAMP = 150,
PROP_VARIANCE_VALUE = 151,
PROP_ACTIVE_COV_SUBSCRIPTIONS = 152,
PROP_BACKUP_FAILURE_TIMEOUT = 153,
PROP_CONFIGURATION_FILES = 154,
PROP_DATABASE_REVISION = 155,
PROP_DIRECT_READING = 156,
PROP_LAST_RESTORE_TIME = 157,
PROP_MAINTENANCE_REQUIRED = 158,
PROP_MEMBER_OF = 159,
PROP_MODE = 160,
PROP_OPERATION_EXPECTED = 161,
PROP_SETTING = 162,
PROP_SILENCED = 163,
PROP_TRACKING_VALUE = 164,
PROP_ZONE_MEMBERS = 165,
PROP_LIFE_SAFETY_ALARM_VALUES = 166,
PROP_MAX_SEGMENTS_ACCEPTED = 167,
PROP_PROFILE_NAME = 168,
PROP_AUTO_SLAVE_DISCOVERY = 169,
PROP_MANUAL_SLAVE_ADDRESS_BINDING = 170,
PROP_SLAVE_ADDRESS_BINDING = 171,
PROP_SLAVE_PROXY_ENABLE = 172,
PROP_LAST_NOTIFY_RECORD = 173,
PROP_SCHEDULE_DEFAULT = 174,
PROP_ACCEPTED_MODES = 175,
PROP_ADJUST_VALUE = 176,
PROP_COUNT = 177,
PROP_COUNT_BEFORE_CHANGE = 178,
PROP_COUNT_CHANGE_TIME = 179,
PROP_COV_PERIOD = 180,
PROP_INPUT_REFERENCE = 181,
PROP_LIMIT_MONITORING_INTERVAL = 182,
PROP_LOGGING_OBJECT = 183,
PROP_LOGGING_RECORD = 184,
PROP_PRESCALE = 185,
PROP_PULSE_RATE = 186,
PROP_SCALE = 187,
PROP_SCALE_FACTOR = 188,
PROP_UPDATE_TIME = 189,
PROP_VALUE_BEFORE_CHANGE = 190,
PROP_VALUE_SET = 191,
PROP_VALUE_CHANGE_TIME = 192,
/* enumerations 193-206 are new */
PROP_ALIGN_INTERVALS = 193,
/* enumeration 194 is unassigned */
PROP_INTERVAL_OFFSET = 195,
PROP_LAST_RESTART_REASON = 196,
PROP_LOGGING_TYPE = 197,
/* enumeration 198-201 is unassigned */
PROP_RESTART_NOTIFICATION_RECIPIENTS = 202,
PROP_TIME_OF_DEVICE_RESTART = 203,
PROP_TIME_SYNCHRONIZATION_INTERVAL = 204,
PROP_TRIGGER = 205,
PROP_UTC_TIME_SYNCHRONIZATION_RECIPIENTS = 206,
/* enumerations 207-211 are used in Addendum d to ANSI/ASHRAE 135-2004 */
PROP_NODE_SUBTYPE = 207,
PROP_NODE_TYPE = 208,
PROP_STRUCTURED_OBJECT_LIST = 209,
PROP_SUBORDINATE_ANNOTATIONS = 210,
PROP_SUBORDINATE_LIST = 211,
/* enumerations 212-225 are used in Addendum e to ANSI/ASHRAE 135-2004 */
PROP_ACTUAL_SHED_LEVEL = 212,
PROP_DUTY_WINDOW = 213,
PROP_EXPECTED_SHED_LEVEL = 214,
PROP_FULL_DUTY_BASELINE = 215,
/* enumerations 216-217 are unassigned */
/* enumerations 212-225 are used in Addendum e to ANSI/ASHRAE 135-2004 */
PROP_REQUESTED_SHED_LEVEL = 218,
PROP_SHED_DURATION = 219,
PROP_SHED_LEVEL_DESCRIPTIONS = 220,
PROP_SHED_LEVELS = 221,
PROP_STATE_DESCRIPTION = 222,
/* enumerations 223-225 are unassigned */
/* enumerations 226-235 are used in Addendum f to ANSI/ASHRAE 135-2004 */
PROP_DOOR_ALARM_STATE = 226,
PROP_DOOR_EXTENDED_PULSE_TIME = 227,
PROP_DOOR_MEMBERS = 228,
PROP_DOOR_OPEN_TOO_LONG_TIME = 229,
PROP_DOOR_PULSE_TIME = 230,
PROP_DOOR_STATUS = 231,
PROP_DOOR_UNLOCK_DELAY_TIME = 232,
PROP_LOCK_STATUS = 233,
PROP_MASKED_ALARM_VALUES = 234,
PROP_SECURED_STATUS = 235,
/* enumerations 236-243 are unassigned */
/* enumerations 244-311 are used in Addendum j to ANSI/ASHRAE 135-2004 */
PROP_ABSENTEE_LIMIT = 244,
PROP_ACCESS_ALARM_EVENTS = 245,
PROP_ACCESS_DOORS = 246,
PROP_ACCESS_EVENT = 247,
PROP_ACCESS_EVENT_AUTHENTICATION_FACTOR = 248,
PROP_ACCESS_EVENT_CREDENTIAL = 249,
PROP_ACCESS_EVENT_TIME = 250,
PROP_ACCESS_TRANSACTION_EVENTS = 251,
PROP_ACCOMPANIMENT = 252,
PROP_ACCOMPANIMENT_TIME = 253,
PROP_ACTIVATION_TIME = 254,
PROP_ACTIVE_AUTHENTICATION_POLICY = 255,
PROP_ASSIGNED_ACCESS_RIGHTS = 256,
PROP_AUTHENTICATION_FACTORS = 257,
PROP_AUTHENTICATION_POLICY_LIST = 258,
PROP_AUTHENTICATION_POLICY_NAMES = 259,
PROP_AUTHENTICATION_STATUS = 260,
PROP_AUTHORIZATION_MODE = 261,
PROP_BELONGS_TO = 262,
PROP_CREDENTIAL_DISABLE = 263,
PROP_CREDENTIAL_STATUS = 264,
PROP_CREDENTIALS = 265,
PROP_CREDENTIALS_IN_ZONE = 266,
PROP_DAYS_REMAINING = 267,
PROP_ENTRY_POINTS = 268,
PROP_EXIT_POINTS = 269,
PROP_EXPIRY_TIME = 270,
PROP_EXTENDED_TIME_ENABLE = 271,
PROP_FAILED_ATTEMPT_EVENTS = 272,
PROP_FAILED_ATTEMPTS = 273,
PROP_FAILED_ATTEMPTS_TIME = 274,
PROP_LAST_ACCESS_EVENT = 275,
PROP_LAST_ACCESS_POINT = 276,
PROP_LAST_CREDENTIAL_ADDED = 277,
PROP_LAST_CREDENTIAL_ADDED_TIME = 278,
PROP_LAST_CREDENTIAL_REMOVED = 279,
PROP_LAST_CREDENTIAL_REMOVED_TIME = 280,
PROP_LAST_USE_TIME = 281,
PROP_LOCKOUT = 282,
PROP_LOCKOUT_RELINQUISH_TIME = 283,
PROP_MASTER_EXEMPTION = 284,
PROP_MAX_FAILED_ATTEMPTS = 285,
PROP_MEMBERS = 286,
PROP_MUSTER_POINT = 287,
PROP_NEGATIVE_ACCESS_RULES = 288,
PROP_NUMBER_OF_AUTHENTICATION_POLICIES = 289,
PROP_OCCUPANCY_COUNT = 290,
PROP_OCCUPANCY_COUNT_ADJUST = 291,
PROP_OCCUPANCY_COUNT_ENABLE = 292,
PROP_OCCUPANCY_EXEMPTION = 293,
PROP_OCCUPANCY_LOWER_LIMIT = 294,
PROP_OCCUPANCY_LOWER_LIMIT_ENFORCED = 295,
PROP_OCCUPANCY_STATE = 296,
PROP_OCCUPANCY_UPPER_LIMIT = 297,
PROP_OCCUPANCY_UPPER_LIMIT_ENFORCED = 298,
PROP_PASSBACK_EXEMPTION = 299,
PROP_PASSBACK_MODE = 300,
PROP_PASSBACK_TIMEOUT = 301,
PROP_POSITIVE_ACCESS_RULES = 302,
PROP_REASON_FOR_DISABLE = 303,
PROP_SUPPORTED_FORMATS = 304,
PROP_SUPPORTED_FORMAT_CLASSES = 305,
PROP_THREAT_AUTHORITY = 306,
PROP_THREAT_LEVEL = 307,
PROP_TRACE_FLAG = 308,
PROP_TRANSACTION_NOTIFICATION_CLASS = 309,
PROP_USER_EXTERNAL_IDENTIFIER = 310,
PROP_USER_INFORMATION_REFERENCE = 311,
/* enumerations 312-316 are unassigned */
PROP_USER_NAME = 317,
PROP_USER_TYPE = 318,
PROP_USES_REMAINING = 319,
PROP_ZONE_FROM = 320,
PROP_ZONE_TO = 321,
PROP_ACCESS_EVENT_TAG = 322,
PROP_GLOBAL_IDENTIFIER = 323,
/* enumerations 324-325 are unassigned */
PROP_VERIFICATION_TIME = 326,
PROP_BASE_DEVICE_SECURITY_POLICY = 327,
PROP_DISTRIBUTION_KEY_REVISION = 328,
PROP_DO_NOT_HIDE = 329,
PROP_KEY_SETS = 330,
PROP_LAST_KEY_SERVER = 331,
PROP_NETWORK_ACCESS_SECURITY_POLICIES = 332,
PROP_PACKET_REORDER_TIME = 333,
PROP_SECURITY_PDU_TIMEOUT = 334,
PROP_SECURITY_TIME_WINDOW = 335,
PROP_SUPPORTED_SECURITY_ALGORITHM = 336,
PROP_UPDATE_KEY_SET_TIMEOUT = 337,
PROP_BACKUP_AND_RESTORE_STATE = 338,
PROP_BACKUP_PREPARATION_TIME = 339,
PROP_RESTORE_COMPLETION_TIME = 340,
PROP_RESTORE_PREPARATION_TIME = 341,
/* enumerations 342-344 are defined in Addendum 2008-w */
PROP_BIT_MASK = 342,
PROP_BIT_TEXT = 343,
PROP_IS_UTC = 344,
PROP_GROUP_MEMBERS = 345,
PROP_GROUP_MEMBER_NAMES = 346,
PROP_MEMBER_STATUS_FLAGS = 347,
PROP_REQUESTED_UPDATE_INTERVAL = 348,
PROP_COVU_PERIOD = 349,
PROP_COVU_RECIPIENTS = 350,
PROP_EVENT_MESSAGE_TEXTS = 351,
/* enumerations 352-363 are defined in Addendum 2010-af */
PROP_EVENT_MESSAGE_TEXTS_CONFIG = 352,
PROP_EVENT_DETECTION_ENABLE = 353,
PROP_EVENT_ALGORITHM_INHIBIT = 354,
PROP_EVENT_ALGORITHM_INHIBIT_REF = 355,
PROP_TIME_DELAY_NORMAL = 356,
PROP_RELIABILITY_EVALUATION_INHIBIT = 357,
PROP_FAULT_PARAMETERS = 358,
PROP_FAULT_TYPE = 359,
PROP_LOCAL_FORWARDING_ONLY = 360,
PROP_PROCESS_IDENTIFIER_FILTER = 361,
PROP_SUBSCRIBED_RECIPIENTS = 362,
PROP_PORT_FILTER = 363,
/* enumeration 364 is defined in Addendum 2010-ae */
PROP_AUTHORIZATION_EXEMPTIONS = 364,
/* enumerations 365-370 are defined in Addendum 2010-aa */
PROP_ALLOW_GROUP_DELAY_INHIBIT = 365,
PROP_CHANNEL_NUMBER = 366,
PROP_CONTROL_GROUPS = 367,
PROP_EXECUTION_DELAY = 368,
PROP_LAST_PRIORITY = 369,
PROP_WRITE_STATUS = 370,
/* enumeration 371 is defined in Addendum 2010-ao */
PROP_PROPERTY_LIST = 371,
/* enumeration 372 is defined in Addendum 2010-ak */
PROP_SERIAL_NUMBER = 372,
/* enumerations 373-386 are defined in Addendum 2010-i */
PROP_BLINK_WARN_ENABLE = 373,
PROP_DEFAULT_FADE_TIME = 374,
PROP_DEFAULT_RAMP_RATE = 375,
PROP_DEFAULT_STEP_INCREMENT = 376,
PROP_EGRESS_TIME = 377,
PROP_IN_PROGRESS = 378,
PROP_INSTANTANEOUS_POWER = 379,
PROP_LIGHTING_COMMAND = 380,
PROP_LIGHTING_COMMAND_DEFAULT_PRIORITY = 381,
PROP_MAX_ACTUAL_VALUE = 382,
PROP_MIN_ACTUAL_VALUE = 383,
PROP_POWER = 384,
PROP_TRANSITION = 385,
PROP_EGRESS_ACTIVE = 386,
PROP_INTERFACE_VALUE = 387,
PROP_FAULT_HIGH_LIMIT = 388,
PROP_FAULT_LOW_LIMIT = 389,
PROP_LOW_DIFF_LIMIT = 390,
/* enumerations 391-392 are defined in Addendum 135-2012az */
PROP_STRIKE_COUNT = 391,
PROP_TIME_OF_STRIKE_COUNT_RESET = 392,
/* enumerations 393-398 are defined in Addendum 135-2012ay */
PROP_DEFAULT_TIMEOUT = 393,
PROP_INITIAL_TIMEOUT = 394,
PROP_LAST_STATE_CHANGE = 395,
PROP_STATE_CHANGE_VALUES = 396,
PROP_TIMER_RUNNING = 397,
PROP_TIMER_STATE = 398,
// Addendum-135-2012as
PROP_COMMAND_TIME_ARRAY = 430,
PROP_CURRENT_COMMAND_PRIORITY = 431,
PROP_LAST_COMMAND_TIME = 432,
PROP_VALUE_SOURCE = 433,
PROP_VALUE_SOURCE_ARRAY = 434,
/* The special property identifiers all, optional, and required */
/* are reserved for use in the ReadPropertyConditional and */
/* ReadPropertyMultiple services or services not defined in this standard. */
/* Enumerated values 0-511 are reserved for definition by ASHRAE. */
/* Enumerated values 512-4194303 may be used by others subject to the */
/* procedures and constraints described in Clause 23. */
/* do the max range inside of enum so that
compilers will allocate adequate sized datatype for enum
which is used to store decoding */
MAX_BACNET_PROPERTY_ID = 4194303
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Zyborg.Security.Cryptography;
using Zyborg.Vault.Ext.SystemBackend;
using Zyborg.Vault.Model;
using Zyborg.Vault.MockServer.Auth;
using Zyborg.Vault.MockServer.Policy;
using Zyborg.Vault.MockServer.Secret;
using Zyborg.Vault.MockServer.Storage;
using Microsoft.AspNetCore.Http;
namespace Zyborg.Vault.MockServer
{
public class MockServer
{
public static readonly DateTime UnixEpoch = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
/// <summary>
/// Byte length of the unseal keys.
/// </summary>
public const int UnsealKeyLength = 33;
private IHttpContextAccessor _httpAcc;
private TokenManager _tok;
private PathMap<IAuthBackend> _authReservedMounts = new PathMap<IAuthBackend>();
private PathMap<IAuthBackend> _authMounts = new PathMap<IAuthBackend>();
private Dictionary<string, PolicyDefinition> _policies = PolicyManager.GetBasePolicies();
private PathMap<ISecretBackend> _secretReservedMounts = new PathMap<ISecretBackend>();
private PathMap<ISecretBackend> _secretMounts = new PathMap<ISecretBackend>();
public MockServer(IServiceProvider di, IHttpContextAccessor httpAcc)
{
DI = di;
_httpAcc = httpAcc;
}
public IServiceProvider DI
{ get; }
public ServerSettings Settings
{ get; } = new ServerSettings();
public IStorage Storage
{ get; private set; }
public HealthStatus Health
{ get; } = new HealthImpl();
public ServerState State
{ get; } = new ServerState();
public void Start()
{
// Assume we're not initialized yet
Health.Initialized = false;
Health.Sealed = true;
Health.Standby = true;
StartStorage().Wait();
StartAuthMounts().Wait();
StartSecretMounts().Wait();
// Register root token
//! var tokenId = State.Durable.RootTokenId;
//! _tok.AddTokenAsync(new Ext.Token.CreateParameters
//! {
//! Id = tokenId,
//! Policies = new[] { "root" },
//! }, null, null).Wait();
}
public async Task StartStorage()
{
if (!Standard.StorageTypes.TryGetValue(Settings.Storage.Type, out var storageType))
throw new NotSupportedException($"unsupported storage type: {Settings.Storage.Type}");
IStorage s = (IStorage)ActivatorUtilities.CreateInstance(DI, storageType);
if (s == null)
throw new NotSupportedException($"unresolved storage type: {Settings.Storage.Type}: {storageType}");
this.Storage = s;
var stateJson = await this.Storage.ReadAsync("server/state");
if (stateJson != null)
{
State.Durable = JsonConvert.DeserializeObject<DurableServerState>(
stateJson);
Health.Initialized = true;
}
}
public async Task StartAuthMounts()
{
// Build our Token auth backend and manager
var tok = new TokenAuthBackend(this, new StorageWrapper(Storage, "sys/auth"), _httpAcc);
_tok = tok.Manager;
_authMounts.Set("token", tok);
_authReservedMounts.Set("token", tok); // Make sure it fixed
_authMounts.Set("userpass", new UserpassAuthBackend(
new StorageWrapper(Storage, "auth-mounts/userpass")));
await Task.CompletedTask;
}
public async Task StartSecretMounts()
{
ISecretBackend backend = new DummyBackend();
// Reserve the sys backend mount -- this will actually be intercepted
// and handled by the Sys Controller
_secretMounts.Set("sys", backend);
_secretReservedMounts.Set("sys", backend);
// Reserve the cubbyhole mount -- TODO: for now we just use a plain old
// Generic secret but will eventually correct this
backend = new GenericSecretBackend(new StorageWrapper(Storage,
"sys-mounts/cubbyhole"));
_secretMounts.Set("cubbyhole", backend);
_secretReservedMounts.Set("cubbyhole", backend);
_secretMounts.Set("secret", new GenericSecretBackend(new StorageWrapper(Storage,
"secret-mounts/secret")));
// _secretMounts.Set("alt-secret1", new GenericSecretBackend(
// new StorageWrapper(Storage, "secret-mounts/alt-secret1")));
// _secretMounts.Set("alt/secret/second", new GenericSecretBackend(
// new StorageWrapper(Storage, "secret-mounts/alt/secret/second")));
await Task.CompletedTask;
}
public async Task SaveState()
{
if (this.Storage == null)
throw new InvalidOperationException("storage system has not been initialized");
var ser = JsonConvert.SerializeObject(State.Durable, Formatting.Indented);
await this.Storage.WriteAsync("server/state", ser);
}
public InitializationStatus GetInitializationStatus()
{
return new InitializationStatus
{
Initialized = Health.Initialized,
};
}
public InitializationResponse Initialize(int n, int t)
{
if (Health.Initialized)
return null;
using (var aes = Aes.Create())
using (var tss = ThresholdSecretSharingAlgorithm.Create())
using (var sha = SHA512.Create())
{
aes.KeySize = 256;
aes.GenerateKey();
var rootKeyClear = aes.Key;
var rootKeyCrypt = tss.Split(rootKeyClear, n, t);
var rootKeyShares = tss.Shares.ToArray();
var rootToken = Guid.NewGuid();
var resp = new InitializationResponse
{
Keys = rootKeyShares.Select(x => BitConverter.ToString(x).Replace("-","")).ToArray(),
KeysBase64 = rootKeyShares.Select(x => Convert.ToBase64String(x)).ToArray(),
RootToken = rootToken.ToString(),
};
try
{
State.Durable = new DurableServerState();
State.Durable.SecretShares = n;
State.Durable.SecretThreshold = t;
State.Durable.RootKeyTerm = 1;
State.Durable.RootKeyInstallTime = DateTime.UtcNow;
State.Durable.RootKeyEncrypted = rootKeyCrypt;
State.Durable.RootKeyHash = sha.ComputeHash(rootKeyClear);
State.Durable.RootTokenHash = sha.ComputeHash(rootToken.ToByteArray());
State.Durable.ClusterName = Settings.ClusterName;
State.Durable.ClusterId = Guid.NewGuid().ToString();
SaveState().Wait();
Health.Initialized = true;
return resp;
}
catch
{
State.Durable = null;
throw;
}
}
}
public SealStatus Unseal(string key, bool reset)
{
if (reset)
{
State.UnsealNonce = null;
State.UnsealProgress = null;
}
else
{
byte[] keyBytes;
if (key.Length == UnsealKeyLength * 2)
{
// Hex-encoded key
// TODO: try-catch this and confirm the error response
keyBytes = Vault.Util.HexUtil.HexToByteArray(key);
}
else if (key.Length == UnsealKeyLength * 4 / 3)
{
// Base64-encoded key
keyBytes = Convert.FromBase64String(key);
}
else
{
throw new ArgumentException("invalid length key", nameof(key));
}
if (State.UnsealProgress == null)
{
// TODO: research this
State.UnsealNonce = Guid.NewGuid().ToString();
State.UnsealProgress = new List<string>(State.Durable.SecretThreshold);
}
var keyB64 = Convert.ToBase64String(keyBytes);
if (!State.UnsealProgress.Contains(keyB64))
State.UnsealProgress.Add(keyB64);
if (State.UnsealProgress.Count >= State.Durable.SecretThreshold)
{
var keys = State.UnsealProgress.Select(x => Convert.FromBase64String(x)).ToArray();
// Either we succeed or we fail but
// we reset the unseal state regardless
State.UnsealNonce = null;
State.UnsealProgress.Clear();
State.UnsealProgress = null;
// Combine the assembled keys
// to derive the true root key
Unseal(keys);
// If we get here, we succeeded
State.UnsealKeys = keys;
Health.Sealed = false;
}
}
return GetSealStatus();
}
private void Unseal(IEnumerable<byte[]> keys)
{
using (var tss = ThresholdSecretSharingAlgorithm.Create())
using (var sha = SHA512.Create())
{
tss.Shares = keys;
var rootKeyClear = tss.Combine(State.Durable.RootKeyEncrypted);
var rootKeyHash = sha.ComputeHash(rootKeyClear);
if (BitConverter.ToString(rootKeyHash) != BitConverter.ToString(State.Durable.RootKeyHash))
// TODO: verify the response in this case
throw new InvalidDataException("Invalid keys!");
State.RootKey = rootKeyClear;
}
}
public SealStatus GetSealStatus()
{
if (!Health.Initialized)
return null;
return new SealStatus
{
Sealed = Health.Sealed,
SecretThreshold = State.Durable.SecretThreshold,
SecretShares = State.Durable.SecretShares,
Progress = (State.UnsealProgress?.Count).GetValueOrDefault(),
Nonce = State.UnsealNonce ??string.Empty,
Version = Health.Version,
ClusterName = Health.ClusterName,
ClusterId = Health.ClusterId,
};
}
public KeyStatus GetKeyStatus()
{
if (!Health.Initialized || Health.Sealed)
return null;
return new KeyStatus
{
Term = State.Durable.RootKeyTerm.Value,
InstallTime = State.Durable.RootKeyInstallTime.Value,
};
}
public LeaderStatus GetLeaderStatus()
{
if (!Health.Initialized || Health.Sealed)
return null;
return new LeaderStatus
{
HaEnabled = false,
IsSelf = true,
LeaderAddress = "???",
};
}
public async Task<AuthInfo> GetToken(string id)
{
var tok = await _tok.GetTokenAsync(id);
if (tok == null)
throw new ArgumentException("token not found");
return new AuthInfo
{
Accessor = tok.Accessor,
ClientToken = id,
LeaseDuration = (long)tok.Ttl,
Metadata = tok.Metadata,
Policies = tok.Policies,
Renewable = tok.Renewable,
};
}
public IEnumerable<string> ListPolicies()
{
// TODO: move this to persistent operations
return _policies.Keys.OrderBy(x => x);
}
public PolicyDefinition ReadPolicy(string name)
{
if (!_policies.TryGetValue(name, out var polDef))
_policies.TryGetValue(name, out polDef);
// TODO: move this to persistent operations
return polDef;
}
public void WritePolicy(string name, string policyDefinition)
{
if (_policies.TryGetValue(name, out var polDef))
if (polDef.IsUpdateForbidden)
throw new ArgumentException(
$"cannot update {name} policy");
IPolicy pol;
try
{
// Parse and validate the policy definition
pol = PolicyManager.ParseDefinition(policyDefinition);
}
catch (Exception ex)
{
throw new ArgumentException(
$"Failed to parse policy: {ex.GetBaseException().Message}");
}
if (polDef == null)
polDef = new PolicyDefinition { Name = name };
polDef.Definition = policyDefinition;
polDef.Policy = pol;
// TODO: move this to persistent operations
_policies[name] = polDef;
}
public bool DeletePolicy(string name)
{
if (_policies.TryGetValue(name, out var polDef))
if (polDef.IsDeleteForbidden)
throw new ArgumentException(
$"cannot delete {name} policy");
// TODO: move this to persistent operations
return _policies.Remove(name);
}
public void AssertAuthorized(string capability, string path,
Dictionary<string, string> parameters = null, bool isSudo = false,
params string[] policies)
{
var pols = PolicyManager.NoPolicies;
if (policies != null && policies.Length > 0)
pols = policies.Select(x => _policies.TryGetValue(x, out var pol)
? pol.Policy : null).Where(x => x != null).ToArray();
if (!PolicyManager.IsAuthorized(capability, path, parameters, isSudo, pols))
throw new System.Security.SecurityException("permission denied");
}
public void GetAuthProviders()
{
}
public void MountAuthProvider()
{
}
public void DismountAuthProvider()
{
}
public IEnumerable<string> ListAuthMounts()
{
return _authMounts.ListPaths();
}
public (IAuthBackend backend, string path) ResolveAuthMount(string mountAndPath)
{
if (string.IsNullOrEmpty(mountAndPath))
return (null, null);
string mount = mountAndPath;
string path = string.Empty;
while (!_authMounts.Exists(mount))
{
int lastSlash = mount.LastIndexOf('/');
if (lastSlash <= 0)
// No more splitting and no match
return (null, null);
path = $"{mount.Substring(lastSlash + 1)}/{path}";
mount = mount.Substring(0, lastSlash);
}
return (_authMounts.Get(mount), path);
}
public void AddAuthMount(string mount, IAuthBackend backend)
{
if (_authReservedMounts.Exists(mount))
throw new InvalidOperationException("RESERVED");
throw new NotImplementedException(); }
public IEnumerable<string> ListSecretMounts()
{
return _secretMounts.ListPaths();
}
public (ISecretBackend backend, string path) ResolveSecretMount(string mountAndPath)
{
if (string.IsNullOrEmpty(mountAndPath))
return (null, null);
string mount = mountAndPath;
string path = string.Empty;
while (!_secretMounts.Exists(mount))
{
int lastSlash = mount.LastIndexOf('/');
if (lastSlash <= 0)
// No more splitting and no match
return (null, null);
path = $"{mount.Substring(lastSlash + 1)}/{path}";
mount = mount.Substring(0, lastSlash);
}
return (_secretMounts.Get(mount), path);
}
public void AddSecretMount(string mount, ISecretBackend backend)
{
if (_secretReservedMounts.Exists(mount))
throw new InvalidOperationException("RESERVED");
throw new NotImplementedException();
}
}
public class HealthImpl : HealthStatus
{
public override string Version
{
get => typeof(MockServer).Assembly.GetName().Version.ToString();
set => throw new NotSupportedException();
}
public override long ServerTimeUtc
{
get => (long)(DateTime.UtcNow - MockServer.UnixEpoch).TotalSeconds;
set => throw new NotSupportedException();
}
}
}
| |
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using NuGet.Common;
namespace Sleet
{
/// <summary>
/// Common file operations.
/// </summary>
public abstract class FileBase : ISleetFile
{
/// <summary>
/// File system tracking the file.
/// </summary>
public ISleetFileSystem FileSystem { get; }
/// <summary>
/// Root path.
/// </summary>
public Uri RootPath { get; }
/// <summary>
/// Remote feed URI.
/// </summary>
public Uri EntityUri { get; }
/// <summary>
/// True if the file has been modified.
/// </summary>
public bool HasChanges { get; private set; }
/// <summary>
/// True if the file was downloaded at some point.
/// This will be true even if the file was deleted.
/// </summary>
protected bool IsDownloaded { get; private set; }
/// <summary>
/// True if the file exists. This is for internally
/// tracking if the remote source contains the file
/// before it is downloaded.
/// </summary>
protected bool? RemoteExistsCacheValue { get; private set; }
/// <summary>
/// Local file on disk.
/// If IsLink is true this is an external file.
/// If IsLink is false, this is a temp file.
/// </summary>
protected FileInfo LocalCacheFile { get; private set; }
/// <summary>
/// File operation performance tracker.
/// </summary>
protected IPerfTracker PerfTracker { get; }
/// <summary>
/// True if the file is linked and not in the LocalCache.
/// Linked files should NEVER be deleted from their original location.
/// </summary>
protected bool IsLink { get; private set; }
/// <summary>
/// Retry count for failures.
/// </summary>
protected int RetryCount { get; set; } = 5;
/// <summary>
/// Original local cache file from the constructor. This is used if the linked
/// file is removed.
/// </summary>
private FileInfo _originalLocalCacheFile;
protected FileBase(ISleetFileSystem fileSystem, Uri rootPath, Uri displayPath, FileInfo localCacheFile, IPerfTracker perfTracker)
{
FileSystem = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
RootPath = rootPath ?? throw new ArgumentNullException(nameof(rootPath));
EntityUri = displayPath ?? throw new ArgumentNullException(nameof(displayPath));
PerfTracker = perfTracker ?? NullPerfTracker.Instance;
LocalCacheFile = localCacheFile ?? throw new ArgumentNullException(nameof(localCacheFile));
_originalLocalCacheFile = LocalCacheFile;
}
/// <summary>
/// True if the file exists.
/// </summary>
public async Task<bool> Exists(ILogger log, CancellationToken token)
{
// If the file was aleady downloaded then the local disk is the authority.
if (IsDownloaded)
{
return File.Exists(LocalCacheFile.FullName);
}
// If the file was not downloaded check the remote source if needed.
if (!RemoteExistsCacheValue.HasValue)
{
// Check the remote source
RemoteExistsCacheValue = await RemoteExists(log, token);
// If the file doesn't exist then it can be marked as downloaded
// to avoid an extra request later if Fetch is called.
if (!RemoteExistsCacheValue.Value)
{
IsDownloaded = true;
}
}
// Use the existing check.
return RemoteExistsCacheValue.Value;
}
/// <summary>
/// Fetch a file then check if it exists. This is optimized for scenarios
/// where it is known that the file will be used if it exists.
/// </summary>
public async Task<bool> ExistsWithFetch(ILogger log, CancellationToken token)
{
await FetchAsync(log, token);
return await Exists(log, token);
}
public async Task Push(ILogger log, CancellationToken token)
{
if (HasChanges)
{
using (var timer = PerfEntryWrapper.CreateFileTimer(this, PerfTracker, PerfFileEntry.FileOperation.Put))
{
var retry = Math.Max(RetryCount, 1);
for (var i = 0; i < retry; i++)
{
try
{
// Upload to remote source.
await CopyToSource(log, token);
// The file no longer has changes.
HasChanges = false;
break;
}
catch (Exception ex) when (i < (retry - 1))
{
await log.LogAsync(LogLevel.Debug, ex.ToString());
await log.LogAsync(LogLevel.Warning, $"Failed to upload '{RootPath}'. Retrying.");
await Task.Delay(TimeSpan.FromSeconds(10));
}
}
}
}
}
/// <summary>
/// Retrieve json file.
/// </summary>
public async Task<JObject> GetJson(ILogger log, CancellationToken token)
{
await EnsureFileOrThrow(log, token);
return await JsonUtility.LoadJsonAsync(LocalCacheFile);
}
/// <summary>
/// Retrieve json file if it exists.
/// </summary>
public async Task<JObject> GetJsonOrNull(ILogger log, CancellationToken token)
{
JObject json = null;
if (await ExistsWithFetch(log, token))
{
json = await JsonUtility.LoadJsonAsync(LocalCacheFile);
}
return json;
}
/// <summary>
/// Write json to the file.
/// </summary>
public Task Write(JObject json, ILogger log, CancellationToken token)
{
using (var timer = PerfEntryWrapper.CreateFileTimer(this, PerfTracker, PerfFileEntry.FileOperation.LocalWrite))
{
// Remove the file if it exists
Delete(log, token);
// Write out json to the file.
return JsonUtility.SaveJsonAsync(LocalCacheFile, json);
}
}
/// <summary>
/// Write a stream to the file.
/// </summary>
public async Task Write(Stream stream, ILogger log, CancellationToken token)
{
using (var timer = PerfEntryWrapper.CreateFileTimer(this, PerfTracker, PerfFileEntry.FileOperation.LocalWrite))
{
// Remove the file if it exists
Delete(log, token);
using (stream)
using (var writeStream = File.OpenWrite(LocalCacheFile.FullName))
{
await stream.CopyToAsync(writeStream);
}
}
}
/// <summary>
/// Link this file to an external file instead of creating a file in LocalCache.
/// </summary>
public void Link(string path, ILogger log, CancellationToken token)
{
var file = new FileInfo(path);
if (!file.Exists)
{
throw new FileNotFoundException(path);
}
// Remove the file if it exists
Delete(log, token);
// Mark this file as linked and use path directly instead
// of creating a new temp file and copy.
IsLink = true;
LocalCacheFile = file;
}
/// <summary>
/// Delete a file from the feed.
/// </summary>
public void Delete(ILogger log, CancellationToken token)
{
IsDownloaded = true;
HasChanges = true;
DeleteInternal();
}
/// <summary>
/// Delete without changing IsDownloaded or HasChanges.
/// If the file is linked this will remove the link.
/// </summary>
protected void DeleteInternal()
{
EnsureValid();
if (IsLink)
{
// Convert this file back to a non-linked and non-existant temp file.
IsLink = false;
LocalCacheFile = _originalLocalCacheFile;
}
if (File.Exists(LocalCacheFile.FullName))
{
File.Delete(LocalCacheFile.FullName);
}
}
/// <summary>
/// Ensure that the file exists on disk if it exists.
/// </summary>
protected async Task EnsureFile(ILogger log, CancellationToken token)
{
EnsureValid();
if (!IsDownloaded)
{
using (var timer = PerfEntryWrapper.CreateFileTimer(this, PerfTracker, PerfFileEntry.FileOperation.Get))
{
var retry = Math.Max(RetryCount, 1);
for (var i = 0; !IsDownloaded && i < retry; i++)
{
try
{
// Delete any existing file
DeleteInternal();
// Download from the remote source.
await CopyFromSource(log, token);
IsDownloaded = true;
}
catch (Exception ex) when (i < (retry - 1))
{
await log.LogAsync(LogLevel.Debug, ex.ToString());
await log.LogAsync(LogLevel.Warning, $"Failed to sync '{RootPath}'. Retrying.");
await Task.Delay(TimeSpan.FromSeconds(5));
}
}
}
}
}
/// <summary>
/// Ensure that the file is downloaded to disk. If it does not exist throw.
/// </summary>
protected async Task EnsureFileOrThrow(ILogger log, CancellationToken token)
{
await EnsureFile(log, token);
if (!File.Exists(LocalCacheFile.FullName))
{
throw new FileNotFoundException($"File does not exist. Remote: {EntityUri.AbsoluteUri} Local: {LocalCacheFile.FullName}");
}
}
/// <summary>
/// Returns the stream the file exists. Otherwise throws.
/// </summary>
public async Task<Stream> GetStream(ILogger log, CancellationToken token)
{
await EnsureFileOrThrow(log, token);
return File.OpenRead(LocalCacheFile.FullName);
}
/// <summary>
/// Copy the file to the destination path.
/// </summary>
/// <returns>True if the file was successfully copied.</returns>
public async Task<bool> CopyTo(string path, bool overwrite, ILogger log, CancellationToken token)
{
var pathInfo = new FileInfo(path);
if (!overwrite && pathInfo.Exists)
{
return false;
}
// Download the file if needed.
await EnsureFile(log, token);
// Check if the local copy exists
if (File.Exists(LocalCacheFile.FullName))
{
// Create the parent dir
pathInfo.Directory.Create();
// Copy the file
LocalCacheFile.CopyTo(pathInfo.FullName, overwrite);
return true;
}
return false;
}
/// <summary>
/// Returns FileInfo.Length if the file exists.
/// Null if the file does not exist.
/// </summary>
public long LocalFileSizeIfExists
{
get
{
long size = 0;
if (File.Exists(LocalCacheFile.FullName))
{
size = LocalCacheFile.Length;
}
return size;
}
}
public override string ToString()
{
return EntityUri.AbsoluteUri;
}
/// <summary>
/// Ensure that the file has been downloaded to disk if it exists.
/// </summary>
public Task FetchAsync(ILogger log, CancellationToken token)
{
return EnsureFile(log, token);
}
/// <summary>
/// Download a file to disk.
/// </summary>
protected abstract Task CopyFromSource(ILogger log, CancellationToken token);
/// <summary>
/// Upload a file.
/// </summary>
protected abstract Task CopyToSource(ILogger log, CancellationToken token);
/// <summary>
/// True if the file exists in the source.
/// </summary>
protected abstract Task<bool> RemoteExists(ILogger log, CancellationToken token);
/// <summary>
/// Called when the file system is reset. This file should not longer be used after this is called.
/// </summary>
public void Invalidate()
{
HasBeenInvalidated = true;
}
/// <summary>
/// True if the file is tracked by the file system.
/// </summary>
protected bool HasBeenInvalidated
{
get; set;
}
/// <summary>
/// Throw if the file is no longer tracked by the file system.
/// </summary>
protected virtual void EnsureValid()
{
if (HasBeenInvalidated)
{
throw new InvalidOperationException($"File is out of sync with the file system and cannot be used. This may occur if the file was kept externally while the file system was locked and unlocked between operations. Uri: {EntityUri.AbsoluteUri}");
}
}
/// <summary>
/// True if the file should not be compressed by default.
/// </summary>
protected virtual bool SkipCompress()
{
// Example of skipping compression by service
// return (SleetUtility.GetServiceName(this) == ServiceNames.Badges);
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
namespace Internal.Cryptography.Pal.AnyOS
{
internal sealed partial class ManagedPkcsPal : PkcsPal
{
public override void AddCertsFromStoreForDecryption(X509Certificate2Collection certs)
{
certs.AddRange(PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.CurrentUser, openExistingOnly: false));
try
{
// This store exists on macOS, but not Linux
certs.AddRange(
PkcsHelpers.GetStoreCertificates(StoreName.My, StoreLocation.LocalMachine, openExistingOnly: false));
}
catch (CryptographicException)
{
}
}
public override byte[] GetSubjectKeyIdentifier(X509Certificate2 certificate)
{
Debug.Assert(certificate != null);
X509Extension extension = certificate.Extensions[Oids.SubjectKeyIdentifier];
if (extension == null)
{
// Construct the value from the public key info.
extension = new X509SubjectKeyIdentifierExtension(
certificate.PublicKey,
X509SubjectKeyIdentifierHashAlgorithm.CapiSha1,
false);
}
// Certificates are DER encoded.
AsnReader reader = new AsnReader(extension.RawData, AsnEncodingRules.DER);
if (reader.TryReadPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> contents))
{
reader.ThrowIfNotEmpty();
return contents.ToArray();
}
// TryGetPrimitiveOctetStringBytes will have thrown if the next tag wasn't
// Universal (primitive) OCTET STRING, since we're in DER mode.
// So there's really no way we can get here.
Debug.Fail($"TryGetPrimitiveOctetStringBytes returned false in DER mode");
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
public override T GetPrivateKeyForSigning<T>(X509Certificate2 certificate, bool silent)
{
return GetPrivateKey<T>(certificate);
}
public override T GetPrivateKeyForDecryption<T>(X509Certificate2 certificate, bool silent)
{
return GetPrivateKey<T>(certificate);
}
private T GetPrivateKey<T>(X509Certificate2 certificate) where T : AsymmetricAlgorithm
{
if (typeof(T) == typeof(RSA))
return (T)(object)certificate.GetRSAPrivateKey();
if (typeof(T) == typeof(ECDsa))
return (T)(object)certificate.GetECDsaPrivateKey();
#if netcoreapp || netcoreapp30 || netstandard21
if (typeof(T) == typeof(DSA))
return (T)(object)certificate.GetDSAPrivateKey();
#endif
Debug.Fail($"Unknown key type requested: {typeof(T).FullName}");
return null;
}
private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifierAsn contentEncryptionAlgorithm)
{
SymmetricAlgorithm alg = OpenAlgorithm(contentEncryptionAlgorithm.Algorithm);
if (alg is RC2)
{
if (contentEncryptionAlgorithm.Parameters == null)
{
// Windows issues CRYPT_E_BAD_DECODE
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
Rc2CbcParameters rc2Params = Rc2CbcParameters.Decode(
contentEncryptionAlgorithm.Parameters.Value,
AsnEncodingRules.BER);
alg.KeySize = rc2Params.GetEffectiveKeyBits();
alg.IV = rc2Params.Iv.ToArray();
}
else
{
if (contentEncryptionAlgorithm.Parameters == null)
{
// Windows issues CRYPT_E_BAD_DECODE
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
AsnReader reader = new AsnReader(contentEncryptionAlgorithm.Parameters.Value, AsnEncodingRules.BER);
if (reader.TryReadPrimitiveOctetStringBytes(out ReadOnlyMemory<byte> primitiveBytes))
{
alg.IV = primitiveBytes.ToArray();
}
else
{
byte[] iv = new byte[alg.BlockSize / 8];
if (!reader.TryCopyOctetStringBytes(iv, out int bytesWritten) ||
bytesWritten != iv.Length)
{
throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding);
}
alg.IV = iv;
}
}
return alg;
}
private static SymmetricAlgorithm OpenAlgorithm(AlgorithmIdentifier algorithmIdentifier)
{
SymmetricAlgorithm alg = OpenAlgorithm(algorithmIdentifier.Oid);
if (alg is RC2)
{
if (algorithmIdentifier.KeyLength != 0)
{
alg.KeySize = algorithmIdentifier.KeyLength;
}
else
{
alg.KeySize = KeyLengths.Rc2_128Bit;
}
}
return alg;
}
private static SymmetricAlgorithm OpenAlgorithm(Oid algorithmIdentifier)
{
Debug.Assert(algorithmIdentifier != null);
SymmetricAlgorithm alg;
switch (algorithmIdentifier.Value)
{
case Oids.Rc2Cbc:
#pragma warning disable CA5351
alg = RC2.Create();
#pragma warning restore CA5351
break;
case Oids.DesCbc:
#pragma warning disable CA5351
alg = DES.Create();
#pragma warning restore CA5351
break;
case Oids.TripleDesCbc:
#pragma warning disable CA5350
alg = TripleDES.Create();
#pragma warning restore CA5350
break;
case Oids.Aes128Cbc:
alg = Aes.Create();
alg.KeySize = 128;
break;
case Oids.Aes192Cbc:
alg = Aes.Create();
alg.KeySize = 192;
break;
case Oids.Aes256Cbc:
alg = Aes.Create();
alg.KeySize = 256;
break;
default:
throw new CryptographicException(SR.Cryptography_Cms_UnknownAlgorithm, algorithmIdentifier.Value);
}
// These are the defaults, but they're restated here for clarity.
alg.Padding = PaddingMode.PKCS7;
alg.Mode = CipherMode.CBC;
return alg;
}
}
}
| |
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// File: StringBuilderExtNumeric.cs
// Date: 9th March 2010
// Author: Gavin Pugh
// Details: Extension methods for the 'StringBuilder' standard .NET class, to allow garbage-free concatenation of
// a selection of simple numeric types.
//
// Copyright (c) Gavin Pugh 2010 - Released under the zlib license: http://www.opensource.org/licenses/zlib-license.php
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Text;
using UnityEngine;
using Debug = System.Diagnostics.Debug;
namespace GCMonitor
{
public static partial class StringBuilderExtensions
{
// These digits are here in a static array to support hex with simple, easily-understandable code.
// Since A-Z don't sit next to 0-9 in the ascii table.
private static readonly char[] ms_digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private static readonly uint ms_default_decimal_places = 5; //< Matches standard .NET formatting dp's
private static readonly char ms_default_pad_char = '0';
//! Convert a given unsigned integer value to a string and concatenate onto the stringbuilder. Any base value allowed.
public static StringBuilder Concat( this StringBuilder string_builder, ulong ulong_val, uint pad_amount, char pad_char, bool thousand_sep, uint base_val )
{
Debug.Assert( base_val > 0 && base_val <= 16 );
// Calculate length of integer when written out
uint length = 0;
ulong length_calc = ulong_val;
do
{
length_calc /= base_val;
length++;
}
while ( length_calc > 0 );
if (thousand_sep)
length += (length - 1) / 3;
//uint str_length = thousand_sep ? length + (length - 1) / 3 : length;
uint str_length = length;
// Pad out space for writing.
string_builder.Append( pad_char, (int)Math.Max( pad_amount, length));
int strpos = string_builder.Length;
// We're writing backwards, one character at a time.
while ( length > 0 )
{
strpos--;
if (thousand_sep && (str_length - length) % 4 == 3)
{
string_builder[strpos] = ' ';
}
else
{
// Lookup from static char array, to cover hex values too
string_builder[strpos] = ms_digits[ulong_val % base_val];
ulong_val /= base_val;
}
length--;
}
return string_builder;
}
//! Convert a given unsigned integer value to a string and concatenate onto the stringbuilder. Assume no padding and base ten.
public static StringBuilder Concat( this StringBuilder string_builder, ulong ulong_val )
{
string_builder.Concat( ulong_val, 0, ms_default_pad_char, false, 10 );
return string_builder;
}
//! Convert a given unsigned integer value to a string and concatenate onto the stringbuilder. Assume base ten.
public static StringBuilder Concat( this StringBuilder string_builder, ulong ulong_val, uint pad_amount )
{
string_builder.Concat( ulong_val, pad_amount, ms_default_pad_char, false, 10 );
return string_builder;
}
//! Convert a given unsigned integer value to a string and concatenate onto the stringbuilder. Assume base ten.
public static StringBuilder Concat( this StringBuilder string_builder, ulong ulong_val, uint pad_amount, char pad_char )
{
string_builder.Concat( ulong_val, pad_amount, pad_char, false, 10 );
return string_builder;
}
//! Convert a given unsigned integer value to a string and concatenate onto the stringbuilder. Assume base ten.
public static StringBuilder Concat(this StringBuilder string_builder, ulong ulong_val, uint pad_amount, char pad_char, bool thousand_sep)
{
string_builder.Concat(ulong_val, pad_amount, pad_char, thousand_sep, 10);
return string_builder;
}
//! Convert a given signed integer value to a string and concatenate onto the stringbuilder. Any base value allowed.
public static StringBuilder Concat( this StringBuilder string_builder, long int_val, uint pad_amount, char pad_char, bool thousand_sep, uint base_val )
{
Debug.Assert( base_val > 0 && base_val <= 16 );
// Deal with negative numbers
if (int_val < 0)
{
string_builder.Append( '-' );
ulong uint_val = ulong.MaxValue - ((ulong) int_val ) + 1; //< This is to deal with Int32.MinValue
string_builder.Concat( uint_val, pad_amount, pad_char, thousand_sep, base_val );
}
else
{
string_builder.Concat((ulong)int_val, pad_amount, pad_char, thousand_sep, base_val );
}
return string_builder;
}
//! Convert a given signed integer value to a string and concatenate onto the stringbuilder. Assume no padding and base ten.
public static StringBuilder Concat( this StringBuilder string_builder, long int_val )
{
string_builder.Concat( int_val, 0, ms_default_pad_char, false, 10 );
return string_builder;
}
//! Convert a given signed integer value to a string and concatenate onto the stringbuilder. Assume base ten.
public static StringBuilder Concat( this StringBuilder string_builder, long int_val, uint pad_amount )
{
string_builder.Concat( int_val, pad_amount, ms_default_pad_char, false, 10 );
return string_builder;
}
//! Convert a given signed integer value to a string and concatenate onto the stringbuilder. Assume base ten.
public static StringBuilder Concat( this StringBuilder string_builder, long int_val, uint pad_amount, char pad_char )
{
string_builder.Concat( int_val, pad_amount, pad_char, false, 10 );
return string_builder;
}
public static StringBuilder Concat(this StringBuilder string_builder, long int_val, uint pad_amount, char pad_char, bool thousand_sep)
{
string_builder.Concat(int_val, pad_amount, pad_char, thousand_sep, 10);
return string_builder;
}
//! Convert a given double value to a string and concatenate onto the stringbuilder
public static StringBuilder Concat(this StringBuilder string_builder, double double_val, uint decimal_places, uint pad_amount, char pad_char, bool thousand_sep)
{
if (decimal_places == 0)
{
// No decimal places, just round up and print it as an int
long int_val = (long) Math.Floor(double_val);
string_builder.Concat(int_val, pad_amount, ' ', thousand_sep, 10);
}
else
{
long int_part = (long)double_val;
// First part is easy, just cast to an integer
string_builder.Concat(int_part, pad_amount, ' ', thousand_sep, 10);
// Decimal point
string_builder.Append('.');
// Work out remainder we need to print after the d.p.
double remainder = Math.Abs(double_val - int_part);
double r = remainder;
//Leading zeros in the decimal portion
remainder *= 10;
decimal_places--;
while (decimal_places > 0 && ((uint)remainder % 10) == 0)
{
remainder *= 10;
decimal_places--;
string_builder.Append('0');
}
// Multiply up to become an int that we can print
while (decimal_places > 0)
{
remainder *= 10;
decimal_places--;
}
// Round up. It's guaranteed to be a positive number, so no extra work required here.
// Commented since it adds a 0 for numbers like 0.96 ( prints 0.10 instead of 0.1)
// Good enough for my use...
//remainder += 0.5f;
if ((ulong)remainder > 9)
MonoBehaviour.print("Wrong " + (ulong)remainder + " " + remainder.ToString("F5") + " " +r.ToString("F5") + " "+ double_val.ToString("F5"));
// All done, print that as an int!
string_builder.Concat((ulong)remainder, 0, '0', false, 10);
}
return string_builder;
}
//! Convert a given float value to a string and concatenate onto the stringbuilder. Assumes five decimal places, and no padding.
public static StringBuilder Concat(this StringBuilder string_builder, double double_val)
{
string_builder.Concat(double_val, ms_default_decimal_places, 0, ms_default_pad_char, false);
return string_builder;
}
//! Convert a given float value to a string and concatenate onto the stringbuilder. Assumes no padding.
public static StringBuilder Concat(this StringBuilder string_builder, double double_val, uint decimal_places)
{
string_builder.Concat(double_val, decimal_places, 0, ms_default_pad_char, false);
return string_builder;
}
//! Convert a given float value to a string and concatenate onto the stringbuilder.
public static StringBuilder Concat(this StringBuilder string_builder, double double_val, uint decimal_places, uint pad_amount)
{
string_builder.Concat(double_val, decimal_places, pad_amount, ms_default_pad_char, false);
return string_builder;
}
//! Convert a given float value to a string and concatenate onto the stringbuilder.
public static StringBuilder Concat(this StringBuilder string_builder, double double_val, uint decimal_places, uint pad_amount, char pad_char)
{
string_builder.Concat(double_val, decimal_places, pad_amount, pad_char, false);
return string_builder;
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudioTools.Project
{
internal class ProjectReferenceNode : ReferenceNode
{
#region fields
/// <summary>
/// The name of the assembly this refernce represents
/// </summary>
private Guid referencedProjectGuid;
private string referencedProjectName = String.Empty;
private string referencedProjectRelativePath = String.Empty;
private string referencedProjectFullPath = String.Empty;
private BuildDependency buildDependency;
/// <summary>
/// This is a reference to the automation object for the referenced project.
/// </summary>
private EnvDTE.Project referencedProject;
/// <summary>
/// This state is controlled by the solution events.
/// The state is set to false by OnBeforeUnloadProject.
/// The state is set to true by OnBeforeCloseProject event.
/// </summary>
private bool canRemoveReference = true;
/// <summary>
/// Possibility for solution listener to update the state on the dangling reference.
/// It will be set in OnBeforeUnloadProject then the nopde is invalidated then it is reset to false.
/// </summary>
private bool isNodeValid;
#endregion
#region properties
public override string Url
{
get
{
return this.referencedProjectFullPath;
}
}
public override string Caption
{
get
{
return this.referencedProjectName;
}
}
internal Guid ReferencedProjectGuid
{
get
{
return this.referencedProjectGuid;
}
}
/// <summary>
/// Possiblity to shortcut and set the dangling project reference icon.
/// It is ussually manipulated by solution listsneres who handle reference updates.
/// </summary>
internal protected bool IsNodeValid
{
get
{
return this.isNodeValid;
}
set
{
this.isNodeValid = value;
}
}
/// <summary>
/// Controls the state whether this reference can be removed or not. Think of the project unload scenario where the project reference should not be deleted.
/// </summary>
internal bool CanRemoveReference
{
get
{
return this.canRemoveReference;
}
set
{
this.canRemoveReference = value;
}
}
internal string ReferencedProjectName
{
get { return this.referencedProjectName; }
}
/// <summary>
/// Gets the automation object for the referenced project.
/// </summary>
internal EnvDTE.Project ReferencedProjectObject
{
get
{
// If the referenced project is null then re-read.
if (this.referencedProject == null)
{
// Search for the project in the collection of the projects in the
// current solution.
EnvDTE.DTE dte = (EnvDTE.DTE)this.ProjectMgr.GetService(typeof(EnvDTE.DTE));
if ((null == dte) || (null == dte.Solution))
{
return null;
}
foreach (EnvDTE.Project prj in dte.Solution.Projects)
{
//Skip this project if it is an umodeled project (unloaded)
if (string.Compare(EnvDTE.Constants.vsProjectKindUnmodeled, prj.Kind, StringComparison.OrdinalIgnoreCase) == 0)
{
continue;
}
// Get the full path of the current project.
EnvDTE.Property pathProperty = null;
try
{
if (prj.Properties == null)
{
continue;
}
pathProperty = prj.Properties.Item("FullPath");
if (null == pathProperty)
{
// The full path should alway be availabe, but if this is not the
// case then we have to skip it.
continue;
}
}
catch (ArgumentException)
{
continue;
}
string prjPath = pathProperty.Value.ToString();
EnvDTE.Property fileNameProperty = null;
// Get the name of the project file.
try
{
fileNameProperty = prj.Properties.Item("FileName");
if (null == fileNameProperty)
{
// Again, this should never be the case, but we handle it anyway.
continue;
}
}
catch (ArgumentException)
{
continue;
}
prjPath = Path.Combine(prjPath, fileNameProperty.Value.ToString());
// If the full path of this project is the same as the one of this
// reference, then we have found the right project.
if (CommonUtils.IsSamePath(prjPath, referencedProjectFullPath))
{
this.referencedProject = prj;
break;
}
}
}
return this.referencedProject;
}
set
{
this.referencedProject = value;
}
}
/// <summary>
/// Gets the full path to the assembly generated by this project.
/// </summary>
internal string ReferencedProjectOutputPath
{
get
{
// Make sure that the referenced project implements the automation object.
if (null == this.ReferencedProjectObject)
{
return null;
}
// Get the configuration manager from the project.
EnvDTE.ConfigurationManager confManager = this.ReferencedProjectObject.ConfigurationManager;
if (null == confManager)
{
return null;
}
// Get the active configuration.
EnvDTE.Configuration config = confManager.ActiveConfiguration;
if (null == config)
{
return null;
}
if (null == config.Properties)
{
return null;
}
// Get the output path for the current configuration.
EnvDTE.Property outputPathProperty = config.Properties.Item("OutputPath");
if (null == outputPathProperty || outputPathProperty.Value == null)
{
return null;
}
// Usually the output path is relative to the project path. If it is set as an
// absolute path, this call has no effect.
string outputPath = CommonUtils.GetAbsoluteDirectoryPath(
Path.GetDirectoryName(referencedProjectFullPath),
outputPathProperty.Value.ToString());
// Now get the name of the assembly from the project.
// Some project system throw if the property does not exist. We expect an ArgumentException.
EnvDTE.Property assemblyNameProperty = null;
try
{
assemblyNameProperty = this.ReferencedProjectObject.Properties.Item("OutputFileName");
}
catch (ArgumentException)
{
}
if (null == assemblyNameProperty)
{
return null;
}
// build the full path adding the name of the assembly to the output path.
outputPath = Path.Combine(outputPath, assemblyNameProperty.Value.ToString());
return outputPath;
}
}
internal string AssemblyName
{
get
{
// Now get the name of the assembly from the project.
// Some project system throw if the property does not exist. We expect an ArgumentException.
EnvDTE.Property assemblyNameProperty = null;
if (ReferencedProjectObject != null &&
!(ReferencedProjectObject is Automation.OAProject)) // our own projects don't have assembly names
{
try
{
assemblyNameProperty = this.ReferencedProjectObject.Properties.Item(ProjectFileConstants.AssemblyName);
}
catch (ArgumentException)
{
}
if (assemblyNameProperty != null)
{
return assemblyNameProperty.Value.ToString();
}
}
return null;
}
}
private Automation.OAProjectReference projectReference;
internal override object Object
{
get
{
if (null == projectReference)
{
projectReference = new Automation.OAProjectReference(this);
}
return projectReference;
}
}
#endregion
#region ctors
/// <summary>
/// Constructor for the ReferenceNode. It is called when the project is reloaded, when the project element representing the refernce exists.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2234:PassSystemUriObjectsInsteadOfStrings")]
public ProjectReferenceNode(ProjectNode root, ProjectElement element)
: base(root, element)
{
this.referencedProjectRelativePath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectRelativePath), "Could not retrieve referenced project path form project file");
string guidString = this.ItemNode.GetMetadata(ProjectFileConstants.Project);
// Continue even if project setttings cannot be read.
try
{
this.referencedProjectGuid = new Guid(guidString);
this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);
this.ProjectMgr.AddBuildDependency(this.buildDependency);
}
finally
{
Debug.Assert(this.referencedProjectGuid != Guid.Empty, "Could not retrive referenced project guidproject file");
this.referencedProjectName = this.ItemNode.GetMetadata(ProjectFileConstants.Name);
Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "Could not retrive referenced project name form project file");
}
// TODO: Maybe referenced projects should be relative to ProjectDir?
this.referencedProjectFullPath = CommonUtils.GetAbsoluteFilePath(this.ProjectMgr.ProjectHome, this.referencedProjectRelativePath);
}
/// <summary>
/// constructor for the ProjectReferenceNode
/// </summary>
public ProjectReferenceNode(ProjectNode root, string referencedProjectName, string projectPath, string projectReference)
: base(root)
{
Debug.Assert(root != null && !String.IsNullOrEmpty(referencedProjectName) && !String.IsNullOrEmpty(projectReference)
&& !String.IsNullOrEmpty(projectPath), "Can not add a reference because the input for adding one is invalid.");
if (projectReference == null)
{
throw new ArgumentNullException("projectReference");
}
this.referencedProjectName = referencedProjectName;
int indexOfSeparator = projectReference.IndexOf('|');
string fileName = String.Empty;
// Unfortunately we cannot use the path part of the projectReference string since it is not resolving correctly relative pathes.
if (indexOfSeparator != -1)
{
string projectGuid = projectReference.Substring(0, indexOfSeparator);
this.referencedProjectGuid = new Guid(projectGuid);
if (indexOfSeparator + 1 < projectReference.Length)
{
string remaining = projectReference.Substring(indexOfSeparator + 1);
indexOfSeparator = remaining.IndexOf('|');
if (indexOfSeparator == -1)
{
fileName = remaining;
}
else
{
fileName = remaining.Substring(0, indexOfSeparator);
}
}
}
Debug.Assert(!String.IsNullOrEmpty(fileName), "Can not add a project reference because the input for adding one is invalid.");
string justTheFileName = Path.GetFileName(fileName);
this.referencedProjectFullPath = CommonUtils.GetAbsoluteFilePath(projectPath, justTheFileName);
// TODO: Maybe referenced projects should be relative to ProjectDir?
this.referencedProjectRelativePath = CommonUtils.GetRelativeFilePath(this.ProjectMgr.ProjectHome, this.referencedProjectFullPath);
this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);
}
#endregion
#region methods
protected override NodeProperties CreatePropertiesObject()
{
return new ProjectReferencesProperties(this);
}
/// <summary>
/// The node is added to the hierarchy and then updates the build dependency list.
/// </summary>
public override void AddReference()
{
if (this.ProjectMgr == null)
{
return;
}
base.AddReference();
this.ProjectMgr.AddBuildDependency(this.buildDependency);
return;
}
/// <summary>
/// Overridden method. The method updates the build dependency list before removing the node from the hierarchy.
/// </summary>
public override void Remove(bool removeFromStorage)
{
if (this.ProjectMgr == null || !this.CanRemoveReference)
{
return;
}
this.ProjectMgr.RemoveBuildDependency(this.buildDependency);
base.Remove(removeFromStorage);
return;
}
/// <summary>
/// Links a reference node to the project file.
/// </summary>
protected override void BindReferenceData()
{
Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "The referencedProjectName field has not been initialized");
Debug.Assert(this.referencedProjectGuid != Guid.Empty, "The referencedProjectName field has not been initialized");
this.ItemNode = new MsBuildProjectElement(this.ProjectMgr, this.referencedProjectRelativePath, ProjectFileConstants.ProjectReference);
this.ItemNode.SetMetadata(ProjectFileConstants.Name, this.referencedProjectName);
this.ItemNode.SetMetadata(ProjectFileConstants.Project, this.referencedProjectGuid.ToString("B"));
this.ItemNode.SetMetadata(ProjectFileConstants.Private, true.ToString());
}
/// <summary>
/// Defines whether this node is valid node for painting the refererence icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon()
{
if (this.referencedProjectGuid == Guid.Empty || this.ProjectMgr == null || this.ProjectMgr.IsClosed || this.isNodeValid)
{
return false;
}
IVsHierarchy hierarchy = null;
hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, this.referencedProjectGuid);
if (hierarchy == null)
{
return false;
}
//If the Project is unloaded return false
if (this.ReferencedProjectObject == null)
{
return false;
}
return File.Exists(this.referencedProjectFullPath);
}
/// <summary>
/// Checks if a project reference can be added to the hierarchy. It calls base to see if the reference is not already there, then checks for circular references.
/// </summary>
/// <param name="errorHandler">The error handler delegate to return</param>
/// <returns></returns>
protected override bool CanAddReference(out CannotAddReferenceErrorMessage errorHandler)
{
// When this method is called this refererence has not yet been added to the hierarchy, only instantiated.
if (!base.CanAddReference(out errorHandler))
{
return false;
}
errorHandler = null;
if (this.IsThisProjectReferenceInCycle())
{
errorHandler = new CannotAddReferenceErrorMessage(ShowCircularReferenceErrorMessage);
return false;
}
return true;
}
private bool IsThisProjectReferenceInCycle()
{
return IsReferenceInCycle(this.referencedProjectGuid);
}
private void ShowCircularReferenceErrorMessage()
{
string message = String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ProjectContainsCircularReferences, CultureInfo.CurrentUICulture), this.referencedProjectName);
string title = string.Empty;
OLEMSGICON icon = OLEMSGICON.OLEMSGICON_CRITICAL;
OLEMSGBUTTON buttons = OLEMSGBUTTON.OLEMSGBUTTON_OK;
OLEMSGDEFBUTTON defaultButton = OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST;
VsShellUtilities.ShowMessageBox(this.ProjectMgr.Site, title, message, icon, buttons, defaultButton);
}
/// <summary>
/// Recursively search if this project reference guid is in cycle.
/// </summary>
private bool IsReferenceInCycle(Guid projectGuid)
{
// TODO: This has got to be wrong, it doesn't work w/ other project types.
IVsHierarchy hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, projectGuid);
IReferenceContainerProvider provider = hierarchy.GetProject().GetCommonProject() as IReferenceContainerProvider;
if (provider != null)
{
IReferenceContainer referenceContainer = provider.GetReferenceContainer();
Utilities.CheckNotNull(referenceContainer, "Could not found the References virtual node");
foreach (ReferenceNode refNode in referenceContainer.EnumReferences())
{
ProjectReferenceNode projRefNode = refNode as ProjectReferenceNode;
if (projRefNode != null)
{
if (projRefNode.ReferencedProjectGuid == this.ProjectMgr.ProjectIDGuid)
{
return true;
}
if (this.IsReferenceInCycle(projRefNode.ReferencedProjectGuid))
{
return true;
}
}
}
}
return false;
}
#endregion
}
}
| |
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using Zenject;
namespace Zenject.Tests.Installers
{
public class TestCompositeInstallerExtensions
{
TestInstaller _installer1;
TestCompositeInstaller _compositeInstaller1;
TestCompositeInstaller _compositeInstaller2;
TestCompositeInstaller _circularRefCompositeInstaller1;
List<TestCompositeInstaller> _parentInstallers1;
TestInstaller _dummyInstaller1;
TestInstaller _dummyInstaller2;
TestInstaller _dummyInstaller3;
TestCompositeInstaller _dummyCompositeInstaller1;
[SetUp]
public void SetUp()
{
_installer1 = new TestInstaller();
_compositeInstaller1 = new TestCompositeInstaller
{
_leafInstallers = new List<TestInstaller>()
};
_compositeInstaller2 = new TestCompositeInstaller
{
_leafInstallers = new List<TestInstaller>
{
_compositeInstaller1,
},
};
_circularRefCompositeInstaller1 = new TestCompositeInstaller
{
_leafInstallers = new List<TestInstaller>()
};
_circularRefCompositeInstaller1._leafInstallers.Add(_circularRefCompositeInstaller1);
_parentInstallers1 = new List<TestCompositeInstaller>
{
_compositeInstaller1,
};
_dummyInstaller1 = new TestInstaller();
_dummyInstaller2 = new TestInstaller();
_dummyInstaller3 = new TestInstaller();
_dummyCompositeInstaller1 = new TestCompositeInstaller
{
_leafInstallers = new List<TestInstaller>()
};
}
[Test]
public void TestValidateAsCompositeZeroParent()
{
var circular = _circularRefCompositeInstaller1;
Assert.True(_installer1.ValidateAsComposite());
Assert.True(_compositeInstaller1.ValidateAsComposite());
Assert.False(circular.ValidateAsComposite<IInstaller>());
Assert.False(circular.ValidateAsComposite<TestInstaller>());
// T will be infered as TestCompositeInstaller, so parent will be "ICompositeInstaller<TestCompositeInstaller>>"
Assert.True(circular.ValidateAsComposite());
}
[Test]
public void TestValidateAsCompositeOneParent()
{
var dummy = _dummyCompositeInstaller1;
var circular = _circularRefCompositeInstaller1;
Assert.True(_installer1.ValidateAsComposite(dummy));
Assert.True(_installer1.ValidateAsComposite(circular));
Assert.True(_compositeInstaller1.ValidateAsComposite(dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(_compositeInstaller1));
Assert.False(circular.ValidateAsComposite(dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(_compositeInstaller1));
}
[Test]
public void TestValidateAsCompositeTwoParents()
{
var dummy = _dummyCompositeInstaller1;
var circular = _circularRefCompositeInstaller1;
Assert.True(_installer1.ValidateAsComposite(dummy, dummy));
Assert.True(_installer1.ValidateAsComposite(circular, circular));
Assert.True(_compositeInstaller1.ValidateAsComposite(dummy, dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(_compositeInstaller1, dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, _compositeInstaller1));
Assert.False(circular.ValidateAsComposite(dummy, dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(_compositeInstaller1, dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, _compositeInstaller1));
}
[Test]
public void TestValidateAsCompositeThreeParents()
{
var dummy = _dummyCompositeInstaller1;
var circular = _circularRefCompositeInstaller1;
Assert.True(_installer1.ValidateAsComposite(dummy, dummy, dummy));
Assert.True(_installer1.ValidateAsComposite(circular, circular, circular));
Assert.True(_compositeInstaller1.ValidateAsComposite(dummy, dummy, dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(_compositeInstaller1, dummy, dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, _compositeInstaller1, dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, dummy, _compositeInstaller1));
Assert.False(circular.ValidateAsComposite(dummy, dummy, dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(_compositeInstaller1, dummy, dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, _compositeInstaller1, dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, dummy, _compositeInstaller1));
}
[Test]
public void TestValidateAsCompositeFourParents()
{
var dummy = _dummyCompositeInstaller1;
var circular = _circularRefCompositeInstaller1;
Assert.True(_installer1.ValidateAsComposite(dummy, dummy, dummy, dummy));
Assert.True(_installer1.ValidateAsComposite(circular, circular, circular, circular));
Assert.True(_compositeInstaller1.ValidateAsComposite(dummy, dummy, dummy, dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(_compositeInstaller1, dummy, dummy, dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, _compositeInstaller1, dummy, dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, dummy, _compositeInstaller1, dummy));
Assert.False(_compositeInstaller1.ValidateAsComposite(dummy, dummy, dummy, _compositeInstaller1));
Assert.False(circular.ValidateAsComposite(dummy, dummy, dummy, dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(_compositeInstaller1, dummy, dummy, dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, _compositeInstaller1, dummy, dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, dummy, _compositeInstaller1, dummy));
Assert.False(_compositeInstaller2.ValidateAsComposite(dummy, dummy, dummy, _compositeInstaller1));
}
[Test]
public void TestValidateLeafInstallers()
{
Assert.True(_compositeInstaller1.ValidateLeafInstallers());
}
[Test]
public void TestValidateLeafInstallersWithCircularRef()
{
Assert.False(_circularRefCompositeInstaller1.ValidateLeafInstallers());
}
[Test]
public void TestValidateLeafInstallersWithCircularRefLeaf()
{
_compositeInstaller1._leafInstallers = new List<TestInstaller>
{
_circularRefCompositeInstaller1,
};
Assert.False(_compositeInstaller1.ValidateLeafInstallers());
}
[Test]
public void TestValidateAsCompositeWithInstaller()
{
Assert.True(_installer1.ValidateAsComposite(_parentInstallers1));
}
[Test]
public void TestValidateAsCompositeWithCompositeInstallerWithoutCircularRef()
{
_parentInstallers1 = new List<TestCompositeInstaller>
{
new TestCompositeInstaller(),
new TestCompositeInstaller(),
new TestCompositeInstaller(),
};
bool actual = _compositeInstaller1.ValidateAsComposite(_parentInstallers1);
Assert.True(actual);
}
[Test]
public void TestValidateAsCompositeWithCompositeInstallerWithoutCircularRefDeep()
{
var compositeInstaller1 = new TestCompositeInstaller();
var compositeInstaller2 = new TestCompositeInstaller();
var compositeInstaller3 = new TestCompositeInstaller();
compositeInstaller1._leafInstallers = new List<TestInstaller>
{
_dummyInstaller1,
compositeInstaller2,
_dummyInstaller2,
};
compositeInstaller2._leafInstallers = new List<TestInstaller>
{
compositeInstaller3,
};
compositeInstaller3._leafInstallers = new List<TestInstaller>
{
_dummyInstaller3,
};
bool actual = compositeInstaller1.ValidateAsComposite(_parentInstallers1);
Assert.True(actual);
}
[Test]
public void TestValidateAsCompositeWithCompositeInstallerAndParentAsSelf()
{
_parentInstallers1 = new List<TestCompositeInstaller>
{
_compositeInstaller1,
};
bool actual = _compositeInstaller1.ValidateAsComposite(_parentInstallers1);
Assert.False(actual);
}
[Test]
public void TestValidateAsCompositeWithCompositeInstallerAndSelfCircularRef()
{
_parentInstallers1.Clear();
bool actual = _circularRefCompositeInstaller1.ValidateAsComposite(_parentInstallers1);
Assert.False(actual);
}
[Test]
public void TestValidateAsCompositeWithCompositeInstallerAndSelfCircularRefDeep()
{
var installer1 = new TestCompositeInstaller();
var installer2 = new TestCompositeInstaller();
var installer3 = new TestCompositeInstaller();
installer1._leafInstallers = new List<TestInstaller>
{
_dummyInstaller1,
installer2,
_dummyInstaller2,
};
installer2._leafInstallers = new List<TestInstaller>
{
installer3,
};
installer3._leafInstallers = new List<TestInstaller>
{
installer1, // a circular reference
_dummyInstaller3,
};
bool actual = installer1.ValidateAsComposite(_parentInstallers1);
Assert.False(actual);
}
[Test]
public void TestValidateAsCompositeWithCompositeInstallerAndParentCircularRef()
{
var installer = new TestCompositeInstaller
{
_leafInstallers = new List<TestInstaller>
{
_compositeInstaller1,
},
};
_parentInstallers1 = new List<TestCompositeInstaller>
{
_compositeInstaller1,
};
bool actual = installer.ValidateAsComposite(_parentInstallers1);
Assert.False(actual);
}
[Test]
public void TestValidateAsCompositeWithCompositeInstallerAndParentCircularRefDeep()
{
var installer1 = new TestCompositeInstaller();
var installer2 = new TestCompositeInstaller();
var installer3 = new TestCompositeInstaller();
installer1._leafInstallers = new List<TestInstaller>
{
_dummyInstaller1,
installer2,
_dummyInstaller2,
};
installer2._leafInstallers = new List<TestInstaller>
{
installer3,
};
installer3._leafInstallers = new List<TestInstaller>
{
_compositeInstaller1, // a circular reference
_dummyInstaller3,
};
bool actual = installer1.ValidateAsComposite(_parentInstallers1);
Assert.False(actual);
}
[Test]
public void TestValidateAsCompositeWithCompositeInstallerAndAnotherCircularRef()
{
var installer1 = new TestCompositeInstaller();
var installer2 = new TestCompositeInstaller();
var installer3 = new TestCompositeInstaller();
installer1._leafInstallers = new List<TestInstaller>
{
_dummyInstaller1,
installer2,
_dummyInstaller2,
};
installer2._leafInstallers = new List<TestInstaller>
{
installer3,
};
installer3._leafInstallers = new List<TestInstaller>
{
installer2, // a circular reference
_dummyInstaller3,
};
bool actual = installer1.ValidateAsComposite(_parentInstallers1);
Assert.False(actual);
}
[Test]
public void TestValidateAsCompositeWithCompositeInstallerAndAnotherCircularRefDeep()
{
var installer1 = new TestCompositeInstaller();
var installer2 = new TestCompositeInstaller();
var installer3 = new TestCompositeInstaller();
var installer4 = new TestCompositeInstaller();
var installer5 = new TestCompositeInstaller();
installer1._leafInstallers = new List<TestInstaller>
{
_dummyInstaller1,
installer2,
_dummyInstaller2,
};
installer2._leafInstallers = new List<TestInstaller>
{
installer3,
};
installer3._leafInstallers = new List<TestInstaller>
{
installer4,
_dummyInstaller3,
};
installer4._leafInstallers = new List<TestInstaller>
{
installer5,
};
installer5._leafInstallers = new List<TestInstaller>
{
installer3, // a circular reference
};
bool actual = installer1.ValidateAsComposite(_parentInstallers1);
Assert.False(actual);
}
[Test]
public void TestValidateAsCompositeSavedAllocWithInstaller()
{
var reusableParentInstallers = new List<ICompositeInstaller<TestInstaller>>
{
new TestCompositeInstaller(),
new TestCompositeInstaller(),
new TestCompositeInstaller(),
};
Assert.True(_installer1.ValidateAsCompositeSavedAlloc(reusableParentInstallers));
Assert.AreEqual(3, reusableParentInstallers.Count);
}
[Test]
public void TestValidateAsCompositeSavedAllocWithCompositeInstaller()
{
var reusableParentInstallers = new List<ICompositeInstaller<TestInstaller>>
{
new TestCompositeInstaller(),
new TestCompositeInstaller(),
new TestCompositeInstaller(),
};
Assert.True(_compositeInstaller2.ValidateAsCompositeSavedAlloc(reusableParentInstallers));
Assert.AreEqual(3, reusableParentInstallers.Count);
}
[Test]
public void TestValidateAsCompositeSavedAllocWithCompositeInstallerSelfInParent()
{
var reusableParentInstallers = new List<ICompositeInstaller<TestInstaller>>
{
new TestCompositeInstaller(),
_compositeInstaller1,
new TestCompositeInstaller(),
};
Assert.False(_compositeInstaller1.ValidateAsCompositeSavedAlloc(reusableParentInstallers));
Assert.AreEqual(3, reusableParentInstallers.Count);
}
[Test]
public void TestValidateAsCompositeSavedAllocWithCompositeInstallerParentCircularRef()
{
var reusableParentInstallers = new List<ICompositeInstaller<TestInstaller>>
{
new TestCompositeInstaller(),
_compositeInstaller1,
new TestCompositeInstaller(),
};
Assert.False(_compositeInstaller2.ValidateAsCompositeSavedAlloc(reusableParentInstallers));
Assert.AreEqual(3, reusableParentInstallers.Count);
}
public class TestInstaller : IInstaller
{
public bool IsEnabled => false;
public void InstallBindings() { }
}
public class TestCompositeInstaller : TestInstaller, ICompositeInstaller<TestInstaller>
{
public List<TestInstaller> _leafInstallers;
public IReadOnlyList<TestInstaller> LeafInstallers => _leafInstallers;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Test
{
// a key part of cancellation testing is 'promptness'. Those tests appear in pfxperfunittests.
// the tests here are only regarding basic API correctness and sanity checking.
public static class WithCancellationTests
{
[Fact]
public static void PreCanceledToken_ForAll()
{
OperationCanceledException caughtException = null;
var cs = new CancellationTokenSource();
cs.Cancel();
IEnumerable<int> throwOnFirstEnumerable = Enumerables<int>.ThrowOnEnumeration();
try
{
throwOnFirstEnumerable
.AsParallel()
.WithCancellation(cs.Token)
.ForAll((x) => { Console.WriteLine(x.ToString()); });
}
catch (OperationCanceledException ex)
{
caughtException = ex;
}
Assert.NotNull(caughtException);
Assert.Equal(cs.Token, caughtException.CancellationToken);
}
[Fact]
public static void PreCanceledToken_SimpleEnumerator()
{
OperationCanceledException caughtException = null;
var cs = new CancellationTokenSource();
cs.Cancel();
IEnumerable<int> throwOnFirstEnumerable = Enumerables<int>.ThrowOnEnumeration();
try
{
var query = throwOnFirstEnumerable
.AsParallel()
.WithCancellation(cs.Token);
foreach (var item in query)
{
}
}
catch (OperationCanceledException ex)
{
caughtException = ex;
}
Assert.NotNull(caughtException);
Assert.Equal(cs.Token, caughtException.CancellationToken);
}
[Fact]
public static void MultiplesWithCancellationIsIllegal()
{
InvalidOperationException caughtException = null;
try
{
CancellationTokenSource cs = new CancellationTokenSource();
CancellationToken ct = cs.Token;
var query = Enumerable.Range(1, 10).AsParallel().WithDegreeOfParallelism(2).WithDegreeOfParallelism(2);
query.ToArray();
}
catch (InvalidOperationException ex)
{
caughtException = ex;
//Program.TestHarness.Log("IOE caught. message = " + ex.Message);
}
Assert.NotNull(caughtException);
}
[Fact]
public static void CTT_Sorting_ToArray()
{
int size = 10000;
CancellationTokenSource tokenSource = new CancellationTokenSource();
OperationCanceledException caughtException = null;
try
{
Enumerable.Range(1, size).AsParallel()
.WithCancellation(tokenSource.Token)
.Select(i =>
{
tokenSource.Cancel();
return i;
})
.ToArray();
}
catch (OperationCanceledException ex)
{
caughtException = ex;
}
Assert.NotNull(caughtException);
Assert.Equal(tokenSource.Token, caughtException.CancellationToken);
}
[Fact]
public static void CTT_NonSorting_AsynchronousMergerEnumeratorDispose()
{
int size = 10000;
CancellationTokenSource tokenSource = new CancellationTokenSource();
Exception caughtException = null;
IEnumerator<int> enumerator = null;
ParallelQuery<int> query = null;
query = Enumerable.Range(1, size).AsParallel()
.WithCancellation(tokenSource.Token)
.Select(i =>
{
enumerator.Dispose();
return i;
});
enumerator = query.GetEnumerator();
try
{
for (int j = 0; j < 1000; j++)
{
enumerator.MoveNext();
}
}
catch (Exception ex)
{
caughtException = ex;
}
Assert.NotNull(caughtException);
}
[Fact]
public static void CTT_NonSorting_SynchronousMergerEnumeratorDispose()
{
int size = 10000;
CancellationTokenSource tokenSource = new CancellationTokenSource();
Exception caughtException = null;
IEnumerator<int> enumerator = null;
var query =
Enumerable.Range(1, size).AsParallel()
.WithCancellation(tokenSource.Token)
.Select(
i =>
{
enumerator.Dispose();
return i;
}).WithMergeOptions(ParallelMergeOptions.FullyBuffered);
enumerator = query.GetEnumerator();
try
{
// This query should run for at least a few seconds due to the sleeps in the select-delegate
for (int j = 0; j < 1000; j++)
{
enumerator.MoveNext();
}
}
catch (ObjectDisposedException ex)
{
caughtException = ex;
}
Assert.NotNull(caughtException);
}
/// <summary>
///
/// [Regression Test]
/// This issue occured because the QuerySettings structure was not being deep-cloned during
/// query-opening. As a result, the concurrent inner-enumerators (for the RHS operators)
/// that occur in SelectMany were sharing CancellationState that they should not have.
/// The result was that enumerators could falsely believe they had been canceled when
/// another inner-enumerator was disposed.
///
/// Note: the failure was intermittent. this test would fail about 1 in 2 times on mikelid1 (4-core).
/// </summary>
/// <returns></returns>
[Fact]
public static void CloningQuerySettingsForSelectMany()
{
var plinq_src = ParallelEnumerable.Range(0, 1999).AsParallel();
Exception caughtException = null;
try
{
var inner = ParallelEnumerable.Range(0, 20).AsParallel().Select(_item => _item);
var output = plinq_src
.SelectMany(
_x => inner,
(_x, _y) => _x
)
.ToArray();
}
catch (Exception ex)
{
caughtException = ex;
}
Assert.Null(caughtException);
}
// [Regression Test]
// Use of the async channel can block both the consumer and producer threads.. before the cancellation work
// these had no means of being awoken.
//
// However, only the producers need to wake up on cancellation as the consumer
// will wake up once all the producers have gone away (via AsynchronousOneToOneChannel.SetDone())
//
// To specifically verify this test, we want to know that the Async channels were blocked in TryEnqueChunk before Dispose() is called
// -> this was verified manually, but is not simple to automate
[Fact]
[OuterLoop] // explicit timeouts / delays
public static void ChannelCancellation_ProducerBlocked()
{
Console.WriteLine("PlinqCancellationTests.ChannelCancellation_ProducerBlocked()");
Console.WriteLine(" Query running (should be few seconds max)..");
var query1 = Enumerable.Range(0, 100000000) //provide 100million elements to ensure all the cores get >64K ints. Good up to 1600cores
.AsParallel()
.Select(x => x);
var enumerator1 = query1.GetEnumerator();
enumerator1.MoveNext();
Task.Delay(1000).Wait();
enumerator1.MoveNext();
enumerator1.Dispose(); //can potentially hang
Console.WriteLine(" Done (success).");
}
/// <summary>
/// [Regression Test]
/// This issue occurred because aggregations like Sum or Average would incorrectly
/// wrap OperationCanceledException with AggregateException.
/// </summary>
[Fact]
public static void AggregatesShouldntWrapOCE()
{
var cs = new CancellationTokenSource();
cs.Cancel();
// Expect OperationCanceledException rather than AggregateException or something else
try
{
Enumerable.Range(0, 1000).AsParallel().WithCancellation(cs.Token).Sum(x => x);
}
catch (OperationCanceledException)
{
return;
}
catch (Exception e)
{
Assert.True(false, string.Format("PlinqCancellationTests.AggregatesShouldntWrapOCE: > Failed: got {0}, expected OperationCanceledException", e.GetType().ToString()));
}
Assert.True(false, string.Format("PlinqCancellationTests.AggregatesShouldntWrapOCE: > Failed: no exception occured, expected OperationCanceledException"));
}
// Plinq suppresses OCE(externalCT) occurring in worker threads and then throws a single OCE(ct)
// if a manual OCE(ct) is thrown but ct is not canceled, Plinq should not suppress it, else things
// get confusing...
// ONLY an OCE(ct) for ct.IsCancellationRequested=true is co-operative cancellation
[Fact]
public static void OnlySuppressOCEifCTCanceled()
{
AggregateException caughtException = null;
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken externalToken = cts.Token;
try
{
Enumerable.Range(1, 10).AsParallel()
.WithCancellation(externalToken)
.Select(
x =>
{
if (x % 2 == 0) throw new OperationCanceledException(externalToken);
return x;
}
)
.ToArray();
}
catch (AggregateException ae)
{
caughtException = ae;
}
Assert.NotNull(caughtException);
}
// a specific repro where inner queries would see an ODE on the merged cancellation token source
// when the implementation involved disposing and recreating the token on each worker thread
[Fact]
public static void Cancellation_ODEIssue()
{
AggregateException caughtException = null;
try
{
Enumerable.Range(0, 1999).ToArray()
.AsParallel().AsUnordered()
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.Zip<int, int, int>(
Enumerable.Range(1000, 20).Select<int, int>(_item => (int)_item).AsParallel().AsUnordered(),
(first, second) => { throw new OperationCanceledException(); })
.ForAll(x => { });
}
catch (AggregateException ae)
{
caughtException = ae;
}
//the failure was an ODE coming out due to an ephemeral disposed merged cancellation token source.
Assert.True(caughtException != null,
"Cancellation_ODEIssue: We expect an aggregate exception with OCEs in it.");
}
[Fact]
[OuterLoop] // explicit timeouts / delays
public static void CancellationSequentialWhere()
{
IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue);
CancellationTokenSource tokenSrc = new CancellationTokenSource();
var q = src.AsParallel().WithCancellation(tokenSrc.Token).Where(x => false).TakeWhile(x => true);
Task task = Task.Run(
() =>
{
try
{
foreach (var x in q) { }
Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialWhere: > Failed: OperationCanceledException was not caught."));
}
catch (OperationCanceledException oce)
{
if (oce.CancellationToken != tokenSrc.Token)
{
Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialWhere: > Failed: Wrong cancellation token."));
}
}
}
);
// We wait for 100 ms. If we canceled the token source immediately, the cancellation
// would occur at the query opening time. The goal of this test is to test cancellation
// at query execution time.
Task.Delay(100).Wait();
//Thread.Sleep(100);
tokenSrc.Cancel();
task.Wait();
}
[Fact]
[OuterLoop] // explicit timeouts / delays
public static void CancellationSequentialElementAt()
{
IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue);
CancellationTokenSource tokenSrc = new CancellationTokenSource();
Task task = Task.Run(
() =>
{
try
{
int res = src.AsParallel()
.WithCancellation(tokenSrc.Token)
.Where(x => true)
.TakeWhile(x => true)
.ElementAt(int.MaxValue - 1);
Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialElementAt: > Failed: OperationCanceledException was not caught."));
}
catch (OperationCanceledException oce)
{
Assert.Equal(oce.CancellationToken, tokenSrc.Token);
}
}
);
// We wait for 100 ms. If we canceled the token source immediately, the cancellation
// would occur at the query opening time. The goal of this test is to test cancellation
// at query execution time.
Task.Delay(100).Wait();
tokenSrc.Cancel();
task.Wait();
}
[Fact]
[OuterLoop] // explicit timeouts / delays
public static void CancellationSequentialDistinct()
{
IEnumerable<int> src = Enumerable.Repeat(0, int.MaxValue);
CancellationTokenSource tokenSrc = new CancellationTokenSource();
Task task = Task.Run(
() =>
{
try
{
var q = src.AsParallel()
.WithCancellation(tokenSrc.Token)
.Distinct()
.TakeWhile(x => true);
foreach (var x in q) { }
Assert.True(false, string.Format("PlinqCancellationTests.CancellationSequentialDistinct: > Failed: OperationCanceledException was not caught."));
}
catch (OperationCanceledException oce)
{
Assert.Equal(oce.CancellationToken, tokenSrc.Token);
}
}
);
// We wait for 100 ms. If we canceled the token source immediately, the cancellation
// would occur at the query opening time. The goal of this test is to test cancellation
// at query execution time.
Task.Delay(100).Wait();
tokenSrc.Cancel();
task.Wait();
}
// Regression test for an issue causing ODE if a queryEnumerator is disposed before moveNext is called.
[Fact]
public static void ImmediateDispose()
{
var queryEnumerator = Enumerable.Range(1, 10).AsParallel().Select(x => x).GetEnumerator();
queryEnumerator.Dispose();
}
// REPRO 1 -- cancellation
[Fact]
public static void SetOperationsThrowAggregateOnCancelOrDispose_1()
{
CancellationTokenSource cs = new CancellationTokenSource();
var plinq_src =
Enumerable.Range(0, 5000000).Select(x =>
{
cs.Cancel();
return x;
});
try
{
var plinq = plinq_src
.AsParallel().WithCancellation(cs.Token)
.WithDegreeOfParallelism(1)
.Union(Enumerable.Range(0, 10).AsParallel());
var walker = plinq.GetEnumerator();
while (walker.MoveNext())
{
var item = walker.Current;
}
Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_1: OperationCanceledException was expected, but no exception occured."));
}
catch (OperationCanceledException)
{
//This is expected.
}
catch (Exception e)
{
Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_1: OperationCanceledException was expected, but a different exception occured. " + e.ToString()));
}
}
// throwing a fake OCE(ct) when the ct isn't canceled should produce an AggregateException.
[Fact]
public static void SetOperationsThrowAggregateOnCancelOrDispose_2()
{
try
{
CancellationTokenSource cs = new CancellationTokenSource();
var plinq = Enumerable.Range(0, 50)
.AsParallel().WithCancellation(cs.Token)
.WithDegreeOfParallelism(1)
.Union(Enumerable.Range(0, 10).AsParallel().Select<int, int>(x => { throw new OperationCanceledException(cs.Token); }));
var walker = plinq.GetEnumerator();
while (walker.MoveNext())
{
}
Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_2: failed. AggregateException was expected, but no exception occured."));
}
catch (AggregateException)
{
// expected
}
catch (Exception e)
{
Assert.True(false, string.Format("PlinqCancellationTests.SetOperationsThrowAggregateOnCancelOrDispose_2. failed. AggregateException was expected, but some other exception occured." + e.ToString()));
}
}
// Changes made to hash-partitioning (April'09) lost the cancellation checks during the
// main repartitioning loop (matrix building).
[Fact]
public static void HashPartitioningCancellation()
{
OperationCanceledException caughtException = null;
CancellationTokenSource cs = new CancellationTokenSource();
//Without ordering
var queryUnordered = Enumerable.Range(0, int.MaxValue)
.Select(x => { if (x == 0) cs.Cancel(); return x; })
.AsParallel()
.WithCancellation(cs.Token)
.Intersect(Enumerable.Range(0, 1000000).AsParallel());
try
{
foreach (var item in queryUnordered)
{
}
}
catch (OperationCanceledException oce)
{
caughtException = oce;
}
Assert.NotNull(caughtException);
caughtException = null;
//With ordering
var queryOrdered = Enumerable.Range(0, int.MaxValue)
.Select(x => { if (x == 0) cs.Cancel(); return x; })
.AsParallel().AsOrdered()
.WithCancellation(cs.Token)
.Intersect(Enumerable.Range(0, 1000000).AsParallel());
try
{
foreach (var item in queryOrdered)
{
}
}
catch (OperationCanceledException oce)
{
caughtException = oce;
}
Assert.NotNull(caughtException);
}
// If a query is cancelled and immediately disposed, the dispose should not throw an OCE.
[Fact]
public static void CancelThenDispose()
{
try
{
CancellationTokenSource cancel = new CancellationTokenSource();
var q = ParallelEnumerable.Range(0, 1000).WithCancellation(cancel.Token).Select(x => x);
IEnumerator<int> e = q.GetEnumerator();
e.MoveNext();
cancel.Cancel();
e.Dispose();
}
catch (Exception e)
{
Assert.True(false, string.Format("PlinqCancellationTests.CancelThenDispose: > Failed. Expected no exception, got " + e.GetType()));
}
}
[Fact]
public static void DontDoWorkIfTokenAlreadyCanceled()
{
OperationCanceledException oce = null;
CancellationTokenSource cs = new CancellationTokenSource();
var query = Enumerable.Range(0, 100000000)
.Select(x =>
{
if (x > 0) // to avoid the "Error:unreachable code detected"
throw new ArgumentException("User-delegate exception.");
return x;
})
.AsParallel()
.WithCancellation(cs.Token)
.Select(x => x);
cs.Cancel();
try
{
foreach (var item in query) //We expect an OperationCancelledException during the MoveNext
{
}
}
catch (OperationCanceledException ex)
{
oce = ex;
}
Assert.NotNull(oce);
}
// To help the user, we will check if a cancellation token passed to WithCancellation() is
// not backed by a disposed CTS. This will help them identify incorrect cts.Dispose calls, but
// doesn't solve all their problems if they don't manage CTS lifetime correctly.
// We test via a few random queries that have shown inconsistent behavior in the past.
[Fact]
public static void PreDisposedCTSPassedToPlinq()
{
ArgumentException ae1 = null;
ArgumentException ae2 = null;
ArgumentException ae3 = null;
CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken ct = cts.Token;
cts.Dispose(); // Early dispose
try
{
Enumerable.Range(1, 10).AsParallel()
.WithCancellation(ct)
.OrderBy(x => x)
.ToArray();
}
catch (Exception ex)
{
// This is not going to be the case since we changed the behavior of WithCancellation
// to not throw when called on disposed cancellationtokens.
ae1 = (ArgumentException)ex;
}
try
{
Enumerable.Range(1, 10).AsParallel()
.WithCancellation(ct)
.Last();
}
catch (Exception ex)
{
// This is not going to be the case since we changed the behavior of WithCancellation
// to not throw when called on disposed cancellationtokens.
ae2 = (ArgumentException)ex;
}
try
{
Enumerable.Range(1, 10).AsParallel()
.WithCancellation(ct)
.OrderBy(x => x)
.Last();
}
catch (Exception ex)
{
// This is not going to be the case since we changed the behavior of WithCancellation
// to not throw when called on disposed cancellationtokens.
ae3 = (ArgumentException)ex;
}
Assert.Null(ae1);
Assert.Null(ae2);
Assert.Null(ae3);
}
public static void SimulateThreadSleep(int milliseconds)
{
ManualResetEvent mre = new ManualResetEvent(false);
mre.WaitOne(milliseconds);
}
}
}
| |
// 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.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace Windows.UI.Xaml
{
public partial struct CornerRadius
{
private int _dummyPrimitive;
public CornerRadius(double uniformRadius) { throw null; }
public CornerRadius(double topLeft, double topRight, double bottomRight, double bottomLeft) { throw null; }
public double BottomLeft { get { throw null; } set { } }
public double BottomRight { get { throw null; } set { } }
public double TopLeft { get { throw null; } set { } }
public double TopRight { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public bool Equals(Windows.UI.Xaml.CornerRadius cornerRadius) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Windows.UI.Xaml.CornerRadius cr1, Windows.UI.Xaml.CornerRadius cr2) { throw null; }
public static bool operator !=(Windows.UI.Xaml.CornerRadius cr1, Windows.UI.Xaml.CornerRadius cr2) { throw null; }
public override string ToString() { throw null; }
}
public partial struct Duration
{
private int _dummyPrimitive;
public Duration(System.TimeSpan timeSpan) { throw null; }
public static Windows.UI.Xaml.Duration Automatic { get { throw null; } }
public static Windows.UI.Xaml.Duration Forever { get { throw null; } }
public bool HasTimeSpan { get { throw null; } }
public System.TimeSpan TimeSpan { get { throw null; } }
public Windows.UI.Xaml.Duration Add(Windows.UI.Xaml.Duration duration) { throw null; }
public static int Compare(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public override bool Equals(object value) { throw null; }
public bool Equals(Windows.UI.Xaml.Duration duration) { throw null; }
public static bool Equals(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public override int GetHashCode() { throw null; }
public static Windows.UI.Xaml.Duration operator +(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public static bool operator ==(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public static bool operator >(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public static bool operator >=(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public static implicit operator Windows.UI.Xaml.Duration (System.TimeSpan timeSpan) { throw null; }
public static bool operator !=(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public static bool operator <(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public static bool operator <=(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public static Windows.UI.Xaml.Duration operator -(Windows.UI.Xaml.Duration t1, Windows.UI.Xaml.Duration t2) { throw null; }
public static Windows.UI.Xaml.Duration operator +(Windows.UI.Xaml.Duration duration) { throw null; }
public Windows.UI.Xaml.Duration Subtract(Windows.UI.Xaml.Duration duration) { throw null; }
public override string ToString() { throw null; }
}
public enum DurationType
{
Automatic = 0,
TimeSpan = 1,
Forever = 2,
}
public partial struct GridLength
{
private int _dummyPrimitive;
public GridLength(double pixels) { throw null; }
public GridLength(double value, Windows.UI.Xaml.GridUnitType type) { throw null; }
public static Windows.UI.Xaml.GridLength Auto { get { throw null; } }
public Windows.UI.Xaml.GridUnitType GridUnitType { get { throw null; } }
public bool IsAbsolute { get { throw null; } }
public bool IsAuto { get { throw null; } }
public bool IsStar { get { throw null; } }
public double Value { get { throw null; } }
public override bool Equals(object oCompare) { throw null; }
public bool Equals(Windows.UI.Xaml.GridLength gridLength) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Windows.UI.Xaml.GridLength gl1, Windows.UI.Xaml.GridLength gl2) { throw null; }
public static bool operator !=(Windows.UI.Xaml.GridLength gl1, Windows.UI.Xaml.GridLength gl2) { throw null; }
public override string ToString() { throw null; }
}
public enum GridUnitType
{
Auto = 0,
Pixel = 1,
Star = 2,
}
public partial class LayoutCycleException : System.Exception
{
public LayoutCycleException() { }
protected LayoutCycleException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
public LayoutCycleException(string message) { }
public LayoutCycleException(string message, System.Exception innerException) { }
}
public partial struct Thickness
{
private int _dummyPrimitive;
public Thickness(double uniformLength) { throw null; }
public Thickness(double left, double top, double right, double bottom) { throw null; }
public double Bottom { get { throw null; } set { } }
public double Left { get { throw null; } set { } }
public double Right { get { throw null; } set { } }
public double Top { get { throw null; } set { } }
public override bool Equals(object obj) { throw null; }
public bool Equals(Windows.UI.Xaml.Thickness thickness) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Windows.UI.Xaml.Thickness t1, Windows.UI.Xaml.Thickness t2) { throw null; }
public static bool operator !=(Windows.UI.Xaml.Thickness t1, Windows.UI.Xaml.Thickness t2) { throw null; }
public override string ToString() { throw null; }
}
}
namespace Windows.UI.Xaml.Automation
{
public partial class ElementNotAvailableException : System.Exception
{
public ElementNotAvailableException() { }
protected ElementNotAvailableException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
public ElementNotAvailableException(string message) { }
public ElementNotAvailableException(string message, System.Exception innerException) { }
}
public partial class ElementNotEnabledException : System.Exception
{
public ElementNotEnabledException() { }
public ElementNotEnabledException(string message) { }
public ElementNotEnabledException(string message, System.Exception innerException) { }
}
}
namespace Windows.UI.Xaml.Controls.Primitives
{
public partial struct GeneratorPosition
{
private int _dummyPrimitive;
public GeneratorPosition(int index, int offset) { throw null; }
public int Index { get { throw null; } set { } }
public int Offset { get { throw null; } set { } }
public override bool Equals(object o) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp1, Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp2) { throw null; }
public static bool operator !=(Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp1, Windows.UI.Xaml.Controls.Primitives.GeneratorPosition gp2) { throw null; }
public override string ToString() { throw null; }
}
}
namespace Windows.UI.Xaml.Markup
{
public partial class XamlParseException : System.Exception
{
public XamlParseException() { }
public XamlParseException(string message) { }
public XamlParseException(string message, System.Exception innerException) { }
}
}
namespace Windows.UI.Xaml.Media
{
public partial struct Matrix : System.IFormattable
{
private int _dummyPrimitive;
public Matrix(double m11, double m12, double m21, double m22, double offsetX, double offsetY) { throw null; }
public static Windows.UI.Xaml.Media.Matrix Identity { get { throw null; } }
public bool IsIdentity { get { throw null; } }
public double M11 { get { throw null; } set { } }
public double M12 { get { throw null; } set { } }
public double M21 { get { throw null; } set { } }
public double M22 { get { throw null; } set { } }
public double OffsetX { get { throw null; } set { } }
public double OffsetY { get { throw null; } set { } }
public override bool Equals(object o) { throw null; }
public bool Equals(Windows.UI.Xaml.Media.Matrix value) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Windows.UI.Xaml.Media.Matrix matrix1, Windows.UI.Xaml.Media.Matrix matrix2) { throw null; }
public static bool operator !=(Windows.UI.Xaml.Media.Matrix matrix1, Windows.UI.Xaml.Media.Matrix matrix2) { throw null; }
string System.IFormattable.ToString(string format, System.IFormatProvider provider) { throw null; }
public override string ToString() { throw null; }
public string ToString(System.IFormatProvider provider) { throw null; }
public Windows.Foundation.Point Transform(Windows.Foundation.Point point) { throw null; }
}
}
namespace Windows.UI.Xaml.Media.Animation
{
public partial struct KeyTime
{
private int _dummyPrimitive;
public System.TimeSpan TimeSpan { get { throw null; } }
public override bool Equals(object value) { throw null; }
public bool Equals(Windows.UI.Xaml.Media.Animation.KeyTime value) { throw null; }
public static bool Equals(Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { throw null; }
public static Windows.UI.Xaml.Media.Animation.KeyTime FromTimeSpan(System.TimeSpan timeSpan) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { throw null; }
public static implicit operator Windows.UI.Xaml.Media.Animation.KeyTime (System.TimeSpan timeSpan) { throw null; }
public static bool operator !=(Windows.UI.Xaml.Media.Animation.KeyTime keyTime1, Windows.UI.Xaml.Media.Animation.KeyTime keyTime2) { throw null; }
public override string ToString() { throw null; }
}
public partial struct RepeatBehavior : System.IFormattable
{
private int _dummyPrimitive;
public RepeatBehavior(double count) { throw null; }
public RepeatBehavior(System.TimeSpan duration) { throw null; }
public double Count { get { throw null; } set { } }
public System.TimeSpan Duration { get { throw null; } set { } }
public static Windows.UI.Xaml.Media.Animation.RepeatBehavior Forever { get { throw null; } }
public bool HasCount { get { throw null; } }
public bool HasDuration { get { throw null; } }
public Windows.UI.Xaml.Media.Animation.RepeatBehaviorType Type { get { throw null; } set { } }
public override bool Equals(object value) { throw null; }
public bool Equals(Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior) { throw null; }
public static bool Equals(Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { throw null; }
public override int GetHashCode() { throw null; }
public static bool operator ==(Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { throw null; }
public static bool operator !=(Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior1, Windows.UI.Xaml.Media.Animation.RepeatBehavior repeatBehavior2) { throw null; }
string System.IFormattable.ToString(string format, System.IFormatProvider formatProvider) { throw null; }
public override string ToString() { throw null; }
public string ToString(System.IFormatProvider formatProvider) { throw null; }
}
public enum RepeatBehaviorType
{
Count = 0,
Duration = 1,
Forever = 2,
}
}
namespace Windows.UI.Xaml.Media.Media3D
{
public partial struct Matrix3D : System.IFormattable
{
private int _dummyPrimitive;
public Matrix3D(double m11, double m12, double m13, double m14, double m21, double m22, double m23, double m24, double m31, double m32, double m33, double m34, double offsetX, double offsetY, double offsetZ, double m44) { throw null; }
public bool HasInverse { get { throw null; } }
public static Windows.UI.Xaml.Media.Media3D.Matrix3D Identity { get { throw null; } }
public bool IsIdentity { get { throw null; } }
public double M11 { get { throw null; } set { } }
public double M12 { get { throw null; } set { } }
public double M13 { get { throw null; } set { } }
public double M14 { get { throw null; } set { } }
public double M21 { get { throw null; } set { } }
public double M22 { get { throw null; } set { } }
public double M23 { get { throw null; } set { } }
public double M24 { get { throw null; } set { } }
public double M31 { get { throw null; } set { } }
public double M32 { get { throw null; } set { } }
public double M33 { get { throw null; } set { } }
public double M34 { get { throw null; } set { } }
public double M44 { get { throw null; } set { } }
public double OffsetX { get { throw null; } set { } }
public double OffsetY { get { throw null; } set { } }
public double OffsetZ { get { throw null; } set { } }
public override bool Equals(object o) { throw null; }
public bool Equals(Windows.UI.Xaml.Media.Media3D.Matrix3D value) { throw null; }
public override int GetHashCode() { throw null; }
public void Invert() { }
public static bool operator ==(Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { throw null; }
public static bool operator !=(Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { throw null; }
public static Windows.UI.Xaml.Media.Media3D.Matrix3D operator *(Windows.UI.Xaml.Media.Media3D.Matrix3D matrix1, Windows.UI.Xaml.Media.Media3D.Matrix3D matrix2) { throw null; }
string System.IFormattable.ToString(string format, System.IFormatProvider provider) { throw null; }
public override string ToString() { throw null; }
public string ToString(System.IFormatProvider provider) { throw null; }
}
}
| |
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved.
* Use of this file is governed by the BSD 3-clause license that
* can be found in the LICENSE.txt file in the project root.
*/
using System;
using System.Collections.Generic;
using System.Text;
using erl.Oracle.TnsNames.Antlr4.Runtime;
using erl.Oracle.TnsNames.Antlr4.Runtime.Misc;
using erl.Oracle.TnsNames.Antlr4.Runtime.Sharpen;
using erl.Oracle.TnsNames.Antlr4.Runtime.Tree;
using erl.Oracle.TnsNames.Antlr4.Runtime.Tree.Pattern;
namespace erl.Oracle.TnsNames.Antlr4.Runtime.Tree.Pattern
{
/// <summary>
/// A tree pattern matching mechanism for ANTLR
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree"/>
/// s.
/// <p>Patterns are strings of source input text with special tags representing
/// token or rule references such as:</p>
/// <p>
/// <c><ID> = <expr>;</c>
/// </p>
/// <p>Given a pattern start rule such as
/// <c>statement</c>
/// , this object constructs
/// a
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree"/>
/// with placeholders for the
/// <c>ID</c>
/// and
/// <c>expr</c>
/// subtree. Then the
/// <see cref="Match(erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree, ParseTreePattern)"/>
/// routines can compare an actual
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree"/>
/// from a parse with this pattern. Tag
/// <c><ID></c>
/// matches
/// any
/// <c>ID</c>
/// token and tag
/// <c><expr></c>
/// references the result of the
/// <c>expr</c>
/// rule (generally an instance of
/// <c>ExprContext</c>
/// .</p>
/// <p>Pattern
/// <c>x = 0;</c>
/// is a similar pattern that matches the same pattern
/// except that it requires the identifier to be
/// <c>x</c>
/// and the expression to
/// be
/// <c>0</c>
/// .</p>
/// <p>The
/// <see cref="Matches(erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree, ParseTreePattern)"/>
/// routines return
/// <see langword="true"/>
/// or
/// <see langword="false"/>
/// based
/// upon a match for the tree rooted at the parameter sent in. The
/// <see cref="Match(erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree, ParseTreePattern)"/>
/// routines return a
/// <see cref="ParseTreeMatch"/>
/// object that
/// contains the parse tree, the parse tree pattern, and a map from tag name to
/// matched nodes (more below). A subtree that fails to match, returns with
/// <see cref="ParseTreeMatch.MismatchedNode"/>
/// set to the first tree node that did not
/// match.</p>
/// <p>For efficiency, you can compile a tree pattern in string form to a
/// <see cref="ParseTreePattern"/>
/// object.</p>
/// <p>See
/// <c>TestParseTreeMatcher</c>
/// for lots of examples.
/// <see cref="ParseTreePattern"/>
/// has two static helper methods:
/// <see cref="ParseTreePattern.FindAll(erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree, string)"/>
/// and
/// <see cref="ParseTreePattern.Match(erl.Oracle.TnsNames.Antlr4.Runtime.Tree.IParseTree)"/>
/// that
/// are easy to use but not super efficient because they create new
/// <see cref="ParseTreePatternMatcher"/>
/// objects each time and have to compile the
/// pattern in string form before using it.</p>
/// <p>The lexer and parser that you pass into the
/// <see cref="ParseTreePatternMatcher"/>
/// constructor are used to parse the pattern in string form. The lexer converts
/// the
/// <c><ID> = <expr>;</c>
/// into a sequence of four tokens (assuming lexer
/// throws out whitespace or puts it on a hidden channel). Be aware that the
/// input stream is reset for the lexer (but not the parser; a
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.ParserInterpreter"/>
/// is created to parse the input.). Any user-defined
/// fields you have put into the lexer might get changed when this mechanism asks
/// it to scan the pattern string.</p>
/// <p>Normally a parser does not accept token
/// <c><expr></c>
/// as a valid
/// <c>expr</c>
/// but, from the parser passed in, we create a special version of
/// the underlying grammar representation (an
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Atn.ATN"/>
/// ) that allows imaginary
/// tokens representing rules (
/// <c><expr></c>
/// ) to match entire rules. We call
/// these <em>bypass alternatives</em>.</p>
/// <p>Delimiters are
/// <c><</c>
/// and
/// <c>></c>
/// , with
/// <c>\</c>
/// as the escape string
/// by default, but you can set them to whatever you want using
/// <see cref="SetDelimiters(string, string, string)"/>
/// . You must escape both start and stop strings
/// <c>\<</c>
/// and
/// <c>\></c>
/// .</p>
/// </summary>
public class ParseTreePatternMatcher
{
[System.Serializable]
public class CannotInvokeStartRule : Exception
{
public CannotInvokeStartRule(Exception e)
: base(e.Message, e)
{
}
}
[System.Serializable]
public class StartRuleDoesNotConsumeFullPattern : Exception
{
// Fixes https://github.com/antlr/antlr4/issues/413
// "Tree pattern compilation doesn't check for a complete parse"
}
/// <summary>
/// This is the backing field for
/// <see cref="Lexer()"/>
/// .
/// </summary>
private readonly Lexer lexer;
/// <summary>
/// This is the backing field for
/// <see cref="Parser()"/>
/// .
/// </summary>
private readonly Parser parser;
protected internal string start = "<";
protected internal string stop = ">";
protected internal string escape = "\\";
/// <summary>
/// Constructs a
/// <see cref="ParseTreePatternMatcher"/>
/// or from a
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Lexer"/>
/// and
/// <see cref="erl.Oracle.TnsNames.Antlr4.Runtime.Parser"/>
/// object. The lexer input stream is altered for tokenizing
/// the tree patterns. The parser is used as a convenient mechanism to get
/// the grammar name, plus token, rule names.
/// </summary>
public ParseTreePatternMatcher(Lexer lexer, Parser parser)
{
// e.g., \< and \> must escape BOTH!
this.lexer = lexer;
this.parser = parser;
}
/// <summary>
/// Set the delimiters used for marking rule and token tags within concrete
/// syntax used by the tree pattern parser.
/// </summary>
/// <remarks>
/// Set the delimiters used for marking rule and token tags within concrete
/// syntax used by the tree pattern parser.
/// </remarks>
/// <param name="start">The start delimiter.</param>
/// <param name="stop">The stop delimiter.</param>
/// <param name="escapeLeft">The escape sequence to use for escaping a start or stop delimiter.</param>
/// <exception>
/// IllegalArgumentException
/// if
/// <paramref name="start"/>
/// is
/// <see langword="null"/>
/// or empty.
/// </exception>
/// <exception>
/// IllegalArgumentException
/// if
/// <paramref name="stop"/>
/// is
/// <see langword="null"/>
/// or empty.
/// </exception>
public virtual void SetDelimiters(string start, string stop, string escapeLeft)
{
if (string.IsNullOrEmpty(start))
{
throw new ArgumentException("start cannot be null or empty");
}
if (string.IsNullOrEmpty(stop))
{
throw new ArgumentException("stop cannot be null or empty");
}
this.start = start;
this.stop = stop;
this.escape = escapeLeft;
}
/// <summary>
/// Does
/// <paramref name="pattern"/>
/// matched as rule
/// <paramref name="patternRuleIndex"/>
/// match
/// <paramref name="tree"/>
/// ?
/// </summary>
public virtual bool Matches(IParseTree tree, string pattern, int patternRuleIndex)
{
ParseTreePattern p = Compile(pattern, patternRuleIndex);
return Matches(tree, p);
}
/// <summary>
/// Does
/// <paramref name="pattern"/>
/// matched as rule patternRuleIndex match tree? Pass in a
/// compiled pattern instead of a string representation of a tree pattern.
/// </summary>
public virtual bool Matches(IParseTree tree, ParseTreePattern pattern)
{
MultiMap<string, IParseTree> labels = new MultiMap<string, IParseTree>();
IParseTree mismatchedNode = MatchImpl(tree, pattern.PatternTree, labels);
return mismatchedNode == null;
}
/// <summary>
/// Compare
/// <paramref name="pattern"/>
/// matched as rule
/// <paramref name="patternRuleIndex"/>
/// against
/// <paramref name="tree"/>
/// and return a
/// <see cref="ParseTreeMatch"/>
/// object that contains the
/// matched elements, or the node at which the match failed.
/// </summary>
public virtual ParseTreeMatch Match(IParseTree tree, string pattern, int patternRuleIndex)
{
ParseTreePattern p = Compile(pattern, patternRuleIndex);
return Match(tree, p);
}
/// <summary>
/// Compare
/// <paramref name="pattern"/>
/// matched against
/// <paramref name="tree"/>
/// and return a
/// <see cref="ParseTreeMatch"/>
/// object that contains the matched elements, or the
/// node at which the match failed. Pass in a compiled pattern instead of a
/// string representation of a tree pattern.
/// </summary>
[return: NotNull]
public virtual ParseTreeMatch Match(IParseTree tree, ParseTreePattern pattern)
{
MultiMap<string, IParseTree> labels = new MultiMap<string, IParseTree>();
IParseTree mismatchedNode = MatchImpl(tree, pattern.PatternTree, labels);
return new ParseTreeMatch(tree, pattern, labels, mismatchedNode);
}
/// <summary>
/// For repeated use of a tree pattern, compile it to a
/// <see cref="ParseTreePattern"/>
/// using this method.
/// </summary>
public virtual ParseTreePattern Compile(string pattern, int patternRuleIndex)
{
IList<IToken> tokenList = Tokenize(pattern);
ListTokenSource tokenSrc = new ListTokenSource(tokenList);
CommonTokenStream tokens = new CommonTokenStream(tokenSrc);
ParserInterpreter parserInterp = new ParserInterpreter(parser.GrammarFileName, parser.Vocabulary, Arrays.AsList(parser.RuleNames), parser.GetATNWithBypassAlts(), tokens);
IParseTree tree = null;
try
{
parserInterp.ErrorHandler = new BailErrorStrategy();
tree = parserInterp.Parse(patternRuleIndex);
}
catch (ParseCanceledException e)
{
// System.out.println("pattern tree = "+tree.toStringTree(parserInterp));
throw (RecognitionException)e.InnerException;
}
catch (RecognitionException)
{
throw;
}
catch (Exception e)
{
throw new ParseTreePatternMatcher.CannotInvokeStartRule(e);
}
// Make sure tree pattern compilation checks for a complete parse
if (tokens.LA(1) != TokenConstants.EOF)
{
throw new ParseTreePatternMatcher.StartRuleDoesNotConsumeFullPattern();
}
return new ParseTreePattern(this, pattern, patternRuleIndex, tree);
}
/// <summary>Used to convert the tree pattern string into a series of tokens.</summary>
/// <remarks>
/// Used to convert the tree pattern string into a series of tokens. The
/// input stream is reset.
/// </remarks>
[NotNull]
public virtual Lexer Lexer
{
get
{
return lexer;
}
}
/// <summary>
/// Used to collect to the grammar file name, token names, rule names for
/// used to parse the pattern into a parse tree.
/// </summary>
/// <remarks>
/// Used to collect to the grammar file name, token names, rule names for
/// used to parse the pattern into a parse tree.
/// </remarks>
[NotNull]
public virtual Parser Parser
{
get
{
return parser;
}
}
// ---- SUPPORT CODE ----
/// <summary>
/// Recursively walk
/// <paramref name="tree"/>
/// against
/// <paramref name="patternTree"/>
/// , filling
/// <c>match.</c>
/// <see cref="ParseTreeMatch.Labels"/>
/// .
/// </summary>
/// <returns>
/// the first node encountered in
/// <paramref name="tree"/>
/// which does not match
/// a corresponding node in
/// <paramref name="patternTree"/>
/// , or
/// <see langword="null"/>
/// if the match
/// was successful. The specific node returned depends on the matching
/// algorithm used by the implementation, and may be overridden.
/// </returns>
[return: Nullable]
protected internal virtual IParseTree MatchImpl(IParseTree tree, IParseTree patternTree, MultiMap<string, IParseTree> labels)
{
if (tree == null)
{
throw new ArgumentException("tree cannot be null");
}
if (patternTree == null)
{
throw new ArgumentException("patternTree cannot be null");
}
// x and <ID>, x and y, or x and x; or could be mismatched types
if (tree is ITerminalNode && patternTree is ITerminalNode)
{
ITerminalNode t1 = (ITerminalNode)tree;
ITerminalNode t2 = (ITerminalNode)patternTree;
IParseTree mismatchedNode = null;
// both are tokens and they have same type
if (t1.Symbol.Type == t2.Symbol.Type)
{
if (t2.Symbol is TokenTagToken)
{
// x and <ID>
TokenTagToken tokenTagToken = (TokenTagToken)t2.Symbol;
// track label->list-of-nodes for both token name and label (if any)
labels.Map(tokenTagToken.TokenName, tree);
if (tokenTagToken.Label != null)
{
labels.Map(tokenTagToken.Label, tree);
}
}
else
{
if (t1.GetText().Equals(t2.GetText(), StringComparison.Ordinal))
{
}
else
{
// x and x
// x and y
if (mismatchedNode == null)
{
mismatchedNode = t1;
}
}
}
}
else
{
if (mismatchedNode == null)
{
mismatchedNode = t1;
}
}
return mismatchedNode;
}
if (tree is ParserRuleContext && patternTree is ParserRuleContext)
{
ParserRuleContext r1 = (ParserRuleContext)tree;
ParserRuleContext r2 = (ParserRuleContext)patternTree;
IParseTree mismatchedNode = null;
// (expr ...) and <expr>
RuleTagToken ruleTagToken = GetRuleTagToken(r2);
if (ruleTagToken != null)
{
if (r1.RuleIndex == r2.RuleIndex)
{
// track label->list-of-nodes for both rule name and label (if any)
labels.Map(ruleTagToken.RuleName, tree);
if (ruleTagToken.Label != null)
{
labels.Map(ruleTagToken.Label, tree);
}
}
else
{
if (mismatchedNode == null)
{
mismatchedNode = r1;
}
}
return mismatchedNode;
}
// (expr ...) and (expr ...)
if (r1.ChildCount != r2.ChildCount)
{
if (mismatchedNode == null)
{
mismatchedNode = r1;
}
return mismatchedNode;
}
int n = r1.ChildCount;
for (int i = 0; i < n; i++)
{
IParseTree childMatch = MatchImpl(r1.GetChild(i), patternTree.GetChild(i), labels);
if (childMatch != null)
{
return childMatch;
}
}
return mismatchedNode;
}
// if nodes aren't both tokens or both rule nodes, can't match
return tree;
}
/// <summary>
/// Is
/// <paramref name="t"/>
///
/// <c>(expr <expr>)</c>
/// subtree?
/// </summary>
protected internal virtual RuleTagToken GetRuleTagToken(IParseTree t)
{
if (t is IRuleNode)
{
IRuleNode r = (IRuleNode)t;
if (r.ChildCount == 1 && r.GetChild(0) is ITerminalNode)
{
ITerminalNode c = (ITerminalNode)r.GetChild(0);
if (c.Symbol is RuleTagToken)
{
// System.out.println("rule tag subtree "+t.toStringTree(parser));
return (RuleTagToken)c.Symbol;
}
}
}
return null;
}
public virtual IList<IToken> Tokenize(string pattern)
{
// split pattern into chunks: sea (raw input) and islands (<ID>, <expr>)
IList<Chunk> chunks = Split(pattern);
// create token stream from text and tags
IList<IToken> tokens = new List<IToken>();
foreach (Chunk chunk in chunks)
{
if (chunk is TagChunk)
{
TagChunk tagChunk = (TagChunk)chunk;
// add special rule token or conjure up new token from name
if (System.Char.IsUpper(tagChunk.Tag[0]))
{
int ttype = parser.GetTokenType(tagChunk.Tag);
if (ttype == TokenConstants.InvalidType)
{
throw new ArgumentException("Unknown token " + tagChunk.Tag + " in pattern: " + pattern);
}
TokenTagToken t = new TokenTagToken(tagChunk.Tag, ttype, tagChunk.Label);
tokens.Add(t);
}
else
{
if (System.Char.IsLower(tagChunk.Tag[0]))
{
int ruleIndex = parser.GetRuleIndex(tagChunk.Tag);
if (ruleIndex == -1)
{
throw new ArgumentException("Unknown rule " + tagChunk.Tag + " in pattern: " + pattern);
}
int ruleImaginaryTokenType = parser.GetATNWithBypassAlts().ruleToTokenType[ruleIndex];
tokens.Add(new RuleTagToken(tagChunk.Tag, ruleImaginaryTokenType, tagChunk.Label));
}
else
{
throw new ArgumentException("invalid tag: " + tagChunk.Tag + " in pattern: " + pattern);
}
}
}
else
{
TextChunk textChunk = (TextChunk)chunk;
AntlrInputStream @in = new AntlrInputStream(textChunk.Text);
lexer.SetInputStream(@in);
IToken t = lexer.NextToken();
while (t.Type != TokenConstants.EOF)
{
tokens.Add(t);
t = lexer.NextToken();
}
}
}
// System.out.println("tokens="+tokens);
return tokens;
}
/// <summary>
/// Split
/// <c><ID> = <e:expr> ;</c>
/// into 4 chunks for tokenizing by
/// <see cref="Tokenize(string)"/>
/// .
/// </summary>
internal virtual IList<Chunk> Split(string pattern)
{
int p = 0;
int n = pattern.Length;
IList<Chunk> chunks = new List<Chunk>();
// find all start and stop indexes first, then collect
IList<int> starts = new List<int>();
IList<int> stops = new List<int>();
while (p < n)
{
if (p == pattern.IndexOf(escape + start, p))
{
p += escape.Length + start.Length;
}
else
{
if (p == pattern.IndexOf(escape + stop, p))
{
p += escape.Length + stop.Length;
}
else
{
if (p == pattern.IndexOf(start, p))
{
starts.Add(p);
p += start.Length;
}
else
{
if (p == pattern.IndexOf(stop, p))
{
stops.Add(p);
p += stop.Length;
}
else
{
p++;
}
}
}
}
}
// System.out.println("");
// System.out.println(starts);
// System.out.println(stops);
if (starts.Count > stops.Count)
{
throw new ArgumentException("unterminated tag in pattern: " + pattern);
}
if (starts.Count < stops.Count)
{
throw new ArgumentException("missing start tag in pattern: " + pattern);
}
int ntags = starts.Count;
for (int i = 0; i < ntags; i++)
{
if (starts[i] >= stops[i])
{
throw new ArgumentException("tag delimiters out of order in pattern: " + pattern);
}
}
// collect into chunks now
if (ntags == 0)
{
string text = Sharpen.Runtime.Substring(pattern, 0, n);
chunks.Add(new TextChunk(text));
}
if (ntags > 0 && starts[0] > 0)
{
// copy text up to first tag into chunks
string text = Sharpen.Runtime.Substring(pattern, 0, starts[0]);
chunks.Add(new TextChunk(text));
}
for (int i_1 = 0; i_1 < ntags; i_1++)
{
// copy inside of <tag>
string tag = Sharpen.Runtime.Substring(pattern, starts[i_1] + start.Length, stops[i_1]);
string ruleOrToken = tag;
string label = null;
int colon = tag.IndexOf(':');
if (colon >= 0)
{
label = Sharpen.Runtime.Substring(tag, 0, colon);
ruleOrToken = Sharpen.Runtime.Substring(tag, colon + 1, tag.Length);
}
chunks.Add(new TagChunk(label, ruleOrToken));
if (i_1 + 1 < ntags)
{
// copy from end of <tag> to start of next
string text = Sharpen.Runtime.Substring(pattern, stops[i_1] + stop.Length, starts[i_1 + 1]);
chunks.Add(new TextChunk(text));
}
}
if (ntags > 0)
{
int afterLastTag = stops[ntags - 1] + stop.Length;
if (afterLastTag < n)
{
// copy text from end of last tag to end
string text = Sharpen.Runtime.Substring(pattern, afterLastTag, n);
chunks.Add(new TextChunk(text));
}
}
// strip out the escape sequences from text chunks but not tags
for (int i_2 = 0; i_2 < chunks.Count; i_2++)
{
Chunk c = chunks[i_2];
if (c is TextChunk)
{
TextChunk tc = (TextChunk)c;
string unescaped = tc.Text.Replace(escape, string.Empty);
if (unescaped.Length < tc.Text.Length)
{
chunks.Set(i_2, new TextChunk(unescaped));
}
}
}
return chunks;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace System.Linq.Expressions
{
/// <summary>
/// Strongly-typed and parameterized exception factory.
/// </summary>
internal static partial class Error
{
/// <summary>
/// ArgumentException with message like "reducible nodes must override Expression.Reduce()"
/// </summary>
internal static Exception ReducibleMustOverrideReduce()
{
return new ArgumentException(Strings.ReducibleMustOverrideReduce);
}
/// <summary>
/// ArgumentException with message like "node cannot reduce to itself or null"
/// </summary>
internal static Exception MustReduceToDifferent()
{
return new ArgumentException(Strings.MustReduceToDifferent);
}
/// <summary>
/// ArgumentException with message like "cannot assign from the reduced node type to the original node type"
/// </summary>
internal static Exception ReducedNotCompatible()
{
return new ArgumentException(Strings.ReducedNotCompatible);
}
/// <summary>
/// ArgumentException with message like "Setter must have parameters."
/// </summary>
internal static Exception SetterHasNoParams()
{
return new ArgumentException(Strings.SetterHasNoParams);
}
/// <summary>
/// ArgumentException with message like "Property cannot have a managed pointer type."
/// </summary>
internal static Exception PropertyCannotHaveRefType()
{
return new ArgumentException(Strings.PropertyCannotHaveRefType);
}
/// <summary>
/// ArgumentException with message like "Indexing parameters of getter and setter must match."
/// </summary>
internal static Exception IndexesOfSetGetMustMatch()
{
return new ArgumentException(Strings.IndexesOfSetGetMustMatch);
}
/// <summary>
/// ArgumentException with message like "Accessor method should not have VarArgs."
/// </summary>
internal static Exception AccessorsCannotHaveVarArgs()
{
return new ArgumentException(Strings.AccessorsCannotHaveVarArgs);
}
/// <summary>
/// ArgumentException with message like "Accessor indexes cannot be passed ByRef."
/// </summary>
internal static Exception AccessorsCannotHaveByRefArgs()
{
return new ArgumentException(Strings.AccessorsCannotHaveByRefArgs);
}
/// <summary>
/// ArgumentException with message like "Bounds count cannot be less than 1"
/// </summary>
internal static Exception BoundsCannotBeLessThanOne()
{
return new ArgumentException(Strings.BoundsCannotBeLessThanOne);
}
/// <summary>
/// ArgumentException with message like "type must not be ByRef"
/// </summary>
internal static Exception TypeMustNotBeByRef()
{
return new ArgumentException(Strings.TypeMustNotBeByRef);
}
/// <summary>
/// ArgumentException with message like "Type doesn't have constructor with a given signature"
/// </summary>
internal static Exception TypeDoesNotHaveConstructorForTheSignature()
{
return new ArgumentException(Strings.TypeDoesNotHaveConstructorForTheSignature);
}
/// <summary>
/// ArgumentException with message like "Setter should have void type."
/// </summary>
internal static Exception SetterMustBeVoid()
{
return new ArgumentException(Strings.SetterMustBeVoid);
}
/// <summary>
/// ArgumentException with message like "Property type must match the value type of setter"
/// </summary>
internal static Exception PropertyTyepMustMatchSetter()
{
return new ArgumentException(Strings.PropertyTyepMustMatchSetter);
}
/// <summary>
/// ArgumentException with message like "Both accessors must be static."
/// </summary>
internal static Exception BothAccessorsMustBeStatic()
{
return new ArgumentException(Strings.BothAccessorsMustBeStatic);
}
/// <summary>
/// ArgumentException with message like "Static method requires null instance, non-static method requires non-null instance."
/// </summary>
internal static Exception OnlyStaticMethodsHaveNullInstance()
{
return new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance);
}
/// <summary>
/// ArgumentException with message like "Property cannot have a void type."
/// </summary>
internal static Exception PropertyTypeCannotBeVoid()
{
return new ArgumentException(Strings.PropertyTypeCannotBeVoid);
}
/// <summary>
/// ArgumentException with message like "Can only unbox from an object or interface type to a value type."
/// </summary>
internal static Exception InvalidUnboxType()
{
return new ArgumentException(Strings.InvalidUnboxType);
}
/// <summary>
/// ArgumentException with message like "Argument must not have a value type."
/// </summary>
internal static Exception ArgumentMustNotHaveValueType()
{
return new ArgumentException(Strings.ArgumentMustNotHaveValueType);
}
/// <summary>
/// ArgumentException with message like "must be reducible node"
/// </summary>
internal static Exception MustBeReducible()
{
return new ArgumentException(Strings.MustBeReducible);
}
/// <summary>
/// ArgumentException with message like "Default body must be supplied if case bodies are not System.Void."
/// </summary>
internal static Exception DefaultBodyMustBeSupplied()
{
return new ArgumentException(Strings.DefaultBodyMustBeSupplied);
}
/// <summary>
/// ArgumentException with message like "MethodBuilder does not have a valid TypeBuilder"
/// </summary>
internal static Exception MethodBuilderDoesNotHaveTypeBuilder()
{
return new ArgumentException(Strings.MethodBuilderDoesNotHaveTypeBuilder);
}
/// <summary>
/// ArgumentException with message like "Label type must be System.Void if an expression is not supplied"
/// </summary>
internal static Exception LabelMustBeVoidOrHaveExpression()
{
return new ArgumentException(Strings.LabelMustBeVoidOrHaveExpression);
}
/// <summary>
/// ArgumentException with message like "Type must be System.Void for this label argument"
/// </summary>
internal static Exception LabelTypeMustBeVoid()
{
return new ArgumentException(Strings.LabelTypeMustBeVoid);
}
/// <summary>
/// ArgumentException with message like "Quoted expression must be a lambda"
/// </summary>
internal static Exception QuotedExpressionMustBeLambda()
{
return new ArgumentException(Strings.QuotedExpressionMustBeLambda);
}
/// <summary>
/// ArgumentException with message like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables."
/// </summary>
internal static Exception VariableMustNotBeByRef(object p0, object p1)
{
return new ArgumentException(Strings.VariableMustNotBeByRef(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object."
/// </summary>
internal static Exception DuplicateVariable(object p0)
{
return new ArgumentException(Strings.DuplicateVariable(p0));
}
/// <summary>
/// ArgumentException with message like "Start and End must be well ordered"
/// </summary>
internal static Exception StartEndMustBeOrdered()
{
return new ArgumentException(Strings.StartEndMustBeOrdered);
}
/// <summary>
/// ArgumentException with message like "fault cannot be used with catch or finally clauses"
/// </summary>
internal static Exception FaultCannotHaveCatchOrFinally()
{
return new ArgumentException(Strings.FaultCannotHaveCatchOrFinally);
}
/// <summary>
/// ArgumentException with message like "try must have at least one catch, finally, or fault clause"
/// </summary>
internal static Exception TryMustHaveCatchFinallyOrFault()
{
return new ArgumentException(Strings.TryMustHaveCatchFinallyOrFault);
}
/// <summary>
/// ArgumentException with message like "Body of catch must have the same type as body of try."
/// </summary>
internal static Exception BodyOfCatchMustHaveSameTypeAsBodyOfTry()
{
return new ArgumentException(Strings.BodyOfCatchMustHaveSameTypeAsBodyOfTry);
}
/// <summary>
/// InvalidOperationException with message like "Extension node must override the property {0}."
/// </summary>
internal static Exception ExtensionNodeMustOverrideProperty(object p0)
{
return new InvalidOperationException(Strings.ExtensionNodeMustOverrideProperty(p0));
}
/// <summary>
/// ArgumentException with message like "User-defined operator method '{0}' must be static."
/// </summary>
internal static Exception UserDefinedOperatorMustBeStatic(object p0)
{
return new ArgumentException(Strings.UserDefinedOperatorMustBeStatic(p0));
}
/// <summary>
/// ArgumentException with message like "User-defined operator method '{0}' must not be void."
/// </summary>
internal static Exception UserDefinedOperatorMustNotBeVoid(object p0)
{
return new ArgumentException(Strings.UserDefinedOperatorMustNotBeVoid(p0));
}
/// <summary>
/// InvalidOperationException with message like "No coercion operator is defined between types '{0}' and '{1}'."
/// </summary>
internal static Exception CoercionOperatorNotDefined(object p0, object p1)
{
return new InvalidOperationException(Strings.CoercionOperatorNotDefined(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The unary operator {0} is not defined for the type '{1}'."
/// </summary>
internal static Exception UnaryOperatorNotDefined(object p0, object p1)
{
return new InvalidOperationException(Strings.UnaryOperatorNotDefined(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The binary operator {0} is not defined for the types '{1}' and '{2}'."
/// </summary>
internal static Exception BinaryOperatorNotDefined(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.BinaryOperatorNotDefined(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Reference equality is not defined for the types '{0}' and '{1}'."
/// </summary>
internal static Exception ReferenceEqualityNotDefined(object p0, object p1)
{
return new InvalidOperationException(Strings.ReferenceEqualityNotDefined(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The operands for operator '{0}' do not match the parameters of method '{1}'."
/// </summary>
internal static Exception OperandTypesDoNotMatchParameters(object p0, object p1)
{
return new InvalidOperationException(Strings.OperandTypesDoNotMatchParameters(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'."
/// </summary>
internal static Exception OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1)
{
return new InvalidOperationException(Strings.OverloadOperatorTypeDoesNotMatchConversionType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "Conversion is not supported for arithmetic types without operator overloading."
/// </summary>
internal static Exception ConversionIsNotSupportedForArithmeticTypes()
{
return new InvalidOperationException(Strings.ConversionIsNotSupportedForArithmeticTypes);
}
/// <summary>
/// ArgumentException with message like "Argument must be array"
/// </summary>
internal static Exception ArgumentMustBeArray()
{
return new ArgumentException(Strings.ArgumentMustBeArray);
}
/// <summary>
/// ArgumentException with message like "Argument must be boolean"
/// </summary>
internal static Exception ArgumentMustBeBoolean()
{
return new ArgumentException(Strings.ArgumentMustBeBoolean);
}
/// <summary>
/// ArgumentException with message like "The user-defined equality method '{0}' must return a boolean value."
/// </summary>
internal static Exception EqualityMustReturnBoolean(object p0)
{
return new ArgumentException(Strings.EqualityMustReturnBoolean(p0));
}
/// <summary>
/// ArgumentException with message like "Argument must be either a FieldInfo or PropertyInfo"
/// </summary>
internal static Exception ArgumentMustBeFieldInfoOrPropertyInfo()
{
return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertyInfo);
}
/// <summary>
/// ArgumentException with message like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo"
/// </summary>
internal static Exception ArgumentMustBeFieldInfoOrPropertyInfoOrMethod()
{
return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod);
}
/// <summary>
/// ArgumentException with message like "Argument must be an instance member"
/// </summary>
internal static Exception ArgumentMustBeInstanceMember()
{
return new ArgumentException(Strings.ArgumentMustBeInstanceMember);
}
/// <summary>
/// ArgumentException with message like "Argument must be of an integer type"
/// </summary>
internal static Exception ArgumentMustBeInteger()
{
return new ArgumentException(Strings.ArgumentMustBeInteger);
}
/// <summary>
/// ArgumentException with message like "Argument for array index must be of type Int32"
/// </summary>
internal static Exception ArgumentMustBeArrayIndexType()
{
return new ArgumentException(Strings.ArgumentMustBeArrayIndexType);
}
/// <summary>
/// ArgumentException with message like "Argument must be single dimensional array type"
/// </summary>
internal static Exception ArgumentMustBeSingleDimensionalArrayType()
{
return new ArgumentException(Strings.ArgumentMustBeSingleDimensionalArrayType);
}
/// <summary>
/// ArgumentException with message like "Argument types do not match"
/// </summary>
internal static Exception ArgumentTypesMustMatch()
{
return new ArgumentException(Strings.ArgumentTypesMustMatch);
}
/// <summary>
/// InvalidOperationException with message like "Cannot auto initialize elements of value type through property '{0}', use assignment instead"
/// </summary>
internal static Exception CannotAutoInitializeValueTypeElementThroughProperty(object p0)
{
return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeElementThroughProperty(p0));
}
/// <summary>
/// InvalidOperationException with message like "Cannot auto initialize members of value type through property '{0}', use assignment instead"
/// </summary>
internal static Exception CannotAutoInitializeValueTypeMemberThroughProperty(object p0)
{
return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeMemberThroughProperty(p0));
}
/// <summary>
/// ArgumentException with message like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither"
/// </summary>
internal static Exception IncorrectTypeForTypeAs(object p0)
{
return new ArgumentException(Strings.IncorrectTypeForTypeAs(p0));
}
/// <summary>
/// InvalidOperationException with message like "Coalesce used with type that cannot be null"
/// </summary>
internal static Exception CoalesceUsedOnNonNullType()
{
return new InvalidOperationException(Strings.CoalesceUsedOnNonNullType);
}
/// <summary>
/// InvalidOperationException with message like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeCannotInitializeArrayType(object p0, object p1)
{
return new InvalidOperationException(Strings.ExpressionTypeCannotInitializeArrayType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchConstructorParameter(object p0, object p1)
{
return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchConstructorParameter(p0, p1);
}
/// <summary>
/// ArgumentException with message like " Argument type '{0}' does not match the corresponding member type '{1}'"
/// </summary>
internal static Exception ArgumentTypeDoesNotMatchMember(object p0, object p1)
{
return new ArgumentException(Strings.ArgumentTypeDoesNotMatchMember(p0, p1));
}
/// <summary>
/// ArgumentException with message like " The member '{0}' is not declared on type '{1}' being created"
/// </summary>
internal static Exception ArgumentMemberNotDeclOnType(object p0, object p1)
{
return new ArgumentException(Strings.ArgumentMemberNotDeclOnType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchMethodParameter(object p0, object p1, object p2)
{
return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchMethodParameter(p0, p1, p2);
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchParameter(object p0, object p1)
{
return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchParameter(p0, p1);
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for return type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchReturn(object p0, object p1)
{
return new ArgumentException(Strings.ExpressionTypeDoesNotMatchReturn(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for assignment to type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchAssignment(object p0, object p1)
{
return new ArgumentException(Strings.ExpressionTypeDoesNotMatchAssignment(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for label of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchLabel(object p0, object p1)
{
return new ArgumentException(Strings.ExpressionTypeDoesNotMatchLabel(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be invoked"
/// </summary>
internal static Exception ExpressionTypeNotInvocable(object p0)
{
return new ArgumentException(Strings.ExpressionTypeNotInvocable(p0));
}
/// <summary>
/// ArgumentException with message like "Field '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception FieldNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.FieldNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance field '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception InstanceFieldNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.InstanceFieldNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Field '{0}.{1}' is not defined for type '{2}'"
/// </summary>
internal static Exception FieldInfoNotDefinedForType(object p0, object p1, object p2)
{
return new ArgumentException(Strings.FieldInfoNotDefinedForType(p0, p1, p2));
}
/// <summary>
/// ArgumentException with message like "Incorrect number of indexes"
/// </summary>
internal static Exception IncorrectNumberOfIndexes()
{
return new ArgumentException(Strings.IncorrectNumberOfIndexes);
}
/// <summary>
/// InvalidOperationException with message like "Incorrect number of arguments supplied for lambda invocation"
/// </summary>
internal static Exception IncorrectNumberOfLambdaArguments()
{
return Dynamic.Utils.Error.IncorrectNumberOfLambdaArguments();
}
/// <summary>
/// ArgumentException with message like "Incorrect number of parameters supplied for lambda declaration"
/// </summary>
internal static Exception IncorrectNumberOfLambdaDeclarationParameters()
{
return new ArgumentException(Strings.IncorrectNumberOfLambdaDeclarationParameters);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of arguments supplied for call to method '{0}'"
/// </summary>
internal static Exception IncorrectNumberOfMethodCallArguments(object p0)
{
return Dynamic.Utils.Error.IncorrectNumberOfMethodCallArguments(p0);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of arguments for constructor"
/// </summary>
internal static Exception IncorrectNumberOfConstructorArguments()
{
return Dynamic.Utils.Error.IncorrectNumberOfConstructorArguments();
}
/// <summary>
/// ArgumentException with message like " Incorrect number of members for constructor"
/// </summary>
internal static Exception IncorrectNumberOfMembersForGivenConstructor()
{
return new ArgumentException(Strings.IncorrectNumberOfMembersForGivenConstructor);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of arguments for the given members "
/// </summary>
internal static Exception IncorrectNumberOfArgumentsForMembers()
{
return new ArgumentException(Strings.IncorrectNumberOfArgumentsForMembers);
}
/// <summary>
/// ArgumentException with message like "Lambda type parameter must be derived from System.Delegate"
/// </summary>
internal static Exception LambdaTypeMustBeDerivedFromSystemDelegate()
{
return new ArgumentException(Strings.LambdaTypeMustBeDerivedFromSystemDelegate);
}
/// <summary>
/// ArgumentException with message like "Member '{0}' not field or property"
/// </summary>
internal static Exception MemberNotFieldOrProperty(object p0)
{
return new ArgumentException(Strings.MemberNotFieldOrProperty(p0));
}
/// <summary>
/// ArgumentException with message like "Method {0} contains generic parameters"
/// </summary>
internal static Exception MethodContainsGenericParameters(object p0)
{
return new ArgumentException(Strings.MethodContainsGenericParameters(p0));
}
/// <summary>
/// ArgumentException with message like "Method {0} is a generic method definition"
/// </summary>
internal static Exception MethodIsGeneric(object p0)
{
return new ArgumentException(Strings.MethodIsGeneric(p0));
}
/// <summary>
/// ArgumentException with message like "The method '{0}.{1}' is not a property accessor"
/// </summary>
internal static Exception MethodNotPropertyAccessor(object p0, object p1)
{
return new ArgumentException(Strings.MethodNotPropertyAccessor(p0, p1));
}
/// <summary>
/// ArgumentException with message like "The property '{0}' has no 'get' accessor"
/// </summary>
internal static Exception PropertyDoesNotHaveGetter(object p0)
{
return new ArgumentException(Strings.PropertyDoesNotHaveGetter(p0));
}
/// <summary>
/// ArgumentException with message like "The property '{0}' has no 'set' accessor"
/// </summary>
internal static Exception PropertyDoesNotHaveSetter(object p0)
{
return new ArgumentException(Strings.PropertyDoesNotHaveSetter(p0));
}
/// <summary>
/// ArgumentException with message like "The property '{0}' has no 'get' or 'set' accessors"
/// </summary>
internal static Exception PropertyDoesNotHaveAccessor(object p0)
{
return new ArgumentException(Strings.PropertyDoesNotHaveAccessor(p0));
}
/// <summary>
/// ArgumentException with message like "'{0}' is not a member of type '{1}'"
/// </summary>
internal static Exception NotAMemberOfType(object p0, object p1)
{
return new ArgumentException(Strings.NotAMemberOfType(p0, p1));
}
/// <summary>
/// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for type '{1}'"
/// </summary>
internal static Exception ExpressionNotSupportedForType(object p0, object p1)
{
return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForType(p0, p1));
}
/// <summary>
/// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for nullable type '{1}'"
/// </summary>
internal static Exception ExpressionNotSupportedForNullableType(object p0, object p1)
{
return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForNullableType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'"
/// </summary>
internal static Exception ParameterExpressionNotValidAsDelegate(object p0, object p1)
{
return new ArgumentException(Strings.ParameterExpressionNotValidAsDelegate(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Property '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception PropertyNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.PropertyNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance property '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception InstancePropertyNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.InstancePropertyNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance property '{0}' that takes no argument is not defined for type '{1}'"
/// </summary>
internal static Exception InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.InstancePropertyWithoutParameterNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance property '{0}{1}' is not defined for type '{2}'"
/// </summary>
internal static Exception InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2)
{
return new ArgumentException(Strings.InstancePropertyWithSpecifiedParametersNotDefinedForType(p0, p1, p2));
}
/// <summary>
/// ArgumentException with message like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'"
/// </summary>
internal static Exception InstanceAndMethodTypeMismatch(object p0, object p1, object p2)
{
return new ArgumentException(Strings.InstanceAndMethodTypeMismatch(p0, p1, p2));
}
/// <summary>
/// ArgumentException with message like "Type '{0}' does not have a default constructor"
/// </summary>
internal static Exception TypeMissingDefaultConstructor(object p0)
{
return new ArgumentException(Strings.TypeMissingDefaultConstructor(p0));
}
/// <summary>
/// ArgumentException with message like "List initializers must contain at least one initializer"
/// </summary>
internal static Exception ListInitializerWithZeroMembers()
{
return new ArgumentException(Strings.ListInitializerWithZeroMembers);
}
/// <summary>
/// ArgumentException with message like "Element initializer method must be named 'Add'"
/// </summary>
internal static Exception ElementInitializerMethodNotAdd()
{
return new ArgumentException(Strings.ElementInitializerMethodNotAdd);
}
/// <summary>
/// ArgumentException with message like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter"
/// </summary>
internal static Exception ElementInitializerMethodNoRefOutParam(object p0, object p1)
{
return new ArgumentException(Strings.ElementInitializerMethodNoRefOutParam(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Element initializer method must have at least 1 parameter"
/// </summary>
internal static Exception ElementInitializerMethodWithZeroArgs()
{
return new ArgumentException(Strings.ElementInitializerMethodWithZeroArgs);
}
/// <summary>
/// ArgumentException with message like "Element initializer method must be an instance method"
/// </summary>
internal static Exception ElementInitializerMethodStatic()
{
return new ArgumentException(Strings.ElementInitializerMethodStatic);
}
/// <summary>
/// ArgumentException with message like "Type '{0}' is not IEnumerable"
/// </summary>
internal static Exception TypeNotIEnumerable(object p0)
{
return new ArgumentException(Strings.TypeNotIEnumerable(p0));
}
/// <summary>
/// InvalidOperationException with message like "Unexpected coalesce operator."
/// </summary>
internal static Exception UnexpectedCoalesceOperator()
{
return new InvalidOperationException(Strings.UnexpectedCoalesceOperator);
}
/// <summary>
/// InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}"
/// </summary>
internal static Exception InvalidCast(object p0, object p1)
{
return new InvalidOperationException(Strings.InvalidCast(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Unhandled binary: {0}"
/// </summary>
internal static Exception UnhandledBinary(object p0)
{
return new ArgumentException(Strings.UnhandledBinary(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled binding "
/// </summary>
internal static Exception UnhandledBinding()
{
return new ArgumentException(Strings.UnhandledBinding);
}
/// <summary>
/// ArgumentException with message like "Unhandled Binding Type: {0}"
/// </summary>
internal static Exception UnhandledBindingType(object p0)
{
return new ArgumentException(Strings.UnhandledBindingType(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled convert: {0}"
/// </summary>
internal static Exception UnhandledConvert(object p0)
{
return new ArgumentException(Strings.UnhandledConvert(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled Expression Type: {0}"
/// </summary>
internal static Exception UnhandledExpressionType(object p0)
{
return new ArgumentException(Strings.UnhandledExpressionType(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled unary: {0}"
/// </summary>
internal static Exception UnhandledUnary(object p0)
{
return new ArgumentException(Strings.UnhandledUnary(p0));
}
/// <summary>
/// ArgumentException with message like "Unknown binding type"
/// </summary>
internal static Exception UnknownBindingType()
{
return new ArgumentException(Strings.UnknownBindingType);
}
/// <summary>
/// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types."
/// </summary>
internal static Exception UserDefinedOpMustHaveConsistentTypes(object p0, object p1)
{
return new ArgumentException(Strings.UserDefinedOpMustHaveConsistentTypes(p0, p1));
}
/// <summary>
/// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type."
/// </summary>
internal static Exception UserDefinedOpMustHaveValidReturnType(object p0, object p1)
{
return new ArgumentException(Strings.UserDefinedOpMustHaveValidReturnType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators."
/// </summary>
internal static Exception LogicalOperatorMustHaveBooleanOperators(object p0, object p1)
{
return new ArgumentException(Strings.LogicalOperatorMustHaveBooleanOperators(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "No method '{0}' exists on type '{1}'."
/// </summary>
internal static Exception MethodDoesNotExistOnType(object p0, object p1)
{
return new InvalidOperationException(Strings.MethodDoesNotExistOnType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "No method '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static Exception MethodWithArgsDoesNotExistOnType(object p0, object p1)
{
return new InvalidOperationException(Strings.MethodWithArgsDoesNotExistOnType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. "
/// </summary>
internal static Exception GenericMethodWithArgsDoesNotExistOnType(object p0, object p1)
{
return new InvalidOperationException(Strings.GenericMethodWithArgsDoesNotExistOnType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static Exception MethodWithMoreThanOneMatch(object p0, object p1)
{
return new InvalidOperationException(Strings.MethodWithMoreThanOneMatch(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static Exception PropertyWithMoreThanOneMatch(object p0, object p1)
{
return new InvalidOperationException(Strings.PropertyWithMoreThanOneMatch(p0, p1));
}
/// <summary>
/// ArgumentException with message like "An incorrect number of type args were specified for the declaration of a Func type."
/// </summary>
internal static Exception IncorrectNumberOfTypeArgsForFunc()
{
return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForFunc);
}
/// <summary>
/// ArgumentException with message like "An incorrect number of type args were specified for the declaration of an Action type."
/// </summary>
internal static Exception IncorrectNumberOfTypeArgsForAction()
{
return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForAction);
}
/// <summary>
/// ArgumentException with message like "Argument type cannot be System.Void."
/// </summary>
internal static Exception ArgumentCannotBeOfTypeVoid()
{
return new ArgumentException(Strings.ArgumentCannotBeOfTypeVoid);
}
/// <summary>
/// ArgumentException with message like "Invalid operation: '{0}'"
/// </summary>
internal static Exception InvalidOperation(object p0)
{
return new ArgumentException(Strings.InvalidOperation(p0));
}
/// <summary>
/// ArgumentOutOfRangeException with message like "{0} must be greater than or equal to {1}"
/// </summary>
internal static Exception OutOfRange(object p0, object p1)
{
return new ArgumentOutOfRangeException(Strings.OutOfRange(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "Cannot redefine label '{0}' in an inner block."
/// </summary>
internal static Exception LabelTargetAlreadyDefined(object p0)
{
return new InvalidOperationException(Strings.LabelTargetAlreadyDefined(p0));
}
/// <summary>
/// InvalidOperationException with message like "Cannot jump to undefined label '{0}'."
/// </summary>
internal static Exception LabelTargetUndefined(object p0)
{
return new InvalidOperationException(Strings.LabelTargetUndefined(p0));
}
/// <summary>
/// InvalidOperationException with message like "Control cannot leave a finally block."
/// </summary>
internal static Exception ControlCannotLeaveFinally()
{
return new InvalidOperationException(Strings.ControlCannotLeaveFinally);
}
/// <summary>
/// InvalidOperationException with message like "Control cannot leave a filter test."
/// </summary>
internal static Exception ControlCannotLeaveFilterTest()
{
return new InvalidOperationException(Strings.ControlCannotLeaveFilterTest);
}
/// <summary>
/// InvalidOperationException with message like "Cannot jump to ambiguous label '{0}'."
/// </summary>
internal static Exception AmbiguousJump(object p0)
{
return new InvalidOperationException(Strings.AmbiguousJump(p0));
}
/// <summary>
/// InvalidOperationException with message like "Control cannot enter a try block."
/// </summary>
internal static Exception ControlCannotEnterTry()
{
return new InvalidOperationException(Strings.ControlCannotEnterTry);
}
/// <summary>
/// InvalidOperationException with message like "Control cannot enter an expression--only statements can be jumped into."
/// </summary>
internal static Exception ControlCannotEnterExpression()
{
return new InvalidOperationException(Strings.ControlCannotEnterExpression);
}
/// <summary>
/// InvalidOperationException with message like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values."
/// </summary>
internal static Exception NonLocalJumpWithValue(object p0)
{
return new InvalidOperationException(Strings.NonLocalJumpWithValue(p0));
}
/// <summary>
/// InvalidOperationException with message like "Extension should have been reduced."
/// </summary>
internal static Exception ExtensionNotReduced()
{
return new InvalidOperationException(Strings.ExtensionNotReduced);
}
/// <summary>
/// InvalidOperationException with message like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value."
/// </summary>
internal static Exception CannotCompileConstant(object p0)
{
return new InvalidOperationException(Strings.CannotCompileConstant(p0));
}
/// <summary>
/// NotSupportedException with message like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite."
/// </summary>
internal static Exception CannotCompileDynamic()
{
return new NotSupportedException(Strings.CannotCompileDynamic);
}
/// <summary>
/// InvalidOperationException with message like "Invalid lvalue for assignment: {0}."
/// </summary>
internal static Exception InvalidLvalue(ExpressionType p0)
{
return new InvalidOperationException(Strings.InvalidLvalue(p0));
}
/// <summary>
/// InvalidOperationException with message like "Invalid member type: {0}."
/// </summary>
internal static Exception InvalidMemberType(object p0)
{
return new InvalidOperationException(Strings.InvalidMemberType(p0));
}
/// <summary>
/// InvalidOperationException with message like "unknown lift type: '{0}'."
/// </summary>
internal static Exception UnknownLiftType(object p0)
{
return new InvalidOperationException(Strings.UnknownLiftType(p0));
}
/// <summary>
/// ArgumentException with message like "Invalid output directory."
/// </summary>
internal static Exception InvalidOutputDir()
{
return new ArgumentException(Strings.InvalidOutputDir);
}
/// <summary>
/// ArgumentException with message like "Invalid assembly name or file extension."
/// </summary>
internal static Exception InvalidAsmNameOrExtension()
{
return new ArgumentException(Strings.InvalidAsmNameOrExtension);
}
/// <summary>
/// ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters"
/// </summary>
internal static Exception IllegalNewGenericParams(object p0)
{
return new ArgumentException(Strings.IllegalNewGenericParams(p0));
}
/// <summary>
/// InvalidOperationException with message like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined"
/// </summary>
internal static Exception UndefinedVariable(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.UndefinedVariable(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'"
/// </summary>
internal static Exception CannotCloseOverByRef(object p0, object p1)
{
return new InvalidOperationException(Strings.CannotCloseOverByRef(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "Unexpected VarArgs call to method '{0}'"
/// </summary>
internal static Exception UnexpectedVarArgsCall(object p0)
{
return new InvalidOperationException(Strings.UnexpectedVarArgsCall(p0));
}
/// <summary>
/// InvalidOperationException with message like "Rethrow statement is valid only inside a Catch block."
/// </summary>
internal static Exception RethrowRequiresCatch()
{
return new InvalidOperationException(Strings.RethrowRequiresCatch);
}
/// <summary>
/// InvalidOperationException with message like "Try expression is not allowed inside a filter body."
/// </summary>
internal static Exception TryNotAllowedInFilter()
{
return new InvalidOperationException(Strings.TryNotAllowedInFilter);
}
/// <summary>
/// InvalidOperationException with message like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type."
/// </summary>
internal static Exception MustRewriteToSameNode(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.MustRewriteToSameNode(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite."
/// </summary>
internal static Exception MustRewriteChildToSameType(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.MustRewriteChildToSameType(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is is intentional, override '{1}' and change it to allow this rewrite."
/// </summary>
internal static Exception MustRewriteWithoutMethod(object p0, object p1)
{
return new InvalidOperationException(Strings.MustRewriteWithoutMethod(p0, p1));
}
/// <summary>
/// NotSupportedException with message like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression."
/// </summary>
internal static Exception TryNotSupportedForMethodsWithRefArgs(object p0)
{
return new NotSupportedException(Strings.TryNotSupportedForMethodsWithRefArgs(p0));
}
/// <summary>
/// NotSupportedException with message like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression."
/// </summary>
internal static Exception TryNotSupportedForValueTypeInstances(object p0)
{
return new NotSupportedException(Strings.TryNotSupportedForValueTypeInstances(p0));
}
/// <summary>
/// InvalidOperationException with message like "Dynamic operations can only be performed in homogenous AppDomain."
/// </summary>
internal static Exception HomogenousAppDomainRequired()
{
return new InvalidOperationException(Strings.HomogenousAppDomainRequired);
}
/// <summary>
/// ArgumentException with message like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
/// </summary>
internal static Exception TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1)
{
return new ArgumentException(Strings.TestValueTypeDoesNotMatchComparisonMethodParameter(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
/// </summary>
internal static Exception SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1)
{
return new ArgumentException(Strings.SwitchValueTypeDoesNotMatchComparisonMethodParameter(p0, p1));
}
/// <summary>
/// NotSupportedException with message like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod."
/// </summary>
internal static Exception PdbGeneratorNeedsExpressionCompiler()
{
return new NotSupportedException(Strings.PdbGeneratorNeedsExpressionCompiler);
}
/// <summary>
/// The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
/// </summary>
internal static Exception ArgumentNull(string paramName)
{
return new ArgumentNullException(paramName);
}
/// <summary>
/// The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
/// </summary>
internal static Exception ArgumentOutOfRange(string paramName)
{
return new ArgumentOutOfRangeException(paramName);
}
/// <summary>
/// The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
/// </summary>
internal static Exception NotSupported()
{
return new NotSupportedException();
}
#if FEATURE_COMPILE
/// <summary>
/// NotImplementedException with message like "The operator '{0}' is not implemented for type '{1}'"
/// </summary>
internal static Exception OperatorNotImplementedForType(object p0, object p1)
{
return NotImplemented.ByDesignWithMessage(Strings.OperatorNotImplementedForType(p0, p1));
}
#endif
/// <summary>
/// ArgumentException with message like "The constructor should not be static"
/// </summary>
internal static Exception NonStaticConstructorRequired()
{
return new ArgumentException(Strings.NonStaticConstructorRequired);
}
/// <summary>
/// InvalidOperationException with message like "Can't compile a NewExpression with a constructor declared on an abstract class"
/// </summary>
internal static Exception NonAbstractConstructorRequired()
{
return new InvalidOperationException(Strings.NonAbstractConstructorRequired);
}
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Controller class for VGI_AClinicosDet
/// </summary>
[System.ComponentModel.DataObject]
public partial class VgiAClinicosDetController
{
// Preload our schema..
VgiAClinicosDet thisSchemaLoad = new VgiAClinicosDet();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public VgiAClinicosDetCollection FetchAll()
{
VgiAClinicosDetCollection coll = new VgiAClinicosDetCollection();
Query qry = new Query(VgiAClinicosDet.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public VgiAClinicosDetCollection FetchByID(object IdVGIAClinico)
{
VgiAClinicosDetCollection coll = new VgiAClinicosDetCollection().Where("idVGIAClinico", IdVGIAClinico).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public VgiAClinicosDetCollection FetchByQuery(Query qry)
{
VgiAClinicosDetCollection coll = new VgiAClinicosDetCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object IdVGIAClinico)
{
return (VgiAClinicosDet.Delete(IdVGIAClinico) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object IdVGIAClinico)
{
return (VgiAClinicosDet.Destroy(IdVGIAClinico) == 1);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(int IdVGIDatos,string Ta,decimal? Peso,decimal? Talla,decimal? Imc,string Hta,string Dbt,string Dislip,string Irc,string CardioIsq,string Acv,string Amputacion,string Tabaquismo,string Alcoholismo,string Parkinson,string Demencia,string Prostatismo,string Incontinencia,string Neuplasias,string Otros,string Rcvg,string VisionConducir,string VacunacionDT,string VacunacionHepB,string VacunacionGripe,string VacunacionNeumococo,string AudicionPSeguirConv,int? Medicacion1,int? Medicacion2,int? Medicacion3,int? Medicacion4,int? Medicacion5,string CaidasFrecuentes,string NeuplaciaDet)
{
VgiAClinicosDet item = new VgiAClinicosDet();
item.IdVGIDatos = IdVGIDatos;
item.Ta = Ta;
item.Peso = Peso;
item.Talla = Talla;
item.Imc = Imc;
item.Hta = Hta;
item.Dbt = Dbt;
item.Dislip = Dislip;
item.Irc = Irc;
item.CardioIsq = CardioIsq;
item.Acv = Acv;
item.Amputacion = Amputacion;
item.Tabaquismo = Tabaquismo;
item.Alcoholismo = Alcoholismo;
item.Parkinson = Parkinson;
item.Demencia = Demencia;
item.Prostatismo = Prostatismo;
item.Incontinencia = Incontinencia;
item.Neuplasias = Neuplasias;
item.Otros = Otros;
item.Rcvg = Rcvg;
item.VisionConducir = VisionConducir;
item.VacunacionDT = VacunacionDT;
item.VacunacionHepB = VacunacionHepB;
item.VacunacionGripe = VacunacionGripe;
item.VacunacionNeumococo = VacunacionNeumococo;
item.AudicionPSeguirConv = AudicionPSeguirConv;
item.Medicacion1 = Medicacion1;
item.Medicacion2 = Medicacion2;
item.Medicacion3 = Medicacion3;
item.Medicacion4 = Medicacion4;
item.Medicacion5 = Medicacion5;
item.CaidasFrecuentes = CaidasFrecuentes;
item.NeuplaciaDet = NeuplaciaDet;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int IdVGIDatos,decimal IdVGIAClinico,string Ta,decimal? Peso,decimal? Talla,decimal? Imc,string Hta,string Dbt,string Dislip,string Irc,string CardioIsq,string Acv,string Amputacion,string Tabaquismo,string Alcoholismo,string Parkinson,string Demencia,string Prostatismo,string Incontinencia,string Neuplasias,string Otros,string Rcvg,string VisionConducir,string VacunacionDT,string VacunacionHepB,string VacunacionGripe,string VacunacionNeumococo,string AudicionPSeguirConv,int? Medicacion1,int? Medicacion2,int? Medicacion3,int? Medicacion4,int? Medicacion5,string CaidasFrecuentes,string NeuplaciaDet)
{
VgiAClinicosDet item = new VgiAClinicosDet();
item.MarkOld();
item.IsLoaded = true;
item.IdVGIDatos = IdVGIDatos;
item.IdVGIAClinico = IdVGIAClinico;
item.Ta = Ta;
item.Peso = Peso;
item.Talla = Talla;
item.Imc = Imc;
item.Hta = Hta;
item.Dbt = Dbt;
item.Dislip = Dislip;
item.Irc = Irc;
item.CardioIsq = CardioIsq;
item.Acv = Acv;
item.Amputacion = Amputacion;
item.Tabaquismo = Tabaquismo;
item.Alcoholismo = Alcoholismo;
item.Parkinson = Parkinson;
item.Demencia = Demencia;
item.Prostatismo = Prostatismo;
item.Incontinencia = Incontinencia;
item.Neuplasias = Neuplasias;
item.Otros = Otros;
item.Rcvg = Rcvg;
item.VisionConducir = VisionConducir;
item.VacunacionDT = VacunacionDT;
item.VacunacionHepB = VacunacionHepB;
item.VacunacionGripe = VacunacionGripe;
item.VacunacionNeumococo = VacunacionNeumococo;
item.AudicionPSeguirConv = AudicionPSeguirConv;
item.Medicacion1 = Medicacion1;
item.Medicacion2 = Medicacion2;
item.Medicacion3 = Medicacion3;
item.Medicacion4 = Medicacion4;
item.Medicacion5 = Medicacion5;
item.CaidasFrecuentes = CaidasFrecuentes;
item.NeuplaciaDet = NeuplaciaDet;
item.Save(UserName);
}
}
}
| |
using System.Linq.Expressions;
using GammaJul.ReSharper.EnhancedTooltip.Psi;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using GammaJul.ReSharper.EnhancedTooltip.Presentation;
using GammaJul.ReSharper.EnhancedTooltip.Settings;
using GammaJul.ReSharper.EnhancedTooltip.VisualStudio;
using JetBrains.Application.Settings;
using JetBrains.DocumentModel;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Descriptions;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Files;
using JetBrains.ReSharper.Psi.Impl;
using JetBrains.ReSharper.Psi.Modules;
using JetBrains.ReSharper.Psi.Resolve;
using JetBrains.ReSharper.Psi.Resources;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.ReSharper.Psi.Util;
using JetBrains.TextControl.DocumentMarkup;
using JetBrains.UI.Icons;
using JetBrains.UI.RichText;
using JetBrains.Util;
namespace GammaJul.ReSharper.EnhancedTooltip.DocumentMarkup {
/// <summary>
/// Provides colored identifier tooltips.
/// </summary>
[SolutionComponent]
public class IdentifierTooltipContentProvider {
private sealed class DeclaredElementInfo {
internal readonly IDeclaredElement DeclaredElement;
internal readonly ISubstitution Substitution;
internal readonly ITreeNode TreeNode;
internal readonly TextRange SourceRange;
internal readonly IReference? Reference;
public DeclaredElementInfo(
IDeclaredElement declaredElement,
ISubstitution substitution,
ITreeNode treeNode,
TextRange sourceRange,
IReference? reference) {
DeclaredElement = declaredElement;
Substitution = substitution;
TreeNode = treeNode;
SourceRange = sourceRange;
Reference = reference;
}
}
private readonly struct PresentableInfo {
internal readonly DeclaredElementInfo? DeclaredElementInfo;
internal readonly PresentableNode PresentableNode;
public bool IsValid()
=> DeclaredElementInfo is not null && DeclaredElementInfo.DeclaredElement.IsValid()
|| PresentableNode.Node is not null;
public PresentableInfo(DeclaredElementInfo? declaredElementInfo) {
DeclaredElementInfo = declaredElementInfo;
PresentableNode = default;
}
public PresentableInfo(PresentableNode presentableNode) {
DeclaredElementInfo = null;
PresentableNode = presentableNode;
}
}
private readonly ISolution _solution;
private readonly IDeclaredElementDescriptionPresenter _declaredElementDescriptionPresenter;
private readonly HighlighterIdProviderFactory _highlighterIdProviderFactory;
private readonly ColorizerPresenter _colorizerPresenter;
/// <summary>
/// Returns a colored <see cref="IdentifierContentGroup"/> for an identifier represented by a <see cref="IHighlighter"/>.
/// </summary>
/// <param name="highlighter">The highlighter representing the identifier.</param>
/// <param name="settings">The settings to use.</param>
/// <returns>An <see cref="IdentifierContentGroup"/> representing a colored tooltip, or <c>null</c>.</returns>
public IdentifierContentGroup? GetIdentifierContentGroup(IHighlighter highlighter, IContextBoundSettingsStore settings) {
if (!highlighter.IsValid)
return null;
if (!settings.GetValue((IdentifierTooltipSettings s) => s.Enabled)) {
if (TryPresentNonColorized(highlighter, null, settings) is { } content)
return new IdentifierContentGroup { Identifiers = { content } };
return null;
}
return GetIdentifierContentGroupCore(new DocumentRange(highlighter.Document, highlighter.Range), settings, highlighter);
}
/// <summary>
/// Returns a colored <see cref="IdentifierContentGroup"/> for an identifier at a given <see cref="DocumentRange"/>.
/// </summary>
/// <param name="documentRange">The document range where to find a <see cref="IDeclaredElement"/>.</param>
/// <param name="settings">The settings to use.</param>
/// <returns>An <see cref="IdentifierContentGroup"/> representing a colored tooltip, or <c>null</c>.</returns>
public IdentifierContentGroup? GetIdentifierContentGroup(DocumentRange documentRange, IContextBoundSettingsStore settings) {
if (!settings.GetValue((IdentifierTooltipSettings s) => s.Enabled))
return null;
return GetIdentifierContentGroupCore(documentRange, settings, null);
}
private IdentifierContentGroup? GetIdentifierContentGroupCore(
DocumentRange documentRange,
IContextBoundSettingsStore settings,
IHighlighter? highlighter) {
PresentableInfo presentable = FindPresentable(documentRange);
if (!presentable.IsValid())
return null;
IdentifierTooltipContent? standardContent =
TryPresentColorized(presentable.DeclaredElementInfo, settings)
?? TryPresentColorized(presentable.PresentableNode, settings)
?? TryPresentNonColorized(highlighter, presentable.DeclaredElementInfo?.DeclaredElement, settings);
IdentifierTooltipContent? additionalContent = TryGetAdditionalIdentifierContent(presentable.DeclaredElementInfo, settings, out bool replacesStandardContent);
if (replacesStandardContent) {
standardContent = additionalContent;
additionalContent = null;
}
var result = new IdentifierContentGroup();
if (standardContent is not null)
result.Identifiers.Add(standardContent);
if (additionalContent is not null)
result.Identifiers.Add(additionalContent);
ITreeNode? node = presentable.DeclaredElementInfo?.TreeNode ?? presentable.PresentableNode.Node;
result.ArgumentRole = TryGetArgumentRoleContent(node, settings);
return result;
}
private IdentifierTooltipContent? TryGetAdditionalIdentifierContent(
DeclaredElementInfo? info,
IContextBoundSettingsStore settings,
out bool replacesStandardContent) {
replacesStandardContent = false;
if (info?.DeclaredElement is not IConstructor constructor || constructor.GetContainingType() is not { } typeElement)
return null;
ConstructorReferenceDisplay display = settings.GetValue(GetConstructorSettingsKey(typeElement.IsAttribute()));
switch (display) {
case ConstructorReferenceDisplay.TypeOnly:
replacesStandardContent = true;
return TryGetTypeIdentifierContentFromConstructor(constructor, info, settings);
case ConstructorReferenceDisplay.Both:
return TryGetTypeIdentifierContentFromConstructor(constructor, info, settings);
default:
return null;
}
}
private static Expression<Func<IdentifierTooltipSettings, ConstructorReferenceDisplay>> GetConstructorSettingsKey(bool isAttribute) {
if (isAttribute)
return s => s.AttributeConstructorReferenceDisplay;
return s => s.ConstructorReferenceDisplay;
}
private IdentifierTooltipContent? TryGetTypeIdentifierContentFromConstructor(
IConstructor constructor, DeclaredElementInfo constructorInfo, IContextBoundSettingsStore settings) {
if (constructor.GetContainingType() is not { } typeElement)
return null;
var typeInfo = new DeclaredElementInfo(typeElement, constructorInfo.Substitution, constructorInfo.TreeNode, constructorInfo.SourceRange, null);
return TryPresentColorized(typeInfo, settings);
}
private IdentifierTooltipContent? TryPresentColorized(DeclaredElementInfo? info, IContextBoundSettingsStore settings) {
if (info is null)
return null;
PsiLanguageType languageType = info.TreeNode.Language;
IDeclaredElement element = info.DeclaredElement;
IPsiModule psiModule = info.TreeNode.GetPsiModule();
HighlighterIdProvider highlighterIdProvider = _highlighterIdProviderFactory.CreateProvider(settings);
var reflectionCppTooltipContentProvider = _solution.TryGetComponent<ReflectionCppTooltipContentProvider>();
RichText? identifierText;
if (reflectionCppTooltipContentProvider is not null && reflectionCppTooltipContentProvider.IsCppDeclaredElement(element))
identifierText = reflectionCppTooltipContentProvider.TryPresentCppDeclaredElement(element);
else {
identifierText = _colorizerPresenter.TryPresent(
new DeclaredElementInstance(element, info.Substitution),
PresenterOptions.ForIdentifierToolTip(settings, !element.IsEnumMember()),
languageType,
highlighterIdProvider,
info.TreeNode,
out _);
}
if (identifierText is null || identifierText.IsEmpty)
return null;
var identifierContent = new IdentifierTooltipContent(identifierText, info.SourceRange);
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowIcon))
identifierContent.Icon = TryGetIcon(element);
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowDocumentation)) {
XmlNode? xmlDoc = element.GetXMLDoc(true);
identifierContent.Description = TryGetDescription(element, xmlDoc, psiModule, languageType);
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowObsolete))
identifierContent.Obsolete = TryRemoveObsoletePrefix(TryGetObsolete(element, psiModule, languageType));
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowReturn))
identifierContent.Return = TryPresentDocNode(xmlDoc, "returns", languageType, psiModule);
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowValue))
identifierContent.Value = TryPresentDocNode(xmlDoc, "value", languageType, psiModule);
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowRemarks))
identifierContent.Remarks = TryPresentDocNode(xmlDoc, "remarks", languageType, psiModule);
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowExceptions))
identifierContent.Exceptions.AddRange(GetExceptions(xmlDoc, languageType, psiModule));
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowParams))
identifierContent.Parameters.AddRange(IdentifierTooltipContentProvider.GetParams(xmlDoc, languageType, psiModule));
}
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowOverloadCount))
identifierContent.OverloadCount = TryGetOverloadCount(element as IFunction, info.Reference, languageType);
if (info.DeclaredElement is ITypeElement typeElement) {
var baseTypeDisplayKind = settings.GetValue((IdentifierTooltipSettings s) => s.BaseTypeDisplayKind);
var implementedInterfacesDisplayKind = settings.GetValue((IdentifierTooltipSettings s) => s.ImplementedInterfacesDisplayKind);
if (baseTypeDisplayKind != BaseTypeDisplayKind.Never
|| implementedInterfacesDisplayKind != ImplementedInterfacesDisplayKind.Never)
AddSuperTypes(identifierContent, typeElement, baseTypeDisplayKind, implementedInterfacesDisplayKind, languageType, info.TreeNode, highlighterIdProvider, settings);
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowAttributesUsage) && typeElement.IsAttribute())
identifierContent.AttributeUsage = GetAttributeUsage((IClass) info.DeclaredElement);
}
return identifierContent;
}
private static int? TryGetOverloadCount(IFunction? function, IReference? reference, PsiLanguageType languageType) {
if (function is null || reference is null || function is PredefinedOperator)
return null;
var candidateCountProvider = LanguageManager.Instance.TryGetService<IInvocationCandidateCountProvider>(languageType);
int? candidateCount = candidateCountProvider?.TryGetInvocationCandidateCount(reference);
if (candidateCount is null || candidateCount.Value <= 0)
return null;
return candidateCount.Value - 1;
}
private void AddSuperTypes(
IdentifierTooltipContent identifierContent,
ITypeElement typeElement,
BaseTypeDisplayKind baseTypeDisplayKind,
ImplementedInterfacesDisplayKind implementedInterfacesDisplayKind,
PsiLanguageType languageType,
ITreeNode contextualNode,
HighlighterIdProvider highlighterIdProvider,
IContextBoundSettingsStore settings) {
GetSuperTypes(
typeElement,
baseTypeDisplayKind,
implementedInterfacesDisplayKind,
out DeclaredElementInstance? baseType,
out IList<DeclaredElementInstance> implementedInterfaces);
if (baseType is null && implementedInterfaces.Count == 0)
return;
PresenterOptions presenterOptions = PresenterOptions.ForBaseTypeOrImplementedInterfaceTooltip(settings);
if (baseType is not null)
identifierContent.BaseType = _colorizerPresenter.TryPresent(baseType, presenterOptions, languageType, highlighterIdProvider, contextualNode, out _);
if (implementedInterfaces.Count > 0) {
var sortedPresentedInterfaces = new SortedDictionary<string, RichText>(StringComparer.Ordinal);
foreach (DeclaredElementInstance implementedInterface in implementedInterfaces) {
if (_colorizerPresenter.TryPresent(implementedInterface, presenterOptions, languageType, highlighterIdProvider, contextualNode, out _) is { } richText)
sortedPresentedInterfaces[richText.ToString(false)] = richText;
}
foreach (RichText richText in sortedPresentedInterfaces.Values)
identifierContent.ImplementedInterfaces.Add(richText);
}
}
private static void GetSuperTypes(
ITypeElement typeElement,
BaseTypeDisplayKind baseTypeDisplayKind,
ImplementedInterfacesDisplayKind implementedInterfacesDisplayKind,
out DeclaredElementInstance? baseType,
out IList<DeclaredElementInstance> implementedInterfaces) {
baseType = null;
implementedInterfaces = EmptyList<DeclaredElementInstance>.InstanceList;
var searchForBaseType = baseTypeDisplayKind != BaseTypeDisplayKind.Never && typeElement is IClass or ITypeParameter;
bool searchForImplementedInterfaces = implementedInterfacesDisplayKind != ImplementedInterfacesDisplayKind.Never;
if (!searchForBaseType && !searchForImplementedInterfaces)
return;
var foundInterfaces = new LocalList<DeclaredElementInstance>();
foreach (var superType in typeElement.GetAllSuperTypes()) {
ITypeElement? superTypeElement = superType.GetTypeElement();
if (superTypeElement is IClass or IDelegate) {
if (searchForBaseType) {
searchForBaseType = false;
if (MatchesBaseTypeDisplayKind(superTypeElement, baseTypeDisplayKind))
baseType = new DeclaredElementInstance(superTypeElement, superType.GetSubstitution());
if (!searchForImplementedInterfaces)
return;
}
continue;
}
if (searchForImplementedInterfaces
&& superTypeElement is IInterface @interface
&& MatchesImplementedInterfacesDisplayKind(@interface, implementedInterfacesDisplayKind))
foundInterfaces.Add(new DeclaredElementInstance(superTypeElement, superType.GetSubstitution()));
}
implementedInterfaces = foundInterfaces.ResultingList();
}
private static bool MatchesBaseTypeDisplayKind(ITypeElement typeElement, BaseTypeDisplayKind displayKind)
=> displayKind switch {
BaseTypeDisplayKind.Never => false,
BaseTypeDisplayKind.SolutionCode => typeElement is not ICompiledElement,
BaseTypeDisplayKind.SolutionCodeAndNonSystemExternalCode => !(typeElement is ICompiledElement && typeElement.IsInSystemLikeNamespace()),
BaseTypeDisplayKind.OnlyIfNotSystemObject => !typeElement.IsObjectClass(),
BaseTypeDisplayKind.Always => true,
_ => false
};
private static bool MatchesImplementedInterfacesDisplayKind(ITypeElement typeElement, ImplementedInterfacesDisplayKind displayKind)
=> displayKind switch {
ImplementedInterfacesDisplayKind.Never => false,
ImplementedInterfacesDisplayKind.SolutionCode => typeElement is not ICompiledElement,
ImplementedInterfacesDisplayKind.SolutionCodeAndNonSystemExternalCode => !(typeElement is ICompiledElement && typeElement.IsInSystemLikeNamespace()),
ImplementedInterfacesDisplayKind.Always => true,
_ => false
};
private static AttributeUsageContent GetAttributeUsage(IClass attributeClass) {
AttributeTargets targets;
bool allowMultiple;
bool inherited;
if (attributeClass.GetAttributeInstances(PredefinedType.ATTRIBUTE_USAGE_ATTRIBUTE_CLASS, true).FirstOrDefault() is { } attributeUsage) {
targets = (AttributeTargets?) (attributeUsage.PositionParameter(0).ConstantValue.Value as int?) ?? AttributeTargets.All;
allowMultiple = attributeUsage.NamedParameter(nameof(AttributeUsageAttribute.AllowMultiple)).ConstantValue.Value as bool? ?? false;
inherited = attributeUsage.NamedParameter(nameof(AttributeUsageAttribute.Inherited)).ConstantValue.Value as bool? ?? true;
}
else {
targets = AttributeTargets.All;
allowMultiple = attributeClass.HasAttributeInstance(PredefinedType.WINRT_ALLOW_MULTIPLE_ATTRIBUTE_CLASS, true);
inherited = true;
}
return new AttributeUsageContent(targets.ToHumanReadableString(), allowMultiple, inherited);
}
private IdentifierTooltipContent? TryPresentNonColorized(
IHighlighter? highlighter,
IDeclaredElement? element,
IContextBoundSettingsStore settings) {
if (highlighter?.TryGetTooltip(HighlighterTooltipKind.TextEditor) is not { } richTextToolTip)
return null;
RichText richText = richTextToolTip.RichText;
if (richText.IsNullOrEmpty())
return null;
var identifierContent = new IdentifierTooltipContent(richText, highlighter.Range);
if (element is not null && settings.GetValue((IdentifierTooltipSettings s) => s.ShowIcon))
identifierContent.Icon = TryGetIcon(element);
return identifierContent;
}
private static RichText? TryPresentDocNode(
XmlNode? xmlDoc,
string nodeName,
PsiLanguageType languageType,
IPsiModule psiModule) {
XmlNode? returnsNode = xmlDoc?.SelectSingleNode(nodeName);
if (returnsNode is null || !returnsNode.HasChildNodes)
return null;
var richText = XmlDocRichTextPresenterEx.Run(returnsNode, false, languageType, DeclaredElementPresenterTextStyles.Empty, psiModule).RichText;
return richText.IsNullOrEmpty() ? null : richText;
}
private static IEnumerable<ExceptionContent> GetExceptions(
XmlNode? xmlDoc,
PsiLanguageType languageType,
IPsiModule psiModule) {
if (xmlDoc?.SelectNodes("exception") is not { Count: > 0 } exceptionNodes)
return EmptyList<ExceptionContent>.InstanceList;
var exceptions = new LocalList<ExceptionContent>();
foreach (XmlNode exceptionNode in exceptionNodes) {
if (TryExtractException(exceptionNode as XmlElement, languageType, psiModule) is { } exceptionContent)
exceptions.Add(exceptionContent);
}
return exceptions.ResultingList();
}
private static IEnumerable<ParamContent> GetParams(
XmlNode? xmlDoc,
PsiLanguageType languageType,
IPsiModule psiModule) {
XmlNodeList? typeParamNodes = xmlDoc?.SelectNodes("typeparam");
XmlNodeList? paramNodes = xmlDoc?.SelectNodes("param");
Boolean paramExists = !(typeParamNodes?.Count == 0 && paramNodes?.Count == 0);
if (!paramExists)
return EmptyList<ParamContent>.InstanceList;
var paramNodesList = new LocalList<ParamContent>();
if (typeParamNodes != null) {
foreach (XmlNode paramNode in typeParamNodes) {
if (IdentifierTooltipContentProvider.TryExtractParams(paramNode as XmlElement, languageType, psiModule) is { } typeparam)
paramNodesList.Add(typeparam);
}
}
if (paramNodes != null) {
foreach (XmlNode paramNode in paramNodes) {
if (IdentifierTooltipContentProvider.TryExtractParams(paramNode as XmlElement, languageType, psiModule) is { } param)
paramNodesList.Add(param);
}
}
return paramNodesList.ResultingList();
}
private static ParamContent? TryExtractParams(
XmlElement? paramElement,
PsiLanguageType languageType,
IPsiModule psiModule) {
string? name = paramElement?.GetAttribute("name");
if (String.IsNullOrEmpty(name))
return null;
var paramContent = new ParamContent(name!);
RichText richText = XmlDocRichTextPresenterEx.Run(paramElement!, false, languageType, DeclaredElementPresenterTextStyles.Empty, psiModule).RichText;
if (!richText.IsNullOrEmpty())
paramContent.Description = richText;
return paramContent;
}
private static ExceptionContent? TryExtractException(
XmlElement? exceptionElement,
PsiLanguageType languageType,
IPsiModule psiModule) {
string? cref = exceptionElement?.GetAttribute("cref");
if (String.IsNullOrEmpty(cref))
return null;
cref = XmlDocPresenterUtil.ProcessCref(cref);
if (String.IsNullOrEmpty(cref))
return null;
var exceptionContent = new ExceptionContent(cref);
if (exceptionElement!.HasChildNodes) {
RichText richText = XmlDocRichTextPresenterEx.Run(exceptionElement, false, languageType, DeclaredElementPresenterTextStyles.Empty, psiModule).RichText;
if (!richText.IsNullOrEmpty())
exceptionContent.Description = richText;
}
return exceptionContent;
}
/// <summary>
/// Returns the description of an element, if available.
/// </summary>
/// <param name="element">The element whose description will be returned.</param>
/// <param name="xmlDoc">The XML documentation for <paramref name="element"/>.</param>
/// <param name="psiModule">The PSI module of the file containing the identifier.</param>
/// <param name="languageType">The type of language used to present the identifier.</param>
private RichText? TryGetDescription(
IDeclaredElement element,
XmlNode? xmlDoc,
IPsiModule psiModule,
PsiLanguageType languageType) {
if (TryPresentDocNode(xmlDoc, "summary", languageType, psiModule) is { } richText)
return richText;
return _declaredElementDescriptionPresenter
.GetDeclaredElementDescription(element, DeclaredElementDescriptionStyle.NO_OBSOLETE_SUMMARY_STYLE, languageType, psiModule)
?.RichText;
}
/// <summary>
/// Returns the obsolete message of an element, if available.
/// </summary>
/// <param name="element">The element whose description will be returned.</param>
/// <param name="psiModule">The PSI module of the file containing the identifier.</param>
/// <param name="languageType">The type of language used to present the identifier.</param>
private RichText? TryGetObsolete(
IDeclaredElement element,
IPsiModule psiModule,
PsiLanguageType languageType)
=> _declaredElementDescriptionPresenter
.GetDeclaredElementDescription(element, DeclaredElementDescriptionStyle.OBSOLETE_DESCRIPTION, languageType, psiModule)
?.RichText;
private static RichText? TryRemoveObsoletePrefix(RichText? text) {
if (text is null)
return null;
const string obsoletePrefix = "Obsolete: ";
IList<RichString> parts = text.GetFormattedParts();
if (parts.Count >= 2 && parts[0].Text == obsoletePrefix)
return text.Split(obsoletePrefix.Length)[1];
return text;
}
private IconId? TryGetIcon(IDeclaredElement declaredElement) {
var psiIconManager = _solution.GetComponent<PsiIconManager>();
return psiIconManager.GetImage(declaredElement, declaredElement.PresentationLanguage, true);
}
private IdentifierTooltipContent? TryPresentColorized(PresentableNode presentableNode, IContextBoundSettingsStore settings) {
if (presentableNode.Node is not { } node)
return null;
HighlighterIdProvider highlighterIdProvider = _highlighterIdProviderFactory.CreateProvider(settings);
RichText? identifierText = _colorizerPresenter.TryPresent(
node,
PresenterOptions.ForIdentifierToolTip(settings, true),
node.Language,
highlighterIdProvider);
if (identifierText is null || identifierText.IsEmpty)
return null;
var identifierContent = new IdentifierTooltipContent(identifierText, node.GetDocumentRange().TextRange);
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowIcon))
identifierContent.Icon = presentableNode.Icon;
return identifierContent;
}
/// <summary>
/// Finds a valid presentable element represented at a given <see cref="DocumentRange"/>.
/// </summary>
/// <param name="documentRange">The document range where to find a <see cref="IDeclaredElement"/> or a <see cref="ILiteralExpression"/>.</param>
/// <returns>A <see cref="PresentableInfo"/> which may not be valid if nothing was found.</returns>
private PresentableInfo FindPresentable(DocumentRange documentRange) {
if (documentRange.Document is not { } document || !documentRange.IsValid())
return default;
IPsiServices psiServices = _solution.GetPsiServices();
if (!psiServices.Files.AllDocumentsAreCommitted || psiServices.Caches.HasDirtyFiles)
return default;
return document
.GetPsiSourceFiles(_solution)
.SelectMany(
psiSourceFile => psiServices.Files.GetPsiFiles(psiSourceFile, documentRange),
(_, file) => FindPresentable(documentRange, file))
.FirstOrDefault(info => info.IsValid());
}
/// <summary>
/// Finds an element at a given file range, either a reference or a declaration.
/// </summary>
/// <param name="range">The range to get the element in <paramref name="file"/>.</param>
/// <param name="file">The file to search into.</param>
/// <returns>A <see cref="PresentableInfo"/> at range <paramref name="range"/> in <paramref name="file"/>, which may not be valid if nothing was found.</returns>
private static PresentableInfo FindPresentable(DocumentRange range, IFile file) {
if (!file.IsValid())
return default;
TreeTextRange treeTextRange = file.Translate(range);
if (!treeTextRange.IsValid())
return default;
var references = file.FindReferencesAt(treeTextRange);
DeclaredElementInfo? bestReference = null;
if (references.Count > 0) {
bestReference = GetBestReference(references.ToArray());
if (bestReference is not null
&& bestReference.Reference?.GetTreeNode() is not ICollectionElementInitializer) // we may do better than showing a collection initializer
return new PresentableInfo(bestReference);
}
// FindNodeAt seems to return the previous node on single-char literals (eg '0'). FindNodesAt is fine.
var node = file.FindNodesAt<ITreeNode>(treeTextRange).FirstOrDefault();
if (node is not null && node.IsValid()) {
if ((FindDeclaration(node, file) ?? FindSpecialElement(node, file)) is { } declaredElementInfo)
return new PresentableInfo(declaredElementInfo);
PresentableNode presentableNode = FindPresentableNode(node, file);
if (presentableNode.Node is not null)
return new PresentableInfo(presentableNode);
}
return new PresentableInfo(bestReference);
}
/// <summary>
/// Gets the best reference (the "deepest" one) from a collection of references.
/// </summary>
/// <param name="references">A collection of references.</param>
/// <returns>The <see cref="DeclaredElementInfo"/> corresponding to the best reference.</returns>
private static DeclaredElementInfo? GetBestReference(IReference[] references) {
SortReferences(references);
foreach (IReference reference in references) {
IResolveResult resolveResult = reference.Resolve().Result;
if (reference.CheckResolveResult() == ResolveErrorType.DYNAMIC)
return null;
if (resolveResult.DeclaredElement is { } foundElement) {
var referenceRange = reference.GetDocumentRange().TextRange;
return new DeclaredElementInfo(foundElement, resolveResult.Substitution, reference.GetTreeNode(), referenceRange, reference);
}
}
return null;
}
private static void SortReferences(IReference[] references) {
int count = references.Length;
if (count <= 1)
return;
int[] pathLengths = new int[count];
for (int i = 0; i < count; ++i) {
ITreeNode treeNode = references[i].GetTreeNode();
int pathToRootLength = treeNode.PathToRoot().Count();
pathLengths[i] = treeNode is ICollectionElementInitializer
? Int32.MaxValue - pathToRootLength // collection initializers have the lowest priority, and are reversed if nested
: pathToRootLength;
}
Array.Sort(pathLengths, references);
}
private static DeclaredElementInfo? FindDeclaration(ITreeNode node, IFile file) {
if (node.GetContainingNode<IDeclaration>(true) is not { } declaration)
return null;
TreeTextRange nameRange = declaration.GetNameRange();
if (!nameRange.IntersectsOrContacts(node.GetTreeTextRange()))
return null;
if (declaration.DeclaredElement is not { } declaredElement)
return null;
return new DeclaredElementInfo(declaredElement, EmptySubstitution.INSTANCE, node, file.GetDocumentRange(nameRange).TextRange, null);
}
private static DeclaredElementInfo? FindSpecialElement(ITreeNode node, IFile file)
=> LanguageManager.Instance.TryGetService<IPresentableNodeFinder>(file.Language) is { } finder
&& finder.FindDeclaredElement(node, file, out TextRange sourceRange) is { } declaredElementInstance
? new DeclaredElementInfo(declaredElementInstance.Element, declaredElementInstance.Substitution, node, sourceRange, null)
: null;
private static PresentableNode FindPresentableNode(ITreeNode node, IFile file) {
var finder = LanguageManager.Instance.TryGetService<IPresentableNodeFinder>(file.Language);
if (finder is null)
return default;
return finder.FindPresentableNode(node);
}
private ArgumentRoleTooltipContent? TryGetArgumentRoleContent(ITreeNode? node, IContextBoundSettingsStore settings) {
if (node is null || !settings.GetValue((IdentifierTooltipSettings s) => s.ShowArgumentsRole))
return null;
var argument = node.GetContainingNode<IArgument>();
if (argument?.MatchingParameter is not { } parameterInstance)
return null;
IParameter parameter = parameterInstance.Element;
if (parameter.ContainingParametersOwner is not { } parametersOwner)
return null;
HighlighterIdProvider highlighterIdProvider = _highlighterIdProviderFactory.CreateProvider(settings);
RichText final = new RichText("Argument of ", TextStyle.Default);
var parametersOwnerDisplay = _colorizerPresenter.TryPresent(
new DeclaredElementInstance(parametersOwner, parameterInstance.Substitution),
PresenterOptions.ForArgumentRoleParametersOwnerToolTip(settings),
argument.Language,
highlighterIdProvider,
node,
out _);
if (parametersOwnerDisplay is not null)
final.Append(parametersOwnerDisplay);
final.Append(": ", TextStyle.Default);
var parameterDisplay = _colorizerPresenter.TryPresent(
parameterInstance,
PresenterOptions.ForArgumentRoleParameterToolTip(settings),
argument.Language,
highlighterIdProvider,
node,
out _);
if (parameterDisplay is not null)
final.Append(parameterDisplay);
var content = new ArgumentRoleTooltipContent(final, argument.GetDocumentRange().TextRange) {
Description = TryGetDescription(parameter, parameter.GetXMLDoc(true), parameter.Module, argument.Language)
};
if (settings.GetValue((IdentifierTooltipSettings s) => s.ShowIcon))
content.Icon = PsiSymbolsThemedIcons.Parameter.Id;
return content;
}
public IdentifierTooltipContentProvider(
ISolution solution,
ColorizerPresenter colorizerPresenter,
IDeclaredElementDescriptionPresenter declaredElementDescriptionPresenter,
HighlighterIdProviderFactory highlighterIdProviderFactory) {
_solution = solution;
_colorizerPresenter = colorizerPresenter;
_declaredElementDescriptionPresenter = declaredElementDescriptionPresenter;
_highlighterIdProviderFactory = highlighterIdProviderFactory;
}
}
}
| |
// <copyright file="FirefoxDriverService.cs" company="WebDriver Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
// </copyright>
using System;
using System.Globalization;
using System.Net;
using System.Text;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Firefox
{
/// <summary>
/// Exposes the service provided by the native FirefoxDriver executable.
/// </summary>
public sealed class FirefoxDriverService : DriverService
{
private const string DefaultFirefoxDriverServiceFileName = "geckodriver";
private static readonly Uri FirefoxDriverDownloadUrl = new Uri("https://github.com/mozilla/geckodriver/releases");
private bool connectToRunningBrowser;
private bool openBrowserToolbox;
private int browserCommunicationPort = -1;
private string browserBinaryPath = string.Empty;
private string host = string.Empty;
private string browserCommunicationHost = string.Empty;
private FirefoxDriverLogLevel loggingLevel = FirefoxDriverLogLevel.Default;
/// <summary>
/// Initializes a new instance of the <see cref="FirefoxDriverService"/> class.
/// </summary>
/// <param name="executablePath">The full path to the Firefox driver executable.</param>
/// <param name="executableFileName">The file name of the Firefox driver executable.</param>
/// <param name="port">The port on which the Firefox driver executable should listen.</param>
private FirefoxDriverService(string executablePath, string executableFileName, int port)
: base(executablePath, port, executableFileName, FirefoxDriverDownloadUrl)
{
}
/// <summary>
/// Gets or sets the location of the Firefox binary executable.
/// </summary>
public string FirefoxBinaryPath
{
get { return this.browserBinaryPath; }
set { this.browserBinaryPath = value; }
}
/// <summary>
/// Gets or sets the port used by the driver executable to communicate with the browser.
/// </summary>
public int BrowserCommunicationPort
{
get { return this.browserCommunicationPort; }
set { this.browserCommunicationPort = value; }
}
/// <summary>
/// Gets or sets the value of the IP address of the host adapter used by the driver
/// executable to communicate with the browser.
/// </summary>
public string BrowserCommunicationHost
{
get { return this.browserCommunicationHost; }
set { this.browserCommunicationHost = value; }
}
/// <summary>
/// Gets or sets the value of the IP address of the host adapter on which the
/// service should listen for connections.
/// </summary>
public string Host
{
get { return this.host; }
set { this.host = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to connect to an already-running
/// instance of Firefox.
/// </summary>
public bool ConnectToRunningBrowser
{
get { return this.connectToRunningBrowser; }
set { this.connectToRunningBrowser = value; }
}
/// <summary>
/// Gets or sets a value indicating whether to open the Firefox Browser Toolbox
/// when Firefox is launched.
/// </summary>
public bool OpenBrowserToolbox
{
get { return this.openBrowserToolbox; }
set { this.openBrowserToolbox = value; }
}
/// <summary>
/// Gets or sets the level at which log output is displayed.
/// </summary>
/// <remarks>
/// This is largely equivalent to setting the <see cref="FirefoxOptions.LogLevel"/>
/// property, except the log level is set when the driver launches, instead of
/// when the browser is launched, meaning that initial driver logging before
/// initiation of a session can be controlled.
/// </remarks>
public FirefoxDriverLogLevel LogLevel
{
get { return this.loggingLevel; }
set { this.loggingLevel = value; }
}
/// <summary>
/// Gets a value indicating the time to wait for an initial connection before timing out.
/// </summary>
protected override TimeSpan InitializationTimeout
{
get { return TimeSpan.FromSeconds(2); }
}
/// <summary>
/// Gets a value indicating the time to wait for the service to terminate before forcing it to terminate.
/// </summary>
protected override TimeSpan TerminationTimeout
{
// Use a very small timeout for terminating the Firefox driver,
// because the executable does not have a clean shutdown command,
// which means we have to kill the process. Using a short timeout
// gets us to the termination point much faster.
get { return TimeSpan.FromMilliseconds(100); }
}
/// <summary>
/// Gets a value indicating whether the service has a shutdown API that can be called to terminate
/// it gracefully before forcing a termination.
/// </summary>
protected override bool HasShutdown
{
// The Firefox driver executable does not have a clean shutdown command,
// which means we have to kill the process.
get { return false; }
}
/// <summary>
/// Gets the command-line arguments for the driver service.
/// </summary>
protected override string CommandLineArguments
{
get
{
StringBuilder argsBuilder = new StringBuilder();
if (this.connectToRunningBrowser)
{
argsBuilder.Append(" --connect-existing");
}
if (this.browserCommunicationPort > 0)
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --marionette-port {0}", this.browserCommunicationPort);
}
if (!string.IsNullOrEmpty(this.browserCommunicationHost))
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --marionette-host \"{0}\"", this.host);
}
if (this.Port > 0)
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --port {0}", this.Port);
}
if (!string.IsNullOrEmpty(this.browserBinaryPath))
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --binary \"{0}\"", this.browserBinaryPath);
}
if (!string.IsNullOrEmpty(this.host))
{
argsBuilder.AppendFormat(CultureInfo.InvariantCulture, " --host \"{0}\"", this.host);
}
if (this.loggingLevel != FirefoxDriverLogLevel.Default)
{
argsBuilder.Append(string.Format(CultureInfo.InvariantCulture, " --log {0}", this.loggingLevel.ToString().ToLowerInvariant()));
}
if (this.openBrowserToolbox)
{
argsBuilder.Append(" --jsdebugger");
}
return argsBuilder.ToString().Trim();
}
}
/// <summary>
/// Creates a default instance of the FirefoxDriverService.
/// </summary>
/// <returns>A FirefoxDriverService that implements default settings.</returns>
public static FirefoxDriverService CreateDefaultService()
{
string serviceDirectory = DriverService.FindDriverServiceExecutable(FirefoxDriverServiceFileName(), FirefoxDriverDownloadUrl);
return CreateDefaultService(serviceDirectory);
}
/// <summary>
/// Creates a default instance of the FirefoxDriverService using a specified path to the Firefox driver executable.
/// </summary>
/// <param name="driverPath">The directory containing the Firefox driver executable.</param>
/// <returns>A FirefoxDriverService using a random port.</returns>
public static FirefoxDriverService CreateDefaultService(string driverPath)
{
return CreateDefaultService(driverPath, FirefoxDriverServiceFileName());
}
/// <summary>
/// Creates a default instance of the FirefoxDriverService using a specified path to the Firefox driver executable with the given name.
/// </summary>
/// <param name="driverPath">The directory containing the Firefox driver executable.</param>
/// <param name="driverExecutableFileName">The name of the Firefox driver executable file.</param>
/// <returns>A FirefoxDriverService using a random port.</returns>
public static FirefoxDriverService CreateDefaultService(string driverPath, string driverExecutableFileName)
{
return new FirefoxDriverService(driverPath, driverExecutableFileName, PortUtilities.FindFreePort());
}
/// <summary>
/// Returns the Firefox driver filename for the currently running platform
/// </summary>
/// <returns>The file name of the Firefox driver service executable.</returns>
private static string FirefoxDriverServiceFileName()
{
string fileName = DefaultFirefoxDriverServiceFileName;
// Unfortunately, detecting the currently running platform isn't as
// straightforward as you might hope.
// See: http://mono.wikia.com/wiki/Detecting_the_execution_platform
// and https://msdn.microsoft.com/en-us/library/3a8hyw88(v=vs.110).aspx
const int PlatformMonoUnixValue = 128;
switch (Environment.OSVersion.Platform)
{
case PlatformID.Win32NT:
case PlatformID.Win32S:
case PlatformID.Win32Windows:
case PlatformID.WinCE:
fileName += ".exe";
break;
case PlatformID.MacOSX:
case PlatformID.Unix:
break;
// Don't handle the Xbox case. Let default handle it.
// case PlatformID.Xbox:
// break;
default:
if ((int)Environment.OSVersion.Platform == PlatformMonoUnixValue)
{
break;
}
throw new WebDriverException("Unsupported platform: " + Environment.OSVersion.Platform);
}
return fileName;
}
}
}
| |
// The MIT License (MIT)
//
// Copyright (c) 2015 FPT Software
//
// 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.Drawing;
#if __UNIFIED__
using UIKit;
using Foundation;
using CoreGraphics;
using RectangleF = CoreGraphics.CGRect;
using SizeF = CoreGraphics.CGSize;
using PointF = CoreGraphics.CGPoint;
#else
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using MonoTouch.CoreGraphics;
using nfloat = global::System.Single;
using nint = global::System.Int32;
using nuint = global::System.UInt32;
#endif
//TODO: RIGHT_MODE UNCOMPLETED: transition and overlay (bachpx)
namespace SidebarNavigation
{
public class SidebarController : UIViewController
{
public const float DefaultFlingPercentage = 0.5f;
public const float DefaultFlingVelocity = 800f;
public const int DefaultMenuWidth = 230;
public enum MenuLocations{
Left = 1,
Right
}
#region Private Fields
private nfloat _slideSpeed = 0.2f;
private bool _isIos7 = false;
private bool _isOpen = false;
private bool _shadowShown;
private bool _openWhenRotated = false;
// for swipe gesture
private nfloat _panOriginX;
private bool _ignorePan;
// gesture recognizers
private UITapGestureRecognizer _tapGesture;
private UIPanGestureRecognizer _panGesture;
private UIImageView _statusImage;
private event UITouchEventArgs _shouldReceiveTouch;
private UIView _shadownOverlayContent;
private UIView _shadownOverlayMenu;
#endregion
#region Public Properties
/// <summary>
/// The view shown in the content area.
/// </summary>
public UIViewController ContentAreaController { get; private set; }
/// <summary>
/// Determines the percent of width to complete slide action.
/// </summary>
public float FlingPercentage { get; set; }
/// <summary>
/// Determines the minimum velocity considered a "fling" to complete slide action.
/// </summary>
public float FlingVelocity { get; set; }
/// <summary>
/// The view controller for the side menu.
/// This is what will be shown when the menu is displayed.
/// </summary>
public UIViewController MenuAreaController { get; private set; }
/// <summary>
/// Determines if the status bar should be made static.
/// </summary>
/// <value>True to make the status bar static, false to make it move with the content area.</value>
public bool StatusBarMoves { get; set; }
/// <summary>
/// Gets or sets a value indicating whether there should be shadowing effects on the content view.
/// </summary>
public bool HasShadowing { get; set; }
/// <summary>
/// Determines if the menu should be reopened after the screen is roated.
/// </summary>
public bool ReopenOnRotate { get; set; }
/// <summary>
/// Determines the width of the menu when open.
/// </summary>
public int MenuWidth { get; set; }
/// <summary>
/// Determines if the menu is on the left or right of the screen.
/// </summary>
public MenuLocations MenuLocation { get; set; }
/// <summary>
/// This Event will be called when the Side Menu is Opened/closed( at the end of the animation)
/// The Event Arg is a Boolean = isOpen.
/// </summary>
public event EventHandler<bool> StateChangeHandler;
/// <summary>
/// Gets the current state of the menu.
/// Setting this property will open/close the menu respectively.
/// </summary>
public bool IsOpen
{
get { return _isOpen; }
set
{
_isOpen = value;
if (value)
CloseMenu();
else
OpenMenu();
}
}
#endregion
#region Private Properties
/// <summary>
/// The UIView of the content view controller.
/// </summary>
private UIView _contentAreaView
{
get
{
if (ContentAreaController == null)
return null;
return ContentAreaController.View;
}
}
#endregion
#region Constructors
/// <summary>
/// Required contructor.
/// </summary>
public SidebarController(IntPtr handle) : base(handle)
{
}
/// <summary>
/// Contructor.
/// </summary>
/// <param name="contentAreaController">
/// The view controller for the content area.
/// </param>
/// <param name="navigationAreaController">
/// The view controller for the side menu.
/// </param>
public SidebarController(UIViewController rootViewController, UIViewController contentAreaController, UIViewController navigationAreaController)
{
Initialize(contentAreaController, navigationAreaController);
// handle wiring things up so events propogate properly
rootViewController.AddChildViewController(this);
rootViewController.View.AddSubview(this.View);
this.DidMoveToParentViewController(rootViewController);
}
#endregion
#region Public Methods
/// <summary>
/// Toggles the menu open or closed.
/// </summary>
public void ToggleMenu()
{
if (IsOpen)
CloseMenu();
else
OpenMenu();
}
/// <summary>
/// Shows the slideout navigation menu.
/// </summary>
public void OpenMenu()
{
if (IsOpen)
return;
ShowShadow(5);
var view = _contentAreaView;
view.EndEditing(true);
UIView.Animate(
_slideSpeed,
0,
UIViewAnimationOptions.CurveEaseInOut,
() => {
_shadownOverlayContent.Alpha = 0.7f;
_shadownOverlayMenu.Alpha = 0.0f;
if(MenuLocation == MenuLocations.Right){
view.Frame = new RectangleF (-MenuWidth, 0, view.Frame.Width, view.Frame.Height);
}else if(MenuLocation == MenuLocations.Left){
view.Frame = new RectangleF (MenuWidth, 0, view.Frame.Width, view.Frame.Height);
MenuAreaController.View.Frame = new RectangleF (0, 0, MenuAreaController.View.Frame.Width, MenuAreaController.View.Frame.Height);
}
},
() => {
if (view.Subviews.Length > 0)
view.Subviews[0].UserInteractionEnabled = false;
view.AddGestureRecognizer(_tapGesture);
_isOpen = true;
if (StateChangeHandler != null) {
StateChangeHandler.Invoke(this, _isOpen);
}
});
}
/// <summary>
/// Hides the slideout navigation menu.
/// </summary>
public void CloseMenu(bool animate = true)
{
if (!IsOpen)
return;
MenuAreaController.View.EndEditing(true);
var view = _contentAreaView;
#if __UNIFIED__
Action animation;
Action finished;
#else
NSAction animation;
NSAction finished;
#endif
animation = () => {
view.Frame = new RectangleF (0, 0, view.Frame.Width, view.Frame.Height);
MenuAreaController.View.Frame = new RectangleF (-MenuWidth, 0, MenuAreaController.View.Frame.Width, MenuAreaController.View.Frame.Height);
_shadownOverlayContent.Alpha = 0.0f;
_shadownOverlayMenu.Alpha = 1.0f;
};
// Action animationSh = () => { };
// animationSh ();
finished = () => {
if (view.Subviews.Length > 0)
view.Subviews[0].UserInteractionEnabled = true;
view.RemoveGestureRecognizer (_tapGesture);
_isOpen = false;
if (StateChangeHandler != null) {
StateChangeHandler.Invoke(this, _isOpen);
}
};
if (animate)
UIView.Animate(_slideSpeed, 0, UIViewAnimationOptions.CurveEaseInOut, animation, finished);
else {
// fire the animation results manually
animation();
finished();
}
HideShadow();
}
/// <summary>
/// Replaces the content area view controller with the specified view controller.
/// </summary>
/// <param name="newContentView">
/// New content view.
/// </param>
public void ChangeContentView(UIViewController newContentView) {
if (_contentAreaView != null)
_contentAreaView.RemoveFromSuperview();
if (ContentAreaController != null)
ContentAreaController.RemoveFromParentViewController ();
ContentAreaController = newContentView;
SetVisibleView();
CloseMenu();
// setup a tap gesture to close the menu on root view tap
_tapGesture = new UITapGestureRecognizer ();
_tapGesture.AddTarget (() => CloseMenu());
_tapGesture.NumberOfTapsRequired = 1;
_panGesture = new UIPanGestureRecognizer {
Delegate = new SlideoutPanDelegate(),
MaximumNumberOfTouches = 1,
MinimumNumberOfTouches = 1
};
_panGesture.AddTarget (() => Pan (_contentAreaView));
_contentAreaView.AddGestureRecognizer(_panGesture);
}
#endregion
#region Private Methods
private void Initialize(UIViewController currentViewController, UIViewController navigationViewController)
{
ContentAreaController = currentViewController;
MenuAreaController = navigationViewController;
// set default fling percentage
FlingPercentage = DefaultFlingPercentage;
// set default fling velocity
FlingVelocity = DefaultFlingVelocity;
// place menu on right by default
MenuLocation = MenuLocations.Right;
// set default menu width
MenuWidth = DefaultMenuWidth;
// enable shadow by default
HasShadowing = true;
// enable menu reopening on rotate by default
ReopenOnRotate = true;
// make the status bar static
StatusBarMoves = true;
_statusImage = new UIImageView();
// set iOS 7 flag
var version = new System.Version(UIDevice.CurrentDevice.SystemVersion);
_isIos7 = version.Major >= 7;
// add the navigation view on the right
RectangleF navigationFrame;
navigationFrame = MenuAreaController.View.Frame;
navigationFrame.X = navigationFrame.Width - MenuWidth;
navigationFrame.Width = MenuWidth;
MenuAreaController.View.Frame = navigationFrame;
View.AddSubview(MenuAreaController.View);
ChangeContentView(currentViewController);
MenuAreaController.View.Frame = new RectangleF (-MenuWidth, 0, MenuAreaController.View.Frame.Width, MenuAreaController.View.Frame.Height);
_shadownOverlayContent = new UIView ();
_shadownOverlayContent.Frame = View.Frame;
_shadownOverlayContent.BackgroundColor = UIColor.Black;
ContentAreaController.View.AddSubview (_shadownOverlayContent);
_shadownOverlayMenu = new UIView ();
_shadownOverlayMenu.Frame = new RectangleF (0, 0, MenuWidth, MenuAreaController.View.Frame.Height);
_shadownOverlayMenu.BackgroundColor = UIColor.Black;
MenuAreaController.View.AddSubview (_shadownOverlayMenu);
_shadownOverlayContent.Alpha = 0.0f;
_shadownOverlayMenu.Alpha = 0.0f;
}
/// <summary>
/// Places the root view on top of the navigation view.
/// </summary>
private void SetVisibleView()
{
if(!StatusBarMoves)
UIApplication.SharedApplication.SetStatusBarHidden(false, UIStatusBarAnimation.Fade);
RectangleF frame = View.Bounds;
if (IsOpen)
frame.X = MenuWidth;
SetViewSize();
SetLocation(frame);
View.AddSubview(_contentAreaView);
AddChildViewController(ContentAreaController);
}
/// <summary>
/// Sets the size of the root view.
/// </summary>
private void SetViewSize()
{
RectangleF frame = View.Bounds;
if (_contentAreaView.Bounds == frame)
return;
_contentAreaView.Bounds = frame;
}
/// <summary>
/// Sets the location of the root view.
/// </summary>
/// <param name="frame">Frame.</param>
private void SetLocation(RectangleF frame)
{
frame.Y = 0;
_contentAreaView.Layer.AnchorPoint = new PointF (.5f, .5f);
// exit if we're already at the desired location
if (_contentAreaView.Frame.Location == frame.Location)
return;
frame.Size = _contentAreaView.Frame.Size;
// set the root views cetner
var center = new PointF(frame.Left + frame.Width / 2,
frame.Top + frame.Height / 2);
_contentAreaView.Center = center;
// if x is greater than 0 then position the status view
if (Math.Abs(frame.X - 0) > float.Epsilon)
{
GetStatusImage();
var statusFrame = _statusImage.Frame;
statusFrame.X = _contentAreaView.Frame.X;
_statusImage.Frame = statusFrame;
}
}
/// <summary>
/// Pan the specified view.
/// </summary>
private void Pan(UIView view)
{
if (_panGesture.State == UIGestureRecognizerState.Began) {
_panOriginX = view.Frame.X;
if (MenuLocation == MenuLocations.Left)
_ignorePan = _panGesture.LocationInView(view).X > 50;
else
_ignorePan = _panGesture.LocationInView(view).X < view.Bounds.Width - 50;
} else if (!_ignorePan && (_panGesture.State == UIGestureRecognizerState.Changed)) {
var t = _panGesture.TranslationInView(view).X;
if (MenuLocation == MenuLocations.Left) {
if ((t > 0 && !IsOpen) || (t < 0 && IsOpen)) {
if (t > MenuWidth)
t = MenuWidth;
else if (t < -MenuWidth && IsOpen)
t = MenuWidth;
if (_panOriginX + t <= MenuWidth) {
view.Frame = new RectangleF (_panOriginX + t, view.Frame.Y, view.Frame.Width, view.Frame.Height);
MenuAreaController.View.Frame = new RectangleF (_panOriginX + t - MenuWidth, MenuAreaController.View.Frame.Y, MenuAreaController.View.Frame.Width, MenuAreaController.View.Frame.Height);
//view.Alpha = 1.0f - ((_panOriginX + t) / MenuWidth)/2;
_shadownOverlayContent.Alpha = ((_panOriginX + t) / MenuWidth)*0.7f;
_shadownOverlayMenu.Alpha = 1.0f - ((_panOriginX + t) / MenuWidth);
}
ShowShadowWhileDragging();
}
} else if (MenuLocation == MenuLocations.Right) {
if ((t < 0 && !IsOpen) || (t > 0 && IsOpen)) {
if (t < -MenuWidth)
t = -MenuWidth;
else if (t > MenuWidth)
t = MenuWidth;
if (_panOriginX + t <= 0)
view.Frame = new RectangleF(_panOriginX + t, view.Frame.Y, view.Frame.Width, view.Frame.Height);
ShowShadowWhileDragging();
}
}
} else if (!_ignorePan && (_panGesture.State == UIGestureRecognizerState.Ended || _panGesture.State == UIGestureRecognizerState.Cancelled)) {
var t = _panGesture.TranslationInView(view).X;
var velocity = _panGesture.VelocityInView(view).X;
if ((MenuLocation == MenuLocations.Left && IsOpen && t < 0) || (MenuLocation == MenuLocations.Right && IsOpen && t > 0)) {
if (view.Frame.X > -view.Frame.Width / 2) {
CloseMenu();
} else {
UIView.Animate(_slideSpeed, 0, UIViewAnimationOptions.CurveEaseInOut,
() => {
view.Frame = new RectangleF(-MenuWidth, view.Frame.Y, view.Frame.Width, view.Frame.Height);
}, () => {
});
}
} if ((MenuLocation == MenuLocations.Left && (velocity > FlingVelocity || view.Frame.X > (MenuWidth * FlingPercentage)))
|| (MenuLocation == MenuLocations.Right && (velocity < -FlingVelocity || view.Frame.X < -(MenuWidth * FlingPercentage)))) {
OpenMenu();
} else {
UIView.Animate(_slideSpeed, 0, UIViewAnimationOptions.CurveEaseInOut,
() =>
{
view.Frame = new RectangleF(0, 0, view.Frame.Width, view.Frame.Height);
}, () =>
{
});
}
}
}
/// <summary>
/// Shows the shadow of the root view while dragging.
/// </summary>
private void ShowShadowWhileDragging()
{
if (!HasShadowing)
return;
_contentAreaView.Layer.ShadowOffset = new SizeF(1, 1);
_contentAreaView.Layer.ShadowPath = UIBezierPath.FromRect (_contentAreaView.Bounds).CGPath;
_contentAreaView.Layer.ShadowRadius = 4.0f;
_contentAreaView.Layer.ShadowOpacity = 0.5f;
_contentAreaView.Layer.ShadowColor = UIColor.Black.CGColor;
}
/// <summary>
/// Shows the shadow.
/// </summary>
private void ShowShadow(float position)
{
//Dont need to call this twice if its already shown
if (!HasShadowing || _shadowShown)
return;
_contentAreaView.Layer.ShadowOffset = new SizeF(position, 0);
_contentAreaView.Layer.ShadowPath = UIBezierPath.FromRect (_contentAreaView.Bounds).CGPath;
_contentAreaView.Layer.ShadowRadius = 4.0f;
_contentAreaView.Layer.ShadowOpacity = 0.5f;
_contentAreaView.Layer.ShadowColor = UIColor.Black.CGColor;
_shadowShown = true;
}
/// <summary>
/// Hides the shadow of the root view.
/// </summary>
private void HideShadow()
{
//Dont need to call this twice if its already hidden
if (!HasShadowing || !_shadowShown)
return;
_contentAreaView.Layer.ShadowOffset = new SizeF (0, 0);
_contentAreaView.Layer.ShadowRadius = 0.0f;
_contentAreaView.Layer.ShadowOpacity = 0.0f;
_contentAreaView.Layer.ShadowColor = UIColor.Clear.CGColor;
_shadowShown = false;
}
/// <summary>
/// Places the static status image.
/// </summary>
private void GetStatusImage()
{
if (StatusBarMoves || !_isIos7 || _statusImage.Superview != null)
return;
this.View.AddSubview(_statusImage);
_statusImage.Image = CaptureStatusBarImage();
_statusImage.Frame = UIApplication.SharedApplication.StatusBarFrame;
UIApplication.SharedApplication.StatusBarHidden = true;
}
/// <summary>
/// Gets a static image of the status bar.
/// </summary>
private UIImage CaptureStatusBarImage()
{
var frame = UIApplication.SharedApplication.StatusBarFrame;
frame.Width *= 2;
frame.Height *= 2;
var image = CGImage.ScreenImage;
image = image.WithImageInRect(frame);
var newImage = new UIImage(image).Scale(UIApplication.SharedApplication.StatusBarFrame.Size, 2f);
return newImage;
}
/// <summary>
/// Hides the static status bar image.
/// </summary>
private void HideStatusImage()
{
if (!_isIos7)
return;
_statusImage.RemoveFromSuperview();
UIApplication.SharedApplication.StatusBarHidden = false;
}
/// <summary>
/// Hides the static status bar when the close animation completes
/// </summary>
[Export("animationEnded")]
private void HideComplete()
{
HideStatusImage();
}
/// <summary>
/// Should the receive touch.
/// </summary>
internal bool ShouldReceiveTouch(UIGestureRecognizer gesture, UITouch touch)
{
if (_shouldReceiveTouch != null)
return _shouldReceiveTouch(gesture, touch);
return true;
}
#endregion
private class SlideoutPanDelegate : UIGestureRecognizerDelegate
{
public override bool ShouldReceiveTouch (UIGestureRecognizer recognizer, UITouch touch)
{
return true;
}
}
public override void ViewDidLayoutSubviews()
{
base.ViewDidLayoutSubviews();
RectangleF navigationFrame = View.Bounds;
if (MenuLocation == MenuLocations.Right) {
navigationFrame.X = navigationFrame.Width - MenuWidth;
} else if (MenuLocation == MenuLocations.Left) {
navigationFrame.X = 0;
}
navigationFrame.Width = MenuWidth;
if (MenuAreaController.View.Frame != navigationFrame)
MenuAreaController.View.Frame = navigationFrame;
}
public override void ViewWillAppear(bool animated)
{
RectangleF navigationFrame = MenuAreaController.View.Frame;
if (MenuLocation == MenuLocations.Right) {
navigationFrame.X = navigationFrame.Width - MenuWidth;
} else if (MenuLocation == MenuLocations.Left) {
navigationFrame.X = 0;
}
navigationFrame.Width = MenuWidth;
navigationFrame.Location = PointF.Empty;
MenuAreaController.View.Frame = navigationFrame;
View.SetNeedsLayout();
base.ViewWillAppear(animated);
}
public override void WillRotate(UIInterfaceOrientation toInterfaceOrientation, double duration)
{
base.WillRotate(toInterfaceOrientation, duration);
if (IsOpen)
_openWhenRotated = true;
this.CloseMenu(false);
}
public override void DidRotate(UIInterfaceOrientation fromInterfaceOrientation)
{
base.DidRotate(fromInterfaceOrientation);
if (_openWhenRotated && ReopenOnRotate)
OpenMenu();
_openWhenRotated = false;
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Win32;
namespace Microsoft.PythonTools.Profiling {
using Infrastructure;
using IServiceProvider = System.IServiceProvider;
/// <summary>
/// Represents an individual profiling session. We have nodes:
/// 0 - the configuration for what to profile
/// 1 - a folder, sessions that have been run
/// 2+ - the sessions themselves.
///
/// This looks like:
/// Root
/// Target
/// Sessions
/// Session #1
/// Session #2
/// </summary>
class SessionNode : BaseHierarchyNode, IVsHierarchyDeleteHandler, IVsPersistHierarchyItem {
private readonly string _filename;
private readonly uint _docCookie;
internal bool _isDirty, _neverSaved;
private bool _isReportsExpanded;
private readonly SessionsNode _parent;
internal readonly IServiceProvider _serviceProvider;
private ProfilingTarget _target;
private AutomationSession _automationSession;
internal readonly uint ItemId;
//private const int ConfigItemId = 0;
private const int ReportsItemId = 1;
internal const uint StartingReportId = 2;
public SessionNode(IServiceProvider serviceProvider, SessionsNode parent, ProfilingTarget target, string filename) {
_serviceProvider = serviceProvider;
_parent = parent;
_target = target;
_filename = filename;
// Register this with the running document table. This will prompt
// for save when the file is dirty and by responding to GetProperty
// for VSHPROPID_ItemDocCookie we will support Ctrl-S when one of
// our files is dirty.
// http://msdn.microsoft.com/en-us/library/bb164600(VS.80).aspx
var rdt = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable));
Debug.Assert(rdt != null, "_serviceProvider has no RDT service");
uint cookie;
IntPtr punkDocData = Marshal.GetIUnknownForObject(this);
try {
ErrorHandler.ThrowOnFailure(rdt.RegisterAndLockDocument(
(uint)(_VSRDTFLAGS.RDT_VirtualDocument | _VSRDTFLAGS.RDT_EditLock | _VSRDTFLAGS.RDT_CanBuildFromMemory),
filename,
this,
VSConstants.VSITEMID_ROOT,
punkDocData,
out cookie
));
} finally {
if (punkDocData != IntPtr.Zero) {
Marshal.Release(punkDocData);
}
}
_docCookie = cookie;
ItemId = parent._sessionsCollection.Add(this);
}
public IPythonProfileSession GetAutomationObject() {
if (_automationSession == null) {
_automationSession = new AutomationSession(this);
}
return _automationSession;
}
public SortedDictionary<uint, Report> Reports {
get {
if (_target.Reports == null) {
_target.Reports = new Reports();
}
if (_target.Reports.AllReports == null) {
_target.Reports.AllReports = new SortedDictionary<uint, Report>();
}
return _target.Reports.AllReports;
}
}
public string Caption {
get {
string name = Name;
if (_isDirty) {
return Strings.CaptionDirty.FormatUI(name);
}
return name;
}
}
public ProfilingTarget Target {
get {
return _target;
}
}
public override int SetProperty(uint itemid, int propid, object var) {
var prop = (__VSHPROPID)propid;
switch (prop) {
case __VSHPROPID.VSHPROPID_Expanded:
if (itemid == ReportsItemId) {
_isReportsExpanded = Convert.ToBoolean(var);
break;
}
break;
}
return base.SetProperty(itemid, propid, var);
}
public override int GetProperty(uint itemid, int propid, out object pvar) {
// GetProperty is called many many times for this particular property
pvar = null;
var prop = (__VSHPROPID)propid;
switch (prop) {
case __VSHPROPID.VSHPROPID_Parent:
if (itemid == ReportsItemId) {
pvar = VSConstants.VSITEMID_ROOT;
} else if (IsReportItem(itemid)) {
pvar = ReportsItemId;
}
break;
case __VSHPROPID.VSHPROPID_FirstChild:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = ReportsItemId;
} else if (itemid == ReportsItemId && Reports.Count > 0) {
pvar = Reports.First().Key;
} else {
pvar = VSConstants.VSITEMID_NIL;
}
break;
case __VSHPROPID.VSHPROPID_NextSibling:
pvar = VSConstants.VSITEMID_NIL;
if (IsReportItem(itemid)) {
var items = Reports.Keys.ToArray();
for (int i = 0; i < items.Length; i++) {
if (items[i] > (int)itemid) {
pvar = itemid + 1;
break;
}
}
}
break;
case __VSHPROPID.VSHPROPID_ItemDocCookie:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = (int)_docCookie;
}
break;
case __VSHPROPID.VSHPROPID_Expandable:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = true;
} else if (itemid == ReportsItemId && Reports.Count > 0) {
pvar = true;
} else {
pvar = false;
}
break;
case __VSHPROPID.VSHPROPID_ExpandByDefault:
pvar = true;
break;
case __VSHPROPID.VSHPROPID_IconImgList:
case __VSHPROPID.VSHPROPID_OpenFolderIconHandle:
pvar = (int)SessionsNode._imageList.Handle;
break;
case __VSHPROPID.VSHPROPID_IconIndex:
case __VSHPROPID.VSHPROPID_OpenFolderIconIndex:
if (itemid == ReportsItemId) {
if (_isReportsExpanded) {
pvar = (int)TreeViewIconIndex.OpenFolder;
} else {
pvar = (int)TreeViewIconIndex.CloseFolder;
}
} else if (IsReportItem(itemid)) {
pvar = (int)TreeViewIconIndex.GreenNotebook;
}
break;
case __VSHPROPID.VSHPROPID_Caption:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = Caption;
} else if (itemid == ReportsItemId) {
pvar = Strings.Reports;
} else if (IsReportItem(itemid)) {
pvar = Path.GetFileNameWithoutExtension(GetReport(itemid).Filename);
}
break;
case __VSHPROPID.VSHPROPID_ParentHierarchy:
if (itemid == VSConstants.VSITEMID_ROOT) {
pvar = _parent as IVsHierarchy;
}
break;
}
if (pvar != null)
return VSConstants.S_OK;
return VSConstants.DISP_E_MEMBERNOTFOUND;
}
public override int ExecCommand(uint itemid, ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (pguidCmdGroup == VsMenus.guidVsUIHierarchyWindowCmds) {
switch ((VSConstants.VsUIHierarchyWindowCmdIds)nCmdID) {
case VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_DoubleClick:
case VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_EnterKey:
if (itemid == VSConstants.VSITEMID_ROOT) {
OpenTargetProperties();
// S_FALSE: don't process the double click to expand the item
return VSConstants.S_FALSE;
} else if (IsReportItem(itemid)) {
OpenProfile(itemid);
}
return (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED;
case VSConstants.VsUIHierarchyWindowCmdIds.UIHWCMDID_RightClick:
int? ctxMenu = null;
if (itemid == VSConstants.VSITEMID_ROOT) {
ctxMenu = (int)PkgCmdIDList.menuIdPerfContext;
} else if (itemid == ReportsItemId) {
ctxMenu = (int)PkgCmdIDList.menuIdPerfReportsContext;
} else if (IsReportItem(itemid)) {
ctxMenu = (int)PkgCmdIDList.menuIdPerfSingleReportContext;
}
if (ctxMenu != null) {
var uishell = (IVsUIShell)_serviceProvider.GetService(typeof(SVsUIShell));
if (uishell != null) {
var pt = System.Windows.Forms.Cursor.Position;
var pnts = new[] { new POINTS { x = (short)pt.X, y = (short)pt.Y } };
var guid = GuidList.guidPythonProfilingCmdSet;
int hr = uishell.ShowContextMenu(
0,
ref guid,
ctxMenu.Value,
pnts,
new ContextCommandTarget(this, itemid));
ErrorHandler.ThrowOnFailure(hr);
}
}
break;
}
}
return base.ExecCommand(itemid, ref pguidCmdGroup, nCmdID, nCmdexecopt, pvaIn, pvaOut);
}
internal ProfilingTarget OpenTargetProperties() {
var targetView = new ProfilingTargetView(_serviceProvider, _target);
var dialog = new LaunchProfiling(_serviceProvider, targetView);
var res = dialog.ShowModal() ?? false;
if (res && targetView.IsValid) {
var target = targetView.GetTarget();
if (target != null && !ProfilingTarget.IsSame(target, _target)) {
_target = target;
MarkDirty();
return _target;
}
}
return null;
}
private void OpenProfile(uint itemid) {
var item = GetReport(itemid);
if (!File.Exists(item.Filename)) {
MessageBox.Show(Strings.PerformanceReportNotFound.FormatUI(item.Filename), Strings.ProductTitle);
} else {
var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));
dte.ItemOperations.OpenFile(item.Filename);
}
}
class ContextCommandTarget : IOleCommandTarget {
private readonly SessionNode _node;
private readonly uint _itemid;
public ContextCommandTarget(SessionNode node, uint itemid) {
_node = node;
_itemid = itemid;
}
#region IOleCommandTarget Members
public int Exec(ref Guid pguidCmdGroup, uint nCmdID, uint nCmdexecopt, IntPtr pvaIn, IntPtr pvaOut) {
if (pguidCmdGroup == GuidList.guidPythonProfilingCmdSet) {
switch (nCmdID) {
case PkgCmdIDList.cmdidOpenReport:
_node.OpenProfile(_itemid);
return VSConstants.S_OK;
case PkgCmdIDList.cmdidPerfCtxSetAsCurrent:
_node._parent.SetActiveSession(_node);
return VSConstants.S_OK;
case PkgCmdIDList.cmdidPerfCtxStartProfiling:
_node.StartProfiling();
return VSConstants.S_OK;
case PkgCmdIDList.cmdidReportsCompareReports: {
CompareReportsView compareView;
if (_node.IsReportItem(_itemid)) {
var report = _node.GetReport(_itemid);
compareView = new CompareReportsView(report.Filename);
} else {
compareView = new CompareReportsView();
}
var dialog = new CompareReportsWindow(compareView);
var res = dialog.ShowModal() ?? false;
if (res && compareView.IsValid) {
IVsUIShellOpenDocument sod = _node._serviceProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
if (sod == null) {
return VSConstants.E_FAIL;
}
Microsoft.VisualStudio.Shell.Interop.IVsWindowFrame frame = null;
Guid guid = new Guid("{9C710F59-984F-4B83-B781-B6356C363B96}"); // performance diff guid
Guid guidNull = Guid.Empty;
sod.OpenSpecificEditor(
(uint)(_VSRDTFLAGS.RDT_CantSave | _VSRDTFLAGS.RDT_DontAddToMRU | _VSRDTFLAGS.RDT_NonCreatable | _VSRDTFLAGS.RDT_NoLock),
compareView.GetComparisonUri(),
ref guid,
null,
ref guidNull,
Strings.PerformanceComparisonTitle,
_node,
_itemid,
IntPtr.Zero,
null,
out frame
);
if (frame != null) {
Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(frame.Show());
}
}
return VSConstants.S_OK;
}
case PkgCmdIDList.cmdidReportsAddReport: {
var dialog = new OpenFileDialog();
dialog.Filter = PythonProfilingPackage.PerformanceFileFilter;
dialog.CheckFileExists = true;
var res = dialog.ShowDialog() ?? false;
if (res) {
_node.AddProfile(dialog.FileName);
}
return VSConstants.S_OK;
}
}
} else if (pguidCmdGroup == VSConstants.GUID_VSStandardCommandSet97) {
switch((VSConstants.VSStd97CmdID)nCmdID) {
case VSConstants.VSStd97CmdID.PropSheetOrProperties:
_node.OpenTargetProperties();
return VSConstants.S_OK;
}
}
return (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED;
}
public int QueryStatus(ref Guid pguidCmdGroup, uint cCmds, OLECMD[] prgCmds, IntPtr pCmdText) {
return (int)Microsoft.VisualStudio.OLE.Interop.Constants.OLECMDERR_E_NOTSUPPORTED;
}
#endregion
}
internal void MarkDirty() {
_isDirty = true;
OnPropertyChanged(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Caption, 0);
}
public override int QueryStatusCommand(uint itemid, ref Guid pguidCmdGroup, uint cCmds, VisualStudio.OLE.Interop.OLECMD[] prgCmds, IntPtr pCmdText) {
return base.QueryStatusCommand(itemid, ref pguidCmdGroup, cCmds, prgCmds, pCmdText);
}
private bool IsReportItem(uint itemid) {
return itemid >= StartingReportId && Reports.ContainsKey(itemid);
}
private Report GetReport(uint itemid) {
return Reports[itemid];
}
public void AddProfile(string filename) {
if (_target.Reports == null) {
_target.Reports = new Reports(new[] { new Report(filename) });
} else {
if (_target.Reports.Report == null) {
_target.Reports.Report = new Report[0];
}
uint prevSibling, newId;
if (Reports.Count > 0) {
prevSibling = (uint)Reports.Last().Key;
newId = prevSibling + 1;
} else {
prevSibling = VSConstants.VSITEMID_NIL;
newId = StartingReportId;
}
Reports[newId] = new Report(filename);
OnItemAdded(
ReportsItemId,
prevSibling,
newId
);
}
MarkDirty();
}
public void Save(VSSAVEFLAGS flags, out int pfCanceled) {
pfCanceled = 0;
switch (flags) {
case VSSAVEFLAGS.VSSAVE_Save:
if (_neverSaved) {
goto case VSSAVEFLAGS.VSSAVE_SaveAs;
}
Save(_filename);
break;
case VSSAVEFLAGS.VSSAVE_SaveAs:
case VSSAVEFLAGS.VSSAVE_SaveCopyAs:
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.FileName = _filename;
if (saveDialog.ShowDialog() == true) {
Save(saveDialog.FileName);
_neverSaved = false;
} else {
pfCanceled = 1;
}
break;
}
}
internal void Removed() {
IVsRunningDocumentTable rdt = _serviceProvider.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)_VSRDTFLAGS.RDT_EditLock, _docCookie));
}
#region IVsHierarchyDeleteHandler Members
public int DeleteItem(uint dwDelItemOp, uint itemid) {
Debug.Assert(_target.Reports != null && _target.Reports.Report != null && _target.Reports.Report.Length > 0);
var report = GetReport(itemid);
Reports.Remove(itemid);
OnItemDeleted(itemid);
OnInvalidateItems(ReportsItemId);
if (File.Exists(report.Filename) && dwDelItemOp == (uint)__VSDELETEITEMOPERATION.DELITEMOP_DeleteFromStorage) {
// close the file if it's open before deleting it...
var dte = (EnvDTE.DTE)_serviceProvider.GetService(typeof(EnvDTE.DTE));
if (dte.ItemOperations.IsFileOpen(report.Filename)) {
var doc = dte.Documents.Item(report.Filename);
doc.Close();
}
File.Delete(report.Filename);
}
return VSConstants.S_OK;
}
public int QueryDeleteItem(uint dwDelItemOp, uint itemid, out int pfCanDelete) {
if (IsReportItem(itemid)) {
pfCanDelete = 1;
return VSConstants.S_OK;
}
pfCanDelete = 0;
return VSConstants.S_OK;
}
#endregion
internal void StartProfiling(bool openReport = true) {
PythonProfilingPackage.Instance.StartProfiling(_target, this, openReport);
}
public void Save(string filename = null) {
if (filename == null) {
filename = _filename;
}
using (var stream = new FileStream(filename, FileMode.Create)) {
ProfilingTarget.Serializer.Serialize(
stream,
_target
);
_isDirty = false;
stream.Close();
OnPropertyChanged(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Caption, 0);
}
}
public string Filename { get { return _filename; } }
public string Name {
get {
return Path.GetFileNameWithoutExtension(_filename);
}
}
public bool IsSaved {
get {
return !_isDirty && !_neverSaved;
}
}
#region IVsPersistHierarchyItem Members
public int IsItemDirty(uint itemid, IntPtr punkDocData, out int pfDirty) {
if (itemid == VSConstants.VSITEMID_ROOT) {
pfDirty = _isDirty ? 1 : 0;
return VSConstants.S_OK;
} else {
pfDirty = 0;
return VSConstants.E_FAIL;
}
}
public int SaveItem(VSSAVEFLAGS dwSave, string pszSilentSaveAsName, uint itemid, IntPtr punkDocData, out int pfCanceled) {
if (itemid == VSConstants.VSITEMID_ROOT) {
Save(dwSave, out pfCanceled);
return VSConstants.S_OK;
}
pfCanceled = 0;
return VSConstants.E_FAIL;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ExtendToVector256UInt64()
{
var test = new GenericUnaryOpTest__ExtendToVector256UInt64();
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 GenericUnaryOpTest__ExtendToVector256UInt64
{
private struct TestStruct
{
public Vector128<UInt64> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref testStruct._fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
return testStruct;
}
public void RunStructFldScenario(GenericUnaryOpTest__ExtendToVector256UInt64 testClass)
{
var result = Avx.ExtendToVector256<UInt64>(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt64>>() / sizeof(UInt64);
private static UInt64[] _data = new UInt64[Op1ElementCount];
private static Vector128<UInt64> _clsVar;
private Vector128<UInt64> _fld;
private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable;
static GenericUnaryOpTest__ExtendToVector256UInt64()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
}
public GenericUnaryOpTest__ExtendToVector256UInt64()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt64(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx.ExtendToVector256<UInt64>(
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx.ExtendToVector256<UInt64>(
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx.ExtendToVector256<UInt64>(
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(UInt64) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(UInt64) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx).GetMethod(nameof(Avx.ExtendToVector256))
.MakeGenericMethod( new Type[] { typeof(UInt64) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt64>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx.ExtendToVector256<UInt64>(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr);
var result = Avx.ExtendToVector256<UInt64>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Avx.ExtendToVector256<UInt64>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr));
var result = Avx.ExtendToVector256<UInt64>(firstOp);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new GenericUnaryOpTest__ExtendToVector256UInt64();
var result = Avx.ExtendToVector256<UInt64>(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx.ExtendToVector256<UInt64>(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx.ExtendToVector256(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] inArray = new UInt64[Op1ElementCount];
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt64>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
if (firstOp[0] != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((i < (RetElementCount / 2)) ? firstOp[i] : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.ExtendToVector256)}<UInt64>(Vector128<UInt64>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.TrafficManager.Fluent
{
using ResourceManager.Fluent.Core;
using TrafficManagerEndpoint.UpdateDefinition;
using TrafficManagerEndpoint.Definition;
using System.Threading.Tasks;
using TrafficManagerEndpoint.UpdateNestedProfileEndpoint;
using TrafficManagerEndpoint.UpdateExternalEndpoint;
using System.Threading;
using TrafficManagerEndpoint.UpdateAzureEndpoint;
using ResourceManager.Fluent.Core.ChildResourceActions;
using Models;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
/// <summary>
/// Implementation for TrafficManagerEndpoint.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LnRyYWZmaWNtYW5hZ2VyLmltcGxlbWVudGF0aW9uLlRyYWZmaWNNYW5hZ2VyRW5kcG9pbnRJbXBs
internal partial class TrafficManagerEndpointImpl :
ExternalChildResource<ITrafficManagerEndpoint, EndpointInner, ITrafficManagerProfile, TrafficManagerProfileImpl>,
ITrafficManagerEndpoint,
IDefinition<TrafficManagerProfile.Definition.IWithCreate>,
IUpdateDefinition<TrafficManagerProfile.Update.IUpdate>,
IUpdateAzureEndpoint,
IUpdateExternalEndpoint,
IUpdateNestedProfileEndpoint
{
private const string endpointStatusDisabled = "Disabled";
private const string endpointStatusEnabled = "Enabled";
///GENMHASH:2521373455D66779FDC191E5AF5A324E:A74628459133C1690F2A62C7C482A9A9
internal TrafficManagerEndpointImpl(string name, TrafficManagerProfileImpl parent, EndpointInner inner) : base(name, parent, inner)
{
}
///GENMHASH:974E7FCA59BCBB12A26AB795E4C4A982:8418C83028CC7E2D2717B3EC2E3DBF97
public TrafficManagerEndpointImpl ToResourceId(string resourceId)
{
Inner.TargetResourceId = resourceId;
return this;
}
///GENMHASH:7E4D6CD4225C7C45A2617BA279790518:CDE1537547721862503F9A0FA1A322D4
public int RoutingPriority()
{
return (int)Inner.Priority.Value;
}
///GENMHASH:01C4B6E26D53E1762A443721CECB5D96:43F1F30B8E8EB5054939168766D4F5BE
public EndpointType EndpointType()
{
return Fluent.EndpointType.Parse(Inner.Type);
}
///GENMHASH:85BAA8BAAF184D879CCE5080E089F024:D3868AC81F258C85BCA29FE3546FDBB0
public TrafficManagerEndpointImpl ToProfile(ITrafficManagerProfile nestedProfile)
{
Inner.TargetResourceId = nestedProfile.Id;
Inner.MinChildEndpoints = 1;
return this;
}
///GENMHASH:3A31ACD3BD909199AC20F8F3E3739FBC:74F3955C06F9B8A4E58621607D351E22
public int RoutingWeight()
{
return (int)Inner.Weight.Value;
}
public IReadOnlyDictionary<string,string> CustomHeaders()
{
if (Inner.CustomHeaders == null)
{
return new Dictionary<string, string>();
}
return Inner.CustomHeaders.ToDictionary(k => k.Name, v => v.Value);
}
public IReadOnlyList<string> SubnetRoute()
{
if (Inner.Subnets == null)
{
return new List<string>();
}
return Inner.Subnets.Select(s => string.IsNullOrEmpty(s.Last) ? $"{s.First}/{s.Scope}" : $"{s.First}-{s.Last}").ToList();
}
///GENMHASH:4002186478A1CB0B59732EBFB18DEB3A:C47C4325FAE65E493A947196909A8664
protected override async Task<EndpointInner> GetInnerAsync(CancellationToken cancellationToken)
{
return await Parent.Manager.Inner.Endpoints.GetAsync(
Parent.ResourceGroupName,
Parent.Name,
EndpointType().ToString(),
Name(), cancellationToken: cancellationToken);
}
///GENMHASH:0FEDA307DAD2022B36843E8905D26EAD:E3744107BCA5CCCE4C7486E0C86460B6
public async override Task DeleteAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await Parent.Manager.Inner.Endpoints.DeleteAsync(
Parent.ResourceGroupName,
Parent.Name,
EndpointType().LocalName,
Name(),
cancellationToken);
}
///GENMHASH:91BB0A08404D6D37671F71EB696F7DDA:C7EED8E9DF95CD503E77886E10606183
public TrafficManagerEndpointImpl FromRegion(Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region location)
{
Inner.EndpointLocation = location.Name;
return this;
}
///GENMHASH:32A8B56FE180FA4429482D706189DEA2:456A0329D077009BC6D9D0C6B91ADA12
public async override Task<ITrafficManagerEndpoint> CreateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
EndpointInner endpointInner = await Parent.Manager.Inner.Endpoints.CreateOrUpdateAsync(
Parent.ResourceGroupName,
Parent.Name,
EndpointType().LocalName,
Name(),
Inner,
cancellationToken);
SetInner(endpointInner);
return this;
}
///GENMHASH:3F2076D33F84FDFAB700A1F0C8C41647:DABEB48E6D840C88546C3B33907CE0B9
public bool IsEnabled()
{
return Inner.EndpointStatus.Equals(endpointStatusEnabled, System.StringComparison.OrdinalIgnoreCase);
}
///GENMHASH:E596842042AC44324049E25924338641:279322A898E3742765E012128C6BA094
public TrafficManagerEndpointImpl WithTrafficDisabled()
{
Inner.EndpointStatus = TrafficManagerEndpointImpl.endpointStatusDisabled;
return this;
}
///GENMHASH:F08598A17ADD014E223DFD77272641FF:B679398E05D03276D85F279699903D19
public async override Task<ITrafficManagerEndpoint> UpdateAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return await CreateAsync(cancellationToken);
}
///GENMHASH:0F772C1CE5DA7681E1BE68BEBBDC7ED7:4CA1E78BF8CEC54E9503538BE5ED1B9E
public TrafficManagerEndpointImpl WithRoutingPriority(int priority)
{
Inner.Priority = priority;
return this;
}
///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:899F2B088BBBD76CCBC31221756265BC
public string Id
{
get
{
return Inner.Id;
}
}
///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:34C3D97AC56EA49A0A7DE74A085B41B2
public TrafficManagerProfileImpl Attach()
{
return this.Parent.WithEndpoint(this);
}
///GENMHASH:F3CEF905F52D0898C9748690DA270B37:E6BE9AF60DE7E23E08DA51CD41A40433
public TrafficManagerEndpointImpl WithTrafficEnabled()
{
Inner.EndpointStatus = endpointStatusEnabled;
return this;
}
///GENMHASH:2BE295DCD7E2E4E353B535754D34B1FF:103A6872B920F82A78D36FE5074C69CB
public EndpointMonitorStatus MonitorStatus()
{
return EndpointMonitorStatus.Parse(Inner.EndpointMonitorStatus);
}
///GENMHASH:F1873F4E2C7FA7133A7B71292C66E670:DA5C65C0BDAEE12A7FCA134EE523B9C0
public TrafficManagerEndpointImpl WithRoutingWeight(int weight)
{
Inner.Weight = weight;
return this;
}
///GENMHASH:4A45A5907E7D657D8DD40DC76FD41F58:93984FB229DD83A7718C89B007D276C9
public TrafficManagerEndpointImpl WithGeographicLocation(IGeographicLocation geographicLocation)
{
return this.WithGeographicLocation(geographicLocation.Code);
}
///GENMHASH:A547F59734E4765D7E8C66BD9DEABC48:4394EC74F5644573990215653DA5A2D5
public TrafficManagerEndpointImpl WithGeographicLocations(IList<Microsoft.Azure.Management.TrafficManager.Fluent.IGeographicLocation> geographicLocations)
{
foreach (var location in geographicLocations)
{
this.WithGeographicLocation(location);
}
return this;
}
///GENMHASH:2B09C0B6E5A6C9EB0FD5F8E5B6F64071:10487097C091DC4BD14341EFE97436FA
public TrafficManagerEndpointImpl WithGeographicLocations(IList<string> geographicLocationCodes)
{
foreach (var locationCode in geographicLocationCodes)
{
this.WithGeographicLocation(locationCode);
}
return this;
}
///GENMHASH:D941F2842B927A4DB3CBC5C46BF0FB8C:3758D276108819137AC1BAC3E4F73D66
public TrafficManagerEndpointImpl WithGeographicLocation(string geographicLocationCode)
{
if (this.Inner.GeoMapping == null)
{
this.Inner.GeoMapping = new List<string>();
}
if (!this.Inner.GeoMapping.Any(code => code.Equals(geographicLocationCode, System.StringComparison.OrdinalIgnoreCase)))
{
this.Inner.GeoMapping.Add(geographicLocationCode);
}
return this;
}
///GENMHASH:6B5F84A9B6F2D8700DA3A5F71E5000F8:FB9D4C73535F411169B12EACB830D877
public TrafficManagerEndpointImpl WithoutGeographicLocation(IGeographicLocation geographicLocation)
{
return this.WithoutGeographicLocation(geographicLocation.Code);
}
///GENMHASH:B75C241BF5B6DE548F6D8E4910E12E09:EC93F846A74453DA3A4CBDF41628EF0F
public TrafficManagerEndpointImpl WithoutGeographicLocation(string geographicLocationCode)
{
if (this.Inner.GeoMapping == null)
{
return this;
}
this.Inner.GeoMapping = this.Inner.GeoMapping
.Where(code => !code.Equals(geographicLocationCode, System.StringComparison.OrdinalIgnoreCase))
.Select(code => code)
.ToList();
return this;
}
///GENMHASH:A4259C4B7C7D66426DF3049BC1F1EA7F:7ED9C9DE573E721F3D9C8B9D654C0F0E
public TrafficManagerEndpointImpl ToFqdn(string externalFqdn)
{
Inner.Target = externalFqdn;
return this;
}
///GENMHASH:E4E05A91613DD6996BA2D79AA74792A7:E7BC928E840DEFB2EF72E4980D9651F7
public TrafficManagerEndpointImpl WithMinimumEndpointsToEnableTraffic(int count)
{
Inner.MinChildEndpoints = count;
return this;
}
///GENMHASH:F507C7F84BADE3B2935D09B0602D7DE3:645998E0C566D23B620982BEA38A808C
public IReadOnlyList<string> GeographicLocationCodes()
{
if (this.Inner.GeoMapping == null || this.Inner.GeoMapping.Count == 0)
{
return new List<string>();
}
return new ReadOnlyCollection<string>(this.Inner.GeoMapping);
}
TrafficManagerProfile.Update.IUpdate ISettable<TrafficManagerProfile.Update.IUpdate>.Parent()
{
return this.Parent;
}
public TrafficManagerEndpointImpl WithSubnetRouting(string first, string last)
{
if (this.Inner.Subnets == null)
{
this.Inner.Subnets = new List<EndpointPropertiesSubnetsItem>();
}
this.Inner.Subnets.Add(new EndpointPropertiesSubnetsItem(first: first, last: last));
return this;
}
public TrafficManagerEndpointImpl WithSubnetRouting(string ipAddress, int mask)
{
if (this.Inner.Subnets == null)
{
this.Inner.Subnets = new List<EndpointPropertiesSubnetsItem>();
}
this.Inner.Subnets.Add(new EndpointPropertiesSubnetsItem(first: ipAddress, scope: mask));
return this;
}
public TrafficManagerEndpointImpl WithCustomHeaders(IDictionary<string, string> headers)
{
if (this.Inner.CustomHeaders == null)
{
this.Inner.CustomHeaders = new List<EndpointPropertiesCustomHeadersItem>();
}
foreach(var item in headers)
{
this.Inner.CustomHeaders.Add(new EndpointPropertiesCustomHeadersItem(item.Key, item.Value));
}
return this;
}
public TrafficManagerEndpointImpl WithCustomHeader(string name, string value)
{
if (this.Inner.CustomHeaders == null)
{
this.Inner.CustomHeaders = new List<EndpointPropertiesCustomHeadersItem>();
}
this.Inner.CustomHeaders.Add(new EndpointPropertiesCustomHeadersItem(name, value));
return this;
}
}
}
| |
using System;
using System.Collections;
using System.Diagnostics;
using QuickGraph;
using QuickGraph.Providers;
using QuickGraph.Concepts;
using QuickGraph.Concepts.Traversals;
using QuickGraph.Concepts.Modifications;
using QuickGraph.Concepts.MutableTraversals;
using QuickGraph.Concepts.Predicates;
using QuickGraph.Concepts.Providers;
using QuickGraph.Concepts.Collections;
using QuickGraph.Concepts.Serialization;
using QuickGraph.Collections;
using QuickGraph.Exceptions;
using QuickGraph.Predicates;
using Microsoft.Tools.FxCop.Sdk.Reflection.IL;
namespace FxCop.Graph.Rules
{
/// <summary>
/// A mutable bidirectional
/// incidence graph implemetation of <see cref="ProgramStepVertex"/> and
/// <see cref="Edge"/>.
/// </summary>
public class ProgramStepGraph :
IMutableGraph
,IFilteredVertexAndEdgeListGraph
,IFilteredIncidenceGraph
,IMutableEdgeListGraph
,IEdgeMutableGraph
,IMutableIncidenceGraph
,IEdgeListAndIncidenceGraph
,ISerializableVertexAndEdgeListGraph
,IMutableVertexAndEdgeListGraph
,IAdjacencyGraph
,IIndexedVertexListGraph
,IFilteredBidirectionalGraph
,IMutableBidirectionalGraph
,IBidirectionalVertexAndEdgeListGraph
,IMutableBidirectionalVertexAndEdgeListGraph
{
private int version=0;
private bool allowParallelEdges;
private ProgramStepVertexProvider vertexProvider;
private EdgeProvider edgeProvider;
private ProgramStepVertexEdgeCollectionDictionary vertexOutEdges = new ProgramStepVertexEdgeCollectionDictionary();
private ProgramStepVertexEdgeCollectionDictionary vertexInEdges = new ProgramStepVertexEdgeCollectionDictionary();
private ProgramStepVertex root=null;
#region Constructors
/// <summary>
/// Builds a new empty directed graph with default vertex and edge
/// provider.
/// </summary>
/// <remarks>
/// </remarks>
public ProgramStepGraph()
:this(
new ProgramStepVertexProvider(),
new EdgeProvider(),
true
)
{}
/// <summary>
/// Builds a new empty directed graph with default vertex and edge
/// provider.
/// </summary>
/// <param name="allowParallelEdges">true if parallel edges are allowed</param>
public ProgramStepGraph(bool allowParallelEdges)
:this(
new ProgramStepVertexProvider(),
new EdgeProvider(),
allowParallelEdges
)
{}
/// <summary>
/// Builds a new empty directed graph with custom providers
/// </summary>
/// <param name="allowParallelEdges">true if the graph allows
/// multiple edges</param>
/// <param name="edgeProvider">custom edge provider</param>
/// <param name="vertexProvider">custom vertex provider</param>
/// <exception cref="ArgumentNullException">
/// vertexProvider or edgeProvider is a null reference (Nothing in Visual Basic)
/// </exception>
public ProgramStepGraph(
ProgramStepVertexProvider vertexProvider,
EdgeProvider edgeProvider,
bool allowParallelEdges
)
{
if (vertexProvider == null)
throw new ArgumentNullException("vertexProvider");
if (edgeProvider == null)
throw new ArgumentNullException("edgeProvider");
this.vertexProvider = vertexProvider;
this.edgeProvider = edgeProvider;
this.allowParallelEdges = allowParallelEdges;
}
#endregion
#region IMutableGraph
/// <summary>
/// Remove all of the edges and vertices from the graph.
/// </summary>
public virtual void Clear()
{
this.version++;
this.vertexOutEdges.Clear();
this.vertexInEdges.Clear();
}
#endregion
#region IGraph
/// <summary>
/// Gets a value indicating if the <see cref="ProgramStepGraph"/>
/// is directed.
/// </summary>
/// <value>
/// true if the graph is directed, false if undirected.
/// </value>
public bool IsDirected
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating if the <see cref="ProgramStepGraph"/> allows parallel edges.
/// </summary>
/// <value>
/// true if the <see cref="ProgramStepGraph"/> is a multi-graph, false otherwise
/// </value>
public bool AllowParallelEdges
{
get
{
return this.IsDirected && this.allowParallelEdges;
}
}
#endregion
#region IVertexMutableGraph
/// <summary>
/// Gets the <see cref="ProgramStepVertex"/> provider
/// </summary>
/// <value>
/// <see cref="ProgramStepVertex"/> provider
/// </value>
public ProgramStepVertexProvider VertexProvider
{
get
{
return this.vertexProvider;
}
}
IVertexProvider IVertexMutableGraph.VertexProvider
{
get
{
return this.VertexProvider;
}
}
/// <summary>
/// Add a new ProgramStepVertex to the graph and returns it.
/// </summary>
/// <returns>
/// Created vertex
/// </returns>
public virtual ProgramStepVertex AddVertex()
{
this.version++;
ProgramStepVertex v = (ProgramStepVertex)this.VertexProvider.ProvideVertex();
if (this.VerticesCount==0)
this.root=v;
this.vertexOutEdges.Add(v);
this.vertexInEdges.Add(v);
return v;
}
IVertex IVertexMutableGraph.AddVertex()
{
return this.AddVertex();
}
public ProgramStepVertex Root
{
get
{
return this.root;
}
}
/// <summary>
/// Removes the vertex from the graph.
/// </summary>
/// <param name="v">vertex to remove</param>
/// <exception cref="ArgumentNullException">v is null</exception>
public virtual void RemoveVertex(ProgramStepVertex v)
{
if (v == null)
throw new ArgumentNullException("v");
if (!ContainsVertex(v))
throw new VertexNotFoundException("v");
this.version++;
this.ClearVertex(v);
// removing vertex
this.vertexOutEdges.Remove(v);
this.vertexInEdges.Remove(v);
}
void IVertexMutableGraph.RemoveVertex(IVertex v)
{
this.RemoveVertex((ProgramStepVertex)v);
}
#endregion
#region IEdgeMutableGraph
/// <summary>
/// Gets the <see cref="Edge"/> provider
/// </summary>
/// <value>
/// <see cref="Edge"/> provider
/// </value>
public EdgeProvider EdgeProvider
{
get
{
return this.edgeProvider;
}
}
IEdgeProvider IEdgeMutableGraph.EdgeProvider
{
get
{
return this.EdgeProvider;
}
}
/// <summary>
/// Add a new vertex from source to target
///
/// Complexity: 2 search + 1 insertion
/// </summary>
/// <param name="source">Source vertex</param>
/// <param name="target">Target vertex</param>
/// <returns>Created Edge</returns>
/// <exception cref="ArgumentNullException">
/// source or target is a null reference
/// </exception>
/// <exception cref="Exception">source or target are not part of the graph</exception>
public virtual Edge AddEdge(
ProgramStepVertex source,
ProgramStepVertex target
)
{
// look for the vertex in the list
if (!this.vertexOutEdges.Contains(source))
throw new VertexNotFoundException("Could not find source vertex");
if (!this.vertexOutEdges.Contains(target))
throw new VertexNotFoundException("Could not find target vertex");
// if parralel edges are not allowed check if already in the graph
if (!this.AllowParallelEdges)
{
if (ContainsEdge(source,target))
throw new Exception("Parallel edge not allowed");
}
this.version++;
// create edge
Edge e = (Edge)this.EdgeProvider.ProvideEdge(source,target);
this.vertexOutEdges[source].Add(e);
this.vertexInEdges[target].Add(e);
return e;
}
IEdge IEdgeMutableGraph.AddEdge(
IVertex source,
IVertex target
)
{
return this.AddEdge((ProgramStepVertex)source,(ProgramStepVertex)target);
}
/// <summary>
/// Remove all edges to and from vertex u from the graph.
/// </summary>
/// <param name="v"></param>
public virtual void ClearVertex(ProgramStepVertex v)
{
if (v == null)
throw new ArgumentNullException("vertex");
this.version++;
// removing edges touching v
this.RemoveEdgeIf(new IsAdjacentEdgePredicate(v));
// removing edges
this.vertexOutEdges[v].Clear();
this.vertexInEdges[v].Clear();
}
void IEdgeMutableGraph.ClearVertex(IVertex v)
{
this.ClearVertex((ProgramStepVertex)v);
}
/// <summary>
/// Removes an edge from the graph.
///
/// Complexity: 2 edges removed from the vertex edge list + 1 edge
/// removed from the edge list.
/// </summary>
/// <param name="e">edge to remove</param>
/// <exception cref="ArgumentNullException">
/// e is a null reference (Nothing in Visual Basic)
/// </exception>
/// <exception cref="EdgeNotFoundException">
/// <paramref name="e"/> is not part of the graph
/// </exception>
public virtual void RemoveEdge(Edge e)
{
if (e == null)
throw new ArgumentNullException("e");
if (!this.ContainsEdge(e))
throw new EdgeNotFoundException("e");
this.version++;
// removing edge from vertices
ProgramStepVertex source= (ProgramStepVertex)e.Source;
EdgeCollection outEdges = this.vertexOutEdges[source];
if (outEdges==null)
throw new VertexNotFoundException(source.ToString());
outEdges.Remove(e);
ProgramStepVertex target= (ProgramStepVertex)e.Target;
EdgeCollection inEdges = this.vertexInEdges[target];
if (inEdges==null)
throw new VertexNotFoundException(target.ToString());
inEdges.Remove(e);
}
void IEdgeMutableGraph.RemoveEdge(IEdge e)
{
this.RemoveEdge((Edge)e);
}
/// <summary>
/// Remove the edge (u,v) from the graph.
/// If the graph allows parallel edges this remove all occurrences of
/// (u,v).
/// </summary>
/// <param name="u">source vertex</param>
/// <param name="v">target vertex</param>
public virtual void RemoveEdge(ProgramStepVertex u, ProgramStepVertex v)
{
if (u == null)
throw new ArgumentNullException("u");
if (v == null)
throw new ArgumentNullException("v");
this.version++;
// getting out-edges
EdgeCollection outEdges = this.vertexOutEdges[u];
// marking edges to remove
EdgeCollection removedEdges = new EdgeCollection();
foreach(Edge e in outEdges)
{
if (e.Target == v)
removedEdges.Add(e);
}
//removing out-edges
foreach(Edge e in removedEdges)
outEdges.Remove(e);
removedEdges.Clear();
EdgeCollection inEdges = this.vertexInEdges[v];
foreach(Edge e in inEdges)
{
if (e.Source == u)
removedEdges.Add(e);
}
//removing in-edges
foreach(Edge e in removedEdges)
inEdges.Remove(e);
}
void IEdgeMutableGraph.RemoveEdge(IVertex u, IVertex v)
{
this.RemoveEdge((ProgramStepVertex) u, (ProgramStepVertex) v);
}
#endregion
#region ISerializableVertexListGraph
/// <summary>
/// Add a new vertex to the graph and returns it.
/// </summary>
/// <returns>Create vertex</returns>
public virtual void AddVertex(ProgramStepVertex v)
{
if (v==null)
throw new ArgumentNullException("vertex");
if (this.vertexOutEdges.Contains(v))
throw new ArgumentException("vertex already in graph");
this.version++;
this.VertexProvider.UpdateVertex(v);
this.vertexOutEdges.Add(v);
this.vertexInEdges.Add(v);
}
void ISerializableVertexListGraph.AddVertex(IVertex v)
{
this.AddVertex((ProgramStepVertex) v);
}
#endregion
#region ISerializableEdgeListGraph
/// <summary>
/// Used for serialization. Not for private use.
/// </summary>
/// <param name="e">edge to add.</param>
public virtual void AddEdge(Edge e)
{
if (e==null)
throw new ArgumentNullException("vertex");
if (e.GetType().IsAssignableFrom(EdgeProvider.EdgeType))
throw new ArgumentNullException("vertex type not valid");
ProgramStepVertex source= (ProgramStepVertex)e.Source;
if (!this.vertexOutEdges.Contains(source))
throw new VertexNotFoundException(source.ToString());
ProgramStepVertex target= (ProgramStepVertex)e.Target;
if (!this.vertexOutEdges.Contains(target))
throw new VertexNotFoundException(target.ToString());
// if parralel edges are not allowed check if already in the graph
if (!this.AllowParallelEdges)
{
if (ContainsEdge(source,target))
throw new ArgumentException("graph does not allow duplicate edges");
}
// create edge
this.EdgeProvider.UpdateEdge(e);
this.vertexOutEdges[source].Add(e);
this.vertexInEdges[target].Add(e);
}
void ISerializableEdgeListGraph.AddEdge(IEdge e)
{
this.AddEdge((Edge)e);
}
#endregion
#region IIncidenceGraph
/// <summary>
/// Gets a value indicating if the set of out-edges is empty
/// </summary>
/// <remarks>
/// <para>
/// Usually faster that calling <see cref="OutDegree"/>.
/// </para>
/// </remarks>
/// <value>
/// true if the out-edge set is empty, false otherwise.
/// </value>
/// <exception cref="ArgumentNullException">
/// v is a null reference (Nothing in Visual Basic)
/// </exception>
/// <exception cref="VertexNotFoundException">
/// v is not part of the graph.
/// </exception>
public bool OutEdgesEmpty(ProgramStepVertex v)
{
if (v == null)
throw new ArgumentNullException("v");
EdgeCollection edges = this.vertexOutEdges[v];
if (edges==null)
throw new VertexNotFoundException(v.ToString());
return edges.Count==0;
}
bool IIncidenceGraph.OutEdgesEmpty(IVertex v)
{
return this.OutEdgesEmpty((ProgramStepVertex)v);
}
/// <summary>
/// Returns the number of out-degree edges of v
/// </summary>
/// <param name="v">vertex</param>
/// <returns>number of out-edges of the <see cref="ProgramStepVertex"/> v</returns>
/// <exception cref="ArgumentNullException">
/// v is a null reference (Nothing in Visual Basic)
/// </exception>
/// <exception cref="VertexNotFoundException">
/// v is not part of the graph.
/// </exception>
public int OutDegree(ProgramStepVertex v)
{
if (v == null)
throw new ArgumentNullException("v");
EdgeCollection edges = this.vertexOutEdges[v];
if (edges==null)
throw new VertexNotFoundException(v.ToString());
return edges.Count;
}
int IIncidenceGraph.OutDegree(IVertex v)
{
return this.OutDegree((ProgramStepVertex)v);
}
/// <summary>
/// Returns an iterable collection over the edge connected to v
/// </summary>
/// <param name="v"></param>
/// <returns>out-edges of v</returns>
/// <exception cref="ArgumentNullException">
/// v is a null reference.
/// </exception>
/// <exception cref="VertexNotFoundException">
/// v is not part of the graph.
/// </exception>
public IEdgeCollection OutEdges(ProgramStepVertex v)
{
if (v == null)
throw new ArgumentNullException("v");
EdgeCollection edges = this.vertexOutEdges[v];
if (edges==null)
throw new VertexNotFoundException(v.ToString());
return edges;
}
IEdgeEnumerable IIncidenceGraph.OutEdges(IVertex v)
{
return this.OutEdges((ProgramStepVertex)v);
}
/// <summary>
/// Test is an edge (u,v) is part of the graph
/// </summary>
/// <param name="u">source vertex</param>
/// <param name="v">target vertex</param>
/// <returns>true if part of the graph</returns>
public bool ContainsEdge(ProgramStepVertex u,ProgramStepVertex v)
{
// try to find the edge
foreach(Edge e in this.OutEdges(u))
{
if (e.Target == v)
return true;
}
return false;
}
bool IIncidenceGraph.ContainsEdge(IVertex u, IVertex v)
{
return this.ContainsEdge((ProgramStepVertex)u,(ProgramStepVertex)v);
}
#endregion
#region IFilteredIncidenceGraph
/// <summary>
/// Returns the first out-edge that matches the predicate
/// </summary>
/// <param name="v"></param>
/// <param name="ep">Edge predicate</param>
/// <returns>null if not found, otherwize the first Edge that
/// matches the predicate.</returns>
/// <exception cref="ArgumentNullException">v or ep is null</exception>
public Edge SelectSingleOutEdge(ProgramStepVertex v, IEdgePredicate ep)
{
if (ep==null)
throw new ArgumentNullException("ep");
foreach(Edge e in this.SelectOutEdges(v,ep))
return e;
return null;
}
IEdge IFilteredIncidenceGraph.SelectSingleOutEdge(IVertex v, IEdgePredicate ep)
{
return this.SelectSingleOutEdge((ProgramStepVertex)v,ep);
}
/// <summary>
/// Returns the collection of out-edges that matches the predicate
/// </summary>
/// <param name="v"></param>
/// <param name="ep">Edge predicate</param>
/// <returns>enumerable colleciton of vertices that matches the
/// criteron</returns>
/// <exception cref="ArgumentNullException">v or ep is null</exception>
public IEdgeEnumerable SelectOutEdges(ProgramStepVertex v, IEdgePredicate ep)
{
if (v==null)
throw new ArgumentNullException("v");
if (ep==null)
throw new ArgumentNullException("ep");
return new FilteredEdgeEnumerable(this.OutEdges(v),ep);
}
IEdgeEnumerable IFilteredIncidenceGraph.SelectOutEdges(IVertex v, IEdgePredicate ep)
{
return this.SelectOutEdges((ProgramStepVertex)v,ep);
}
/// <summary>
/// Remove all the edges from graph g for which the predicate pred
/// returns true.
/// </summary>
/// <param name="pred">edge predicate</param>
public virtual void RemoveEdgeIf(IEdgePredicate pred)
{
if (pred == null)
throw new ArgumentNullException("predicate");
// marking edge for removal
EdgeCollection removedEdges = new EdgeCollection();
foreach(Edge e in Edges)
{
if (pred.Test(e))
removedEdges.Add(e);
}
// removing edges
foreach(Edge e in removedEdges)
this.RemoveEdge(e);
}
#endregion
#region IMutableIncidenceGraph
/// <summary>
/// Remove all the out-edges of vertex u for which the predicate pred
/// returns true.
/// </summary>
/// <param name="u">vertex</param>
/// <param name="pred">edge predicate</param>
public virtual void RemoveOutEdgeIf(ProgramStepVertex u, IEdgePredicate pred)
{
if (u==null)
throw new ArgumentNullException("u");
if (pred == null)
throw new ArgumentNullException("pred");
EdgeCollection edges = this.vertexOutEdges[u];
EdgeCollection removedEdges = new EdgeCollection();
foreach(Edge e in edges)
{
if (pred.Test(e))
removedEdges.Add(e);
}
foreach(Edge e in removedEdges)
this.RemoveEdge(e);
}
void IMutableIncidenceGraph.RemoveOutEdgeIf(IVertex u, IEdgePredicate pred)
{
this.RemoveOutEdgeIf((ProgramStepVertex)u,pred);
}
#endregion
#region IIndexedIncidenceGraph
IEdgeCollection IIndexedIncidenceGraph.OutEdges(IVertex v)
{
return this.OutEdges((ProgramStepVertex)v);
}
#endregion
#region IVertexListGraph
/// <summary>
/// Gets a value indicating if the vertex set is empty
/// </summary>
/// <para>
/// Usually faster (O(1)) that calling <c>VertexCount</c>.
/// </para>
/// <value>
/// true if the vertex set is empty, false otherwise.
/// </value>
public bool VerticesEmpty
{
get
{
return this.vertexOutEdges.Count==0;
}
}
/// <summary>
/// Gets the number of vertices
/// </summary>
/// <value>
/// Number of vertices in the graph
/// </value>
public int VerticesCount
{
get
{
return this.vertexOutEdges.Count;
}
}
/// <summary>
/// Enumerable collection of vertices.
/// </summary>
public IVertexEnumerable Vertices
{
get
{
return this.vertexOutEdges.Vertices;
}
}
/// <summary>
/// Tests if a <see cref="ProgramStepVertex"/> is part of the graph
/// </summary>
/// <param name="v">Vertex to test</param>
/// <returns>true if is part of the graph, false otherwize</returns>
public bool ContainsVertex(ProgramStepVertex v)
{
return this.vertexOutEdges.Contains(v);
}
bool IVertexListGraph.ContainsVertex(IVertex v)
{
return this.ContainsVertex((ProgramStepVertex)v);
}
#endregion
#region IFilteredVertexListGraph
/// <summary>
/// Returns the first <see cref="ProgramStepVertex"/> that matches the predicate
/// </summary>
/// <param name="vp">vertex predicate</param>
/// <returns>null if not found, otherwize the first vertex that
/// matches the predicate.</returns>
/// <exception cref="ArgumentNullException">vp is null</exception>
public ProgramStepVertex SelectSingleVertex(IVertexPredicate vp)
{
if (vp == null)
throw new ArgumentNullException("vertex predicate");
foreach(ProgramStepVertex v in this.SelectVertices(vp))
return v;
return null;
}
IVertex IFilteredVertexListGraph.SelectSingleVertex(IVertexPredicate vp)
{
return this.SelectSingleVertex(vp);
}
/// <summary>
/// Returns the collection of vertices that matches the predicate
/// </summary>
/// <param name="vp">vertex predicate</param>
/// <returns>enumerable colleciton of vertices that matches the
/// criteron</returns>
/// <exception cref="ArgumentNullException">vp is null</exception>
public IVertexEnumerable SelectVertices(IVertexPredicate vp)
{
if (vp == null)
throw new ArgumentNullException("vertex predicate");
return new FilteredVertexEnumerable(Vertices,vp);
}
#endregion
#region EdgeListGraph
/// <summary>
/// Gets a value indicating if the vertex set is empty
/// </summary>
/// <remarks>
/// <para>
/// Usually faster that calling <see cref="EdgesCount"/>.
/// </para>
/// </remarks>
/// <value>
/// true if the vertex set is empty, false otherwise.
/// </value>
public bool EdgesEmpty
{
get
{
return this.EdgesCount==0;
}
}
/// <summary>
/// Gets the edge count
/// </summary>
/// <remarks>
/// Edges count
/// </remarks>
public int EdgesCount
{
get
{
int n = 0;
foreach(DictionaryEntry d in vertexOutEdges)
{
n+=((EdgeCollection)d.Value).Count;
}
return n;
}
}
/// <summary>
/// Enumerable collection of edges.
/// </summary>
public IEdgeEnumerable Edges
{
get
{
return this.vertexOutEdges.Edges;
}
}
/// <summary>
/// Tests if a (<see cref="Edge"/>) is part of the graph
/// </summary>
/// <param name="e">Edge to test</param>
/// <returns>true if is part of the graph, false otherwize</returns>
public bool ContainsEdge(Edge e)
{
foreach(DictionaryEntry di in this.vertexOutEdges)
{
EdgeCollection es = (EdgeCollection)di.Value;
if (es.Contains(e))
return true;
}
return false;
}
bool IEdgeListGraph.ContainsEdge(IEdge e)
{
return this.ContainsEdge((Edge)e);
}
#endregion
#region IFileteredEdgeListGraph
/// <summary>
/// Returns the first Edge that matches the predicate
/// </summary>
/// <param name="ep">Edge predicate</param>
/// <returns>null if not found, otherwize the first Edge that
/// matches the predicate.</returns>
/// <exception cref="ArgumentNullException">ep is null</exception>
public Edge SelectSingleEdge(IEdgePredicate ep)
{
if (ep == null)
throw new ArgumentNullException("edge predicate");
foreach(Edge e in this.SelectEdges(ep))
return e;
return null;
}
IEdge IFilteredEdgeListGraph.SelectSingleEdge(IEdgePredicate ep)
{
return this.SelectSingleEdge(ep);
}
/// <summary>
/// Returns the collection of edges that matches the predicate
/// </summary>
/// <param name="ep">Edge predicate</param>
/// <returns>enumerable colleciton of vertices that matches the
/// criteron</returns>
/// <exception cref="ArgumentNullException">ep is null</exception>
public IEdgeEnumerable SelectEdges(IEdgePredicate ep)
{
if (ep == null)
throw new ArgumentNullException("edge predicate");
return new FilteredEdgeEnumerable(Edges,ep);
}
#endregion
#region IAdjacencyGraph
/// <summary>
/// Gets an enumerable collection of adjacent vertices
/// </summary>
/// <param name="v"></param>
/// <returns>Enumerable collection of adjacent vertices</returns>
public IVertexEnumerable AdjacentVertices(ProgramStepVertex v)
{
return new TargetVertexEnumerable(this.OutEdges(v));
}
IVertexEnumerable IAdjacencyGraph.AdjacentVertices(IVertex v)
{
return AdjacentVertices((ProgramStepVertex)v);
}
#endregion
#region IBidirectionalGraph
/// <summary>
/// Gets a value indicating if the set of in-edges is empty
/// </summary>
/// <remarks>
/// <para>
/// Usually faster that calling <see cref="InDegree"/>.
/// </para>
/// </remarks>
/// <value>
/// true if the in-edge set is empty, false otherwise.
/// </value>
/// <exception cref="ArgumentNullException">
/// v is a null reference (Nothing in Visual Basic)
/// </exception>
/// <exception cref="VertexNotFoundException">
/// <paramref name="v"/> is not part of the graph.
/// </exception>
public bool InEdgesEmpty(ProgramStepVertex v)
{
if (v==null)
throw new ArgumentNullException("v");
EdgeCollection edges = this.vertexInEdges[v];
if (edges==null)
throw new VertexNotFoundException("v");
return edges.Count==0;
}
bool IBidirectionalGraph.InEdgesEmpty(IVertex v)
{
return this.InEdgesEmpty((ProgramStepVertex)v);
}
/// <summary>
/// Returns the number of in-degree edges of v
/// </summary>
/// <param name="v"></param>
/// <returns>number of in-edges of the vertex v</returns>
/// <exception cref="ArgumentNullException">
/// v is a null reference (Nothing in Visual Basic)
/// </exception>
/// <exception cref="VertexNotFoundException">
/// <paramref name="v"/> is not part of the graph.
/// </exception>
public int InDegree(ProgramStepVertex v)
{
if (v == null)
throw new ArgumentNullException("v");
EdgeCollection edges = this.vertexInEdges[v];
if (edges==null)
throw new VertexNotFoundException("v");
return edges.Count;
}
int IBidirectionalGraph.InDegree(IVertex v)
{
return this.InDegree((ProgramStepVertex)v);
}
/// <summary>
/// Returns an iterable collection over the in-edge connected to v
/// </summary>
/// <param name="v"></param>
/// <returns>in-edges of v</returns>
/// <exception cref="ArgumentNullException">
/// v is a null reference (Nothing in Visual Basic)
/// </exception>
/// <exception cref="VertexNotFoundException">
/// <paramref name="v"/> is not part of the graph.
/// </exception>
public IEdgeCollection InEdges(ProgramStepVertex v)
{
if (v == null)
throw new ArgumentNullException("v");
EdgeCollection edges = this.vertexInEdges[v];
if (edges==null)
throw new VertexNotFoundException(v.ToString());
return edges;
}
/// <summary>
/// Incidence graph implementation
/// </summary>
IEdgeEnumerable IBidirectionalGraph.InEdges(IVertex v)
{
return this.InEdges((ProgramStepVertex)v);
}
/// <summary>
/// Gets a value indicating if the set of edges connected to v is empty
/// </summary>
/// <remarks>
/// <para>
/// Usually faster that calling <see cref="Degree"/>.
/// </para>
/// </remarks>
/// <value>
/// true if the adjacent edge set is empty, false otherwise.
/// </value>
/// <exception cref="ArgumentNullException">v is a null reference</exception>
public bool AdjacentEdgesEmpty(ProgramStepVertex v)
{
if (v==null)
throw new ArgumentNullException("v");
return this.OutEdgesEmpty(v) && this.InEdgesEmpty(v);
}
bool IBidirectionalGraph.AdjacentEdgesEmpty(IVertex v)
{
return this.AdjacentEdgesEmpty((ProgramStepVertex)v);
}
/// <summary>
/// Returns the number of in-edges plus out-edges.
/// </summary>
/// <param name="v"></param>
/// <returns></returns>
public int Degree(ProgramStepVertex v)
{
if (v == null)
throw new ArgumentNullException("v");
EdgeCollection outEdges = this.vertexOutEdges[v];
if (outEdges==null)
throw new VertexNotFoundException("v");
EdgeCollection inEdges = this.vertexInEdges[v];
Debug.Assert(inEdges!=null);
return outEdges.Count + inEdges.Count;
}
int IBidirectionalGraph.Degree(IVertex v)
{
return this.Degree((ProgramStepVertex)v);
}
#endregion
#region IFilteredBidirectionalGraph
/// <summary>
/// Returns the first in-edge that matches the predicate
/// </summary>
/// <param name="v"></param>
/// <param name="ep">Edge predicate</param>
/// <returns>null if not found, otherwize the first Edge that
/// matches the predicate.</returns>
/// <exception cref="ArgumentNullException">v or ep is null</exception>
public Edge SelectSingleInEdge(ProgramStepVertex v, IEdgePredicate ep)
{
if (ep==null)
throw new ArgumentNullException("edge predicate");
foreach(Edge e in this.SelectInEdges(v,ep))
return e;
return null;
}
IEdge IFilteredBidirectionalGraph.SelectSingleInEdge(IVertex v, IEdgePredicate ep)
{
return this.SelectSingleInEdge((ProgramStepVertex)v, ep);
}
/// <summary>
/// Returns the collection of in-edges that matches the predicate
/// </summary>
/// <param name="v"></param>
/// <param name="ep">Edge predicate</param>
/// <returns>enumerable colleciton of vertices that matches the
/// criteron</returns>
/// <exception cref="ArgumentNullException">v or ep is null</exception>
public IEdgeEnumerable SelectInEdges(ProgramStepVertex v, IEdgePredicate ep)
{
if (v==null)
throw new ArgumentNullException("vertex");
if (ep==null)
throw new ArgumentNullException("edge predicate");
return new FilteredEdgeEnumerable(this.InEdges(v),ep);
}
/// <summary>
///
/// </summary>
/// <param name="v"></param>
/// <param name="ep"></param>
/// <returns></returns>
IEdgeEnumerable IFilteredBidirectionalGraph.SelectInEdges(IVertex v, IEdgePredicate ep)
{
return this.SelectInEdges((ProgramStepVertex)v,ep);
}
#endregion
#region IMutableBidirectionalGraph
/// <summary>
/// Remove all the out-edges of vertex u for which the predicate pred
/// returns true.
/// </summary>
/// <param name="u">vertex</param>
/// <param name="pred">edge predicate</param>
public void RemoveInEdgeIf(ProgramStepVertex u, IEdgePredicate pred)
{
if (u==null)
throw new ArgumentNullException("vertex u");
if (pred == null)
throw new ArgumentNullException("predicate");
EdgeCollection edges = this.vertexInEdges[u];
EdgeCollection removedEdges = new EdgeCollection();
foreach(Edge e in edges)
{
if (pred.Test(e))
removedEdges.Add(e);
}
foreach(Edge e in removedEdges)
this.RemoveEdge(e);
}
void IMutableBidirectionalGraph.RemoveInEdgeIf(IVertex u, IEdgePredicate pred)
{
this.RemoveInEdgeIf((ProgramStepVertex)u,pred);
}
#endregion
#region EdgeCollection
private class EdgeCollection :
CollectionBase
,IEdgeCollection
{
/// <summary>
/// Initializes a new empty instance of the
/// <see cref="EdgeCollection"/> class.
/// </summary>
public EdgeCollection()
{}
/// <summary>
/// Adds an instance of type <see cref="Edge"/> to the end of this
/// <see cref="EdgeCollection"/>.
/// </summary>
/// <param name="value">
/// The Edge to be added to the end of this EdgeCollection.
/// </param>
internal void Add(Edge value)
{
this.List.Add(value);
}
/// <summary>
/// Removes the first occurrence of a specific Edge from this EdgeCollection.
/// </summary>
/// <param name="value">
/// The Edge value to remove from this EdgeCollection.
/// </param>
internal void Remove(IEdge value)
{
this.List.Remove(value);
}
#region IEdgeCollection
/// <summary>
/// Determines whether a specfic <see cref="Edge"/> value is in this EdgeCollection.
/// </summary>
/// <param name="value">
/// edge value to locate in this <see cref="EdgeCollection"/>.
/// </param>
/// <returns>
/// true if value is found in this collection;
/// false otherwise.
/// </returns>
public bool Contains(Edge value)
{
return this.List.Contains(value);
}
bool IEdgeCollection.Contains(IEdge value)
{
return this.Contains((Edge)value);
}
/// <summary>
/// Gets or sets the Edge at the given index in this EdgeCollection.
/// </summary>
public Edge this[int index]
{
get
{
return (Edge)this.List[index];
}
set
{
this.List[index] = value;
}
}
IEdge IEdgeCollection.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (Edge)value;
}
}
#endregion
#region IEdgeEnumerable
/// <summary>
/// Returns an enumerator that can iterate through the elements of this EdgeCollection.
/// </summary>
/// <returns>
/// An object that implements System.Collections.IEnumerator.
/// </returns>
public new IEdgeEnumerator GetEnumerator()
{
return new EdgeEnumerator(this);
}
private class EdgeEnumerator : IEdgeEnumerator
{
private IEnumerator wrapped;
/// <summary>
/// Create a new enumerator on the collection
/// </summary>
/// <param name="collection">collection to enumerate</param>
public EdgeEnumerator(EdgeCollection collection)
{
this.wrapped = ((System.Collections.CollectionBase)collection).GetEnumerator();
}
/// <summary>
/// The current element.
/// </summary>
public Edge Current
{
get
{
return (Edge)this.wrapped.Current;
}
}
#region IEdgeEnumerator
IEdge IEdgeEnumerator.Current
{
get
{
return this.Current;
}
}
#endregion
#region IEnumerator
object IEnumerator.Current
{
get
{
return this.Current;
}
}
/// <summary>
/// Moves cursor to next element.
/// </summary>
/// <returns>true if current is valid, false otherwize</returns>
public bool MoveNext()
{
return this.wrapped.MoveNext();
}
/// <summary>
/// Resets the cursor to the position before the first element.
/// </summary>
public void Reset()
{
this.wrapped.Reset();
}
#endregion
}
#endregion
}
#endregion
#region ProgramStepVertexEdgeCollectionDictionary
private class ProgramStepVertexEdgeCollectionDictionary :
DictionaryBase
{
public ProgramStepVertexEdgeCollectionDictionary()
{}
public void Add(ProgramStepVertex u)
{
Debug.Assert(u!=null);
this.Dictionary.Add(u, new EdgeCollection() );
}
public bool Contains(ProgramStepVertex key)
{
return this.Dictionary.Contains(key);
}
public void Remove(ProgramStepVertex key)
{
this.Dictionary.Remove(key);
}
public IVertexEnumerable Vertices
{
get
{
return new ProgramStepVertexEdgeCollectionVertexEnumerable(this.Dictionary.Keys);
}
}
public IEdgeEnumerable Edges
{
get
{
return new ProgramStepVertexEdgeCollectionEdgeEnumerable(this.Dictionary.Values);
}
}
public EdgeCollection this[ProgramStepVertex v]
{
get
{
return (EdgeCollection)this.Dictionary[v];
}
}
#region Vertex Enumerable/Enumerator
private class ProgramStepVertexEdgeCollectionVertexEnumerable :
IVertexEnumerable
{
private IEnumerable en;
public ProgramStepVertexEdgeCollectionVertexEnumerable(IEnumerable en)
{
Debug.Assert(en!=null);
this.en = en;
}
public IVertexEnumerator GetEnumerator()
{
return new ProgramStepVertexEdgeCollectionVertexEnumerator(en);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#region Enumerator
private class ProgramStepVertexEdgeCollectionVertexEnumerator :
IVertexEnumerator
{
private IEnumerator en;
public ProgramStepVertexEdgeCollectionVertexEnumerator(IEnumerable col)
{
Debug.Assert(col!=null);
this.en = col.GetEnumerator();
}
public ProgramStepVertex Current
{
get
{
return (ProgramStepVertex)this.en.Current;
}
}
IVertex IVertexEnumerator.Current
{
get
{
return this.Current;
}
}
Object IEnumerator.Current
{
get
{
return this.Current;
}
}
public void Reset()
{
this.en.Reset();
}
public bool MoveNext()
{
return this.en.MoveNext();
}
}
#endregion
}
#endregion
#region Edge Enumerable/Enumerator
private class ProgramStepVertexEdgeCollectionEdgeEnumerable :
IEdgeEnumerable
{
private IEnumerable en;
public ProgramStepVertexEdgeCollectionEdgeEnumerable(IEnumerable en)
{
Debug.Assert(en!=null);
this.en = en;
}
public IEdgeEnumerator GetEnumerator()
{
return new ProgramStepVertexEdgeCollectionEdgeEnumerator(en);
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#region Edge Enumerator
private class ProgramStepVertexEdgeCollectionEdgeEnumerator :
IEdgeEnumerator
{
private IEnumerator edges;
private IEdgeEnumerator edge;
public ProgramStepVertexEdgeCollectionEdgeEnumerator(IEnumerable en)
{
Debug.Assert(en!=null);
this.edges = en.GetEnumerator();
this.edge = null;
}
public void Reset()
{
this.edges.Reset();
this.edge=null;
}
public bool MoveNext()
{
// check if first time.
if (this.edge == null)
{
if (!moveNextVertex())
return false;
}
// getting next valid entry
do
{
// try getting edge in the current out edge list
if (edge.MoveNext())
return true;
// move to the next outedge list
if (!moveNextVertex())
return false;
}
while(true);
}
public Edge Current
{
get
{
if (this.edge == null)
throw new InvalidOperationException();
return (Edge)this.edge.Current;
}
}
IEdge IEdgeEnumerator.Current
{
get
{
return this.Current;
}
}
Object IEnumerator.Current
{
get
{
return this.Current;
}
}
private bool moveNextVertex()
{
// check if empty vertex set
if (!this.edges.MoveNext())
{
this.edges=null;
return false;
}
// getting enumerator
this.edge = ((EdgeCollection)this.edges.Current).GetEnumerator();
return true;
}
}
#endregion
}
#endregion
}
#endregion
#region ProgramStepVertexEnumerator
private class ProgramStepVertexEnumerator : IVertexEnumerator
{
private IEnumerator en;
public ProgramStepVertexEnumerator(IEnumerable enumerable)
{
Debug.Assert(en!=null);
this.en = enumerable.GetEnumerator();
}
public void Reset()
{
this.en.Reset();
}
public bool MoveNext()
{
return this.en.MoveNext();
}
public ProgramStepVertex Current
{
get
{
return (ProgramStepVertex)this.en.Current;
}
}
IVertex IVertexEnumerator.Current
{
get
{
return this.Current;
}
}
Object IEnumerator.Current
{
get
{
return this.en.Current;
}
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.Azure.Management.WebSites;
using Microsoft.Azure.Management.WebSites.Models;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Microsoft.Azure.Test.HttpRecorder;
using WebSites.Tests.Helpers;
using Xunit;
namespace WebSites.Tests.ScenarioTests
{
public class WebHostingPlanScenarioTests : TestBase
{
[Fact]
public void CreateAndVerifyWebHostingPlan()
{
using (var context = MockContext.Start(this.GetType()))
{
var webSitesClient = this.GetWebSiteManagementClient(context);
var resourcesClient = this.GetResourceManagementClient(context);
string webHostingPlanName = TestUtilities.GenerateName("csmsf");
string resourceGroupName = TestUtilities.GenerateName("csmrg");
var location = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites");
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
webSitesClient.AppServicePlans.CreateOrUpdate(resourceGroupName, webHostingPlanName, new AppServicePlan()
{
Location = location,
Sku = new SkuDescription()
{
Name = "B1",
Tier = "Basic",
Capacity = 1
}
});
var webHostingPlanResponse = webSitesClient.AppServicePlans.Get(resourceGroupName, webHostingPlanName);
Assert.Equal(webHostingPlanName, webHostingPlanResponse.Name);
Assert.Equal(1, webHostingPlanResponse.Sku.Capacity);
Assert.Equal("B1", webHostingPlanResponse.Sku.Name);
Assert.Equal("Basic", webHostingPlanResponse.Sku.Tier);
}
}
[Fact]
public void CreateAndVerifyListOfWebHostingPlan()
{
using (var context = MockContext.Start(this.GetType()))
{
var webSitesClient = this.GetWebSiteManagementClient(context);
var resourcesClient = this.GetResourceManagementClient(context);
string whpName1 = TestUtilities.GenerateName("csmwhp");
string whpName2 = TestUtilities.GenerateName("csmwhp");
string resourceGroupName = TestUtilities.GenerateName("csmrg");
var location = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites");
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
webSitesClient.AppServicePlans.CreateOrUpdate(resourceGroupName, whpName1, new AppServicePlan()
{
Location = location,
Sku = new SkuDescription
{
Name = "D1",
Tier = "Shared"
}
});
webSitesClient.AppServicePlans.CreateOrUpdate(resourceGroupName, whpName2, new AppServicePlan()
{
Location = location,
Sku = new SkuDescription
{
Name = "B1",
Capacity = 1,
Tier = "Basic"
}
});
var webHostingPlanResponse = webSitesClient.AppServicePlans.ListByResourceGroup(resourceGroupName);
var whp1 = webHostingPlanResponse.First(f => f.Name == whpName1);
var whp2 = webHostingPlanResponse.First(f => f.Name == whpName2);
Assert.Equal(whp1.Sku.Tier, "Shared");
Assert.Equal(whp2.Sku.Tier, "Basic");
}
}
[Fact]
public void CreateAndDeleteWebHostingPlan()
{
using (var context = MockContext.Start(this.GetType()))
{
var webSitesClient = this.GetWebSiteManagementClient(context);
var resourcesClient = this.GetResourceManagementClient(context);
string whpName = TestUtilities.GenerateName("csmsf");
string resourceGroupName = TestUtilities.GenerateName("csmrg");
var location = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites");
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
webSitesClient.WebApps.ListByResourceGroup(resourceGroupName);
webSitesClient.AppServicePlans.CreateOrUpdate(resourceGroupName, whpName, new AppServicePlan()
{
Location = location,
Sku = new SkuDescription
{
Name = "D1",
Capacity = 1,
Tier = "Shared"
}
});
webSitesClient.AppServicePlans.Delete(resourceGroupName, whpName);
var webHostingPlanResponse = webSitesClient.AppServicePlans.ListByResourceGroup(resourceGroupName);
Assert.Equal(0, webHostingPlanResponse.Count());
}
}
[Fact]
public void GetAndSetAdminSiteWebHostingPlan()
{
using (var context = MockContext.Start(this.GetType()))
{
var webSitesClient = this.GetWebSiteManagementClient(context);
var resourcesClient = this.GetResourceManagementClient(context);
string webSiteName = TestUtilities.GenerateName("csmws");
string webHostingPlanName = TestUtilities.GenerateName("csmsf");
string resourceGroupName = TestUtilities.GenerateName("csmrg");
var serverFarmId = ResourceGroupHelper.GetServerFarmId(webSitesClient.SubscriptionId, resourceGroupName,
webHostingPlanName);
var location = ResourceGroupHelper.GetResourceLocation(resourcesClient, "Microsoft.Web/sites");
resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName,
new ResourceGroup
{
Location = location
});
var serverFarm = webSitesClient.AppServicePlans.CreateOrUpdate(resourceGroupName, webHostingPlanName, new AppServicePlan()
{
Location = location,
Sku = new SkuDescription
{
Name = "S1",
Capacity = 1,
Tier = "Standard"
}
});
webSitesClient.WebApps.CreateOrUpdate(resourceGroupName, webSiteName, new Site()
{
Location = location,
Tags = new Dictionary<string, string> { { "tag1", "value1" }, { "tag2", "" } },
ServerFarmId = serverFarmId
});
webSitesClient.AppServicePlans.CreateOrUpdate(resourceGroupName, webHostingPlanName, serverFarm);
var webHostingPlanResponse = webSitesClient.AppServicePlans.Get(resourceGroupName, webHostingPlanName);
Assert.Equal(webHostingPlanName, webHostingPlanResponse.Name);
Assert.Equal(1, webHostingPlanResponse.Sku.Capacity);
Assert.Equal("S1", webHostingPlanResponse.Sku.Name);
Assert.Equal("Standard", webHostingPlanResponse.Sku.Tier);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Valle.SqlGestion;
using Valle.SqlUtilidades;
using Valle.Utilidades;
namespace Valle.ToolsTpv
{
public class TablaEnString{
public static string VistaRondasServidas(IGesSql gesL, string consIntervaloTicket, string consIDTpv, string intervaloHoras, string tarifa, string nomCarareo){
/* if( gesL.EjecutarSqlSelect("","SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES "+
" WHERE (ROUTINE_NAME = 'CalculoPrecioUnidad') AND (ROUTINE_SCHEMA = 'dbo') AND (ROUTINE_TYPE = 'FUNCTION') ").Rows.Count<=0){
gesL.EjConsultaNoSelect("","CREATE FUNCTION dbo.CalculoPrecioUnidad( "+
"@numero integer, @nombre VARCHAR(50)) "+
" RETURNS Decimal(5,2) "+
" AS BEGIN "+
" DECLARE @PrecioUnidad Decimal(5,2) "+
" DECLARE CDatos CURSOR FOR "+
" Select Top 1 TotalLinea/Cantidad "+
" From LineasTicket "+
" Where numTicket = @numero AND nomArticulo = @nombre "+
" open CDatos Fetch CDatos Into @PrecioUnidad "+
" RETURN @PrecioUnidad END ");
}*/
consIntervaloTicket = consIntervaloTicket.Length>0 ? " AND ("+consIntervaloTicket.Replace("numTicket","Ticket.NumTicket")+")":"";
intervaloHoras = intervaloHoras.Length>0 ? " AND ("+intervaloHoras.Replace("Fecha","Rondas.FechaServido + ' ' + Rondas.HoraServido")+")":"";
tarifa = tarifa.Length>0 ? " AND ("+tarifa.Replace("Tarifa","LineasRonda.Tarifa")+")":"";
consIDTpv = consIDTpv.Length>0? "("+consIDTpv.Replace("IDTpv","Ticket.IDTpv")+")":"";
nomCarareo = nomCarareo.Length>0 ? " AND ("+nomCarareo.Replace("nomCamarero","Rondas.CamareroServido")+")":"";
string consultaCompleta = "(SELECT (FechaServido+' '+HoraServido) as Fecha, TotalLinea "+
" FROM LineasRonda INNER JOIN "+
" Rondas ON Rondas.IDVinculacion = LineasRonda.IDRonda INNER JOIN "+
" Ticket ON Ticket.NumTicket = LineasRonda.numTicket "+
" WHERE @IDTpv @Tarifa @NomCamarero @Intervalo_horas @Intervalo_ticket) AS VistaRondasSl";
consultaCompleta = consultaCompleta.Replace("@Intervalo_ticket",consIntervaloTicket);
consultaCompleta = consultaCompleta.Replace("@IDTpv",consIDTpv);
consultaCompleta = consultaCompleta.Replace("@Intervalo_horas",intervaloHoras);
consultaCompleta = consultaCompleta.Replace("@Tarifa",tarifa);
consultaCompleta = consultaCompleta.Replace("@NomCamarero",nomCarareo);
return consultaCompleta;
}
}
public class DesgloseCierre{
public string[] lienasArticulos;
public decimal totalCierre =0;
public string fechaCierre ="";
public string HoraCierre = "";
public int numTicket=0;
}
public class VentaCamarero
{
public decimal totalCobrado = 0;
public decimal totalServido = 0;
public string nomCamarero = "";
public int numticketCobrados = 0;
public int numRodasServidas = 0;
public decimal VentaComision = 0;
public decimal Comision = 0;
public decimal MediaVentas
{
get { return totalCobrado / numticketCobrados; }
}
public decimal MediaServido
{
get { return totalServido / numRodasServidas;
}
}
public VentaCamarero(IGesSql gesL, string nomCam, string nomCamaSim, int IDCierre)
{
this.nomCamarero = nomCam;
DataTable tbCierre = gesL.EjecutarSqlSelect("UnCierre", "SELECT * FROM CierreDeCaja WHERE IDCierre = " + IDCierre);
object CalculoTotal = gesL.EjEscalar("SELECT SUM(LineasTicket.TotalLinea) AS TotalLinea " +
"FROM Ticket INNER JOIN LineasTicket ON Ticket.NumTicket = LineasTicket.numTicket " +
"WHERE (Ticket.NumTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ")"+
" AND (Ticket.NumTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ") AND (Ticket.Camarero = '" + nomCam + "') AND "+
"(Ticket.IDTpv ="+tbCierre.Rows[0]["IDTpv"].ToString()+")");
object CalculoNumTicket = gesL.EjEscalar("SELECT COUNT(*) " +
"FROM Ticket WHERE (Ticket.NumTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ")"+
" AND (Ticket.NumTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ")"+
" AND (Ticket.Camarero = '" + nomCam + "')"+
" AND (Ticket.IDTpv ="+tbCierre.Rows[0]["IDTpv"].ToString()+")");
if ((!CalculoTotal.GetType().Name.Equals("DBNull")) && ((decimal)CalculoTotal > 0))
{
totalCobrado = (decimal)CalculoTotal;
numticketCobrados = Convert.ToInt32(CalculoNumTicket);
}
object CalculoNumRondas = gesL.EjEscalar("SELECT COUNT(DISTINCT LineasRonda.IDRonda) AS Cuenta "+
"FROM Rondas INNER JOIN "+
"LineasRonda ON Rondas.IDVinculacion = LineasRonda.IDRonda INNER JOIN "+
"Ticket ON LineasRonda.numTicket = Ticket.NumTicket "+
" WHERE (LineasRonda.numTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ")"+
" AND (LineasRonda.numTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ") AND (IDTpv = "+tbCierre.Rows[0]["IDTpv"].ToString()+")"+
" AND (CamareroServido = '"+nomCam+ "')");
object CalculoTotalServido = gesL.EjEscalar("SELECT SUM(TotalLinea) AS suma FROM "+ TablaEnString.VistaRondasServidas(gesL,
"(numTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ") AND (numTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ")",
"(IDTpv = "+tbCierre.Rows[0]["IDTpv"].ToString()+")","","", "(nomCamarero = '"+nomCam+ "') "));
if ((!CalculoTotalServido.GetType().Name.Equals("DBNull")) && ((decimal)CalculoTotalServido > 0))
{
totalServido = (decimal)CalculoTotalServido;
numRodasServidas = Convert.ToInt32(CalculoNumRondas);
this.calculoComision(gesL,nomCam,nomCamaSim,tbCierre.Rows[0]);
}
}
void calculoComision(IGesSql gesL, string nomCam,string nomCamPila , DataRow Cierre)
{
DataRow Camarero = gesL.EjecutarSqlSelect("Camareros","SELECT * FROM Camareros WHERE Nombre ='"+nomCamPila+"'").Rows[0];
DataTable InstCom = gesL.EjecutarSqlSelect("Inst","SELECT * FROM InstComision WHERE IDCamarero ="+ Camarero["IDCamarero"].ToString());
if(InstCom.Rows.Count>0){
string HCierre = Cierre["HoraCierre"].ToString();
DataRow FechaTicketPrimero = gesL.EjecutarSqlSelect("TicketPrimero","Select * FROM Ticket WHERE NumTicket = "+
Cierre["desdeTicket"].ToString()).Rows[0];
DataRow FechaTicketUltimo = gesL.EjecutarSqlSelect("TicketPrimero","Select * FROM Ticket WHERE NumTicket = "+
Cierre["hastaTicket"].ToString()).Rows[0];
// DataTable ResComision = gesL.ExtraerTabla ("ResComision","IDVinculacion");
foreach(DataRow r in InstCom.Rows){
string consultaTarifa = !(r["Tarifa"].GetType().Name.Equals("DBNull")) ? "(Tarifa = "+r["Tarifa"].ToString() +")": "";
string HFinal = !r["HoraFin"].GetType().Name.Equals("DBNull") ? FechaTicketUltimo["FechaCobrado"].ToString()+" "+r["HoraFin"].ToString() :
FechaTicketUltimo["FechaCobrado"].ToString()+" "+HCierre;
string intervaloH = CadenasParaSql.CrearConsultaIntervaloHora("Fecha", FechaTicketPrimero["FechaCobrado"].ToString()+" "+ r["HoraInicio"].ToString(), HFinal);
object totalComision = gesL.EjEscalar("SELECT SUM(TotalLinea) AS suma FROM "+ TablaEnString.VistaRondasServidas(gesL,
"(numTicket >= " + Cierre["desdeTicket"].ToString() + ") AND (numTicket <= " + Cierre["hastaTicket"].ToString() + ")",
"(IDTpv = "+Cierre["IDTpv"].ToString()+")",intervaloH,
consultaTarifa,"(nomCamarero = '"+nomCam+ "')"));
if ((!totalComision.GetType().Name.Equals("DBNull")) && ((decimal)totalComision > 0))
{
this.VentaComision += (decimal)totalComision;
this.Comision += this.VentaComision* (decimal)r["PorcientoCom"];
}
}
}
}
}
public class VentaHoras
{
public decimal totalVenta = 0;
public string HInicio = "";
public string HFin = "";
public int numTicket = 0;
public decimal Media
{
get { return totalVenta / numTicket; }
}
public VentaHoras(IGesSql gesL, string hIni, string hFin, int IDCierre)
{
DataTable tbCierre = gesL.EjecutarSqlSelect("UnCierre", "SELECT * FROM CierreDeCaja WHERE IDCierre = " + IDCierre);
object CalculoTotal = gesL.EjEscalar("SELECT SUM(LineasTicket.TotalLinea) "+
"FROM Ticket INNER JOIN LineasTicket ON Ticket.NumTicket = LineasTicket.numTicket "+
"WHERE "+ CadenasParaSql.CrearConsultaIntervaloHora("Ticket.HoraCobrado",hIni,hFin) +
" AND (Ticket.NumTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ") AND (Ticket.NumTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ")"+
" AND Ticket.IDTpv = "+tbCierre.Rows[0]["IDTpv"].ToString());
object CalculoNumTicket = gesL.EjEscalar("SELECT COUNT(*) " +
"FROM Ticket WHERE " + CadenasParaSql.CrearConsultaIntervaloHora("Ticket.HoraCobrado", hIni, hFin) +
" AND (Ticket.NumTicket >= " + tbCierre.Rows[0]["desdeTicket"].ToString() + ") AND (Ticket.NumTicket <= " + tbCierre.Rows[0]["hastaTicket"].ToString() + ")"+
" AND Ticket.IDTpv = "+tbCierre.Rows[0]["IDTpv"].ToString());
HInicio = hIni;
HFin = hFin;
if ((!CalculoTotal.GetType().Name.Equals("DBNull")) && ((decimal)CalculoTotal > 0))
{
totalVenta = (decimal)CalculoTotal;
numTicket = Convert.ToInt32(CalculoNumTicket);
}
}
}
public class GesVentas
{
public DesgloseCierre CalcularCierre(IGesSql ges, int idTpv, int ticketCom, int ticketFin)
{
DesgloseCierre desglose = new DesgloseCierre();
DataTable tbSumaCierre ;
DataTable tbResumen;
DataTable tbNumTicket;
int numComienzo = ticketCom;
tbSumaCierre = ges.EjecutarSqlSelect("SumaCierre","SELECT SUM(TotalLinea) AS total FROM "+
"(SELECT LineasTicket.numTicket, LineasTicket.TotalLinea FROM "+
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket "+
"WHERE (Ticket.IDTpv = "+ idTpv+ ")) AS LineasTpv WHERE numTicket >= "+numComienzo
+" AND numTicket <= "+ ticketFin);
tbNumTicket = ges.EjecutarSqlSelect("NumTicket", ("SELECT MIN(numTicket) AS minimo, MAX(numTicket) AS maximo FROM " +
"(SELECT LineasTicket.numTicket FROM " +
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket " +
"WHERE (Ticket.IDTpv = " + idTpv + ")) AS LineasTpv WHERE numTicket >= "+numComienzo
+" AND numTicket <= "+ ticketFin));
tbResumen = ges.EjecutarSqlSelect("TbResumen","SELECT nomArticulo, SUM(Cantidad) AS Cantidad " +
"FROM (SELECT LineasTicket.numTicket, LineasTicket.nomArticulo, LineasTicket.Cantidad FROM "+
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket "+
"WHERE (Ticket.IDTpv = "+ idTpv+ ")) AS LineasTpv WHERE (numTicket >= "+numComienzo
+" AND numTicket <= "+ ticketFin+") " +
"GROUP BY nomArticulo");
if (tbResumen.Rows.Count > 0)
{
int logArray = tbResumen.Rows.Count;
desglose.lienasArticulos = new String[logArray];
desglose.totalCierre = (decimal)tbSumaCierre.Rows[0][0];
desglose.numTicket = (int)tbNumTicket.Rows[0]["maximo"] - (int)tbNumTicket.Rows[0]["minimo"]+1;
int punt = 0;
foreach (DataRow dr in tbResumen.Rows)
{
String cantidad = String.Format("{0:#0.###}", dr["Cantidad"]);
if(cantidad.Contains(",")){
string[] cantidades = cantidad.Split(',');
cantidad = cantidades[0].PadLeft(4)+','+cantidades[1];
}else{
cantidad = cantidad.PadLeft(4);
}
desglose.lienasArticulos[punt] = dr["nomArticulo"].ToString().PadRight(22) + cantidad;
punt++;
}
return desglose;
}
return null;
}
public List<string> CalcularVentaHoras(IGesSql ges, int IDCierre){
string[] Intervalos = new string[] { "07:00-09:00", "09:01-11:00", "11:01-13:00", "13:01-15:00", "15:01-17:00","17:01-19:00",
"19:01-21:00","21:01-23:00","23:01-00:00",
"00:01-02:00","02:01-03:00","03:01-05:00",
"05:01-06:59"};
List<string> Listado = new List<string>();
VentaHoras infVentaHoras;
Listado.Add("Estadistica de ventas por hora");
Listado.Add("");
foreach (string intervalo in Intervalos)
{
string[] sepInt = intervalo.Split('-');
infVentaHoras = new VentaHoras(ges, sepInt[0], sepInt[1], IDCierre);
if(infVentaHoras.totalVenta>0){
Listado.Add("En el intervalo de "+ intervalo);
Listado.Add(String.Format("Total vendido = {0:c}",infVentaHoras.totalVenta));
Listado.Add("Num de ticket "+ infVentaHoras.numTicket);
Listado.Add(String.Format("Media por ticket = {0:c}",infVentaHoras.Media));
Listado.Add("");
}
}
return Listado;
}
public List<string> CalcularVentaCamareros(IGesSql ges, int IDCierre, IBarrProgres miBarra)
{
List<string> Listado = new List<string>();
Listado.Add("Estadistica de camareros");
Listado.Add("");
VentaCamarero infVentaCamarero;
DataTable tbCamareros = ges.ExtraerTabla("Camareros",null);
miBarra.MaxProgreso = tbCamareros.Rows.Count;
foreach (DataRow rC in tbCamareros.Rows)
{
miBarra.Progreso ++;
infVentaCamarero = new VentaCamarero(ges,rC["Nombre"].ToString()+" "+rC["Apellidos"].ToString(),rC["Nombre"].ToString(), IDCierre);
if(infVentaCamarero.totalCobrado + infVentaCamarero.totalServido + infVentaCamarero.VentaComision >0)
Listado.Add("Camarero = "+rC["Nombre"].ToString()+" "+rC["Apellidos"].ToString());
if(infVentaCamarero.totalCobrado>0){
Listado.Add(String.Format("Total cobrado = {0:c}", infVentaCamarero.totalCobrado));
Listado.Add("Num ticket cobrados = "+ infVentaCamarero.numticketCobrados);
Listado.Add(String.Format("Media de ticket cobrados = {0:c}",infVentaCamarero.MediaVentas));
Listado.Add("");
}
if(infVentaCamarero.totalServido>0){
Listado.Add(String.Format("Total servido = {0:c}",infVentaCamarero.totalServido));
Listado.Add("Num rondas servidas = "+ infVentaCamarero.numRodasServidas);
Listado.Add(String.Format("Media servido = {0:c}", infVentaCamarero.MediaServido));
Listado.Add("");
}
if(infVentaCamarero.VentaComision>0){
Listado.Add(String.Format("Total venta comision = {0:c}", infVentaCamarero.VentaComision));
Listado.Add(String.Format("Comision dia = {0:c}",infVentaCamarero.Comision));
Listado.Add("");
}
}
return Listado;
}
public string[] CalcularCierre(IGesSql ges, int idTpv)
{
DataTable tbCierreCaja = ges.ExtraerTabla("CierreDeCaja", "IDCierre");
DataTable tbSumaCierre ;
DataTable tbResumen;
DataTable tbNumTicket;
DataView dwCierre = new DataView(tbCierreCaja, "IDTpv =" + idTpv, "hastaTicket", DataViewRowState.CurrentRows);
int numComienzo = dwCierre.Count > 0 ?
(int)dwCierre[dwCierre.Count - 1]["hastaTicket"] : 0;
tbSumaCierre = ges.EjecutarSqlSelect("SumaCierre","SELECT SUM(TotalLinea) AS total FROM "+
"(SELECT LineasTicket.numTicket, LineasTicket.TotalLinea FROM "+
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket "+
"WHERE (Ticket.IDTpv = "+ idTpv+ ")) AS LineasTpv WHERE numTicket > "+numComienzo);
tbNumTicket = ges.EjecutarSqlSelect("NumTicket", ("SELECT MIN(numTicket) AS minimo, MAX(numTicket) AS maximo FROM " +
"(SELECT LineasTicket.numTicket FROM " +
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket " +
"WHERE (Ticket.IDTpv = " + idTpv + ")) AS LineasTpv WHERE numTicket > " + numComienzo));
tbResumen = ges.EjecutarSqlSelect("TbResumen","SELECT nomArticulo, SUM(Cantidad) AS Cantidad " +
"FROM (SELECT LineasTicket.numTicket, LineasTicket.nomArticulo, LineasTicket.Cantidad FROM "+
"LineasTicket INNER JOIN Ticket ON LineasTicket.numTicket = Ticket.NumTicket "+
"WHERE (Ticket.IDTpv = "+ idTpv+ ")) AS LineasTpv WHERE (numTicket > "+numComienzo+") " +
"GROUP BY nomArticulo");
if (tbResumen.Rows.Count > 0)
{
int logArray = 4 + tbResumen.Rows.Count;
String[] linea = new String[logArray];
decimal totalDia = (decimal)tbSumaCierre.Rows[0][0];
linea[0] = String.Format("Total del dia: {0:#0.00}", totalDia);
int numTicket = (int)tbNumTicket.Rows[0]["maximo"] - (int)tbNumTicket.Rows[0]["minimo"];
linea[1] = String.Format("Numero de ticket: {0}", numTicket);
linea[2] = String.Format("Media por ticket: {0:#0.00}", totalDia / numTicket);
linea[3] = "";
int punt = 4;
foreach (DataRow dr in tbResumen.Rows)
{
String cantidad = String.Format("{0:#0.###}", dr["Cantidad"]);
if(cantidad.Contains(",")){
string[] cantidades = cantidad.Split(',');
cantidad = cantidades[0].PadLeft(4)+','+cantidades[1];
}else{
cantidad = cantidad.PadLeft(4);
}
linea[punt] = dr["nomArticulo"].ToString().PadRight(30) + cantidad;
punt++;
}
DataRow drCierre = tbCierreCaja.NewRow();
drCierre["desdeTicket"] = (int)tbNumTicket.Rows[0]["minimo"];
drCierre["hastaTicket"] = (int)tbNumTicket.Rows[0]["maximo"];
drCierre["fechaCierre"] = Utilidades.CadenasTexto.RotarFecha(DateTime.Now.ToShortDateString());
drCierre["HoraCierre"] = DateTime.Now.ToShortTimeString().PadLeft(5,'0');
drCierre["IDTpv"] = idTpv;
tbCierreCaja.Rows.Add(drCierre);
ges.EjConsultaNoSelect("CierreDeCaja",Valle.SqlUtilidades.UtilidadesReg.ExConsultaNoSelet(drCierre,AccionesConReg.Agregar,
"").Replace(@"\",@"\\"));
return linea;
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.HttpEndPointListener
//
// Author:
// Gonzalo Paniagua Javier (gonzalo.mono@gmail.com)
//
// Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
// Copyright (c) 2012 Xamarin, Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Collections.Generic;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
namespace System.Net
{
internal sealed class HttpEndPointListener
{
private HttpListener _listener;
private IPEndPoint _endpoint;
private Socket _socket;
private Dictionary<ListenerPrefix, HttpListener> _prefixes;
private List<ListenerPrefix> _unhandledPrefixes; // host = '*'
private List<ListenerPrefix> _allPrefixes; // host = '+'
private X509Certificate _cert;
private bool _secure;
private Dictionary<HttpConnection, HttpConnection> _unregisteredConnections;
public HttpEndPointListener(HttpListener listener, IPAddress addr, int port, bool secure)
{
_listener = listener;
if (secure)
{
_secure = secure;
_cert = _listener.LoadCertificateAndKey (addr, port);
}
_endpoint = new IPEndPoint(addr, port);
_socket = new Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(_endpoint);
_socket.Listen(500);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.UserToken = this;
args.Completed += OnAccept;
Socket dummy = null;
Accept(_socket, args, ref dummy);
_prefixes = new Dictionary<ListenerPrefix, HttpListener>();
_unregisteredConnections = new Dictionary<HttpConnection, HttpConnection>();
}
internal HttpListener Listener
{
get { return _listener; }
}
private static void Accept(Socket socket, SocketAsyncEventArgs e, ref Socket accepted)
{
e.AcceptSocket = null;
bool asyn;
try
{
asyn = socket.AcceptAsync(e);
}
catch
{
if (accepted != null)
{
try
{
accepted.Close();
}
catch
{
}
accepted = null;
}
return;
}
if (!asyn)
{
ProcessAccept(e);
}
}
private static void ProcessAccept(SocketAsyncEventArgs args)
{
Socket accepted = null;
if (args.SocketError == SocketError.Success)
accepted = args.AcceptSocket;
HttpEndPointListener epl = (HttpEndPointListener)args.UserToken;
Accept(epl._socket, args, ref accepted);
if (accepted == null)
return;
if (epl._secure && epl._cert == null)
{
accepted.Close();
return;
}
HttpConnection conn = new HttpConnection(accepted, epl, epl._secure, epl._cert);
lock (epl._unregisteredConnections)
{
epl._unregisteredConnections[conn] = conn;
}
conn.BeginReadRequest();
}
private static void OnAccept(object sender, SocketAsyncEventArgs e)
{
ProcessAccept(e);
}
internal void RemoveConnection(HttpConnection conn)
{
lock (_unregisteredConnections)
{
_unregisteredConnections.Remove(conn);
}
}
public bool BindContext(HttpListenerContext context)
{
HttpListenerRequest req = context.Request;
ListenerPrefix prefix;
HttpListener listener = SearchListener(req.Url, out prefix);
if (listener == null)
return false;
context._listener = listener;
context.Connection.Prefix = prefix;
return true;
}
public void UnbindContext(HttpListenerContext context)
{
if (context == null || context.Request == null)
return;
context._listener.UnregisterContext(context);
}
private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix)
{
prefix = null;
if (uri == null)
return null;
string host = uri.Host;
int port = uri.Port;
string path = WebUtility.UrlDecode(uri.AbsolutePath);
string pathSlash = path[path.Length - 1] == '/' ? path : path + "/";
HttpListener bestMatch = null;
int bestLength = -1;
if (host != null && host != "")
{
Dictionary<ListenerPrefix, HttpListener> localPrefixes = _prefixes;
foreach (ListenerPrefix p in localPrefixes.Keys)
{
string ppath = p.Path;
if (ppath.Length < bestLength)
continue;
if (p.Host != host || p.Port != port)
continue;
if (path.StartsWith(ppath) || pathSlash.StartsWith(ppath))
{
bestLength = ppath.Length;
bestMatch = localPrefixes[p];
prefix = p;
}
}
if (bestLength != -1)
return bestMatch;
}
List<ListenerPrefix> list = _unhandledPrefixes;
bestMatch = MatchFromList(host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = MatchFromList(host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
list = _allPrefixes;
bestMatch = MatchFromList(host, path, list, out prefix);
if (path != pathSlash && bestMatch == null)
bestMatch = MatchFromList(host, pathSlash, list, out prefix);
if (bestMatch != null)
return bestMatch;
return null;
}
private HttpListener MatchFromList(string host, string path, List<ListenerPrefix> list, out ListenerPrefix prefix)
{
prefix = null;
if (list == null)
return null;
HttpListener bestMatch = null;
int bestLength = -1;
foreach (ListenerPrefix p in list)
{
string ppath = p.Path;
if (ppath.Length < bestLength)
continue;
if (path.StartsWith(ppath))
{
bestLength = ppath.Length;
bestMatch = p._listener;
prefix = p;
}
}
return bestMatch;
}
private void AddSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
{
if (list == null)
return;
foreach (ListenerPrefix p in list)
{
if (p.Path == prefix.Path)
throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.Format(SR.net_listener_already, prefix));
}
list.Add(prefix);
}
private bool RemoveSpecial(List<ListenerPrefix> list, ListenerPrefix prefix)
{
if (list == null)
return false;
int c = list.Count;
for (int i = 0; i < c; i++)
{
ListenerPrefix p = list[i];
if (p.Path == prefix.Path)
{
list.RemoveAt(i);
return true;
}
}
return false;
}
private void CheckIfRemove()
{
if (_prefixes.Count > 0)
return;
List<ListenerPrefix> list = _unhandledPrefixes;
if (list != null && list.Count > 0)
return;
list = _allPrefixes;
if (list != null && list.Count > 0)
return;
HttpEndPointManager.RemoveEndPoint(this, _endpoint);
}
public void Close()
{
_socket.Close();
lock (_unregisteredConnections)
{
// Clone the list because RemoveConnection can be called from Close
var connections = new List<HttpConnection>(_unregisteredConnections.Keys);
foreach (HttpConnection c in connections)
c.Close(true);
_unregisteredConnections.Clear();
}
}
public void AddPrefix(ListenerPrefix prefix, HttpListener listener)
{
List<ListenerPrefix> current;
List<ListenerPrefix> future;
if (prefix.Host == "*")
{
do
{
current = _unhandledPrefixes;
future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
prefix._listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
return;
}
if (prefix.Host == "+")
{
do
{
current = _allPrefixes;
future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
prefix._listener = listener;
AddSpecial(future, prefix);
} while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs, p2;
do
{
prefs = _prefixes;
if (prefs.ContainsKey(prefix))
{
HttpListener other = (HttpListener)prefs[prefix];
if (other != listener)
throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.Format(SR.net_listener_already, prefix));
return;
}
p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
p2[prefix] = listener;
} while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
}
public void RemovePrefix(ListenerPrefix prefix, HttpListener listener)
{
List<ListenerPrefix> current;
List<ListenerPrefix> future;
if (prefix.Host == "*")
{
do
{
current = _unhandledPrefixes;
future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref _unhandledPrefixes, future, current) != current);
CheckIfRemove();
return;
}
if (prefix.Host == "+")
{
do
{
current = _allPrefixes;
future = current != null ? new List<ListenerPrefix>(current) : new List<ListenerPrefix>();
if (!RemoveSpecial(future, prefix))
break; // Prefix not found
} while (Interlocked.CompareExchange(ref _allPrefixes, future, current) != current);
CheckIfRemove();
return;
}
Dictionary<ListenerPrefix, HttpListener> prefs, p2;
do
{
prefs = _prefixes;
if (!prefs.ContainsKey(prefix))
break;
p2 = new Dictionary<ListenerPrefix, HttpListener>(prefs);
p2.Remove(prefix);
} while (Interlocked.CompareExchange(ref _prefixes, p2, prefs) != prefs);
CheckIfRemove();
}
}
}
| |
// 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;
namespace System.Collections.ObjectModel
{
[Serializable]
[DebuggerTypeProxy(typeof(DictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> m_dictionary; // Do not rename (binary serialization)
[NonSerialized]
private KeyCollection _keys;
[NonSerialized]
private ValueCollection _values;
public ReadOnlyDictionary(IDictionary<TKey, TValue> dictionary)
{
m_dictionary = dictionary ?? throw new ArgumentNullException(nameof(dictionary));
}
protected IDictionary<TKey, TValue> Dictionary => m_dictionary;
public KeyCollection Keys
{
get => _keys ?? (_keys = new KeyCollection(m_dictionary.Keys));
}
public ValueCollection Values
{
get => _values ?? (_values = new ValueCollection(m_dictionary.Values));
}
public bool ContainsKey(TKey key) => m_dictionary.ContainsKey(key);
ICollection<TKey> IDictionary<TKey, TValue>.Keys => Keys;
public bool TryGetValue(TKey key, out TValue value)
{
return m_dictionary.TryGetValue(key, out value);
}
ICollection<TValue> IDictionary<TKey, TValue>.Values => Values;
public TValue this[TKey key] => m_dictionary[key];
void IDictionary<TKey, TValue>.Add(TKey key, TValue value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IDictionary<TKey, TValue>.Remove(TKey key)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
TValue IDictionary<TKey, TValue>.this[TKey key]
{
get => m_dictionary[key];
set => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
public int Count => m_dictionary.Count;
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item)
{
return m_dictionary.Contains(item);
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
m_dictionary.CopyTo(array, arrayIndex);
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly => true;
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
{
return m_dictionary.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable)m_dictionary).GetEnumerator();
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return key is TKey;
}
void IDictionary.Add(object key, object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IDictionary.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IDictionary.Contains(object key)
{
return IsCompatibleKey(key) && ContainsKey((TKey)key);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
IDictionary d = m_dictionary as IDictionary;
if (d != null)
{
return d.GetEnumerator();
}
return new DictionaryEnumerator(m_dictionary);
}
bool IDictionary.IsFixedSize => true;
bool IDictionary.IsReadOnly => true;
ICollection IDictionary.Keys => Keys;
void IDictionary.Remove(object key)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
ICollection IDictionary.Values => Values;
object IDictionary.this[object key]
{
get
{
if (!IsCompatibleKey(key))
{
return null;
}
return this[(TKey)key];
}
set => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (index < 0 || index > array.Length)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[];
if (pairs != null)
{
m_dictionary.CopyTo(pairs, index);
}
else
{
DictionaryEntry[] dictEntryArray = array as DictionaryEntry[];
if (dictEntryArray != null)
{
foreach (var item in m_dictionary)
{
dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value);
}
}
else
{
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
try
{
foreach (var item in m_dictionary)
{
objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value);
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => (m_dictionary is ICollection coll) ? coll.SyncRoot : this;
private struct DictionaryEnumerator : IDictionaryEnumerator
{
private readonly IDictionary<TKey, TValue> _dictionary;
private IEnumerator<KeyValuePair<TKey, TValue>> _enumerator;
public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary)
{
_dictionary = dictionary;
_enumerator = _dictionary.GetEnumerator();
}
public DictionaryEntry Entry
{
get => new DictionaryEntry(_enumerator.Current.Key, _enumerator.Current.Value);
}
public object Key => _enumerator.Current.Key;
public object Value => _enumerator.Current.Value;
public object Current => Entry;
public bool MoveNext() => _enumerator.MoveNext();
public void Reset() => _enumerator.Reset();
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys => Keys;
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values => Values;
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private readonly ICollection<TKey> _collection;
internal KeyCollection(ICollection<TKey> collection)
{
_collection = collection ?? throw new ArgumentNullException(nameof(collection));
}
void ICollection<TKey>.Add(TKey item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<TKey>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<TKey>.Contains(TKey item)
{
return _collection.Contains(item);
}
public void CopyTo(TKey[] array, int arrayIndex)
{
_collection.CopyTo(array, arrayIndex);
}
public int Count => _collection.Count;
bool ICollection<TKey>.IsReadOnly => true;
bool ICollection<TKey>.Remove(TKey item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
public IEnumerator<TKey> GetEnumerator() => _collection.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)_collection).GetEnumerator();
void ICollection.CopyTo(Array array, int index)
{
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TKey>(_collection, array, index);
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => (_collection is ICollection coll) ? coll.SyncRoot : this;
}
[DebuggerTypeProxy(typeof(CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private readonly ICollection<TValue> _collection;
internal ValueCollection(ICollection<TValue> collection)
{
_collection = collection ?? throw new ArgumentNullException(nameof(collection));
}
void ICollection<TValue>.Add(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<TValue>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<TValue>.Contains(TValue item) => _collection.Contains(item);
public void CopyTo(TValue[] array, int arrayIndex)
{
_collection.CopyTo(array, arrayIndex);
}
public int Count => _collection.Count;
bool ICollection<TValue>.IsReadOnly => true;
bool ICollection<TValue>.Remove(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
public IEnumerator<TValue> GetEnumerator() => _collection.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable)_collection).GetEnumerator();
void ICollection.CopyTo(Array array, int index)
{
ReadOnlyDictionaryHelpers.CopyToNonGenericICollectionHelper<TValue>(_collection, array, index);
}
bool ICollection.IsSynchronized => false;
object ICollection.SyncRoot => (_collection is ICollection coll) ? coll.SyncRoot : this;
}
}
// To share code when possible, use a non-generic class to get rid of irrelevant type parameters.
internal static class ReadOnlyDictionaryHelpers
{
// Abstracted away to avoid redundant implementations.
internal static void CopyToNonGenericICollectionHelper<T>(ICollection<T> collection, Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < collection.Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
// Easy out if the ICollection<T> implements the non-generic ICollection
ICollection nonGenericCollection = collection as ICollection;
if (nonGenericCollection != null)
{
nonGenericCollection.CopyTo(array, index);
return;
}
T[] items = array as T[];
if (items != null)
{
collection.CopyTo(items, index);
}
else
{
// We can't cast array of value type to object[], so we don't support
// widening of primitive types here.
object[] objects = array as object[];
if (objects == null)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
try
{
foreach (var item in collection)
{
objects[index++] = item;
}
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ClosedXML.Excel
{
internal class XLTable : XLRange, IXLTable
{
#region Private fields
private string _name;
internal bool _showTotalsRow;
internal HashSet<String> _uniqueNames;
#endregion
#region Constructor
public XLTable(XLRange range, Boolean addToTables, Boolean setAutofilter = true)
: base(new XLRangeParameters(range.RangeAddress, range.Style ))
{
InitializeValues(setAutofilter);
Int32 id = 1;
while (true)
{
string tableName = String.Format("Table{0}", id);
if (!Worksheet.Tables.Any(t => t.Name == tableName))
{
Name = tableName;
AddToTables(range, addToTables);
break;
}
id++;
}
}
public XLTable(XLRange range, String name, Boolean addToTables, Boolean setAutofilter = true)
: base(new XLRangeParameters(range.RangeAddress, range.Style))
{
InitializeValues(setAutofilter);
Name = name;
AddToTables(range, addToTables);
}
#endregion
private IXLRangeAddress _lastRangeAddress;
private Dictionary<String, IXLTableField> _fieldNames = null;
public Dictionary<String, IXLTableField> FieldNames
{
get
{
if (_fieldNames != null && _lastRangeAddress != null && _lastRangeAddress.Equals(RangeAddress)) return _fieldNames;
_fieldNames = new Dictionary<String, IXLTableField>();
_lastRangeAddress = RangeAddress;
if (ShowHeaderRow)
{
var headersRow = HeadersRow();
Int32 cellPos = 0;
foreach (var cell in headersRow.Cells())
{
var name = cell.GetString();
if (XLHelper.IsNullOrWhiteSpace(name))
{
name = "Column" + (cellPos + 1);
cell.SetValue(name);
}
if (_fieldNames.ContainsKey(name))
throw new ArgumentException("The header row contains more than one field name '" + name + "'.");
_fieldNames.Add(name, new XLTableField(this, name) {Index = cellPos++ });
}
}
else
{
if (_fieldNames == null) _fieldNames = new Dictionary<String, IXLTableField>();
Int32 colCount = ColumnCount();
for (Int32 i = 1; i <= colCount; i++)
{
if (!_fieldNames.Values.Any(f => f.Index == i - 1))
{
var name = "Column" + i;
_fieldNames.Add(name, new XLTableField(this, name) {Index = i - 1 });
}
}
}
return _fieldNames;
}
}
internal void AddFields(IEnumerable<String> fieldNames)
{
_fieldNames = new Dictionary<String, IXLTableField>();
Int32 cellPos = 0;
foreach(var name in fieldNames)
{
_fieldNames.Add(name, new XLTableField(this, name) { Index = cellPos++ });
}
}
internal String RelId { get; set; }
public IXLTableRange DataRange
{
get
{
XLRange range;
//var ws = Worksheet;
//var tracking = ws.EventTrackingEnabled;
//ws.EventTrackingEnabled = false;
if (_showHeaderRow)
{
range = _showTotalsRow
? Range(2, 1,RowCount() - 1,ColumnCount())
: Range(2, 1, RowCount(), ColumnCount());
}
else
{
range = _showTotalsRow
? Range(1, 1, RowCount() - 1, ColumnCount())
: Range(1, 1, RowCount(), ColumnCount());
}
//ws.EventTrackingEnabled = tracking;
return new XLTableRange(range, this);
}
}
private XLAutoFilter _autoFilter;
public XLAutoFilter AutoFilter
{
get
{
using (var asRange = ShowTotalsRow ? Range(1, 1, RowCount() - 1, ColumnCount()) : AsRange())
{
if (_autoFilter == null)
_autoFilter = new XLAutoFilter();
_autoFilter.Range = asRange;
}
return _autoFilter;
}
}
public new IXLBaseAutoFilter SetAutoFilter()
{
return AutoFilter;
}
#region IXLTable Members
public Boolean EmphasizeFirstColumn { get; set; }
public Boolean EmphasizeLastColumn { get; set; }
public Boolean ShowRowStripes { get; set; }
public Boolean ShowColumnStripes { get; set; }
private Boolean _showAutoFilter;
public Boolean ShowAutoFilter {
get { return _showHeaderRow && _showAutoFilter; }
set { _showAutoFilter = value; }
}
public XLTableTheme Theme { get; set; }
public String Name
{
get { return _name; }
set
{
if (Worksheet.Tables.Any(t => t.Name == value))
{
throw new ArgumentException(String.Format("This worksheet already contains a table named '{0}'",
value));
}
_name = value;
}
}
public Boolean ShowTotalsRow
{
get { return _showTotalsRow; }
set
{
if (value && !_showTotalsRow)
InsertRowsBelow(1);
else if (!value && _showTotalsRow)
TotalsRow().Delete();
_showTotalsRow = value;
if (_showTotalsRow)
{
AutoFilter.Range = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber, RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber - 1, RangeAddress.LastAddress.ColumnNumber);
}
else
AutoFilter.Range = Worksheet.Range(RangeAddress);
}
}
public IXLRangeRow HeadersRow()
{
if (!ShowHeaderRow) return null;
var m = FieldNames;
return FirstRow();
}
public IXLRangeRow TotalsRow()
{
return ShowTotalsRow ? LastRow() : null;
}
public IXLTableField Field(String fieldName)
{
return Field(GetFieldIndex(fieldName));
}
public IXLTableField Field(Int32 fieldIndex)
{
return FieldNames.Values.First(f => f.Index == fieldIndex);
}
public IEnumerable<IXLTableField> Fields
{
get
{
Int32 columnCount = ColumnCount();
for (int co = 0; co < columnCount; co++)
yield return Field(co);
}
}
public IXLTable SetEmphasizeFirstColumn()
{
EmphasizeFirstColumn = true;
return this;
}
public IXLTable SetEmphasizeFirstColumn(Boolean value)
{
EmphasizeFirstColumn = value;
return this;
}
public IXLTable SetEmphasizeLastColumn()
{
EmphasizeLastColumn = true;
return this;
}
public IXLTable SetEmphasizeLastColumn(Boolean value)
{
EmphasizeLastColumn = value;
return this;
}
public IXLTable SetShowRowStripes()
{
ShowRowStripes = true;
return this;
}
public IXLTable SetShowRowStripes(Boolean value)
{
ShowRowStripes = value;
return this;
}
public IXLTable SetShowColumnStripes()
{
ShowColumnStripes = true;
return this;
}
public IXLTable SetShowColumnStripes(Boolean value)
{
ShowColumnStripes = value;
return this;
}
public IXLTable SetShowTotalsRow()
{
ShowTotalsRow = true;
return this;
}
public IXLTable SetShowTotalsRow(Boolean value)
{
ShowTotalsRow = value;
return this;
}
public IXLTable SetShowAutoFilter()
{
ShowAutoFilter = true;
return this;
}
public IXLTable SetShowAutoFilter(Boolean value)
{
ShowAutoFilter = value;
return this;
}
public new IXLRange Sort(String columnsToSortBy, XLSortOrder sortOrder = XLSortOrder.Ascending,
Boolean matchCase = false, Boolean ignoreBlanks = true)
{
var toSortBy = new StringBuilder();
foreach (string coPairTrimmed in columnsToSortBy.Split(',').Select(coPair => coPair.Trim()))
{
String coString;
String order;
if (coPairTrimmed.Contains(' '))
{
var pair = coPairTrimmed.Split(' ');
coString = pair[0];
order = pair[1];
}
else
{
coString = coPairTrimmed;
order = "ASC";
}
Int32 co;
if (!Int32.TryParse(coString, out co))
co = Field(coString).Index + 1;
toSortBy.Append(co);
toSortBy.Append(" ");
toSortBy.Append(order);
toSortBy.Append(",");
}
return DataRange.Sort(toSortBy.ToString(0, toSortBy.Length - 1), sortOrder, matchCase, ignoreBlanks);
}
public new IXLTable Clear(XLClearOptions clearOptions = XLClearOptions.ContentsAndFormats)
{
base.Clear(clearOptions);
return this;
}
IXLBaseAutoFilter IXLTable.AutoFilter
{
get { return AutoFilter; }
}
public new void Dispose()
{
if (AutoFilter != null)
AutoFilter.Dispose();
base.Dispose();
}
#endregion
private void InitializeValues(Boolean setAutofilter)
{
ShowRowStripes = true;
_showHeaderRow = true;
Theme = XLTableTheme.TableStyleLight9;
if (setAutofilter)
InitializeAutoFilter();
HeadersRow().DataType = XLCellValues.Text;
if (RowCount() == 1)
InsertRowsBelow(1);
}
public void InitializeAutoFilter()
{
ShowAutoFilter = true;
}
private void AddToTables(XLRange range, Boolean addToTables)
{
if (!addToTables) return;
_uniqueNames = new HashSet<string>();
Int32 co = 1;
foreach (IXLCell c in range.Row(1).Cells())
{
if (XLHelper.IsNullOrWhiteSpace(((XLCell)c).InnerText))
c.Value = GetUniqueName("Column" + co.ToInvariantString());
_uniqueNames.Add(c.GetString());
co++;
}
Worksheet.Tables.Add(this);
}
private String GetUniqueName(String originalName)
{
String name = originalName;
if (_uniqueNames.Contains(name))
{
Int32 i = 1;
name = originalName + i.ToInvariantString();
while (_uniqueNames.Contains(name))
{
i++;
name = originalName + i.ToInvariantString();
}
}
_uniqueNames.Add(name);
return name;
}
public Int32 GetFieldIndex(String name)
{
if (FieldNames.ContainsKey(name))
return FieldNames[name].Index;
throw new ArgumentOutOfRangeException("The header row doesn't contain field name '" + name + "'.");
}
internal Boolean _showHeaderRow;
public Boolean ShowHeaderRow
{
get { return _showHeaderRow; }
set
{
if (_showHeaderRow == value) return;
if (_showHeaderRow)
{
var headersRow = HeadersRow();
_uniqueNames = new HashSet<string>();
Int32 co = 1;
foreach (IXLCell c in headersRow.Cells())
{
if (XLHelper.IsNullOrWhiteSpace(((XLCell)c).InnerText))
c.Value = GetUniqueName("Column" + co.ToInvariantString());
_uniqueNames.Add(c.GetString());
co++;
}
headersRow.Clear();
RangeAddress.FirstAddress = new XLAddress(Worksheet, RangeAddress.FirstAddress.RowNumber + 1,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.FirstAddress.FixedRow,
RangeAddress.FirstAddress.FixedColumn);
HeadersRow().DataType = XLCellValues.Text;
}
else
{
using(var asRange = Worksheet.Range(
RangeAddress.FirstAddress.RowNumber - 1 ,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.LastAddress.RowNumber,
RangeAddress.LastAddress.ColumnNumber
))
using (var firstRow = asRange.FirstRow())
{
IXLRangeRow rangeRow;
if (firstRow.IsEmpty(true))
{
rangeRow = firstRow;
RangeAddress.FirstAddress = new XLAddress(Worksheet,
RangeAddress.FirstAddress.RowNumber - 1,
RangeAddress.FirstAddress.ColumnNumber,
RangeAddress.FirstAddress.FixedRow,
RangeAddress.FirstAddress.FixedColumn);
}
else
{
var fAddress = RangeAddress.FirstAddress;
var lAddress = RangeAddress.LastAddress;
rangeRow = firstRow.InsertRowsBelow(1, false).First();
RangeAddress.FirstAddress = new XLAddress(Worksheet, fAddress.RowNumber,
fAddress.ColumnNumber,
fAddress.FixedRow,
fAddress.FixedColumn);
RangeAddress.LastAddress = new XLAddress(Worksheet, lAddress.RowNumber + 1,
lAddress.ColumnNumber,
lAddress.FixedRow,
lAddress.FixedColumn);
}
Int32 co = 1;
foreach (var name in FieldNames.Values.Select(f => f.Name))
{
rangeRow.Cell(co).SetValue(name);
co++;
}
}
}
_showHeaderRow = value;
}
}
public IXLTable SetShowHeaderRow()
{
return SetShowHeaderRow(true);
}
public IXLTable SetShowHeaderRow(Boolean value)
{
ShowHeaderRow = value;
return this;
}
public void ExpandTableRows(Int32 rows)
{
RangeAddress.LastAddress = new XLAddress(Worksheet, RangeAddress.LastAddress.RowNumber + rows,
RangeAddress.LastAddress.ColumnNumber,
RangeAddress.LastAddress.FixedRow,
RangeAddress.LastAddress.FixedColumn);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// The GroupCollection lists the captured Capture numbers
// contained in a compiled Regex.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Text.RegularExpressions
{
/// <summary>
/// Represents a sequence of capture substrings. The object is used
/// to return the set of captures done by a single capturing group.
/// </summary>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(RegexCollectionDebuggerProxy<Group>))]
public class GroupCollection : IList<Group>, IReadOnlyList<Group>, IList
{
private readonly Match _match;
private readonly Dictionary<int, int> _captureMap;
// cache of Group objects fed to the user
private Group[] _groups;
internal GroupCollection(Match match, Dictionary<int, int> caps)
{
_match = match;
_captureMap = caps;
}
/// <summary>
/// Returns the number of groups.
/// </summary>
public int Count
{
get { return _match._matchcount.Length; }
}
public Group this[int groupnum]
{
get { return GetGroup(groupnum); }
}
public Group this[string groupname]
{
get
{
if (_match._regex == null)
return Group._emptygroup;
return GetGroup(_match._regex.GroupNumberFromName(groupname));
}
}
/// <summary>
/// Copies all the elements of the collection to the given array
/// beginning at the given index.
/// </summary>
public void CopyTo(Group[] array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
if (arrayIndex < 0 || arrayIndex > array.Length)
throw new ArgumentOutOfRangeException("arrayIndex");
if (array.Length - arrayIndex < Count)
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
for (int i = arrayIndex, j = 0; j < Count; i++, j++)
{
array[i] = this[j];
}
}
/// <summary>
/// Provides an enumerator in the same order as Item[].
/// </summary>
public IEnumerator GetEnumerator()
{
return new Enumerator(this);
}
IEnumerator<Group> IEnumerable<Group>.GetEnumerator()
{
return new Enumerator(this);
}
private Group GetGroup(int groupnum)
{
if (_captureMap != null)
{
int groupNumImpl;
if (_captureMap.TryGetValue(groupnum, out groupNumImpl))
{
return GetGroupImpl(groupNumImpl);
}
}
else if (groupnum < _match._matchcount.Length && groupnum >= 0)
{
return GetGroupImpl(groupnum);
}
return Group._emptygroup;
}
/// <summary>
/// Caches the group objects
/// </summary>
private Group GetGroupImpl(int groupnum)
{
if (groupnum == 0)
return _match;
// Construct all the Group objects the first time GetGroup is called
if (_groups == null)
{
_groups = new Group[_match._matchcount.Length - 1];
for (int i = 0; i < _groups.Length; i++)
{
string groupname = _match._regex.GroupNameFromNumber(i + 1);
_groups[i] = new Group(_match._text, _match._matches[i + 1], _match._matchcount[i + 1], groupname);
}
}
return _groups[groupnum - 1];
}
int IList<Group>.IndexOf(Group item)
{
var comparer = EqualityComparer<Group>.Default;
for (int i = 0; i < Count; i++)
{
if (comparer.Equals(this[i], item))
return i;
}
return -1;
}
void IList<Group>.Insert(int index, Group item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList<Group>.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
Group IList<Group>.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
void ICollection<Group>.Add(Group item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void ICollection<Group>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool ICollection<Group>.Contains(Group item)
{
return ((IList<Group>)this).IndexOf(item) >= 0;
}
bool ICollection<Group>.IsReadOnly
{
get { return true; }
}
bool ICollection<Group>.Remove(Group item)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
int IList.Add(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.Clear()
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.Contains(object value)
{
return value is Group && ((ICollection<Group>)this).Contains((Group)value);
}
int IList.IndexOf(object value)
{
return value is Group ? ((IList<Group>)this).IndexOf((Group)value) : -1;
}
void IList.Insert(int index, object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
bool IList.IsFixedSize
{
get { return true; }
}
bool IList.IsReadOnly
{
get { return true; }
}
void IList.Remove(object value)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
void IList.RemoveAt(int index)
{
throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection);
}
object IList.this[int index]
{
get { return this[index]; }
set { throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return _match; }
}
void ICollection.CopyTo(Array array, int arrayIndex)
{
if (array == null)
throw new ArgumentNullException("array");
for (int i = arrayIndex, j = 0; j < Count; i++, j++)
{
array.SetValue(this[j], i);
}
}
private class Enumerator : IEnumerator<Group>
{
private readonly GroupCollection _collection;
private int _index;
internal Enumerator(GroupCollection collection)
{
Debug.Assert(collection != null, "collection cannot be null.");
_collection = collection;
_index = -1;
}
public bool MoveNext()
{
int size = _collection.Count;
if (_index >= size)
return false;
_index++;
return _index < size;
}
public Group Current
{
get
{
if (_index < 0 || _index >= _collection.Count)
throw new InvalidOperationException(SR.EnumNotStarted);
return _collection[_index];
}
}
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
_index = -1;
}
void IDisposable.Dispose()
{
}
}
}
}
| |
using CakeMail.RestClient.Exceptions;
using Moq;
using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace CakeMail.RestClient.UnitTests
{
public class CakeMailRestClientTests
{
private const string API_KEY = "...dummy API key...";
private const string USER_KEY = "...dummy USER key...";
private const long CLIENT_ID = 999;
[Fact]
public void Version_is_not_empty()
{
// Arrange
// Act
var version = CakeMailRestClient.Version;
// Assert
version.ShouldNotBeNullOrEmpty();
}
[Fact]
public void RestClient_constructor_with_ApiKey()
{
// Arrange
// Act
var client = new CakeMailRestClient(API_KEY);
var baseUrl = client.BaseUrl;
// Assert
baseUrl.ShouldBe(new Uri("https://api.wbsrvc.com"));
}
[Fact]
public void RestClient_constructor_with_IWebProxy()
{
// Arrange
var mockProxy = new Mock<IWebProxy>(MockBehavior.Strict);
// Act
var client = new CakeMailRestClient(API_KEY, mockProxy.Object);
// Assert
client.BaseUrl.ShouldBe(new Uri("https://api.wbsrvc.com/"));
}
[Fact]
public void RestClient_constructor_with_HttpClient()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
var httpClient = new HttpClient(mockHttp);
// Act
var client = new CakeMailRestClient(API_KEY, httpClient);
// Assert
client.BaseUrl.ShouldBe(new Uri("https://api.wbsrvc.com/"));
}
[Fact]
public void RestClient_dispose()
{
var client = new CakeMailRestClient(API_KEY);
client.Dispose();
}
[Fact]
public async Task RestClient_Throws_exception_when_responsestatus_is_error()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Country/GetList")).Respond(HttpStatusCode.BadRequest);
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<HttpException>(async () =>
{
var result = await client.Countries.GetListAsync().ConfigureAwait(false);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_responsestatus_is_timeout()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Country/GetList")).Respond(HttpStatusCode.RequestTimeout);
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<HttpException>(async () =>
{
var result = await client.Countries.GetListAsync().ConfigureAwait(false);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_request_is_successful_but_response_content_is_empty()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Country/GetList")).Respond(HttpStatusCode.OK, new StringContent(""));
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<JsonReaderException>(async () =>
{
var result = await client.Countries.GetListAsync().ConfigureAwait(false);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_responsescode_is_between_400_and_499_and_content_is_empty()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Country/GetList")).Respond((HttpStatusCode)450);
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<HttpException>(async () =>
{
var result = await client.Countries.GetListAsync().ConfigureAwait(false);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_responsescode_is_between_400_and_499_and_content_is_not_empty()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Country/GetList")).Respond((HttpStatusCode)450, new StringContent("dummy content", Encoding.UTF8, "application/json"));
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<HttpException>(async () =>
{
var result = await client.Countries.GetListAsync().ConfigureAwait(false);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_responsescode_is_between_500_and_599()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Country/GetList")).Respond((HttpStatusCode)550);
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<HttpException>(async () =>
{
var result = await client.Countries.GetListAsync().ConfigureAwait(false);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_responsescode_is_greater_than_599()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
mockHttp.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Country/GetList")).Respond((HttpStatusCode)600);
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<HttpException>(async () =>
{
var result = await client.Countries.GetListAsync().ConfigureAwait(false);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_responsecode_is_greater_than_599_and_custom_errormessage()
{
// Arrange
var mockHttp = new MockHttpMessageHandler();
mockHttp
.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Country/GetList"))
.Respond((HttpStatusCode)600, new StringContent("This is a bogus error message", Encoding.UTF8, "application/json"));
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<HttpException>(async () =>
{
var result = await client.Countries.GetListAsync().ConfigureAwait(false);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_cakemail_api_returns_failure_with_post_details()
{
// Arrange
var campaignId = 123L;
var jsonResponse = string.Format("{{\"status\":\"failed\",\"data\":\"There is no campaign with the id {0} and client id {1}!\",\"post\":{{\"user_key\":\"{2}\",\"campaign_id\":\"{0}\",\"client_id\":\"{1}\"}}}}", campaignId, CLIENT_ID, USER_KEY);
var mockHttp = new MockHttpMessageHandler();
mockHttp
.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Campaign/Delete"))
.Respond((HttpStatusCode)200, new StringContent(jsonResponse, Encoding.UTF8, "application/json"));
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<CakeMailPostException>(async () =>
{
var result = await client.Campaigns.DeleteAsync(USER_KEY, campaignId, CLIENT_ID);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_reponse_contains_invalid_json()
{
// Arrange
var campaignId = 123L;
var jsonResponse = "{\"status\":\"success\",\"data\":\"{This content is not valid json (missing closing brackets)\"";
var mockHttp = new MockHttpMessageHandler();
mockHttp
.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("Campaign/Delete"))
.Respond((HttpStatusCode)200, new StringContent(jsonResponse, Encoding.UTF8, "application/json"));
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<JsonReaderException>(async () =>
{
var result = await client.Campaigns.DeleteAsync(USER_KEY, campaignId, CLIENT_ID);
});
}
[Fact]
public async Task RestClient_Throws_exception_when_reponse_does_not_contain_expected_property()
{
// Arrange
var categoryId = 123;
var labels = new Dictionary<string, string>
{
{ "en_US", "My Category" }
};
var jsonResponse = string.Format("{{\"status\":\"success\",\"data\":{{\"we_expected_a_property_named_id_but_instead_we_received_this_bogus_property\":\"{0}\"}}}}", categoryId);
var mockHttp = new MockHttpMessageHandler();
mockHttp
.Expect(HttpMethod.Post, Utils.GetCakeMailApiUri("TemplateV2/CreateCategory"))
.Respond((HttpStatusCode)200, new StringContent(jsonResponse, Encoding.UTF8, "application/json"));
// Act
var client = new CakeMailRestClient(API_KEY, httpClient: mockHttp.ToHttpClient());
await Should.ThrowAsync<CakeMailException>(async () =>
{
var result = await client.Templates.CreateCategoryAsync(USER_KEY, labels);
});
}
}
}
| |
#region License
/* The MIT License
*
* Copyright (c) 2011 Red Badger Consulting
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
namespace RedBadger.Xpf.Controls
{
using System.Collections.Generic;
using RedBadger.Xpf.Graphics;
using RedBadger.Xpf.Internal;
using RedBadger.Xpf.Media;
public class Border : UIElement
{
public static readonly ReactiveProperty<Brush> BackgroundProperty =
ReactiveProperty<Brush>.Register(
"Background", typeof(Border), ReactivePropertyChangedCallbacks.InvalidateArrange);
public static readonly ReactiveProperty<Brush> BorderBrushProperty =
ReactiveProperty<Brush>.Register(
"BorderBrush", typeof(Border), null, ReactivePropertyChangedCallbacks.InvalidateArrange);
public static readonly ReactiveProperty<Thickness> BorderThicknessProperty =
ReactiveProperty<Thickness>.Register(
"BorderThickness", typeof(Border), new Thickness(), ReactivePropertyChangedCallbacks.InvalidateMeasure);
public static readonly ReactiveProperty<IElement> ChildProperty = ReactiveProperty<IElement>.Register(
"Child", typeof(Border), null, ChildPropertyChangedCallback);
public static readonly ReactiveProperty<Thickness> PaddingProperty =
ReactiveProperty<Thickness>.Register(
"Padding", typeof(Border), new Thickness(), ReactivePropertyChangedCallbacks.InvalidateMeasure);
private readonly IList<Rect> borders = new List<Rect>();
public Brush Background
{
get
{
return this.GetValue(BackgroundProperty);
}
set
{
this.SetValue(BackgroundProperty, value);
}
}
public Brush BorderBrush
{
get
{
return this.GetValue(BorderBrushProperty);
}
set
{
this.SetValue(BorderBrushProperty, value);
}
}
public Thickness BorderThickness
{
get
{
return this.GetValue(BorderThicknessProperty);
}
set
{
this.SetValue(BorderThicknessProperty, value);
}
}
public IElement Child
{
get
{
return this.GetValue(ChildProperty);
}
set
{
this.SetValue(ChildProperty, value);
}
}
public Thickness Padding
{
get
{
return this.GetValue(PaddingProperty);
}
set
{
this.SetValue(PaddingProperty, value);
}
}
public override IEnumerable<IElement> GetVisualChildren()
{
IElement child = this.Child;
if (child != null)
{
yield return child;
}
yield break;
}
protected override Size ArrangeOverride(Size finalSize)
{
IElement child = this.Child;
if (child != null)
{
var finalRect = new Rect(new Point(), finalSize);
finalRect = finalRect.Deflate(this.BorderThickness);
finalRect = finalRect.Deflate(this.Padding);
child.Arrange(finalRect);
}
return finalSize;
}
protected override Size MeasureOverride(Size availableSize)
{
Thickness borderThicknessAndPadding = this.BorderThickness + this.Padding;
IElement child = this.Child;
if (child != null)
{
child.Measure(availableSize.Deflate(borderThicknessAndPadding));
return child.DesiredSize.Inflate(borderThicknessAndPadding);
}
return borderThicknessAndPadding.Collapse();
}
protected override void OnRender(IDrawingContext drawingContext)
{
if (this.BorderThickness != new Thickness() && this.BorderBrush != null)
{
this.GenerateBorders();
foreach (Rect border in this.borders)
{
drawingContext.DrawRectangle(border, this.BorderBrush);
}
}
if (this.Background != null)
{
drawingContext.DrawRectangle(
new Rect(0, 0, this.ActualWidth, this.ActualHeight).Deflate(this.BorderThickness), this.Background);
}
}
private static void ChildPropertyChangedCallback(
IReactiveObject source, ReactivePropertyChangeEventArgs<IElement> change)
{
var border = (Border)source;
border.InvalidateMeasure();
IElement oldChild = change.OldValue;
if (oldChild != null)
{
oldChild.VisualParent = null;
}
IElement newChild = change.NewValue;
if (newChild != null)
{
newChild.VisualParent = border;
}
}
private void GenerateBorders()
{
this.borders.Clear();
if (this.BorderThickness.Left > 0)
{
this.borders.Add(new Rect(0, 0, this.BorderThickness.Left, this.ActualHeight));
}
if (this.BorderThickness.Top > 0)
{
this.borders.Add(
new Rect(
this.BorderThickness.Left,
0,
this.ActualWidth - this.BorderThickness.Left,
this.BorderThickness.Top));
}
if (this.BorderThickness.Right > 0)
{
this.borders.Add(
new Rect(
this.ActualWidth - this.BorderThickness.Right,
this.BorderThickness.Top,
this.BorderThickness.Right,
this.ActualHeight - this.BorderThickness.Top));
}
if (this.BorderThickness.Bottom > 0)
{
this.borders.Add(
new Rect(
this.BorderThickness.Left,
this.ActualHeight - this.BorderThickness.Bottom,
this.ActualWidth - (this.BorderThickness.Left + this.BorderThickness.Right),
this.BorderThickness.Bottom));
}
}
}
}
| |
using System;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.Application.Progress;
using JetBrains.Diagnostics;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.QuickFixes;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Daemon.Errors;
using JetBrains.ReSharper.Plugins.Unity.Utils;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.CSharp.Util;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Resolve.Managed;
using JetBrains.ReSharper.Psi.Naming.Settings;
using JetBrains.ReSharper.Psi.Resolve.Managed;
using JetBrains.ReSharper.Psi.Tree;
using JetBrains.TextControl;
using JetBrains.Util;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.QuickFixes
{
[QuickFix]
public class PreferAddressByIdToGraphicsParamsQuickFix : QuickFixBase
{
private readonly IInvocationExpression myInvocationExpression;
private readonly ICSharpArgument myArgument;
// using for name of new generated field
private readonly string myFieldName;
// using for find already declared field or property
private readonly string myGraphicsPropertyName;
// using to handle concatenation operations with const values and save possibility to correct refactoring
private readonly IExpression myArgumentExpression;
private readonly string myMapFunction;
private readonly string myTypeName;
public PreferAddressByIdToGraphicsParamsQuickFix(PreferAddressByIdToGraphicsParamsWarning warning)
{
myInvocationExpression = warning.InvocationMethod;
myArgument = warning.Argument;
myFieldName = myGraphicsPropertyName = warning.Literal;
if (!ValidityChecker.IsValidIdentifier(myFieldName)) myFieldName = "Property";
myArgumentExpression = warning.ArgumentExpression;
myMapFunction = warning.MapFunction;
myTypeName = warning.TypeName;
}
protected override Action<ITextControl> ExecutePsiTransaction(ISolution solution, IProgressIndicator progress)
{
var factory = CSharpElementFactory.GetInstance(myInvocationExpression);
// try find declaration where string to id conversation is done. If we don't find it, create in top-level class
var idDeclaration = TryFindDeclaration(myInvocationExpression, myGraphicsPropertyName, myTypeName, myMapFunction, out var name);
if (idDeclaration == null)
{
var psiModule = myInvocationExpression.PsiModule;
var fieldInitializerValue = factory.CreateExpression("$0.$1($2)",
TypeFactory.CreateTypeByCLRName(myTypeName, myInvocationExpression.PsiModule),
myMapFunction,
myArgumentExpression.Copy());
name = NamingUtil.GetUniqueName( myInvocationExpression, myFieldName, NamedElementKinds.PrivateStaticReadonly).NotNull();
var newDeclaration = factory.CreateFieldDeclaration(psiModule.GetPredefinedType().Int, name);
idDeclaration = newDeclaration.DeclaredElement;
if (idDeclaration == null)
return null;
newDeclaration.SetReadonly(true);
newDeclaration.SetStatic(true);
newDeclaration.SetAccessRights(AccessRights.PRIVATE);
newDeclaration.SetInitial(factory.CreateExpressionInitializer(fieldInitializerValue));
// TODO: [C#8] default interface implementations
// interface is not good place to add field declaration
var classDeclaration = GetTopLevelClassLikeDeclaration(myInvocationExpression);
classDeclaration.AddClassMemberDeclaration(newDeclaration);
}
// replace argument
var referenceExpression = factory.CreateReferenceExpression("$0", idDeclaration);
var argument = factory.CreateArgument(ParameterKind.VALUE, myArgument.NameIdentifier?.Name, referenceExpression);
myArgument.ReplaceBy(argument);
return null;
}
[CanBeNull]
private static IDeclaredElement TryFindIdDeclarationInClassLikeDeclaration(IClassLikeDeclaration declaration, string propertyName,
string requiredTypeName, string requiredMethodName, out string name)
{
name = null;
var classDeclaredElement = declaration.DeclaredElement;
if (classDeclaredElement == null)
return null;
var members = classDeclaredElement.GetMembers().Where(x => x is IField || x is IProperty)
.SelectNotNull(x => x.GetDeclarations().SingleOrDefault());
foreach (var member in members)
{
switch (member)
{
case IFieldDeclaration field:
if (HandleField(field, propertyName, requiredTypeName, requiredMethodName, out name))
return field.DeclaredElement;
break;
case IPropertyDeclaration property:
if (HandleProperty(property, propertyName, requiredTypeName, requiredMethodName, out name))
{
return property.DeclaredElement;
}
break;
}
}
return null;
}
private static bool HandleProperty(IPropertyDeclaration property, string propertyName, string requiredTypeName, string requiredMethodName, out string name)
{
name = null;
if (!property.IsStatic)
return false;
var accessors = property.AccessorDeclarations;
if (accessors.Count != 1)
return false;
if (accessors[0].Kind != AccessorKind.GETTER)
return false;
if (property.DeclaredElement == null)
return false;
var initializer = property.Initial;
if (initializer is IExpressionInitializer exprInit && exprInit.Value is IInvocationExpression invocation)
{
return HandleInvocation(invocation, propertyName, requiredTypeName, requiredMethodName, out name);
}
return false;
}
private static bool HandleField(IFieldDeclaration field, string propertyName, string requiredTypeName, string requiredMethodName, out string name)
{
name = null;
if (!field.IsStatic || !field.IsReadonly)
return false;
if (field.DeclaredElement == null)
return false;
var initializer = field.Initial;
if (initializer is IExpressionInitializer exprInit && exprInit.Value is IInvocationExpression invocation)
{
return HandleInvocation(invocation, propertyName, requiredTypeName, requiredMethodName, out name);
}
return false;
}
private static bool HandleInvocation(IInvocationExpression invocation, string propertyName, string requiredTypeName,
string requiredMethodName, out string name)
{
name = null;
var method = invocation.Reference?.Resolve().DeclaredElement as IMethod;
if (method == null) return false;
if (!method.ShortName.Equals(requiredMethodName)) return false;
var containingType = method.GetContainingType();
if (containingType == null) return false;
if (!containingType.GetClrName().FullName.Equals(requiredTypeName)) return false;
var arguments = invocation.Arguments;
if (arguments.Count == 1)
{
var constantValue = arguments[0].Value.ConstantValue(new UniversalContext(invocation));
if (constantValue.Value?.Equals(propertyName) == true)
return true;
}
return false;
}
private static IDeclaredElement TryFindDeclaration([NotNull]IInvocationExpression expression, [NotNull]string propertyName,
[NotNull]string requiredTypeName, [NotNull]string requiredMethodName, out string name)
{
name = null;
var baseClass = expression.GetContainingNode<IClassLikeDeclaration>();
if (baseClass == null)
{
return null;
}
var result = TryFindIdDeclarationInClassLikeDeclaration(baseClass, propertyName, requiredTypeName, requiredMethodName, out name);
if (result != null)
return result;
var next = ClassLikeDeclarationNavigator.GetByNestedTypeDeclaration(baseClass);
while (next != null)
{
baseClass = next;
result = TryFindIdDeclarationInClassLikeDeclaration(baseClass, propertyName, requiredTypeName, requiredMethodName, out name);
if (result != null)
return result;
next = ClassLikeDeclarationNavigator.GetByNestedTypeDeclaration(baseClass);
}
return null;
}
private static IClassLikeDeclaration GetTopLevelClassLikeDeclaration([NotNull]IInvocationExpression expression)
{
var baseClass = expression.GetContainingNode<IClassLikeDeclaration>();
if (baseClass == null)
return null;
var next = ClassLikeDeclarationNavigator.GetByNestedTypeDeclaration(baseClass);
while (next != null)
{
baseClass = next;
next = ClassLikeDeclarationNavigator.GetByNestedTypeDeclaration(baseClass);
}
return baseClass;
}
// TODO: Show different text
// "Introduce field to cache property index"
// "Use cached property index"
public override string Text => "Use cached property index";
public override bool IsAvailable(IUserDataHolder cache)
{
return myInvocationExpression.IsValid() && myArgument.IsValid();
}
}
}
| |
// 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.trees.RBDictionary
{
internal static class Factory
{
public static IDictionary<K, V> New<K, V>() { return new TreeDictionary<K, V>(); }
}
[TestFixture]
public class Formatting
{
private IDictionary<int, int> coll;
private IFormatProvider rad16;
[SetUp]
public void Init() { coll = Factory.New<int, int>(); rad16 = new RadixFormatProvider(16); }
[TearDown]
public void Dispose() { coll = null; rad16 = null; }
[Test]
public void Format()
{
Assert.AreEqual("[ ]", coll.ToString());
coll.Add(23, 67); coll.Add(45, 89);
Assert.AreEqual("[ [23, 67], [45, 89] ]", coll.ToString());
Assert.AreEqual("[ [17, 43], [2D, 59] ]", coll.ToString(null, rad16));
Assert.AreEqual("[ [23, 67], ... ]", coll.ToString("L14", null));
Assert.AreEqual("[ [17, 43], ... ]", coll.ToString("L14", rad16));
}
}
[TestFixture]
public class RBDict
{
private TreeDictionary<string, string> dict;
[SetUp]
public void Init() { dict = new TreeDictionary<string, string>(new SC()); }
[TearDown]
public void Dispose() { dict = null; }
[Test]
public void NullEqualityComparerinConstructor1()
{
Assert.Throws<NullReferenceException>(() => new TreeDictionary<int, int>(null));
}
[Test]
public void Choose()
{
dict.Add("YES", "NO");
Assert.AreEqual(new System.Collections.Generic.KeyValuePair<string, string>("YES", "NO"), dict.Choose());
}
[Test]
public void BadChoose()
{
Assert.Throws<NoSuchItemException>(() => dict.Choose());
}
[Test]
public void Pred1()
{
dict.Add("A", "1");
dict.Add("C", "2");
dict.Add("E", "3");
Assert.AreEqual("1", dict.Predecessor("B").Value);
Assert.AreEqual("1", dict.Predecessor("C").Value);
Assert.AreEqual("1", dict.WeakPredecessor("B").Value);
Assert.AreEqual("2", dict.WeakPredecessor("C").Value);
Assert.AreEqual("2", dict.Successor("B").Value);
Assert.AreEqual("3", dict.Successor("C").Value);
Assert.AreEqual("2", dict.WeakSuccessor("B").Value);
Assert.AreEqual("2", dict.WeakSuccessor("C").Value);
}
[Test]
public void Pred2()
{
dict.Add("A", "1");
dict.Add("C", "2");
dict.Add("E", "3");
Assert.IsTrue(dict.TryPredecessor("B", out System.Collections.Generic.KeyValuePair<string, string> res));
Assert.AreEqual("1", res.Value);
Assert.IsTrue(dict.TryPredecessor("C", out res));
Assert.AreEqual("1", res.Value);
Assert.IsTrue(dict.TryWeakPredecessor("B", out res));
Assert.AreEqual("1", res.Value);
Assert.IsTrue(dict.TryWeakPredecessor("C", out res));
Assert.AreEqual("2", res.Value);
Assert.IsTrue(dict.TrySuccessor("B", out res));
Assert.AreEqual("2", res.Value);
Assert.IsTrue(dict.TrySuccessor("C", out res));
Assert.AreEqual("3", res.Value);
Assert.IsTrue(dict.TryWeakSuccessor("B", out res));
Assert.AreEqual("2", res.Value);
Assert.IsTrue(dict.TryWeakSuccessor("C", out res));
Assert.AreEqual("2", res.Value);
Assert.IsFalse(dict.TryPredecessor("A", out res));
Assert.AreEqual(null, res.Key);
Assert.AreEqual(null, res.Value);
Assert.IsFalse(dict.TryWeakPredecessor("@", out res));
Assert.AreEqual(null, res.Key);
Assert.AreEqual(null, res.Value);
Assert.IsFalse(dict.TrySuccessor("E", out res));
Assert.AreEqual(null, res.Key);
Assert.AreEqual(null, res.Value);
Assert.IsFalse(dict.TryWeakSuccessor("F", out res));
Assert.AreEqual(null, res.Key);
Assert.AreEqual(null, res.Value);
}
[Test]
public void Initial()
{
bool res;
Assert.IsFalse(dict.IsReadOnly);
Assert.AreEqual(dict.Count, 0, "new dict should be empty");
dict.Add("A", "B");
Assert.AreEqual(dict.Count, 1, "bad count");
Assert.AreEqual(dict["A"], "B", "Wrong value for dict[A]");
dict.Add("C", "D");
Assert.AreEqual(dict.Count, 2, "bad count");
Assert.AreEqual(dict["A"], "B", "Wrong value");
Assert.AreEqual(dict["C"], "D", "Wrong value");
res = dict.Remove("A");
Assert.IsTrue(res, "bad return value from Remove(A)");
Assert.IsTrue(dict.Check());
Assert.AreEqual(dict.Count, 1, "bad count");
Assert.AreEqual(dict["C"], "D", "Wrong value of dict[C]");
res = dict.Remove("Z");
Assert.IsFalse(res, "bad return value from Remove(Z)");
Assert.AreEqual(dict.Count, 1, "bad count");
Assert.AreEqual(dict["C"], "D", "Wrong value of dict[C] (2)");
dict.Clear();
Assert.AreEqual(dict.Count, 0, "dict should be empty");
}
[Test]
public void Contains()
{
dict.Add("C", "D");
Assert.IsTrue(dict.Contains("C"));
Assert.IsFalse(dict.Contains("D"));
}
[Test]
public void IllegalAdd()
{
dict.Add("A", "B");
var exception = Assert.Throws<DuplicateNotAllowedException>(() => dict.Add("A", "B"));
Assert.AreEqual("Key being added: 'A'", exception.Message);
}
[Test]
public void GettingNonExisting()
{
Assert.Throws<NoSuchItemException>(() => Console.WriteLine(dict["R"]));
}
[Test]
public void Setter()
{
dict["R"] = "UYGUY";
Assert.AreEqual(dict["R"], "UYGUY");
dict["R"] = "UIII";
Assert.AreEqual(dict["R"], "UIII");
dict["S"] = "VVV";
Assert.AreEqual(dict["R"], "UIII");
Assert.AreEqual(dict["S"], "VVV");
//dict.dump();
}
}
[TestFixture]
public class GuardedSortedDictionaryTest
{
private GuardedSortedDictionary<string, string> dict;
[SetUp]
public void Init()
{
ISortedDictionary<string, string> dict = new TreeDictionary<string, string>(new SC())
{
{ "A", "1" },
{ "C", "2" },
{ "E", "3" }
};
this.dict = new GuardedSortedDictionary<string, string>(dict);
}
[TearDown]
public void Dispose() { dict = null; }
[Test]
public void Pred1()
{
Assert.AreEqual("1", dict.Predecessor("B").Value);
Assert.AreEqual("1", dict.Predecessor("C").Value);
Assert.AreEqual("1", dict.WeakPredecessor("B").Value);
Assert.AreEqual("2", dict.WeakPredecessor("C").Value);
Assert.AreEqual("2", dict.Successor("B").Value);
Assert.AreEqual("3", dict.Successor("C").Value);
Assert.AreEqual("2", dict.WeakSuccessor("B").Value);
Assert.AreEqual("2", dict.WeakSuccessor("C").Value);
}
[Test]
public void Pred2()
{
Assert.IsTrue(dict.TryPredecessor("B", out System.Collections.Generic.KeyValuePair<string, string> res));
Assert.AreEqual("1", res.Value);
Assert.IsTrue(dict.TryPredecessor("C", out res));
Assert.AreEqual("1", res.Value);
Assert.IsTrue(dict.TryWeakPredecessor("B", out res));
Assert.AreEqual("1", res.Value);
Assert.IsTrue(dict.TryWeakPredecessor("C", out res));
Assert.AreEqual("2", res.Value);
Assert.IsTrue(dict.TrySuccessor("B", out res));
Assert.AreEqual("2", res.Value);
Assert.IsTrue(dict.TrySuccessor("C", out res));
Assert.AreEqual("3", res.Value);
Assert.IsTrue(dict.TryWeakSuccessor("B", out res));
Assert.AreEqual("2", res.Value);
Assert.IsTrue(dict.TryWeakSuccessor("C", out res));
Assert.AreEqual("2", res.Value);
Assert.IsFalse(dict.TryPredecessor("A", out res));
Assert.AreEqual(null, res.Key);
Assert.AreEqual(null, res.Value);
Assert.IsFalse(dict.TryWeakPredecessor("@", out res));
Assert.AreEqual(null, res.Key);
Assert.AreEqual(null, res.Value);
Assert.IsFalse(dict.TrySuccessor("E", out res));
Assert.AreEqual(null, res.Key);
Assert.AreEqual(null, res.Value);
Assert.IsFalse(dict.TryWeakSuccessor("F", out res));
Assert.AreEqual(null, res.Key);
Assert.AreEqual(null, res.Value);
}
[Test]
public void Initial()
{
Assert.IsTrue(dict.IsReadOnly);
Assert.AreEqual(3, dict.Count);
Assert.AreEqual("1", dict["A"]);
}
[Test]
public void Contains()
{
Assert.IsTrue(dict.Contains("A"));
Assert.IsFalse(dict.Contains("1"));
}
[Test]
public void IllegalAdd()
{
Assert.Throws<ReadOnlyCollectionException>(() => dict.Add("Q", "7"));
}
[Test]
public void IllegalClear()
{
Assert.Throws<ReadOnlyCollectionException>(() => dict.Clear());
}
[Test]
public void IllegalSet()
{
Assert.Throws<ReadOnlyCollectionException>(() => dict["A"] = "8");
}
public void IllegalRemove()
{
Assert.Throws<ReadOnlyCollectionException>(() => dict.Remove("A"));
}
[Test]
public void GettingNonExisting()
{
Assert.Throws<NoSuchItemException>(() => Console.WriteLine(dict["R"]));
}
}
[TestFixture]
public class Enumerators
{
private TreeDictionary<string, string> dict;
private SCG.IEnumerator<System.Collections.Generic.KeyValuePair<string, string>> dictenum;
[SetUp]
public void Init()
{
dict = new TreeDictionary<string, string>(new SC())
{
["S"] = "A",
["T"] = "B",
["R"] = "C"
};
dictenum = dict.GetEnumerator();
}
[TearDown]
public void Dispose()
{
dictenum = null;
dict = null;
}
[Test]
public void KeysEnumerator()
{
SCG.IEnumerator<string> keys = dict.Keys.GetEnumerator();
Assert.AreEqual(3, dict.Keys.Count);
Assert.IsTrue(keys.MoveNext());
Assert.AreEqual("R", keys.Current);
Assert.IsTrue(keys.MoveNext());
Assert.AreEqual("S", keys.Current);
Assert.IsTrue(keys.MoveNext());
Assert.AreEqual("T", keys.Current);
Assert.IsFalse(keys.MoveNext());
}
[Test]
public void KeysISorted()
{
ISorted<string> keys = dict.Keys;
Assert.IsTrue(keys.IsReadOnly);
Assert.AreEqual("R", keys.FindMin());
Assert.AreEqual("T", keys.FindMax());
Assert.IsTrue(keys.Contains("S"));
Assert.AreEqual(3, keys.Count);
// This doesn't hold, maybe because the dict uses a special key comparer?
// Assert.IsTrue(keys.SequencedEquals(new WrappedArray<string>(new string[] { "R", "S", "T" })));
Assert.IsTrue(keys.UniqueItems().All(delegate (String s) { return s == "R" || s == "S" || s == "T"; }));
Assert.IsTrue(keys.All(delegate (String s) { return s == "R" || s == "S" || s == "T"; }));
Assert.IsFalse(keys.Exists(delegate (String s) { return s != "R" && s != "S" && s != "T"; }));
Assert.IsTrue(keys.Find(delegate (String s) { return s == "R"; }, out string res));
Assert.AreEqual("R", res);
Assert.IsFalse(keys.Find(delegate (String s) { return s == "Q"; }, out res));
Assert.AreEqual(null, res);
}
[Test]
public void KeysISortedPred()
{
ISorted<string> keys = dict.Keys;
Assert.IsTrue(keys.TryPredecessor("S", out string res));
Assert.AreEqual("R", res);
Assert.IsTrue(keys.TryWeakPredecessor("R", out res));
Assert.AreEqual("R", res);
Assert.IsTrue(keys.TrySuccessor("S", out res));
Assert.AreEqual("T", res);
Assert.IsTrue(keys.TryWeakSuccessor("T", out res));
Assert.AreEqual("T", res);
Assert.IsFalse(keys.TryPredecessor("R", out res));
Assert.AreEqual(null, res);
Assert.IsFalse(keys.TryWeakPredecessor("P", out res));
Assert.AreEqual(null, res);
Assert.IsFalse(keys.TrySuccessor("T", out res));
Assert.AreEqual(null, res);
Assert.IsFalse(keys.TryWeakSuccessor("U", out res));
Assert.AreEqual(null, res);
Assert.AreEqual("R", keys.Predecessor("S"));
Assert.AreEqual("R", keys.WeakPredecessor("R"));
Assert.AreEqual("T", keys.Successor("S"));
Assert.AreEqual("T", keys.WeakSuccessor("T"));
}
[Test]
public void ValuesEnumerator()
{
SCG.IEnumerator<string> values = dict.Values.GetEnumerator();
Assert.AreEqual(3, dict.Values.Count);
Assert.IsTrue(values.MoveNext());
Assert.AreEqual("C", values.Current);
Assert.IsTrue(values.MoveNext());
Assert.AreEqual("A", values.Current);
Assert.IsTrue(values.MoveNext());
Assert.AreEqual("B", values.Current);
Assert.IsFalse(values.MoveNext());
}
[Test]
public void Fun()
{
Assert.AreEqual("B", dict.Func("T"));
}
[Test]
public void NormalUse()
{
Assert.IsTrue(dictenum.MoveNext());
Assert.AreEqual(dictenum.Current, new System.Collections.Generic.KeyValuePair<string, string>("R", "C"));
Assert.IsTrue(dictenum.MoveNext());
Assert.AreEqual(dictenum.Current, new System.Collections.Generic.KeyValuePair<string, string>("S", "A"));
Assert.IsTrue(dictenum.MoveNext());
Assert.AreEqual(dictenum.Current, new System.Collections.Generic.KeyValuePair<string, string>("T", "B"));
Assert.IsFalse(dictenum.MoveNext());
}
}
namespace PathCopyPersistence
{
[TestFixture]
public class Simple
{
private TreeDictionary<string, string> dict;
private TreeDictionary<string, string> snap;
[SetUp]
public void Init()
{
dict = new TreeDictionary<string, string>(new SC())
{
["S"] = "A",
["T"] = "B",
["R"] = "C",
["V"] = "G"
};
snap = (TreeDictionary<string, string>)dict.Snapshot();
}
[Test]
public void Test()
{
dict["SS"] = "D";
Assert.AreEqual(5, dict.Count);
Assert.AreEqual(4, snap.Count);
dict["T"] = "bb";
Assert.AreEqual(5, dict.Count);
Assert.AreEqual(4, snap.Count);
Assert.AreEqual("B", snap["T"]);
Assert.AreEqual("bb", dict["T"]);
Assert.IsFalse(dict.IsReadOnly);
Assert.IsTrue(snap.IsReadOnly);
//Finally, update of root node:
_ = (TreeDictionary<string, string>)dict.Snapshot();
dict["S"] = "abe";
Assert.AreEqual("abe", dict["S"]);
}
[Test]
public void UpdateSnap()
{
Assert.Throws<ReadOnlyCollectionException>(() => snap["Y"] = "J");
}
[TearDown]
public void Dispose()
{
dict = null;
snap = null;
}
}
}
}
| |
/**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
using System;
using System.Runtime.InteropServices;
namespace Facebook.Yoga
{
internal static class Native
{
#if (UNITY_IOS && !UNITY_EDITOR) || __IOS__
private const string DllName = "__Internal";
#else
private const string DllName = "yoga";
#endif
internal class YGNodeHandle : SafeHandle
{
private YGNodeHandle() : base(IntPtr.Zero, true)
{
}
public override bool IsInvalid
{
get
{
return this.handle == IntPtr.Zero;
}
}
protected override bool ReleaseHandle()
{
Native.YGNodeFree(this.handle);
GC.KeepAlive(this);
return true;
}
}
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGInteropSetLogger(
[MarshalAs(UnmanagedType.FunctionPtr)] YogaLogger.Func func);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YGNodeHandle YGNodeNew();
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeFree(IntPtr node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeReset(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern int YGNodeGetInstanceCount();
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGSetExperimentalFeatureEnabled(
YogaExperimentalFeature feature,
bool enabled);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern bool YGIsExperimentalFeatureEnabled(
YogaExperimentalFeature feature);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeInsertChild(YGNodeHandle node, YGNodeHandle child, uint index);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeRemoveChild(YGNodeHandle node, YGNodeHandle child);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeCalculateLayout(YGNodeHandle node,
float availableWidth,
float availableHeight,
YogaDirection parentDirection);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeMarkDirty(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool YGNodeIsDirty(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodePrint(YGNodeHandle node, YogaPrintOptions options);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeCopyStyle(YGNodeHandle dstNode, YGNodeHandle srcNode);
#region YG_NODE_PROPERTY
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeSetMeasureFunc(
YGNodeHandle node,
[MarshalAs(UnmanagedType.FunctionPtr)] YogaMeasureFunc measureFunc);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeSetBaselineFunc(
YGNodeHandle node,
[MarshalAs(UnmanagedType.FunctionPtr)] YogaBaselineFunc baselineFunc);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeSetHasNewLayout(YGNodeHandle node, [MarshalAs(UnmanagedType.I1)] bool hasNewLayout);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)]
public static extern bool YGNodeGetHasNewLayout(YGNodeHandle node);
#endregion
#region YG_NODE_STYLE_PROPERTY
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetDirection(YGNodeHandle node, YogaDirection direction);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaDirection YGNodeStyleGetDirection(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexDirection(YGNodeHandle node, YogaFlexDirection flexDirection);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaFlexDirection YGNodeStyleGetFlexDirection(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetJustifyContent(YGNodeHandle node, YogaJustify justifyContent);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaJustify YGNodeStyleGetJustifyContent(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetAlignContent(YGNodeHandle node, YogaAlign alignContent);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaAlign YGNodeStyleGetAlignContent(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetAlignItems(YGNodeHandle node, YogaAlign alignItems);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaAlign YGNodeStyleGetAlignItems(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetAlignSelf(YGNodeHandle node, YogaAlign alignSelf);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaAlign YGNodeStyleGetAlignSelf(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPositionType(YGNodeHandle node, YogaPositionType positionType);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaPositionType YGNodeStyleGetPositionType(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexWrap(YGNodeHandle node, YogaWrap flexWrap);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaWrap YGNodeStyleGetFlexWrap(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetOverflow(YGNodeHandle node, YogaOverflow flexWrap);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaOverflow YGNodeStyleGetOverflow(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetDisplay(YGNodeHandle node, YogaDisplay display);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaDisplay YGNodeStyleGetDisplay(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlex(YGNodeHandle node, float flex);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexGrow(YGNodeHandle node, float flexGrow);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeStyleGetFlexGrow(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexShrink(YGNodeHandle node, float flexShrink);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeStyleGetFlexShrink(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexBasis(YGNodeHandle node, float flexBasis);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexBasisPercent(YGNodeHandle node, float flexBasis);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetFlexBasisAuto(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetFlexBasis(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetWidth(YGNodeHandle node, float width);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetWidthPercent(YGNodeHandle node, float width);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetWidthAuto(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetWidth(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetHeight(YGNodeHandle node, float height);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetHeightPercent(YGNodeHandle node, float height);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetHeightAuto(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetHeight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMinWidth(YGNodeHandle node, float minWidth);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMinWidthPercent(YGNodeHandle node, float minWidth);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMinWidth(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMinHeight(YGNodeHandle node, float minHeight);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMinHeightPercent(YGNodeHandle node, float minHeight);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMinHeight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMaxWidth(YGNodeHandle node, float maxWidth);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMaxWidthPercent(YGNodeHandle node, float maxWidth);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMaxWidth(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMaxHeight(YGNodeHandle node, float maxHeight);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMaxHeightPercent(YGNodeHandle node, float maxHeight);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMaxHeight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetAspectRatio(YGNodeHandle node, float aspectRatio);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeStyleGetAspectRatio(YGNodeHandle node);
#endregion
#region YG_NODE_STYLE_EDGE_PROPERTY
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPosition(YGNodeHandle node, YogaEdge edge, float position);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPositionPercent(YGNodeHandle node, YogaEdge edge, float position);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetPosition(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMargin(YGNodeHandle node, YogaEdge edge, float margin);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMarginPercent(YGNodeHandle node, YogaEdge edge, float margin);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetMarginAuto(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetMargin(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPadding(YGNodeHandle node, YogaEdge edge, float padding);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetPaddingPercent(YGNodeHandle node, YogaEdge edge, float padding);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaValue YGNodeStyleGetPadding(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern void YGNodeStyleSetBorder(YGNodeHandle node, YogaEdge edge, float border);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeStyleGetBorder(YGNodeHandle node, YogaEdge edge);
#endregion
#region YG_NODE_LAYOUT_PROPERTY
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetLeft(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetTop(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetRight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetBottom(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetWidth(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetHeight(YGNodeHandle node);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetMargin(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern float YGNodeLayoutGetPadding(YGNodeHandle node, YogaEdge edge);
[DllImport(DllName, ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)]
public static extern YogaDirection YGNodeLayoutGetDirection(YGNodeHandle node);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Collections;
using System.Xml.Schema;
namespace System.Xml.Tests
{
//[TestCase(Name = "TC_SchemaSet_Remove", Desc = "")]
public class TC_SchemaSet_Remove : TC_SchemaSetBase
{
private ITestOutputHelper _output;
public TC_SchemaSet_Remove(ITestOutputHelper output)
{
_output = output;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v1 - Remove with null", Priority = 0)]
[InlineData()]
[Theory]
public void v1()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.Remove(null);
}
catch (ArgumentNullException)
{
// GLOBALIZATION
return;
}
Assert.True(false);
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v2 - Remove with just added schema", Priority = 0)]
[InlineData()]
[Theory]
public void v2()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
sc.Compile();
sc.Remove(Schema1);
CError.Compare(sc.Count, 0, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 0, "ICollection.Count");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v3 - Remove first added schema, check the rest", Priority = 0)]
[InlineData()]
[Theory]
public void v3()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add("test", TestData._XsdNoNs);
sc.Compile();
sc.Remove(Schema1);
CError.Compare(sc.Count, 1, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 1, "ICollection.Count");
CError.Compare(sc.Contains("test"), true, "Contains");
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v4.6 - Remove A(ns-a) include B(ns-a) which includes C(ns-a) ", Priority = 1, Params = new object[] { "include_v7_a.xsd" })]
[InlineData("include_v7_a.xsd")]
//[Variation(Desc = "v4.5 - Remove: A with NS includes B and C with no NS", Priority = 1, Params = new object[] { "include_v6_a.xsd" })]
[InlineData("include_v6_a.xsd")]
//[Variation(Desc = "v4.4 - Remove: A with NS includes B and C with no NS, B also includes C", Priority = 1, Params = new object[] { "include_v5_a.xsd" })]
[InlineData("include_v5_a.xsd")]
//[Variation(Desc = "v4.3 - Remove: A with NS includes B with no NS, which includes C with no NS", Priority = 1, Params = new object[] { "include_v4_a.xsd" })]
[InlineData("include_v4_a.xsd")]
//[Variation(Desc = "v4.2 - Remove: A with no NS includes B with no NS", Params = new object[] { "include_v3_a.xsd" })]
[InlineData("include_v3_a.xsd")]
//[Variation(Desc = "v4.1 - Remove: A with NS includes B with no NS", Params = new object[] { "include_v1_a.xsd", })]
[InlineData("include_v1_a.xsd")]
[Theory]
public void v4(object param0)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename
sc.Compile();
sc.Remove(Schema2);
CError.Compare(sc.Count, 1, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 1, "ICollection.Count");
}
catch (Exception)
{
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v5.3 - Remove: A(ns-a) which imports B (no ns)", Priority = 1, Params = new object[] { "import_v4_a.xsd", 2 })]
[InlineData("import_v4_a.xsd", 2)]
//[Variation(Desc = "v5.2 - Remove: A(ns-a) improts B (ns-b)", Priority = 1, Params = new object[] { "import_v2_a.xsd", 2 })]
[InlineData("import_v2_a.xsd", 2)]
//[Variation(Desc = "v5.1 - Remove: A with NS imports B with no NS", Priority = 1, Params = new object[] { "import_v1_a.xsd", 2 })]
[InlineData("import_v1_a.xsd", 2)]
[Theory]
public void v5(object param0, object param1)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, TestData._XsdAuthor);
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename
sc.Compile();
sc.Remove(Schema2);
CError.Compare(sc.Count, param1, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, param1, "ICollection.Count");
}
catch (Exception)
{
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v6 - Remove: Add B(NONS) to a namespace, Add A(ns-a) which imports B, Remove B(nons)", Priority = 1)]
[InlineData()]
[Theory]
public void v6()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add("ns-b", Path.Combine(TestData._Root, "import_v4_b.xsd"));
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, "import_v5_a.xsd")); // param as filename
sc.Compile();
sc.Remove(Schema1);
CError.Compare(sc.Count, 2, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 2, "ICollection.Count");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains(String.Empty), true, "Contains");
CError.Compare(sc.Contains("ns-a"), true, "Contains");
}
catch (Exception)
{
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v7 - Remove: Add B(NONS) to a namespace, Add A(ns-a) which improts B, Remove B(ns-b)", Priority = 1)]
[InlineData()]
[Theory]
public void v7()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add("ns-b", Path.Combine(TestData._Root, "import_v4_b.xsd"));
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, "import_v5_a.xsd")); // param as filename
sc.Compile();
ICollection col = sc.Schemas(String.Empty);
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 2, "Count");
ICollection Col = sc.Schemas();
CError.Compare(Col.Count, 2, "ICollection.Count");
CError.Compare(sc.Contains("ns-b"), true, "Contains");
CError.Compare(sc.Contains(String.Empty), false, "Contains");
CError.Compare(sc.Contains("ns-a"), true, "Contains");
}
catch (Exception)
{
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v8.2 - Remove: A(ns-a) imports B(NO NS) imports C (ns-c)", Priority = 1, Params = new object[] { "import_v10_a.xsd", "ns-a", "", "ns-c" })]
[InlineData("import_v10_a.xsd", "ns-a", "", "ns-c")]
//[Variation(Desc = "v8.1 - Remove: A(ns-a) imports B(ns-b) imports C (ns-c)", Priority = 1, Params = new object[] { "import_v9_a.xsd", "ns-a", "ns-b", "ns-c" })]
[InlineData("import_v9_a.xsd", "ns-a", "ns-b", "ns-c")]
[Theory]
public void v8(object param0, object param1, object param2, object param3)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString()));
sc.Compile();
CError.Compare(sc.Count, 3, "Count");
ICollection col = sc.Schemas(param2.ToString());
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 2, "Count");
CError.Compare(sc.Contains(param2.ToString()), false, "Contains");
col = sc.Schemas(param3.ToString());
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains(param3.ToString()), false, "Contains");
CError.Compare(sc.Contains(param1.ToString()), true, "Contains");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v9 - Remove: A imports B and B and C, B imports C and D, C imports D and A", Priority = 1, Params = new object[] { "import_v13_a.xsd" })]
[InlineData("import_v13_a.xsd")]
[Theory]
public void v9(object param0)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString()));
sc.Compile();
CError.Compare(sc.Count, 4, "Count");
ICollection col = sc.Schemas("ns-d");
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 3, "Count");
CError.Compare(sc.Contains("ns-d"), false, "Contains");
col = sc.Schemas("ns-c");
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 2, "Count");
CError.Compare(sc.Contains("ns-c"), false, "Contains");
col = sc.Schemas("ns-b");
foreach (XmlSchema schema in col)
{
sc.Remove(schema); //should remove just one
}
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains("ns-b"), false, "Contains");
CError.Compare(sc.Contains("ns-a"), true, "Contains");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//-----------------------------------------------------------------------------------
//[Variation(Desc = "v10 - Import: B(ns-b) added, A(ns-a) imports B's NS", Priority = 2)]
[InlineData()]
[Theory]
public void v10()
{
try
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
sc.Add(null, Path.Combine(TestData._Root, "import_v16_b.xsd"));
XmlSchema parent = sc.Add(null, Path.Combine(TestData._Root, "import_v16_a.xsd"));
sc.Compile();
sc.Remove(parent);
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.Contains("ns-b"), true, "Contains");
return;
}
catch (XmlSchemaException e)
{
_output.WriteLine("Exception : " + e.Message);
}
Assert.True(false);
}
//[Variation(Desc = "v11.2 - Remove: A(ns-a) improts B (ns-b), Remove imported schema", Priority = 2, Params = new object[] { "import_v2_a.xsd", "import_v2_b.xsd" })]
[InlineData("import_v2_a.xsd", "import_v2_b.xsd")]
//[Variation(Desc = "v11.1 - Remove: A with NS imports B with no NS, Remove imported schema", Priority = 2, Params = new object[] { "import_v1_a.xsd", "include_v1_b.xsd" })]
[InlineData("import_v1_a.xsd", "include_v1_b.xsd")]
[Theory]
public void v11(object param0, object param1)
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
try
{
XmlSchema Schema1 = sc.Add(null, Path.Combine(TestData._Root, param0.ToString())); // param as filename
XmlSchema Schema2 = sc.Add(null, Path.Combine(TestData._Root, param1.ToString())); // param as filename
sc.Compile();
CError.Compare(sc.Count, 2, "Count");
sc.Remove(Schema2);
sc.Compile();
CError.Compare(sc.Count, 1, "Count");
CError.Compare(sc.GlobalElements.Count, 2, "GlobalElems Count");
}
catch (Exception e)
{
_output.WriteLine(e.ToString());
Assert.True(false);
}
return;
}
//[Variation(Desc = "v20 - 358206 : Removing the last schema from the set should clear the global tables", Priority = 2)]
[InlineData()]
[Theory]
public void v20()
{
XmlSchemaSet sc = new XmlSchemaSet();
sc.XmlResolver = new XmlUrlResolver();
XmlSchema Schema = sc.Add(null, TestData._XsdAuthor); // param as filename
sc.Compile();
CError.Compare(sc.Count, 1, "Count before remove");
sc.Remove(Schema);
sc.Compile();
CError.Compare(sc.Count, 0, "Count after remove");
CError.Compare(sc.GlobalElements.Count, 0, "GlobalElems Count");
return;
}
}
}
| |
// 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 program uses code hyperlinks available as part of the HyperAddin Visual Studio plug-in.
// It is available from http://www.codeplex.com/hyperAddin
#if PLATFORM_WINDOWS
#define FEATURE_MANAGED_ETW
#if !ES_BUILD_STANDALONE
#define FEATURE_ACTIVITYSAMPLING
#endif
#endif // PLATFORM_WINDOWS
#if ES_BUILD_STANDALONE
#define FEATURE_MANAGED_ETW_CHANNELS
// #define FEATURE_ADVANCED_MANAGED_ETW_CHANNELS
#endif
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor;
#endif
using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Collections.ObjectModel;
#if !ES_BUILD_AGAINST_DOTNET_V35
using System.Collections.Generic;
using System.Text;
#else
using System.Collections.Generic;
using System.Text;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
public partial class EventSource
{
#if FEATURE_MANAGED_ETW
private byte[] providerMetadata;
#endif
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
public EventSource(
string eventSourceName)
: this(eventSourceName, EventSourceSettings.EtwSelfDescribingEventFormat)
{ }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
public EventSource(
string eventSourceName,
EventSourceSettings config)
: this(eventSourceName, config, null) { }
/// <summary>
/// Construct an EventSource with a given name for non-contract based events (e.g. those using the Write() API).
///
/// Also specify a list of key-value pairs called traits (you must pass an even number of strings).
/// The first string is the key and the second is the value. These are not interpreted by EventSource
/// itself but may be interpreted the listeners. Can be fetched with GetTrait(string).
/// </summary>
/// <param name="eventSourceName">
/// The name of the event source. Must not be null.
/// </param>
/// <param name="config">
/// Configuration options for the EventSource as a whole.
/// </param>
/// <param name="traits">A collection of key-value strings (must be an even number).</param>
public EventSource(
string eventSourceName,
EventSourceSettings config,
params string[] traits)
: this(
eventSourceName == null ? new Guid() : GenerateGuidFromName(eventSourceName.ToUpperInvariant()),
eventSourceName,
config, traits)
{
if (eventSourceName == null)
{
throw new ArgumentNullException(nameof(eventSourceName));
}
}
/// <summary>
/// Writes an event with no fields and default options.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
public unsafe void Write(string eventName)
{
if (eventName == null)
{
throw new ArgumentNullException(nameof(eventName));
}
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
}
/// <summary>
/// Writes an event with no fields.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <param name="eventName">The name of the event. Must not be null.</param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
public unsafe void Write(string eventName, EventSourceOptions options)
{
if (eventName == null)
{
throw new ArgumentNullException(nameof(eventName));
}
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, null, null, null, SimpleEventTypes<EmptyStruct>.Instance);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
public unsafe void Write<T>(
string eventName,
T data)
{
if (!this.IsEnabled())
{
return;
}
var options = new EventSourceOptions();
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
public unsafe void Write<T>(
string eventName,
EventSourceOptions options,
T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// This overload is for use with extension methods that wish to efficiently
/// forward the options or data parameter without performing an extra copy.
/// (Native API: EventWriteTransfer)
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
this.WriteImpl(eventName, ref options, data, null, null, SimpleEventTypes<T>.Instance);
}
/// <summary>
/// Writes an event.
/// This overload is meant for clients that need to manipuate the activityId
/// and related ActivityId for the event.
/// </summary>
/// <typeparam name="T">
/// The type that defines the event and its payload. This must be an
/// anonymous type or a type with an [EventData] attribute.
/// </typeparam>
/// <param name="eventName">
/// The name for the event. If null, the event name is automatically
/// determined based on T, either from the Name property of T's EventData
/// attribute or from typeof(T).Name.
/// </param>
/// <param name="options">
/// Options for the event, such as the level, keywords, and opcode. Unset
/// options will be set to default values.
/// </param>
/// <param name="activityId">
/// The GUID of the activity associated with this event.
/// </param>
/// <param name="relatedActivityId">
/// The GUID of another activity that is related to this activity, or Guid.Empty
/// if there is no related activity. Most commonly, the Start operation of a
/// new activity specifies a parent activity as its related activity.
/// </param>
/// <param name="data">
/// The object containing the event payload data. The type T must be
/// an anonymous type or a type with an [EventData] attribute. The
/// public instance properties of data will be written recursively to
/// create the fields of the event.
/// </param>
public unsafe void Write<T>(
string eventName,
ref EventSourceOptions options,
ref Guid activityId,
ref Guid relatedActivityId,
ref T data)
{
if (!this.IsEnabled())
{
return;
}
fixed (Guid* pActivity = &activityId, pRelated = &relatedActivityId)
{
this.WriteImpl(
eventName,
ref options,
data,
pActivity,
relatedActivityId == Guid.Empty ? null : pRelated,
SimpleEventTypes<T>.Instance);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// This method does a quick check on whether this event is enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null) </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
private unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
if (!this.IsEnabled())
{
return;
}
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
WriteMultiMergeInner(eventName, ref options, eventTypes, activityID, childActivityID, values);
}
}
/// <summary>
/// Writes an extended event, where the values of the event are the
/// combined properties of any number of values. This method is
/// intended for use in advanced logging scenarios that support a
/// dynamic set of event context providers.
/// Attention: This API does not check whether the event is enabled or not.
/// Please use WriteMultiMerge to avoid spending CPU cycles for events that are
/// not enabled.
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="values">
/// The values to include in the event. Must not be null. The number and types of
/// the values must match the number and types of the fields described by the
/// eventTypes parameter.
/// </param>
private unsafe void WriteMultiMergeInner(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
params object[] values)
{
#if FEATURE_MANAGED_ETW
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventTypes.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventTypes.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventTypes.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventTypes.keywords;
var nameInfo = eventTypes.GetNameInfo(eventName ?? eventTypes.Name, tags);
if (nameInfo == null)
{
return;
}
identity = nameInfo.identity;
EventDescriptor descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
for (int i = 0; i < pinCount; i++)
pins[i] = default(GCHandle);
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#if (!ES_BUILD_PCL && !ES_BUILD_PN)
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
try
{
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
var info = eventTypes.typeInfos[i];
info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(values[i]));
}
this.WriteEventRaw(
eventName,
ref descriptor,
activityID,
childActivityID,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
}
finally
{
this.WriteCleanup(pins, pinCount);
}
}
#endif // FEATURE_MANAGED_ETW
}
/// <summary>
/// Writes an extended event, where the values of the event have already
/// been serialized in "data".
/// </summary>
/// <param name="eventName">
/// The name for the event. If null, the name from eventTypes is used.
/// (Note that providing the event name via the name parameter is slightly
/// less efficient than using the name from eventTypes.)
/// </param>
/// <param name="options">
/// Optional overrides for the event, such as the level, keyword, opcode,
/// activityId, and relatedActivityId. Any settings not specified by options
/// are obtained from eventTypes.
/// </param>
/// <param name="eventTypes">
/// Information about the event and the types of the values in the event.
/// Must not be null. Note that the eventTypes object should be created once and
/// saved. It should not be recreated for each event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// A pointer to the child activity ID to log (can be null)
/// </param>
/// <param name="data">
/// The previously serialized values to include in the event. Must not be null.
/// The number and types of the values must match the number and types of the
/// fields described by the eventTypes parameter.
/// </param>
internal unsafe void WriteMultiMerge(
string eventName,
ref EventSourceOptions options,
TraceLoggingEventTypes eventTypes,
Guid* activityID,
Guid* childActivityID,
EventData* data)
{
#if FEATURE_MANAGED_ETW
if (!this.IsEnabled())
{
return;
}
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
// We make a descriptor for each EventData, and because we morph strings to counted strings
// we may have 2 for each arg, so we allocate enough for this.
var descriptors = stackalloc EventData[eventTypes.dataCount + eventTypes.typeInfos.Length * 2 + 3];
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
int numDescrs = 3;
for (int i = 0; i < eventTypes.typeInfos.Length; i++)
{
// Until M3, we need to morph strings to a counted representation
// When TDH supports null terminated strings, we can remove this.
if (eventTypes.typeInfos[i].DataType == typeof(string))
{
// Write out the size of the string
descriptors[numDescrs].DataPointer = (IntPtr) (&descriptors[numDescrs + 1].m_Size);
descriptors[numDescrs].m_Size = 2;
numDescrs++;
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size - 2; // Remove the null terminator
numDescrs++;
}
else
{
descriptors[numDescrs].m_Ptr = data[i].m_Ptr;
descriptors[numDescrs].m_Size = data[i].m_Size;
// old conventions for bool is 4 bytes, but meta-data assumes 1.
if (data[i].m_Size == 4 && eventTypes.typeInfos[i].DataType == typeof(bool))
descriptors[numDescrs].m_Size = 1;
numDescrs++;
}
}
this.WriteEventRaw(
eventName,
ref descriptor,
activityID,
childActivityID,
numDescrs,
(IntPtr)descriptors);
}
}
#endif // FEATURE_MANAGED_ETW
}
private unsafe void WriteImpl(
string eventName,
ref EventSourceOptions options,
object data,
Guid* pActivityId,
Guid* pRelatedActivityId,
TraceLoggingEventTypes eventTypes)
{
try
{
fixed (EventSourceOptions* pOptions = &options)
{
EventDescriptor descriptor;
options.Opcode = options.IsOpcodeSet ? options.Opcode : GetOpcodeWithDefault(options.Opcode, eventName);
var nameInfo = this.UpdateDescriptor(eventName, eventTypes, ref options, out descriptor);
if (nameInfo == null)
{
return;
}
#if FEATURE_MANAGED_ETW
var pinCount = eventTypes.pinCount;
var scratch = stackalloc byte[eventTypes.scratchSize];
var descriptors = stackalloc EventData[eventTypes.dataCount + 3];
var pins = stackalloc GCHandle[pinCount];
for (int i = 0; i < pinCount; i++)
pins[i] = default(GCHandle);
fixed (byte*
pMetadata0 = this.providerMetadata,
pMetadata1 = nameInfo.nameMetadata,
pMetadata2 = eventTypes.typeMetadata)
{
descriptors[0].SetMetadata(pMetadata0, this.providerMetadata.Length, 2);
descriptors[1].SetMetadata(pMetadata1, nameInfo.nameMetadata.Length, 1);
descriptors[2].SetMetadata(pMetadata2, eventTypes.typeMetadata.Length, 1);
#endif // FEATURE_MANAGED_ETW
#if (!ES_BUILD_PCL && !ES_BUILD_PN)
System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions();
#endif
EventOpcode opcode = (EventOpcode)descriptor.Opcode;
Guid activityId = Guid.Empty;
Guid relatedActivityId = Guid.Empty;
if (pActivityId == null && pRelatedActivityId == null &&
((options.ActivityOptions & EventActivityOptions.Disable) == 0))
{
if (opcode == EventOpcode.Start)
{
m_activityTracker.OnStart(m_name, eventName, 0, ref activityId, ref relatedActivityId, options.ActivityOptions);
}
else if (opcode == EventOpcode.Stop)
{
m_activityTracker.OnStop(m_name, eventName, 0, ref activityId);
}
if (activityId != Guid.Empty)
pActivityId = &activityId;
if (relatedActivityId != Guid.Empty)
pRelatedActivityId = &relatedActivityId;
}
try
{
#if FEATURE_MANAGED_ETW
DataCollector.ThreadInstance.Enable(
scratch,
eventTypes.scratchSize,
descriptors + 3,
eventTypes.dataCount,
pins,
pinCount);
var info = eventTypes.typeInfos[0];
info.WriteData(TraceLoggingDataCollector.Instance, info.PropertyValueFactory(data));
this.WriteEventRaw(
eventName,
ref descriptor,
pActivityId,
pRelatedActivityId,
(int)(DataCollector.ThreadInstance.Finish() - descriptors),
(IntPtr)descriptors);
#endif // FEATURE_MANAGED_ETW
// TODO enable filtering for listeners.
if (m_Dispatchers != null)
{
var eventData = (EventPayload)(eventTypes.typeInfos[0].GetData(data));
WriteToAllListeners(eventName, ref descriptor, nameInfo.tags, pActivityId, eventData);
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(eventName, ex);
}
#if FEATURE_MANAGED_ETW
finally
{
this.WriteCleanup(pins, pinCount);
}
}
#endif // FEATURE_MANAGED_ETW
}
}
catch (Exception ex)
{
if (ex is EventSourceException)
throw;
else
ThrowEventSourceException(eventName, ex);
}
}
private unsafe void WriteToAllListeners(string eventName, ref EventDescriptor eventDescriptor, EventTags tags, Guid* pActivityId, EventPayload payload)
{
EventWrittenEventArgs eventCallbackArgs = new EventWrittenEventArgs(this);
eventCallbackArgs.EventName = eventName;
eventCallbackArgs.m_level = (EventLevel) eventDescriptor.Level;
eventCallbackArgs.m_keywords = (EventKeywords) eventDescriptor.Keywords;
eventCallbackArgs.m_opcode = (EventOpcode) eventDescriptor.Opcode;
eventCallbackArgs.m_tags = tags;
// Self described events do not have an id attached. We mark it internally with -1.
eventCallbackArgs.EventId = -1;
if (pActivityId != null)
eventCallbackArgs.RelatedActivityId = *pActivityId;
if (payload != null)
{
eventCallbackArgs.Payload = new ReadOnlyCollection<object>((IList<object>)payload.Values);
eventCallbackArgs.PayloadNames = new ReadOnlyCollection<string>((IList<string>)payload.Keys);
}
DispatchToAllListeners(-1, pActivityId, eventCallbackArgs);
}
#if (!ES_BUILD_PCL && !ES_BUILD_PN)
[System.Runtime.ConstrainedExecution.ReliabilityContract(
System.Runtime.ConstrainedExecution.Consistency.WillNotCorruptState,
System.Runtime.ConstrainedExecution.Cer.Success)]
#endif
[NonEvent]
private unsafe void WriteCleanup(GCHandle* pPins, int cPins)
{
DataCollector.ThreadInstance.Disable();
for (int i = 0; i < cPins; i++)
{
if (pPins[i].IsAllocated)
{
pPins[i].Free();
}
}
}
private void InitializeProviderMetadata()
{
#if FEATURE_MANAGED_ETW
if (m_traits != null)
{
List<byte> traitMetaData = new List<byte>(100);
for (int i = 0; i < m_traits.Length - 1; i += 2)
{
if (m_traits[i].StartsWith("ETW_", StringComparison.Ordinal))
{
string etwTrait = m_traits[i].Substring(4);
byte traitNum;
if (!byte.TryParse(etwTrait, out traitNum))
{
if (etwTrait == "GROUP")
{
traitNum = 1;
}
else
{
throw new ArgumentException(Resources.GetResourceString("UnknownEtwTrait", etwTrait), "traits");
}
}
string value = m_traits[i + 1];
int lenPos = traitMetaData.Count;
traitMetaData.Add(0); // Emit size (to be filled in later)
traitMetaData.Add(0);
traitMetaData.Add(traitNum); // Emit Trait number
var valueLen = AddValueToMetaData(traitMetaData, value) + 3; // Emit the value bytes +3 accounts for 3 bytes we emited above.
traitMetaData[lenPos] = unchecked((byte)valueLen); // Fill in size
traitMetaData[lenPos + 1] = unchecked((byte)(valueLen >> 8));
}
}
providerMetadata = Statics.MetadataForString(this.Name, 0, traitMetaData.Count, 0);
int startPos = providerMetadata.Length - traitMetaData.Count;
foreach (var b in traitMetaData)
providerMetadata[startPos++] = b;
}
else
providerMetadata = Statics.MetadataForString(this.Name, 0, 0, 0);
#endif //FEATURE_MANAGED_ETW
}
private static int AddValueToMetaData(List<byte> metaData, string value)
{
if (value.Length == 0)
return 0;
int startPos = metaData.Count;
char firstChar = value[0];
if (firstChar == '@')
metaData.AddRange(Encoding.UTF8.GetBytes(value.Substring(1)));
else if (firstChar == '{')
metaData.AddRange(new Guid(value).ToByteArray());
else if (firstChar == '#')
{
for (int i = 1; i < value.Length; i++)
{
if (value[i] != ' ') // Skip spaces between bytes.
{
if (!(i + 1 < value.Length))
{
throw new ArgumentException(Resources.GetResourceString("EvenHexDigits"), "traits");
}
metaData.Add((byte)(HexDigit(value[i]) * 16 + HexDigit(value[i + 1])));
i++;
}
}
}
else if ('A' <= firstChar || ' ' == firstChar) // Is it alphabetic or space (excludes digits and most punctuation).
{
metaData.AddRange(Encoding.UTF8.GetBytes(value));
}
else
{
throw new ArgumentException(Resources.GetResourceString("IllegalValue", value), "traits");
}
return metaData.Count - startPos;
}
/// <summary>
/// Returns a value 0-15 if 'c' is a hexadecimal digit. If it throws an argument exception.
/// </summary>
private static int HexDigit(char c)
{
if ('0' <= c && c <= '9')
{
return (c - '0');
}
if ('a' <= c)
{
c = unchecked((char)(c - ('a' - 'A'))); // Convert to lower case
}
if ('A' <= c && c <= 'F')
{
return (c - 'A' + 10);
}
throw new ArgumentException(Resources.GetResourceString("BadHexDigit", c), "traits");
}
private NameInfo UpdateDescriptor(
string name,
TraceLoggingEventTypes eventInfo,
ref EventSourceOptions options,
out EventDescriptor descriptor)
{
NameInfo nameInfo = null;
int identity = 0;
byte level = (options.valuesSet & EventSourceOptions.levelSet) != 0
? options.level
: eventInfo.level;
byte opcode = (options.valuesSet & EventSourceOptions.opcodeSet) != 0
? options.opcode
: eventInfo.opcode;
EventTags tags = (options.valuesSet & EventSourceOptions.tagsSet) != 0
? options.tags
: eventInfo.Tags;
EventKeywords keywords = (options.valuesSet & EventSourceOptions.keywordsSet) != 0
? options.keywords
: eventInfo.keywords;
if (this.IsEnabled((EventLevel)level, keywords))
{
nameInfo = eventInfo.GetNameInfo(name ?? eventInfo.Name, tags);
identity = nameInfo.identity;
}
descriptor = new EventDescriptor(identity, level, opcode, (long)keywords);
return nameInfo;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Net.Http;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Authorization;
namespace Microsoft.Azure.Management.Authorization
{
public partial class AuthorizationManagementClient : ServiceClient<AuthorizationManagementClient>, IAuthorizationManagementClient
{
private string _apiVersion;
public const string APIVersion = "2015-07-01";
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IClassicAdministratorOperations _classicAdministrators;
/// <summary>
/// Get classic administrator details (see http://TBD for more
/// information)
/// </summary>
public virtual IClassicAdministratorOperations ClassicAdministrators
{
get { return this._classicAdministrators; }
}
private IPermissionOperations _permissions;
/// <summary>
/// Get resource or resource group permissions (see http://TBD for
/// more information)
/// </summary>
public virtual IPermissionOperations Permissions
{
get { return this._permissions; }
}
private IRoleAssignmentOperations _roleAssignments;
/// <summary>
/// TBD (see http://TBD for more information)
/// </summary>
public virtual IRoleAssignmentOperations RoleAssignments
{
get { return this._roleAssignments; }
}
private IRoleDefinitionOperations _roleDefinitions;
/// <summary>
/// TBD (see http://TBD for more information)
/// </summary>
public virtual IRoleDefinitionOperations RoleDefinitions
{
get { return this._roleDefinitions; }
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
public AuthorizationManagementClient()
: base()
{
this._classicAdministrators = new ClassicAdministratorOperations(this);
this._permissions = new PermissionOperations(this);
this._roleAssignments = new RoleAssignmentOperations(this);
this._roleDefinitions = new RoleDefinitionOperations(this);
this._apiVersion = APIVersion;
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public AuthorizationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public AuthorizationManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AuthorizationManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._classicAdministrators = new ClassicAdministratorOperations(this);
this._permissions = new PermissionOperations(this);
this._roleAssignments = new RoleAssignmentOperations(this);
this._roleDefinitions = new RoleDefinitionOperations(this);
this._apiVersion = APIVersion;
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AuthorizationManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the AuthorizationManagementClient
/// class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public AuthorizationManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.azure.com/");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// AuthorizationManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of AuthorizationManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<AuthorizationManagementClient> client)
{
base.Clone(client);
if (client is AuthorizationManagementClient)
{
AuthorizationManagementClient clonedClient = ((AuthorizationManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
// QuickGraph Library
//
// Copyright (c) 2004 Jonathan de Halleux
//
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from
// the use of this software.
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment in the product
// documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must
// not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
// QuickGraph Library HomePage: http://www.mbunit.com
// Author: Jonathan de Halleux
namespace QuickGraph.Algorithms.Search
{
using System;
using System.Collections;
using System.Collections.Specialized;
using QuickGraph.Collections;
using QuickGraph.Concepts;
using QuickGraph.Concepts.Algorithms;
using QuickGraph.Concepts.Traversals;
using QuickGraph.Concepts.Visitors;
/// <summary>
/// </summary>
public class HeightFirstSearchAlgorithm :
IAlgorithm,
IPredecessorRecorderAlgorithm,
ITimeStamperAlgorithm,
IVertexColorizerAlgorithm,
ITreeEdgeBuilderAlgorithm
{
private IBidirectionalVertexListGraph visitedGraph;
private VertexColorDictionary colors;
private int maxDepth = int.MaxValue;
/// <summary>
/// A height first search algorithm on a directed graph
/// </summary>
/// <param name="g">The graph to traverse</param>
/// <exception cref="ArgumentNullException">g is null</exception>
public HeightFirstSearchAlgorithm(IBidirectionalVertexListGraph g)
{
if (g == null)
throw new ArgumentNullException("g");
this.visitedGraph = g;
this.colors = new VertexColorDictionary();
}
/// <summary>
/// A height first search algorithm on a directed graph
/// </summary>
/// <param name="g">The graph to traverse</param>
/// <param name="colors">vertex color map</param>
/// <exception cref="ArgumentNullException">g or colors are null</exception>
public HeightFirstSearchAlgorithm(
IBidirectionalVertexListGraph g,
VertexColorDictionary colors
)
{
if (g == null)
throw new ArgumentNullException("g");
if (colors == null)
throw new ArgumentNullException("Colors");
this.visitedGraph = g;
this.colors = colors;
}
/// <summary>
/// Visited graph
/// </summary>
public IBidirectionalVertexListGraph VisitedGraph
{
get
{
return this.visitedGraph;
}
}
Object IAlgorithm.VisitedGraph
{
get
{
return this.VisitedGraph;
}
}
/// <summary>
/// Gets the vertex color map
/// </summary>
/// <value>
/// Vertex color (<see cref="GraphColor"/>) dictionary
/// </value>
public VertexColorDictionary Colors
{
get
{
return this.colors;
}
}
/// <summary>
/// IVertexColorizerAlgorithm implementation
/// </summary>
IDictionary IVertexColorizerAlgorithm.Colors
{
get
{
return this.Colors;
}
}
/// <summary>
/// Gets or sets the maximum exploration depth, from
/// the start vertex.
/// </summary>
/// <remarks>
/// Defaulted at <c>int.MaxValue</c>.
/// </remarks>
/// <value>
/// Maximum exploration depth.
/// </value>
public int MaxDepth
{
get
{
return this.maxDepth;
}
set
{
this.maxDepth = value;
}
}
#region Events
/// <summary>
/// Invoked on every vertex of the graph before the start of the graph
/// search.
/// </summary>
public event VertexEventHandler InitializeVertex;
/// <summary>
/// Raises the <see cref="InitializeVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
protected void OnInitializeVertex(IVertex v)
{
if (InitializeVertex!=null)
InitializeVertex(this, new VertexEventArgs(v));
}
/// <summary>
/// Invoked on the source vertex once before the start of the search.
/// </summary>
public event VertexEventHandler StartVertex;
/// <summary>
/// Raises the <see cref="StartVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
protected void OnStartVertex(IVertex v)
{
if (StartVertex!=null)
StartVertex(this, new VertexEventArgs(v));
}
/// <summary>
/// Invoked when a vertex is encountered for the first time.
/// </summary>
public event VertexEventHandler DiscoverVertex;
/// <summary>
/// Raises the <see cref="DiscoverVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
protected void OnDiscoverVertex(IVertex v)
{
if (DiscoverVertex!=null)
DiscoverVertex(this, new VertexEventArgs(v));
}
/// <summary>
/// Invoked on every out-edge of each vertex after it is discovered.
/// </summary>
public event EdgeEventHandler ExamineEdge;
/// <summary>
/// Raises the <see cref="ExamineEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
protected void OnExamineEdge(IEdge e)
{
if (ExamineEdge!=null)
ExamineEdge(this, new EdgeEventArgs(e));
}
/// <summary>
/// Invoked on each edge as it becomes a member of the edges that form
/// the search tree. If you wish to record predecessors, do so at this
/// event point.
/// </summary>
public event EdgeEventHandler TreeEdge;
/// <summary>
/// Raises the <see cref="TreeEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
protected void OnTreeEdge(IEdge e)
{
if (TreeEdge!=null)
TreeEdge(this, new EdgeEventArgs(e));
}
/// <summary>
/// Invoked on the back edges in the graph.
/// </summary>
public event EdgeEventHandler BackEdge;
/// <summary>
/// Raises the <see cref="BackEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
protected void OnBackEdge(IEdge e)
{
if (BackEdge!=null)
BackEdge(this, new EdgeEventArgs(e));
}
/// <summary>
/// Invoked on forward or cross edges in the graph.
/// (In an undirected graph this method is never called.)
/// </summary>
public event EdgeEventHandler ForwardOrCrossEdge;
/// <summary>
/// Raises the <see cref="ForwardOrCrossEdge"/> event.
/// </summary>
/// <param name="e">edge that raised the event</param>
protected void OnForwardOrCrossEdge(IEdge e)
{
if (ForwardOrCrossEdge!=null)
ForwardOrCrossEdge(this, new EdgeEventArgs(e));
}
/// <summary>
/// Invoked on a vertex after all of its out edges have been added to
/// the search tree and all of the adjacent vertices have been
/// discovered (but before their out-edges have been examined).
/// </summary>
public event VertexEventHandler FinishVertex;
/// <summary>
/// Raises the <see cref="FinishVertex"/> event.
/// </summary>
/// <param name="v">vertex that raised the event</param>
protected void OnFinishVertex(IVertex v)
{
if (FinishVertex!=null)
FinishVertex(this, new VertexEventArgs(v));
}
#endregion
/// <summary>
/// Execute the DFS search.
/// </summary>
public void Compute()
{
Compute(null);
}
/// <summary>
/// Execute the DFS starting with the vertex s
/// </summary>
/// <param name="s">Starting vertex</param>
public void Compute(IVertex s)
{
// put all vertex to white
Initialize();
// if there is a starting vertex, start whith him:
if (s != null)
{
OnStartVertex(s);
Visit(s,0);
}
// process each vertex
foreach(IVertex u in VisitedGraph.Vertices)
{
if (Colors[u] == GraphColor.White)
{
OnStartVertex(u);
Visit(u,0);
}
}
}
/// <summary>
/// Initializes the vertex color map
/// </summary>
/// <remarks>
/// </remarks>
public void Initialize()
{
foreach(IVertex u in VisitedGraph.Vertices)
{
Colors[u] = GraphColor.White;
OnInitializeVertex(u);
}
}
/// <summary>
/// Does a depth first search on the vertex u
/// </summary>
/// <param name="u">vertex to explore</param>
/// <param name="depth">current recursion depth</param>
/// <exception cref="ArgumentNullException">u cannot be null</exception>
public void Visit(IVertex u, int depth)
{
if (depth > this.maxDepth)
return;
if (u==null)
throw new ArgumentNullException("u");
Colors[u] = GraphColor.Gray;
OnDiscoverVertex(u);
IVertex v = null;
foreach(IEdge e in VisitedGraph.InEdges(u))
{
OnExamineEdge(e);
v = e.Source;
GraphColor c=Colors[v];
if (c == GraphColor.White)
{
OnTreeEdge(e);
Visit(v,depth+1);
}
else if (c == GraphColor.Gray)
{
OnBackEdge(e);
}
else
{
OnForwardOrCrossEdge(e);
}
}
Colors[u] = GraphColor.Black;
OnFinishVertex(u);
}
/// <summary>
/// Registers the predecessors handler
/// </summary>
/// <param name="vis"></param>
public void RegisterPredecessorRecorderHandlers(IPredecessorRecorderVisitor vis)
{
if (vis == null)
throw new ArgumentNullException("visitor");
TreeEdge += new EdgeEventHandler(vis.TreeEdge);
FinishVertex += new VertexEventHandler(vis.FinishVertex);
}
/// <summary>
///
/// </summary>
/// <param name="vis"></param>
public void RegisterTimeStamperHandlers(ITimeStamperVisitor vis)
{
if (vis == null)
throw new ArgumentNullException("visitor");
DiscoverVertex += new VertexEventHandler(vis.DiscoverVertex);
FinishVertex += new VertexEventHandler(vis.FinishVertex);
}
/// <summary>
///
/// </summary>
/// <param name="vis"></param>
public void RegisterVertexColorizerHandlers(IVertexColorizerVisitor vis)
{
if (vis == null)
throw new ArgumentNullException("visitor");
InitializeVertex += new VertexEventHandler(vis.InitializeVertex);
DiscoverVertex += new VertexEventHandler(vis.DiscoverVertex);
FinishVertex += new VertexEventHandler(vis.FinishVertex);
}
/// <summary>
///
/// </summary>
/// <param name="vis"></param>
public void RegisterTreeEdgeBuilderHandlers(ITreeEdgeBuilderVisitor vis)
{
if (vis == null)
throw new ArgumentNullException("visitor");
TreeEdge += new EdgeEventHandler(vis.TreeEdge);
}
}
}
| |
// 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.ServiceModel;
namespace WcfService
{
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class RpcEncSingleNsService : ICalculator
{
public static IntParams IntParamsProp { get; set; }
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public void SetIntParamsProperty(IntParams par)
{
IntParamsProp = par;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public IntParams GetIntParamsProperty()
{
return IntParamsProp;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class RpcLitSingleNsService : ICalculator
{
public static IntParams IntParamsProp { get; set; }
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public void SetIntParamsProperty(IntParams par)
{
IntParamsProp = par;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public IntParams GetIntParamsProperty()
{
return IntParamsProp;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class DocLitSingleNsService : ICalculator
{
public static IntParams IntParamsProp { get; set; }
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public void SetIntParamsProperty(IntParams par)
{
IntParamsProp = par;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public IntParams GetIntParamsProperty()
{
return IntParamsProp;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class RpcEncDualNsService : ICalculator, IHelloWorld
{
public static IntParams IntParamsProp { get; set; }
public static string StringField;
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public void SetIntParamsProperty(IntParams par)
{
IntParamsProp = par;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public IntParams GetIntParamsProperty()
{
return IntParamsProp;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public void SetStringField(string str)
{
StringField = str;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Encoded)]
public string GetStringField()
{
return StringField;
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class RpcLitDualNsService : ICalculator, IHelloWorld
{
public static IntParams IntParamsProp { get; set; }
public static string StringField;
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public void SetIntParamsProperty(IntParams par)
{
IntParamsProp = par;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public IntParams GetIntParamsProperty()
{
return IntParamsProp;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public void SetStringField(string str)
{
StringField = str;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Rpc, Use = OperationFormatUse.Literal)]
public string GetStringField()
{
return StringField;
}
}
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class DocLitDualNsService : ICalculator, IHelloWorld
{
public static IntParams IntParamsProp { get; set; }
public static string StringField;
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public int Sum2(int i, int j)
{
return i + j;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public int Sum(IntParams par)
{
return par.P1 + par.P2;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public float Divide(FloatParams par)
{
return (float)(par.P1 / par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public string Concatenate(IntParams par)
{
return string.Format("{0}{1}", par.P1, par.P2);
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public void SetIntParamsProperty(IntParams par)
{
IntParamsProp = par;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public IntParams GetIntParamsProperty()
{
return IntParamsProp;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public DateTime ReturnInputDateTime(DateTime dt)
{
return dt;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public byte[] CreateSet(ByteParams par)
{
return new byte[] { par.P1, par.P2 };
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public void SetStringField(string str)
{
StringField = str;
}
[OperationBehavior]
[XmlSerializerFormat(Style = OperationFormatStyle.Document, Use = OperationFormatUse.Literal)]
public string GetStringField()
{
return StringField;
}
}
}
| |
// Copyright 2019 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
//
// 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 Google.Api.Ads.AdManager.Lib;
using Google.Api.Ads.AdManager.Util.v202202;
using Google.Api.Ads.AdManager.v202202;
using DateTime = Google.Api.Ads.AdManager.v202202.DateTime;
namespace Google.Api.Ads.AdManager.Examples.CSharp.v202202
{
/// <summary>
/// This code example gets a forecast for a prospective line item.
/// </summary>
public class GetAvailabilityForecast : SampleBase
{
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return "This code example gets a forecast for a prospective line item.";
}
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
public static void Main()
{
GetAvailabilityForecast codeExample = new GetAvailabilityForecast();
Console.WriteLine(codeExample.Description);
codeExample.Run(new AdManagerUser());
}
/// <summary>
/// Run the code example.
/// </summary>
public void Run(AdManagerUser user)
{
using (ForecastService forecastService = user.GetService<ForecastService>())
using (NetworkService networkService = user.GetService<NetworkService>())
{
// Set the ID of the advertiser (company) to forecast for. Setting an advertiser
// will cause the forecast to apply the appropriate unified blocking rules.
long advertiserId = long.Parse(_T("INSERT_ADVERTISER_ID_HERE"));
String rootAdUnitId = networkService.getCurrentNetwork().effectiveRootAdUnitId;
System.DateTime tomorrow = System.DateTime.Now.AddDays(1);
// Create prospective line item.
LineItem lineItem = new LineItem()
{
targeting = new Targeting()
{
inventoryTargeting = new InventoryTargeting()
{
targetedAdUnits = new AdUnitTargeting[] {
new AdUnitTargeting()
{
adUnitId = rootAdUnitId,
includeDescendants = true
}
}
}
},
creativePlaceholders = new CreativePlaceholder[] {
new CreativePlaceholder()
{
size = new Size()
{
width = 300,
height = 250
}
}
},
lineItemType = LineItemType.SPONSORSHIP,
// Set the line item to run for 5 days.
startDateTime = DateTimeUtilities.FromDateTime(
tomorrow, "America/New_York"),
endDateTime = DateTimeUtilities.FromDateTime(
tomorrow.AddDays(5), "America/New_York"),
// Set the cost type to match the unit type.
costType = CostType.CPM,
primaryGoal = new Goal()
{
goalType = GoalType.DAILY,
unitType = UnitType.IMPRESSIONS,
units = 50L
}
};
try
{
// Get availability forecast.
AvailabilityForecastOptions options = new AvailabilityForecastOptions()
{
includeContendingLineItems = true,
// Targeting criteria breakdown can only be included if breakdowns
// are not speficied.
includeTargetingCriteriaBreakdown = false,
breakdown = new ForecastBreakdownOptions
{
timeWindows = new DateTime[] {
lineItem.startDateTime,
DateTimeUtilities.FromDateTime(tomorrow.AddDays(1),
"America/New_York"),
DateTimeUtilities.FromDateTime(tomorrow.AddDays(2),
"America/New_York"),
DateTimeUtilities.FromDateTime(tomorrow.AddDays(3),
"America/New_York"),
DateTimeUtilities.FromDateTime(tomorrow.AddDays(4),
"America/New_York"),
lineItem.endDateTime
},
targets = new ForecastBreakdownTarget[] {
new ForecastBreakdownTarget()
{
// Optional name field to identify this breakdown
// in the response.
name = "United States",
targeting = new Targeting()
{
inventoryTargeting = new InventoryTargeting()
{
targetedAdUnits = new AdUnitTargeting[] {
new AdUnitTargeting()
{
adUnitId = rootAdUnitId,
includeDescendants = true
}
}
},
geoTargeting = new GeoTargeting()
{
targetedLocations = new Location[] {
new Location() { id = 2840L }
}
}
}
}, new ForecastBreakdownTarget()
{
// Optional name field to identify this breakdown
// in the response.
name = "Geneva",
targeting = new Targeting()
{
inventoryTargeting = new InventoryTargeting()
{
targetedAdUnits = new AdUnitTargeting[] {
new AdUnitTargeting()
{
adUnitId = rootAdUnitId,
includeDescendants = true
}
}
},
geoTargeting = new GeoTargeting()
{
targetedLocations = new Location[] {
new Location () { id = 20133L }
}
}
}
}
}
}
};
ProspectiveLineItem prospectiveLineItem = new ProspectiveLineItem()
{
advertiserId = advertiserId,
lineItem = lineItem
};
AvailabilityForecast forecast =
forecastService.getAvailabilityForecast(prospectiveLineItem, options);
// Display results.
long matched = forecast.matchedUnits;
double availablePercent =
(double)(forecast.availableUnits / (matched * 1.0)) * 100;
String unitType = forecast.unitType.ToString().ToLower();
Console.WriteLine($"{matched} {unitType} matched.");
Console.WriteLine($"{availablePercent}% {unitType} available.");
if (forecast.possibleUnitsSpecified)
{
double possiblePercent =
(double)(forecast.possibleUnits / (matched * 1.0)) * 100;
Console.WriteLine($"{possiblePercent}% {unitType} possible.");
}
var contendingLineItems =
forecast.contendingLineItems ?? new ContendingLineItem[] { };
Console.WriteLine($"{contendingLineItems.Length} contending line items.");
if (forecast.breakdowns != null)
{
foreach (ForecastBreakdown breakdown in forecast.breakdowns)
{
Console.WriteLine("Forecast breakdown for {0} to {1}",
DateTimeUtilities.ToString(breakdown.startTime, "yyyy-MM-dd"),
DateTimeUtilities.ToString(breakdown.endTime, "yyyy-MM-dd"));
foreach (ForecastBreakdownEntry entry in breakdown.breakdownEntries)
{
Console.WriteLine($"\t{entry.name}");
long breakdownMatched = entry.forecast.matched;
Console.WriteLine($"\t\t{breakdownMatched} {unitType} matched.");
if (breakdownMatched > 0)
{
long breakdownAvailable = entry.forecast.available;
double breakdownAvailablePercent =
(double)(breakdownAvailable / (breakdownMatched * 1.0)) * 100;
Console.WriteLine(
$"\t\t{breakdownAvailablePercent}% {unitType} available");
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Failed to get forecast. Exception says \"{0}\"", e.Message);
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowConflateSpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Akka.Streams.Dsl;
using Akka.Streams.Supervision;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.TestKit;
using Akka.Util;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowConflateSpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public FlowConflateSpec(ITestOutputHelper helper) : base(helper)
{
var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(2, 2);
Materializer = ActorMaterializer.Create(Sys, settings);
}
[Fact]
public void Conflate_must_pass_through_elements_unchanged_when_there_is_no_rate_difference()
{
var publisher = TestPublisher.CreateProbe<int>(this);
var subscriber = TestSubscriber.CreateManualProbe<int>(this);
Source.FromPublisher(publisher)
.ConflateWithSeed(i => i, (sum, i) => sum + i)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var sub = subscriber.ExpectSubscription();
for (var i = 1; i <= 100; i++)
{
sub.Request(1);
publisher.SendNext(i);
subscriber.ExpectNext(i);
}
sub.Cancel();
}
[Fact]
public void Conflate_must_pass_through_elements_unchanged_when_there_is_no_rate_difference_simple_conflate()
{
var publisher = TestPublisher.CreateProbe<int>(this);
var subscriber = TestSubscriber.CreateManualProbe<int>(this);
Source.FromPublisher(publisher)
.Conflate((sum, i) => sum + i)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var sub = subscriber.ExpectSubscription();
for (var i = 1; i <= 100; i++)
{
sub.Request(1);
publisher.SendNext(i);
subscriber.ExpectNext(i);
}
sub.Cancel();
}
[Fact]
public void Conflate_must_conflate_elements_while_downstream_is_silent()
{
var publisher = TestPublisher.CreateProbe<int>(this);
var subscriber = TestSubscriber.CreateManualProbe<int>(this);
Source.FromPublisher(publisher)
.ConflateWithSeed(i=>i,(sum, i) => sum + i)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var sub = subscriber.ExpectSubscription();
for (var i = 1; i <= 100; i++)
publisher.SendNext(i);
subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1));
sub.Request(1);
subscriber.ExpectNext(5050);
sub.Cancel();
}
[Fact]
public void Conflate_must_conflate_elements_while_downstream_is_silent_simple_conflate()
{
var publisher = TestPublisher.CreateProbe<int>(this);
var subscriber = TestSubscriber.CreateManualProbe<int>(this);
Source.FromPublisher(publisher)
.Conflate((sum, i) => sum + i)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var sub = subscriber.ExpectSubscription();
for (var i = 1; i <= 100; i++)
publisher.SendNext(i);
subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1));
sub.Request(1);
subscriber.ExpectNext(5050);
sub.Cancel();
}
[Fact]
public void Conflate_must_work_on_a_variable_rate_chain()
{
var future = Source.From(Enumerable.Range(1, 1000)).ConflateWithSeed(i => i, (sum, i) => sum + i).Select(i =>
{
if (ThreadLocalRandom.Current.Next(1, 3) == 2)
Thread.Sleep(10);
return i;
}).RunAggregate(0, (sum, i) => sum + i, Materializer);
future.Wait(TimeSpan.FromSeconds(10)).Should().BeTrue();
future.Result.Should().Be(500500);
}
[Fact]
public void Conflate_must_work_on_a_variable_rate_chain_simple_conflate()
{
var future = Source.From(Enumerable.Range(1, 1000)).Conflate((sum, i) => sum + i).Select(i =>
{
if (ThreadLocalRandom.Current.Next(1, 3) == 2)
Thread.Sleep(10);
return i;
}).RunAggregate(0, (sum, i) => sum + i, Materializer);
future.Wait(TimeSpan.FromSeconds(10)).Should().BeTrue();
future.Result.Should().Be(500500);
}
[Fact]
public void Conflate_must_backpressure_subscriber_when_upstream_is_slower()
{
var publisher = TestPublisher.CreateProbe<int>(this);
var subscriber = TestSubscriber.CreateManualProbe<int>(this);
Source.FromPublisher(publisher)
.ConflateWithSeed(i=>i, (sum, i) => sum + i)
.To(Sink.FromSubscriber(subscriber))
.Run(Materializer);
var sub = subscriber.ExpectSubscription();
sub.Request(1);
publisher.SendNext(1);
subscriber.ExpectNext(1);
sub.Request(1);
subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
publisher.SendNext(2);
subscriber.ExpectNext(2);
publisher.SendNext(3);
publisher.SendNext(4);
// The request can be in race with the above onNext(4) so the result would be either 3 or 7.
subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
sub.Request(1);
subscriber.ExpectNext(7);
sub.Request(1);
subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500));
sub.Cancel();
}
[Fact]
public void Conflate_must_work_with_a_buffer_and_aggregate()
{
var future =
Source.From(Enumerable.Range(1, 50))
.ConflateWithSeed(i => i, (sum, i) => sum + i)
.Buffer(50, OverflowStrategy.Backpressure)
.RunAggregate(0, (sum, i) => sum + i, Materializer);
future.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue();
future.Result.Should().Be(Enumerable.Range(1, 50).Sum());
}
[Fact]
public void Conflate_must_restart_when_seed_throws_and_a_RestartDescider_is_used()
{
var sourceProbe = TestPublisher.CreateProbe<int>(this);
var sinkProbe = TestSubscriber.CreateManualProbe<int>(this);
var exceptionlath = new TestLatch();
var graph = Source.FromPublisher(sourceProbe).ConflateWithSeed(i =>
{
if (i%2 == 0)
{
exceptionlath.Open();
throw new TestException("I hate even seed numbers");
}
return i;
}, (sum, i) => sum + i)
.WithAttributes(ActorAttributes.CreateSupervisionStrategy(Deciders.RestartingDecider))
.To(Sink.FromSubscriber(sinkProbe))
.WithAttributes(Attributes.CreateInputBuffer(1, 1));
RunnableGraph.FromGraph(graph).Run(Materializer);
var sub = sourceProbe.ExpectSubscription();
var sinkSub = sinkProbe.ExpectSubscription();
// push the first value
sub.ExpectRequest(1);
sub.SendNext(1);
// and consume it, so that the next element
// will trigger seed
sinkSub.Request(1);
sinkProbe.ExpectNext(1);
sub.ExpectRequest(1);
sub.SendNext(2);
// make sure the seed exception happened
// before going any further
exceptionlath.Ready(TimeSpan.FromSeconds(3));
sub.ExpectRequest(1);
sub.SendNext(3);
// now we should have lost the 2 and the accumulated state
sinkSub.Request(1);
sinkProbe.ExpectNext(3);
}
[Fact]
public void Conflate_must_restart_when_aggregate_throws_and_a_RestartingDecider_is_used()
{
var sourceProbe = TestPublisher.CreateProbe<string>(this);
var sinkProbe = TestSubscriber.CreateProbe<string>(this);
var latch = new TestLatch();
var conflate = Flow.Create<string>().ConflateWithSeed(i => i, (state, elem) =>
{
if (elem == "two")
{
latch.Open();
throw new TestException("two is a three letter word");
}
return state + elem;
}).WithAttributes(ActorAttributes.CreateSupervisionStrategy(Deciders.RestartingDecider));
var graph = Source.FromPublisher(sourceProbe)
.Via(conflate)
.To(Sink.FromSubscriber(sinkProbe))
.WithAttributes(Attributes.CreateInputBuffer(4, 4));
RunnableGraph.FromGraph(graph).Run(Materializer);
var sub = sourceProbe.ExpectSubscription();
sub.ExpectRequest(4);
sub.SendNext("one");
sub.SendNext("two");
sub.SendNext("three");
sub.SendComplete();
//"one" should be lost
latch.Ready(TimeSpan.FromSeconds(3));
sinkProbe.RequestNext("three");
}
[Fact]
public void Conflate_must_restart_when_aggregate_throws_and_a_ResumingDecider_is_used()
{
var sourceProbe = TestPublisher.CreateProbe<int>(this);
var sinkProbe = TestSubscriber.CreateManualProbe<List<int>>(this);
var saw4Latch = new TestLatch();
var graph = Source.FromPublisher(sourceProbe).ConflateWithSeed(i => new List<int> { i },
(state, elem) =>
{
if (elem == 2)
throw new TestException("three is a four letter word");
if (elem == 4)
saw4Latch.Open();
state.Add(elem);
return state;
})
.WithAttributes(ActorAttributes.CreateSupervisionStrategy(Deciders.ResumingDecider))
.To(Sink.FromSubscriber(sinkProbe))
.WithAttributes(Attributes.CreateInputBuffer(1, 1));
RunnableGraph.FromGraph(graph).Run(Materializer);
var sub = sourceProbe.ExpectSubscription();
var sinkSub = sinkProbe.ExpectSubscription();
// push the first three values, the third will trigger
// the exception
sub.ExpectRequest(1);
sub.SendNext(1);
// causing the 1 to get thrown away
sub.ExpectRequest(1);
sub.SendNext(2);
sub.ExpectRequest(1);
sub.SendNext(3);
sub.ExpectRequest(1);
sub.SendNext(4);
// and consume it, so that the next element
// will trigger seed
saw4Latch.Ready(TimeSpan.FromSeconds(3));
sinkSub.Request(1);
sinkProbe.ExpectNext().ShouldAllBeEquivalentTo(new [] {1, 3, 4});
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using Newtonsoft.Json.Linq;
using ReactNative.Json;
using System.Collections.Generic;
#if WINDOWS_UWP
using Windows.UI.Xaml.Automation.Peers;
#endif
namespace ReactNative.UIManager
{
/// <summary>
/// Prop keys for React views.
/// </summary>
public static class ViewProps
{
#pragma warning disable CS1591
public const string ViewClassName = "RCTView";
// Layout only (only affect positions of children, causes no drawing)
// !!! Keep in sync with s_layoutOnlyProps below !!!
public const string AlignItems = "alignItems";
public const string AlignSelf = "alignSelf";
public const string AlignContent = "alignContent";
public const string Display = "display";
public const string Bottom = "bottom";
public const string Collapsible = "collapsable";
public const string Flex = "flex";
public const string FlexGrow = "flexGrow";
public const string FlexShrink = "flexShrink";
public const string FlexBasis = "flexBasis";
public const string FlexDirection = "flexDirection";
public const string FlexWrap = "flexWrap";
public const string Height = "height";
public const string JustifyContent = "justifyContent";
public const string Left = "left";
public const string Margin = "margin";
public const string MarginVertical = "marginVertical";
public const string MarginHorizontal = "marginHorizontal";
public const string MarginLeft = "marginLeft";
public const string MarginRight = "marginRight";
public const string MarginTop = "marginTop";
public const string MarginBottom = "marginBottom";
public const string MarginStart = "marginStart";
public const string MarginEnd = "marginEnd";
public const string Padding = "padding";
public const string PaddingVertical = "paddingVertical";
public const string PaddingHorizontal = "paddingHorizontal";
public const string PaddingLeft = "paddingLeft";
public const string PaddingRight = "paddingRight";
public const string PaddingTop = "paddingTop";
public const string PaddingBottom = "paddingBottom";
public const string PaddingStart = "paddingStart";
public const string PaddingEnd = "paddingEnd";
public const string Position = "position";
public const string Right = "right";
public const string Top = "top";
public const string Width = "width";
public const string Start = "start";
public const string End = "end";
public const string MinWidth = "minWidth";
public const string MaxWidth = "maxWidth";
public const string MinHeight = "minHeight";
public const string MaxHeight = "maxHeight";
public const string AspectRatio = "aspectRatio";
// Props that sometimes may prevent us from collapsing views
public const string PointerEvents = "pointerEvents";
public const string Auto = "auto";
public const string BoxNone = "box-none";
// Props that affect more than just layout
public const string Disabled = "disabled";
public const string BackgroundColor = "backgroundColor";
public const string BlurRadius = "blurRadius";
public const string BlurEffect = "blurEffect";
public const string Color = "color";
public const string FontSize = "fontSize";
public const string FontWeight = "fontWeight";
public const string FontStyle = "fontStyle";
public const string FontFamily = "fontFamily";
public const string LetterSpacing = "letterSpacing";
public const string LineHeight = "lineHeight";
public const string NumberOfLines = "numberOfLines";
public const string Value = "value";
public const string ResizeMode = "resizeMode";
public const string TextAlign = "textAlign";
public const string TextAlignVertical = "textAlignVertical";
public const string TextDecorationLine = "textDecorationLine";
public const string Opacity = "opacity";
public const string Overflow = "overflow";
public const string Hidden = "hidden";
public const string Visible = "visible";
public const string AccessibilityTraits = "accessibilityTraits";
public const string AccessibilityLabel = "accessibilityLabel";
public const string ImportantForAccessibility = "importantForAccessibility";
public const string AccessibilityLiveRegion = "accessibilityLiveRegion";
public const string AllowFontScaling = "allowFontScaling";
public const string BorderWidth = "borderWidth";
public const string BorderLeftWidth = "borderLeftWidth";
public const string BorderStartWidth = "borderStartWidth";
public const string BorderEndWidth = "borderEndWidth";
public const string BorderTopWidth = "borderTopWidth";
public const string BorderRightWidth = "borderRightWidth";
public const string BorderBottomWidth = "borderBottomWidth";
public const string BorderRadius = "borderRadius";
public const string BorderTopLeftRadius = "borderTopLeftRadius";
public const string BorderTopRightRadius = "borderTopRightRadius";
public const string BorderBottomLeftRadius = "borderBottomLeftRadius";
public const string BorderBottomRightRadius = "borderBottomRightRadius";
public const string BorderColor = "borderColor";
public const string BorderTopStartRadius = "borderTopStartRadius";
public const string BorderTopEndRadius = "borderTopEndRadius";
public const string BorderBottomStartRadius = "borderBottomStartRadius";
public const string BorderBottomEndRadius = "borderBottomEndRadius";
public const string OnLayout = "onLayout";
#pragma warning restore CS1591
/// <summary>
/// Ordered list of margin spacing types.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "IReadOnlyList is immutable.")]
public static readonly IReadOnlyList<int> BorderSpacingTypes =
new List<int>
{
EdgeSpacing.All,
EdgeSpacing.Top,
EdgeSpacing.Bottom,
EdgeSpacing.Left,
EdgeSpacing.Right,
};
/// <summary>
/// Ordered list of border spacing types.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "IReadOnlyList is immutable.")]
public static readonly IReadOnlyList<int> PaddingMarginSpacingTypes =
new List<int>
{
EdgeSpacing.All,
EdgeSpacing.Vertical,
EdgeSpacing.Horizontal,
EdgeSpacing.Start,
EdgeSpacing.End,
EdgeSpacing.Top,
EdgeSpacing.Bottom,
EdgeSpacing.Left,
EdgeSpacing.Right,
};
/// <summary>
/// Ordered list of position spacing types.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes", Justification = "IReadOnlyList is immutable.")]
public static readonly IReadOnlyList<int> PositionSpacingTypes =
new List<int>
{
EdgeSpacing.Start,
EdgeSpacing.End,
EdgeSpacing.Left,
EdgeSpacing.Right,
EdgeSpacing.Top,
EdgeSpacing.Bottom,
};
private static readonly HashSet<string> s_layoutOnlyProps =
new HashSet<string>
{
AlignSelf,
AlignItems,
Collapsible,
Flex,
FlexBasis,
FlexDirection,
FlexGrow,
FlexShrink,
FlexWrap,
JustifyContent,
AlignContent,
Display,
/* position */
Position,
Right,
Top,
Bottom,
Left,
Start,
End,
/* dimensions */
Width,
Height,
MinWidth,
MaxWidth,
MinHeight,
MaxHeight,
/* margins */
Margin,
MarginVertical,
MarginHorizontal,
MarginLeft,
MarginRight,
MarginTop,
MarginBottom,
MarginStart,
MarginEnd,
/* paddings */
Padding,
PaddingVertical,
PaddingHorizontal,
PaddingLeft,
PaddingRight,
PaddingTop,
PaddingBottom,
PaddingStart,
PaddingEnd,
};
/// <summary>
/// Checks if the prop key is layout-only.
/// </summary>
/// <param name="props">The prop collection.</param>
/// <param name="prop">The prop name.</param>
/// <returns>
/// <b>true</b> if the prop is layout-only, <b>false</b> otherwise.
/// </returns>
public static bool IsLayoutOnly(JObject props, string prop)
{
if (s_layoutOnlyProps.Contains(prop))
{
return true;
}
else if (prop == PointerEvents)
{
var value = props.Value<string>(prop);
return value == Auto || value == BoxNone;
}
// These are more aggressive optimizations based on property values.
// In RN Android there is a runtime check here. We omitted it because
// the check didn't inspire confidence in the optimizations that must be
// either correct or not.
{
var value = props[prop];
switch (prop)
{
case Opacity:
// null opacity behaves like opacity = 1
// Ignore if explicitly set to default opacity.
return value == null || value.Value<double>() == 1.0;
case BorderWidth:
return value == null || value.Value<double>() == 0.0;
case BorderLeftWidth:
return value == null || value.Value<double>() == 0.0;
case BorderTopWidth:
return value == null || value.Value<double>() == 0.0;
case BorderRightWidth:
return value == null || value.Value<double>() == 0.0;
case BorderBottomWidth:
return value == null || value.Value<double>() == 0.0;
case Overflow:
return value == null || value.Value<string>() == Visible;
case AccessibilityTraits:
return value == null || value is JArray array && array.Count == 0;
case AccessibilityLabel:
return value == null || value.Type == JTokenType.String && value.Value<string>().Length == 0;
case ImportantForAccessibility:
return value == null || value.Type == JTokenType.String &&
(value.Value<string>().Length == 0 || value.Value<string>() == "auto");
#if WINDOWS_UWP
case AccessibilityLiveRegion:
return value == null || value.Type == JTokenType.String &&
(value.Value<string>().Length == 0 || value.Value<string>() == "off");
#endif
}
}
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Data.Entity.Relational.Migrations.Infrastructure;
using infiny.Models;
namespace infiny.Migrations
{
[ContextType(typeof(ApplicationDbContext))]
partial class CreateIdentitySchema
{
public override string Id
{
get { return "00000000000000_CreateIdentitySchema"; }
}
public override string ProductVersion
{
get { return "7.0.0-beta5"; }
}
public override void BuildTargetModel(ModelBuilder builder)
{
builder
.Annotation("SqlServer:ValueGeneration", "Identity");
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("Name")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("NormalizedName")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoles");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetRoleClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.GenerateValueOnAdd()
.StoreGeneratedPattern(StoreGeneratedPattern.Identity)
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ClaimType")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ClaimValue")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUserClaims");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<string>("ProviderKey")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ProviderDisplayName")
.Annotation("OriginalValueIndex", 2);
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 3);
b.Key("LoginProvider", "ProviderKey");
b.Annotation("Relational:TableName", "AspNetUserLogins");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.Annotation("OriginalValueIndex", 0);
b.Property<string>("RoleId")
.Annotation("OriginalValueIndex", 1);
b.Key("UserId", "RoleId");
b.Annotation("Relational:TableName", "AspNetUserRoles");
});
builder.Entity("infiny.Models.ApplicationUser", b =>
{
b.Property<string>("Id")
.GenerateValueOnAdd()
.Annotation("OriginalValueIndex", 0);
b.Property<int>("AccessFailedCount")
.Annotation("OriginalValueIndex", 1);
b.Property<string>("ConcurrencyStamp")
.ConcurrencyToken()
.Annotation("OriginalValueIndex", 2);
b.Property<string>("Email")
.Annotation("OriginalValueIndex", 3);
b.Property<bool>("EmailConfirmed")
.Annotation("OriginalValueIndex", 4);
b.Property<bool>("LockoutEnabled")
.Annotation("OriginalValueIndex", 5);
b.Property<DateTimeOffset?>("LockoutEnd")
.Annotation("OriginalValueIndex", 6);
b.Property<string>("NormalizedEmail")
.Annotation("OriginalValueIndex", 7);
b.Property<string>("NormalizedUserName")
.Annotation("OriginalValueIndex", 8);
b.Property<string>("PasswordHash")
.Annotation("OriginalValueIndex", 9);
b.Property<string>("PhoneNumber")
.Annotation("OriginalValueIndex", 10);
b.Property<bool>("PhoneNumberConfirmed")
.Annotation("OriginalValueIndex", 11);
b.Property<string>("SecurityStamp")
.Annotation("OriginalValueIndex", 12);
b.Property<bool>("TwoFactorEnabled")
.Annotation("OriginalValueIndex", 13);
b.Property<string>("UserName")
.Annotation("OriginalValueIndex", 14);
b.Key("Id");
b.Annotation("Relational:TableName", "AspNetUsers");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b =>
{
b.Reference("infiny.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b =>
{
b.Reference("infiny.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b =>
{
b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole")
.InverseCollection()
.ForeignKey("RoleId");
b.Reference("infiny.Models.ApplicationUser")
.InverseCollection()
.ForeignKey("UserId");
});
}
}
}
| |
/*
* IdSharp - A tagging library for .NET
* Copyright (C) 2007 Jud White
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
using System;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using IdSharp.Tagging.ID3v1;
using IdSharp.Tagging.ID3v2;
namespace IdSharpHarness
{
public partial class MainForm : Form
{
#region <<< Private Fields >>>
private Boolean m_IsScanning;
private Boolean m_CancelScanning;
private String m_Filename;
#endregion <<< Private Fields >>>
#region <<< Constructor >>>
public MainForm()
{
InitializeComponent();
AssemblyName assemblyName = AssemblyName.GetAssemblyName("IdSharp.dll");
lblVersion.Text = String.Format("IdSharp library version: {0} ALPHA RELEASE PLEASE TEST ON BACKUPS ONLY", assemblyName.Version);
}
#endregion <<< Constructor >>>
#region <<< Event Handlers >>>
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnChooseDirectory_Click(object sender, EventArgs e)
{
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
txtDirectory.Text = folderBrowserDialog.SelectedPath;
}
}
private void btnScan_Click(object sender, EventArgs e)
{
if (m_IsScanning)
{
m_CancelScanning = true;
return;
}
if (Directory.Exists(txtDirectory.Text))
StartRecursiveScan(txtDirectory.Text);
else
MessageBox.Show("Directory does not exist");
}
private void btnLoad_Click(object sender, EventArgs e)
{
if (audioOpenFileDialog.ShowDialog() == DialogResult.OK)
{
LoadFile(audioOpenFileDialog.FileName);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveFile(m_Filename);
}
private void btnRemoveID3v2_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(m_Filename))
{
MessageBox.Show("No file loaded", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
DialogResult result = MessageBox.Show(String.Format("Remove ID3v2 tag from '{0}'?", Path.GetFileName(m_Filename)), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
Boolean success = ID3v2Helper.RemoveTag(m_Filename);
if (success)
MessageBox.Show("ID3v2 tag successfully removed", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("ID3v2 tag not found", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
btnRemoveID3v2.Enabled = ID3v2Helper.DoesTagExist(m_Filename);
ucID3v2.LoadFile(m_Filename);
}
private void btnRemoveID3v1_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(m_Filename))
{
MessageBox.Show("No file loaded", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
DialogResult result = MessageBox.Show(String.Format("Remove ID3v1 tag from '{0}'?", Path.GetFileName(m_Filename)), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
Boolean success = ID3v1Helper.RemoveTag(m_Filename);
if (success)
MessageBox.Show("ID3v1 tag successfully removed", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
else
MessageBox.Show("ID3v1 tag not found", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
btnRemoveID3v1.Enabled = ID3v1Helper.DoesTagExist(m_Filename);
ucID3v1.LoadFile(m_Filename);
}
#endregion <<< Event Handlers >>>
#region <<< Private Methods >>>
private void StartRecursiveScan(String basePath)
{
m_IsScanning = true;
m_CancelScanning = false;
lblDirectory.Visible = false;
txtDirectory.Visible = false;
btnChooseDirectory.Visible = false;
btnScan.Text = "&Cancel";
btnScan.Enabled = false;
prgScanFiles.Value = 0;
prgScanFiles.Visible = true;
ThreadPool.QueueUserWorkItem(new WaitCallback(this.ScanDirectory), basePath);
}
private void ScanDirectory(Object basePathObject)
{
Int32 totalFiles = 0;
BindingList<Track> trackList = new BindingList<Track>();
try
{
String basePath = (String)basePathObject;
DirectoryInfo di = new DirectoryInfo(basePath);
FileInfo[] fileList = di.GetFiles("*.mp3", SearchOption.AllDirectories);
EnableCancelButton();
totalFiles = fileList.Length;
for (Int32 i = 0; i < totalFiles; i++)
{
if (m_CancelScanning)
{
totalFiles = i;
break;
}
IID3v2 id3 = ID3v2Helper.CreateID3v2(fileList[i].FullName);
trackList.Add(new Track(id3.Artist, id3.Title, id3.Album, id3.Year, id3.Genre, fileList[i].Name));
if ((i % 100) == 0)
{
UpdateProgress(i * 100 / totalFiles);
}
}
}
finally
{
EndRecursiveScanning(totalFiles, trackList);
}
}
private void EnableCancelButton()
{
if (!this.InvokeRequired)
this.btnScan.Enabled = true;
else
this.Invoke(new MethodInvoker(this.EnableCancelButton));
}
private delegate void UpdateProgressDelegate(Int32 progressValue);
private void UpdateProgress(Int32 progressValue)
{
if (!this.InvokeRequired)
this.prgScanFiles.Value = progressValue;
else
this.Invoke(new UpdateProgressDelegate(this.UpdateProgress), progressValue);
}
private delegate void EndRecursiveScanningDelegate(Int32 totalFiles, BindingList<Track> trackList);
private void EndRecursiveScanning(Int32 totalFiles, BindingList<Track> trackList)
{
if (!this.InvokeRequired)
{
m_IsScanning = false;
prgScanFiles.Visible = false;
lblDirectory.Visible = true;
txtDirectory.Visible = true;
btnChooseDirectory.Visible = true;
btnScan.Text = "&Scan";
btnScan.Enabled = true;
this.dataGridView1.DataSource = trackList;
}
else
{
this.Invoke(new EndRecursiveScanningDelegate(this.EndRecursiveScanning), totalFiles, trackList);
}
}
private void LoadFile(String path)
{
m_Filename = path;
ucID3v2.LoadFile(m_Filename);
ucID3v1.LoadFile(m_Filename);
btnSave.Enabled = true;
btnRemoveID3v2.Enabled = ID3v2Helper.DoesTagExist(m_Filename);
btnRemoveID3v1.Enabled = ID3v1Helper.DoesTagExist(m_Filename);
}
private void SaveFile(String path)
{
ucID3v2.SaveFile(path);
ucID3v1.SaveFile(path);
LoadFile(path);
}
#endregion <<< Private Methods >>>
}
}
| |
// Copyright 2020 The Tilt Brush 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 System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Video;
namespace TiltBrush {
[System.Serializable]
public class ReferenceVideo {
/// The controller is used as a handle for controlling the video - videos stay instantiated as
/// long as there are controllers in existence that reference them. For this reason it is
/// important to Dispose() of controllers once they are no longer needed.
///
/// Properties of videos that can change (playing state, volume, scrub position) are all accessed
/// through the Controller - properties of videos that are unchanging are accessed through the
/// ReferenceVideo.
public class Controller : IDisposable {
private Action m_OnVideoInitialized;
private ReferenceVideo m_ReferenceVideo;
private bool m_VideoInitialized;
public bool Initialized => m_VideoInitialized;
/// Videos do not start playing immediately; this event is triggered when the video is ready.
/// However, as several controllers may point at the same video, if a controller is made to
/// point at an already playing video, when a user adds a value to OnVideoInitialized, the event
/// will be made to trigger immediately. The event is always cleared after triggering so this
/// will not cause OnVideoInitialized functions to be called more than once.
public event Action OnVideoInitialized {
add {
m_OnVideoInitialized += value;
if (m_VideoInitialized) {
OnInitialization();
}
}
remove { m_OnVideoInitialized -= value; }
}
private VideoPlayer VideoPlayer => m_ReferenceVideo.m_VideoPlayer;
public Texture VideoTexture {
get { return m_VideoInitialized ? VideoPlayer.texture : null; }
}
public bool Playing {
get => m_VideoInitialized ? VideoPlayer.isPlaying : false;
set {
if (m_VideoInitialized) {
if (VideoPlayer.isPlaying) {
VideoPlayer.Pause();
} else {
VideoPlayer.Play();
}
}
}
}
public float Volume {
get => (!m_VideoInitialized || VideoPlayer.GetDirectAudioMute(0))
? 0f : VideoPlayer.GetDirectAudioVolume(0);
set {
if (m_VideoInitialized) {
if (value <= 0.005f) {
VideoPlayer.SetDirectAudioVolume(0, 0f);
VideoPlayer.SetDirectAudioMute(0, true);
} else {
VideoPlayer.SetDirectAudioMute(0, false);
VideoPlayer.SetDirectAudioVolume(0, value);
}
}
}
}
public float Position {
get => m_VideoInitialized ? (float) (VideoPlayer.time / VideoPlayer.length) : 0f;
set {
if (m_VideoInitialized) {
VideoPlayer.time = VideoPlayer.length * Mathf.Clamp01(value);
}
}
}
public float Time {
get => m_VideoInitialized ? (float) VideoPlayer.time : 0f;
set {
if (m_VideoInitialized) {
VideoPlayer.time = Mathf.Clamp(value, 0, (float)VideoPlayer.length);
}
}
}
public float Length => m_VideoInitialized ? (float) VideoPlayer.length : 0f;
public Controller(ReferenceVideo referenceVideo) {
m_ReferenceVideo = referenceVideo;
if (m_ReferenceVideo.m_VideoPlayer != null) {
m_VideoInitialized = m_ReferenceVideo.m_VideoPlayer.isPrepared;
}
}
public Controller(Controller other) {
m_ReferenceVideo = other.m_ReferenceVideo;
m_VideoInitialized = other.m_VideoInitialized;
m_ReferenceVideo.m_Controllers.Add(this);
}
public void Dispose() {
if (m_ReferenceVideo != null) {
m_ReferenceVideo.OnControllerDisposed(this);
m_ReferenceVideo = null;
}
}
public void OnInitialization() {
m_VideoInitialized = true;
m_OnVideoInitialized?.Invoke();
m_OnVideoInitialized = null;
}
}
public static ReferenceVideo CreateDummyVideo() {
return new ReferenceVideo();
}
private VideoPlayer m_VideoPlayer;
private HashSet<Controller> m_Controllers = new HashSet<Controller>();
/// Persistent path is relative to the Tilt Brush/Media Library/Videos directory, if it is a
/// filename.
public string PersistentPath { get; }
public string AbsolutePath { get; }
public bool NetworkVideo { get; }
public string HumanName { get; }
public Texture2D Thumbnail { get; private set; }
public uint Width { get; private set; }
public uint Height { get; private set; }
public float Aspect { get; private set; }
public bool IsInitialized { get; private set; }
public bool HasInstances => m_Controllers.Count > 0;
public string Error { get; private set; }
public ReferenceVideo(string filePath) {
NetworkVideo = filePath.EndsWith(".txt");
PersistentPath = filePath.Substring(App.VideoLibraryPath().Length + 1);
HumanName = System.IO.Path.GetFileName(PersistentPath);
AbsolutePath = filePath;
}
// Dummy ReferenceVideo - this is used when a video referenced in a sketch cannot be found.
private ReferenceVideo() {
IsInitialized = false;
Width = 160;
Height = 90;
Aspect = 16 / 9f;
PersistentPath = "";
AbsolutePath = "";
NetworkVideo = false;
HumanName = "";
}
/// Creates a controller for this reference video. Controllers are Disposable and it is important
/// to Dispose a controller after it is finished with. If disposal does not happen, then the
/// video decoder will keep decoding, using up memory and bandwidth. If the audio is turned on
/// then the audio will continue. DISPOSE OF YOUR CONTROLLERS.
public Controller CreateController() {
Controller controller = new Controller(this);
bool alreadyPrepared = HasInstances;
m_Controllers.Add(controller);
if (!alreadyPrepared) {
VideoCatalog.Instance.StartCoroutine(PrepareVideoPlayer(InitializeControllers));
}
return controller;
}
private void InitializeControllers() {
foreach (var controller in m_Controllers) {
controller.OnInitialization();
}
}
private void OnControllerDisposed(Controller controller) {
m_Controllers.Remove(controller);
if (!HasInstances && m_VideoPlayer != null) {
m_VideoPlayer.Stop();
UnityEngine.Object.Destroy(m_VideoPlayer.gameObject);
m_VideoPlayer = null;
}
}
private IEnumerator<Null> PrepareVideoPlayer(Action onCompletion) {
Error = null;
var gobj = new GameObject(HumanName);
gobj.transform.SetParent(VideoCatalog.Instance.gameObject.transform);
try {
m_VideoPlayer = gobj.AddComponent<VideoPlayer>();
m_VideoPlayer.playOnAwake = false;
if (NetworkVideo) {
if (System.IO.File.Exists(AbsolutePath)) {
m_VideoPlayer.url = System.IO.File.ReadAllText(AbsolutePath);
}
} else {
string fullPath = System.IO.Path.Combine(App.VideoLibraryPath(), PersistentPath);
m_VideoPlayer.url = $"file:///{fullPath}";
}
m_VideoPlayer.isLooping = true;
m_VideoPlayer.renderMode = VideoRenderMode.APIOnly;
m_VideoPlayer.skipOnDrop = true;
m_VideoPlayer.audioOutputMode = VideoAudioOutputMode.Direct;
m_VideoPlayer.Prepare();
m_VideoPlayer.errorReceived += OnError;
} catch (Exception ex) {
Debug.LogException(ex);
Error = ex.Message;
yield break;
}
while (!m_VideoPlayer.isPrepared) {
if (Error != null) {
yield break;
}
yield return null;
}
// This code is *super* useful for testing the reference video panel, and I've written it at
// least five times, so I'd like to just leave it here as it may well be useful in the future.
#if false
// Delays the video load by two seconds
for (var wait = DateTime.Now + TimeSpan.FromSeconds(2); wait > DateTime.Now;) {
yield return null;
}
#endif
Width = m_VideoPlayer.width;
Height = m_VideoPlayer.height;
Aspect = Width / (float) Height;
for (int i = 0; i < m_VideoPlayer.audioTrackCount; ++i) {
m_VideoPlayer.SetDirectAudioMute((ushort)i, true);
}
m_VideoPlayer.Play();
if (onCompletion != null) {
onCompletion();
}
}
private void OnError(VideoPlayer player, string error) {
Error = error;
}
public IEnumerator<Null> Initialize() {
Controller thumbnailExtractor = CreateController();
while (!thumbnailExtractor.Initialized) {
if (Error != null) {
thumbnailExtractor.Dispose();
yield break;
}
yield return null;
}
int width, height;
if (Aspect > 1) {
width = 128;
height = Mathf.RoundToInt(width / Aspect);
} else {
height = 128;
width = Mathf.RoundToInt(height * Aspect);
}
// A frame does not always seem to be immediately available, so wait until we've hit at least
// the second frame before continuing.
while (m_VideoPlayer.frame < 1) {
yield return null;
}
// Because the Thumbnail needs to be a Texture2D, we need to do the little dance of copying
// the rendertexture over to the Texture2D.
var rt = RenderTexture.GetTemporary(width, height, 0);
Graphics.Blit(m_VideoPlayer.texture, rt);
Thumbnail = new Texture2D(width, height, TextureFormat.RGB24, false);
var oldActive = RenderTexture.active;
RenderTexture.active = rt;
Thumbnail.ReadPixels(new Rect(0,0, width, height),0, 0 );
RenderTexture.active = oldActive;
Thumbnail.Apply(false);
RenderTexture.ReleaseTemporary(rt);
thumbnailExtractor.Dispose();
IsInitialized = true;
}
public void Dispose() {
if (m_VideoPlayer != null) {
Debug.Assert(m_Controllers.Count > 0,
"There should be controllers if the VideoPlayer is not null.");
foreach (var controller in m_Controllers.ToArray()) {
// Controller.Dispose handles removing itself from m_Controllers, so we don't do it here.
controller.Dispose();
}
}
if (Thumbnail != null) {
UnityEngine.Object.Destroy(Thumbnail);
}
}
public override string ToString() {
return $"{HumanName}: {Width}x{Height} {Aspect}";
}
}
} // namespace TiltBrush
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using CURLAUTH = Interop.Http.CURLAUTH;
using CURLcode = Interop.Http.CURLcode;
using CURLoption = Interop.Http.CURLoption;
using CurlProtocols = Interop.Http.CurlProtocols;
using CURLProxyType = Interop.Http.curl_proxytype;
using SafeCurlHandle = Interop.Http.SafeCurlHandle;
using SafeCurlSListHandle = Interop.Http.SafeCurlSListHandle;
using SafeCallbackHandle = Interop.Http.SafeCallbackHandle;
using SeekCallback = Interop.Http.SeekCallback;
using ReadWriteCallback = Interop.Http.ReadWriteCallback;
using ReadWriteFunction = Interop.Http.ReadWriteFunction;
using SslCtxCallback = Interop.Http.SslCtxCallback;
using DebugCallback = Interop.Http.DebugCallback;
namespace System.Net.Http
{
internal partial class CurlHandler : HttpMessageHandler
{
/// <summary>Provides all of the state associated with a single request/response, referred to as an "easy" request in libcurl parlance.</summary>
private sealed class EasyRequest : TaskCompletionSource<HttpResponseMessage>
{
/// <summary>Maximum content length where we'll use COPYPOSTFIELDS to let libcurl dup the content.</summary>
private const int InMemoryPostContentLimit = 32 * 1024; // arbitrary limit; could be tweaked in the future based on experimentation
/// <summary>Debugging flag used to enable CURLOPT_VERBOSE to dump to stderr when not redirecting it to the event source.</summary>
private static readonly bool s_curlDebugLogging = Environment.GetEnvironmentVariable("CURLHANDLER_DEBUG_VERBOSE") == "true";
internal readonly CurlHandler _handler;
internal readonly MultiAgent _associatedMultiAgent;
internal readonly HttpRequestMessage _requestMessage;
internal readonly CurlResponseMessage _responseMessage;
internal readonly CancellationToken _cancellationToken;
internal Stream _requestContentStream;
internal long? _requestContentStreamStartingPosition;
internal bool _inMemoryPostContent;
internal SafeCurlHandle _easyHandle;
private SafeCurlSListHandle _requestHeaders;
internal SendTransferState _sendTransferState;
internal StrongToWeakReference<EasyRequest> _selfStrongToWeakReference;
private SafeCallbackHandle _callbackHandle;
public EasyRequest(CurlHandler handler, MultiAgent agent, HttpRequestMessage requestMessage, CancellationToken cancellationToken) :
base(TaskCreationOptions.RunContinuationsAsynchronously)
{
Debug.Assert(handler != null, $"Expected non-null {nameof(handler)}");
Debug.Assert(agent != null, $"Expected non-null {nameof(agent)}");
Debug.Assert(requestMessage != null, $"Expected non-null {nameof(requestMessage)}");
_handler = handler;
_associatedMultiAgent = agent;
_requestMessage = requestMessage;
_cancellationToken = cancellationToken;
_responseMessage = new CurlResponseMessage(this);
}
/// <summary>
/// Initialize the underlying libcurl support for this EasyRequest.
/// This is separated out of the constructor so that we can take into account
/// any additional configuration needed based on the request message
/// after the EasyRequest is configured and so that error handling
/// can be better handled in the caller.
/// </summary>
internal void InitializeCurl()
{
// Create the underlying easy handle
SafeCurlHandle easyHandle = Interop.Http.EasyCreate();
if (easyHandle.IsInvalid)
{
throw new OutOfMemoryException();
}
_easyHandle = easyHandle;
EventSourceTrace("Configuring request.");
// Before setting any other options, turn on curl's debug tracing
// if desired. CURLOPT_VERBOSE may also be set subsequently if
// EventSource tracing is enabled.
if (s_curlDebugLogging)
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
}
// Configure the handle
SetUrl();
SetNetworkingOptions();
SetMultithreading();
SetTimeouts();
SetRedirection();
SetVerb();
SetVersion();
SetDecompressionOptions();
SetProxyOptions(_requestMessage.RequestUri);
SetCredentialsOptions(_handler._useDefaultCredentials ? GetDefaultCredentialAndAuth() : _handler.GetCredentials(_requestMessage.RequestUri));
SetCookieOption(_requestMessage.RequestUri);
SetRequestHeaders();
SetSslOptions();
EventSourceTrace("Done configuring request.");
}
public void EnsureResponseMessagePublished()
{
// If the response message hasn't been published yet, do any final processing of it before it is.
if (!Task.IsCompleted)
{
EventSourceTrace("Publishing response message");
// On Windows, if the response was automatically decompressed, Content-Encoding and Content-Length
// headers are removed from the response. Do the same thing here.
DecompressionMethods dm = _handler.AutomaticDecompression;
if (dm != DecompressionMethods.None)
{
HttpContentHeaders contentHeaders = _responseMessage.Content.Headers;
IEnumerable<string> encodings;
if (contentHeaders.TryGetValues(HttpKnownHeaderNames.ContentEncoding, out encodings))
{
foreach (string encoding in encodings)
{
if (((dm & DecompressionMethods.GZip) != 0 && string.Equals(encoding, EncodingNameGzip, StringComparison.OrdinalIgnoreCase)) ||
((dm & DecompressionMethods.Deflate) != 0 && string.Equals(encoding, EncodingNameDeflate, StringComparison.OrdinalIgnoreCase)))
{
contentHeaders.Remove(HttpKnownHeaderNames.ContentEncoding);
contentHeaders.Remove(HttpKnownHeaderNames.ContentLength);
break;
}
}
}
}
}
// Now ensure it's published.
bool completedTask = TrySetResult(_responseMessage);
Debug.Assert(completedTask || Task.IsCompletedSuccessfully,
"If the task was already completed, it should have been completed successfully; " +
"we shouldn't be completing as successful after already completing as failed.");
// If we successfully transitioned it to be completed, we also handed off lifetime ownership
// of the response to the owner of the task. Transition our reference on the EasyRequest
// to be weak instead of strong, so that we don't forcibly keep it alive.
if (completedTask)
{
Debug.Assert(_selfStrongToWeakReference != null, "Expected non-null wrapper");
_selfStrongToWeakReference.MakeWeak();
}
}
public void CleanupAndFailRequest(Exception error)
{
try
{
Cleanup();
}
catch (Exception exc)
{
// This would only happen in an aggregious case, such as a Stream failing to seek when
// it claims to be able to, but in case something goes very wrong, make sure we don't
// lose the exception information.
error = new AggregateException(error, exc);
}
finally
{
FailRequest(error);
}
}
public void FailRequest(Exception error)
{
Debug.Assert(error != null, "Expected non-null exception");
EventSourceTrace("Failing request: {0}", error);
var oce = error as OperationCanceledException;
if (oce != null)
{
TrySetCanceled(oce.CancellationToken);
}
else
{
if (error is InvalidOperationException || error is IOException || error is CurlException || error == null)
{
error = CreateHttpRequestException(error);
}
TrySetException(error);
}
// There's not much we can reasonably assert here about the result of TrySet*.
// It's possible that the task wasn't yet completed (e.g. a failure while initiating the request),
// it's possible that the task was already completed as success (e.g. a failure sending back the response),
// and it's possible that the task was already completed as failure (e.g. we handled the exception and
// faulted the task, but then tried to fault it again while finishing processing in the main loop).
// Make sure the exception is available on the response stream so that it's propagated
// from any attempts to read from the stream.
_responseMessage.ResponseStream.SignalComplete(error);
}
public void Cleanup() // not called Dispose because the request may still be in use after it's cleaned up
{
// Don't dispose of the ResponseMessage.ResponseStream as it may still be in use
// by code reading data stored in the stream. Also don't dispose of the request content
// stream; that'll be handled by the disposal of the request content by the HttpClient,
// and doing it here prevents reuse by an intermediate handler sitting between the client
// and this handler.
// However, if we got an original position for the request stream, we seek back to that position,
// for the corner case where the stream does get reused before it's disposed by the HttpClient
// (if the same request object is used multiple times from an intermediate handler, we'll be using
// ReadAsStreamAsync, which on the same request object will return the same stream object, which
// we've already advanced).
if (_requestContentStream != null && _requestContentStream.CanSeek)
{
Debug.Assert(_requestContentStreamStartingPosition.HasValue, "The stream is seekable, but we don't have a starting position?");
_requestContentStream.Position = _requestContentStreamStartingPosition.GetValueOrDefault();
}
// Dispose of the underlying easy handle. We're no longer processing it.
_easyHandle?.Dispose();
// Dispose of the request headers if we had any. We had to keep this handle
// alive as long as the easy handle was using it. We didn't need to do any
// ref counting on the safe handle, though, as the only processing happens
// in Process, which ensures the handle will be rooted while libcurl is
// doing any processing that assumes it's valid.
_requestHeaders?.Dispose();
// Dispose native callback resources
_callbackHandle?.Dispose();
// Release any send transfer state, which will return its buffer to the pool
_sendTransferState?.Dispose();
}
private void SetUrl()
{
Uri requestUri = _requestMessage.RequestUri;
long scopeId;
if (IsLinkLocal(requestUri, out scopeId))
{
// Uri.AbsoluteUri doesn't include the ScopeId/ZoneID, so if it is link-local,
// we separately pass the scope to libcurl.
EventSourceTrace("ScopeId: {0}", scopeId);
SetCurlOption(CURLoption.CURLOPT_ADDRESS_SCOPE, scopeId);
}
EventSourceTrace("Url: {0}", requestUri);
string idnHost = requestUri.IdnHost;
string url = requestUri.Host == idnHost ?
requestUri.AbsoluteUri :
new UriBuilder(requestUri) { Host = idnHost }.Uri.AbsoluteUri;
SetCurlOption(CURLoption.CURLOPT_URL, url);
SetCurlOption(CURLoption.CURLOPT_PROTOCOLS, (long)(CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS));
}
private static bool IsLinkLocal(Uri url, out long scopeId)
{
IPAddress ip;
if (IPAddress.TryParse(url.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal)
{
scopeId = ip.ScopeId;
return true;
}
scopeId = 0;
return false;
}
private void SetNetworkingOptions()
{
// Disable the TCP Nagle algorithm. It's disabled by default starting with libcurl 7.50.2,
// and when enabled has a measurably negative impact on latency in key scenarios
// (e.g. POST'ing small-ish data).
SetCurlOption(CURLoption.CURLOPT_TCP_NODELAY, 1L);
}
private void SetMultithreading()
{
SetCurlOption(CURLoption.CURLOPT_NOSIGNAL, 1L);
}
private void SetTimeouts()
{
// Set timeout limit on the connect phase.
SetCurlOption(CURLoption.CURLOPT_CONNECTTIMEOUT_MS, int.MaxValue);
// Override the default DNS cache timeout. libcurl defaults to a 1 minute
// timeout, but we extend that to match the Windows timeout of 10 minutes.
const int DnsCacheTimeoutSeconds = 10 * 60;
SetCurlOption(CURLoption.CURLOPT_DNS_CACHE_TIMEOUT, DnsCacheTimeoutSeconds);
}
private void SetRedirection()
{
if (!_handler._automaticRedirection)
{
return;
}
SetCurlOption(CURLoption.CURLOPT_FOLLOWLOCATION, 1L);
CurlProtocols redirectProtocols = string.Equals(_requestMessage.RequestUri.Scheme, UriSchemeHttps, StringComparison.OrdinalIgnoreCase) ?
CurlProtocols.CURLPROTO_HTTPS : // redirect only to another https
CurlProtocols.CURLPROTO_HTTP | CurlProtocols.CURLPROTO_HTTPS; // redirect to http or to https
SetCurlOption(CURLoption.CURLOPT_REDIR_PROTOCOLS, (long)redirectProtocols);
SetCurlOption(CURLoption.CURLOPT_MAXREDIRS, _handler._maxAutomaticRedirections);
EventSourceTrace("Max automatic redirections: {0}", _handler._maxAutomaticRedirections);
}
/// <summary>
/// When a Location header is received along with a 3xx status code, it's an indication
/// that we're likely to redirect. Prepare the easy handle in case we do.
/// </summary>
internal void SetPossibleRedirectForLocationHeader(string location)
{
// Reset cookies in case we redirect. Below we'll set new cookies for the
// new location if we have any.
if (_handler._useCookie)
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, IntPtr.Zero);
}
// Parse the location string into a relative or absolute Uri, then combine that
// with the current request Uri to get the new location.
var updatedCredentials = default(KeyValuePair<NetworkCredential, CURLAUTH>);
Uri newUri;
if (Uri.TryCreate(_requestMessage.RequestUri, location.Trim(), out newUri))
{
// Just as with WinHttpHandler, for security reasons, we drop the server credential if it is
// anything other than a CredentialCache. We allow credentials in a CredentialCache since they
// are specifically tied to URIs.
updatedCredentials = _handler._useDefaultCredentials ?
GetDefaultCredentialAndAuth() :
GetCredentials(newUri, _handler.Credentials as CredentialCache, s_orderedAuthTypes);
// Reset proxy - it is possible that the proxy has different credentials for the new URI
SetProxyOptions(newUri);
// Set up new cookies
if (_handler._useCookie)
{
SetCookieOption(newUri);
}
}
// Set up the new credentials, either for the new Uri if we were able to get it,
// or to empty creds if we couldn't.
SetCredentialsOptions(updatedCredentials);
// Set the headers again. This is a workaround for libcurl's limitation in handling
// headers with empty values.
SetRequestHeaders();
}
private void SetContentLength(CURLoption lengthOption)
{
Debug.Assert(lengthOption == CURLoption.CURLOPT_POSTFIELDSIZE || lengthOption == CURLoption.CURLOPT_INFILESIZE);
if (_requestMessage.Content == null)
{
// Tell libcurl there's no data to be sent.
SetCurlOption(lengthOption, 0L);
return;
}
long? contentLengthOpt = _requestMessage.Content.Headers.ContentLength;
if (contentLengthOpt != null)
{
long contentLength = contentLengthOpt.GetValueOrDefault();
if (contentLength <= int.MaxValue)
{
// Tell libcurl how much data we expect to send.
SetCurlOption(lengthOption, contentLength);
}
else
{
// Similarly, tell libcurl how much data we expect to send. However,
// as the amount is larger than a 32-bit value, switch to the "_LARGE"
// equivalent libcurl options.
SetCurlOption(
lengthOption == CURLoption.CURLOPT_INFILESIZE ? CURLoption.CURLOPT_INFILESIZE_LARGE : CURLoption.CURLOPT_POSTFIELDSIZE_LARGE,
contentLength);
}
EventSourceTrace("Set content length: {0}", contentLength);
return;
}
// There is content but we couldn't determine its size. Don't set anything.
}
private void SetVerb()
{
EventSourceTrace<string>("Verb: {0}", _requestMessage.Method.Method);
if (_requestMessage.Method == HttpMethod.Put)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
SetContentLength(CURLoption.CURLOPT_INFILESIZE);
}
else if (_requestMessage.Method == HttpMethod.Head)
{
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else if (_requestMessage.Method == HttpMethod.Post)
{
SetCurlOption(CURLoption.CURLOPT_POST, 1L);
// Set the content length if we have one available. We must set POSTFIELDSIZE before setting
// COPYPOSTFIELDS, as the setting of COPYPOSTFIELDS uses the size to know how much data to read
// out; if POSTFIELDSIZE is not done before, COPYPOSTFIELDS will look for a null terminator, and
// we don't necessarily have one.
SetContentLength(CURLoption.CURLOPT_POSTFIELDSIZE);
// For most content types and most HTTP methods, we use a callback that lets libcurl
// get data from us if/when it wants it. However, as an optimization, for POSTs that
// use content already known to be entirely in memory, we hand that data off to libcurl
// ahead of time. This not only saves on costs associated with all of the async transfer
// between the content and libcurl, it also lets libcurl do larger writes that can, for
// example, enable fewer packets to be sent on the wire.
var inMemContent = _requestMessage.Content as ByteArrayContent;
ArraySegment<byte> contentSegment;
if (inMemContent != null &&
inMemContent.TryGetBuffer(out contentSegment) &&
contentSegment.Count <= InMemoryPostContentLimit) // skip if we'd be forcing libcurl to allocate/copy a large buffer
{
// Only pre-provide the content if the content still has its ContentLength
// and if that length matches the segment. If it doesn't, something has been overridden,
// and we should rely on reading from the content stream to get the data.
long? contentLength = inMemContent.Headers.ContentLength;
if (contentLength.HasValue && contentLength.GetValueOrDefault() == contentSegment.Count)
{
_inMemoryPostContent = true;
// Debug double-check array segment; this should all have been validated by the ByteArrayContent
Debug.Assert(contentSegment.Array != null, "Expected non-null byte content array");
Debug.Assert(contentSegment.Count >= 0, $"Expected non-negative byte content count {contentSegment.Count}");
Debug.Assert(contentSegment.Offset >= 0, $"Expected non-negative byte content offset {contentSegment.Offset}");
Debug.Assert(contentSegment.Array.Length - contentSegment.Offset >= contentSegment.Count,
$"Expected offset {contentSegment.Offset} + count {contentSegment.Count} to be within array length {contentSegment.Array.Length}");
// Hand the data off to libcurl with COPYPOSTFIELDS for it to copy out the data. (The alternative
// is to use POSTFIELDS, which would mean we'd need to pin the array in the ByteArrayContent for the
// duration of the request. Often with a ByteArrayContent, the data will be small and the copy cheap.)
unsafe
{
fixed (byte* inMemContentPtr = contentSegment.Array)
{
SetCurlOption(CURLoption.CURLOPT_COPYPOSTFIELDS, new IntPtr(inMemContentPtr + contentSegment.Offset));
EventSourceTrace("Set post fields rather than using send content callback");
}
}
}
}
}
else if (_requestMessage.Method == HttpMethod.Trace)
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
SetCurlOption(CURLoption.CURLOPT_NOBODY, 1L);
}
else
{
SetCurlOption(CURLoption.CURLOPT_CUSTOMREQUEST, _requestMessage.Method.Method);
if (_requestMessage.Content != null)
{
SetCurlOption(CURLoption.CURLOPT_UPLOAD, 1L);
SetContentLength(CURLoption.CURLOPT_INFILESIZE);
}
}
}
private void SetVersion()
{
Version v = _requestMessage.Version;
if (v != null)
{
// Try to use the requested version, if a known version was explicitly requested.
// If an unknown version was requested, we simply use libcurl's default.
var curlVersion =
(v.Major == 1 && v.Minor == 1) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_1 :
(v.Major == 1 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_1_0 :
(v.Major == 2 && v.Minor == 0) ? Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_2_0 :
Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE;
if (curlVersion != Interop.Http.CurlHttpVersion.CURL_HTTP_VERSION_NONE)
{
// Ask libcurl to use the specified version if possible.
CURLcode c = Interop.Http.EasySetOptionLong(_easyHandle, CURLoption.CURLOPT_HTTP_VERSION, (long)curlVersion);
if (c == CURLcode.CURLE_OK)
{
// Success. The requested version will be used.
EventSourceTrace("HTTP version: {0}", v);
}
else if (c == CURLcode.CURLE_UNSUPPORTED_PROTOCOL)
{
// The requested version is unsupported. Fall back to using the default version chosen by libcurl.
EventSourceTrace("Unsupported protocol: {0}", v);
}
else
{
// Some other error. Fail.
ThrowIfCURLEError(c);
}
}
}
}
private void SetDecompressionOptions()
{
if (!_handler.SupportsAutomaticDecompression)
{
return;
}
DecompressionMethods autoDecompression = _handler.AutomaticDecompression;
bool gzip = (autoDecompression & DecompressionMethods.GZip) != 0;
bool deflate = (autoDecompression & DecompressionMethods.Deflate) != 0;
if (gzip || deflate)
{
string encoding = (gzip && deflate) ? EncodingNameGzip + "," + EncodingNameDeflate :
gzip ? EncodingNameGzip :
EncodingNameDeflate;
SetCurlOption(CURLoption.CURLOPT_ACCEPT_ENCODING, encoding);
EventSourceTrace<string>("Encoding: {0}", encoding);
}
}
internal void SetProxyOptions(Uri requestUri)
{
if (!_handler._useProxy)
{
// Explicitly disable the use of a proxy. This will prevent libcurl from using
// any proxy, including ones set via environment variable.
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("UseProxy false, disabling proxy");
return;
}
if (_handler.Proxy == null)
{
// UseProxy was true, but Proxy was null. Let libcurl do its default handling,
// which includes checking the http_proxy environment variable.
EventSourceTrace("UseProxy true, Proxy null, using default proxy");
// Since that proxy set in an environment variable might require a username and password,
// use the default proxy credentials if there are any. Currently only NetworkCredentials
// are used, as we can't query by the proxy Uri, since we don't know it.
SetProxyCredentials(_handler.DefaultProxyCredentials as NetworkCredential);
return;
}
// Custom proxy specified.
Uri proxyUri;
try
{
// Should we bypass a proxy for this URI?
if (_handler.Proxy.IsBypassed(requestUri))
{
SetCurlOption(CURLoption.CURLOPT_PROXY, string.Empty);
EventSourceTrace("Proxy's IsBypassed returned true, bypassing proxy");
return;
}
// Get the proxy Uri for this request.
proxyUri = _handler.Proxy.GetProxy(requestUri);
if (proxyUri == null)
{
EventSourceTrace("GetProxy returned null, using default.");
return;
}
}
catch (PlatformNotSupportedException)
{
// WebRequest.DefaultWebProxy throws PlatformNotSupportedException,
// in which case we should use the default rather than the custom proxy.
EventSourceTrace("PlatformNotSupportedException from proxy, using default");
return;
}
// Configure libcurl with the gathered proxy information
// uri.AbsoluteUri/ToString() omit IPv6 scope IDs. SerializationInfoString ensures these details
// are included, but does not properly handle international hosts. As a workaround we check whether
// the host is a link-local IP address, and based on that either return the SerializationInfoString
// or the AbsoluteUri. (When setting the request Uri itself, we instead use CURLOPT_ADDRESS_SCOPE to
// set the scope id and the url separately, avoiding these issues and supporting versions of libcurl
// prior to v7.37 that don't support parsing scope IDs out of the url's host. As similar feature
// doesn't exist for proxies.)
IPAddress ip;
string proxyUrl = IPAddress.TryParse(proxyUri.DnsSafeHost, out ip) && ip.IsIPv6LinkLocal ?
proxyUri.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped) :
proxyUri.AbsoluteUri;
EventSourceTrace<string>("Proxy: {0}", proxyUrl);
SetCurlOption(CURLoption.CURLOPT_PROXYTYPE, (long)CURLProxyType.CURLPROXY_HTTP);
SetCurlOption(CURLoption.CURLOPT_PROXY, proxyUrl);
SetCurlOption(CURLoption.CURLOPT_PROXYPORT, proxyUri.Port);
KeyValuePair<NetworkCredential, CURLAUTH> credentialScheme = GetCredentials(
proxyUri, _handler.Proxy.Credentials, s_orderedAuthTypes);
SetProxyCredentials(credentialScheme.Key);
}
private void SetProxyCredentials(NetworkCredential credentials)
{
if (credentials == CredentialCache.DefaultCredentials)
{
EventSourceTrace("DefaultCredentials set for proxy. Skipping.");
}
else if (credentials != null)
{
if (string.IsNullOrEmpty(credentials.UserName))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "UserName");
}
// Unlike normal credentials, proxy credentials are URL decoded by libcurl, so we URL encode
// them in order to allow, for example, a colon in the username.
string credentialText = string.IsNullOrEmpty(credentials.Domain) ?
WebUtility.UrlEncode(credentials.UserName) + ":" + WebUtility.UrlEncode(credentials.Password) :
string.Format("{2}\\{0}:{1}", WebUtility.UrlEncode(credentials.UserName), WebUtility.UrlEncode(credentials.Password), WebUtility.UrlEncode(credentials.Domain));
EventSourceTrace("Proxy credentials set.");
SetCurlOption(CURLoption.CURLOPT_PROXYUSERPWD, credentialText);
}
}
internal void SetCredentialsOptions(KeyValuePair<NetworkCredential, CURLAUTH> credentialSchemePair)
{
if (credentialSchemePair.Key == null)
{
EventSourceTrace("Credentials cleared.");
SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero);
SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero);
return;
}
NetworkCredential credentials = credentialSchemePair.Key;
CURLAUTH authScheme = credentialSchemePair.Value;
string userName = string.IsNullOrEmpty(credentials.Domain) ?
credentials.UserName :
credentials.Domain + "\\" + credentials.UserName;
SetCurlOption(CURLoption.CURLOPT_USERNAME, userName);
SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, (long)authScheme);
if (credentials.Password != null)
{
SetCurlOption(CURLoption.CURLOPT_PASSWORD, credentials.Password);
}
EventSourceTrace("Credentials set.");
}
private static KeyValuePair<NetworkCredential, CURLAUTH> GetDefaultCredentialAndAuth() =>
new KeyValuePair<NetworkCredential, CURLAUTH>(CredentialCache.DefaultNetworkCredentials, CURLAUTH.Negotiate);
internal void SetCookieOption(Uri uri)
{
if (!_handler._useCookie)
{
return;
}
string cookieValues = _handler.CookieContainer.GetCookieHeader(uri);
if (!string.IsNullOrEmpty(cookieValues))
{
SetCurlOption(CURLoption.CURLOPT_COOKIE, cookieValues);
EventSourceTrace<string>("Cookies: {0}", cookieValues);
}
}
internal void SetRequestHeaders()
{
var slist = new SafeCurlSListHandle();
// Add content request headers
if (_requestMessage.Content != null)
{
SetChunkedModeForSend(_requestMessage);
AddRequestHeaders(_requestMessage.Content.Headers, slist);
if (_requestMessage.Content.Headers.ContentType == null)
{
// Remove the Content-Type header libcurl adds by default.
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoContentType));
}
}
// Add request headers
AddRequestHeaders(_requestMessage.Headers, slist);
// Since libcurl always adds a Transfer-Encoding header, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.TransferEncodingChunked.HasValue &&
!_requestMessage.Headers.TransferEncodingChunked.Value)
{
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoTransferEncoding));
}
// Since libcurl adds an Expect header if it sees enough post data, we need to explicitly block
// it if caller specifically does not want to set the header
if (_requestMessage.Headers.ExpectContinue.HasValue &&
!_requestMessage.Headers.ExpectContinue.Value)
{
ThrowOOMIfFalse(Interop.Http.SListAppend(slist, NoExpect));
}
if (!slist.IsInvalid)
{
SafeCurlSListHandle prevList = _requestHeaders;
_requestHeaders = slist;
SetCurlOption(CURLoption.CURLOPT_HTTPHEADER, slist);
prevList?.Dispose();
}
else
{
slist.Dispose();
}
}
private void SetSslOptions()
{
// SSL Options should be set regardless of the type of the original request,
// in case an http->https redirection occurs.
//
// While this does slow down the theoretical best path of the request the code
// to decide that we need to register the callback is more complicated than, and
// potentially more expensive than, just always setting the callback.
SslProvider.SetSslOptions(this, _handler.ClientCertificateOptions);
}
internal bool ServerCertificateValidationCallbackAcceptsAll => ReferenceEquals(
_handler.ServerCertificateValidationCallback,
HttpClientHandler.DangerousAcceptAnyServerCertificateValidator);
internal void SetCurlCallbacks(
IntPtr easyGCHandle,
ReadWriteCallback receiveHeadersCallback,
ReadWriteCallback sendCallback,
SeekCallback seekCallback,
ReadWriteCallback receiveBodyCallback,
DebugCallback debugCallback)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
// Add callback for processing headers
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Header,
receiveHeadersCallback,
easyGCHandle,
ref _callbackHandle);
ThrowOOMIfInvalid(_callbackHandle);
// If we're sending data as part of the request and it wasn't already added as
// in-memory data, add callbacks for sending request data.
if (!_inMemoryPostContent && _requestMessage.Content != null)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Read,
sendCallback,
easyGCHandle,
ref _callbackHandle);
Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers");
Interop.Http.RegisterSeekCallback(
_easyHandle,
seekCallback,
easyGCHandle,
ref _callbackHandle);
Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers");
}
// If we're expecting any data in response, add a callback for receiving body data
if (_requestMessage.Method != HttpMethod.Head)
{
Interop.Http.RegisterReadWriteCallback(
_easyHandle,
ReadWriteFunction.Write,
receiveBodyCallback,
easyGCHandle,
ref _callbackHandle);
Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers");
}
if (NetEventSource.IsEnabled)
{
SetCurlOption(CURLoption.CURLOPT_VERBOSE, 1L);
CURLcode curlResult = Interop.Http.RegisterDebugCallback(
_easyHandle,
debugCallback,
easyGCHandle,
ref _callbackHandle);
Debug.Assert(!_callbackHandle.IsInvalid, $"Should have been allocated (or failed) when originally adding handlers");
if (curlResult != CURLcode.CURLE_OK)
{
EventSourceTrace("Failed to register debug callback.");
}
}
}
internal CURLcode SetSslCtxCallback(SslCtxCallback callback, IntPtr userPointer)
{
if (_callbackHandle == null)
{
_callbackHandle = new SafeCallbackHandle();
}
return Interop.Http.RegisterSslCtxCallback(_easyHandle, callback, userPointer, ref _callbackHandle);
}
private static void AddRequestHeaders(HttpHeaders headers, SafeCurlSListHandle handle)
{
foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
{
if (string.Equals(header.Key, HttpKnownHeaderNames.ContentLength, StringComparison.OrdinalIgnoreCase))
{
// avoid overriding libcurl's handling via INFILESIZE/POSTFIELDSIZE
continue;
}
string headerKeyAndValue;
string[] values = header.Value as string[];
Debug.Assert(values != null, "Implementation detail, but expected Value to be a string[]");
if (values != null && values.Length < 2)
{
// 0 or 1 values
headerKeyAndValue = values.Length == 0 || string.IsNullOrEmpty(values[0]) ?
header.Key + ";" : // semicolon used by libcurl to denote empty value that should be sent
header.Key + ": " + values[0];
}
else
{
// Either Values wasn't a string[], or it had 2 or more items. Both are handled by GetHeaderString.
string headerValue = headers.GetHeaderString(header.Key);
headerKeyAndValue = string.IsNullOrEmpty(headerValue) ?
header.Key + ";" : // semicolon needed by libcurl; see above
header.Key + ": " + headerValue;
}
ThrowOOMIfFalse(Interop.Http.SListAppend(handle, headerKeyAndValue));
}
}
internal void SetCurlOption(CURLoption option, string value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionString(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, long value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionLong(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, IntPtr value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
internal void SetCurlOption(CURLoption option, SafeHandle value)
{
ThrowIfCURLEError(Interop.Http.EasySetOptionPointer(_easyHandle, option, value));
}
private static void ThrowOOMIfFalse(bool appendResult)
{
if (!appendResult)
{
ThrowOOM();
}
}
private static void ThrowOOMIfInvalid(SafeHandle handle)
{
if (handle.IsInvalid)
{
ThrowOOM();
}
}
private static void ThrowOOM()
{
throw CreateHttpRequestException(new CurlException((int)CURLcode.CURLE_OUT_OF_MEMORY, isMulti: false));
}
internal sealed class SendTransferState : IDisposable
{
internal byte[] Buffer { get; private set; }
internal int Offset { get; set; }
internal int Count { get; set; }
internal Task<int> Task { get; private set; }
public SendTransferState(int bufferLength)
{
Debug.Assert(bufferLength > 0 && bufferLength <= MaxRequestBufferSize, $"Expected 0 < bufferLength <= {MaxRequestBufferSize}, got {bufferLength}");
Buffer = ArrayPool<byte>.Shared.Rent(bufferLength);
}
public void Dispose()
{
byte[] b = Buffer;
if (b != null)
{
Buffer = null;
ArrayPool<byte>.Shared.Return(b);
}
}
public void SetTaskOffsetCount(Task<int> task, int offset, int count)
{
Debug.Assert(offset >= 0, "Offset should never be negative");
Debug.Assert(count >= 0, "Count should never be negative");
Debug.Assert(offset <= count, "Offset should never be greater than count");
Task = task;
Offset = offset;
Count = count;
}
}
internal void StoreLastEffectiveUri()
{
IntPtr urlCharPtr; // do not free; will point to libcurl private memory
CURLcode urlResult = Interop.Http.EasyGetInfoPointer(_easyHandle, Interop.Http.CURLINFO.CURLINFO_EFFECTIVE_URL, out urlCharPtr);
if (urlResult == CURLcode.CURLE_OK && urlCharPtr != IntPtr.Zero)
{
string url = Marshal.PtrToStringAnsi(urlCharPtr);
if (url != _requestMessage.RequestUri.OriginalString)
{
Uri finalUri;
if (Uri.TryCreate(url, UriKind.Absolute, out finalUri))
{
_requestMessage.RequestUri = finalUri;
}
}
return;
}
Debug.Fail("Expected to be able to get the last effective Uri from libcurl");
}
private void EventSourceTrace<TArg0>(string formatMessage, TArg0 arg0, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(formatMessage, arg0, easy: this, memberName: memberName);
}
private void EventSourceTrace(string message, [CallerMemberName] string memberName = null)
{
CurlHandler.EventSourceTrace(message, easy: this, memberName: memberName);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// a set of lightweight static helpers for lazy initialization.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
namespace System.Threading
{
/// <summary>
/// Provides lazy initialization routines.
/// </summary>
/// <remarks>
/// These routines avoid needing to allocate a dedicated, lazy-initialization instance, instead using
/// references to ensure targets have been initialized as they are accessed.
/// </remarks>
public static class LazyInitializer
{
/// <summary>
/// Initializes a target reference type with the type's default constructor if the target has not
/// already been initialized.
/// </summary>
/// <typeparam name="T">The refence type of the reference to be initialized.</typeparam>
/// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not
/// already been initialized.</param>
/// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
/// <exception cref="T:System.MissingMemberException">Type <typeparamref name="T"/> does not have a default
/// constructor.</exception>
/// <exception cref="T:System.MemberAccessException">
/// Permissions to access the constructor of type <typeparamref name="T"/> were missing.
/// </exception>
/// <remarks>
/// <para>
/// This method may only be used on reference types. To ensure initialization of value
/// types, see other overloads of EnsureInitialized.
/// </para>
/// <para>
/// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
/// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
/// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
/// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
public static T EnsureInitialized<T>(ref T target) where T : class =>
Volatile.Read<T>(ref target) ?? EnsureInitializedCore<T>(ref target, LazyHelpers<T>.ActivatorFactorySelectorFunc);
/// <summary>
/// Initializes a target reference type using the specified function if it has not already been
/// initialized.
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The reference of type <typeparamref name="T"/> to initialize if it has not
/// already been initialized.</param>
/// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the
/// reference.</param>
/// <returns>The initialized reference of type <typeparamref name="T"/>.</returns>
/// <exception cref="T:System.MissingMemberException">Type <typeparamref name="T"/> does not have a
/// default constructor.</exception>
/// <exception cref="T:System.InvalidOperationException"><paramref name="valueFactory"/> returned
/// null.</exception>
/// <remarks>
/// <para>
/// This method may only be used on reference types, and <paramref name="valueFactory"/> may
/// not return a null reference (Nothing in Visual Basic). To ensure initialization of value types or
/// to allow null reference types, see other overloads of EnsureInitialized.
/// </para>
/// <para>
/// This method may be used concurrently by multiple threads to initialize <paramref name="target"/>.
/// In the event that multiple threads access this method concurrently, multiple instances of <typeparamref name="T"/>
/// may be created, but only one will be stored into <paramref name="target"/>. In such an occurrence, this method will not dispose of the
/// objects that were not stored. If such objects must be disposed, it is up to the caller to determine
/// if an object was not used and to then dispose of the object appropriately.
/// </para>
/// </remarks>
public static T EnsureInitialized<T>(ref T target, Func<T> valueFactory) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore<T>(ref target, valueFactory);
/// <summary>
/// Initialize the target using the given delegate (slow path).
/// </summary>
/// <typeparam name="T">The reference type of the reference to be initialized.</typeparam>
/// <param name="target">The variable that need to be initialized</param>
/// <param name="valueFactory">The delegate that will be executed to initialize the target</param>
/// <returns>The initialized variable</returns>
private static T EnsureInitializedCore<T>(ref T target, Func<T> valueFactory) where T : class
{
T value = valueFactory();
if (value == null)
{
throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
}
Interlocked.CompareExchange(ref target, value, null);
Debug.Assert(target != null);
return target;
}
/// <summary>
/// Initializes a target reference or value type with its default constructor if it has not already
/// been initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized.</typeparam>
/// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
/// has not already been initialized.</param>
/// <param name="initialized">A reference to a boolean that determines whether the target has already
/// been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock)
{
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
}
return EnsureInitializedCore<T>(ref target, ref initialized, ref syncLock, LazyHelpers<T>.ActivatorFactorySelectorFunc);
}
/// <summary>
/// Initializes a target reference or value type with a specified function if it has not already been
/// initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized.</typeparam>
/// <param name="target">A reference or value of type <typeparamref name="T"/> to initialize if it
/// has not already been initialized.</param>
/// <param name="initialized">A reference to a boolean that determines whether the target has already
/// been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the
/// reference or value.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
{
// Fast path.
if (Volatile.Read(ref initialized))
{
return target;
}
return EnsureInitializedCore<T>(ref target, ref initialized, ref syncLock, valueFactory);
}
/// <summary>
/// Ensure the lock object is intialized.
/// </summary>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <returns>Initialized lock object.</returns>
private static object EnsureLockInitialized(ref object syncLock) =>
syncLock ??
Interlocked.CompareExchange(ref syncLock, new object(), null) ??
syncLock;
/// <summary>
/// Initializes a target reference type with a specified function if it has not already been initialized.
/// </summary>
/// <typeparam name="T">The type of the reference to be initialized. Has to be reference type.</typeparam>
/// <param name="target">A reference of type <typeparamref name="T"/> to initialize if it has not already been initialized.</param>
/// <param name="syncLock">A reference to an object used as the mutually exclusive lock for initializing
/// <paramref name="target"/>. If <paramref name="syncLock"/> is null, a new object will be instantiated.</param>
/// <param name="valueFactory">The <see cref="T:System.Func{T}"/> invoked to initialize the reference.</param>
/// <returns>The initialized value of type <typeparamref name="T"/>.</returns>
public static T EnsureInitialized<T>(ref T target, ref object syncLock, Func<T> valueFactory) where T : class =>
Volatile.Read(ref target) ?? EnsureInitializedCore<T>(ref target, ref syncLock, valueFactory);
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload permits nulls
/// and also works for value type targets. Uses the supplied function to create the value.
/// </summary>
/// <typeparam name="T">The type of target.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="initialized">A reference to a location tracking whether the target has been initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>(ref T target, ref bool initialized, ref object syncLock, Func<T> valueFactory)
{
// Lazily initialize the lock if necessary and, then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (!Volatile.Read(ref initialized))
{
target = valueFactory();
Volatile.Write(ref initialized, true);
}
}
return target;
}
/// <summary>
/// Ensure the target is initialized and return the value (slow path). This overload works only for reference type targets.
/// Uses the supplied function to create the value.
/// </summary>
/// <typeparam name="T">The type of target. Has to be reference type.</typeparam>
/// <param name="target">A reference to the target to be initialized.</param>
/// <param name="syncLock">A reference to a location containing a mutual exclusive lock. If <paramref name="syncLock"/> is null,
/// a new object will be instantiated.</param>
/// <param name="valueFactory">
/// The <see cref="T:System.Func{T}"/> to invoke in order to produce the lazily-initialized value.
/// </param>
/// <returns>The initialized object.</returns>
private static T EnsureInitializedCore<T>(ref T target, ref object syncLock, Func<T> valueFactory) where T : class
{
// Lazily initialize the lock if necessary and, then double check if initialization is still required.
lock (EnsureLockInitialized(ref syncLock))
{
if (Volatile.Read(ref target) == null)
{
Volatile.Write(ref target, valueFactory());
if (target == null)
{
throw new InvalidOperationException(SR.Lazy_StaticInit_InvalidOperation);
}
}
}
return target;
}
}
// Caches the activation selector function to avoid delegate allocations.
internal static class LazyHelpers<T>
{
// internal static Func<T> s_activatorFactorySelector = new Func<T>(ActivatorFactorySelector);
internal static Func<T> ActivatorFactorySelectorFunc { get { return ActivatorFactorySelector; } }
private static T ActivatorFactorySelector()
{
try
{
return Activator.CreateInstance<T>();
}
catch (MissingMemberException)
{
throw new MissingMemberException(SR.Lazy_CreateValue_NoParameterlessCtorForT);
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Globalization.DateTimeFormatInfo.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Globalization
{
sealed public partial class DateTimeFormatInfo : ICloneable, IFormatProvider
{
#region Methods and constructors
public Object Clone()
{
return default(Object);
}
public DateTimeFormatInfo()
{
}
public string GetAbbreviatedDayName(DayOfWeek dayofweek)
{
return default(string);
}
public string GetAbbreviatedEraName(int era)
{
return default(string);
}
public string GetAbbreviatedMonthName(int month)
{
return default(string);
}
public string[] GetAllDateTimePatterns(char format)
{
return default(string[]);
}
public string[] GetAllDateTimePatterns()
{
Contract.Ensures(Contract.Result<string[]>() != null);
return default(string[]);
}
public string GetDayName(DayOfWeek dayofweek)
{
return default(string);
}
public int GetEra(string eraName)
{
Contract.Ensures(-1 <= Contract.Result<int>());
return default(int);
}
public string GetEraName(int era)
{
return default(string);
}
public Object GetFormat(Type formatType)
{
return default(Object);
}
public static System.Globalization.DateTimeFormatInfo GetInstance(IFormatProvider provider)
{
return default(System.Globalization.DateTimeFormatInfo);
}
public string GetMonthName(int month)
{
return default(string);
}
public string GetShortestDayName(DayOfWeek dayOfWeek)
{
return default(string);
}
public static System.Globalization.DateTimeFormatInfo ReadOnly(System.Globalization.DateTimeFormatInfo dtfi)
{
Contract.Ensures(Contract.Result<System.Globalization.DateTimeFormatInfo>() != null);
return default(System.Globalization.DateTimeFormatInfo);
}
public void SetAllDateTimePatterns(string[] patterns, char format)
{
}
#endregion
#region Properties and indexers
public string[] AbbreviatedDayNames
{
get
{
return default(string[]);
}
set
{
}
}
public string[] AbbreviatedMonthGenitiveNames
{
get
{
return default(string[]);
}
set
{
}
}
public string[] AbbreviatedMonthNames
{
get
{
return default(string[]);
}
set
{
}
}
public string AMDesignator
{
get
{
return default(string);
}
set
{
}
}
public Calendar Calendar
{
get
{
return default(Calendar);
}
set
{
}
}
public CalendarWeekRule CalendarWeekRule
{
get
{
return default(CalendarWeekRule);
}
set
{
}
}
public static System.Globalization.DateTimeFormatInfo CurrentInfo
{
get
{
return default(System.Globalization.DateTimeFormatInfo);
}
}
public string DateSeparator
{
get
{
return default(string);
}
set
{
}
}
public string[] DayNames
{
get
{
return default(string[]);
}
set
{
}
}
public DayOfWeek FirstDayOfWeek
{
get
{
return default(DayOfWeek);
}
set
{
}
}
public string FullDateTimePattern
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
set
{
}
}
public static System.Globalization.DateTimeFormatInfo InvariantInfo
{
get
{
Contract.Ensures(Contract.Result<System.Globalization.DateTimeFormatInfo>() != null);
return default(System.Globalization.DateTimeFormatInfo);
}
}
public bool IsReadOnly
{
get
{
return default(bool);
}
}
public string LongDatePattern
{
get
{
return default(string);
}
set
{
}
}
public string LongTimePattern
{
get
{
return default(string);
}
set
{
}
}
public string MonthDayPattern
{
get
{
return default(string);
}
set
{
}
}
public string[] MonthGenitiveNames
{
get
{
return default(string[]);
}
set
{
}
}
public string[] MonthNames
{
get
{
return default(string[]);
}
set
{
}
}
public string NativeCalendarName
{
get
{
Contract.Requires(this.Calendar != null);
return default(string);
}
}
public string PMDesignator
{
get
{
return default(string);
}
set
{
}
}
public string RFC1123Pattern
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>() == @"ddd, dd MMM yyyy HH':'mm':'ss 'GMT'");
return default(string);
}
}
public string ShortDatePattern
{
get
{
return default(string);
}
set
{
}
}
public string[] ShortestDayNames
{
get
{
return default(string[]);
}
set
{
}
}
public string ShortTimePattern
{
get
{
return default(string);
}
set
{
}
}
public string SortableDateTimePattern
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>() == @"yyyy'-'MM'-'dd'T'HH':'mm':'ss");
return default(string);
}
}
public string TimeSeparator
{
get
{
return default(string);
}
set
{
}
}
public string UniversalSortableDateTimePattern
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>() == @"yyyy'-'MM'-'dd HH':'mm':'ss'Z'");
return default(string);
}
}
public string YearMonthPattern
{
get
{
return default(string);
}
set
{
}
}
#endregion
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Drawing;
using OpenLiveWriter.Interop.Windows;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// Rectangle operation helper.
/// </summary>
public sealed class RectangleHelper
{
/// <summary>
/// Initializes a new instance of the RectangleHelper class.
/// </summary>
private RectangleHelper()
{
}
/// <summary>
/// Creates a rectangle from two points.
/// </summary>
/// <param name="topLeft">Top left point of the rectangle.</param>
/// <param name="bottomRight">Bottom right point of the rectangle.</param>
/// <returns>New Rectangle structure.</returns>
public static Rectangle Create(Point topLeft, Point bottomRight)
{
return new Rectangle(topLeft.X, topLeft.Y, bottomRight.X-topLeft.X, bottomRight.Y-topLeft.Y);
}
/// <summary>
/// Adjusts the specified rectangle structure by the specified x and y amount and returns
/// a new rectangle structure.
/// </summary>
/// <param name="rectangle"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public static Rectangle Adjust(Rectangle rectangle, int x, int y)
{
return new Rectangle( rectangle.X+x,
rectangle.Y+y,
Math.Max(0, rectangle.Width-x),
Math.Max(0, rectangle.Height-y));
}
/// <summary>
/// Returns the top half of the specified rectangle.
/// </summary>
/// <param name="rectangle">The rectangle to return the top half of.</param>
/// <returns>A new rectangle representing the top half of the input rectangle.</returns>
public static Rectangle TopHalf(Rectangle rectangle)
{
return new Rectangle( rectangle.X,
rectangle.Y,
rectangle.Width,
rectangle.Height/2);
}
/// <summary>
/// Returns the bottom half of the specified rectangle.
/// </summary>
/// <param name="rectangle">The rectangle to return the bottom half of.</param>
/// <returns>A new rectangle representing the bottom half of the input rectangle.</returns>
public static Rectangle BottomHalf(Rectangle rectangle)
{
int height = rectangle.Height/2;
return new Rectangle( rectangle.X,
rectangle.Y+height,
rectangle.Width,
rectangle.Height-height);
}
/// <summary>
/// Pins a rectangle to the top-left of another rectangle.
/// </summary>
/// <param name="rectangleToPin">Rectangle to pin.</param>
/// <param name="rectangleToPinTo">Rectangle to pin to.</param>
/// <returns>Pinned rectangle.</returns>
public static Rectangle PinTopLeft(Rectangle rectangleToPin, Rectangle rectangleToPinTo)
{
return new Rectangle( rectangleToPinTo.X,
rectangleToPinTo.Y,
rectangleToPin.Width,
rectangleToPin.Height);
}
/// <summary>
/// Pins a rectangle to the top-right of another rectangle.
/// </summary>
/// <param name="rectangleToPin">Rectangle to pin.</param>
/// <param name="rectangleToPinTo">Rectangle to pin to.</param>
/// <returns>Pinned rectangle.</returns>
public static Rectangle PinTopRight(Rectangle rectangleToPin, Rectangle rectangleToPinTo)
{
return new Rectangle( rectangleToPinTo.Right-rectangleToPin.Width,
rectangleToPinTo.Y,
rectangleToPin.Width,
rectangleToPin.Height);
}
/// <summary>
/// Pins a rectangle to the bottom-right of another rectangle.
/// </summary>
/// <param name="rectangleToPin">Rectangle to pin.</param>
/// <param name="rectangleToPinTo">Rectangle to pin to.</param>
/// <returns>Pinned rectangle.</returns>
public static Rectangle PinBottomRight(Rectangle rectangleToPin, Rectangle rectangleToPinTo)
{
return new Rectangle( rectangleToPinTo.Right-rectangleToPin.Width,
rectangleToPinTo.Bottom-rectangleToPin.Height,
rectangleToPin.Width,
rectangleToPin.Height);
}
/// <summary>
/// Pins a rectangle to the bottom-left of another rectangle.
/// </summary>
/// <param name="rectangleToPin">Rectangle to pin.</param>
/// <param name="rectangleToPinTo">Rectangle to pin to.</param>
/// <returns>Pinned rectangle.</returns>
public static Rectangle PinBottomLeft(Rectangle rectangleToPin, Rectangle rectangleToPinTo)
{
return new Rectangle( rectangleToPinTo.X,
rectangleToPinTo.Bottom-rectangleToPin.Height,
rectangleToPin.Width,
rectangleToPin.Height);
}
/// <summary>
/// Convert a Win32 RECT structure into a .NET rectangle
/// </summary>
/// <param name="rect"></param>
/// <returns></returns>
public static Rectangle Convert( RECT rect )
{
return new Rectangle( rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top ) ;
}
/// <summary>
/// Convert a .NET rectangle structure into a Win32 RECT structure
/// </summary>
/// <param name="rect">rect to convert</param>
/// <returns>converted rect</returns>
public static RECT Convert( Rectangle rect )
{
RECT newRect = new RECT() ;
newRect.left = rect.Left ;
newRect.top = rect.Top ;
newRect.right = rect.Right ;
newRect.bottom = rect.Bottom ;
return newRect ;
}
public static Rectangle Center(Size desiredSize, Rectangle anchor, bool shrinkIfNecessary)
{
int dW = anchor.Width - desiredSize.Width;
int dH = anchor.Height - desiredSize.Height;
int width = desiredSize.Width;
int height = desiredSize.Height;
if (shrinkIfNecessary && dW < 0)
{
dW = 0;
width = anchor.Width;
}
if (shrinkIfNecessary && dH < 0)
{
dH = 0;
height = anchor.Height;
}
return new Rectangle(anchor.Left + dW/2, anchor.Top + dH/2, width, height);
}
public static Rectangle RotateFlip(Size container, Rectangle rect, RotateFlipType rotateFlip)
{
bool rotate = false;
bool flipX = false;
bool flipY = false;
switch (rotateFlip)
{
case RotateFlipType.RotateNoneFlipNone:
return rect;
case RotateFlipType.RotateNoneFlipX:
flipX = true;
break;
case RotateFlipType.RotateNoneFlipXY:
flipX = flipY = true;
break;
case RotateFlipType.RotateNoneFlipY:
flipY = true;
break;
case RotateFlipType.Rotate90FlipNone:
rotate = true;
break;
case RotateFlipType.Rotate90FlipX:
rotate = flipX = true;
break;
case RotateFlipType.Rotate90FlipXY:
rotate = flipX = flipY = true;
break;
case RotateFlipType.Rotate90FlipY:
rotate = flipY = true;
break;
}
if (flipX)
rect.X = container.Width - rect.Right;
if (flipY)
rect.Y = container.Height - rect.Bottom;
if (rotate)
{
Point p = new Point(rect.Left, rect.Bottom);
rect.Location = new Point(container.Height - p.Y, p.X);
int oldWidth = rect.Width;
rect.Width = rect.Height;
rect.Height = oldWidth;
}
return rect;
}
public static Rectangle UndoRotateFlip(Size container, Rectangle rect, RotateFlipType rotateFlip)
{
switch (rotateFlip)
{
case RotateFlipType.RotateNoneFlipNone:
return rect;
case RotateFlipType.RotateNoneFlipX:
rotateFlip = RotateFlipType.RotateNoneFlipX;
break;
case RotateFlipType.RotateNoneFlipXY:
rotateFlip = RotateFlipType.RotateNoneFlipXY;
break;
case RotateFlipType.RotateNoneFlipY:
rotateFlip = RotateFlipType.RotateNoneFlipY;
break;
case RotateFlipType.Rotate90FlipNone:
rotateFlip = RotateFlipType.Rotate270FlipNone;
break;
case RotateFlipType.Rotate90FlipX:
rotateFlip = RotateFlipType.Rotate270FlipX;
break;
case RotateFlipType.Rotate90FlipXY:
rotateFlip = RotateFlipType.Rotate270FlipXY;
break;
case RotateFlipType.Rotate90FlipY:
rotateFlip = RotateFlipType.Rotate270FlipY;
break;
}
return RotateFlip(container, rect, rotateFlip);
}
public static Rectangle EnforceAspectRatio(Rectangle bounds, float aspectRatio)
{
Size originalSize = bounds.Size;
float portalAspectRatio = aspectRatio;
float imageAspectRatio = originalSize.Width / (float)originalSize.Height;
Rectangle srcRect = new Rectangle(Point.Empty, originalSize);
if (imageAspectRatio < portalAspectRatio)
{
srcRect.Height = System.Convert.ToInt32(originalSize.Width / portalAspectRatio);
srcRect.Y = Math.Max(0, (originalSize.Height - srcRect.Height) / 2);
srcRect.Height = Math.Min(srcRect.Height, originalSize.Height - srcRect.Y);
}
else
{
srcRect.Width = System.Convert.ToInt32(originalSize.Height * portalAspectRatio);
srcRect.X = Math.Max(0, (originalSize.Width - srcRect.Width) / 2);
srcRect.Width = Math.Min(srcRect.Width, originalSize.Width - srcRect.X);
}
srcRect.Offset(bounds.Location);
return srcRect;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Qwack.Core.Basic;
using Qwack.Core.Cubes;
using Qwack.Core.Curves;
using Qwack.Core.Instruments;
using Qwack.Core.Instruments.Asset;
using Qwack.Core.Models;
using Qwack.Dates;
using Qwack.Math;
using Qwack.Math.Extensions;
using Qwack.Math.Interpolation;
using Qwack.Models.Models;
using Qwack.Transport.BasicTypes;
using Qwack.Utils.Parallel;
using static System.Math;
using static Qwack.Core.Basic.Consts.Cubes;
using Qwack.Models.MCModels;
namespace Qwack.Models.Risk
{
public class CapitalCalculator
{
public static double PVCapital_BII_IMM(DateTime originDate, DateTime[] EADDates, double[] EADs, HazzardCurve hazzardCurve,
IIrCurve discountCurve, double LGD, Portfolio portfolio)
{
if (EADDates.Length != EADs.Length)
throw new Exception("Number of EPE dates and EPE values must be equal");
var pds = EADDates.Select(d => hazzardCurve.GetDefaultProbability(d, d.AddYears(1))).ToArray();
var epees = EADs.Select((d,ix) => EADs.Skip(ix).Max()).ToArray();
var Ms = EADDates.Select(d => Max(1.0, portfolio.WeightedMaturity(d))).ToArray();
var ks = epees.Select((e, ix) => BaselHelper.K(pds[ix], LGD, Ms[ix]) * e *1.4).ToArray();
var pvCapital = PvProfile(originDate, EADDates, ks, discountCurve);
return pvCapital;
}
public static double PvCcrCapital_BII_SM(DateTime originDate, DateTime[] EADDates, IAssetFxModel[] models, Portfolio portfolio,
HazzardCurve hazzardCurve, Currency reportingCurrency, IIrCurve discountCurve, double LGD, Dictionary<string, double> assetIdToCCFMap,
ICurrencyProvider currencyProvider, double[] epeProfile, double[] eadProfile = null)
{
var pds = EADDates.Select(d => hazzardCurve.GetDefaultProbability(d, d.AddYears(1))).ToArray();
var eads = eadProfile ?? EAD_BII_SM(originDate, EADDates, epeProfile, models, portfolio, reportingCurrency, assetIdToCCFMap, currencyProvider);
var Ms = EADDates.Select(d => Max(1.0, portfolio.WeightedMaturity(d))).ToArray();
var ks = eads.Select((e, ix) => BaselHelper.K(pds[ix], LGD, Ms[ix]) * e).ToArray();
var pvCapital = PvProfile(originDate, EADDates, ks, discountCurve);
return pvCapital;
}
public static double PvCvaCapital_BII_SM(DateTime originDate, DateTime[] EADDates, IAssetFxModel[] models, Portfolio portfolio,
Currency reportingCurrency, IIrCurve discountCurve, double partyWeight, Dictionary<string, double> hedgeSetToCCF,
ICurrencyProvider currencyProvider, double[] epeProfile, double[] eadProfile=null)
{
var eads = eadProfile??EAD_BII_SM(originDate, EADDates, epeProfile, models, portfolio, reportingCurrency, hedgeSetToCCF, currencyProvider);
var Ms = EADDates.Select(d => Max(1.0,portfolio.WeightedMaturity(d))).ToArray();
var dfs = Ms.Select(m => m == 0 ? 1.0 : (1.0 - Exp(-0.05 * m)) / (0.05 * m)).ToArray();
var ks = eads.Select((e, ix) => XVACalculator.Capital_BaselII_CVA_SM(e * dfs[ix], Ms[ix], partyWeight)).ToArray();
var pvCapital = PvProfile(originDate, EADDates, ks, discountCurve);
return pvCapital;
}
public static double PvCvaCapital_BIII_Basic(DateTime originDate, DateTime[] EADDates, IAssetFxModel[] models, Portfolio portfolio,
Currency reportingCurrency, IIrCurve discountCurve, double supervisoryRiskWeight, Dictionary<string, string> assetIdToTypeMap,
Dictionary<string, SaCcrAssetClass> typeToAssetClassMap, ICurrencyProvider currencyProvider, double[] epeProfile, double[] eadProfile = null)
{
var eads = eadProfile ?? EAD_BIII_SACCR(originDate, EADDates, epeProfile, models, portfolio, reportingCurrency, assetIdToTypeMap, typeToAssetClassMap, currencyProvider);
var Ms = EADDates.Select(d => Max(10.0/365, portfolio.WeightedMaturity(d))).ToArray();
var ks = eads.Select((e, ix) => BaselHelper.BasicCvaB3.CvaCapitalCharge(supervisoryRiskWeight, Ms[ix], e)).ToArray();
var pvCapital = PvProfile(originDate, EADDates, ks, discountCurve);
return pvCapital;
}
public static (double CVA_t1, double CVA_t2, double CCR_t1, double CCR_t2) PvCapital_Split(DateTime originDate, DateTime[] EADDates, IAssetFxModel[] models,
Portfolio portfolio, HazzardCurve hazzardCurve, Currency reportingCurrency, IIrCurve discountCurve, double LGD, double supervisoryRiskWeight, double riskWeight,
Dictionary<string, string> assetIdToTypeMap, Dictionary<string, SaCcrAssetClass> typeToAssetClassMap, Dictionary<string, double> assetIdToCCFMap,
ICurrencyProvider currencyProvider, double[] epeProfile, double tier1Ratio, double tier2Ratio, double tier1Cost, double tier2Cost, DateTime? B2B3ChangeDate=null, double[] eadProfile = null)
{
if (!B2B3ChangeDate.HasValue)
B2B3ChangeDate = DateTime.MaxValue;
var eads = eadProfile ?? EAD_Split(originDate, EADDates, epeProfile, models, portfolio, reportingCurrency, assetIdToTypeMap, typeToAssetClassMap, assetIdToCCFMap, B2B3ChangeDate.Value, currencyProvider);
eads = eads.Select(e => e).ToArray();
var pds = EADDates.Select(d => hazzardCurve.GetDefaultProbability(d, d.AddYears(1))).ToArray();
var MsCcr = EADDates.Select(d => d < B2B3ChangeDate ? 2.5 : SaCcrUtils.MfUnmargined(portfolio.WeightedMaturity(d))).ToArray();
//var MsCva = EADDates.Select(d => d < B2B3ChangeDate ? portfolio.WeightedMaturity(d) : SaCcrUtils.MfUnmargined(portfolio.WeightedMaturity(d))).ToArray();
var MsCva = EADDates.Select(d => Max(1.0,portfolio.WeightedMaturity(d))).ToArray();
var rwasCcr = RwaCalculator(eads, pds, MsCcr, LGD);
var t1Ccr = rwasCcr.Select(r => r * tier1Ratio).ToArray();
var t2Ccr = rwasCcr.Select(r => r * tier2Ratio).ToArray();
var ts = EADDates.Select((x, ix) => ix < EADDates.Length - 1 ? (EADDates[ix + 1] - x).TotalDays / 365.0 : 0).ToArray();
var t1CcrPv = t1Ccr.Select((x, ix) => ts[ix] * x * tier1Cost).Sum();
var t2CcrPv = t2Ccr.Select((x, ix) => ts[ix] * x * tier2Cost).Sum();
var ksCVA = eads.Select((e, ix) => BaselHelper.StandardCvaB3.CvaCapitalCharge(supervisoryRiskWeight, MsCva[ix], e)).ToArray();
var pvCapitalCVA = PvProfileWithCost(originDate, EADDates, ksCVA, discountCurve, tier1Cost);
//var pvRwaCVA = pvCapitalCVA *= 12.5;
//var t1CvaPv = pvRwaCVA * tier1Ratio;
return (pvCapitalCVA, 0, t1CcrPv, t2CcrPv);
}
public static double[] EAD_Split(DateTime originDate, DateTime[] EADDates, double[] EPEs, IAssetFxModel[] models, Portfolio portfolio, Currency reportingCurrency,
Dictionary<string, string> assetIdToTypeMap, Dictionary<string, SaCcrAssetClass> typeToAssetClassMap, Dictionary<string, double> assetIdToCCFMap,
DateTime changeOverDate, ICurrencyProvider currencyProvider)
{
var changeOverIx = Array.BinarySearch(EADDates, changeOverDate);
if (changeOverIx < 0)
changeOverIx = ~changeOverIx;
changeOverIx = Min(changeOverIx, EADDates.Length);
var EADb2 = EAD_BII_SM(originDate, EADDates.Take(changeOverIx).ToArray(), EPEs.Take(changeOverIx).ToArray(), models, portfolio, reportingCurrency, assetIdToCCFMap, currencyProvider);
if (changeOverIx == EADDates.Length) //all under Basel II / SM
return EADb2;
var EADb3 = EAD_BIII_SACCR(originDate, EADDates.Skip(changeOverIx).ToArray(), EPEs.Skip(changeOverIx).ToArray(), models.Skip(changeOverIx).ToArray(), portfolio, reportingCurrency, assetIdToTypeMap, typeToAssetClassMap, currencyProvider);
return EADb2.Concat(EADb3).ToArray();
}
public static bool IsPrecious(string pair) => pair.StartsWith("X") || pair.Contains("/X");
public static double[] EAD_BII_SM(DateTime originDate, DateTime[] EADDates, double[] EPEs, IAssetFxModel[] models, Portfolio portfolio, Currency reportingCurrency,
Dictionary<string, double> assetIdToCCFMap, ICurrencyProvider currencyProvider)
{
var beta = 1.4;
if (!assetIdToCCFMap.TryGetValue("FX", out var ccfFx))
ccfFx = 0.025;
var eads = new double[EADDates.Length];
ParallelUtils.Instance.For(0, EADDates.Length, 1, i =>
//for (var i = 0; i < EADDates.Length; i++)
{
if (EADDates[i] >= originDate)
{
var pv = EPEs[i];
var deltas = new Dictionary<string, double>();
foreach(var ins in portfolio.Instruments)
{
var d = Basel2Risk.Delta(ins, models[i], reportingCurrency);
foreach(var delta in d)
{
if (!deltas.ContainsKey(delta.Key))
deltas[delta.Key] = 0;
deltas[delta.Key] += delta.Value;
}
}
var deltaSum = 0.0;
foreach (var delta in deltas)
{
if(!assetIdToCCFMap.TryGetValue(delta.Key, out var ccf))
{
if (AssetFxModel.IsFx(delta.Key))
ccf = ccfFx;
else
throw new Exception($"CCF not found for assetId {delta.Key}");
}
deltaSum += Abs(delta.Value) * ccf;
}
eads[i] = Max(pv, deltaSum) * beta;
}
}).Wait();
return eads;
}
public static double[] EAD_BII_SM_old(DateTime originDate, DateTime[] EADDates, double[] EPEs, IAssetFxModel[] models, Portfolio portfolio, Currency reportingCurrency,
Dictionary<string, double> assetIdToCCFMap, ICurrencyProvider currencyProvider)
{
var beta = 1.4;
if (!assetIdToCCFMap.TryGetValue("FX", out var ccfFx))
ccfFx = 0.025;
var eads = new double[EADDates.Length];
ParallelUtils.Instance.For(0, EADDates.Length, 1, i =>
//for (var i = 0; i < EADDates.Length; i++)
{
if (EADDates[i] >= originDate)
{
var m = models[i].Clone();
m.AttachPortfolio(portfolio);
var pv = EPEs[i];
var deltaSum = 0.0;
var assetDeltaCube = m.AssetCashDelta(reportingCurrency).Pivot(AssetId, AggregationAction.Sum);
foreach (var row in assetDeltaCube.GetAllRows())
{
var asset = (string)row.MetaData[0];
var ccf = assetIdToCCFMap[asset];
var delta = Abs(row.Value); //need to consider buckets
deltaSum += ccf * delta;
}
var fxDeltaCube = m.FxDelta(reportingCurrency, currencyProvider, false, true).Pivot(AssetId, AggregationAction.Sum);
foreach (var row in fxDeltaCube.GetAllRows())
{
var pair = (string)row.MetaData[0];
var rate = m.FundingModel.GetFxRate(m.BuildDate, pair);
var ccfToUse = ccfFx;
if (IsPrecious(pair))
{
if (!assetIdToCCFMap.TryGetValue(pair, out ccfToUse))
{
var flippedPair = $"{pair.Substring(pair.Length - 3, 3)}/{pair.Substring(0, 3)}";
if (!assetIdToCCFMap.TryGetValue(flippedPair, out ccfToUse))
{
throw new Exception($"Could not find pair {pair} or its inverse in hedge set map");
}
}
}
deltaSum += Abs(row.Value) / rate * ccfToUse;
}
eads[i] = Max(pv, deltaSum) * beta;
}
}).Wait();
return eads;
}
public static double[] EAD_BIII_SACCR(DateTime originDate, DateTime[] EADDates, double[] EPEs, IAssetFxModel[] models, Portfolio portfolio, Currency reportingCurrency,
Dictionary<string,string> assetIdToTypeMap, Dictionary<string, SaCcrAssetClass> typeToAssetClassMap, ICurrencyProvider currencyProvider)
{
var eads = new double[EADDates.Length];
foreach(ISaCcrEnabledCommodity ins in portfolio.Instruments)
{
ins.CommodityType = assetIdToTypeMap[(ins as IAssetInstrument).AssetIds.First()];
ins.AssetClass = typeToAssetClassMap[ins.CommodityType];
}
for (var i = 0; i < EADDates.Length; i++)
{
if (EADDates[i] < originDate)
continue;
IAssetFxModel m;
if(models[i].FundingModel.FxMatrix.BaseCurrency!=reportingCurrency)
{
var newFm = FundingModel.RemapBaseCurrency(models[i].FundingModel, reportingCurrency, currencyProvider);
m = models[i].Clone(newFm);
}
else
{
m = models[i].Clone();
}
m.AttachPortfolio(portfolio);
eads[i] = SaCcrHelper.SaCcrEad(portfolio, m, EPEs[i]);
}
return eads;
}
public static double PVCapital_BII_IMM(DateTime originDate, ICube expectedEAD, HazzardCurve hazzardCurve, IIrCurve discountCurve, double LGD, Portfolio portfolio)
{
(var eadDates, var eadValues) = XVACalculator.CubeToExposures(expectedEAD);
return PVCapital_BII_IMM(originDate, eadDates, eadValues, hazzardCurve, discountCurve, LGD, portfolio);
}
public static double PvProfile(DateTime originDate, DateTime[] exposureDates, double[] exposures , IIrCurve discountCurve)
{
var capital = 0.0;
var time = 0.0;
if (exposureDates.Length != exposures.Length || exposures.Length < 1)
throw new DataMisalignedException();
if (exposureDates.Length == 1)
return discountCurve.GetDf(originDate, exposureDates[0]) * exposures[0];
var discountedExposures = exposures.Select((x, ix) => x * discountCurve.GetDf(originDate, exposureDates[ix])).ToArray();
var timeAxis = exposureDates.Select(d => originDate.CalculateYearFraction(d, DayCountBasis.Act365F)).ToArray();
var interp = new CubicHermiteSplineInterpolator(timeAxis, discountedExposures);
var integral = interp.DefiniteIntegral(0, timeAxis.Last());
var timeWeightedCapital = integral / timeAxis.Last();
return timeWeightedCapital;
//for (var i = 0; i < exposureDates.Length - 1; i++)
//{
// var exposure = (exposures[i] + exposures[i + 1]) / 2.0;
// var df = discountCurve.GetDf(originDate, exposureDates[i+1]);
// var dt = exposureDates[i].CalculateYearFraction(exposureDates[i + 1], DayCountBasis.ACT365F);
// capital += exposure * dt * df;
// time += dt;
//}
//return capital / time;
}
public static double PvProfileWithCost(DateTime originDate, DateTime[] exposureDates, double[] exposures, IIrCurve discountCurve, double cost)
{
var capital = 0.0;
if (exposureDates.Length != exposures.Length || exposures.Length < 1)
throw new DataMisalignedException();
if (exposureDates.Length == 1)
return discountCurve.GetDf(originDate, exposureDates[0]) * exposures[0];
for (var i = 0; i < exposureDates.Length - 1; i++)
{
var exposure = exposures[i];
var df = discountCurve.GetDf(originDate, exposureDates[i + 1]);
var dt = exposureDates[i].CalculateYearFraction(exposureDates[i + 1], DayCountBasis.ACT365F);
capital += exposure * dt * df * cost;
}
return capital;
}
public static ICube RwaCalculator(ICube eads, HazzardCurve hazzardCurve, Portfolio portfolio, double lgd)
{
var dateIx = eads.GetColumnIndex(ExposureDate);
var eadVec = eads.GetAllRows().Select(e => e.Value).ToArray();
var exposureDates = eads.GetAllRows().Select(x => (DateTime)x.MetaData[dateIx]).ToArray();
var pds = exposureDates.Select(d => hazzardCurve.GetDefaultProbability(d, d.AddYears(1))).ToArray();
var weightedMaturities = exposureDates.Select(d => portfolio.WeightedMaturity(d)).ToArray();
var rwas = RwaCalculator(eadVec, pds, weightedMaturities, lgd);
var result = new Dictionary<DateTime, double>();
for(var i=0;i<rwas.Length;i++)
{
result.Add(exposureDates[i], rwas[i]);
}
var cube = AssetFxMCModel.PackResults(result, "RWA");
return cube;
}
public static double[] RwaCalculator(double[] eads, double[] pds, double[] weightedMaturities, double lgd )
{
var ks = pds.Select((pd, ix) => BaselHelper.K(pd, lgd, weightedMaturities[ix])).ToArray();
var rwas = eads.Select((ead, ix) => ead * ks[ix] * 12.5).ToArray();
return rwas;
}
}
}
| |
// 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.Runtime;
using System.Security;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// This is a set of stub methods implementing the support for the IList interface on WinRT
// objects that support IBindableVector. Used by the interop mashaling infrastructure.
//
// The methods on this class must be written VERY carefully to avoid introducing security holes.
// That's because they are invoked with special "this"! The "this" object
// for all of these methods are not BindableVectorToListAdapter objects. Rather, they are
// of type IBindableVector. No actual BindableVectorToListAdapter object is ever instantiated.
// Thus, you will see a lot of expressions that cast "this" to "IBindableVector".
internal sealed class BindableVectorToListAdapter
{
private BindableVectorToListAdapter()
{
Debug.Assert(false, "This class is never instantiated");
}
// object this[int index] { get }
internal object Indexer_Get(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
return GetAt(_this, (uint)index);
}
// object this[int index] { set }
internal void Indexer_Set(int index, object value)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
SetAt(_this, (uint)index, value);
}
// int Add(object value)
internal int Add(object value)
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
_this.Append(value);
uint size = _this.Size;
if (((uint)Int32.MaxValue) < size)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
}
return (int)(size - 1);
}
// bool Contains(object item)
internal bool Contains(object item)
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
uint index;
return _this.IndexOf(item, out index);
}
// void Clear()
internal void Clear()
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
_this.Clear();
}
// bool IsFixedSize { get }
[Pure]
internal bool IsFixedSize()
{
return false;
}
// bool IsReadOnly { get }
[Pure]
internal bool IsReadOnly()
{
return false;
}
// int IndexOf(object item)
internal int IndexOf(object item)
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
uint index;
bool exists = _this.IndexOf(item, out index);
if (!exists)
return -1;
if (((uint)Int32.MaxValue) < index)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
}
return (int)index;
}
// void Insert(int index, object item)
internal void Insert(int index, object item)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
InsertAtHelper(_this, (uint)index, item);
}
// bool Remove(object item)
internal void Remove(object item)
{
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
uint index;
bool exists = _this.IndexOf(item, out index);
if (exists)
{
if (((uint)Int32.MaxValue) < index)
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CollectionBackingListTooLarge"));
}
RemoveAtHelper(_this, index);
}
}
// void RemoveAt(int index)
internal void RemoveAt(int index)
{
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index));
IBindableVector _this = JitHelpers.UnsafeCast<IBindableVector>(this);
RemoveAtHelper(_this, (uint)index);
}
// Helpers:
private static object GetAt(IBindableVector _this, uint index)
{
try
{
return _this.GetAt(index);
// We delegate bounds checking to the underlying collection and if it detected a fault,
// we translate it to the right exception:
}
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
}
private static void SetAt(IBindableVector _this, uint index, object value)
{
try
{
_this.SetAt(index, value);
// We delegate bounds checking to the underlying collection and if it detected a fault,
// we translate it to the right exception:
}
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
}
private static void InsertAtHelper(IBindableVector _this, uint index, object item)
{
try
{
_this.InsertAt(index, item);
// We delegate bounds checking to the underlying collection and if it detected a fault,
// we translate it to the right exception:
}
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
}
private static void RemoveAtHelper(IBindableVector _this, uint index)
{
try
{
_this.RemoveAt(index);
// We delegate bounds checking to the underlying collection and if it detected a fault,
// we translate it to the right exception:
}
catch (Exception ex)
{
if (__HResults.E_BOUNDS == ex._HResult)
throw new ArgumentOutOfRangeException(nameof(index));
throw;
}
}
}
}
| |
/*
* Copyright 2013 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.Globalization;
using System.Text;
namespace ZXing.PDF417.Internal
{
/// <summary>
///
/// </summary>
/// <author>Guenther Grau</author>
public class DetectionResult
{
private const int ADJUST_ROW_NUMBER_SKIP = 2;
/// <summary>
/// metadata which are found
/// </summary>
public BarcodeMetadata Metadata { get; private set; }
/// <summary>
/// result columns
/// </summary>
public DetectionResultColumn[] DetectionResultColumns { get; set; }
/// <summary>
/// bounding box of the detected result
/// </summary>
public BoundingBox Box { get; internal set; }
/// <summary>
/// column count
/// </summary>
public int ColumnCount { get; private set; }
/// <summary>
/// row count
/// </summary>
public int RowCount
{
get { return Metadata.RowCount; }
}
/// <summary>
/// error correction level
/// </summary>
public int ErrorCorrectionLevel
{
get { return Metadata.ErrorCorrectionLevel; }
}
/// <summary>
/// initializing constructor
/// </summary>
/// <param name="metadata"></param>
/// <param name="box"></param>
public DetectionResult(BarcodeMetadata metadata, BoundingBox box)
{
Metadata = metadata;
Box = box;
ColumnCount = metadata.ColumnCount;
DetectionResultColumns = new DetectionResultColumn[ColumnCount + 2];
}
/// <summary>
/// Returns the DetectionResult Columns. This does a fair bit of calculation, so call it sparingly.
/// </summary>
/// <returns>The detection result columns.</returns>
public DetectionResultColumn[] getDetectionResultColumns()
{
adjustIndicatorColumnRowNumbers(DetectionResultColumns[0]);
adjustIndicatorColumnRowNumbers(DetectionResultColumns[ColumnCount + 1]);
int unadjustedCodewordCount = PDF417Common.MAX_CODEWORDS_IN_BARCODE;
int previousUnadjustedCount;
do
{
previousUnadjustedCount = unadjustedCodewordCount;
unadjustedCodewordCount = adjustRowNumbers();
} while (unadjustedCodewordCount > 0 && unadjustedCodewordCount < previousUnadjustedCount);
return DetectionResultColumns;
}
/// <summary>
/// Adjusts the indicator column row numbers.
/// </summary>
/// <param name="detectionResultColumn">Detection result column.</param>
private void adjustIndicatorColumnRowNumbers(DetectionResultColumn detectionResultColumn)
{
if (detectionResultColumn != null)
{
((DetectionResultRowIndicatorColumn)detectionResultColumn)
.adjustCompleteIndicatorColumnRowNumbers(Metadata);
}
}
/// <summary>
/// return number of codewords which don't have a valid row number. Note that the count is not accurate as codewords .
/// will be counted several times. It just serves as an indicator to see when we can stop adjusting row numbers
/// </summary>
/// <returns>The row numbers.</returns>
private int adjustRowNumbers()
{
// TODO ensure that no detected codewords with unknown row number are left
// we should be able to estimate the row height and use it as a hint for the row number
// we should also fill the rows top to bottom and bottom to top
int unadjustedCount = adjustRowNumbersByRow();
if (unadjustedCount == 0)
{
return 0;
}
for (int barcodeColumn = 1; barcodeColumn < ColumnCount + 1; barcodeColumn++)
{
Codeword[] codewords = DetectionResultColumns[barcodeColumn].Codewords;
for (int codewordsRow = 0; codewordsRow < codewords.Length; codewordsRow++)
{
if (codewords[codewordsRow] == null)
{
continue;
}
if (!codewords[codewordsRow].HasValidRowNumber)
{
adjustRowNumbers(barcodeColumn, codewordsRow, codewords);
}
}
}
return unadjustedCount;
}
/// <summary>
/// Adjusts the row numbers by row.
/// </summary>
/// <returns>The row numbers by row.</returns>
private int adjustRowNumbersByRow()
{
adjustRowNumbersFromBothRI(); // RI = RowIndicators
// TODO we should only do full row adjustments if row numbers of left and right row indicator column match.
// Maybe it's even better to calculated the height (in codeword rows) and divide it by the number of barcode
// rows. This, together with the LRI and RRI row numbers should allow us to get a good estimate where a row
// number starts and ends.
int unadjustedCount = adjustRowNumbersFromLRI();
return unadjustedCount + adjustRowNumbersFromRRI();
}
/// <summary>
/// Adjusts the row numbers from both Row Indicators
/// </summary>
/// <returns> zero </returns>
private void adjustRowNumbersFromBothRI()
{
if (DetectionResultColumns[0] == null || DetectionResultColumns[ColumnCount + 1] == null)
{
return;
}
Codeword[] LRIcodewords = DetectionResultColumns[0].Codewords;
Codeword[] RRIcodewords = DetectionResultColumns[ColumnCount + 1].Codewords;
for (int codewordsRow = 0; codewordsRow < LRIcodewords.Length; codewordsRow++)
{
if (LRIcodewords[codewordsRow] != null &&
RRIcodewords[codewordsRow] != null &&
LRIcodewords[codewordsRow].RowNumber == RRIcodewords[codewordsRow].RowNumber)
{
for (int barcodeColumn = 1; barcodeColumn <= ColumnCount; barcodeColumn++)
{
Codeword codeword = DetectionResultColumns[barcodeColumn].Codewords[codewordsRow];
if (codeword == null)
{
continue;
}
codeword.RowNumber = LRIcodewords[codewordsRow].RowNumber;
if (!codeword.HasValidRowNumber)
{
// LOG.info("Removing codeword with invalid row number, cw[" + codewordsRow + "][" + barcodeColumn + "]");
DetectionResultColumns[barcodeColumn].Codewords[codewordsRow] = null;
}
}
}
}
}
/// <summary>
/// Adjusts the row numbers from Right Row Indicator.
/// </summary>
/// <returns>The unadjusted row count.</returns>
private int adjustRowNumbersFromRRI()
{
if (DetectionResultColumns[ColumnCount + 1] == null)
{
return 0;
}
int unadjustedCount = 0;
Codeword[] codewords = DetectionResultColumns[ColumnCount + 1].Codewords;
for (int codewordsRow = 0; codewordsRow < codewords.Length; codewordsRow++)
{
if (codewords[codewordsRow] == null)
{
continue;
}
int rowIndicatorRowNumber = codewords[codewordsRow].RowNumber;
int invalidRowCounts = 0;
for (int barcodeColumn = ColumnCount + 1; barcodeColumn > 0 && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP; barcodeColumn--)
{
Codeword codeword = DetectionResultColumns[barcodeColumn].Codewords[codewordsRow];
if (codeword != null)
{
invalidRowCounts = adjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword);
if (!codeword.HasValidRowNumber)
{
unadjustedCount++;
}
}
}
}
return unadjustedCount;
}
/// <summary>
/// Adjusts the row numbers from Left Row Indicator.
/// </summary>
/// <returns> Unadjusted row Count.</returns>
private int adjustRowNumbersFromLRI()
{
if (DetectionResultColumns[0] == null)
{
return 0;
}
int unadjustedCount = 0;
Codeword[] codewords = DetectionResultColumns[0].Codewords;
for (int codewordsRow = 0; codewordsRow < codewords.Length; codewordsRow++)
{
if (codewords[codewordsRow] == null)
{
continue;
}
int rowIndicatorRowNumber = codewords[codewordsRow].RowNumber;
int invalidRowCounts = 0;
for (int barcodeColumn = 1; barcodeColumn < ColumnCount + 1 && invalidRowCounts < ADJUST_ROW_NUMBER_SKIP; barcodeColumn++)
{
Codeword codeword = DetectionResultColumns[barcodeColumn].Codewords[codewordsRow];
if (codeword != null)
{
invalidRowCounts = adjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword);
if (!codeword.HasValidRowNumber)
{
unadjustedCount++;
}
}
}
}
return unadjustedCount;
}
/// <summary>
/// Adjusts the row number if valid.
/// </summary>
/// <returns>The invalid rows</returns>
/// <param name="rowIndicatorRowNumber">Row indicator row number.</param>
/// <param name="invalidRowCounts">Invalid row counts.</param>
/// <param name="codeword">Codeword.</param>
private static int adjustRowNumberIfValid(int rowIndicatorRowNumber, int invalidRowCounts, Codeword codeword)
{
if (codeword == null)
{
return invalidRowCounts;
}
if (!codeword.HasValidRowNumber)
{
if (codeword.IsValidRowNumber(rowIndicatorRowNumber))
{
codeword.RowNumber = rowIndicatorRowNumber;
invalidRowCounts = 0;
}
else
{
++invalidRowCounts;
}
}
return invalidRowCounts;
}
/// <summary>
/// Adjusts the row numbers.
/// </summary>
/// <param name="barcodeColumn">Barcode column.</param>
/// <param name="codewordsRow">Codewords row.</param>
/// <param name="codewords">Codewords.</param>
private void adjustRowNumbers(int barcodeColumn, int codewordsRow, Codeword[] codewords)
{
Codeword codeword = codewords[codewordsRow];
Codeword[] previousColumnCodewords = DetectionResultColumns[barcodeColumn - 1].Codewords;
Codeword[] nextColumnCodewords = previousColumnCodewords;
if (DetectionResultColumns[barcodeColumn + 1] != null)
{
nextColumnCodewords = DetectionResultColumns[barcodeColumn + 1].Codewords;
}
Codeword[] otherCodewords = new Codeword[14];
otherCodewords[2] = previousColumnCodewords[codewordsRow];
otherCodewords[3] = nextColumnCodewords[codewordsRow];
if (codewordsRow > 0)
{
otherCodewords[0] = codewords[codewordsRow - 1];
otherCodewords[4] = previousColumnCodewords[codewordsRow - 1];
otherCodewords[5] = nextColumnCodewords[codewordsRow - 1];
}
if (codewordsRow > 1)
{
otherCodewords[8] = codewords[codewordsRow - 2];
otherCodewords[10] = previousColumnCodewords[codewordsRow - 2];
otherCodewords[11] = nextColumnCodewords[codewordsRow - 2];
}
if (codewordsRow < codewords.Length - 1)
{
otherCodewords[1] = codewords[codewordsRow + 1];
otherCodewords[6] = previousColumnCodewords[codewordsRow + 1];
otherCodewords[7] = nextColumnCodewords[codewordsRow + 1];
}
if (codewordsRow < codewords.Length - 2)
{
otherCodewords[9] = codewords[codewordsRow + 2];
otherCodewords[12] = previousColumnCodewords[codewordsRow + 2];
otherCodewords[13] = nextColumnCodewords[codewordsRow + 2];
}
foreach (Codeword otherCodeword in otherCodewords)
{
if (adjustRowNumber(codeword, otherCodeword))
{
return;
}
}
}
/// <summary>
/// Adjusts the row number.
/// </summary>
/// <returns><c>true</c>, if row number was adjusted, <c>false</c> otherwise.</returns>
/// <param name="codeword">Codeword.</param>
/// <param name="otherCodeword">Other codeword.</param>
private static bool adjustRowNumber(Codeword codeword, Codeword otherCodeword)
{
if (otherCodeword == null)
{
return false;
}
if (otherCodeword.HasValidRowNumber && otherCodeword.Bucket == codeword.Bucket)
{
codeword.RowNumber = otherCodeword.RowNumber;
return true;
}
return false;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.DetectionResult"/>.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents the current <see cref="ZXing.PDF417.Internal.DetectionResult"/>.</returns>
public override string ToString()
{
StringBuilder formatter = new StringBuilder();
DetectionResultColumn rowIndicatorColumn = DetectionResultColumns[0];
if (rowIndicatorColumn == null)
{
rowIndicatorColumn = DetectionResultColumns[ColumnCount + 1];
}
for (int codewordsRow = 0; codewordsRow < rowIndicatorColumn.Codewords.Length; codewordsRow++)
{
formatter.AppendFormat(CultureInfo.InvariantCulture, "CW {0,3}:", codewordsRow);
for (int barcodeColumn = 0; barcodeColumn < ColumnCount + 2; barcodeColumn++)
{
if (DetectionResultColumns[barcodeColumn] == null)
{
formatter.Append(" | ");
continue;
}
Codeword codeword = DetectionResultColumns[barcodeColumn].Codewords[codewordsRow];
if (codeword == null)
{
formatter.Append(" | ");
continue;
}
formatter.AppendFormat(CultureInfo.InvariantCulture, " {0,3}|{1,3}", codeword.RowNumber, codeword.Value);
}
formatter.Append("\n");
}
return formatter.ToString();
}
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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 SCG = System.Collections.Generic;
namespace C5
{
/// <summary>
/// An entry in a dictionary from K to V.
/// </summary>
[Serializable]
public struct KeyValuePair<K, V> : IEquatable<KeyValuePair<K, V>>, IShowable
{
/// <summary>
/// The key field of the entry
/// </summary>
public K Key;
/// <summary>
/// The value field of the entry
/// </summary>
public V Value;
/// <summary>
/// Create an entry with specified key and value
/// </summary>
/// <param name="key">The key</param>
/// <param name="value">The value</param>
public KeyValuePair(K key, V value) { Key = key; Value = value; }
/// <summary>
/// Create an entry with a specified key. The value will be the default value of type <code>V</code>.
/// </summary>
/// <param name="key">The key</param>
public KeyValuePair(K key) { Key = key; Value = default(V); }
/// <summary>
/// Pretty print an entry
/// </summary>
/// <returns>(key, value)</returns>
public override string ToString() { return "(" + Key + ", " + Value + ")"; }
/// <summary>
/// Check equality of entries.
/// </summary>
/// <param name="obj">The other object</param>
/// <returns>True if obj is an entry of the same type and has the same key and value</returns>
public override bool Equals(object obj)
{
if (!(obj is KeyValuePair<K, V>))
return false;
KeyValuePair<K, V> other = (KeyValuePair<K, V>)obj;
return Equals(other);
}
/// <summary>
/// Get the hash code of the pair.
/// </summary>
/// <returns>The hash code</returns>
public override int GetHashCode() { return EqualityComparer<K>.Default.GetHashCode(Key) + 13984681 * EqualityComparer<V>.Default.GetHashCode(Value); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(KeyValuePair<K, V> other)
{
return EqualityComparer<K>.Default.Equals(Key, other.Key) && EqualityComparer<V>.Default.Equals(Value, other.Value);
}
/// <summary>
///
/// </summary>
/// <param name="pair1"></param>
/// <param name="pair2"></param>
/// <returns></returns>
public static bool operator ==(KeyValuePair<K, V> pair1, KeyValuePair<K, V> pair2) { return pair1.Equals(pair2); }
/// <summary>
///
/// </summary>
/// <param name="pair1"></param>
/// <param name="pair2"></param>
/// <returns></returns>
public static bool operator !=(KeyValuePair<K, V> pair1, KeyValuePair<K, V> pair2) { return !pair1.Equals(pair2); }
#region IShowable Members
/// <summary>
///
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="formatProvider"></param>
/// <param name="rest"></param>
/// <returns></returns>
public bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
if (rest < 0)
return false;
if (!Showing.Show(Key, stringbuilder, ref rest, formatProvider))
return false;
stringbuilder.Append(" => ");
rest -= 4;
if (!Showing.Show(Value, stringbuilder, ref rest, formatProvider))
return false;
return rest >= 0;
}
#endregion
#region IFormattable Members
/// <summary>
///
/// </summary>
/// <param name="format"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return Showing.ShowString(this, format, formatProvider);
}
#endregion
}
/// <summary>
/// Default comparer for dictionary entries in a sorted dictionary.
/// Entry comparisons only look at keys and uses an externally defined comparer for that.
/// </summary>
[Serializable]
public class KeyValuePairComparer<K, V> : SCG.IComparer<KeyValuePair<K, V>>
{
SCG.IComparer<K> comparer;
/// <summary>
/// Create an entry comparer for a item comparer of the keys
/// </summary>
/// <param name="comparer">Comparer of keys</param>
public KeyValuePairComparer(SCG.IComparer<K> comparer)
{
if (comparer == null)
throw new NullReferenceException();
this.comparer = comparer;
}
/// <summary>
/// Compare two entries
/// </summary>
/// <param name="entry1">First entry</param>
/// <param name="entry2">Second entry</param>
/// <returns>The result of comparing the keys</returns>
public int Compare(KeyValuePair<K, V> entry1, KeyValuePair<K, V> entry2)
{
return comparer.Compare(entry1.Key, entry2.Key);
}
}
/// <summary>
/// Default equalityComparer for dictionary entries.
/// Operations only look at keys and uses an externaly defined equalityComparer for that.
/// </summary>
[Serializable]
public sealed class KeyValuePairEqualityComparer<K, V> : SCG.IEqualityComparer<KeyValuePair<K, V>>
{
SCG.IEqualityComparer<K> keyequalityComparer;
/// <summary>
/// Create an entry equalityComparer using the default equalityComparer for keys
/// </summary>
public KeyValuePairEqualityComparer() { keyequalityComparer = EqualityComparer<K>.Default; }
/// <summary>
/// Create an entry equalityComparer from a specified item equalityComparer for the keys
/// </summary>
/// <param name="keyequalityComparer">The key equalityComparer</param>
public KeyValuePairEqualityComparer(SCG.IEqualityComparer<K> keyequalityComparer)
{
if (keyequalityComparer == null)
throw new NullReferenceException("Key equality comparer cannot be null");
this.keyequalityComparer = keyequalityComparer;
}
/// <summary>
/// Get the hash code of the entry
/// </summary>
/// <param name="entry">The entry</param>
/// <returns>The hash code of the key</returns>
public int GetHashCode(KeyValuePair<K, V> entry) { return keyequalityComparer.GetHashCode(entry.Key); }
/// <summary>
/// Test two entries for equality
/// </summary>
/// <param name="entry1">First entry</param>
/// <param name="entry2">Second entry</param>
/// <returns>True if keys are equal</returns>
public bool Equals(KeyValuePair<K, V> entry1, KeyValuePair<K, V> entry2)
{
return keyequalityComparer.Equals(entry1.Key, entry2.Key);
}
}
/// <summary>
/// A base class for implementing a dictionary based on a set collection implementation.
/// <i>See the source code for <see cref="T:C5.HashDictionary`2"/> for an example</i>
///
/// </summary>
[Serializable]
public abstract class DictionaryBase<K, V> : CollectionValueBase<KeyValuePair<K, V>>, IDictionary<K, V>
{
/// <summary>
/// The set collection of entries underlying this dictionary implementation
/// </summary>
protected ICollection<KeyValuePair<K, V>> pairs;
SCG.IEqualityComparer<K> keyequalityComparer;
#region Events
ProxyEventBlock<KeyValuePair<K, V>> eventBlock;
/// <summary>
/// The change event. Will be raised for every change operation on the collection.
/// </summary>
public override event CollectionChangedHandler<KeyValuePair<K, V>> CollectionChanged
{
add { (eventBlock ?? (eventBlock = new ProxyEventBlock<KeyValuePair<K, V>>(this, pairs))).CollectionChanged += value; }
remove { if (eventBlock != null) eventBlock.CollectionChanged -= value; }
}
/// <summary>
/// The change event. Will be raised for every change operation on the collection.
/// </summary>
public override event CollectionClearedHandler<KeyValuePair<K, V>> CollectionCleared
{
add { (eventBlock ?? (eventBlock = new ProxyEventBlock<KeyValuePair<K, V>>(this, pairs))).CollectionCleared += value; }
remove { if (eventBlock != null) eventBlock.CollectionCleared -= value; }
}
/// <summary>
/// The item added event. Will be raised for every individual addition to the collection.
/// </summary>
public override event ItemsAddedHandler<KeyValuePair<K, V>> ItemsAdded
{
add { (eventBlock ?? (eventBlock = new ProxyEventBlock<KeyValuePair<K, V>>(this, pairs))).ItemsAdded += value; }
remove { if (eventBlock != null) eventBlock.ItemsAdded -= value; }
}
/// <summary>
/// The item added event. Will be raised for every individual removal from the collection.
/// </summary>
public override event ItemsRemovedHandler<KeyValuePair<K, V>> ItemsRemoved
{
add { (eventBlock ?? (eventBlock = new ProxyEventBlock<KeyValuePair<K, V>>(this, pairs))).ItemsRemoved += value; }
remove { if (eventBlock != null) eventBlock.ItemsRemoved -= value; }
}
/// <summary>
///
/// </summary>
public override EventTypeEnum ListenableEvents
{
get
{
return EventTypeEnum.Basic;
}
}
/// <summary>
///
/// </summary>
public override EventTypeEnum ActiveEvents
{
get
{
return pairs.ActiveEvents;
}
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="keyequalityComparer"></param>
protected DictionaryBase(SCG.IEqualityComparer<K> keyequalityComparer)
{
if (keyequalityComparer == null)
throw new NullReferenceException("Key equality comparer cannot be null");
this.keyequalityComparer = keyequalityComparer;
}
#region IDictionary<K,V> Members
/// <summary>
///
/// </summary>
/// <value></value>
public virtual SCG.IEqualityComparer<K> EqualityComparer { get { return keyequalityComparer; } }
/// <summary>
/// Add a new (key, value) pair (a mapping) to the dictionary.
/// </summary>
/// <exception cref="DuplicateNotAllowedException"> if there already is an entry with the same key. </exception>
/// <param name="key">Key to add</param>
/// <param name="value">Value to add</param>
public virtual void Add(K key, V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
if (!pairs.Add(p))
throw new DuplicateNotAllowedException("Key being added: '" + key + "'");
}
/// <summary>
/// Add the entries from a collection of <see cref="T:C5.KeyValuePair`2"/> pairs to this dictionary.
/// <para><b>TODO: add restrictions L:K and W:V when the .Net SDK allows it </b></para>
/// </summary>
/// <exception cref="DuplicateNotAllowedException">
/// If the input contains duplicate keys or a key already present in this dictionary.</exception>
/// <param name="entries"></param>
public virtual void AddAll<L, W>(SCG.IEnumerable<KeyValuePair<L, W>> entries)
where L : K
where W : V
{
foreach (KeyValuePair<L, W> pair in entries)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(pair.Key, pair.Value);
if (!pairs.Add(p))
throw new DuplicateNotAllowedException("Key being added: '" + pair.Key + "'");
}
}
/// <summary>
/// Remove an entry with a given key from the dictionary
/// </summary>
/// <param name="key">The key of the entry to remove</param>
/// <returns>True if an entry was found (and removed)</returns>
public virtual bool Remove(K key)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
return pairs.Remove(p);
}
/// <summary>
/// Remove an entry with a given key from the dictionary and report its value.
/// </summary>
/// <param name="key">The key of the entry to remove</param>
/// <param name="value">On exit, the value of the removed entry</param>
/// <returns>True if an entry was found (and removed)</returns>
public virtual bool Remove(K key, out V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
if (pairs.Remove(p, out p))
{
value = p.Value;
return true;
}
else
{
value = default(V);
return false;
}
}
/// <summary>
/// Remove all entries from the dictionary
/// </summary>
public virtual void Clear() { pairs.Clear(); }
/// <summary>
///
/// </summary>
/// <value></value>
public virtual Speed ContainsSpeed { get { return pairs.ContainsSpeed; } }
/// <summary>
/// Check if there is an entry with a specified key
/// </summary>
/// <param name="key">The key to look for</param>
/// <returns>True if key was found</returns>
public virtual bool Contains(K key)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
return pairs.Contains(p);
}
[Serializable]
class LiftedEnumerable<H> : SCG.IEnumerable<KeyValuePair<K, V>> where H : K
{
SCG.IEnumerable<H> keys;
public LiftedEnumerable(SCG.IEnumerable<H> keys) { this.keys = keys; }
public SCG.IEnumerator<KeyValuePair<K, V>> GetEnumerator() { foreach (H key in keys) yield return new KeyValuePair<K, V>(key); }
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
#endregion
}
/// <summary>
///
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public virtual bool ContainsAll<H>(SCG.IEnumerable<H> keys) where H : K
{
return pairs.ContainsAll(new LiftedEnumerable<H>(keys));
}
/// <summary>
/// Check if there is an entry with a specified key and report the corresponding
/// value if found. This can be seen as a safe form of "val = this[key]".
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="value">On exit, the value of the entry</param>
/// <returns>True if key was found</returns>
public virtual bool Find(K key, out V value)
{
return Find(ref key, out value);
}
/// <summary>
/// Check if there is an entry with a specified key and report the corresponding
/// value if found. This can be seen as a safe form of "val = this[key]".
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="value">On exit, the value of the entry</param>
/// <returns>True if key was found</returns>
public virtual bool Find(ref K key, out V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
if (pairs.Find(ref p))
{
key = p.Key;
value = p.Value;
return true;
}
else
{
value = default(V);
return false;
}
}
/// <summary>
/// Look for a specific key in the dictionary and if found replace the value with a new one.
/// This can be seen as a non-adding version of "this[key] = val".
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="value">The new value</param>
/// <returns>True if key was found</returns>
public virtual bool Update(K key, V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
return pairs.Update(p);
}
/// <summary>
///
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="oldvalue"></param>
/// <returns></returns>
public virtual bool Update(K key, V value, out V oldvalue)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
bool retval = pairs.Update(p, out p);
oldvalue = p.Value;
return retval;
}
/// <summary>
/// Look for a specific key in the dictionary. If found, report the corresponding value,
/// else add an entry with the key and the supplied value.
/// </summary>
/// <param name="key">On entry the key to look for</param>
/// <param name="value">On entry the value to add if the key is not found.
/// On exit the value found if any.</param>
/// <returns>True if key was found</returns>
public virtual bool FindOrAdd(K key, ref V value)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
if (!pairs.FindOrAdd(ref p))
return false;
else
{
value = p.Value;
//key = p.key;
return true;
}
}
/// <summary>
/// Update value in dictionary corresponding to key if found, else add new entry.
/// More general than "this[key] = val;" by reporting if key was found.
/// </summary>
/// <param name="key">The key to look for</param>
/// <param name="value">The value to add or replace with.</param>
/// <returns>True if entry was updated.</returns>
public virtual bool UpdateOrAdd(K key, V value)
{
return pairs.UpdateOrAdd(new KeyValuePair<K, V>(key, value));
}
/// <summary>
/// Update value in dictionary corresponding to key if found, else add new entry.
/// More general than "this[key] = val;" by reporting if key was found and the old value if any.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="oldvalue"></param>
/// <returns></returns>
public virtual bool UpdateOrAdd(K key, V value, out V oldvalue)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key, value);
bool retval = pairs.UpdateOrAdd(p, out p);
oldvalue = p.Value;
return retval;
}
#region Keys,Values support classes
[Serializable]
internal class ValuesCollection : CollectionValueBase<V>, ICollectionValue<V>
{
ICollection<KeyValuePair<K, V>> pairs;
internal ValuesCollection(ICollection<KeyValuePair<K, V>> pairs)
{ this.pairs = pairs; }
public override V Choose() { return pairs.Choose().Value; }
public override SCG.IEnumerator<V> GetEnumerator()
{
//Updatecheck is performed by the pairs enumerator
foreach (KeyValuePair<K, V> p in pairs)
yield return p.Value;
}
public override bool IsEmpty { get { return pairs.IsEmpty; } }
public override int Count { get { return pairs.Count; } }
public override Speed CountSpeed { get { return Speed.Constant; } }
}
[Serializable]
internal class KeysCollection : CollectionValueBase<K>, ICollectionValue<K>
{
ICollection<KeyValuePair<K, V>> pairs;
internal KeysCollection(ICollection<KeyValuePair<K, V>> pairs)
{ this.pairs = pairs; }
public override K Choose() { return pairs.Choose().Key; }
public override SCG.IEnumerator<K> GetEnumerator()
{
foreach (KeyValuePair<K, V> p in pairs)
yield return p.Key;
}
public override bool IsEmpty { get { return pairs.IsEmpty; } }
public override int Count { get { return pairs.Count; } }
public override Speed CountSpeed { get { return pairs.CountSpeed; } }
}
#endregion
/// <summary>
///
/// </summary>
/// <value>A collection containg the all the keys of the dictionary</value>
public virtual ICollectionValue<K> Keys { get { return new KeysCollection(pairs); } }
/// <summary>
///
/// </summary>
/// <value>A collection containing all the values of the dictionary</value>
public virtual ICollectionValue<V> Values { get { return new ValuesCollection(pairs); } }
/// <summary>
///
/// </summary>
public virtual Func<K, V> Func { get { return delegate(K k) { return this[k]; }; } }
/// <summary>
/// Indexer by key for dictionary.
/// <para>The get method will throw an exception if no entry is found. </para>
/// <para>The set method behaves like <see cref="M:C5.DictionaryBase`2.UpdateOrAdd(`0,`1)"/>.</para>
/// </summary>
/// <exception cref="NoSuchItemException"> On get if no entry is found. </exception>
/// <value>The value corresponding to the key</value>
public virtual V this[K key]
{
get
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(key);
if (pairs.Find(ref p))
return p.Value;
else
throw new NoSuchItemException("Key '" + key.ToString() + "' not present in Dictionary");
}
set
{ pairs.UpdateOrAdd(new KeyValuePair<K, V>(key, value)); }
}
/// <summary>
///
/// </summary>
/// <value>True if dictionary is read only</value>
public virtual bool IsReadOnly { get { return pairs.IsReadOnly; } }
/// <summary>
/// Check the integrity of the internal data structures of this dictionary.
/// </summary>
/// <returns>True if check does not fail.</returns>
public virtual bool Check() { return pairs.Check(); }
#endregion
#region ICollectionValue<KeyValuePair<K,V>> Members
/// <summary>
///
/// </summary>
/// <value>True if this collection is empty.</value>
public override bool IsEmpty { get { return pairs.IsEmpty; } }
/// <summary>
///
/// </summary>
/// <value>The number of entrues in the dictionary</value>
public override int Count { get { return pairs.Count; } }
/// <summary>
///
/// </summary>
/// <value>The number of entrues in the dictionary</value>
public override Speed CountSpeed { get { return pairs.CountSpeed; } }
/// <summary>
/// Choose some entry in this Dictionary.
/// </summary>
/// <exception cref="NoSuchItemException">if collection is empty.</exception>
/// <returns></returns>
public override KeyValuePair<K, V> Choose() { return pairs.Choose(); }
/// <summary>
/// Create an enumerator for the collection of entries of the dictionary
/// </summary>
/// <returns>The enumerator</returns>
public override SCG.IEnumerator<KeyValuePair<K, V>> GetEnumerator()
{
return pairs.GetEnumerator(); ;
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public override bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
return Showing.ShowDictionary<K, V>(this, stringbuilder, ref rest, formatProvider);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public abstract object Clone();
}
/// <summary>
/// A base class for implementing a sorted dictionary based on a sorted set collection implementation.
/// <i>See the source code for <see cref="T:C5.TreeDictionary`2"/> for an example</i>
///
/// </summary>
[Serializable]
public abstract class SortedDictionaryBase<K, V> : DictionaryBase<K, V>, ISortedDictionary<K, V>
{
#region Fields
/// <summary>
///
/// </summary>
protected ISorted<KeyValuePair<K, V>> sortedpairs;
SCG.IComparer<K> keycomparer;
/// <summary>
///
/// </summary>
/// <param name="keycomparer"></param>
/// <param name="keyequalityComparer"></param>
protected SortedDictionaryBase(SCG.IComparer<K> keycomparer, SCG.IEqualityComparer<K> keyequalityComparer) : base(keyequalityComparer) { this.keycomparer = keycomparer; }
#endregion
#region ISortedDictionary<K,V> Members
/// <summary>
/// The key comparer used by this dictionary.
/// </summary>
/// <value></value>
public SCG.IComparer<K> Comparer { get { return keycomparer; } }
/// <summary>
///
/// </summary>
/// <value></value>
public new ISorted<K> Keys { get { return new SortedKeysCollection(this, sortedpairs, keycomparer, EqualityComparer); } }
/// <summary>
/// Find the entry in the dictionary whose key is the
/// predecessor of the specified key.
/// </summary>
/// <param name="key">The key</param>
/// <param name="res">The predecessor, if any</param>
/// <returns>True if key has a predecessor</returns>
public bool TryPredecessor(K key, out KeyValuePair<K, V> res)
{
return sortedpairs.TryPredecessor(new KeyValuePair<K, V>(key), out res);
}
/// <summary>
/// Find the entry in the dictionary whose key is the
/// successor of the specified key.
/// </summary>
/// <param name="key">The key</param>
/// <param name="res">The successor, if any</param>
/// <returns>True if the key has a successor</returns>
public bool TrySuccessor(K key, out KeyValuePair<K, V> res)
{
return sortedpairs.TrySuccessor(new KeyValuePair<K, V>(key), out res);
}
/// <summary>
/// Find the entry in the dictionary whose key is the
/// weak predecessor of the specified key.
/// </summary>
/// <param name="key">The key</param>
/// <param name="res">The predecessor, if any</param>
/// <returns>True if key has a weak predecessor</returns>
public bool TryWeakPredecessor(K key, out KeyValuePair<K, V> res)
{
return sortedpairs.TryWeakPredecessor(new KeyValuePair<K, V>(key), out res);
}
/// <summary>
/// Find the entry in the dictionary whose key is the
/// weak successor of the specified key.
/// </summary>
/// <param name="key">The key</param>
/// <param name="res">The weak successor, if any</param>
/// <returns>True if the key has a weak successor</returns>
public bool TryWeakSuccessor(K key, out KeyValuePair<K, V> res)
{
return sortedpairs.TryWeakSuccessor(new KeyValuePair<K, V>(key), out res);
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// predecessor of the specified key.
/// </summary>
/// <exception cref="NoSuchItemException"></exception>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
public KeyValuePair<K, V> Predecessor(K key)
{
return sortedpairs.Predecessor(new KeyValuePair<K, V>(key));
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// successor of the specified key.
/// </summary>
/// <exception cref="NoSuchItemException"></exception>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
public KeyValuePair<K, V> Successor(K key)
{
return sortedpairs.Successor(new KeyValuePair<K, V>(key));
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// weak predecessor of the specified key.
/// </summary>
/// <exception cref="NoSuchItemException"></exception>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
public KeyValuePair<K, V> WeakPredecessor(K key)
{
return sortedpairs.WeakPredecessor(new KeyValuePair<K, V>(key));
}
/// <summary>
/// Get the entry in the dictionary whose key is the
/// weak successor of the specified key.
/// </summary>
/// <exception cref="NoSuchItemException"></exception>
/// <param name="key">The key</param>
/// <returns>The entry</returns>
public KeyValuePair<K, V> WeakSuccessor(K key)
{
return sortedpairs.WeakSuccessor(new KeyValuePair<K, V>(key));
}
#endregion
#region ISortedDictionary<K,V> Members
/// <summary>
///
/// </summary>
/// <returns></returns>
public KeyValuePair<K, V> FindMin()
{
return sortedpairs.FindMin();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public KeyValuePair<K, V> DeleteMin()
{
return sortedpairs.DeleteMin();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public KeyValuePair<K, V> FindMax()
{
return sortedpairs.FindMax();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public KeyValuePair<K, V> DeleteMax()
{
return sortedpairs.DeleteMax();
}
/// <summary>
///
/// </summary>
/// <param name="cutter"></param>
/// <param name="lowEntry"></param>
/// <param name="lowIsValid"></param>
/// <param name="highEntry"></param>
/// <param name="highIsValid"></param>
/// <returns></returns>
public bool Cut(IComparable<K> cutter, out KeyValuePair<K, V> lowEntry, out bool lowIsValid, out KeyValuePair<K, V> highEntry, out bool highIsValid)
{
return sortedpairs.Cut(new KeyValuePairComparable(cutter), out lowEntry, out lowIsValid, out highEntry, out highIsValid);
}
/// <summary>
///
/// </summary>
/// <param name="bot"></param>
/// <returns></returns>
public IDirectedEnumerable<KeyValuePair<K, V>> RangeFrom(K bot)
{
return sortedpairs.RangeFrom(new KeyValuePair<K, V>(bot));
}
/// <summary>
///
/// </summary>
/// <param name="bot"></param>
/// <param name="top"></param>
/// <returns></returns>
public IDirectedEnumerable<KeyValuePair<K, V>> RangeFromTo(K bot, K top)
{
return sortedpairs.RangeFromTo(new KeyValuePair<K, V>(bot), new KeyValuePair<K, V>(top));
}
/// <summary>
///
/// </summary>
/// <param name="top"></param>
/// <returns></returns>
public IDirectedEnumerable<KeyValuePair<K, V>> RangeTo(K top)
{
return sortedpairs.RangeTo(new KeyValuePair<K, V>(top));
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public IDirectedCollectionValue<KeyValuePair<K, V>> RangeAll()
{
return sortedpairs.RangeAll();
}
/// <summary>
///
/// </summary>
/// <param name="items"></param>
public void AddSorted(SCG.IEnumerable<KeyValuePair<K, V>> items)
{
sortedpairs.AddSorted(items);
}
/// <summary>
///
/// </summary>
/// <param name="lowKey"></param>
public void RemoveRangeFrom(K lowKey)
{
sortedpairs.RemoveRangeFrom(new KeyValuePair<K, V>(lowKey));
}
/// <summary>
///
/// </summary>
/// <param name="lowKey"></param>
/// <param name="highKey"></param>
public void RemoveRangeFromTo(K lowKey, K highKey)
{
sortedpairs.RemoveRangeFromTo(new KeyValuePair<K, V>(lowKey), new KeyValuePair<K, V>(highKey));
}
/// <summary>
///
/// </summary>
/// <param name="highKey"></param>
public void RemoveRangeTo(K highKey)
{
sortedpairs.RemoveRangeTo(new KeyValuePair<K, V>(highKey));
}
#endregion
[Serializable]
class KeyValuePairComparable : IComparable<KeyValuePair<K, V>>
{
IComparable<K> cutter;
internal KeyValuePairComparable(IComparable<K> cutter) { this.cutter = cutter; }
public int CompareTo(KeyValuePair<K, V> other) { return cutter.CompareTo(other.Key); }
public bool Equals(KeyValuePair<K, V> other) { return cutter.Equals(other.Key); }
}
[Serializable]
class ProjectedDirectedEnumerable : MappedDirectedEnumerable<KeyValuePair<K, V>, K>
{
public ProjectedDirectedEnumerable(IDirectedEnumerable<KeyValuePair<K, V>> directedpairs) : base(directedpairs) { }
public override K Map(KeyValuePair<K, V> pair) { return pair.Key; }
}
[Serializable]
class ProjectedDirectedCollectionValue : MappedDirectedCollectionValue<KeyValuePair<K, V>, K>
{
public ProjectedDirectedCollectionValue(IDirectedCollectionValue<KeyValuePair<K, V>> directedpairs) : base(directedpairs) { }
public override K Map(KeyValuePair<K, V> pair) { return pair.Key; }
}
[Serializable]
class SortedKeysCollection : SequencedBase<K>, ISorted<K>
{
ISortedDictionary<K, V> sorteddict;
//TODO: eliminate this. Only problem is the Find method because we lack method on dictionary that also
// returns the actual key.
ISorted<KeyValuePair<K, V>> sortedpairs;
SCG.IComparer<K> comparer;
internal SortedKeysCollection(ISortedDictionary<K, V> sorteddict, ISorted<KeyValuePair<K, V>> sortedpairs, SCG.IComparer<K> comparer, SCG.IEqualityComparer<K> itemequalityComparer)
: base(itemequalityComparer)
{
this.sorteddict = sorteddict;
this.sortedpairs = sortedpairs;
this.comparer = comparer;
}
public override K Choose() { return sorteddict.Choose().Key; }
public override SCG.IEnumerator<K> GetEnumerator()
{
foreach (KeyValuePair<K, V> p in sorteddict)
yield return p.Key;
}
public override bool IsEmpty { get { return sorteddict.IsEmpty; } }
public override int Count { get { return sorteddict.Count; } }
public override Speed CountSpeed { get { return sorteddict.CountSpeed; } }
#region ISorted<K> Members
public K FindMin() { return sorteddict.FindMin().Key; }
public K DeleteMin() { throw new ReadOnlyCollectionException(); }
public K FindMax() { return sorteddict.FindMax().Key; }
public K DeleteMax() { throw new ReadOnlyCollectionException(); }
public SCG.IComparer<K> Comparer { get { return comparer; } }
public bool TryPredecessor(K item, out K res)
{
KeyValuePair<K, V> pRes;
bool success = sorteddict.TryPredecessor(item, out pRes);
res = pRes.Key;
return success;
}
public bool TrySuccessor(K item, out K res)
{
KeyValuePair<K, V> pRes;
bool success = sorteddict.TrySuccessor(item, out pRes);
res = pRes.Key;
return success;
}
public bool TryWeakPredecessor(K item, out K res)
{
KeyValuePair<K, V> pRes;
bool success = sorteddict.TryWeakPredecessor(item, out pRes);
res = pRes.Key;
return success;
}
public bool TryWeakSuccessor(K item, out K res)
{
KeyValuePair<K, V> pRes;
bool success = sorteddict.TryWeakSuccessor(item, out pRes);
res = pRes.Key;
return success;
}
public K Predecessor(K item) { return sorteddict.Predecessor(item).Key; }
public K Successor(K item) { return sorteddict.Successor(item).Key; }
public K WeakPredecessor(K item) { return sorteddict.WeakPredecessor(item).Key; }
public K WeakSuccessor(K item) { return sorteddict.WeakSuccessor(item).Key; }
public bool Cut(IComparable<K> c, out K low, out bool lowIsValid, out K high, out bool highIsValid)
{
KeyValuePair<K, V> lowpair, highpair;
bool retval = sorteddict.Cut(c, out lowpair, out lowIsValid, out highpair, out highIsValid);
low = lowpair.Key;
high = highpair.Key;
return retval;
}
public IDirectedEnumerable<K> RangeFrom(K bot)
{
return new ProjectedDirectedEnumerable(sorteddict.RangeFrom(bot));
}
public IDirectedEnumerable<K> RangeFromTo(K bot, K top)
{
return new ProjectedDirectedEnumerable(sorteddict.RangeFromTo(bot, top));
}
public IDirectedEnumerable<K> RangeTo(K top)
{
return new ProjectedDirectedEnumerable(sorteddict.RangeTo(top));
}
public IDirectedCollectionValue<K> RangeAll()
{
return new ProjectedDirectedCollectionValue(sorteddict.RangeAll());
}
public void AddSorted(SCG.IEnumerable<K> items) { throw new ReadOnlyCollectionException(); }
public void RemoveRangeFrom(K low) { throw new ReadOnlyCollectionException(); }
public void RemoveRangeFromTo(K low, K hi) { throw new ReadOnlyCollectionException(); }
public void RemoveRangeTo(K hi) { throw new ReadOnlyCollectionException(); }
#endregion
#region ICollection<K> Members
public Speed ContainsSpeed { get { return sorteddict.ContainsSpeed; } }
public bool Contains(K key) { return sorteddict.Contains(key); ; }
public int ContainsCount(K item) { return sorteddict.Contains(item) ? 1 : 0; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<K> UniqueItems()
{
return this;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual ICollectionValue<KeyValuePair<K, int>> ItemMultiplicities()
{
return new MultiplicityOne<K>(this);
}
public bool ContainsAll(SCG.IEnumerable<K> items)
{
//TODO: optimize?
foreach (K item in items)
if (!sorteddict.Contains(item))
return false;
return true;
}
public bool Find(ref K item)
{
KeyValuePair<K, V> p = new KeyValuePair<K, V>(item);
bool retval = sortedpairs.Find(ref p);
item = p.Key;
return retval;
}
public bool FindOrAdd(ref K item) { throw new ReadOnlyCollectionException(); }
public bool Update(K item) { throw new ReadOnlyCollectionException(); }
public bool Update(K item, out K olditem) { throw new ReadOnlyCollectionException(); }
public bool UpdateOrAdd(K item) { throw new ReadOnlyCollectionException(); }
public bool UpdateOrAdd(K item, out K olditem) { throw new ReadOnlyCollectionException(); }
public bool Remove(K item) { throw new ReadOnlyCollectionException(); }
public bool Remove(K item, out K removeditem) { throw new ReadOnlyCollectionException(); }
public void RemoveAllCopies(K item) { throw new ReadOnlyCollectionException(); }
public void RemoveAll(SCG.IEnumerable<K> items) { throw new ReadOnlyCollectionException(); }
public void Clear() { throw new ReadOnlyCollectionException(); }
public void RetainAll(SCG.IEnumerable<K> items) { throw new ReadOnlyCollectionException(); }
#endregion
#region IExtensible<K> Members
public override bool IsReadOnly { get { return true; } }
public bool AllowsDuplicates { get { return false; } }
public bool DuplicatesByCounting { get { return true; } }
public bool Add(K item) { throw new ReadOnlyCollectionException(); }
void SCG.ICollection<K>.Add(K item) { throw new ReadOnlyCollectionException(); }
public void AddAll(System.Collections.Generic.IEnumerable<K> items) { throw new ReadOnlyCollectionException(); }
public bool Check() { return sorteddict.Check(); }
#endregion
#region IDirectedCollectionValue<K> Members
public override IDirectedCollectionValue<K> Backwards()
{
return RangeAll().Backwards();
}
#endregion
#region IDirectedEnumerable<K> Members
IDirectedEnumerable<K> IDirectedEnumerable<K>.Backwards() { return Backwards(); }
#endregion
#region ICloneable Members
//TODO: test
/// <summary>
/// Make a shallow copy of this SortedKeysCollection.
/// </summary>
/// <returns></returns>
public virtual object Clone()
{
//
SortedArrayDictionary<K, V> dictclone = new SortedArrayDictionary<K, V>(sortedpairs.Count, comparer, EqualityComparer);
SortedArray<KeyValuePair<K, V>> sortedpairsclone = (SortedArray<KeyValuePair<K, V>>)(dictclone.sortedpairs);
foreach (K key in sorteddict.Keys)
{
sortedpairsclone.Add(new KeyValuePair<K, V>(key, default(V)));
}
return new SortedKeysCollection(dictclone, sortedpairsclone, comparer, EqualityComparer);
}
#endregion
}
/// <summary>
///
/// </summary>
/// <param name="stringbuilder"></param>
/// <param name="rest"></param>
/// <param name="formatProvider"></param>
/// <returns></returns>
public override bool Show(System.Text.StringBuilder stringbuilder, ref int rest, IFormatProvider formatProvider)
{
return Showing.ShowDictionary<K, V>(this, stringbuilder, ref rest, formatProvider);
}
}
[Serializable]
class SortedArrayDictionary<K, V> : SortedDictionaryBase<K, V>, IDictionary<K, V>, ISortedDictionary<K, V>
{
#region Constructors
public SortedArrayDictionary() : this(Comparer<K>.Default, EqualityComparer<K>.Default) { }
/// <summary>
/// Create a red-black tree dictionary using an external comparer for keys.
/// </summary>
/// <param name="comparer">The external comparer</param>
public SortedArrayDictionary(SCG.IComparer<K> comparer) : this(comparer, new ComparerZeroHashCodeEqualityComparer<K>(comparer)) { }
/// <summary>
///
/// </summary>
/// <param name="comparer"></param>
/// <param name="equalityComparer"></param>
public SortedArrayDictionary(SCG.IComparer<K> comparer, SCG.IEqualityComparer<K> equalityComparer)
: base(comparer, equalityComparer)
{
pairs = sortedpairs = new SortedArray<KeyValuePair<K, V>>(new KeyValuePairComparer<K, V>(comparer));
}
/// <summary>
///
/// </summary>
/// <param name="comparer"></param>
/// <param name="equalityComparer"></param>
/// <param name="capacity"></param>
public SortedArrayDictionary(int capacity, SCG.IComparer<K> comparer, SCG.IEqualityComparer<K> equalityComparer)
: base(comparer, equalityComparer)
{
pairs = sortedpairs = new SortedArray<KeyValuePair<K, V>>(capacity, new KeyValuePairComparer<K, V>(comparer));
}
#endregion
/// <summary>
///
/// </summary>
/// <returns></returns>
public override object Clone()
{
SortedArrayDictionary<K, V> clone = new SortedArrayDictionary<K, V>(Comparer, EqualityComparer);
clone.sortedpairs.AddSorted(sortedpairs);
return clone;
}
}
}
| |
using MatterHackers.VectorMath;
using System;
using System.Reflection;
using System.Xml;
namespace Gaming.Game
{
#region GameDataValueAttribute
[AttributeUsage(AttributeTargets.Field)]
public class GameDataNumberAttribute : GameDataAttribute
{
private double m_MinValue;
private double m_MaxValue;
private double m_Increment;
public GameDataNumberAttribute(string name)
: base(name)
{
m_Increment = 1;
m_MinValue = double.MinValue;
m_MaxValue = double.MaxValue;
}
public override object ReadField(XmlReader xmlReader)
{
return xmlReader.ReadElementContentAsDouble();
}
public override void WriteField(XmlWriter xmlWriter, object fieldToWrite)
{
if (!fieldToWrite.GetType().IsValueType)
{
throw new Exception("You can only put a GameDataNumberAttribute on a ValueType.");
}
base.WriteField(xmlWriter, fieldToWrite);
}
public double Min
{
get
{
return m_MinValue;
}
set
{
m_MinValue = value;
}
}
public double Max
{
get
{
return m_MaxValue;
}
set
{
m_MaxValue = value;
}
}
public double Increment
{
get
{
return m_Increment;
}
set
{
m_Increment = value;
}
}
}
#endregion GameDataValueAttribute
#region GameDataBoolAttribute
[AttributeUsage(AttributeTargets.Field)]
public class GameDataBoolAttribute : GameDataAttribute
{
public GameDataBoolAttribute(string name)
: base(name)
{
}
public override object ReadField(XmlReader xmlReader)
{
return xmlReader.ReadElementContentAsBoolean();
}
public override void WriteField(XmlWriter xmlWriter, object fieldToWrite)
{
if (!fieldToWrite.GetType().IsPrimitive)
{
throw new Exception("You can only put a GameDataBoolAttribute on a Boolean.");
}
base.WriteField(xmlWriter, fieldToWrite);
}
}
#endregion GameDataBoolAttribute
#region GameDataVector2DAttribute
[AttributeUsage(AttributeTargets.Field)]
public class GameDataVector2DAttribute : GameDataAttribute
{
public GameDataVector2DAttribute(string name)
: base(name)
{
}
public override object ReadField(XmlReader xmlReader)
{
var newVector2D = (Vector2)GameDataAttribute.ReadTypeAttributes(xmlReader);
string xString = xmlReader.GetAttribute("x");
string yString = xmlReader.GetAttribute("y");
newVector2D = new Vector2(Convert.ToDouble(xString), Convert.ToDouble(yString));
return newVector2D;
}
public override void WriteField(XmlWriter xmlWriter, object fieldToWrite)
{
if (!(fieldToWrite is Vector2))
{
throw new Exception("You can only put a GameDataVector2DAttribute on a Vector2D.");
}
var vector2DToWrite = (Vector2)fieldToWrite;
xmlWriter.WriteStartAttribute("x");
xmlWriter.WriteValue(vector2DToWrite.X);
xmlWriter.WriteEndAttribute();
xmlWriter.WriteStartAttribute("y");
xmlWriter.WriteValue(vector2DToWrite.Y);
xmlWriter.WriteEndAttribute();
}
}
#endregion GameDataVector2DAttribute
#region GameDataListAttribute
[AttributeUsage(AttributeTargets.Field)]
public class GameDataListAttribute : GameDataAttribute
{
public GameDataListAttribute(string name)
: base(name)
{
}
public override object ReadField(XmlReader xmlReader)
{
object list = GameDataAttribute.ReadTypeAttributes(xmlReader);
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element)
{
if (xmlReader.Name == "Item")
{
object listItem = GameDataAttribute.ReadTypeAttributes(xmlReader);
if (listItem is GameObject)
{
var listGameObject = (GameObject)listItem;
listGameObject.LoadGameObjectData(xmlReader);
MethodInfo addMethod = list.GetType().GetMethod("Add");
addMethod.Invoke(list, new object[] { listGameObject });
}
else
{
throw new NotImplementedException("List of non-GameObjects not deserializable");
}
}
}
else if (xmlReader.NodeType == XmlNodeType.EndElement)
{
break;
}
}
return list;
}
public override void WriteField(XmlWriter xmlWriter, object fieldToWrite)
{
object list = fieldToWrite;
int listCount = (int)list.GetType().GetProperty("Count").GetValue(list, null);
for (int index = 0; index < listCount; index++)
{
object item = list.GetType().GetMethod("get_Item").Invoke(list, new object[] { index });
if (item is GameObject)
{
xmlWriter.WriteStartElement("Item");
GameDataAttribute.WriteTypeAttributes(xmlWriter, item);
((GameObject)item).WriteGameObjectData(xmlWriter);
xmlWriter.WriteEndElement();
}
else
{
xmlWriter.WriteValue(item);
xmlWriter.WriteValue(" ");
}
}
}
}
#endregion GameDataListAttribute
}
| |
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 NUnit.Framework;
using Newtonsoft.Json;
using GlmSharp;
// ReSharper disable InconsistentNaming
namespace GlmSharpTest.Generated.Vec3
{
[TestFixture]
public class LongVec3Test
{
[Test]
public void Constructors()
{
{
var v = new lvec3(-8L);
Assert.AreEqual(-8L, v.x);
Assert.AreEqual(-8L, v.y);
Assert.AreEqual(-8L, v.z);
}
{
var v = new lvec3(9L, -9L, 3L);
Assert.AreEqual(9L, v.x);
Assert.AreEqual(-9L, v.y);
Assert.AreEqual(3L, v.z);
}
{
var v = new lvec3(new lvec2(-5L, -7L));
Assert.AreEqual(-5L, v.x);
Assert.AreEqual(-7L, v.y);
Assert.AreEqual(0, v.z);
}
{
var v = new lvec3(new lvec3(6L, -6L, -9L));
Assert.AreEqual(6L, v.x);
Assert.AreEqual(-6L, v.y);
Assert.AreEqual(-9L, v.z);
}
{
var v = new lvec3(new lvec4(0, 4L, 6L, -1L));
Assert.AreEqual(0, v.x);
Assert.AreEqual(4L, v.y);
Assert.AreEqual(6L, v.z);
}
}
[Test]
public void Indexer()
{
var v = new lvec3(-8L, -8L, -1L);
Assert.AreEqual(-8L, v[0]);
Assert.AreEqual(-8L, v[1]);
Assert.AreEqual(-1L, v[2]);
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-2147483648]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[-2147483648] = 0; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[-1]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[-1] = 0; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[3]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[3] = 0; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[2147483647]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[2147483647] = 0; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { var s = v[5]; } );
Assert.Throws<ArgumentOutOfRangeException>(() => { v[5] = 0; } );
v[1] = 0;
Assert.AreEqual(0, v[1]);
v[2] = 1;
Assert.AreEqual(1, v[2]);
v[1] = 2L;
Assert.AreEqual(2L, v[1]);
v[2] = 3L;
Assert.AreEqual(3L, v[2]);
v[2] = 4L;
Assert.AreEqual(4L, v[2]);
v[1] = 5L;
Assert.AreEqual(5L, v[1]);
v[0] = 6L;
Assert.AreEqual(6L, v[0]);
v[1] = 7L;
Assert.AreEqual(7L, v[1]);
v[1] = 8L;
Assert.AreEqual(8L, v[1]);
v[1] = 9L;
Assert.AreEqual(9L, v[1]);
v[2] = -1L;
Assert.AreEqual(-1L, v[2]);
v[2] = -2L;
Assert.AreEqual(-2L, v[2]);
v[1] = -3L;
Assert.AreEqual(-3L, v[1]);
v[1] = -4L;
Assert.AreEqual(-4L, v[1]);
v[1] = -5L;
Assert.AreEqual(-5L, v[1]);
v[0] = -6L;
Assert.AreEqual(-6L, v[0]);
v[1] = -7L;
Assert.AreEqual(-7L, v[1]);
v[1] = -8L;
Assert.AreEqual(-8L, v[1]);
v[1] = -9L;
Assert.AreEqual(-9L, v[1]);
}
[Test]
public void PropertyValues()
{
var v = new lvec3(-1L, 1, 6L);
var vals = v.Values;
Assert.AreEqual(-1L, vals[0]);
Assert.AreEqual(1, vals[1]);
Assert.AreEqual(6L, vals[2]);
Assert.That(vals.SequenceEqual(v.ToArray()));
}
[Test]
public void StaticProperties()
{
Assert.AreEqual(0, lvec3.Zero.x);
Assert.AreEqual(0, lvec3.Zero.y);
Assert.AreEqual(0, lvec3.Zero.z);
Assert.AreEqual(1, lvec3.Ones.x);
Assert.AreEqual(1, lvec3.Ones.y);
Assert.AreEqual(1, lvec3.Ones.z);
Assert.AreEqual(1, lvec3.UnitX.x);
Assert.AreEqual(0, lvec3.UnitX.y);
Assert.AreEqual(0, lvec3.UnitX.z);
Assert.AreEqual(0, lvec3.UnitY.x);
Assert.AreEqual(1, lvec3.UnitY.y);
Assert.AreEqual(0, lvec3.UnitY.z);
Assert.AreEqual(0, lvec3.UnitZ.x);
Assert.AreEqual(0, lvec3.UnitZ.y);
Assert.AreEqual(1, lvec3.UnitZ.z);
Assert.AreEqual(long.MaxValue, lvec3.MaxValue.x);
Assert.AreEqual(long.MaxValue, lvec3.MaxValue.y);
Assert.AreEqual(long.MaxValue, lvec3.MaxValue.z);
Assert.AreEqual(long.MinValue, lvec3.MinValue.x);
Assert.AreEqual(long.MinValue, lvec3.MinValue.y);
Assert.AreEqual(long.MinValue, lvec3.MinValue.z);
}
[Test]
public void Operators()
{
var v1 = new lvec3(6L, -5L, 3L);
var v2 = new lvec3(6L, -5L, 3L);
var v3 = new lvec3(3L, -5L, 6L);
Assert.That(v1 == new lvec3(v1));
Assert.That(v2 == new lvec3(v2));
Assert.That(v3 == new lvec3(v3));
Assert.That(v1 == v2);
Assert.That(v1 != v3);
Assert.That(v2 != v3);
}
[Test]
public void StringInterop()
{
var v = new lvec3(8L, 3L, -7L);
var s0 = v.ToString();
var s1 = v.ToString("#");
var v0 = lvec3.Parse(s0);
var v1 = lvec3.Parse(s1, "#");
Assert.AreEqual(v, v0);
Assert.AreEqual(v, v1);
var b0 = lvec3.TryParse(s0, out v0);
var b1 = lvec3.TryParse(s1, "#", out v1);
Assert.That(b0);
Assert.That(b1);
Assert.AreEqual(v, v0);
Assert.AreEqual(v, v1);
b0 = lvec3.TryParse(null, out v0);
Assert.False(b0);
b0 = lvec3.TryParse("", out v0);
Assert.False(b0);
b0 = lvec3.TryParse(s0 + ", 0", out v0);
Assert.False(b0);
Assert.Throws<NullReferenceException>(() => { lvec3.Parse(null); });
Assert.Throws<FormatException>(() => { lvec3.Parse(""); });
Assert.Throws<FormatException>(() => { lvec3.Parse(s0 + ", 0"); });
var s2 = v.ToString(";", CultureInfo.InvariantCulture);
Assert.That(s2.Length > 0);
var s3 = v.ToString("; ", "G");
var s4 = v.ToString("; ", "G", CultureInfo.InvariantCulture);
var v3 = lvec3.Parse(s3, "; ", NumberStyles.Number);
var v4 = lvec3.Parse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture);
Assert.AreEqual(v, v3);
Assert.AreEqual(v, v4);
var b4 = lvec3.TryParse(s4, "; ", NumberStyles.Number, CultureInfo.InvariantCulture, out v4);
Assert.That(b4);
Assert.AreEqual(v, v4);
}
[Test]
public void SerializationJson()
{
var v0 = new lvec3(-1L, 4L, -7L);
var s0 = JsonConvert.SerializeObject(v0);
var v1 = JsonConvert.DeserializeObject<lvec3>(s0);
var s1 = JsonConvert.SerializeObject(v1);
Assert.AreEqual(v0, v1);
Assert.AreEqual(s0, s1);
}
[Test]
public void InvariantId()
{
{
var v0 = new lvec3(-9L, 6L, 5L);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new lvec3(-4L, 0, 3L);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new lvec3(9L, -9L, -7L);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new lvec3(-7L, 3L, -1L);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new lvec3(-3L, 9L, 5L);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new lvec3(5L, 3L, 4L);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new lvec3(-3L, -5L, -3L);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new lvec3(-5L, -9L, -2L);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new lvec3(-6L, 4L, 2L);
Assert.AreEqual(v0, +v0);
}
{
var v0 = new lvec3(2L, 3L, 1);
Assert.AreEqual(v0, +v0);
}
}
[Test]
public void InvariantDouble()
{
{
var v0 = new lvec3(-7L, 7L, -5L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new lvec3(-6L, -1L, -5L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new lvec3(-5L, 1, 9L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new lvec3(1, -4L, 7L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new lvec3(0, -6L, 5L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new lvec3(9L, -1L, 4L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new lvec3(-4L, 4L, -2L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new lvec3(0, 7L, -6L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new lvec3(-8L, -3L, 6L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
{
var v0 = new lvec3(-5L, -1L, -6L);
Assert.AreEqual(v0 + v0, 2 * v0);
}
}
[Test]
public void InvariantTriple()
{
{
var v0 = new lvec3(5L, 7L, 5L);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new lvec3(5L, 2L, -4L);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new lvec3(-9L, -1L, -6L);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new lvec3(-1L, -3L, 3L);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new lvec3(5L, 3L, 4L);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new lvec3(-3L, -2L, 2L);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new lvec3(-5L, -6L, 1);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new lvec3(8L, -1L, -3L);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new lvec3(-9L, -2L, -2L);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
{
var v0 = new lvec3(3L, -3L, -7L);
Assert.AreEqual(v0 + v0 + v0, 3 * v0);
}
}
[Test]
public void InvariantCommutative()
{
{
var v0 = new lvec3(-3L, 6L, -6L);
var v1 = new lvec3(-3L, 1, -9L);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new lvec3(-7L, 7L, 9L);
var v1 = new lvec3(5L, -2L, -4L);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new lvec3(-1L, -6L, 2L);
var v1 = new lvec3(-8L, 0, 8L);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new lvec3(-4L, 1, 0);
var v1 = new lvec3(6L, 0, 0);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new lvec3(-1L, -7L, -5L);
var v1 = new lvec3(1, -8L, 1);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new lvec3(-9L, -9L, 0);
var v1 = new lvec3(2L, 6L, -2L);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new lvec3(-4L, 9L, 5L);
var v1 = new lvec3(8L, 7L, -6L);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new lvec3(1, -5L, -1L);
var v1 = new lvec3(4L, 8L, -7L);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new lvec3(-9L, 3L, 4L);
var v1 = new lvec3(-1L, -2L, 9L);
Assert.AreEqual(v0 * v1, v1 * v0);
}
{
var v0 = new lvec3(1, 6L, 5L);
var v1 = new lvec3(-6L, 2L, 3L);
Assert.AreEqual(v0 * v1, v1 * v0);
}
}
[Test]
public void InvariantAssociative()
{
{
var v0 = new lvec3(1, -4L, -2L);
var v1 = new lvec3(0, -6L, 3L);
var v2 = new lvec3(4L, 6L, -7L);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new lvec3(-3L, 2L, 1);
var v1 = new lvec3(2L, -7L, 8L);
var v2 = new lvec3(-9L, -4L, 3L);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new lvec3(-4L, -6L, -1L);
var v1 = new lvec3(-3L, -3L, -2L);
var v2 = new lvec3(4L, 6L, 5L);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new lvec3(8L, 4L, -1L);
var v1 = new lvec3(4L, -2L, 3L);
var v2 = new lvec3(9L, 0, 2L);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new lvec3(-6L, 0, -4L);
var v1 = new lvec3(5L, -1L, -9L);
var v2 = new lvec3(3L, -3L, -3L);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new lvec3(-6L, 2L, -4L);
var v1 = new lvec3(8L, 1, -4L);
var v2 = new lvec3(-9L, 7L, 4L);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new lvec3(6L, 8L, 0);
var v1 = new lvec3(0, -6L, 8L);
var v2 = new lvec3(-7L, -5L, 1);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new lvec3(5L, 7L, 9L);
var v1 = new lvec3(-8L, -3L, -6L);
var v2 = new lvec3(6L, 3L, -4L);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new lvec3(8L, 7L, 4L);
var v1 = new lvec3(-2L, 8L, 0);
var v2 = new lvec3(-8L, 7L, 4L);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
{
var v0 = new lvec3(-1L, -9L, 3L);
var v1 = new lvec3(-6L, 4L, 4L);
var v2 = new lvec3(-8L, 2L, -1L);
Assert.AreEqual(v0 * (v1 + v2), v0 * v1 + v0 * v2);
}
}
[Test]
public void InvariantIdNeg()
{
{
var v0 = new lvec3(2L, 7L, 9L);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new lvec3(-9L, 2L, -8L);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new lvec3(-2L, 1, 0);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new lvec3(7L, -9L, -2L);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new lvec3(-7L, -1L, -6L);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new lvec3(-5L, -2L, 2L);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new lvec3(6L, 5L, -6L);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new lvec3(-9L, -8L, -7L);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new lvec3(-8L, 7L, 8L);
Assert.AreEqual(v0, -(-v0));
}
{
var v0 = new lvec3(-5L, -3L, 3L);
Assert.AreEqual(v0, -(-v0));
}
}
[Test]
public void InvariantCommutativeNeg()
{
{
var v0 = new lvec3(5L, -9L, -7L);
var v1 = new lvec3(1, -1L, -9L);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new lvec3(9L, 6L, -5L);
var v1 = new lvec3(-9L, -2L, -1L);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new lvec3(5L, -3L, 5L);
var v1 = new lvec3(3L, -7L, -1L);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new lvec3(-4L, -1L, -6L);
var v1 = new lvec3(8L, -4L, 4L);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new lvec3(7L, 9L, 9L);
var v1 = new lvec3(-5L, 4L, 3L);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new lvec3(1, 2L, 5L);
var v1 = new lvec3(8L, -7L, -4L);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new lvec3(-4L, 8L, -7L);
var v1 = new lvec3(1, 4L, -8L);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new lvec3(9L, -1L, 4L);
var v1 = new lvec3(2L, 3L, 2L);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new lvec3(-7L, 2L, -3L);
var v1 = new lvec3(5L, -4L, -5L);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
{
var v0 = new lvec3(0, -6L, 4L);
var v1 = new lvec3(-3L, -4L, 0);
Assert.AreEqual(v0 - v1, -(v1 - v0));
}
}
[Test]
public void InvariantAssociativeNeg()
{
{
var v0 = new lvec3(7L, 8L, -9L);
var v1 = new lvec3(9L, -2L, 6L);
var v2 = new lvec3(-2L, -5L, 2L);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new lvec3(-1L, -1L, -1L);
var v1 = new lvec3(2L, -7L, 5L);
var v2 = new lvec3(7L, -9L, 5L);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new lvec3(8L, -2L, 2L);
var v1 = new lvec3(4L, 3L, -5L);
var v2 = new lvec3(-3L, 9L, 1);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new lvec3(-3L, -4L, 2L);
var v1 = new lvec3(-3L, 1, 3L);
var v2 = new lvec3(-8L, 5L, 2L);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new lvec3(-3L, 5L, 3L);
var v1 = new lvec3(1, 2L, -9L);
var v2 = new lvec3(4L, 0, 9L);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new lvec3(-1L, -2L, -9L);
var v1 = new lvec3(-2L, 5L, -9L);
var v2 = new lvec3(-5L, -1L, 4L);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new lvec3(5L, 3L, 5L);
var v1 = new lvec3(4L, -6L, 2L);
var v2 = new lvec3(4L, -8L, 0);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new lvec3(-9L, -7L, 8L);
var v1 = new lvec3(6L, 3L, -2L);
var v2 = new lvec3(2L, -4L, -4L);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new lvec3(2L, 6L, 8L);
var v1 = new lvec3(3L, -9L, 2L);
var v2 = new lvec3(4L, 2L, -8L);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
{
var v0 = new lvec3(2L, 1, 8L);
var v1 = new lvec3(3L, -8L, 9L);
var v2 = new lvec3(-8L, -3L, 2L);
Assert.AreEqual(v0 * (v1 - v2), v0 * v1 - v0 * v2);
}
}
[Test]
public void TriangleInequality()
{
{
var v0 = new lvec3(5L, 1, 6L);
var v1 = new lvec3(5L, -8L, 2L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new lvec3(1, 3L, -5L);
var v1 = new lvec3(-5L, -3L, -9L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new lvec3(-8L, -4L, -6L);
var v1 = new lvec3(4L, -6L, -2L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new lvec3(-7L, -5L, 3L);
var v1 = new lvec3(5L, 9L, -4L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new lvec3(-1L, 7L, 0);
var v1 = new lvec3(-5L, 1, -6L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new lvec3(-9L, 3L, -1L);
var v1 = new lvec3(1, -8L, 8L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new lvec3(3L, -8L, -7L);
var v1 = new lvec3(-9L, 4L, -4L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new lvec3(3L, -3L, -6L);
var v1 = new lvec3(6L, 1, -5L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new lvec3(4L, 0, 2L);
var v1 = new lvec3(8L, -7L, -5L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
{
var v0 = new lvec3(-4L, -9L, -1L);
var v1 = new lvec3(-2L, -4L, -1L);
Assert.GreaterOrEqual(v0.NormMax + v1.NormMax, (v0 + v1).NormMax);
}
}
[Test]
public void InvariantNorm()
{
{
var v0 = new lvec3(4L, 9L, -3L);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new lvec3(-5L, -5L, -8L);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new lvec3(7L, 4L, -9L);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new lvec3(1, 5L, 8L);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new lvec3(4L, 7L, -8L);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new lvec3(2L, 4L, 2L);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new lvec3(-8L, 4L, -6L);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new lvec3(8L, 2L, 1);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new lvec3(-6L, -1L, -9L);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
{
var v0 = new lvec3(-2L, -1L, -6L);
Assert.LessOrEqual(v0.NormMax, v0.Norm);
}
}
[Test]
public void InvariantCrossDot()
{
{
var v0 = new lvec3(-4L, 4L, 3L);
var v1 = new lvec3(1, 7L, -9L);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
{
var v0 = new lvec3(6L, 9L, -1L);
var v1 = new lvec3(-5L, -4L, -4L);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
{
var v0 = new lvec3(-9L, -9L, 3L);
var v1 = new lvec3(-7L, -8L, 2L);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
{
var v0 = new lvec3(-3L, -2L, 3L);
var v1 = new lvec3(-8L, 9L, 6L);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
{
var v0 = new lvec3(-3L, 2L, 0);
var v1 = new lvec3(2L, 0, 1);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
{
var v0 = new lvec3(-5L, 9L, -2L);
var v1 = new lvec3(5L, -3L, -9L);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
{
var v0 = new lvec3(-2L, -4L, 2L);
var v1 = new lvec3(-7L, 1, -8L);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
{
var v0 = new lvec3(4L, 2L, 0);
var v1 = new lvec3(4L, 8L, 4L);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
{
var v0 = new lvec3(4L, -2L, 0);
var v1 = new lvec3(7L, 3L, -2L);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
{
var v0 = new lvec3(-1L, -5L, -5L);
var v1 = new lvec3(-6L, 7L, 5L);
Assert.Less(glm.Abs(glm.Dot(v0, glm.Cross(v0, v1))), 0.1);
}
}
[Test]
public void RandomUniform0()
{
var random = new Random(69950535);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.Random(random, 4, 6);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 4.5, 1.0);
Assert.AreEqual(avg.y, 4.5, 1.0);
Assert.AreEqual(avg.z, 4.5, 1.0);
Assert.AreEqual(variance.x, 0.25, 3.0);
Assert.AreEqual(variance.y, 0.25, 3.0);
Assert.AreEqual(variance.z, 0.25, 3.0);
}
[Test]
public void RandomUniform1()
{
var random = new Random(1498866180);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.RandomUniform(random, -1, 3);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0.5, 1.0);
Assert.AreEqual(avg.y, 0.5, 1.0);
Assert.AreEqual(avg.z, 0.5, 1.0);
Assert.AreEqual(variance.x, 1.25, 3.0);
Assert.AreEqual(variance.y, 1.25, 3.0);
Assert.AreEqual(variance.z, 1.25, 3.0);
}
[Test]
public void RandomUniform2()
{
var random = new Random(780298178);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.Random(random, 4, 8);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 5.5, 1.0);
Assert.AreEqual(avg.y, 5.5, 1.0);
Assert.AreEqual(avg.z, 5.5, 1.0);
Assert.AreEqual(variance.x, 1.25, 3.0);
Assert.AreEqual(variance.y, 1.25, 3.0);
Assert.AreEqual(variance.z, 1.25, 3.0);
}
[Test]
public void RandomUniform3()
{
var random = new Random(61730176);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.RandomUniform(random, -1, 2);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0, 1.0);
Assert.AreEqual(avg.y, 0, 1.0);
Assert.AreEqual(avg.z, 0, 1.0);
Assert.AreEqual(variance.x, 0.666666666666667, 3.0);
Assert.AreEqual(variance.y, 0.666666666666667, 3.0);
Assert.AreEqual(variance.z, 0.666666666666667, 3.0);
}
[Test]
public void RandomUniform4()
{
var random = new Random(796738896);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.Random(random, 4, 7);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 5, 1.0);
Assert.AreEqual(avg.y, 5, 1.0);
Assert.AreEqual(avg.z, 5, 1.0);
Assert.AreEqual(variance.x, 0.666666666666667, 3.0);
Assert.AreEqual(variance.y, 0.666666666666667, 3.0);
Assert.AreEqual(variance.z, 0.666666666666667, 3.0);
}
[Test]
public void RandomPoisson0()
{
var random = new Random(1596008656);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.RandomPoisson(random, 2.07107732983822);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.07107732983822, 1.0);
Assert.AreEqual(avg.y, 2.07107732983822, 1.0);
Assert.AreEqual(avg.z, 2.07107732983822, 1.0);
Assert.AreEqual(variance.x, 2.07107732983822, 3.0);
Assert.AreEqual(variance.y, 2.07107732983822, 3.0);
Assert.AreEqual(variance.z, 2.07107732983822, 3.0);
}
[Test]
public void RandomPoisson1()
{
var random = new Random(877440654);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.RandomPoisson(random, 0.736655773239516);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0.736655773239516, 1.0);
Assert.AreEqual(avg.y, 0.736655773239516, 1.0);
Assert.AreEqual(avg.z, 0.736655773239516, 1.0);
Assert.AreEqual(variance.x, 0.736655773239516, 3.0);
Assert.AreEqual(variance.y, 0.736655773239516, 3.0);
Assert.AreEqual(variance.z, 0.736655773239516, 3.0);
}
[Test]
public void RandomPoisson2()
{
var random = new Random(885661013);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.RandomPoisson(random, 2.1842229197194);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.1842229197194, 1.0);
Assert.AreEqual(avg.y, 2.1842229197194, 1.0);
Assert.AreEqual(avg.z, 2.1842229197194, 1.0);
Assert.AreEqual(variance.x, 2.1842229197194, 3.0);
Assert.AreEqual(variance.y, 2.1842229197194, 3.0);
Assert.AreEqual(variance.z, 2.1842229197194, 3.0);
}
[Test]
public void RandomPoisson3()
{
var random = new Random(167093011);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.RandomPoisson(random, 0.841521480279752);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 0.841521480279752, 1.0);
Assert.AreEqual(avg.y, 0.841521480279752, 1.0);
Assert.AreEqual(avg.z, 0.841521480279752, 1.0);
Assert.AreEqual(variance.x, 0.841521480279752, 3.0);
Assert.AreEqual(variance.y, 0.841521480279752, 3.0);
Assert.AreEqual(variance.z, 0.841521480279752, 3.0);
}
[Test]
public void RandomPoisson4()
{
var random = new Random(175313370);
var sum = new dvec3(0.0);
var sumSqr = new dvec3(0.0);
const int count = 50000;
for (var _ = 0; _ < count; ++_)
{
var v = lvec3.RandomPoisson(random, 2.28908862675963);
sum += (dvec3)v;
sumSqr += glm.Pow2((dvec3)v);
}
var avg = sum / (double)count;
var variance = sumSqr / (double)count - avg * avg;
Assert.AreEqual(avg.x, 2.28908862675963, 1.0);
Assert.AreEqual(avg.y, 2.28908862675963, 1.0);
Assert.AreEqual(avg.z, 2.28908862675963, 1.0);
Assert.AreEqual(variance.x, 2.28908862675963, 3.0);
Assert.AreEqual(variance.y, 2.28908862675963, 3.0);
Assert.AreEqual(variance.z, 2.28908862675963, 3.0);
}
}
}
| |
using System;
using System.Collections.Generic;
using Server.Items;
namespace Server.Engines.Craft
{
public enum CraftECA
{
ChanceMinusSixty,
FiftyPercentChanceMinusTenPercent,
ChanceMinusSixtyToFourtyFive
}
public abstract class CraftSystem
{
private int m_MinCraftEffect;
private int m_MaxCraftEffect;
private double m_Delay;
private bool m_Resmelt;
private bool m_Repair;
private bool m_MarkOption;
private bool m_CanEnhance;
private CraftItemCol m_CraftItems;
private CraftGroupCol m_CraftGroups;
private CraftSubResCol m_CraftSubRes;
private CraftSubResCol m_CraftSubRes2;
private List<int> m_Recipes;
private List<int> m_RareRecipes;
public int MinCraftEffect { get { return m_MinCraftEffect; } }
public int MaxCraftEffect { get { return m_MaxCraftEffect; } }
public double Delay { get { return m_Delay; } }
public CraftItemCol CraftItems{ get { return m_CraftItems; } }
public CraftGroupCol CraftGroups{ get { return m_CraftGroups; } }
public CraftSubResCol CraftSubRes{ get { return m_CraftSubRes; } }
public CraftSubResCol CraftSubRes2{ get { return m_CraftSubRes2; } }
public abstract SkillName MainSkill{ get; }
public virtual int GumpTitleNumber{ get{ return 0; } }
public virtual string GumpTitleString{ get{ return ""; } }
public virtual CraftECA ECA{ get{ return CraftECA.ChanceMinusSixty; } }
private Dictionary<Mobile, CraftContext> m_ContextTable = new Dictionary<Mobile, CraftContext>();
public abstract double GetChanceAtMin( CraftItem item );
public virtual bool RetainsColorFrom( CraftItem item, Type type )
{
return false;
}
public CraftContext GetContext( Mobile m )
{
if ( m == null )
return null;
if ( m.Deleted )
{
m_ContextTable.Remove( m );
return null;
}
CraftContext c = null;
m_ContextTable.TryGetValue( m, out c );
if ( c == null )
m_ContextTable[m] = c = new CraftContext();
return c;
}
public void OnMade( Mobile m, CraftItem item )
{
CraftContext c = GetContext( m );
if ( c != null )
c.OnMade( item );
}
public bool Resmelt
{
get { return m_Resmelt; }
set { m_Resmelt = value; }
}
public bool Repair
{
get{ return m_Repair; }
set{ m_Repair = value; }
}
public bool MarkOption
{
get{ return m_MarkOption; }
set{ m_MarkOption = value; }
}
public bool CanEnhance
{
get{ return m_CanEnhance; }
set{ m_CanEnhance = value; }
}
public CraftSystem( int minCraftEffect, int maxCraftEffect, double delay )
{
m_MinCraftEffect = minCraftEffect;
m_MaxCraftEffect = maxCraftEffect;
m_Delay = delay;
m_CraftItems = new CraftItemCol();
m_CraftGroups = new CraftGroupCol();
m_CraftSubRes = new CraftSubResCol();
m_CraftSubRes2 = new CraftSubResCol();
m_Recipes = new List<int>();
m_RareRecipes = new List<int>();
InitCraftList();
}
public virtual bool ConsumeOnFailure( Mobile from, Type resourceType, CraftItem craftItem )
{
return true;
}
public void CreateItem( Mobile from, Type type, Type typeRes, BaseTool tool, CraftItem realCraftItem )
{
// Verify if the type is in the list of the craftable item
CraftItem craftItem = m_CraftItems.SearchFor( type );
if ( craftItem != null )
{
// The item is in the list, try to create it
// Test code: items like sextant parts can be crafted either directly from ingots, or from different parts
realCraftItem.Craft( from, this, typeRes, tool );
//craftItem.Craft( from, this, typeRes, tool );
}
}
public int RandomRecipe()
{
if (m_Recipes.Count == 0)
return -1;
return m_Recipes[Utility.Random(m_Recipes.Count)];
}
public int RandomRareRecipe()
{
if (m_RareRecipes.Count == 0)
return -1;
return m_RareRecipes[Utility.Random(m_RareRecipes.Count)];
}
public int AddCraft( Type typeItem, TextDefinition group, TextDefinition name, double minSkill, double maxSkill, Type typeRes, TextDefinition nameRes, int amount )
{
return AddCraft( typeItem, group, name, MainSkill, minSkill, maxSkill, typeRes, nameRes, amount, "" );
}
public int AddCraft( Type typeItem, TextDefinition group, TextDefinition name, double minSkill, double maxSkill, Type typeRes, TextDefinition nameRes, int amount, TextDefinition message )
{
return AddCraft( typeItem, group, name, MainSkill, minSkill, maxSkill, typeRes, nameRes, amount, message );
}
public int AddCraft( Type typeItem, TextDefinition group, TextDefinition name, SkillName skillToMake, double minSkill, double maxSkill, Type typeRes, TextDefinition nameRes, int amount )
{
return AddCraft( typeItem, group, name, skillToMake, minSkill, maxSkill, typeRes, nameRes, amount, "" );
}
public int AddCraft( Type typeItem, TextDefinition group, TextDefinition name, SkillName skillToMake, double minSkill, double maxSkill, Type typeRes, TextDefinition nameRes, int amount, TextDefinition message )
{
CraftItem craftItem = new CraftItem( typeItem, group, name );
craftItem.AddRes( typeRes, nameRes, amount, message );
craftItem.AddSkill( skillToMake, minSkill, maxSkill );
DoGroup( group, craftItem );
return m_CraftItems.Add( craftItem );
}
private void DoGroup( TextDefinition groupName, CraftItem craftItem )
{
int index = m_CraftGroups.SearchFor( groupName );
if ( index == -1)
{
CraftGroup craftGroup = new CraftGroup( groupName );
craftGroup.AddCraftItem( craftItem );
m_CraftGroups.Add( craftGroup );
}
else
{
m_CraftGroups.GetAt( index ).AddCraftItem( craftItem );
}
}
public void SetItemHue(int index, int hue)
{
CraftItem craftItem = m_CraftItems.GetAt(index);
craftItem.ItemHue = hue;
}
public void SetManaReq( int index, int mana )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.Mana = mana;
}
public void SetStamReq( int index, int stam )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.Stam = stam;
}
public void SetHitsReq( int index, int hits )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.Hits = hits;
}
public void SetUseAllRes( int index, bool useAll )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.UseAllRes = useAll;
}
public void SetNeedHeat( int index, bool needHeat )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.NeedHeat = needHeat;
}
public void SetNeedOven( int index, bool needOven )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.NeedOven = needOven;
}
public void SetBeverageType(int index, BeverageType requiredBeverage)
{
CraftItem craftItem = m_CraftItems.GetAt(index);
craftItem.RequiredBeverage = requiredBeverage;
}
public void SetNeedMill( int index, bool needMill )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.NeedMill = needMill;
}
public void SetNeededExpansion( int index, Expansion expansion )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.RequiredExpansion = expansion;
}
public void AddRes( int index, Type type, TextDefinition name, int amount )
{
AddRes( index, type, name, amount, "" );
}
public void AddRes( int index, Type type, TextDefinition name, int amount, TextDefinition message )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.AddRes( type, name, amount, message );
}
public void AddSkill( int index, SkillName skillToMake, double minSkill, double maxSkill )
{
CraftItem craftItem = m_CraftItems.GetAt(index);
craftItem.AddSkill(skillToMake, minSkill, maxSkill);
}
public void SetUseSubRes2( int index, bool val )
{
CraftItem craftItem = m_CraftItems.GetAt(index);
craftItem.UseSubRes2 = val;
}
private void AddRecipeBase(int index, int id)
{
CraftItem craftItem = m_CraftItems.GetAt(index);
craftItem.AddRecipe(id, this);
}
public void AddRecipe(int index, int id)
{
AddRecipeBase(index, id);
m_Recipes.Add(id);
}
public void AddRareRecipe(int index, int id)
{
AddRecipeBase(index, id);
m_RareRecipes.Add(id);
}
public void AddQuestRecipe(int index, int id)
{
AddRecipeBase(index, id);
}
public void ForceNonExceptional( int index )
{
CraftItem craftItem = m_CraftItems.GetAt( index );
craftItem.ForceNonExceptional = true;
}
//Plume : Ajout du Low
public void ForceNonLow(int index)
{
CraftItem craftItem = m_CraftItems.GetAt(index);
craftItem.ForceNonLow = true;
}
public void MaxChance(int index, double max)
{
CraftItem craftItem = m_CraftItems.GetAt(index);
craftItem.TopChance = true;
craftItem.MaxChance = max;
}
public void SetSubRes( Type type, string name )
{
m_CraftSubRes.ResType = type;
m_CraftSubRes.NameString = name;
m_CraftSubRes.Init = true;
}
public void SetSubRes( Type type, int name )
{
m_CraftSubRes.ResType = type;
m_CraftSubRes.NameNumber = name;
m_CraftSubRes.Init = true;
}
public void AddSubRes( Type type, int name, double reqSkill, object message )
{
CraftSubRes craftSubRes = new CraftSubRes( type, name, reqSkill, message );
m_CraftSubRes.Add( craftSubRes );
}
public void AddSubRes( Type type, int name, double reqSkill, int genericName, object message )
{
CraftSubRes craftSubRes = new CraftSubRes( type, name, reqSkill, genericName, message );
m_CraftSubRes.Add( craftSubRes );
}
public void AddSubRes( Type type, string name, double reqSkill, object message )
{
CraftSubRes craftSubRes = new CraftSubRes( type, name, reqSkill, message );
m_CraftSubRes.Add( craftSubRes );
}
public void SetSubRes2( Type type, string name )
{
m_CraftSubRes2.ResType = type;
m_CraftSubRes2.NameString = name;
m_CraftSubRes2.Init = true;
}
public void SetSubRes2( Type type, int name )
{
m_CraftSubRes2.ResType = type;
m_CraftSubRes2.NameNumber = name;
m_CraftSubRes2.Init = true;
}
public void AddSubRes2( Type type, int name, double reqSkill, object message )
{
CraftSubRes craftSubRes = new CraftSubRes( type, name, reqSkill, message );
m_CraftSubRes2.Add( craftSubRes );
}
public void AddSubRes2( Type type, int name, double reqSkill, int genericName, object message )
{
CraftSubRes craftSubRes = new CraftSubRes( type, name, reqSkill, genericName, message );
m_CraftSubRes2.Add( craftSubRes );
}
public void AddSubRes2( Type type, string name, double reqSkill, object message )
{
CraftSubRes craftSubRes = new CraftSubRes( type, name, reqSkill, message );
m_CraftSubRes2.Add( craftSubRes );
}
public abstract void InitCraftList();
public abstract void PlayCraftEffect( Mobile from );
public abstract int PlayEndingEffect( Mobile from, bool failed, bool lostMaterial, bool toolBroken, int quality, bool makersMark, CraftItem item );
public abstract int CanCraft( Mobile from, BaseTool tool, Type itemType );
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Threading;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
//
// Data table for encoding classes. Used by System.Text.Encoding.
// This class contains two hashtables to allow System.Text.Encoding
// to retrieve the data item either by codepage value or by webName.
//
// Only statics, does not need to be marked with the serializable attribute
internal static class EncodingTable
{
//This number is the size of the table in native. The value is retrieved by
//calling the native GetNumEncodingItems().
private static int lastEncodingItem = GetNumEncodingItems() - 1;
//This number is the size of the code page table. Its generated when we walk the table the first time.
private static volatile int lastCodePageItem;
//
// This points to a native data table which maps an encoding name to the correct code page.
//
unsafe internal static InternalEncodingDataItem* encodingDataPtr = GetEncodingData();
//
// This points to a native data table which stores the properties for the code page, and
// the table is indexed by code page.
//
unsafe internal static InternalCodePageDataItem* codePageDataPtr = GetCodePageData();
//
// This caches the mapping of an encoding name to a code page.
//
private static Hashtable hashByName = Hashtable.Synchronized(new Hashtable(StringComparer.OrdinalIgnoreCase));
//
// THe caches the data item which is indexed by the code page value.
//
private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable());
// Find the data item by binary searching the table that we have in native.
// nativeCompareOrdinalWC is an internal-only function.
unsafe private static int internalGetCodePageFromName(String name)
{
int left = 0;
int right = lastEncodingItem;
int index;
int result;
//Binary search the array until we have only a couple of elements left and then
//just walk those elements.
while ((right - left) > 3)
{
index = ((right - left) / 2) + left;
result = String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[index].webName);
if (result == 0)
{
//We found the item, return the associated codepage.
return (encodingDataPtr[index].codePage);
}
else if (result < 0)
{
//The name that we're looking for is less than our current index.
right = index;
}
else
{
//The name that we're looking for is greater than our current index
left = index;
}
}
//Walk the remaining elements (it'll be 3 or fewer).
for (; left <= right; left++)
{
if (String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[left].webName) == 0)
{
return (encodingDataPtr[left].codePage);
}
}
// The encoding name is not valid.
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
SR.Argument_EncodingNotSupported, name), nameof(name));
}
// Return a list of all EncodingInfo objects describing all of our encodings
internal static unsafe EncodingInfo[] GetEncodings()
{
if (lastCodePageItem == 0)
{
int count;
for (count = 0; codePageDataPtr[count].codePage != 0; count++)
{
// Count them
}
lastCodePageItem = count;
}
EncodingInfo[] arrayEncodingInfo = new EncodingInfo[lastCodePageItem];
int i;
for (i = 0; i < lastCodePageItem; i++)
{
arrayEncodingInfo[i] = new EncodingInfo(codePageDataPtr[i].codePage, CodePageDataItem.CreateString(codePageDataPtr[i].Names, 0),
SR.GetResourceString("Globalization_cp_" + codePageDataPtr[i].codePage));
}
return arrayEncodingInfo;
}
/*=================================GetCodePageFromName==========================
**Action: Given a encoding name, return the correct code page number for this encoding.
**Returns: The code page for the encoding.
**Arguments:
** name the name of the encoding
**Exceptions:
** ArgumentNullException if name is null.
** internalGetCodePageFromName will throw ArgumentException if name is not a valid encoding name.
============================================================================*/
internal static int GetCodePageFromName(String name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
Object codePageObj;
//
// The name is case-insensitive, but ToLower isn't free. Check for
// the code page in the given capitalization first.
//
codePageObj = hashByName[name];
if (codePageObj != null)
{
return ((int)codePageObj);
}
//Okay, we didn't find it in the hash table, try looking it up in the
//unmanaged data.
int codePage = internalGetCodePageFromName(name);
hashByName[name] = codePage;
return codePage;
}
unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage)
{
CodePageDataItem dataItem;
// We synchronize around dictionary gets/sets. There's still a possibility that two threads
// will create a CodePageDataItem and the second will clobber the first in the dictionary.
// However, that's acceptable because the contents are correct and we make no guarantees
// other than that.
//Look up the item in the hashtable.
dataItem = (CodePageDataItem)hashByCodePage[codepage];
//If we found it, return it.
if (dataItem != null)
{
return dataItem;
}
//If we didn't find it, try looking it up now.
//If we find it, add it to the hashtable.
//This is a linear search, but we probably won't be doing it very often.
//
int i = 0;
int data;
while ((data = codePageDataPtr[i].codePage) != 0)
{
if (data == codepage)
{
dataItem = new CodePageDataItem(i);
hashByCodePage[codepage] = dataItem;
return (dataItem);
}
i++;
}
//Nope, we didn't find it.
return null;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalEncodingDataItem* GetEncodingData();
//
// Return the number of encoding data items.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetNumEncodingItems();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalCodePageDataItem* GetCodePageData();
}
/*=================================InternalEncodingDataItem==========================
**Action: This is used to map a encoding name to a correct code page number. By doing this,
** we can get the properties of this encoding via the InternalCodePageDataItem.
**
** We use this structure to access native data exposed by the native side.
============================================================================*/
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
internal unsafe struct InternalEncodingDataItem
{
internal sbyte* webName;
internal UInt16 codePage;
}
/*=================================InternalCodePageDataItem==========================
**Action: This is used to access the properties related to a code page.
** We use this structure to access native data exposed by the native side.
============================================================================*/
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
internal unsafe struct InternalCodePageDataItem
{
internal UInt16 codePage;
internal UInt16 uiFamilyCodePage;
internal uint flags;
internal sbyte* Names;
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using IomoteDMWebAPI.Areas.HelpPage.ModelDescriptions;
using IomoteDMWebAPI.Areas.HelpPage.Models;
namespace IomoteDMWebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Copyright (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 Microsoft.Azure.Management.Sql
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
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>
/// DatabaseOperations operations.
/// </summary>
internal partial class DatabaseOperations : IServiceOperations<SqlManagementClient>, IDatabaseOperations
{
/// <summary>
/// Initializes a new instance of the DatabaseOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DatabaseOperations(SqlManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the SqlManagementClient
/// </summary>
public SqlManagementClient Client { get; private set; }
/// <summary>
/// Cancels the asynchronous operation on the database.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database.
/// </param>
/// <param name='operationId'>
/// The operation identifier.
/// </param>
/// <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>
/// <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> CancelWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, System.Guid operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("operationId", operationId);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Cancel", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/operations/{operationId}/cancel").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{operationId}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(operationId, Client.SerializationSettings).Trim('"')));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_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));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
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>
/// Gets a list of operations performed on the database.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group that contains the resource. You can obtain
/// this value from the Azure Resource Manager API or the portal.
/// </param>
/// <param name='serverName'>
/// The name of the server.
/// </param>
/// <param name='databaseName'>
/// The name of the database.
/// </param>
/// <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>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </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<IPage<DatabaseOperation>>> ListByDatabaseWithHttpMessagesAsync(string resourceGroupName, string serverName, string databaseName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (serverName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "serverName");
}
if (databaseName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "databaseName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01-preview";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serverName", serverName);
tracingParameters.Add("databaseName", databaseName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByDatabase", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/operations").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName));
_url = _url.Replace("{databaseName}", System.Uri.EscapeDataString(databaseName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new 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));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
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<IPage<DatabaseOperation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<DatabaseOperation>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of operations performed on the database.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <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>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </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<IPage<DatabaseOperation>>> ListByDatabaseNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListByDatabaseNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new 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));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
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<IPage<DatabaseOperation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<DatabaseOperation>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="SqlDependencyUtils.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="true">[....]</owner>
// <owner current="false" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Security.Principal;
using System.Security.AccessControl;
using System.Text;
using System.Threading;
// This is a singleton instance per AppDomain that acts as the notification dispatcher for
// that AppDomain. It receives calls from the SqlDependencyProcessDispatcher with an ID or a server name
// to invalidate matching dependencies in the given AppDomain.
internal class SqlDependencyPerAppDomainDispatcher : MarshalByRefObject { // MBR, since ref'ed by ProcessDispatcher.
// ----------------
// Instance members
// ----------------
internal static readonly SqlDependencyPerAppDomainDispatcher
SingletonInstance = new SqlDependencyPerAppDomainDispatcher(); // singleton object
// Dependency ID -> Dependency hashtable. 1 -> 1 mapping.
// 1) Used for ASP.Net to map from ID to dependency.
// 2) Used to enumerate dependencies to invalidate based on server.
private Dictionary<string, SqlDependency> _dependencyIdToDependencyHash;
// holds dependencies list per notification and the command hash from which this notification was generated
// command hash is needed to remove its entry from _commandHashToNotificationId when the notification is removed
sealed class DependencyList : List<SqlDependency> {
public readonly string CommandHash;
internal DependencyList(string commandHash) {
this.CommandHash = commandHash;
}
}
// notificationId -> Dependencies hashtable: 1 -> N mapping. notificationId == appDomainKey + commandHash.
// More than one dependency can be using the same command hash values resulting in a hash to the same value.
// We use this to cache mapping between command to dependencies such that we may reduce the notification
// resource effect on SQL Server. The Guid identifier is sent to the server during notification enlistment,
// and returned during the notification event. Dependencies look up existing Guids, if one exists, to ensure
// they are re-using notification ids.
private Dictionary<string, DependencyList> _notificationIdToDependenciesHash;
// CommandHash value -> notificationId associated with it: 1->1 mapping. This map is used to quickly find if we need to create
// new notification or hookup into existing one.
// CommandHash is built from connection string, command text and parameters
private Dictionary<string, string> _commandHashToNotificationId;
// TIMEOUT LOGIC DESCRIPTION
//
// Every time we add a dependency we compute the next, earlier timeout.
//
// We setup a timer to get a callback every 15 seconds. In the call back:
// - If there are no active dependencies, we just return.
// - If there are dependencies but none of them timed-out (compared to the "next timeout"),
// we just return.
// - Otherwise we Invalidate() those that timed-out.
//
// So the client-generated timeouts have a granularity of 15 seconds. This allows
// for a simple and low-resource-consumption implementation.
//
// LOCKS: don't update _nextTimeout outside of the _dependencyHash.SyncRoot lock.
private bool _SqlDependencyTimeOutTimerStarted = false;
// Next timeout for any of the dependencies in the dependency table.
private DateTime _nextTimeout;
// Timer to periodically check the dependencies in the table and see if anyone needs
// a timeout. We'll enable this only on demand.
private Timer _timeoutTimer;
// -----------
// BID members
// -----------
private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
private static int _objectTypeCount; // Bid counter
internal int ObjectID {
get {
return _objectID;
}
}
private SqlDependencyPerAppDomainDispatcher() {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher|DEP> %d#", ObjectID);
try {
_dependencyIdToDependencyHash = new Dictionary<string, SqlDependency>();
_notificationIdToDependenciesHash = new Dictionary<string, DependencyList>();
_commandHashToNotificationId = new Dictionary<string, string>();
_timeoutTimer = new Timer(new TimerCallback(TimeoutTimerCallback), null, Timeout.Infinite, Timeout.Infinite);
// If rude abort - we'll leak. This is acceptable for now.
AppDomain.CurrentDomain.DomainUnload += new EventHandler(this.UnloadEventHandler);
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// SQL Hotfix 236
// When remoted across appdomains, MarshalByRefObject links by default time out if there is no activity
// within a few minutes. Add this override to prevent marshaled links from timing out.
public override object InitializeLifetimeService() {
return null;
}
// ------
// Events
// ------
private void UnloadEventHandler(object sender, EventArgs e) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.UnloadEventHandler|DEP> %d#", ObjectID);
try {
// Make non-blocking call to ProcessDispatcher to ThreadPool.QueueUserWorkItem to complete
// stopping of all start calls in this AppDomain. For containers shared among various AppDomains,
// this will just be a ref-count subtract. For non-shared containers, we will close the container
// and clean-up.
SqlDependencyProcessDispatcher dispatcher = SqlDependency.ProcessDispatcher;
if (null != dispatcher) {
dispatcher.QueueAppDomainUnloading(SqlDependency.AppDomainKey);
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// ----------------------------------------------------
// Methods for dependency hash manipulation and firing.
// ----------------------------------------------------
// This method is called upon SqlDependency constructor.
internal void AddDependencyEntry(SqlDependency dep) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.AddDependencyEntry|DEP> %d#, SqlDependency: %d#", ObjectID, dep.ObjectID);
try {
lock (this) {
_dependencyIdToDependencyHash.Add(dep.Id, dep);
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// This method is called upon Execute of a command associated with a SqlDependency object.
internal string AddCommandEntry(string commandHash, SqlDependency dep) {
IntPtr hscp;
string notificationId = string.Empty;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.AddCommandEntry|DEP> %d#, commandHash: '%ls', SqlDependency: %d#", ObjectID, commandHash, dep.ObjectID);
try {
lock (this) {
if (!_dependencyIdToDependencyHash.ContainsKey(dep.Id)) { // Determine if depId->dep hashtable contains dependency. If not, it's been invalidated.
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.AddCommandEntry|DEP> Dependency not present in depId->dep hash, must have been invalidated.\n");
}
else {
// check if we already have notification associated with given command hash
if (_commandHashToNotificationId.TryGetValue(commandHash, out notificationId)) {
// we have one or more SqlDependency instances with same command hash
DependencyList dependencyList = null;
if (!_notificationIdToDependenciesHash.TryGetValue(notificationId, out dependencyList))
{
// this should not happen since _commandHashToNotificationId and _notificationIdToDependenciesHash are always
// updated together
Debug.Assert(false, "_commandHashToNotificationId has entries that were removed from _notificationIdToDependenciesHash. Remember to keep them in [....]");
throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyCommandHashIsNotAssociatedWithNotification);
}
// join the new dependency to the list
if (!dependencyList.Contains(dep)) {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.AddCommandEntry|DEP> Dependency not present for commandHash, adding.\n");
dependencyList.Add(dep);
}
else {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.AddCommandEntry|DEP> Dependency already present for commandHash.\n");
}
}
else {
// we did not find notification ID with the same app domain and command hash, create a new one
// use unique guid to avoid duplicate IDs
// prepend app domain ID to the key - SqlConnectionContainer::ProcessNotificationResults (SqlDependencyListener.cs)
// uses this app domain ID to route the message back to the app domain in which this SqlDependency was created
notificationId = string.Format(System.Globalization.CultureInfo.InvariantCulture,
"{0};{1}",
SqlDependency.AppDomainKey, // must be first
Guid.NewGuid().ToString("D", System.Globalization.CultureInfo.InvariantCulture)
);
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.AddCommandEntry|DEP> Creating new Dependencies list for commandHash.\n");
DependencyList dependencyList = new DependencyList(commandHash);
dependencyList.Add(dep);
// map command hash to notification we just created to reuse it for the next client
// do it inside finally block to avoid ThreadAbort exception interrupt this operation
try {}
finally {
_commandHashToNotificationId.Add(commandHash, notificationId);
_notificationIdToDependenciesHash.Add(notificationId, dependencyList);
}
}
Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in [....]!");
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
return notificationId;
}
// This method is called by the ProcessDispatcher upon a notification for this AppDomain.
internal void InvalidateCommandID(SqlNotification sqlNotification) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.InvalidateCommandID|DEP> %d#, commandHash: '%ls'", ObjectID, sqlNotification.Key);
try {
List<SqlDependency> dependencyList = null;
lock (this) {
dependencyList = LookupCommandEntryWithRemove(sqlNotification.Key);
if (null != dependencyList) {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.InvalidateCommandID|DEP> commandHash found in hashtable.\n");
foreach (SqlDependency dependency in dependencyList) {
// Ensure we remove from process static app domain hash for dependency initiated invalidates.
LookupDependencyEntryWithRemove(dependency.Id);
// Completely remove Dependency from commandToDependenciesHash.
RemoveDependencyFromCommandToDependenciesHash(dependency);
}
}
else {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.InvalidateCommandID|DEP> commandHash NOT found in hashtable.\n");
}
}
if (null != dependencyList) {
// After removal from hashtables, invalidate.
foreach (SqlDependency dependency in dependencyList) {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.InvalidateCommandID|DEP> Dependency found in commandHash dependency ArrayList - calling invalidate.\n");
try {
dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source);
}
catch (Exception e) {
// Since we are looping over dependencies, do not allow one Invalidate
// that results in a throw prevent us from invalidating all dependencies
// related to this server.
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
}
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// This method is called when a connection goes down or other unknown error occurs in the ProcessDispatcher.
internal void InvalidateServer(string server, SqlNotification sqlNotification) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.Invalidate|DEP> %d#, server: '%ls'", ObjectID, server);
try {
List<SqlDependency> dependencies = new List<SqlDependency>();
lock (this) { // Copy inside of lock, but invalidate outside of lock.
foreach (KeyValuePair<string, SqlDependency> entry in _dependencyIdToDependencyHash) {
SqlDependency dependency = entry.Value;
if (dependency.ContainsServer(server)) {
dependencies.Add(dependency);
}
}
foreach (SqlDependency dependency in dependencies) { // Iterate over resulting list removing from our hashes.
// Ensure we remove from process static app domain hash for dependency initiated invalidates.
LookupDependencyEntryWithRemove(dependency.Id);
// Completely remove Dependency from commandToDependenciesHash.
RemoveDependencyFromCommandToDependenciesHash(dependency);
}
}
foreach (SqlDependency dependency in dependencies) { // Iterate and invalidate.
try {
dependency.Invalidate(sqlNotification.Type, sqlNotification.Info, sqlNotification.Source);
}
catch (Exception e) {
// Since we are looping over dependencies, do not allow one Invalidate
// that results in a throw prevent us from invalidating all dependencies
// related to this server.
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// This method is called by SqlCommand to enable ASP.Net scenarios - map from ID to Dependency.
internal SqlDependency LookupDependencyEntry(string id) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.LookupDependencyEntry|DEP> %d#, Key: '%ls'", ObjectID, id);
try {
if (null == id) {
throw ADP.ArgumentNull("id");
}
if (ADP.IsEmpty(id)) {
throw SQL.SqlDependencyIdMismatch();
}
SqlDependency entry = null;
lock (this) {
if (_dependencyIdToDependencyHash.ContainsKey(id)) {
entry = _dependencyIdToDependencyHash[id];
}
else {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.LookupDependencyEntry|DEP|ERR> ERROR - dependency ID mismatch - not throwing.\n");
}
}
return entry;
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// Remove the dependency from the hashtable with the passed id.
private void LookupDependencyEntryWithRemove(string id) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.LookupDependencyEntryWithRemove|DEP> %d#, id: '%ls'", ObjectID, id);
try {
lock (this) {
if (_dependencyIdToDependencyHash.ContainsKey(id)) {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.LookupDependencyEntryWithRemove|DEP> Entry found in hashtable - removing.\n");
_dependencyIdToDependencyHash.Remove(id);
// if there are no more dependencies then we can dispose the timer.
if (0 == _dependencyIdToDependencyHash.Count) {
_timeoutTimer.Change(Timeout.Infinite, Timeout.Infinite);
_SqlDependencyTimeOutTimerStarted = false;
}
}
else {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.LookupDependencyEntryWithRemove|DEP> Entry NOT found in hashtable.\n");
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// Find and return arraylist, and remove passed hash value.
private List<SqlDependency> LookupCommandEntryWithRemove(string notificationId) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.LookupCommandEntryWithRemove|DEP> %d#, commandHash: '%ls'", ObjectID, notificationId);
try {
DependencyList entry = null;
lock (this) {
if (_notificationIdToDependenciesHash.TryGetValue(notificationId, out entry)) {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.LookupDependencyEntriesWithRemove|DEP> Entries found in hashtable - removing.\n");
// update the tables - do it inside finally block to avoid ThreadAbort exception interrupt this operation
try { }
finally {
_notificationIdToDependenciesHash.Remove(notificationId);
// VSTS 216991: cleanup the map between the command hash and associated notification ID
_commandHashToNotificationId.Remove(entry.CommandHash);
}
}
else {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.LookupDependencyEntriesWithRemove|DEP> Entries NOT found in hashtable.\n");
}
Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in [....]!");
}
return entry; // DependencyList inherits from List<SqlDependency>
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// Remove from commandToDependenciesHash all references to the passed dependency.
private void RemoveDependencyFromCommandToDependenciesHash(SqlDependency dependency) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.RemoveDependencyFromCommandToDependenciesHash|DEP> %d#, SqlDependency: %d#", ObjectID, dependency.ObjectID);
try {
lock (this) {
List<string> notificationIdsToRemove = new List<string>();
List<string> commandHashesToRemove = new List<string>();
foreach (KeyValuePair<string, DependencyList> entry in _notificationIdToDependenciesHash) {
DependencyList dependencies = entry.Value;
if (dependencies.Remove(dependency)) {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.RemoveDependencyFromCommandToDependenciesHash|DEP> Removed SqlDependency: %d#, with ID: '%ls'.\n", dependency.ObjectID, dependency.Id);
if (dependencies.Count == 0) {
// this dependency was the last associated with this notification ID, remove the entry
// note: cannot do it inside foreach over dictionary
notificationIdsToRemove.Add(entry.Key);
commandHashesToRemove.Add(entry.Value.CommandHash);
}
}
// same SqlDependency can be associated with more than one command, so we have to continue till the end...
}
Debug.Assert(commandHashesToRemove.Count == notificationIdsToRemove.Count, "maps should be kept in [....]");
for (int i = 0; i < notificationIdsToRemove.Count; i++ ) {
// cleanup the entry outside of foreach
// do it inside finally block to avoid ThreadAbort exception interrupt this operation
try { }
finally {
_notificationIdToDependenciesHash.Remove(notificationIdsToRemove[i]);
// VSTS 216991: cleanup the map between the command hash and associated notification ID
_commandHashToNotificationId.Remove(commandHashesToRemove[i]);
}
}
Debug.Assert(_notificationIdToDependenciesHash.Count == _commandHashToNotificationId.Count, "always keep these maps in [....]!");
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
// -----------------------------------------
// Methods for Timer maintenance and firing.
// -----------------------------------------
internal void StartTimer(SqlDependency dep) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.StartTimer|DEP> %d#, SqlDependency: %d#", ObjectID, dep.ObjectID);
try {
// If this dependency expires sooner than the current next timeout, change
// the timeout and enable timer callback as needed. Note that we change _nextTimeout
// only inside the hashtable syncroot.
lock (this) {
// Enable the timer if needed (disable when empty, enable on the first addition).
if (!_SqlDependencyTimeOutTimerStarted) {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.StartTimer|DEP> Timer not yet started, starting.\n");
_timeoutTimer.Change(15000 /* 15 secs */, 15000 /* 15 secs */);
// Save this as the earlier timeout to come.
_nextTimeout = dep.ExpirationTime;
_SqlDependencyTimeOutTimerStarted = true;
}
else if(_nextTimeout > dep.ExpirationTime) {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.StartTimer|DEP> Timer already started, resetting time.\n");
// Save this as the earlier timeout to come.
_nextTimeout = dep.ExpirationTime;
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
private static void TimeoutTimerCallback(object state) {
IntPtr hscp;
Bid.NotificationsScopeEnter(out hscp, "<sc.SqlDependencyPerAppDomainDispatcher.TimeoutTimerCallback|DEP> AppDomainKey: '%ls'", SqlDependency.AppDomainKey);
try {
SqlDependency[] dependencies;
// Only take the lock for checking whether there is work to do
// if we do have work, we'll copy the hashtable and scan it after releasing
// the lock.
lock (SingletonInstance) {
if (0 == SingletonInstance._dependencyIdToDependencyHash.Count) {
// Nothing to check.
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.TimeoutTimerCallback|DEP> No dependencies, exiting.\n");
return;
}
if (SingletonInstance._nextTimeout > DateTime.UtcNow) {
Bid.NotificationsTrace("<sc.SqlDependencyPerAppDomainDispatcher.TimeoutTimerCallback|DEP> No timeouts expired, exiting.\n");
// No dependency timed-out yet.
return;
}
// If at least one dependency timed-out do a scan of the table.
// NOTE: we could keep a shadow table sorted by expiration time, but
// given the number of typical simultaneously alive dependencies it's
// probably not worth the optimization.
dependencies = new SqlDependency[SingletonInstance._dependencyIdToDependencyHash.Count];
SingletonInstance._dependencyIdToDependencyHash.Values.CopyTo(dependencies, 0);
}
// Scan the active dependencies if needed.
DateTime now = DateTime.UtcNow;
DateTime newNextTimeout = DateTime.MaxValue;
for (int i=0; i < dependencies.Length; i++) {
// If expired fire the change notification.
if(dependencies[i].ExpirationTime <= now) {
try {
// This invokes user-code which may throw exceptions.
// NOTE: this is intentionally outside of the lock, we don't want
// to invoke user-code while holding an internal lock.
dependencies[i].Invalidate(SqlNotificationType.Change, SqlNotificationInfo.Error, SqlNotificationSource.Timeout);
}
catch(Exception e) {
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
// This is an exception in user code, and we're in a thread-pool thread
// without user's code up in the stack, no much we can do other than
// eating the exception.
ADP.TraceExceptionWithoutRethrow(e);
}
}
else {
if (dependencies[i].ExpirationTime < newNextTimeout) {
newNextTimeout = dependencies[i].ExpirationTime; // Track the next earlier timeout.
}
dependencies[i] = null; // Null means "don't remove it from the hashtable" in the loop below.
}
}
// Remove timed-out dependencies from the hashtable.
lock (SingletonInstance) {
for (int i=0; i < dependencies.Length; i++) {
if (null != dependencies[i]) {
SingletonInstance._dependencyIdToDependencyHash.Remove(dependencies[i].Id);
}
}
if (newNextTimeout < SingletonInstance._nextTimeout) {
SingletonInstance._nextTimeout = newNextTimeout; // We're inside the lock so ok to update.
}
}
}
finally {
Bid.ScopeLeave(ref hscp);
}
}
}
// Simple class used to encapsulate all data in a notification.
internal class SqlNotification : MarshalByRefObject {
// This class could be Serializable rather than MBR...
private readonly SqlNotificationInfo _info;
private readonly SqlNotificationSource _source;
private readonly SqlNotificationType _type;
private readonly string _key;
internal SqlNotification(SqlNotificationInfo info, SqlNotificationSource source, SqlNotificationType type, string key) {
_info = info;
_source = source;
_type = type;
_key = key;
}
internal SqlNotificationInfo Info {
get {
return _info;
}
}
internal string Key {
get {
return _key;
}
}
internal SqlNotificationSource Source {
get {
return _source;
}
}
internal SqlNotificationType Type {
get {
return _type;
}
}
}
}
| |
namespace Firebase.Sample.Storage {
using Firebase;
using Firebase.Extensions;
using Firebase.Storage;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
// An automated version of the UIHandler that runs tests on Firebase Storage.
public class UIHandlerAutomated : UIHandler {
// Delegate of method used to perform an operation.
delegate IEnumerator OperationDelegate();
// Delegate which validates a completed task.
delegate Task TaskValidationDelegate(Task task);
private Firebase.Sample.AutomatedTestRunner testRunner;
#if !(UNITY_IOS || UNITY_ANDROID) || UNITY_EDITOR
// Storage bucket (without the scheme) extracted from MyStorageBucket.
private string storageBucket;
// Manually create the default app on desktop so that it's possible to specify the storage bucket.
private FirebaseApp defaultApp;
#endif // !(UNITY_IOS || UNITY_ANDROID) || UNITY_EDITOR
// Metadata to upload to the test file.
private string METADATA_STRING_NON_CUSTOM_ONLY =
"CacheControl=no-cache\n" +
"ContentLanguage=en\n";
// Expected metadata if expectedMetadataTestMode is set to MetadataTestMode.Both and
// MetadataTestMode.NonCustomOnly
private string EXPECTED_METADATA_CACHE_CONTROL = "no-cache";
private string EXPECTED_METADATA_CONTENT_LANGUAGE = "en";
private string METADATA_STRING_CUSTOM_ONLY =
"this=is\n" +
"just=a\n" +
"set=of\n" +
"test=metadata\n";
// Expected custom metadata, if expectedMetadataTestMode is set to MetadataTestMode.Both and
// MetadataTestMode.CustomOnly
private Dictionary<string, string> EXPECTED_CUSTOM_METADATA = new Dictionary<string, string> {
{"this", "is"},
{"just", "a"},
{"set", "of"},
{"test", "metadata"}
};
private enum MetadataTestMode : byte {
Both, // Change both custom and non-custom metadata
CustomOnly, // Change only custom metadata
NonCustomOnly, // Change only non-custom metadata
None, // Change no metadata
};
// X is replaced in this string with a different character per line.
private string FILE_LINE = "X: a relatively large file with lots of evil exs\n";
// File to upload (created from FILE_LINE).
private string LARGE_FILE_CONTENTS;
// Path to the file.
private string LARGE_FILE_PATH = "this_is_a/test_path/to_a/large_text_file.txt";
// Small file contents.
private string SMALL_FILE_CONTENTS = "this is a small text file";
// Path to a small file.
private string SMALL_FILE_PATH = "this_is_a/test_path/to_a/small_text_file.txt";
// Path to a metadata testing file.
private string METADATA_TEST_FILE_PATH = "this_is_a/test_path/to_a/metadata_test_file.txt";
// Path to non-existant file.
private string NON_EXISTANT_FILE_PATH = "this_is_a/path_to_a/non_existant_file.txt";
// Time to wait before canceling an operation.
private float CANCELATION_DELAY_SECONDS = 0.2f;
// Content type for text file uploads
const string ContentTypePlainText = "text/plain";
// Whether the test is validating behavior of the pure C# (old) implementation or the new C++
// backed implementation.
// The pure C# implementation has some poorly documented and in some cases broken behavior.
// When this is true the test will validate the behavior of the pure C# implementation,
// even though it's wrong.
private bool oldImplementationCompatibility;
// Expected total file size in bytes during upload / download.
private int expectedFileSize;
// Expected storage reference during upload / download.
private StorageReference expectedStorageReference;
// Expected metadata test mode (none, non-customized only, customized only or both)
private MetadataTestMode expectedMetadataTestMode;
// Expected metadata value for CacheControl
private string expectedMetadataCacheControlValue;
// Expected metadata value for ContentLanguage
private string expectedMetadataCacheContentLanguageValue;
// Expected custom metadata
private Dictionary<string, string> expectedCustomMetadata;
// Number of upload / download progress updates.
private int progressUpdateCount;
// Class for forcing code to run on the main thread.
private MainThreadDispatcher mainThreadDispatcher;
// When set to true, each download or upload callback will throw an exception.
private bool throwExceptionsInProgressCallbacks = false;
protected override void Start() {
// Set the list of tests to run, note this is done at Start since they are
// non-static.
Func<Task>[] tests = {
TestCreateDestroy,
TestCreateDestroyRace,
TestStorageReferenceNavigation,
TestUrl,
TestGetReference,
TestGetStorageInvalidUris,
TestGetStorageWrongBucket,
TestUploadBytesLargeFile,
TestUploadBytesSmallFile,
TestUploadBytesSmallFileWithNoMetadata,
TestUploadBytesSmallFileWithNonCustomOnlyMetadata,
TestUploadBytesSmallFileWithCustomOnlyMetadata,
TestUploadBytesSmallFileWithBothMetadata,
TestUploadBytesSmallFileThenUpdateMetadata,
TestUploadStreamLargeFile,
TestUploadStreamSmallFile,
TestUploadFromFileLargeFile,
TestUploadFromFileSmallFile,
TestUploadFromNonExistantFile,
TestUploadBytesWithCancelation,
TestUploadStreamWithCancelation,
TestUploadFromFileWithCancelation,
TestUploadSmallFileGetDownloadUrl,
TestGetDownloadUrlNonExistantFile,
TestUploadSmallFileGetMetadata,
TestGetMetadataNonExistantFile,
TestUploadSmallFileAndDelete,
TestDeleteNonExistantFile,
TestDownloadNonExistantFile,
TestUploadSmallFileAndDownload,
TestUploadSmallFileAndDownloadWithProgressExceptions,
TestUploadLargeFileAndDownload,
TestUploadLargeFileAndDownloadWithCancelation,
TestUploadSmallFileAndDownloadUsingStreamCallback,
TestUploadLargeFileAndDownloadUsingStreamCallback,
TestUploadLargeFileAndDownloadUsingStreamCallbackWithCancelation,
TestUploadSmallFileAndDownloadToFile,
TestUploadLargeFileAndDownloadToFile,
TestUploadLargeFileAndDownloadToFileWithCancelation,
};
testRunner = AutomatedTestRunner.CreateTestRunner(
testsToRun: tests,
logFunc: DebugLog
);
mainThreadDispatcher = gameObject.AddComponent<MainThreadDispatcher>();
if (mainThreadDispatcher == null) {
Debug.LogError("Could not create MainThreadDispatcher component!");
return;
}
Debug.Log("NOTE: Some API calls report failures using UnityEngine.Debug.LogError which will " +
"pause execution in the editor when 'Error Pause' in the console window is " +
"enabled. `Error Pause` should be disabled to execute this test.");
var largeFileSize = 512 * 1024;
int repeatedLines = largeFileSize / FILE_LINE.Length;
int partialLineLength = largeFileSize % FILE_LINE.Length;
var builder = new StringBuilder();
for (int i = 0; i < repeatedLines; ++i) {
builder.Append(FILE_LINE.Replace('X', (i % 10).ToString()[0]));
}
builder.Append(FILE_LINE.Substring(0, partialLineLength));
LARGE_FILE_CONTENTS = builder.ToString();
oldImplementationCompatibility = Type.GetType(
"Firebase.Storage.FirebaseStorageInternal, Firebase.Storage, Version=1.0.0.0, " +
"Culture=neutral") == null;
UIEnabled = false;
base.Start();
}
// Create the default FirebaseApp on non-mobile platforms.
private void CreateDefaultApp() {
#if !(UNITY_IOS || UNITY_ANDROID) || UNITY_EDITOR
defaultApp = FirebaseApp.Create(new AppOptions { StorageBucket = storageBucket });
Debug.Log(String.Format("Default app created with storage bucket {0}",
defaultApp.Options.StorageBucket));
#endif // !(UNITY_IOS || UNITY_ANDROID) || UNITY_EDITOR
}
// Remove all reference to the default FirebaseApp.
private void DestroyDefaultApp() {
#if !(UNITY_IOS || UNITY_ANDROID) || UNITY_EDITOR
defaultApp = null;
#endif // !(UNITY_IOS || UNITY_ANDROID) || UNITY_EDITOR
}
protected override void InitializeFirebase() {
#if !(UNITY_IOS || UNITY_ANDROID) || UNITY_EDITOR
storageBucket = (new Uri(MyStorageBucket)).Host;
#endif
CreateDefaultApp();
base.InitializeFirebase();
}
// Passes along the update call to automated test runner.
protected override void Update() {
base.Update();
if (testRunner != null && isFirebaseInitialized) {
testRunner.Update();
}
}
// Throw when condition is false.
private void Assert(string message, bool condition) {
if (!condition)
throw new Exception(String.Format("Assertion failed ({0}): {1}",
testRunner.CurrentTestDescription, message));
}
// Throw when value1 != value2.
private void AssertEq<T>(string message, T value1, T value2) {
if (!(object.Equals(value1, value2))) {
throw new Exception(String.Format("Assertion failed ({0}): {1} != {2} ({3})",
testRunner.CurrentTestDescription, value1, value2,
message));
}
}
// Returns a completed task.
private Task CompletedTask(Exception exception = null) {
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
if (exception == null) {
taskCompletionSource.SetResult(true);
} else {
taskCompletionSource.SetException(exception);
}
return taskCompletionSource.Task;
}
// Make sure it's possible to create and tear down storage instances.
// There's some complexity here, because System.GC.WaitForPendingFinalizers()
// can't be called on the main thread, because it blocks. (And by blocking,
// prevents garbage collection from happening, since that ALSO occurs on the
// main thread, resulting in a deadlock.)
// CreateDefaultApp(), on the other hand, HAS to run on the main thread,
// because it internally depends on several main-thread-specific function
// calls. (get_IsEditor and get_IsPlaying)
Task TestCreateDestroy() {
return Task.Run(() => {
storage = FirebaseStorage.DefaultInstance;
try {
for (int i = 0; i < 100; ++i) {
// Dereference the default storage objects.
storage = null;
DestroyDefaultApp();
// Dereference the default storage and app objects.
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
var task = mainThreadDispatcher.RunOnMainThread(() => {
CreateDefaultApp();
storage = FirebaseStorage.DefaultInstance;
});
task.Wait();
}
} finally {
System.GC.WaitForPendingFinalizers();
// Recreate App and Storage instance just in case.
var task = mainThreadDispatcher.RunOnMainThread(() => {
CreateDefaultApp();
storage = FirebaseStorage.DefaultInstance;
});
task.Wait();
}
});
}
Task TestCreateDestroyRace() {
return Task.Run(() => {
// Dereference the default storage objects.
storage = null;
DestroyDefaultApp();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
try {
for (int i = 0; i < 1000; ++i) {
{
// Get a reference to storage and app and immediately deference both
FirebaseStorage.DefaultInstance.GetReference("RaceTest");
}
System.GC.Collect();
}
} finally {
System.GC.WaitForPendingFinalizers();
// Recreate App and Storage instance
var task = mainThreadDispatcher.RunOnMainThread(() => {
CreateDefaultApp();
storage = FirebaseStorage.DefaultInstance;
});
task.Wait();
}
});
}
// Make sure it's possible to navigate storage references.
Task TestStorageReferenceNavigation() {
DebugLog("TestStorageReferenceNavigation");
var reference = FirebaseStorage.DefaultInstance.GetReference(LARGE_FILE_PATH);
AssertEq("reference.Bucket", reference.Bucket, FirebaseApp.DefaultInstance.Options.StorageBucket);
AssertEq("reference.Name", reference.Name, "large_text_file.txt");
AssertEq("reference.Path", reference.Path, "/" + LARGE_FILE_PATH);
AssertEq("reference.Root", reference.Root, FirebaseStorage.DefaultInstance.RootReference);
AssertEq("reference.Storage", reference.Storage, FirebaseStorage.DefaultInstance);
var parentReference = reference.Parent;
AssertEq("parentReference.Bucket", parentReference.Bucket,
FirebaseApp.DefaultInstance.Options.StorageBucket);
AssertEq("parentReference.Name", parentReference.Name, "to_a");
AssertEq("parentReference.Path", parentReference.Path,
"/this_is_a/test_path/to_a");
AssertEq("parentReference.Root", parentReference.Root,
FirebaseStorage.DefaultInstance.RootReference);
AssertEq("parentReference.Storage", parentReference.Storage, FirebaseStorage.DefaultInstance);
var childReference = parentReference.Child("small_text_file.txt");
AssertEq("childReference.Bucket", childReference.Bucket,
FirebaseApp.DefaultInstance.Options.StorageBucket);
AssertEq("childReference.Name", childReference.Name, "small_text_file.txt");
AssertEq("childReference.Path", childReference.Path,
"/this_is_a/test_path/to_a/small_text_file.txt");
AssertEq("childReference.Root", childReference.Root,
FirebaseStorage.DefaultInstance.RootReference);
AssertEq("childReference.Storage", childReference.Storage, FirebaseStorage.DefaultInstance);
return CompletedTask();
}
// Validate returning url for default and non-default storage objects.
Task TestUrl() {
DebugLog("TestUrl");
// Get the storage URL on the default app.
var expectedDefaultUrl = String.Format("gs://{0}", FirebaseApp.DefaultInstance.Options.StorageBucket);
var defaultUrl = FirebaseStorage.DefaultInstance.Url();
AssertEq("defaultUrl", defaultUrl, expectedDefaultUrl);
// Get the storage URL on a custom app.
var customApp = FirebaseApp.Create(new AppOptions { StorageBucket = "somebucket" }, "emptyapp");
var customStorage = FirebaseStorage.GetInstance(customApp, "gs://somebucket");
var customStorageUrl = customStorage.Url();
AssertEq("customStorageUrl", customStorageUrl, "gs://somebucket");
return CompletedTask();
}
// Validate retrieving references to different buckets and non-default storage objects.
Task TestGetReference() {
DebugLog("TestGetReference");
// Get references using a path vs. URL on the default app.
var defaultReference = FirebaseStorage.DefaultInstance.GetReference(LARGE_FILE_PATH);
var defaultReferenceFromUrl = FirebaseStorage.DefaultInstance.GetReferenceFromUrl(
String.Format("gs://{0}/{1}", FirebaseApp.DefaultInstance.Options.StorageBucket,
LARGE_FILE_PATH));
AssertEq("defaultReference", defaultReference, defaultReferenceFromUrl);
// Get references using a path vs. URL on a custom app.
var customApp = FirebaseApp.Create(new AppOptions { StorageBucket = "somebucket" }, "emptyapp");
var customStorage = FirebaseStorage.GetInstance(customApp, "gs://somebucket");
var anotherReferenceFromUrl = customStorage.GetReferenceFromUrl(
"gs://somebucket/somefile/path.txt");
var anotherReference = FirebaseStorage.GetInstance(customApp, "gs://somebucket").GetReference(
"somefile/path.txt");
AssertEq("anotherReferenceFromUrl", anotherReferenceFromUrl, anotherReference);
return CompletedTask();
}
// Should fail when using invalid storage URIs.
Task TestGetStorageInvalidUris() {
DebugLog("TestGetStorageInvalidUris");
try {
var brokenStorage = FirebaseStorage.GetInstance(
String.Format("gs://{0}/a/b/c/d", FirebaseApp.DefaultInstance.Options.StorageBucket));
Assert("brokenStorage == null", brokenStorage == null);
} catch (ArgumentException) {
// Drop through.
}
return CompletedTask();
}
// Should fail when trying to get a storage object from an app with a mismatched bucket name.
Task TestGetStorageWrongBucket() {
DebugLog("TestGetStorageWrongBucket");
try {
var reference = FirebaseStorage.DefaultInstance.GetReferenceFromUrl(
"gs://somebucket/somefile/path.txt");
Assert("reference == null", reference == null);
} catch (ArgumentException) {
// Drop through.
}
return CompletedTask();
}
// Validate metadata contains the specifeid expected custom metadata.
private void ValidateCustomMetadata(StorageMetadata metadata,
Dictionary<string, string> expected) {
foreach (var kv in expected) {
AssertEq(String.Format("GetCustomMetadata {0}", kv.Key), metadata.GetCustomMetadata(kv.Key),
kv.Value);
}
AssertEq("CustomMetadataKeys.Count", (new List<string>(metadata.CustomMetadataKeys)).Count,
expected.Count);
foreach (var key in metadata.CustomMetadataKeys) {
Assert(String.Format("Contains key {0}", key), expected.ContainsKey(key));
}
}
// Current time in the time zone reported by the StorageMetadata object.
private DateTime MetadataTimeZoneNow() {
if (oldImplementationCompatibility) {
// The C# implementation StorageMetadata times in the current time zone rather than UTC which
// is used by other implementations.
return DateTime.Now;
} else {
return DateTime.UtcNow;
}
}
// Ensure the uploaded / downloaded file metadata matches expectations.
private void ValidateMetadata(StorageMetadata metadata, bool uploadFromFile,
string contentType) {
var expectedName = GetStorageReference().Name;
Assert("metadata not null", metadata != null);
AssertEq("metadata.ContentDisposition", metadata.ContentDisposition,
"inline; filename*=utf-8''" + expectedName);
AssertEq("metadata.ContentEncoding", metadata.ContentEncoding, "identity");
if (contentType != null) {
AssertEq("metadata.ContentType", metadata.ContentType, contentType);
}
AssertEq("metadata.Reference", metadata.Reference, GetStorageReference());
AssertEq("metadata.Bucket", metadata.Bucket, GetStorageReference().Bucket);
AssertEq("metadata.Name", metadata.Name, expectedName);
Assert("metadata.CreationTimeMillis",
Math.Abs(MetadataTimeZoneNow().Subtract(metadata.CreationTimeMillis).TotalSeconds) > 0);
Assert("metadata.UpdatedTimeMillis",
Math.Abs(MetadataTimeZoneNow().Subtract(metadata.UpdatedTimeMillis).TotalMinutes) < 5);
Assert("metadata.Generation", Int64.Parse(metadata.Generation) > 0);
Assert("metadata.MetadataGeneration", Int64.Parse(metadata.MetadataGeneration) > 0);
AssertEq("metadata.SizeBytes", metadata.SizeBytes, expectedFileSize);
// The following metadata may varies based on the MetadataTestMode
AssertEq("metadata.CacheControl", metadata.CacheControl, expectedMetadataCacheControlValue);
AssertEq("metadata.ContentLanguage", metadata.ContentLanguage,
expectedMetadataCacheContentLanguageValue);
ValidateCustomMetadata(metadata, expectedCustomMetadata);
}
// Track upload progress.
protected override void DisplayUploadState(UploadState uploadState) {
base.DisplayUploadState(uploadState);
Assert("uploadState.BytesTransferred",
uploadState.BytesTransferred <= expectedFileSize ||
uploadState.BytesTransferred <= uploadState.TotalByteCount);
if (uploadState.TotalByteCount > 0) {
// Mobile SDKs include the metadata as part of the upload size.
Assert("uploadState.TotalByteCount", uploadState.TotalByteCount >= expectedFileSize);
} else {
// When uploading a stream the C# SDK does not know the complete file size so it reports -1
// instead.
AssertEq("uploadState.TotalByteCount", uploadState.TotalByteCount, -1);
}
AssertEq("uploadState.TotalByteCount", uploadState.Reference.Path,
expectedStorageReference.Path);
// Assert(uploadState.Metadata != null); // TODO: Write validator for this.
// TODO: This is supported in the C# build, need this in the C++ version.
//AssertEq(uploadState.UploadSessionUri != null);
progressUpdateCount++;
if (throwExceptionsInProgressCallbacks) {
throw new Exception(String.Format("Upload state {0}", progressUpdateCount));
}
}
// Validate an upload completed with a report of the expected metadata.
Task ValidateUploadSuccessful(Task task, bool uploadFromFile, string contentType) {
// NOTE: This uses "previousTask" to access the task returned by the upload method.
var storageMetadataTask = previousTask as Task<StorageMetadata>;
Assert("storageMetadataTask != null", storageMetadataTask != null);
if (!(storageMetadataTask.IsFaulted || storageMetadataTask.IsCanceled)) {
ValidateMetadata(storageMetadataTask.Result, uploadFromFile, contentType);
// Make sure progress was reported.
Assert("progressCount > 0", progressUpdateCount > 0);
}
return task;
}
// Validate an upload completed with a report of the expected metadata when uploading from a
// byte array or stream.
Task ValidateUploadSuccessfulNotFile(Task task) {
return ValidateUploadSuccessful(task, false, null);
}
// Validate an upload completed with a report of the expected metadata when uploading from a
// local file.
Task ValidateUploadSuccessfulFile(Task task) {
return ValidateUploadSuccessful(task, true, ContentTypePlainText);
}
// Set the metadata when uploading a file and the expected values for validation later.
void SetMetadataForTest(MetadataTestMode mode, String contentType) {
switch (mode) {
case MetadataTestMode.Both:
fileMetadataChangeString = METADATA_STRING_NON_CUSTOM_ONLY +
METADATA_STRING_CUSTOM_ONLY;
expectedMetadataCacheControlValue = EXPECTED_METADATA_CACHE_CONTROL;
expectedMetadataCacheContentLanguageValue = EXPECTED_METADATA_CONTENT_LANGUAGE;
expectedCustomMetadata = EXPECTED_CUSTOM_METADATA;
break;
case MetadataTestMode.CustomOnly:
fileMetadataChangeString = METADATA_STRING_CUSTOM_ONLY;
expectedMetadataCacheControlValue = "";
expectedMetadataCacheContentLanguageValue = "";
expectedCustomMetadata = EXPECTED_CUSTOM_METADATA;
break;
case MetadataTestMode.NonCustomOnly:
fileMetadataChangeString = METADATA_STRING_NON_CUSTOM_ONLY;
expectedMetadataCacheControlValue = EXPECTED_METADATA_CACHE_CONTROL;
expectedMetadataCacheContentLanguageValue = EXPECTED_METADATA_CONTENT_LANGUAGE;
expectedCustomMetadata = new Dictionary<string, string>();
break;
case MetadataTestMode.None:
fileMetadataChangeString = "";
expectedMetadataCacheControlValue = "";
expectedMetadataCacheContentLanguageValue = "";
expectedCustomMetadata = new Dictionary<string, string>();
break;
}
if (contentType != null) {
fileMetadataChangeString += "ContentType="+contentType+"\n";
}
expectedMetadataTestMode = mode;
}
// Upload and ensure returned storage metadata is valid after upload.
Task UploadToPathUsingDelegate(string path, string contents, MetadataTestMode metadata_mode,
OperationDelegate uploadDelegate,
TaskValidationDelegate taskValidationDelegate) {
progressUpdateCount = 0;
storageLocation = path;
fileContents = contents;
SetMetadataForTest(metadata_mode, null);
expectedFileSize = contents.Length;
expectedStorageReference = GetStorageReference();
return ToTask(uploadDelegate()).ContinueWithOnMainThread((task) => {
return taskValidationDelegate(task);
}).Unwrap();
}
// Upload large file and ensure returned metadata is valid after upload.
Task TestUploadBytesLargeFile() {
return UploadToPathUsingDelegate(LARGE_FILE_PATH, LARGE_FILE_CONTENTS, MetadataTestMode.Both,
UploadBytes, ValidateUploadSuccessfulNotFile);
}
// Upload small file and ensure returned metadata is valid after upload.
Task TestUploadBytesSmallFile() {
return UploadToPathUsingDelegate(SMALL_FILE_PATH, SMALL_FILE_CONTENTS, MetadataTestMode.Both,
UploadBytes, ValidateUploadSuccessfulNotFile);
}
Task TestUploadBytesSmallFileWithNoMetadata() {
return UploadToPathUsingDelegate(METADATA_TEST_FILE_PATH, SMALL_FILE_CONTENTS,
MetadataTestMode.None, UploadBytes,
ValidateUploadSuccessfulNotFile);
}
Task TestUploadBytesSmallFileWithNonCustomOnlyMetadata() {
return UploadToPathUsingDelegate(METADATA_TEST_FILE_PATH, SMALL_FILE_CONTENTS,
MetadataTestMode.NonCustomOnly, UploadBytes,
ValidateUploadSuccessfulNotFile);
}
Task TestUploadBytesSmallFileWithCustomOnlyMetadata() {
return UploadToPathUsingDelegate(METADATA_TEST_FILE_PATH, SMALL_FILE_CONTENTS,
MetadataTestMode.CustomOnly, UploadBytes,
ValidateUploadSuccessfulNotFile);
}
Task TestUploadBytesSmallFileWithBothMetadata() {
return UploadToPathUsingDelegate(METADATA_TEST_FILE_PATH, SMALL_FILE_CONTENTS,
MetadataTestMode.Both, UploadBytes,
ValidateUploadSuccessfulNotFile);
}
// Upload small file and update metadata after upload.
Task TestUploadBytesSmallFileThenUpdateMetadata() {
return TestUploadBytesSmallFile().ContinueWithOnMainThread((task) => {
var metadataChange = new MetadataChange {
CacheControl = "no-transform",
ContentDisposition = "attachment; filename=\"helloworld.txt\"",
ContentEncoding = "gzip",
ContentLanguage = "es",
ContentType = "text/html; charset=utf-8",
CustomMetadata = new Dictionary<string, string> {
{"its_different", "metadata"},
{"this", "isnt"},
}
};
return GetStorageReference().UpdateMetadataAsync(metadataChange).ContinueWithOnMainThread(
(metadataTask) => {
if (!(metadataTask.IsCanceled || metadataTask.IsFaulted)) {
var metadata = metadataTask.Result;
Assert("metadata != null", metadata != null);
AssertEq("metadata.CacheControl", metadata.CacheControl, "no-transform");
AssertEq("metadata.CacheControl", metadata.ContentDisposition,
"attachment; filename=\"helloworld.txt\"");
AssertEq("metadata.CacheControl", metadata.ContentEncoding, "gzip");
AssertEq("metadata.ContentLanguage", metadata.ContentLanguage, "es");
AssertEq("metadata.ContentType", metadata.ContentType, "text/html; charset=utf-8");
AssertEq("metadata.Reference", metadata.Reference, GetStorageReference());
AssertEq("metadata.Bucket", metadata.Bucket, GetStorageReference().Bucket);
AssertEq("metadata.Name", metadata.Name, "small_text_file.txt");
Assert("metadata.CreationTimeMillis",
Math.Abs(MetadataTimeZoneNow().Subtract(
metadata.CreationTimeMillis).TotalSeconds) > 0);
Assert("metadata.UpdatedTimeMillis",
Math.Abs(MetadataTimeZoneNow().Subtract(
metadata.UpdatedTimeMillis).TotalMinutes) < 5);
Assert("metadata.Generation", Int64.Parse(metadata.Generation) > 0);
Assert("metadata.MetadataGeneration", Int64.Parse(metadata.MetadataGeneration) > 0);
AssertEq("metadata.SizeBytes", metadata.SizeBytes, expectedFileSize);
ValidateCustomMetadata(metadata, new Dictionary<string, string> {
{"this", "isnt"},
{"just", "a"},
{"set", "of"},
{"test", "metadata"},
{"its_different", "metadata"}
});
}
return metadataTask;
}).Unwrap();
}).Unwrap();
}
// Upload large file using stream and ensure returned metadata is valid after upload.
Task TestUploadStreamLargeFile() {
return UploadToPathUsingDelegate(LARGE_FILE_PATH, LARGE_FILE_CONTENTS, MetadataTestMode.Both,
UploadStream, ValidateUploadSuccessfulNotFile);
}
// Upload small file using stream and ensure returned metadata is valid after upload.
Task TestUploadStreamSmallFile() {
return UploadToPathUsingDelegate(SMALL_FILE_PATH, SMALL_FILE_CONTENTS, MetadataTestMode.Both,
UploadStream, ValidateUploadSuccessfulNotFile);
}
// Write contents to a local file relative to the persistent data path.
void WriteFile(string pathRelativeToPersistentDataPath, string contents) {
var localDirectory = persistentDataPath;
var localPath = Path.Combine(localDirectory, pathRelativeToPersistentDataPath);
if (!Directory.Exists(localDirectory))
Directory.CreateDirectory(localDirectory);
if (File.Exists(localPath))
File.Delete(localPath);
File.WriteAllText(localPath, contents);
}
// Upload from file and ensure returned storage metadata is valid after upload.
Task UploadFromFileToPath(string path, string contents,
TaskValidationDelegate taskValidationDelegate) {
var filename = Path.GetFileName(path);
WriteFile(filename, contents);
// Initialize UIHandler parameters.
localFilename = filename;
progressUpdateCount = 0;
storageLocation = path;
fileContents = "";
SetMetadataForTest(MetadataTestMode.Both, ContentTypePlainText);
expectedFileSize = contents.Length;
expectedStorageReference = GetStorageReference();
return ToTask(UploadFromFile()).ContinueWithOnMainThread((task) => {
return taskValidationDelegate(task);
}).Unwrap();
}
// The old C# implementation does not support file URIs so workaround the broken behavior.
protected override string PathToPersistentDataPathUriString(string filename) {
if (oldImplementationCompatibility) {
if (filename.StartsWith(UIHandler.UriFileScheme)) {
return filename.Substring(UIHandler.UriFileScheme.Length);
}
return Path.Combine(persistentDataPath, filename);
}
return base.PathToPersistentDataPathUriString(filename);
}
// Upload from large file and ensure returned metadata is valid after upload.
Task TestUploadFromFileLargeFile() {
return UploadFromFileToPath(LARGE_FILE_PATH, LARGE_FILE_CONTENTS,
ValidateUploadSuccessfulFile);
}
// Upload from small file and ensure returned metadata is valid after upload.
Task TestUploadFromFileSmallFile() {
return UploadFromFileToPath(SMALL_FILE_PATH, SMALL_FILE_CONTENTS,
ValidateUploadSuccessfulFile);
}
// Try uploading from a file that doesn't exist.
// The old C# implementation throws an exception on an internal thread when presented with an
// invalid filename which can't be caught by the application or in this case, this test case.
Task TestUploadFromNonExistantFile() {
if (oldImplementationCompatibility) {
return CompletedTask(); // TODO: Re-evaluate this
} else {
storageLocation = SMALL_FILE_PATH;
expectedStorageReference = GetStorageReference();
localFilename = Path.GetFileName(NON_EXISTANT_FILE_PATH);
var expectedLocalPath = PathToPersistentDataPathUriString(localFilename);
return ToTask(UploadFromFile()).ContinueWithOnMainThread((task) => {
var uploadTask = previousTask;
Assert("uploadTask.IsFaulted", uploadTask.IsFaulted);
var fileNotFoundException =
(new List<Exception>(uploadTask.Exception.InnerExceptions))[0] as FileNotFoundException;
Assert("fileNotFoundException", fileNotFoundException != null);
AssertEq("fileNotFoundException.FileName", fileNotFoundException.FileName,
expectedLocalPath);
return CompletedTask();
}).Unwrap();
}
}
// Coroutine method which cancels an operation after waiting cancelationDelay seconds or until the
// first progress update from the transfer.
IEnumerator CancelAfterDelayInSecondsCoroutine(float cancelationDelay) {
float startTime = UnityEngine.Time.realtimeSinceStartup;
yield return new WaitWhile(
() => {
return (UnityEngine.Time.realtimeSinceStartup - startTime) < cancelationDelay &&
progressUpdateCount == 0;
});
// Since it's possible for no progress updates occur before cancelation, fake one here so
// that ValidateTaskCanceled passes.
progressUpdateCount = 1;
CancelOperation();
// TODO: If a task fails prematurely or runs very quickly this could signal cancelation after
// the task is complete.
}
// Cancel an operation after waiting cancelationDelay seconds.
void CancelAfterDelayInSeconds(float cancelationDelay) {
mainThreadDispatcher.RunOnMainThread(() => {
StartCoroutine(CancelAfterDelayInSecondsCoroutine(cancelationDelay));
});
}
// Validate a task was canceled.
Task ValidateTaskCanceled(Task task) {
// NOTE: This uses "previousTask" to access the task returned by the UIHandler's method.
Assert("previousTask.IsCompleted", previousTask.IsCompleted);
Assert("previousTask.IsCanceled", previousTask.IsCanceled);
Assert("!previousTask.IsFaulted", !previousTask.IsFaulted);
return task;
}
// Start uploading from a byte array and cancel the upload.
Task TestUploadBytesWithCancelation() {
var task = UploadToPathUsingDelegate(LARGE_FILE_PATH, LARGE_FILE_CONTENTS,
MetadataTestMode.Both, UploadBytes, ValidateTaskCanceled);
CancelAfterDelayInSeconds(CANCELATION_DELAY_SECONDS);
return task;
}
// Start uploading with a stream and cancel the upload.
Task TestUploadStreamWithCancelation() {
var task = UploadToPathUsingDelegate(LARGE_FILE_PATH, LARGE_FILE_CONTENTS,
MetadataTestMode.Both, UploadStream, ValidateTaskCanceled);
CancelAfterDelayInSeconds(CANCELATION_DELAY_SECONDS);
return task;
}
// Start uploading from a file and cancel the upload.
Task TestUploadFromFileWithCancelation() {
var task = UploadFromFileToPath(LARGE_FILE_PATH, LARGE_FILE_CONTENTS, ValidateTaskCanceled);
CancelAfterDelayInSeconds(CANCELATION_DELAY_SECONDS);
return task;
}
// Upload small file and retrieve a download URL.
Task TestUploadSmallFileGetDownloadUrl() {
return TestUploadBytesSmallFile().ContinueWithOnMainThread((task) => {
return GetStorageReference().GetDownloadUrlAsync().ContinueWithOnMainThread(
(downloadUrlTask) => {
if (downloadUrlTask.IsCanceled || downloadUrlTask.IsFaulted)
return downloadUrlTask;
var url = downloadUrlTask.Result;
AssertEq("url.Host", url.Host, "firebasestorage.googleapis.com");
AssertEq("url.AbsolutePath", Uri.UnescapeDataString(url.AbsolutePath),
String.Format("/v0/b/{0}/o/{1}",
FirebaseApp.DefaultInstance.Options.StorageBucket,
SMALL_FILE_PATH));
return CompletedTask();
}
);
}).Unwrap();
}
// Get download URL from non-existant file.
Task TestGetDownloadUrlNonExistantFile() {
storageLocation = NON_EXISTANT_FILE_PATH;
return GetStorageReference().GetDownloadUrlAsync().ContinueWithOnMainThread((task) => {
Assert("task.IsFaulted", task.IsFaulted);
StorageException exception =
(StorageException)(new List<Exception>(task.Exception.InnerExceptions))[0];
AssertEq("exception.ErrorCode", exception.ErrorCode, StorageException.ErrorObjectNotFound);
AssertEq("exception.HttpResultCode", exception.HttpResultCode, 404);
return CompletedTask();
}).Unwrap();
}
// Upload small file and retrieve metadata.
Task TestUploadSmallFileGetMetadata() {
return TestUploadBytesSmallFile().ContinueWithOnMainThread((task) => {
return ToTask(GetMetadata()).ContinueWithOnMainThread((metadataTask) => {
if (metadataTask.IsCanceled || metadataTask.IsFaulted)
return metadataTask;
ValidateMetadata(((Task<StorageMetadata>)previousTask).Result, false, null);
return CompletedTask();
});
}).Unwrap();
}
// Get metadata from a known missing file.
Task GetMetadataNonExistantFile(string path) {
return FirebaseStorage.DefaultInstance.GetReference(
path).GetMetadataAsync().ContinueWithOnMainThread((task) => {
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
tcs.SetResult(task.IsFaulted);
return tcs.Task;
}).Unwrap();
}
// Get metadata from a non-existant file.
Task TestGetMetadataNonExistantFile() {
return GetMetadataNonExistantFile(NON_EXISTANT_FILE_PATH);
}
// Upload small file, delete and validate the file is inaccessible after deletion.
Task TestUploadSmallFileAndDelete() {
return TestUploadBytesSmallFile().ContinueWithOnMainThread((task) => {
return ToTask(Delete()).ContinueWithOnMainThread((deleteTask) => {
if (deleteTask.IsCanceled || deleteTask.IsFaulted)
return deleteTask;
// Try getting metadata from the reference, this should fail as the file has been
// deleted.
return GetMetadataNonExistantFile(SMALL_FILE_PATH);
});
}).Unwrap();
}
// Try to delete non-existant file.
Task TestDeleteNonExistantFile() {
storageLocation = NON_EXISTANT_FILE_PATH;
return ToTask(Delete()).ContinueWithOnMainThread((task) => {
Assert("task.IsFaulted", task.IsFaulted);
StorageException exception =
(StorageException)(new List<Exception>(previousTask.Exception.InnerExceptions))[0];
AssertEq("exception.ErrorCode", exception.ErrorCode,
Firebase.Storage.StorageException.ErrorObjectNotFound);
AssertEq("exception.HttpResultCode", exception.HttpResultCode, 404);
return CompletedTask();
}).Unwrap();
}
// Try to download non-existant file.
Task TestDownloadNonExistantFile() {
storageLocation = NON_EXISTANT_FILE_PATH;
return ToTask(DownloadBytes()).ContinueWithOnMainThread((task) => {
Assert("task.IsFaulted", task.IsFaulted);
StorageException exception =
(StorageException)(new List<Exception>(previousTask.Exception.InnerExceptions))[0];
AssertEq("exception.ErrorCode", exception.ErrorCode,
Firebase.Storage.StorageException.ErrorObjectNotFound);
AssertEq("exception.ErrorCode", exception.HttpResultCode, 404);
return CompletedTask();
}).Unwrap();
}
// Track download progress.
protected override void DisplayDownloadState(DownloadState downloadState) {
base.DisplayDownloadState(downloadState);
Assert("downloadState.BytesTransferred",
downloadState.BytesTransferred <= expectedFileSize ||
downloadState.BytesTransferred <= downloadState.TotalByteCount ||
expectedFileSize == 0);
AssertEq("downloadState.Reference.Path",
downloadState.Reference.Path, expectedStorageReference.Path);
// In mobile clients the reported total byte count includes metadata.
// Also, if the total download size isn't yet known it will be reported as -1.
Assert("downloadState.TotalByteCount",
downloadState.TotalByteCount < 0 ||
downloadState.TotalByteCount >= expectedFileSize);
progressUpdateCount++;
if (throwExceptionsInProgressCallbacks) {
throw new Exception(String.Format("Download state {0}", progressUpdateCount));
}
}
// Validate downloading a byte array matches the specified expected file contents.
Task ValidateDownloadedBytes(Task downloadTask, string contents) {
if (downloadTask.IsFaulted || downloadTask.IsCanceled)
return downloadTask;
var downloadTaskWithResult = previousTask as Task<byte[]>;
Assert("downloadTaskWithResult != null", downloadTaskWithResult != null);
// Validate the downloaded byte array matches the expected file contents.
var downloadedBytes = downloadTaskWithResult.Result;
var expectedFileContents = System.Text.Encoding.ASCII.GetBytes(contents);
AssertEq("expectedFileContents.Length", expectedFileContents.Length, downloadedBytes.Length);
for (int i = 0; i < expectedFileContents.Length; ++i) {
AssertEq(String.Format("expectedFileContents[{0}]", i),
expectedFileContents[i], downloadedBytes[i]);
}
// Downloading small files does not report status updates.
if (contents.Length == LARGE_FILE_CONTENTS.Length) {
Assert("progressUpdateCount", progressUpdateCount > 0);
}
return downloadTask;
}
// Upload file and download as byte array.
Task UploadAndDownloadAsByteArray(string path, string contents,
TaskValidationDelegate downloadTaskValidationDelegate,
Action predownloadOperation = null) {
return UploadToPathUsingDelegate(path, contents, MetadataTestMode.Both, UploadBytes,
ValidateUploadSuccessfulNotFile).ContinueWithOnMainThread(
(task) => {
if (task.IsFaulted || task.IsCanceled)
return task;
expectedStorageReference = GetStorageReference();
if (oldImplementationCompatibility) {
// To avoid a metadata fetch, the old implementation
// does not report the file size until the download is
// complete.
expectedFileSize = 0;
} else {
expectedFileSize = contents.Length;
}
progressUpdateCount = 0;
if (predownloadOperation != null)
predownloadOperation();
return ToTask(DownloadBytes()).ContinueWithOnMainThread(
(downloadTask) => {
return downloadTaskValidationDelegate(downloadTask);
}
).Unwrap();
}
).Unwrap();
}
// Upload a small file and download.
Task TestUploadSmallFileAndDownload() {
return UploadAndDownloadAsByteArray(
SMALL_FILE_PATH, SMALL_FILE_CONTENTS,
(task) => { return ValidateDownloadedBytes(task, SMALL_FILE_CONTENTS); });
}
// Upload a small file and download while throwing exceptions in the progress callbacks.
Task TestUploadSmallFileAndDownloadWithProgressExceptions() {
throwExceptionsInProgressCallbacks = true;
return UploadAndDownloadAsByteArray(
SMALL_FILE_PATH, SMALL_FILE_CONTENTS,
(task) => {
throwExceptionsInProgressCallbacks = false;
return ValidateDownloadedBytes(task, SMALL_FILE_CONTENTS);
});
}
// Upload a large file and download.
Task TestUploadLargeFileAndDownload() {
return UploadAndDownloadAsByteArray(
LARGE_FILE_PATH, LARGE_FILE_CONTENTS,
(task) => { return ValidateDownloadedBytes(task, LARGE_FILE_CONTENTS); });
}
// Upload a large file, start downloading then cancel.
Task TestUploadLargeFileAndDownloadWithCancelation() {
return UploadAndDownloadAsByteArray(
LARGE_FILE_PATH, LARGE_FILE_CONTENTS, ValidateTaskCanceled,
predownloadOperation: () => { CancelAfterDelayInSeconds(CANCELATION_DELAY_SECONDS); });
}
// Validate the result of a stream download operation.
Task ValidateDownloadedStream(Task downloadTask, string contents) {
AssertEq("fileContents.Length", fileContents.Length, contents.Length);
AssertEq("fileContents", fileContents, contents);
// Small downloads may not result in a progress update before the download is complete.
Assert("progressUpdateCount", contents.Length < LARGE_FILE_CONTENTS.Length ||
progressUpdateCount > 0);
return downloadTask;
}
// Upload file and download using a stream callback.
Task UploadAndDownloadUsingStreamCallback(string path, string contents,
TaskValidationDelegate downloadTaskValidationDelegate,
Action predownloadOperation = null) {
return UploadToPathUsingDelegate(path, contents, MetadataTestMode.Both, UploadBytes,
ValidateUploadSuccessfulNotFile).ContinueWithOnMainThread(
(task) => {
if (task.IsFaulted || task.IsCanceled)
return task;
expectedStorageReference = GetStorageReference();
if (oldImplementationCompatibility) {
// To avoid a metadata fetch, the old implementation
// does not report the file size until the download
// is complete.
expectedFileSize = 0;
} else {
expectedFileSize = contents.Length;
}
progressUpdateCount = 0;
if (predownloadOperation != null)
predownloadOperation();
return
ToTask(DownloadStream()).ContinueWithOnMainThread(
(downloadTask) => {
return downloadTaskValidationDelegate(task);
}
).Unwrap();
}
).Unwrap();
}
// Upload a small file and download using a stream callback.
Task TestUploadSmallFileAndDownloadUsingStreamCallback() {
return UploadAndDownloadUsingStreamCallback(
SMALL_FILE_PATH, SMALL_FILE_CONTENTS,
(task) => { return ValidateDownloadedStream(task, SMALL_FILE_CONTENTS); });
}
// Upload a large file and download using a stream callback.
Task TestUploadLargeFileAndDownloadUsingStreamCallback() {
return UploadAndDownloadUsingStreamCallback(
LARGE_FILE_PATH, LARGE_FILE_CONTENTS,
(task) => { return ValidateDownloadedStream(task, LARGE_FILE_CONTENTS); });
}
// Upload a large file, start downloading using a stream callback then cancel.
Task TestUploadLargeFileAndDownloadUsingStreamCallbackWithCancelation() {
return UploadAndDownloadUsingStreamCallback(
LARGE_FILE_PATH, LARGE_FILE_CONTENTS, ValidateTaskCanceled,
predownloadOperation: () => { CancelAfterDelayInSeconds(CANCELATION_DELAY_SECONDS); });
}
// Validate the result of a file download operation.
Task ValidateDownloadedFile(Task downloadTask, string contents) {
var filename = FileUriStringToPath(PathToPersistentDataPathUriString(localFilename));
Assert(String.Format("{0} exists", filename), File.Exists(filename));
var readFileContents = File.ReadAllText(filename);
AssertEq(String.Format("{0} Length", filename), readFileContents.Length, contents.Length);
AssertEq(String.Format("{0} contents", filename), readFileContents, contents);
// Validate UIHandler has read the file contents correctly.
AssertEq("fileContents.Length", fileContents.Length, contents.Length);
AssertEq("fileContents", fileContents, contents);
// When uploading small files it's possible for no progress updates to occur.
if (contents.Length == LARGE_FILE_CONTENTS.Length) {
Assert("progressUpdateCount", progressUpdateCount > 0);
}
return downloadTask;
}
// Upload file and download to a local file.
Task UploadAndDownloadToFile(string path, string contents,
TaskValidationDelegate downloadTaskValidationDelegate,
Action predownloadOperation = null) {
localFilename = Path.GetFileName(path);
var downloadFilePath = FileUriStringToPath(PathToPersistentDataPathUriString(localFilename));
if (File.Exists(downloadFilePath))
File.Delete(downloadFilePath);
return UploadToPathUsingDelegate(path, contents, MetadataTestMode.Both, UploadBytes,
ValidateUploadSuccessfulNotFile).ContinueWithOnMainThread(
(task) => {
if (task.IsFaulted || task.IsCanceled)
return task;
expectedStorageReference = GetStorageReference();
if (oldImplementationCompatibility) {
// To avoid a metadata fetch, the old implementation
// does not report the file size until the download is
// complete.
expectedFileSize = 0;
} else {
expectedFileSize = contents.Length;
}
progressUpdateCount = 0;
localFilename = Path.GetFileName(path);
if (predownloadOperation != null)
predownloadOperation();
return
ToTask(DownloadToFile()).ContinueWithOnMainThread(
(downloadTask) => {
return downloadTaskValidationDelegate(downloadTask);
}
).Unwrap();
}
).Unwrap();
}
// Upload a small file and download to a file.
Task TestUploadSmallFileAndDownloadToFile() {
return UploadAndDownloadToFile(
SMALL_FILE_PATH, SMALL_FILE_CONTENTS,
(task) => { return ValidateDownloadedFile(task, SMALL_FILE_CONTENTS); });
}
// Upload a large file and download to a file.
Task TestUploadLargeFileAndDownloadToFile() {
return UploadAndDownloadToFile(
LARGE_FILE_PATH, LARGE_FILE_CONTENTS,
(task) => { return ValidateDownloadedFile(task, LARGE_FILE_CONTENTS); });
}
// Upload a large file, start to download to a file then cancel.
Task TestUploadLargeFileAndDownloadToFileWithCancelation() {
return UploadAndDownloadToFile(
LARGE_FILE_PATH, LARGE_FILE_CONTENTS, ValidateTaskCanceled,
predownloadOperation: () => { CancelAfterDelayInSeconds(CANCELATION_DELAY_SECONDS); });
}
// TODO(smiles): Upload and attempt to partially download a file.
/// Wraps IEnumerator in an exception handling Task.
Task ToTask(IEnumerator ienum) {
TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
mainThreadDispatcher.RunOnMainThread(() => {
StartThrowingCoroutine(ienum, ex => {
if (ex == null) {
if (previousTask.IsFaulted) {
tcs.TrySetException(previousTask.Exception);
} else if (previousTask.IsCanceled) {
tcs.TrySetCanceled();
} else {
tcs.TrySetResult(true);
}
} else {
tcs.TrySetException(ex);
}
});
});
return tcs.Task;
}
/// Start a coroutine that might throw an exception. Call the callback with the exception if it
/// does or null if it finishes without throwing an exception.
public Coroutine StartThrowingCoroutine(IEnumerator enumerator, Action<Exception> done) {
return StartCoroutine(RunThrowingIterator(enumerator, done));
}
/// Run an iterator function that might throw an exception. Call the callback with the exception
/// if it does or null if it finishes without throwing an exception.
public static IEnumerator RunThrowingIterator(IEnumerator enumerator, Action<Exception> done) {
while (true) {
object current;
try {
if (enumerator.MoveNext() == false) {
break;
}
current = enumerator.Current;
} catch (Exception ex) {
done(ex);
yield break;
}
yield return current;
}
done(null);
}
}
}
| |
// Copyright 2011 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 System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using NodaTime.Globalization;
using NodaTime.Properties;
using NodaTime.Utility;
using JetBrains.Annotations;
namespace NodaTime.Text.Patterns
{
/// <summary>
/// Builder for a pattern which implements parsing and formatting as a sequence of steps applied
/// in turn.
/// </summary>
internal sealed class SteppedPatternBuilder<TResult, TBucket> where TBucket : ParseBucket<TResult>
{
internal delegate ParseResult<TResult> ParseAction(ValueCursor cursor, TBucket bucket);
private readonly List<Action<TResult, StringBuilder>> formatActions;
private readonly List<ParseAction> parseActions;
private readonly Func<TBucket> bucketProvider;
private PatternFields usedFields;
private bool formatOnly = false;
internal NodaFormatInfo FormatInfo { get; }
internal PatternFields UsedFields => usedFields;
internal SteppedPatternBuilder(NodaFormatInfo formatInfo, Func<TBucket> bucketProvider)
{
this.FormatInfo = formatInfo;
formatActions = new List<Action<TResult, StringBuilder>>();
parseActions = new List<ParseAction>();
this.bucketProvider = bucketProvider;
}
/// <summary>
/// Sets this pattern to only be capable of formatting; any attempt to parse using the
/// built pattern will fail immediately.
/// </summary>
internal void SetFormatOnly()
{
formatOnly = true;
}
/// <summary>
/// Performs common parsing operations: start with a parse action to move the
/// value cursor onto the first character, then call a character handler for each
/// character in the pattern to build up the steps. If any handler fails,
/// that failure is returned - otherwise the return value is null.
/// </summary>
internal void ParseCustomPattern(string patternText,
Dictionary<char, CharacterHandler<TResult, TBucket>> characterHandlers)
{
var patternCursor = new PatternCursor(patternText);
// Now iterate over the pattern.
while (patternCursor.MoveNext())
{
CharacterHandler<TResult, TBucket> handler;
if (characterHandlers.TryGetValue(patternCursor.Current, out handler))
{
handler(patternCursor, this);
}
else
{
char current = patternCursor.Current;
if ((current >= 'A' && current <= 'Z') || (current >= 'a' && current <= 'z'))
{
throw new InvalidPatternException(Messages.Parse_UnquotedLiteral, current);
}
AddLiteral(patternCursor.Current, ParseResult<TResult>.MismatchedCharacter);
}
}
}
/// <summary>
/// Validates the combination of fields used.
/// </summary>
internal void ValidateUsedFields()
{
// We assume invalid combinations are global across all parsers. The way that
// the patterns are parsed ensures we never end up with any invalid individual fields
// (e.g. time fields within a date pattern).
if ((usedFields & (PatternFields.Era | PatternFields.YearOfEra)) == PatternFields.Era)
{
throw new InvalidPatternException(Messages.Parse_EraWithoutYearOfEra);
}
const PatternFields calendarAndEra = PatternFields.Era | PatternFields.Calendar;
if ((usedFields & calendarAndEra) == calendarAndEra)
{
throw new InvalidPatternException(Messages.Parse_CalendarAndEra);
}
}
/// <summary>
/// Returns a built pattern. This is mostly to keep the API for the builder separate from that of the pattern,
/// and for thread safety (publishing a new object, thus leading to a memory barrier).
/// Note that this builder *must not* be used after the result has been built.
/// </summary>
internal IPartialPattern<TResult> Build(TResult sample)
{
Action<TResult, StringBuilder> formatDelegate = null;
foreach (Action<TResult, StringBuilder> formatAction in formatActions)
{
IPostPatternParseFormatAction postAction = formatAction.Target as IPostPatternParseFormatAction;
formatDelegate += postAction == null ? formatAction : postAction.BuildFormatAction(usedFields);
}
return new SteppedPattern(formatDelegate, formatOnly ? null : parseActions.ToArray(), bucketProvider, usedFields, sample);
}
/// <summary>
/// Registers that a pattern field has been used in this pattern, and throws a suitable error
/// result if it's already been used.
/// </summary>
internal void AddField(PatternFields field, char characterInPattern)
{
PatternFields newUsedFields = usedFields | field;
if (newUsedFields == usedFields)
{
throw new InvalidPatternException(Messages.Parse_RepeatedFieldInPattern, characterInPattern);
}
usedFields = newUsedFields;
}
internal void AddParseAction(ParseAction parseAction) => parseActions.Add(parseAction);
internal void AddFormatAction(Action<TResult, StringBuilder> formatAction) => formatActions.Add(formatAction);
/// <summary>
/// Equivalent of <see cref="AddParseValueAction"/> but for 64-bit integers. Currently only
/// positive values are supported.
/// </summary>
internal void AddParseInt64ValueAction(int minimumDigits, int maximumDigits, char patternChar,
long minimumValue, long maximumValue, Action<TBucket, long> valueSetter)
{
Preconditions.DebugCheckArgumentRange(nameof(minimumValue), minimumValue, 0, long.MaxValue);
AddParseAction((cursor, bucket) =>
{
int startingIndex = cursor.Index;
long value;
if (!cursor.ParseInt64Digits(minimumDigits, maximumDigits, out value))
{
cursor.Move(startingIndex);
return ParseResult<TResult>.MismatchedNumber(cursor, new string(patternChar, minimumDigits));
}
if (value < minimumValue || value > maximumValue)
{
cursor.Move(startingIndex);
return ParseResult<TResult>.FieldValueOutOfRange(cursor, value, patternChar);
}
valueSetter(bucket, value);
return null;
});
}
internal void AddParseValueAction(int minimumDigits, int maximumDigits, char patternChar,
int minimumValue, int maximumValue,
Action<TBucket, int> valueSetter)
{
AddParseAction((cursor, bucket) =>
{
int startingIndex = cursor.Index;
int value;
bool negative = cursor.Match('-');
if (negative && minimumValue >= 0)
{
cursor.Move(startingIndex);
return ParseResult<TResult>.UnexpectedNegative(cursor);
}
if (!cursor.ParseDigits(minimumDigits, maximumDigits, out value))
{
cursor.Move(startingIndex);
return ParseResult<TResult>.MismatchedNumber(cursor, new string(patternChar, minimumDigits));
}
if (negative)
{
value = -value;
}
if (value < minimumValue || value > maximumValue)
{
cursor.Move(startingIndex);
return ParseResult<TResult>.FieldValueOutOfRange(cursor, value, patternChar);
}
valueSetter(bucket, value);
return null;
});
}
/// <summary>
/// Adds text which must be matched exactly when parsing, and appended directly when formatting.
/// </summary>
internal void AddLiteral(string expectedText, Func<ValueCursor, ParseResult<TResult>> failure)
{
// Common case - single character literal, often a date or time separator.
if (expectedText.Length == 1)
{
char expectedChar = expectedText[0];
AddParseAction((str, bucket) => str.Match(expectedChar) ? null : failure(str));
AddFormatAction((value, builder) => builder.Append(expectedChar));
return;
}
AddParseAction((str, bucket) => str.Match(expectedText) ? null : failure(str));
AddFormatAction((value, builder) => builder.Append(expectedText));
}
internal static void HandleQuote(PatternCursor pattern, SteppedPatternBuilder<TResult, TBucket> builder)
{
string quoted = pattern.GetQuotedString(pattern.Current);
builder.AddLiteral(quoted, ParseResult<TResult>.QuotedStringMismatch);
}
internal static void HandleBackslash(PatternCursor pattern, SteppedPatternBuilder<TResult, TBucket> builder)
{
if (!pattern.MoveNext())
{
throw new InvalidPatternException(Messages.Parse_EscapeAtEndOfString);
}
builder.AddLiteral(pattern.Current, ParseResult<TResult>.EscapedCharacterMismatch);
}
/// <summary>
/// Handle a leading "%" which acts as a pseudo-escape - it's mostly used to allow format strings such as "%H" to mean
/// "use a custom format string consisting of H instead of a standard pattern H".
/// </summary>
internal static void HandlePercent(PatternCursor pattern, SteppedPatternBuilder<TResult, TBucket> builder)
{
if (pattern.HasMoreCharacters)
{
if (pattern.PeekNext() != '%')
{
// Handle the next character as normal
return;
}
throw new InvalidPatternException(Messages.Parse_PercentDoubled);
}
throw new InvalidPatternException(Messages.Parse_PercentAtEndOfString);
}
/// <summary>
/// Returns a handler for a zero-padded purely-numeric field specifier, such as "seconds", "minutes", "24-hour", "12-hour" etc.
/// </summary>
/// <param name="maxCount">Maximum permissable count (usually two)</param>
/// <param name="field">Field to remember that we've seen</param>
/// <param name="minValue">Minimum valid value for the field (inclusive)</param>
/// <param name="maxValue">Maximum value value for the field (inclusive)</param>
/// <param name="getter">Delegate to retrieve the field value when formatting</param>
/// <param name="setter">Delegate to set the field value into a bucket when parsing</param>
/// <returns>The pattern parsing failure, or null on success.</returns>
internal static CharacterHandler<TResult, TBucket> HandlePaddedField(int maxCount, PatternFields field, int minValue, int maxValue, Func<TResult, int> getter,
Action<TBucket, int> setter)
{
return (pattern, builder) =>
{
int count = pattern.GetRepeatCount(maxCount);
builder.AddField(field, pattern.Current);
builder.AddParseValueAction(count, maxCount, pattern.Current, minValue, maxValue, setter);
builder.AddFormatLeftPad(count, getter, assumeNonNegative: minValue >= 0, assumeFitsInCount: count == maxCount);
};
}
/// <summary>
/// Adds a character which must be matched exactly when parsing, and appended directly when formatting.
/// </summary>
internal void AddLiteral(char expectedChar, Func<ValueCursor, char, ParseResult<TResult>> failureSelector)
{
AddParseAction((str, bucket) => str.Match(expectedChar) ? null : failureSelector(str, expectedChar));
AddFormatAction((value, builder) => builder.Append(expectedChar));
}
/// <summary>
/// Adds parse actions for a list of strings, such as days of the week or month names.
/// The parsing is performed case-insensitively. All candidates are tested, and only the longest
/// match is used.
/// </summary>
internal void AddParseLongestTextAction(char field, Action<TBucket, int> setter, CompareInfo compareInfo, IList<string> textValues)
{
AddParseAction((str, bucket) => {
int bestIndex = -1;
int longestMatch = 0;
FindLongestMatch(compareInfo, str, textValues, ref bestIndex, ref longestMatch);
if (bestIndex != -1)
{
setter(bucket, bestIndex);
str.Move(str.Index + longestMatch);
return null;
}
return ParseResult<TResult>.MismatchedText(str, field);
});
}
/// <summary>
/// Adds parse actions for two list of strings, such as non-genitive and genitive month names.
/// The parsing is performed case-insensitively. All candidates are tested, and only the longest
/// match is used.
/// </summary>
internal void AddParseLongestTextAction(char field, Action<TBucket, int> setter, CompareInfo compareInfo, IList<string> textValues1, IList<string> textValues2)
{
AddParseAction((str, bucket) =>
{
int bestIndex = -1;
int longestMatch = 0;
FindLongestMatch(compareInfo, str, textValues1, ref bestIndex, ref longestMatch);
FindLongestMatch(compareInfo, str, textValues2, ref bestIndex, ref longestMatch);
if (bestIndex != -1)
{
setter(bucket, bestIndex);
str.Move(str.Index + longestMatch);
return null;
}
return ParseResult<TResult>.MismatchedText(str, field);
});
}
/// <summary>
/// Find the longest match from a given set of candidate strings, updating the index/length of the best value
/// accordingly.
/// </summary>
private static void FindLongestMatch(CompareInfo compareInfo, ValueCursor cursor, IList<string> values, ref int bestIndex, ref int longestMatch)
{
for (int i = 0; i < values.Count; i++)
{
string candidate = values[i];
if (candidate == null || candidate.Length <= longestMatch)
{
continue;
}
if (cursor.MatchCaseInsensitive(candidate, compareInfo, false))
{
bestIndex = i;
longestMatch = candidate.Length;
}
}
}
/// <summary>
/// Adds parse and format actions for a mandatory positive/negative sign.
/// </summary>
/// <param name="signSetter">Action to take when to set the given sign within the bucket</param>
/// <param name="nonNegativePredicate">Predicate to detect whether the value being formatted is non-negative</param>
public void AddRequiredSign(Action<TBucket, bool> signSetter, Func<TResult, bool> nonNegativePredicate)
{
string negativeSign = FormatInfo.NegativeSign;
string positiveSign = FormatInfo.PositiveSign;
AddParseAction((str, bucket) =>
{
if (str.Match(negativeSign))
{
signSetter(bucket, false);
return null;
}
if (str.Match(positiveSign))
{
signSetter(bucket, true);
return null;
}
return ParseResult<TResult>.MissingSign(str);
});
AddFormatAction((value, sb) => sb.Append(nonNegativePredicate(value) ? positiveSign : negativeSign));
}
/// <summary>
/// Adds parse and format actions for an "negative only" sign.
/// </summary>
/// <param name="signSetter">Action to take when to set the given sign within the bucket</param>
/// <param name="nonNegativePredicate">Predicate to detect whether the value being formatted is non-negative</param>
public void AddNegativeOnlySign(Action<TBucket, bool> signSetter, Func<TResult, bool> nonNegativePredicate)
{
string negativeSign = FormatInfo.NegativeSign;
string positiveSign = FormatInfo.PositiveSign;
AddParseAction((str, bucket) =>
{
if (str.Match(negativeSign))
{
signSetter(bucket, false);
return null;
}
if (str.Match(positiveSign))
{
return ParseResult<TResult>.PositiveSignInvalid(str);
}
signSetter(bucket, true);
return null;
});
AddFormatAction((value, builder) =>
{
if (!nonNegativePredicate(value))
{
builder.Append(negativeSign);
}
});
}
/// <summary>
/// Adds an action to pad a selected value to a given minimum lenth.
/// </summary>
/// <param name="count">The minimum length to pad to</param>
/// <param name="selector">The selector function to apply to obtain a value to format</param>
/// <param name="assumeNonNegative">Whether it is safe to assume the value will be non-negative</param>
/// <param name="assumeFitsInCount">Whether it is safe to assume the value will not exceed the specified length</param>
internal void AddFormatLeftPad(int count, Func<TResult, int> selector,
bool assumeNonNegative, bool assumeFitsInCount)
{
if (count == 2 && assumeNonNegative && assumeFitsInCount)
{
AddFormatAction((value, sb) => FormatHelper.Format2DigitsNonNegative(selector(value), sb));
}
else if (count == 4 && assumeFitsInCount)
{
AddFormatAction((value, sb) => FormatHelper.Format4DigitsValueFits(selector(value), sb));
}
else if (assumeNonNegative)
{
AddFormatAction((value, sb) => FormatHelper.LeftPadNonNegative(selector(value), count, sb));
}
else
{
AddFormatAction((value, sb) => FormatHelper.LeftPad(selector(value), count, sb));
}
}
internal void AddFormatFraction(int width, int scale, Func<TResult, int> selector) =>
AddFormatAction((value, sb) => FormatHelper.AppendFraction(selector(value), width, scale, sb));
internal void AddFormatFractionTruncate(int width, int scale, Func<TResult, int> selector) =>
AddFormatAction((value, sb) => FormatHelper.AppendFractionTruncate(selector(value), width, scale, sb));
/// <summary>
/// Hack to handle genitive month names - we only know what we need to do *after* we've parsed the whole pattern.
/// </summary>
internal interface IPostPatternParseFormatAction
{
Action<TResult, StringBuilder> BuildFormatAction(PatternFields finalFields);
}
private sealed class SteppedPattern : IPartialPattern<TResult>
{
private readonly Action<TResult, StringBuilder> formatActions;
// This will be null if the pattern is only capable of formatting.
private readonly ParseAction[] parseActions;
private readonly Func<TBucket> bucketProvider;
private readonly PatternFields usedFields;
private readonly int expectedLength;
public SteppedPattern(Action<TResult, StringBuilder> formatActions,
ParseAction[] parseActions,
Func<TBucket> bucketProvider,
PatternFields usedFields,
TResult sample)
{
this.formatActions = formatActions;
this.parseActions = parseActions;
this.bucketProvider = bucketProvider;
this.usedFields = usedFields;
// Format the sample value to work out the expected length, so we
// can use that when creating a StringBuilder. This will definitely not always
// be appropriate, but it's a start.
StringBuilder builder = new StringBuilder();
formatActions(sample, builder);
expectedLength = builder.Length;
}
public ParseResult<TResult> Parse(string text)
{
if (parseActions == null)
{
return ParseResult<TResult>.FormatOnlyPattern;
}
if (text == null)
{
return ParseResult<TResult>.ArgumentNull("text");
}
if (text.Length == 0)
{
return ParseResult<TResult>.ValueStringEmpty;
}
var valueCursor = new ValueCursor(text);
// Prime the pump... the value cursor ends up *before* the first character, but
// our steps always assume it's *on* the right character.
valueCursor.MoveNext();
var result = ParsePartial(valueCursor);
if (!result.Success)
{
return result;
}
// Check that we've used up all the text
if (valueCursor.Current != TextCursor.Nul)
{
return ParseResult<TResult>.ExtraValueCharacters(valueCursor, valueCursor.Remainder);
}
return result;
}
public string Format(TResult value)
{
StringBuilder builder = new StringBuilder(expectedLength);
// This will call all the actions in the multicast delegate.
formatActions(value, builder);
return builder.ToString();
}
public ParseResult<TResult> ParsePartial(ValueCursor cursor)
{
TBucket bucket = bucketProvider();
foreach (var action in parseActions)
{
ParseResult<TResult> failure = action(cursor, bucket);
if (failure != null)
{
return failure;
}
}
return bucket.CalculateValue(usedFields, cursor.Value);
}
public StringBuilder AppendFormat(TResult value, [NotNull] StringBuilder builder)
{
Preconditions.CheckNotNull(builder, nameof(builder));
formatActions(value, builder);
return builder;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace distReST.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Text;
namespace gpcc
{
public class Parser
{
private Grammar grammar;
private int tokenStartLine;
private int tokenStartColumn;
private GrammarToken token;
private Scanner scanner;
public Grammar Parse(string filename)
{
this.scanner = new Scanner(filename);
this.grammar = new Grammar();
this.Advance();
this.ParseHeader();
this.ParseDeclarations();
this.ParseProductions();
this.ParseEpilog();
return this.grammar;
}
private void ParseDeclarations()
{
int num = 0;
while (this.token != GrammarToken.EndOfSection && this.token != GrammarToken.Eof)
{
switch (this.token)
{
case GrammarToken.Union:
this.grammar.unionType = this.scanner.yylval;
this.Advance();
continue;
case GrammarToken.Type:
{
this.Advance();
string kind = null;
if (this.token == GrammarToken.Kind)
{
kind = this.scanner.yylval;
this.Advance();
}
while (this.token == GrammarToken.Symbol)
{
NonTerminal nonTerminal = this.grammar.LookupNonTerminal(this.scanner.yylval);
nonTerminal.kind = kind;
this.Advance();
}
continue;
}
case GrammarToken.Token:
{
this.Advance();
string kind2 = null;
if (this.token == GrammarToken.Kind)
{
kind2 = this.scanner.yylval;
this.Advance();
}
while (this.token == GrammarToken.Symbol)
{
Terminal terminal = this.grammar.LookupTerminal(this.token, this.scanner.yylval);
terminal.kind = kind2;
this.Advance();
}
continue;
}
case GrammarToken.Left:
this.Advance();
num += 10;
while (this.token == GrammarToken.Symbol || this.token == GrammarToken.Literal)
{
Terminal terminal2 = this.grammar.LookupTerminal(this.token, this.scanner.yylval);
terminal2.prec = new Precedence(PrecType.left, num);
this.Advance();
}
continue;
case GrammarToken.Right:
this.Advance();
num += 10;
while (this.token == GrammarToken.Symbol || this.token == GrammarToken.Literal)
{
Terminal terminal3 = this.grammar.LookupTerminal(this.token, this.scanner.yylval);
terminal3.prec = new Precedence(PrecType.right, num);
this.Advance();
}
continue;
case GrammarToken.NonAssoc:
this.Advance();
num += 10;
while (this.token == GrammarToken.Symbol || this.token == GrammarToken.Literal)
{
Terminal terminal4 = this.grammar.LookupTerminal(this.token, this.scanner.yylval);
terminal4.prec = new Precedence(PrecType.nonassoc, num);
this.Advance();
}
continue;
case GrammarToken.Prolog:
{
Grammar expr_7B = this.grammar;
expr_7B.prologCode += this.scanner.yylval;
this.Advance();
continue;
}
case GrammarToken.Start:
this.Advance();
if (this.token == GrammarToken.Symbol)
{
this.grammar.startSymbol = this.grammar.LookupNonTerminal(this.scanner.yylval);
this.Advance();
continue;
}
continue;
case GrammarToken.Namespace:
this.Advance();
this.grammar.Namespace = this.scanner.yylval;
this.Advance();
while (this.scanner.yylval == ".")
{
this.Advance();
Grammar expr_2FF = this.grammar;
expr_2FF.Namespace = expr_2FF.Namespace + "." + this.scanner.yylval;
this.Advance();
}
continue;
case GrammarToken.Visibility:
this.Advance();
this.grammar.Visibility = this.scanner.yylval;
this.Advance();
continue;
case GrammarToken.Attributes:
{
this.Advance();
StringBuilder stringBuilder = new StringBuilder(this.scanner.yylval);
while (this.Advance() == GrammarToken.Symbol)
{
stringBuilder.Append(' ');
stringBuilder.Append(this.scanner.yylval);
}
this.grammar.Attributes = stringBuilder.ToString();
continue;
}
case GrammarToken.ParserName:
this.Advance();
this.grammar.ParserName = this.scanner.yylval;
this.Advance();
continue;
case GrammarToken.TokenName:
this.Advance();
this.grammar.TokenName = this.scanner.yylval;
this.Advance();
continue;
case GrammarToken.ValueTypeName:
this.Advance();
this.grammar.ValueTypeName = this.scanner.yylval;
this.Advance();
continue;
case GrammarToken.PositionType:
this.Advance();
this.grammar.PositionType = this.scanner.yylval;
this.Advance();
continue;
}
this.scanner.ReportError("Unexpected token {0} in declaration section", new object[]
{
this.token
});
this.Advance();
}
this.Advance();
}
private void ParseProductions()
{
while (this.token != GrammarToken.EndOfSection && this.token != GrammarToken.Eof)
{
while (this.token == GrammarToken.Symbol)
{
this.ParseProduction();
}
}
this.Advance();
}
private void ParseProduction()
{
NonTerminal nonTerminal = null;
if (this.token == GrammarToken.Symbol)
{
nonTerminal = this.grammar.LookupNonTerminal(this.scanner.yylval);
if (this.grammar.startSymbol == null)
{
this.grammar.startSymbol = nonTerminal;
}
if (this.grammar.productions.Count == 0)
{
this.grammar.CreateSpecialProduction(this.grammar.startSymbol);
}
}
else
{
this.scanner.ReportError("lhs symbol expected", new object[0]);
}
this.Advance();
if (this.token != GrammarToken.Colon)
{
this.scanner.ReportError("Colon expected", new object[0]);
}
else
{
this.Advance();
}
this.ParseRhs(nonTerminal);
while (this.token == GrammarToken.Divider)
{
this.Advance();
this.ParseRhs(nonTerminal);
}
if (this.token != GrammarToken.SemiColon)
{
this.scanner.ReportError("Semicolon expected", new object[0]);
return;
}
this.Advance();
}
private void ParseRhs(NonTerminal lhs)
{
Production production = new Production(lhs);
int num = 0;
while (this.token == GrammarToken.Symbol || this.token == GrammarToken.Literal || this.token == GrammarToken.Action || this.token == GrammarToken.Prec)
{
GrammarToken grammarToken = this.token;
switch (grammarToken)
{
case GrammarToken.Symbol:
if (this.grammar.terminals.ContainsKey(this.scanner.yylval))
{
production.rhs.Add(this.grammar.terminals[this.scanner.yylval]);
}
else
{
production.rhs.Add(this.grammar.LookupNonTerminal(this.scanner.yylval));
}
this.Advance();
num++;
break;
case GrammarToken.Literal:
production.rhs.Add(this.grammar.LookupTerminal(this.token, this.scanner.yylval));
this.Advance();
num++;
break;
case GrammarToken.Action:
{
SemanticAction semanticAction = new SemanticAction(production, this.tokenStartLine, num, this.scanner.yylval);
this.Advance();
if (this.token == GrammarToken.Divider || this.token == GrammarToken.SemiColon || this.token == GrammarToken.Prec)
{
production.semanticAction = semanticAction;
}
else
{
Grammar arg_1BA_0 = this.grammar;
string arg_1B5_0 = "@";
int num2 = ++this.grammar.NumActions;
NonTerminal nonTerminal = arg_1BA_0.LookupNonTerminal(arg_1B5_0 + num2.ToString());
Production production2 = new Production(nonTerminal);
production2.semanticAction = semanticAction;
this.grammar.AddProduction(production2);
production.rhs.Add(nonTerminal);
}
num++;
break;
}
default:
if (grammarToken == GrammarToken.Prec)
{
this.Advance();
if (this.token == GrammarToken.Symbol)
{
production.prec = this.grammar.LookupTerminal(this.token, this.scanner.yylval).prec;
this.Advance();
}
else
{
this.scanner.ReportError("Expected symbol after %prec", new object[0]);
}
}
break;
}
}
this.grammar.AddProduction(production);
Precedence.Calculate(production);
}
private void ParseHeader()
{
if (this.token == GrammarToken.Prelude)
{
this.grammar.headerCode = this.scanner.yylval;
this.Advance();
}
if (this.token != GrammarToken.EndOfSection)
{
this.scanner.ReportError("Expected next section", new object[0]);
}
this.Advance();
}
private void ParseEpilog()
{
this.grammar.epilogCode = this.scanner.yylval;
this.Advance();
if (this.token != GrammarToken.Eof)
{
this.scanner.ReportError("Expected EOF", new object[0]);
}
}
private GrammarToken Advance()
{
this.tokenStartLine = this.scanner.CurrentLine;
this.tokenStartColumn = this.scanner.CurrentColumn;
return this.token = this.scanner.Next();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Net
{
[System.FlagsAttribute]
public enum AuthenticationSchemes
{
Anonymous = 32768,
Basic = 8,
Digest = 1,
IntegratedWindowsAuthentication = 6,
Negotiate = 2,
None = 0,
Ntlm = 4,
}
public sealed partial class Cookie
{
public Cookie() { }
public Cookie(string name, string value) { }
public Cookie(string name, string value, string path) { }
public Cookie(string name, string value, string path, string domain) { }
public string Comment { get { return default(string); } set { } }
public System.Uri CommentUri { get { return default(System.Uri); } set { } }
public bool Discard { get { return default(bool); } set { } }
public string Domain { get { return default(string); } set { } }
public bool Expired { get { return default(bool); } set { } }
public System.DateTime Expires { get { return default(System.DateTime); } set { } }
public bool HttpOnly { get { return default(bool); } set { } }
public string Name { get { return default(string); } set { } }
public string Path { get { return default(string); } set { } }
public string Port { get { return default(string); } set { } }
public bool Secure { get { return default(bool); } set { } }
public System.DateTime TimeStamp { get { return default(System.DateTime); } }
public string Value { get { return default(string); } set { } }
public int Version { get { return default(int); } set { } }
public override bool Equals(object comparand) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
public partial class CookieCollection : System.Collections.ICollection, System.Collections.IEnumerable
{
public CookieCollection() { }
public int Count { get { return default(int); } }
public System.Net.Cookie this[string name] { get { return default(System.Net.Cookie); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
public void Add(System.Net.Cookie cookie) { }
public void Add(System.Net.CookieCollection cookies) { }
public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
}
public partial class CookieContainer
{
public const int DefaultCookieLengthLimit = 4096;
public const int DefaultCookieLimit = 300;
public const int DefaultPerDomainCookieLimit = 20;
public CookieContainer() { }
public int Capacity { get { return default(int); } set { } }
public int Count { get { return default(int); } }
public int MaxCookieSize { get { return default(int); } set { } }
public int PerDomainCapacity { get { return default(int); } set { } }
public void Add(System.Uri uri, System.Net.Cookie cookie) { }
public void Add(System.Uri uri, System.Net.CookieCollection cookies) { }
public string GetCookieHeader(System.Uri uri) { return default(string); }
public System.Net.CookieCollection GetCookies(System.Uri uri) { return default(System.Net.CookieCollection); }
public void SetCookies(System.Uri uri, string cookieHeader) { }
}
public partial class CookieException : System.FormatException
{
public CookieException() { }
}
public partial class CredentialCache : System.Collections.IEnumerable, System.Net.ICredentials, System.Net.ICredentialsByHost
{
public CredentialCache() { }
public static System.Net.ICredentials DefaultCredentials { get { return default(System.Net.ICredentials); } }
public static System.Net.NetworkCredential DefaultNetworkCredentials { get { return default(System.Net.NetworkCredential); } }
public void Add(string host, int port, string authenticationType, System.Net.NetworkCredential credential) { }
public void Add(System.Uri uriPrefix, string authType, System.Net.NetworkCredential cred) { }
public System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType) { return default(System.Net.NetworkCredential); }
public System.Net.NetworkCredential GetCredential(System.Uri uriPrefix, string authType) { return default(System.Net.NetworkCredential); }
public System.Collections.IEnumerator GetEnumerator() { return default(System.Collections.IEnumerator); }
public void Remove(string host, int port, string authenticationType) { }
public void Remove(System.Uri uriPrefix, string authType) { }
}
[System.FlagsAttribute]
public enum DecompressionMethods
{
Deflate = 2,
GZip = 1,
None = 0,
}
public partial class DnsEndPoint : System.Net.EndPoint
{
public DnsEndPoint(string host, int port) { }
public DnsEndPoint(string host, int port, System.Net.Sockets.AddressFamily addressFamily) { }
public override System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } }
public string Host { get { return default(string); } }
public int Port { get { return default(int); } }
public override bool Equals(object comparand) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
public abstract partial class EndPoint
{
protected EndPoint() { }
public virtual System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } }
public virtual System.Net.EndPoint Create(System.Net.SocketAddress socketAddress) { return default(System.Net.EndPoint); }
public virtual System.Net.SocketAddress Serialize() { return default(System.Net.SocketAddress); }
}
public enum HttpStatusCode
{
Accepted = 202,
Ambiguous = 300,
BadGateway = 502,
BadRequest = 400,
Conflict = 409,
Continue = 100,
Created = 201,
ExpectationFailed = 417,
Forbidden = 403,
Found = 302,
GatewayTimeout = 504,
Gone = 410,
HttpVersionNotSupported = 505,
InternalServerError = 500,
LengthRequired = 411,
MethodNotAllowed = 405,
Moved = 301,
MovedPermanently = 301,
MultipleChoices = 300,
NoContent = 204,
NonAuthoritativeInformation = 203,
NotAcceptable = 406,
NotFound = 404,
NotImplemented = 501,
NotModified = 304,
OK = 200,
PartialContent = 206,
PaymentRequired = 402,
PreconditionFailed = 412,
ProxyAuthenticationRequired = 407,
Redirect = 302,
RedirectKeepVerb = 307,
RedirectMethod = 303,
RequestedRangeNotSatisfiable = 416,
RequestEntityTooLarge = 413,
RequestTimeout = 408,
RequestUriTooLong = 414,
ResetContent = 205,
SeeOther = 303,
ServiceUnavailable = 503,
SwitchingProtocols = 101,
TemporaryRedirect = 307,
Unauthorized = 401,
UnsupportedMediaType = 415,
Unused = 306,
UpgradeRequired = 426,
UseProxy = 305,
}
public partial interface ICredentials
{
System.Net.NetworkCredential GetCredential(System.Uri uri, string authType);
}
public partial interface ICredentialsByHost
{
System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType);
}
public partial class IPAddress
{
public static readonly System.Net.IPAddress Any;
public static readonly System.Net.IPAddress Broadcast;
public static readonly System.Net.IPAddress IPv6Any;
public static readonly System.Net.IPAddress IPv6Loopback;
public static readonly System.Net.IPAddress IPv6None;
public static readonly System.Net.IPAddress Loopback;
public static readonly System.Net.IPAddress None;
public IPAddress(byte[] address) { }
public IPAddress(byte[] address, long scopeid) { }
public IPAddress(long newAddress) { }
public System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } }
public bool IsIPv4MappedToIPv6 { get { return default(bool); } }
public bool IsIPv6LinkLocal { get { return default(bool); } }
public bool IsIPv6Multicast { get { return default(bool); } }
public bool IsIPv6SiteLocal { get { return default(bool); } }
public bool IsIPv6Teredo { get { return default(bool); } }
public long ScopeId { get { return default(long); } set { } }
public override bool Equals(object comparand) { return default(bool); }
public byte[] GetAddressBytes() { return default(byte[]); }
public override int GetHashCode() { return default(int); }
public static short HostToNetworkOrder(short host) { return default(short); }
public static int HostToNetworkOrder(int host) { return default(int); }
public static long HostToNetworkOrder(long host) { return default(long); }
public static bool IsLoopback(System.Net.IPAddress address) { return default(bool); }
public System.Net.IPAddress MapToIPv4() { return default(System.Net.IPAddress); }
public System.Net.IPAddress MapToIPv6() { return default(System.Net.IPAddress); }
public static short NetworkToHostOrder(short network) { return default(short); }
public static int NetworkToHostOrder(int network) { return default(int); }
public static long NetworkToHostOrder(long network) { return default(long); }
public static System.Net.IPAddress Parse(string ipString) { return default(System.Net.IPAddress); }
public override string ToString() { return default(string); }
public static bool TryParse(string ipString, out System.Net.IPAddress address) { address = default(System.Net.IPAddress); return default(bool); }
}
public partial class IPEndPoint : System.Net.EndPoint
{
public const int MaxPort = 65535;
public const int MinPort = 0;
public IPEndPoint(long address, int port) { }
public IPEndPoint(System.Net.IPAddress address, int port) { }
public System.Net.IPAddress Address { get { return default(System.Net.IPAddress); } set { } }
public override System.Net.Sockets.AddressFamily AddressFamily { get { return default(System.Net.Sockets.AddressFamily); } }
public int Port { get { return default(int); } set { } }
public override System.Net.EndPoint Create(System.Net.SocketAddress socketAddress) { return default(System.Net.EndPoint); }
public override bool Equals(object comparand) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override System.Net.SocketAddress Serialize() { return default(System.Net.SocketAddress); }
public override string ToString() { return default(string); }
}
public partial interface IWebProxy
{
System.Net.ICredentials Credentials { get; set; }
System.Uri GetProxy(System.Uri destination);
bool IsBypassed(System.Uri host);
}
public partial class NetworkCredential : System.Net.ICredentials, System.Net.ICredentialsByHost
{
public NetworkCredential() { }
public NetworkCredential(string userName, string password) { }
public NetworkCredential(string userName, string password, string domain) { }
public string Domain { get { return default(string); } set { } }
public string Password { get { return default(string); } set { } }
public string UserName { get { return default(string); } set { } }
public System.Net.NetworkCredential GetCredential(string host, int port, string authenticationType) { return default(System.Net.NetworkCredential); }
public System.Net.NetworkCredential GetCredential(System.Uri uri, string authType) { return default(System.Net.NetworkCredential); }
}
public partial class SocketAddress
{
public SocketAddress(System.Net.Sockets.AddressFamily family) { }
public SocketAddress(System.Net.Sockets.AddressFamily family, int size) { }
public System.Net.Sockets.AddressFamily Family { get { return default(System.Net.Sockets.AddressFamily); } }
public byte this[int offset] { get { return default(byte); } set { } }
public int Size { get { return default(int); } }
public override bool Equals(object comparand) { return default(bool); }
public override int GetHashCode() { return default(int); }
public override string ToString() { return default(string); }
}
public abstract partial class TransportContext
{
protected TransportContext() { }
public abstract System.Security.Authentication.ExtendedProtection.ChannelBinding GetChannelBinding(System.Security.Authentication.ExtendedProtection.ChannelBindingKind kind);
}
}
namespace System.Net.NetworkInformation
{
public partial class IPAddressCollection : System.Collections.Generic.ICollection<System.Net.IPAddress>, System.Collections.Generic.IEnumerable<System.Net.IPAddress>, System.Collections.IEnumerable
{
protected internal IPAddressCollection() { }
public virtual int Count { get { return default(int); } }
public virtual bool IsReadOnly { get { return default(bool); } }
public virtual System.Net.IPAddress this[int index] { get { return default(System.Net.IPAddress); } }
public virtual void Add(System.Net.IPAddress address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.IPAddress address) { return default(bool); }
public virtual void CopyTo(System.Net.IPAddress[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.IPAddress> GetEnumerator() { return default(System.Collections.Generic.IEnumerator<System.Net.IPAddress>); }
public virtual bool Remove(System.Net.IPAddress address) { return default(bool); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
}
}
namespace System.Net.Security
{
public enum AuthenticationLevel
{
MutualAuthRequested = 1,
MutualAuthRequired = 2,
None = 0,
}
[System.FlagsAttribute]
public enum SslPolicyErrors
{
None = 0,
RemoteCertificateChainErrors = 4,
RemoteCertificateNameMismatch = 2,
RemoteCertificateNotAvailable = 1,
}
}
namespace System.Net.Sockets
{
public enum AddressFamily
{
AppleTalk = 16,
Atm = 22,
Banyan = 21,
Ccitt = 10,
Chaos = 5,
Cluster = 24,
DataKit = 9,
DataLink = 13,
DecNet = 12,
Ecma = 8,
FireFox = 19,
HyperChannel = 15,
Ieee12844 = 25,
ImpLink = 3,
InterNetwork = 2,
InterNetworkV6 = 23,
Ipx = 6,
Irda = 26,
Iso = 7,
Lat = 14,
NetBios = 17,
NetworkDesigners = 28,
NS = 6,
Osi = 7,
Pup = 4,
Sna = 11,
Unix = 1,
Unknown = -1,
Unspecified = 0,
VoiceView = 18,
}
public enum SocketError
{
AccessDenied = 10013,
AddressAlreadyInUse = 10048,
AddressFamilyNotSupported = 10047,
AddressNotAvailable = 10049,
AlreadyInProgress = 10037,
ConnectionAborted = 10053,
ConnectionRefused = 10061,
ConnectionReset = 10054,
DestinationAddressRequired = 10039,
Disconnecting = 10101,
Fault = 10014,
HostDown = 10064,
HostNotFound = 11001,
HostUnreachable = 10065,
InProgress = 10036,
Interrupted = 10004,
InvalidArgument = 10022,
IOPending = 997,
IsConnected = 10056,
MessageSize = 10040,
NetworkDown = 10050,
NetworkReset = 10052,
NetworkUnreachable = 10051,
NoBufferSpaceAvailable = 10055,
NoData = 11004,
NoRecovery = 11003,
NotConnected = 10057,
NotInitialized = 10093,
NotSocket = 10038,
OperationAborted = 995,
OperationNotSupported = 10045,
ProcessLimit = 10067,
ProtocolFamilyNotSupported = 10046,
ProtocolNotSupported = 10043,
ProtocolOption = 10042,
ProtocolType = 10041,
Shutdown = 10058,
SocketError = -1,
SocketNotSupported = 10044,
Success = 0,
SystemNotReady = 10091,
TimedOut = 10060,
TooManyOpenSockets = 10024,
TryAgain = 11002,
TypeNotFound = 10109,
VersionNotSupported = 10092,
WouldBlock = 10035,
}
public partial class SocketException : System.Exception
{
public SocketException() { }
public SocketException(int errorCode) { }
public override string Message { get { return default(string); } }
public System.Net.Sockets.SocketError SocketErrorCode { get { return default(System.Net.Sockets.SocketError); } }
}
}
namespace System.Security.Authentication
{
public enum CipherAlgorithmType
{
Aes = 26129,
Aes128 = 26126,
Aes192 = 26127,
Aes256 = 26128,
Des = 26113,
None = 0,
Null = 24576,
Rc2 = 26114,
Rc4 = 26625,
TripleDes = 26115,
}
public enum ExchangeAlgorithmType
{
DiffieHellman = 43522,
None = 0,
RsaKeyX = 41984,
RsaSign = 9216,
}
public enum HashAlgorithmType
{
Md5 = 32771,
None = 0,
Sha1 = 32772,
}
[System.FlagsAttribute]
public enum SslProtocols
{
None = 0,
Ssl2 = 12,
Ssl3 = 48,
Tls = 192,
Tls11 = 768,
Tls12 = 3072,
}
}
namespace System.Security.Authentication.ExtendedProtection
{
public abstract partial class ChannelBinding : System.Runtime.InteropServices.SafeHandle
{
protected ChannelBinding() : base(default(System.IntPtr), default(bool)) { }
protected ChannelBinding(bool ownsHandle) : base(default(System.IntPtr), default(bool)) { }
public abstract int Size { get; }
}
public enum ChannelBindingKind
{
Endpoint = 26,
Unique = 25,
Unknown = 0,
}
}
| |
using System;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using static PasswordSafe.Helpers;
namespace Medo.Security.Cryptography.PasswordSafe {
/// <summary>
/// Abstract field.
/// </summary>
public abstract class Field {
/// <summary>
/// Create a new instance.
/// </summary>
protected Field() {
}
/// <summary>
/// Gets/sets version data.
/// -1 will be returned if conversion cannot be performed.
/// For unknown field types, conversion will always be attempted.
/// </summary>
public int Version {
get {
if ((DataType == PasswordSafeFieldDataType.Version) || (DataType == PasswordSafeFieldDataType.Unknown)) {
var data = RawData;
try {
if (data.Length == 2) {
return BitConverter.ToUInt16(data, 0);
}
} finally {
Array.Clear(data, 0, data.Length);
}
}
return -1; //unknown version
}
set {
if ((DataType != PasswordSafeFieldDataType.Version) && (DataType != PasswordSafeFieldDataType.Unknown)) { throw new FormatException("Field type mismatch."); }
if ((value < 0) || (value > ushort.MaxValue)) { throw new ArgumentOutOfRangeException(nameof(value), "Value outside of range."); }
RawData = BitConverter.GetBytes((ushort)value);
}
}
/// <summary>
/// Gets/sets UUID data.
/// Guid.Empty will be returned if conversion cannot be performed.
/// For unknown field types, conversion will always be attempted.
/// </summary>
public Guid Uuid {
get {
if ((DataType == PasswordSafeFieldDataType.Uuid) || (DataType == PasswordSafeFieldDataType.Unknown)) {
var data = RawData;
try {
if (data.Length == 16) {
return new Guid(data);
}
} finally {
Array.Clear(data, 0, data.Length);
}
}
return Guid.Empty; //unknown guid
}
set {
if ((DataType != PasswordSafeFieldDataType.Uuid) && (DataType != PasswordSafeFieldDataType.Unknown)) { throw new FormatException("Field type mismatch."); }
RawData = value.ToByteArray();
}
}
private static readonly Encoding Utf8Encoding = new UTF8Encoding(false);
/// <summary>
/// Gets/sets text data.
/// Null will be returned if conversion cannot be performed.
/// For unknown field types, conversion will always be attempted.
/// </summary>
public virtual string Text {
get {
if ((DataType == PasswordSafeFieldDataType.Text) || (DataType == PasswordSafeFieldDataType.Unknown)) {
var data = RawData;
try {
return Utf8Encoding.GetString(data);
} finally {
Array.Clear(data, 0, data.Length);
}
}
return null;
}
set {
if ((DataType != PasswordSafeFieldDataType.Text) && (DataType != PasswordSafeFieldDataType.Unknown)) { throw new FormatException("Field type mismatch."); }
if (value == null) { throw new ArgumentNullException(nameof(value), "Value cannot be null."); }
RawData = Utf8Encoding.GetBytes(value);
}
}
private static readonly DateTime TimeMin = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static readonly DateTime TimeMax = TimeMin.AddSeconds(uint.MaxValue);
/// <summary>
/// Gets/sets time data.
/// DateTime.MinValue will be returned if conversion cannot be performed.
/// For unknown field types, conversion will always be attempted.
/// </summary>
public DateTime Time {
get {
if ((DataType == PasswordSafeFieldDataType.Time) || (DataType == PasswordSafeFieldDataType.Unknown)) {
var data = RawData;
try {
if (data.Length == 4) {
var seconds = BitConverter.ToUInt32(RawData, 0);
return TimeMin.AddSeconds(seconds);
} else if (data.Length == 8) { //try hexadecimal
if (uint.TryParse(Utf8Encoding.GetString(data), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var seconds)) {
return TimeMin.AddSeconds(seconds);
} else {
return DateTime.MinValue;
}
}
} finally {
Array.Clear(data, 0, data.Length);
}
}
return DateTime.MinValue;
}
set {
if ((DataType != PasswordSafeFieldDataType.Time) && (DataType != PasswordSafeFieldDataType.Unknown)) { throw new FormatException("Field type mismatch."); }
if ((value < TimeMin) || (value > TimeMax)) { throw new ArgumentNullException(nameof(value), "Time outside of allowable range."); }
var seconds = (uint)((value.ToUniversalTime() - TimeMin).TotalSeconds);
RawData = BitConverter.GetBytes(seconds);
}
}
/// <summary>
/// Returns data as bytes.
/// </summary>
public byte[] GetBytes() {
var data = RawData;
try {
var dataCopy = new byte[data.Length];
Buffer.BlockCopy(data, 0, dataCopy, 0, dataCopy.Length);
return dataCopy;
} finally {
Array.Clear(data, 0, data.Length);
}
}
/// <summary>
/// Returns data as bytes without marking the field as accessed.
/// </summary>
internal byte[] GetBytesSilently() {
return RawDataDirect;
}
/// <summary>
/// Sets byte data.
/// </summary>
/// <param name="value">Bytes.</param>
/// <exception cref="ArgumentNullException">Value cannot be null.</exception>
public void SetBytes(byte[] value) {
if (value == null) { throw new ArgumentNullException(nameof(value), "Value cannot be null."); }
var valueCopy = new byte[value.Length];
try {
Buffer.BlockCopy(value, 0, valueCopy, 0, valueCopy.Length);
RawData = valueCopy;
} finally {
Array.Clear(valueCopy, 0, valueCopy.Length);
}
}
private static readonly RandomNumberGenerator Rnd = RandomNumberGenerator.Create();
private readonly byte[] RawDataEntropy = new byte[16];
private byte[] _rawData = null;
/// <summary>
/// Gets/sets raw data.
/// Bytes are kept encrypted in memory until accessed.
/// </summary>
internal byte[] RawData {
get {
MarkAsAccessed();
return RawDataDirect;
}
set {
if (IsReadOnly) { throw new NotSupportedException("Object is read-only."); }
var oldValue = RawDataDirect;
try {
if (oldValue.Length == value.Length) { //skip writing the same value (to avoid marking document changed without reason)
var areSame = true;
for (var i = 0; i < value.Length; i++) {
if (oldValue[i] != value[i]) {
areSame = false;
break;
}
}
if (areSame) { return; }
}
} finally {
Array.Clear(oldValue, 0, oldValue.Length);
}
Rnd.GetBytes(RawDataEntropy); //new entropy every save
_rawData = ProtectData(value, RawDataEntropy);
Array.Clear(value, 0, value.Length);
MarkAsChanged();
}
}
/// <summary>
/// Gets raw data without marking the field as accessed.
/// Bytes are kept encrypted in memory until accessed.
/// </summary>
protected byte[] RawDataDirect {
get {
if (_rawData == null) { return new byte[0]; } //return empty array if no value has been set so far
return UnprotectData(_rawData, RawDataEntropy);
}
}
/// <summary>
/// Used to mark document as changed.
/// </summary>
protected abstract void MarkAsChanged();
/// <summary>
/// Used to mark document as accessed.
/// </summary>
protected abstract void MarkAsAccessed();
/// <summary>
/// Gets if object is read-only.
/// </summary>
protected abstract bool IsReadOnly { get; }
/// <summary>
/// Gets underlying data type for field.
/// </summary>
protected abstract PasswordSafeFieldDataType DataType { get; }
/// <summary>
/// Underlying data type enumeration used for data parsing.
/// </summary>
protected enum PasswordSafeFieldDataType {
/// <summary>
/// Unknown data type.
/// </summary>
Unknown,
/// <summary>
/// Version.
/// </summary>
Version,
/// <summary>
/// UUID.
/// </summary>
Uuid,
/// <summary>
/// Text.
/// </summary>
Text,
/// <summary>
/// Time.
/// </summary>
Time,
/// <summary>
/// Bytes.
/// </summary>
Binary,
}
/// <summary>
/// Returns a string representation of an object.
/// </summary>
public override string ToString() {
switch (DataType) {
case PasswordSafeFieldDataType.Version: return Version.ToString("X4", CultureInfo.InvariantCulture);
case PasswordSafeFieldDataType.Uuid: return Uuid.ToString();
case PasswordSafeFieldDataType.Text: return Text;
case PasswordSafeFieldDataType.Time: return Time.ToLocalTime().ToString("yyyy'-'MM'-'dd HH':'mm':'ss K", CultureInfo.InvariantCulture);
default: return "0x" + BitConverter.ToString(RawData).Replace("-", "");
}
}
}
}
| |
/*
* CKFinder
* ========
* http://cksource.com/ckfinder
* Copyright (C) 2007-2013, CKSource - Frederico Knabben. All rights reserved.
*
* The software, this file and its contents are subject to the CKFinder
* License. Please read the license.txt file before using, installing, copying,
* modifying or distribute this file or part of its contents. The contents of
* this file is part of the Source Code of CKFinder.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Xml;
using System.Web;
using System.Web.UI;
using ImageManipulation;
using CKFinder;
namespace CKFinder.Connector.CommandHandlers
{
public class ImageResizeCommandHandler : XmlCommandHandlerBase
{
public ImageResizeCommandHandler()
: base()
{
}
protected override void BuildXml()
{
Config _Config = Config.Current;
if ( !this.CurrentFolder.CheckAcl( AccessControlRules.FileDelete | AccessControlRules.FileUpload ) )
{
ConnectorException.Throw( Errors.Unauthorized );
}
string fileName = Request.Form["FileName"];
if ( !Connector.CheckFileName( fileName ) || Config.Current.CheckIsHiddenFile( fileName ) )
{
ConnectorException.Throw( Errors.InvalidRequest );
return;
}
if ( !this.CurrentFolder.ResourceTypeInfo.CheckExtension( System.IO.Path.GetExtension( fileName ) ) )
{
ConnectorException.Throw( Errors.InvalidRequest );
return;
}
string filePath = System.IO.Path.Combine( this.CurrentFolder.ServerPath, fileName );
if ( !System.IO.File.Exists( filePath ) )
ConnectorException.Throw( Errors.FileNotFound );
int newWidth = 0;
int newHeight = 0;
if ( Request.Form["width"] != null && Request.Form["width"].Length > 0
&& Request.Form["height"] != null && Request.Form["height"].Length > 0 )
{
newWidth = System.Int32.Parse( Request.Form["width"].Trim() );
newHeight = System.Int32.Parse( Request.Form["height"].Trim() );
}
bool resizeOriginal = newWidth > 0 && newHeight > 0;
if ( resizeOriginal )
{
if ( Request.Form["newFileName"] == null || Request.Form["newFileName"].Length == 0 )
{
ConnectorException.Throw( Errors.InvalidName );
}
string newFileName = Request.Form["newFileName"];
// Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.Current.ForceSingleExtension )
newFileName = Regex.Replace( newFileName, @"\.(?![^.]*$)", "_", RegexOptions.None );
if ( !this.CurrentFolder.ResourceTypeInfo.CheckExtension( System.IO.Path.GetExtension( newFileName ) ) )
{
ConnectorException.Throw( Errors.InvalidExtension );
return;
}
if ( !Connector.CheckFileName( newFileName ) || Config.Current.CheckIsHiddenFile( newFileName ) )
{
ConnectorException.Throw( Errors.InvalidName );
return;
}
if ( _Config.Images.MaxHeight > 0 && newHeight > _Config.Images.MaxHeight )
{
ConnectorException.Throw( Errors.InvalidRequest );
}
if ( _Config.Images.MaxWidth > 0 && newWidth > _Config.Images.MaxWidth )
{
ConnectorException.Throw( Errors.InvalidRequest );
}
string newFilePath = System.IO.Path.Combine( this.CurrentFolder.ServerPath, newFileName );
if ( Request.Form["overwrite"] != "1" && System.IO.File.Exists( newFilePath ) )
ConnectorException.Throw( Errors.AlreadyExist );
CKFinder.Connector.ImageTools.ResizeImage( filePath, newFilePath, newWidth, newHeight, true, Config.Current.Images.Quality );
}
string sExtension = System.IO.Path.GetExtension( fileName );
sExtension = sExtension.TrimStart( '.' );
// Map the virtual path to the local server path.
string sServerDir = this.CurrentFolder.ServerPath;
string sFileNameNoExt = System.IO.Path.GetFileNameWithoutExtension( fileName );
sFileNameNoExt = Regex.Replace( sFileNameNoExt, @"^(.+)_\d+x\d+$", "$1" );
List<string> sizes = new List<string>( new string[] { "small", "medium", "large" } );
Regex sizeRegex = new Regex( @"^(\d+)x(\d+)$" );
foreach ( string size in sizes )
{
if ( Request.Form[size] != null && Request.Form[size] == "1" )
{
string thumbName = sFileNameNoExt + "_" + size + "." + sExtension;
string newFilePath = System.IO.Path.Combine( this.CurrentFolder.ServerPath, thumbName );
if ( CKFinder.Connector.Config.Current.PluginSettings.ContainsKey( "ImageResize_" + size + "Thumb" ) )
{
string thumbSize = CKFinder.Connector.Config.Current.PluginSettings["ImageResize_" + size + "Thumb"].ToString().Trim();
if ( sizeRegex.IsMatch( thumbSize ) )
{
Match m = sizeRegex.Match( thumbSize );
GroupCollection gc = m.Groups;
newWidth = Int32.Parse( gc[1].Value );
newHeight = Int32.Parse( gc[2].Value );
CKFinder.Connector.ImageTools.ResizeImage( filePath, newFilePath, newWidth, newHeight, true, Config.Current.Images.Quality );
}
}
}
}
}
}
public class ImageResizeInfoCommandHandler : XmlCommandHandlerBase
{
public ImageResizeInfoCommandHandler()
: base()
{
}
protected override void BuildXml()
{
if ( !this.CurrentFolder.CheckAcl( AccessControlRules.FileView ) )
{
ConnectorException.Throw( Errors.Unauthorized );
}
string fileName = Request["FileName"];
System.Drawing.Image sourceImage;
if ( !Connector.CheckFileName( fileName ) || Config.Current.CheckIsHiddenFile( fileName ) )
{
ConnectorException.Throw( Errors.InvalidRequest );
return;
}
if ( !this.CurrentFolder.ResourceTypeInfo.CheckExtension( System.IO.Path.GetExtension( fileName ) ) )
{
ConnectorException.Throw( Errors.InvalidRequest );
return;
}
string filePath = System.IO.Path.Combine( this.CurrentFolder.ServerPath, fileName );
if ( !System.IO.File.Exists( filePath ) )
ConnectorException.Throw( Errors.FileNotFound );
try
{
sourceImage = System.Drawing.Image.FromFile( filePath );
XmlNode oImageInfo = XmlUtil.AppendElement( this.ConnectorNode, "ImageInfo" );
XmlUtil.SetAttribute( oImageInfo, "width", sourceImage.Width.ToString() );
XmlUtil.SetAttribute( oImageInfo, "height", sourceImage.Height.ToString() );
sourceImage.Dispose();
}
catch ( OutOfMemoryException )
{
ConnectorException.Throw( Errors.InvalidName );
}
catch ( System.UnauthorizedAccessException )
{
ConnectorException.Throw( Errors.AccessDenied );
}
catch ( System.Security.SecurityException )
{
ConnectorException.Throw( Errors.AccessDenied );
}
catch ( System.ArgumentException )
{
ConnectorException.Throw( Errors.FileNotFound );
}
catch ( System.IO.PathTooLongException )
{
ConnectorException.Throw( Errors.FileNotFound );
}
catch
{
#if DEBUG
throw;
#else
ConnectorException.Throw( Errors.Unknown );
#endif
}
}
}
}
namespace CKFinder.Plugins
{
public class ImageResize : CKFinder.CKFinderPlugin
{
public string JavascriptPlugins
{
get { return "imageresize"; }
}
public void Init( CKFinder.Connector.CKFinderEvent CKFinderEvent )
{
CKFinderEvent.BeforeExecuteCommand += new CKFinder.Connector.CKFinderEvent.Hook( this.BeforeExecuteCommand );
CKFinderEvent.InitCommand += new CKFinder.Connector.CKFinderEvent.Hook( this.InitCommand );
}
protected void InitCommand( object sender, CKFinder.Connector.CKFinderEventArgs args )
{
XmlNode ConnectorNode = (XmlNode)args.data[0];
XmlNode oimageresize = CKFinder.Connector.XmlUtil.AppendElement( ConnectorNode.SelectSingleNode("PluginsInfo"), "imageresize" );
if ( CKFinder.Connector.Config.Current.PluginSettings.ContainsKey( "ImageResize_smallThumb" ) )
{
CKFinder.Connector.XmlUtil.SetAttribute( oimageresize, "smallThumb", CKFinder.Connector.Config.Current.PluginSettings["ImageResize_smallThumb"].ToString() );
}
if ( CKFinder.Connector.Config.Current.PluginSettings.ContainsKey( "ImageResize_mediumThumb" ) )
{
CKFinder.Connector.XmlUtil.SetAttribute( oimageresize, "mediumThumb", CKFinder.Connector.Config.Current.PluginSettings["ImageResize_mediumThumb"].ToString() );
}
if ( CKFinder.Connector.Config.Current.PluginSettings.ContainsKey( "ImageResize_largeThumb" ) )
{
CKFinder.Connector.XmlUtil.SetAttribute( oimageresize, "largeThumb", CKFinder.Connector.Config.Current.PluginSettings["ImageResize_largeThumb"].ToString() );
}
}
protected void BeforeExecuteCommand( object sender, CKFinder.Connector.CKFinderEventArgs args )
{
String command = (String)args.data[0];
if ( command == "ImageResizeInfo" )
{
HttpResponse Response = (HttpResponse)args.data[1];
CKFinder.Connector.CommandHandlers.CommandHandlerBase commandHandler =
new CKFinder.Connector.CommandHandlers.ImageResizeInfoCommandHandler();
commandHandler.SendResponse( Response );
}
else if ( command == "ImageResize" )
{
HttpResponse Response = (HttpResponse)args.data[1];
CKFinder.Connector.CommandHandlers.CommandHandlerBase commandHandler =
new CKFinder.Connector.CommandHandlers.ImageResizeCommandHandler();
commandHandler.SendResponse( Response );
}
}
}
}
| |
using NSubstitute;
using NVika.BuildServers;
using NVika.Parsers;
using Serilog;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Abstractions.TestingHelpers;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Xunit;
namespace NVika.Tests
{
public class ParseReportCommandTest
{
private StringBuilder _loggerOutput;
private bool _mockBuildServer_IncludeSource;
private bool _mockParser_Alternate;
[Fact]
public void Execute_NoArguments_ShouldLogError_NoReportSpecified()
{
// arrange
var logger = GetLogger();
var buildServerCommand = new ParseReportCommand(logger, new MockFileSystem(), Enumerable.Empty<IBuildServer>(), new LocalBuildServer(logger), Enumerable.Empty<IReportParser>());
buildServerCommand.GetActualOptions().Parse(new string[] { });
// act
var exitCode = buildServerCommand.Run(new string[] { });
// assert
Assert.Equal(1, exitCode);
Assert.Contains("No report was specified. You must indicate at least one report file.", _loggerOutput.ToString().Trim());
}
[Fact]
public void Execute_OnlyDebug_ShouldLogError_NoResportSpecified()
{
// arrange
var logger = GetLogger();
var buildServerCommand = new ParseReportCommand(logger, new MockFileSystem(), Enumerable.Empty<IBuildServer>(), new LocalBuildServer(logger), Enumerable.Empty<IReportParser>());
buildServerCommand.GetActualOptions().Parse(new[] { "--debug" });
// act
var exitCode = buildServerCommand.Run(new string[] { });
// assert
Assert.Equal(1, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("No report was specified. You must indicate at least one report file.", logs);
}
[Fact]
public void Execute_NonExistingReport_ShouldLogError_ReportNotFound()
{
// arrange
var logger = GetLogger();
var fileSystem = new MockFileSystem();
var buildServerCommand = new ParseReportCommand(logger, fileSystem, Enumerable.Empty<IBuildServer>(), new LocalBuildServer(logger), Enumerable.Empty<IReportParser>());
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(2, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("The report \"report.xml\" was not found.", logs);
}
[Fact]
public void Execute_ExistingButEmptyReport_ShouldLogErrorOnLoad_DefaultBuildServerIsLocal()
{
// arrange
var logger = GetLogger();
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { "report.xml", MockFileData.NullObject } });
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer();
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, Enumerable.Empty<IReportParser>());
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(4, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("\t- \"Local console\"", logs);
Assert.Contains("The adequate parser for this report was not found. You are welcome to address us an issue.", logs);
}
[Fact]
public void Execute_ExistingBuEmptyReport_ShouldLogErrorOnLoad_MockBuildServerIsSelected()
{
// arrange
var logger = GetLogger();
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { "report.xml", MockFileData.NullObject } });
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer(true);
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, Enumerable.Empty<IReportParser>());
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(4, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("\t- \"MockBuildServer\"", logs);
Assert.Contains("The adequate parser for this report was not found. You are welcome to address us an issue.", logs);
}
[Fact]
public void Execute_NoParser_ShouldLogError()
{
// arrange
var logger = GetLogger();
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { "report.xml", new MockFileData("<root></root>") } });
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer(true);
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, Enumerable.Empty<IReportParser>());
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(4, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("The adequate parser for this report was not found. You are welcome to address us an issue.", logs);
}
[Fact]
public void Execute_ParserCantParse_ShouldLogError()
{
// arrange
var logger = GetLogger();
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { "report.xml", new MockFileData("<root></root>") } });
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer(true);
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var parsers = new List<IReportParser> { GetMockReportParser() };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, parsers);
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(4, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("The adequate parser for this report was not found. You are welcome to address us an issue.", logs);
}
[Fact]
public void Execute_ParserCanParse_ShouldWriteMessageFromIssues()
{
// arrange
var logger = GetLogger();
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { "report.xml", new MockFileData("<root></root>") } });
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer(true);
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var parsers = new List<IReportParser> { GetMockReportParser(true) };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, parsers);
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(5, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("Message1", logs);
Assert.Contains("Message2", logs);
Assert.Contains("Message3", logs);
}
[Fact]
public void Execute_ParserCanParse_WithDebug_ShouldWriteMessageFromIssuesAndWriteIssuesCount()
{
// arrange
var logger = GetLogger(Serilog.Events.LogEventLevel.Debug);
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { "report.xml", new MockFileData("<root></root>") } });
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer(true);
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var parsers = new List<IReportParser> { GetMockReportParser(true) };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, parsers);
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(5, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("Report path is \"report.xml\"", logs);
Assert.Contains("3 issues was found", logs);
Assert.Contains("Message1", logs);
Assert.Contains("Message2", logs);
Assert.Contains("Message3", logs);
}
[Fact]
public void Execute_NoErrorInIssues_ShouldReturnZero()
{
// arrange
var logger = GetLogger();
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { "report.xml", new MockFileData("<root></root>") } });
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer(true);
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var parsers = new List<IReportParser> { GetMockReportParser(true, false) };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, parsers);
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(0, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("Message1", logs);
Assert.Contains("Message2", logs);
Assert.Contains("Message3", logs);
}
[Fact]
public void Execute_IncludeSource_BuildServerShouldIncludeSource()
{
// arrange
var logger = GetLogger();
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { "report.xml", new MockFileData("<root></root>") } });
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer(true);
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var parsers = new List<IReportParser> { GetMockReportParser(true, false) };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, parsers);
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml", "--includesource" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(0, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("Message1 - Source1", logs);
Assert.Contains("Message2 - Source2", logs);
Assert.Contains("Message3 - Source3", logs);
}
[Fact]
public void Execute_MultipleReports_ShouldWriteMessageFromIssues()
{
// arrange
var logger = GetLogger(Serilog.Events.LogEventLevel.Debug);
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData>
{
{ "report.xml", new MockFileData("<root></root>") },
{ "report2.xml", new MockFileData("<root></root>") }
});
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer(true);
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var parsers = new List<IReportParser> { GetMockReportParser(true, true, true) };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, parsers);
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml", "report2.xml" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(5, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("3 issues was found", logs);
Assert.Contains("Message1", logs);
Assert.Contains("Message2", logs);
Assert.Contains("Message3", logs);
Assert.Contains("Message4", logs);
Assert.Contains("Message5", logs);
Assert.Contains("Message6", logs);
}
[Fact]
public void Execute_TreatWarningsAsErrors_ShouldExitWithCode5()
{
// arrange
var logger = GetLogger();
var fileSystem = new MockFileSystem(new Dictionary<string, MockFileData> { { "report.xml", new MockFileData("<root></root>") } });
var localBuildServer = new LocalBuildServer(logger);
var mockBuildServer = GetMockBuildServer(true);
var buildServers = new List<IBuildServer> { localBuildServer, mockBuildServer };
var parsers = new List<IReportParser> { GetMockReportParser(true, false) };
var buildServerCommand = new ParseReportCommand(logger, fileSystem, buildServers, localBuildServer, parsers);
var remainingArgs = buildServerCommand.GetActualOptions().Parse(new[] { "report.xml", "--treatwarningsaserrors" });
// act
var exitCode = buildServerCommand.Run(remainingArgs.ToArray());
// assert
Assert.Equal(5, exitCode);
var logs = _loggerOutput.ToString();
Assert.Contains("[Suggestion] Message1", logs);
Assert.Contains("[Error] Message2", logs);
Assert.Contains("[Error] Message3", logs);
Assert.Contains("[Fatal] Issues with severity error was found: the build will fail", logs);
}
private IReportParser GetMockReportParser(bool canParse = false, bool issuesContainError = true, bool alternate = false)
{
var mockReportParser = Substitute.For<IReportParser>();
mockReportParser.Name.Returns("MockReportParser");
mockReportParser.CanParse(Arg.Any<string>()).Returns(canParse);
mockReportParser.Parse(Arg.Any<string>()).Returns((ci) =>
{
if (alternate)
{
if (issuesContainError && _mockParser_Alternate)
{
issuesContainError = false;
}
_mockParser_Alternate = !_mockParser_Alternate;
if (_mockParser_Alternate)
{
return GetIssues(issuesContainError);
}
else
{
return GetIssues2(issuesContainError);
}
}
else
{
return GetIssues(issuesContainError);
}
});
return mockReportParser;
}
private IBuildServer GetMockBuildServer(bool canApplyToCurrentContext = false)
{
var mockBuildServer = Substitute.For<IBuildServer>();
mockBuildServer.Name.Returns("MockBuildServer");
mockBuildServer.CanApplyToCurrentContext().Returns(canApplyToCurrentContext);
mockBuildServer.When(bs => bs.ApplyParameters(Arg.Any<bool>())).Do(ci => _mockBuildServer_IncludeSource = ci.Arg<bool>());
mockBuildServer.When(bs => bs.WriteMessage(Arg.Any<Issue>())).Do(ci => _loggerOutput.AppendLine("[" + ci.Arg<Issue>().Severity + "] " + ci.Arg<Issue>().Message + (_mockBuildServer_IncludeSource ? " - " + ci.Arg<Issue>().Source : string.Empty)));
return mockBuildServer;
}
private ILogger GetLogger(Serilog.Events.LogEventLevel logEventLevel = Serilog.Events.LogEventLevel.Information)
{
_loggerOutput = new StringBuilder();
var writer = new StringWriter(_loggerOutput);
var loggerConfiguration = new LoggerConfiguration()
.WriteTo.TextWriter(writer);
loggerConfiguration.MinimumLevel.Is(logEventLevel);
var logger = loggerConfiguration.CreateLogger();
return logger;
}
private List<Issue> GetIssues(bool containError = true)
{
return new List<Issue>
{
new Issue{ Category="Category1", Description = "Description1", FilePath = "FilePath1", HelpUri = null, Line = 42u, Message = "Message1", Name = "Name1", Offset = new Offset{ Start = 2u, End = 5u}, Project = "Project1", Severity = IssueSeverity.Suggestion, Source = "Source1" },
new Issue{ Category="Category2", Description = "Description2", FilePath = "FilePath2", HelpUri = new Uri("https://www.wikipedia.com"), Line = 465u, Message = "Message2", Name = "Name2", Offset = new Offset{ Start = 36u, End = 546u}, Project = "Project1", Severity = IssueSeverity.Warning, Source = "Source2" },
new Issue{ Category="Category1", Description = "Description3", FilePath = "FilePath3", HelpUri = new Uri("http://helperror.com"), Line = 82u, Message = "Message3", Name = "Name3", Project = "Project2", Severity = containError ? IssueSeverity.Error : IssueSeverity.Warning, Source = "Source3" },
};
}
private List<Issue> GetIssues2(bool containError = true)
{
return new List<Issue>
{
new Issue{ Category="Category1", Description = "Description4", FilePath = "FilePath4", HelpUri = null, Line = 42u, Message = "Message4", Name = "Name4", Offset = new Offset{ Start = 2u, End = 5u}, Project = "Project1", Severity = IssueSeverity.Suggestion, Source = "Source1" },
new Issue{ Category="Category2", Description = "Description5", FilePath = "FilePath5", HelpUri = new Uri("https://www.wikipedia.com"), Line = 465u, Message = "Message5", Name = "Name5", Offset = new Offset{ Start = 36u, End = 546u}, Project = "Project1", Severity = IssueSeverity.Warning, Source = "Source2" },
new Issue{ Category="Category1", Description = "Description6", FilePath = "FilePath6", HelpUri = new Uri("http://helperror.com"), Line = 82u, Message = "Message6", Name = "Name6", Project = "Project2", Severity = containError ? IssueSeverity.Error : IssueSeverity.Warning, Source = "Source3" },
};
}
}
}
| |
using System;
using System.Globalization;
using System.Text;
using Microsoft.Build.Framework;
namespace GitVersion.MsBuild.Tests.Helpers
{
/// <summary>
/// Offers a default string format for Error and Warning events
/// </summary>
internal static class EventArgsFormatting
{
/// <summary>
/// Format the error event message and all the other event data into
/// a single string.
/// </summary>
/// <param name="e">Error to format</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildErrorEventArgs e)
{
// "error" should not be localized
return FormatEventMessage("error", e.Subcategory, e.Message,
e.Code, e.File, null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the error event message and all the other event data into
/// a single string.
/// </summary>
/// <param name="e">Error to format</param>
/// <param name="showProjectFile"><code>true</code> to show the project file which issued the event, otherwise <code>false</code>.</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildErrorEventArgs e, bool showProjectFile)
{
// "error" should not be localized
return FormatEventMessage("error", e.Subcategory, e.Message,
e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the warning message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Warning to format</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildWarningEventArgs e)
{
// "warning" should not be localized
return FormatEventMessage("warning", e.Subcategory, e.Message,
e.Code, e.File, null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the warning message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Warning to format</param>
/// <param name="showProjectFile"><code>true</code> to show the project file which issued the event, otherwise <code>false</code>.</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildWarningEventArgs e, bool showProjectFile)
{
// "warning" should not be localized
return FormatEventMessage("warning", e.Subcategory, e.Message,
e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Message to format</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildMessageEventArgs e)
{
return FormatEventMessage(e, false);
}
/// <summary>
/// Format the message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Message to format</param>
/// <param name="showProjectFile">Show project file or not</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildMessageEventArgs e, bool showProjectFile)
{
// "message" should not be localized
return FormatEventMessage("message", e.Subcategory, e.Message,
e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
}
/// <summary>
/// Format the event message and all the other event data into a
/// single string.
/// </summary>
/// <param name="category">category ("error" or "warning")</param>
/// <param name="subcategory">subcategory</param>
/// <param name="message">event message</param>
/// <param name="code">error or warning code number</param>
/// <param name="file">file name</param>
/// <param name="lineNumber">line number (0 if n/a)</param>
/// <param name="endLineNumber">end line number (0 if n/a)</param>
/// <param name="columnNumber">column number (0 if n/a)</param>
/// <param name="endColumnNumber">end column number (0 if n/a)</param>
/// <param name="threadId">thread id</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage
(
string category,
string subcategory,
string message,
string code,
string file,
int lineNumber,
int endLineNumber,
int columnNumber,
int endColumnNumber,
int threadId
)
{
return FormatEventMessage(category, subcategory, message, code, file, null, lineNumber, endLineNumber, columnNumber, endColumnNumber, threadId);
}
/// <summary>
/// Format the event message and all the other event data into a
/// single string.
/// </summary>
/// <param name="category">category ("error" or "warning")</param>
/// <param name="subcategory">subcategory</param>
/// <param name="message">event message</param>
/// <param name="code">error or warning code number</param>
/// <param name="file">file name</param>
/// <param name="projectFile">the project file name</param>
/// <param name="lineNumber">line number (0 if n/a)</param>
/// <param name="endLineNumber">end line number (0 if n/a)</param>
/// <param name="columnNumber">column number (0 if n/a)</param>
/// <param name="endColumnNumber">end column number (0 if n/a)</param>
/// <param name="threadId">thread id</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage
(
string category,
string subcategory,
string message,
string code,
string file,
string projectFile,
int lineNumber,
int endLineNumber,
int columnNumber,
int endColumnNumber,
int threadId
)
{
var format = new StringBuilder();
// Uncomment these lines to show show the processor, if present.
/*
if (threadId != 0)
{
format.Append("{0}>");
}
*/
if ((file == null) || (file.Length == 0))
{
format.Append("MSBUILD : "); // Should not be localized.
}
else
{
format.Append("{1}");
if (lineNumber == 0)
{
format.Append(" : ");
}
else
{
if (columnNumber == 0)
{
if (endLineNumber == 0)
{
format.Append("({2}): ");
}
else
{
format.Append("({2}-{7}): ");
}
}
else
{
if (endLineNumber == 0)
{
if (endColumnNumber == 0)
{
format.Append("({2},{3}): ");
}
else
{
format.Append("({2},{3}-{8}): ");
}
}
else
{
if (endColumnNumber == 0)
{
format.Append("({2}-{7},{3}): ");
}
else
{
format.Append("({2},{3},{7},{8}): ");
}
}
}
}
}
if ((subcategory != null) && (subcategory.Length != 0))
{
format.Append("{9} ");
}
// The category as a string (should not be localized)
format.Append("{4} ");
// Put a code in, if available and necessary.
if (code == null)
{
format.Append(": ");
}
else
{
format.Append("{5}: ");
}
// Put the message in, if available.
if (message != null)
{
format.Append("{6}");
}
// If the project file was specified, tack that onto the very end.
if (projectFile != null && !string.Equals(projectFile, file))
{
format.Append(" [{10}]");
}
// A null message is allowed and is to be treated as a blank line.
if (null == message)
{
message = string.Empty;
}
var finalFormat = format.ToString();
// If there are multiple lines, show each line as a separate message.
var lines = SplitStringOnNewLines(message);
var formattedMessage = new StringBuilder();
for (var i = 0; i < lines.Length; i++)
{
formattedMessage.Append(string.Format(
CultureInfo.CurrentCulture, finalFormat,
threadId, file,
lineNumber, columnNumber, category, code,
lines[i], endLineNumber, endColumnNumber,
subcategory, projectFile));
if (i < (lines.Length - 1))
{
formattedMessage.AppendLine();
}
}
return formattedMessage.ToString();
}
/// <summary>
/// Splits strings on 'newLines' with tolerance for Everett and Dogfood builds.
/// </summary>
/// <param name="s">String to split.</param>
private static string[] SplitStringOnNewLines(string s)
{
var subStrings = s.Split(s_newLines, StringSplitOptions.None);
return subStrings;
}
/// <summary>
/// The kinds of newline breaks we expect.
/// </summary>
/// <remarks>Currently we're not supporting "\r".</remarks>
private static readonly string[] s_newLines = { "\r\n", "\n" };
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.